@agent-custody/receipts 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -13
- package/dist/approval.d.ts +74 -0
- package/dist/approval.js +196 -0
- package/dist/capture.js +49 -1
- package/dist/check.d.ts +19 -0
- package/dist/check.js +288 -0
- package/dist/cli.js +238 -11
- package/dist/config.d.ts +85 -0
- package/dist/config.js +72 -2
- package/dist/console-page.d.ts +4 -0
- package/dist/console-page.js +342 -0
- package/dist/console.d.ts +20 -0
- package/dist/console.js +521 -0
- package/dist/gateway.d.ts +9 -0
- package/dist/gateway.js +335 -45
- package/dist/index.d.ts +9 -2
- package/dist/index.js +7 -1
- package/dist/issue.d.ts +8 -3
- package/dist/issue.js +13 -4
- package/dist/log-store.d.ts +3 -2
- package/dist/log-store.js +2 -0
- package/dist/operations.d.ts +101 -0
- package/dist/operations.js +239 -0
- package/dist/otel.js +12 -5
- package/dist/policy.d.ts +2 -0
- package/dist/policy.js +10 -0
- package/dist/portal.d.ts +78 -4
- package/dist/portal.js +516 -26
- package/dist/receipt.d.ts +36 -1
- package/dist/rest.js +14 -1
- package/dist/simulate.d.ts +58 -0
- package/dist/simulate.js +204 -0
- package/dist/splunk.js +11 -4
- package/dist/sso.d.ts +47 -0
- package/dist/sso.js +161 -0
- package/dist/verify.d.ts +2 -0
- package/dist/verify.js +241 -7
- package/docs/approvals.md +107 -0
- package/docs/codex-recovery.md +132 -0
- package/docs/configuration.md +224 -0
- package/docs/console.md +79 -0
- package/docs/financial-operations.md +99 -0
- package/docs/policies.md +23 -0
- package/docs/threat-model.md +13 -0
- package/docs/tutorials.md +9 -0
- package/docs/usage.md +49 -4
- package/docs/verification.md +26 -8
- package/package.json +8 -2
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +2866 -464
package/dist/verify.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Independent verification of a receipt bundle. Needs only public keys, and optionally a copy of the log.
|
|
2
2
|
import { canonicalize, digestOf, dsseVerifiers, dsseVerify } from "./crypto.js";
|
|
3
|
+
import { isApprovalTime, verifyApproval, verifyApprovalStatement } from "./approval.js";
|
|
3
4
|
import { digestSaltFor, getAt, isCommitment, pathKey, pathText, restorePaths, under } from "./capture.js";
|
|
4
5
|
import { delegationHasParent, delegationValidAt, describeChain, verifyDelegation } from "./delegation.js";
|
|
5
6
|
import { leafHash, MerkleLog, verifyConsistency, verifyInclusion } from "./log.js";
|
|
@@ -7,9 +8,88 @@ import { checkProvider, checkUpstream, contentDigest, isProviderAttestation } fr
|
|
|
7
8
|
import { AUTHORIZATION_PREDICATE_TYPE, RECEIPT_PREDICATE_TYPE, RECEIPT_TYPE, TREEHEAD_TYPE } from "./receipt.js";
|
|
8
9
|
const short = (s) => s.slice(0, 12);
|
|
9
10
|
const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
11
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
12
|
+
const hex64 = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
|
|
13
|
+
function operationProblem(o) {
|
|
14
|
+
if (!isObject(o) || (o.id !== undefined && (typeof o.id !== "string" || !UUID.test(o.id))) || typeof o.originalReceiptId !== "string" || !UUID.test(o.originalReceiptId))
|
|
15
|
+
return "operation ids are not UUIDs";
|
|
16
|
+
if (!hex64(o.idempotencyKey) || !hex64(o.lookupDigest))
|
|
17
|
+
return "operation idempotencyKey or lookupDigest is not a sha256";
|
|
18
|
+
if (!["submitted", "pending", "confirmed", "failed", "unknown"].includes(String(o.status)) || o.provenance !== "observed")
|
|
19
|
+
return "operation status or provenance is invalid";
|
|
20
|
+
if (!isObject(o.budget) || typeof o.budget.id !== "string" || !o.budget.id.length || o.budget.id.length > 128 || typeof o.budget.currency !== "string" || !/^[A-Z]{3}$/.test(o.budget.currency) || typeof o.budget.period !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(o.budget.period))
|
|
21
|
+
return "operation budget is invalid";
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
/** Provider records are JSON in the first text result, just as the gateway's ordinary fact extraction reads them. */
|
|
25
|
+
function providerValue(result, path) {
|
|
26
|
+
let record;
|
|
27
|
+
if (isObject(result) && Array.isArray(result.content)) {
|
|
28
|
+
const text = result.content.find((c) => isObject(c) && c.type === "text");
|
|
29
|
+
if (isObject(text) && typeof text.text === "string") {
|
|
30
|
+
try {
|
|
31
|
+
record = JSON.parse(text.text);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return path.split(".").reduce((v, k) => isObject(v) && Object.hasOwn(v, k) ? v[k] : undefined, record);
|
|
39
|
+
}
|
|
40
|
+
/** Verify a pre-forward authorization on its own when a crash prevented an outcome receipt being written. */
|
|
41
|
+
function verifyOriginalAuthorization(bundle, opts) {
|
|
42
|
+
const checks = [];
|
|
43
|
+
const add = (name, ok, detail) => checks.push({ name, ok, ...(detail === undefined ? {} : { detail }) });
|
|
44
|
+
const sig = dsseVerify(bundle.envelope, opts.issuerKeys);
|
|
45
|
+
const st = sig.ok ? sig.payload : null;
|
|
46
|
+
const typed = !!st && bundle.envelope.payloadType === RECEIPT_TYPE && st.predicateType === AUTHORIZATION_PREDICATE_TYPE;
|
|
47
|
+
add("authorization signature (issuer key)", sig.ok && typed);
|
|
48
|
+
if (!sig.ok || !st || !typed)
|
|
49
|
+
return { ok: false, predicate: null, checks };
|
|
50
|
+
const p = st.predicate;
|
|
51
|
+
// Authorizations have no session, model, or execution; validate the parts they share with ordinary receipts.
|
|
52
|
+
const problem = structuralProblem({ ...p, session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" }, execution: { status: "withheld", provenance: "observed" } });
|
|
53
|
+
add("structural parts in clear", !problem, problem ?? undefined);
|
|
54
|
+
if (problem)
|
|
55
|
+
return { ok: false, predicate: null, checks };
|
|
56
|
+
add("authorization issued by the gateway", p.issuer.kind === "gateway" && p.issuer.keyid === sig.keyid);
|
|
57
|
+
add("authorization operation is submitted", p.operation?.status === "submitted");
|
|
58
|
+
add("authorization permits the original call", p.policy?.decision === "allow" ? Array.isArray(p.policy.errors) && p.policy.errors.length === 0 : p.policy?.decision === "deny" && p.policy.enforced === false);
|
|
59
|
+
const del = p.delegation && verifyDelegation(p.delegation.envelope, opts.principalKeys);
|
|
60
|
+
add("delegation signature (principal key)", !!del?.ok);
|
|
61
|
+
if (del?.ok) {
|
|
62
|
+
const d = del.delegation;
|
|
63
|
+
add("delegation binds principal and agent", d.principal === p.principal.id && d.agent === p.agent.id && p.principal.provenance === "attested" && p.principal.keyid === del.keyid);
|
|
64
|
+
add("delegation valid at receipt time", delegationValidAt(d, p.timestamp));
|
|
65
|
+
add("executed tool within delegated scope", d.scopes.includes(p.tool.name));
|
|
66
|
+
}
|
|
67
|
+
const back = restorePaths(p, p.capture, undefined, opts.captureKey);
|
|
68
|
+
add("captured commitments are well formed", back.problems.length === 0, back.problems[0]?.error);
|
|
69
|
+
const missingArgs = back.missing.some((w) => under(w, ["request", "args"]));
|
|
70
|
+
add("request args digest", st.subject[0]?.digest.sha256 === p.request.argsDigest && (missingArgs || digestOf(back.predicate.request.args, digestSaltFor(back, p.capture, ["request", "args"])) === p.request.argsDigest));
|
|
71
|
+
const th = dsseVerify(bundle.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
|
|
72
|
+
add("tree head signature", th.ok && bundle.treeHead.payloadType === TREEHEAD_TYPE);
|
|
73
|
+
if (th.ok) {
|
|
74
|
+
const head = th.payload;
|
|
75
|
+
if (opts.logId !== undefined)
|
|
76
|
+
add("tree head names the expected log", head.log === opts.logId);
|
|
77
|
+
add("log inclusion proof", head.treeSize === bundle.inclusion.treeSize && verifyInclusion(leafHash(canonicalize(bundle.envelope)), bundle.inclusion, head.rootHash));
|
|
78
|
+
if (opts.logFile) {
|
|
79
|
+
try {
|
|
80
|
+
add("log file root matches tree head", MerkleLog.rootFromFile(opts.logFile, head.treeSize) === head.rootHash);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
add("log file root matches tree head", false);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return { ok: checks.every((c) => c.ok), predicate: p, checks };
|
|
88
|
+
}
|
|
10
89
|
/** The parts of a statement a capture note may never name: what a verifier reads to run its checks. A note naming one, or a commitment sitting there, is not a private receipt but a broken one. */
|
|
11
90
|
const STRUCTURAL_TOP = new Set(["receiptId", "timestamp", "issuer", "principal", "agent", "delegation", "tool", "authorization", "capture"]);
|
|
12
|
-
|
|
91
|
+
// The approval record's envelope and reason are withheld under a private rule; its status, times, and signer ids are not.
|
|
92
|
+
const STRUCTURAL_IN = { approval: new Set(["status", "requiredApprovers", "checkedAt", "consumedAt", "approverKeyids", "fields", "provenance"]), request: new Set(["argsDigest", "provenance"]), execution: new Set(["status", "provenance"]), policy: new Set(["decision", "reasons", "policyDigest", "enforced", "provenance"]), consumed: new Set(["provenance"]), session: new Set(["provenance"]), model: new Set(["provenance"]), operation: new Set(["idempotencyKey", "lookupDigest", "status", "budget", "originalReceiptId", "provenance"]), reconciliation: new Set(["original", "lookup"]) };
|
|
13
93
|
/**
|
|
14
94
|
* Why a statement cannot be verified at all, or null: the capture note is malformed, names a structural part, or a
|
|
15
95
|
* structural part is not what every check assumes it to be. Checked once, before anything reads the statement, so that
|
|
@@ -38,13 +118,15 @@ export function structuralProblem(p) {
|
|
|
38
118
|
return "receiptId or timestamp is not a string";
|
|
39
119
|
if (!isObject(p.issuer) || !isObject(p.principal) || !isObject(p.agent) || !isObject(p.session) || !isObject(p.model))
|
|
40
120
|
return "issuer, principal, agent, session, or model is not an object";
|
|
121
|
+
if (p.principal.provenance === "attested" && typeof p.principal.keyid !== "string")
|
|
122
|
+
return "an attested principal has no keyid";
|
|
41
123
|
if (!isObject(p.tool) || typeof p.tool.name !== "string")
|
|
42
124
|
return "tool.name is not a string";
|
|
43
125
|
if (!isObject(p.request) || typeof p.request.argsDigest !== "string" || !isObject(p.request.args))
|
|
44
126
|
return "request.args or request.argsDigest is not what it should be";
|
|
45
|
-
if (!isObject(p.execution) || !["executed", "failed", "denied", "error", "withheld"].includes(
|
|
127
|
+
if (!isObject(p.execution) || typeof p.execution.status !== "string" || !["executed", "failed", "denied", "error", "withheld"].includes(p.execution.status))
|
|
46
128
|
return "execution.status is not a status";
|
|
47
|
-
if (p.policy !== null && (!isObject(p.policy) || (p.policy.decision !== "allow" && p.policy.decision !== "deny") || !Array.isArray(p.policy.reasons)))
|
|
129
|
+
if (p.policy !== null && (!isObject(p.policy) || (p.policy.decision !== "allow" && p.policy.decision !== "deny") || !Array.isArray(p.policy.reasons) || typeof p.policy.policyDigest !== "string"))
|
|
48
130
|
return "policy is neither null nor a decision";
|
|
49
131
|
if (!isObject(p.facts) || Object.values(p.facts).some((f) => !isObject(f) || typeof f.tool !== "string"))
|
|
50
132
|
return "facts is not a map of facts";
|
|
@@ -52,8 +134,32 @@ export function structuralProblem(p) {
|
|
|
52
134
|
return "consumed is not an object";
|
|
53
135
|
if (p.delegation !== undefined && (!isObject(p.delegation) || !isObject(p.delegation.envelope)))
|
|
54
136
|
return "delegation is not a signed envelope";
|
|
55
|
-
if (p.authorization !== undefined && (!isObject(p.authorization) || !isObject(p.authorization.envelope)))
|
|
137
|
+
if (p.authorization !== undefined && (!isObject(p.authorization) || !isObject(p.authorization.envelope) || !isObject(p.authorization.treeHead) || !isObject(p.authorization.inclusion)))
|
|
56
138
|
return "authorization is not a bundle";
|
|
139
|
+
if (p.approval !== undefined) {
|
|
140
|
+
const a = p.approval;
|
|
141
|
+
if (!isObject(a) || typeof a.status !== "string" || !["approved", "denied"].includes(a.status) || (a.requiredApprovers !== 1 && a.requiredApprovers !== 2) || !isApprovalTime(a.checkedAt) || !Array.isArray(a.approverKeyids) || !a.approverKeyids.every((k) => typeof k === "string") || a.provenance !== "observed")
|
|
142
|
+
return "approval is not an approval record";
|
|
143
|
+
if (a.consumedAt !== undefined && !isApprovalTime(a.consumedAt))
|
|
144
|
+
return "approval consumption time is not a timestamp";
|
|
145
|
+
if (a.fields !== undefined && (!isObject(a.fields) || Object.entries(a.fields).some(([k, v]) => !["amount", "currency", "beneficiary"].includes(k) || typeof v !== "string" || !v.length)))
|
|
146
|
+
return "approval field mapping is malformed";
|
|
147
|
+
}
|
|
148
|
+
if (p.operation !== undefined) {
|
|
149
|
+
const problem = operationProblem(p.operation);
|
|
150
|
+
if (problem)
|
|
151
|
+
return problem;
|
|
152
|
+
}
|
|
153
|
+
if (p.reconciliation !== undefined) {
|
|
154
|
+
const r = p.reconciliation;
|
|
155
|
+
if (!isObject(r) || !isObject(r.original) || !isObject(r.original.envelope) || !isObject(r.original.treeHead) || !isObject(r.original.inclusion) || !isObject(r.lookup))
|
|
156
|
+
return "reconciliation is not a lookup and an original bundle";
|
|
157
|
+
const l = r.lookup;
|
|
158
|
+
const statuses = (v) => Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === "string" && s.length > 0 && s.length <= 128);
|
|
159
|
+
const path = (v) => typeof v === "string" && v.length > 0 && v.length <= 512 && v.split(".").every((s) => s.length > 0);
|
|
160
|
+
if (typeof l.tool !== "string" || !l.tool.length || !isObject(l.args) || !path(l.statusPath) || !path(l.identityPath) || !statuses(l.confirmed) || !statuses(l.failed) || l.confirmed.some((s) => l.failed.includes(s)))
|
|
161
|
+
return "reconciliation lookup is malformed or its terminal statuses overlap";
|
|
162
|
+
}
|
|
57
163
|
if (isObject(p.execution.upstream) && typeof p.execution.upstream.provider !== "undefined" && typeof p.execution.upstream.provider !== "string")
|
|
58
164
|
return "execution.upstream.provider is not a string";
|
|
59
165
|
return null;
|
|
@@ -80,6 +186,17 @@ export function verifyBundle(bundle, opts) {
|
|
|
80
186
|
const p = st.predicate;
|
|
81
187
|
add("issuer kind is known", p.issuer.kind === "gateway" || p.issuer.kind === "sdk", `${p.issuer.kind}${p.issuer.framework ? ` / ${p.issuer.framework}` : ""}`);
|
|
82
188
|
add("issuer keyid matches signer", p.issuer.keyid === sig.keyid);
|
|
189
|
+
if (p.operation) {
|
|
190
|
+
add("operation observed by gateway", p.issuer.kind === "gateway" && p.operation.provenance === "observed");
|
|
191
|
+
if (!p.reconciliation) {
|
|
192
|
+
// A retry of an existing operation has a receipt of its own. It is withheld (never forwarded again) and names the original.
|
|
193
|
+
const retry = p.operation.originalReceiptId !== p.receiptId;
|
|
194
|
+
add("operation names this original receipt", !retry || p.execution.status === "withheld");
|
|
195
|
+
const refused = p.execution.status === "withheld" || p.execution.status === "denied";
|
|
196
|
+
add("operation awaits provider reconciliation", retry || ["submitted", "pending", "unknown"].includes(p.operation.status) || refused && p.operation.status === "failed");
|
|
197
|
+
add("operation carries committed authorization", refused || !!p.authorization);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
83
200
|
if (p.issuer.kind === "gateway") {
|
|
84
201
|
add("gateway receipt carries a delegation", p.delegation !== undefined);
|
|
85
202
|
add("gateway receipt carries a policy decision", p.policy !== null);
|
|
@@ -100,7 +217,7 @@ export function verifyBundle(bundle, opts) {
|
|
|
100
217
|
const executed = p.execution.status === "executed" || p.execution.status === "failed";
|
|
101
218
|
// a call the gateway refused after the grant ran out is still a true record; only an executed call has to sit inside the window
|
|
102
219
|
const valid = delegationValidAt(d, p.timestamp);
|
|
103
|
-
add("delegation valid at receipt time", valid || !executed, valid ? `${d.issuedAt} .. ${d.expiresAt}` : `${d.issuedAt} .. ${d.expiresAt}; the call was ${p.execution.status}, so the grant need not have been in force`);
|
|
220
|
+
add("delegation valid at receipt time", valid || !executed || !!p.reconciliation, valid ? `${d.issuedAt} .. ${d.expiresAt}` : p.reconciliation ? "operator reconciliation; the original authorization's grant window is checked separately" : `${d.issuedAt} .. ${d.expiresAt}; the call was ${p.execution.status}, so the grant need not have been in force`);
|
|
104
221
|
add("executed tool within delegated scope", !executed || inScope, inScope ? p.tool.name : `${p.tool.name} not in [${d.scopes.join(", ")}]`);
|
|
105
222
|
}
|
|
106
223
|
}
|
|
@@ -142,6 +259,46 @@ export function verifyBundle(bundle, opts) {
|
|
|
142
259
|
add("request args digest", subjectOk, committedNote(args.missing));
|
|
143
260
|
else
|
|
144
261
|
add("request args digest", digestOf(full.request.args, digestSaltFor(back, note, ["request", "args"])) === p.request.argsDigest && subjectOk, args.how ? `recomputed from ${args.how} values` : undefined);
|
|
262
|
+
// An upstream error can follow a side effect too; every attempted forward must have consumed a valid approval.
|
|
263
|
+
const forwarded = ["executed", "failed", "error"].includes(p.execution.status);
|
|
264
|
+
if (p.approval) {
|
|
265
|
+
const a = p.approval;
|
|
266
|
+
const consumed = a.consumedAt !== undefined && Date.parse(a.consumedAt) >= Date.parse(a.checkedAt) && Date.parse(a.checkedAt) >= Date.parse(p.timestamp);
|
|
267
|
+
add("approval consistent with execution", !forwarded || (a.status === "approved" && consumed), a.status === "denied" ? `approval refused: ${typeof a.reason === "string" ? a.reason : "not approved"}` : "single use is enforced by the gateway's persistent store; one receipt cannot prove absence of reuse elsewhere");
|
|
268
|
+
// Only a forwarded call must rest on a valid approval. A refusal is an authentic record whatever its approval was:
|
|
269
|
+
// missing, expired, forged, already used, or valid for a call that the policy or the grant then refused.
|
|
270
|
+
if (forwarded && a.status === "approved") {
|
|
271
|
+
// The envelope is withheld under a private rule: it carries the action fields and a digest of the arguments.
|
|
272
|
+
const sealed = region(["approval", "envelope"]);
|
|
273
|
+
if (sealed.problem)
|
|
274
|
+
add("approval signatures (human keys)", false, sealed.problem);
|
|
275
|
+
// The issuer withholds the envelope only when it withholds the arguments. With the arguments in clear, a withheld
|
|
276
|
+
// envelope would let an issuer skip the binding check, so it fails rather than passes as committed.
|
|
277
|
+
else if (sealed.missing.length && !args.paths.length)
|
|
278
|
+
add("approval signatures (human keys)", false, "the approval envelope is withheld but the arguments are in clear; the binding cannot be checked");
|
|
279
|
+
else if (sealed.missing.length)
|
|
280
|
+
add("approval signatures (human keys)", true, committedNote(sealed.missing));
|
|
281
|
+
else {
|
|
282
|
+
const envelope = full.approval.envelope;
|
|
283
|
+
const signed = verifyApprovalStatement(envelope, opts.approvalKeys ?? [], a.requiredApprovers);
|
|
284
|
+
const reported = signed.ok && new Set(a.approverKeyids).size >= a.requiredApprovers && a.approverKeyids.every((id) => signed.approverKeyids.includes(id));
|
|
285
|
+
add("approval signatures (human keys)", signed.ok && reported, signed.ok ? `${signed.approverKeyids.length} distinct trusted signature(s)` : signed.error);
|
|
286
|
+
if (signed.ok) {
|
|
287
|
+
const at = a.consumedAt ?? a.checkedAt;
|
|
288
|
+
const valid = [a.checkedAt, at].every((time) => Date.parse(time) >= Date.parse(signed.approval.issuedAt) && Date.parse(time) < Date.parse(signed.approval.expiresAt));
|
|
289
|
+
add("approval valid at forward time", valid, `${signed.approval.issuedAt} .. ${signed.approval.expiresAt}; checked at ${at}`);
|
|
290
|
+
if (args.problem)
|
|
291
|
+
add("approval payload binding", false, args.problem);
|
|
292
|
+
else if (args.missing.length)
|
|
293
|
+
add("approval payload binding", true, committedNote(args.missing));
|
|
294
|
+
else {
|
|
295
|
+
const binding = verifyApproval(envelope, opts.approvalKeys ?? [], { principal: p.principal.id ?? "", agent: p.agent.id, tool: p.tool.name, args: full.request.args, ...(a.fields ? { fields: a.fields } : {}) }, { at, minApprovers: a.requiredApprovers });
|
|
296
|
+
add("approval payload binding", binding.ok, binding.ok ? "principal, agent, tool, full arguments, amount, currency, and beneficiary match" : binding.error);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
145
302
|
// a captured fact: its commitments are checked against a disclosure or the key; the policy decided on the real value
|
|
146
303
|
for (const name of Object.keys(p.facts)) {
|
|
147
304
|
for (const part of ["value", "args"]) {
|
|
@@ -226,6 +383,54 @@ export function verifyBundle(bundle, opts) {
|
|
|
226
383
|
const errors = isCommitment(p.policy.errors) || (Array.isArray(p.policy.errors) && p.policy.errors.length > 0);
|
|
227
384
|
add("no policy errors on an allow", !(p.policy.decision === "allow" && errors));
|
|
228
385
|
}
|
|
386
|
+
if (p.reconciliation) {
|
|
387
|
+
const r = p.reconciliation;
|
|
388
|
+
// Refuse nesting before the recursive verifier is called; the original must be the first operation attempt.
|
|
389
|
+
const osig = dsseVerify(r.original.envelope, opts.issuerKeys);
|
|
390
|
+
const ost = osig.ok ? osig.payload : null;
|
|
391
|
+
const original = ost?.predicate;
|
|
392
|
+
const eligible = isObject(original) && !("reconciliation" in original);
|
|
393
|
+
let originalOk = false;
|
|
394
|
+
if (eligible && ost) {
|
|
395
|
+
try {
|
|
396
|
+
const nested = ost.predicateType === RECEIPT_PREDICATE_TYPE
|
|
397
|
+
? verifyBundle(r.original, { ...opts, disclosed: undefined })
|
|
398
|
+
: verifyOriginalAuthorization(r.original, opts);
|
|
399
|
+
originalOk = nested.ok;
|
|
400
|
+
for (const c of nested.checks)
|
|
401
|
+
add(`reconciliation original ${c.name}`, c.ok, c.detail);
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
add("reconciliation original bundle is well formed", false);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
add("reconciliation original evidence verifies", eligible && originalOk);
|
|
408
|
+
const o = original?.operation;
|
|
409
|
+
const op = p.operation;
|
|
410
|
+
const linked = !!o && !!op && !operationProblem(o) && ["submitted", "pending", "unknown"].includes(o.status) && o.originalReceiptId === original.receiptId && op.originalReceiptId === original.receiptId && p.receiptId !== original.receiptId && (op.id === undefined || o.id === undefined || op.id === o.id) && op.idempotencyKey === o.idempotencyKey && op.lookupDigest === o.lookupDigest && canonicalize(op.budget) === canonicalize(o.budget) && canonicalize(p.principal) === canonicalize(original.principal) && canonicalize(p.agent) === canonicalize(original.agent) && canonicalize(p.tool) === canonicalize(original.tool) && canonicalize(p.delegation) === canonicalize(original.delegation) && p.issuer.keyid === original.issuer.keyid && Date.parse(p.timestamp) >= Date.parse(original.timestamp);
|
|
411
|
+
add("reconciliation links the original operation", linked);
|
|
412
|
+
add("reconciliation lookup matches authorization", !!o && digestOf(r.lookup) === o.lookupDigest);
|
|
413
|
+
const lookupArgs = region(["request", "args"]);
|
|
414
|
+
add("reconciliation lookup args match request", !lookupArgs.problem && (lookupArgs.missing.length > 0 || canonicalize(full.request.args) === canonicalize(r.lookup.args)), lookupArgs.missing.length > 0 ? "request arguments committed under the capture rule" : undefined);
|
|
415
|
+
const before = r.original.inclusion.leafIndex < bundle.inclusion.leafIndex && r.original.inclusion.treeSize <= bundle.inclusion.treeSize;
|
|
416
|
+
const oth = dsseVerify(r.original.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
|
|
417
|
+
const cth = dsseVerify(bundle.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
|
|
418
|
+
add("reconciliation logged after original", before && oth.ok && cth.ok && isObject(oth.payload) && isObject(cth.payload) && oth.payload.log === cth.payload.log);
|
|
419
|
+
const terminal = op?.status === "confirmed" || op?.status === "failed";
|
|
420
|
+
add("reconciliation records a terminal provider outcome", terminal && p.execution.status === "executed" && p.execution.provenance === "observed");
|
|
421
|
+
const rr = region(["execution", "result"]);
|
|
422
|
+
if (rr.problem)
|
|
423
|
+
add("reconciliation provider status", false, rr.problem);
|
|
424
|
+
else if (rr.missing.some((w) => pathKey(w) !== pathKey(["execution", "result", "_meta"])))
|
|
425
|
+
add("reconciliation provider status", true, "provider result withheld; disclose it or give the capture key to recompute the gateway-observed status");
|
|
426
|
+
else {
|
|
427
|
+
const ex = full.execution;
|
|
428
|
+
const status = providerValue(ex.result, r.lookup.statusPath);
|
|
429
|
+
const mapped = typeof status === "string" ? r.lookup.confirmed.includes(status) ? "confirmed" : r.lookup.failed.includes(status) ? "failed" : null : null;
|
|
430
|
+
const identity = providerValue(ex.result, r.lookup.identityPath);
|
|
431
|
+
add("reconciliation provider status", terminal && mapped === op?.status && identity === op?.idempotencyKey && !(isObject(ex.result) && ex.result.isError === true), "provider read observed by the gateway and bound to its idempotency key; no independent provider signature is implied");
|
|
432
|
+
}
|
|
433
|
+
}
|
|
229
434
|
const logKeys = opts.logKeys ?? [];
|
|
230
435
|
if (p.authorization) {
|
|
231
436
|
// The gateway says it committed this call to the log before forwarding it. Check that the committed statement is
|
|
@@ -237,8 +442,32 @@ export function verifyBundle(bundle, opts) {
|
|
|
237
442
|
add("authorization signature (issuer key)", asig.ok && typed && asig.keyid === sig.keyid, asig.ok ? (typed ? `keyid ${short(asig.keyid)}` : "not an authorization statement") : asig.error);
|
|
238
443
|
if (ast && typed) {
|
|
239
444
|
const ap = ast.predicate;
|
|
240
|
-
const same = ap.receiptId === p.receiptId && ap.tool.name === p.tool.name && ap.request.argsDigest === p.request.argsDigest && ap.agent.id === p.agent.id && ap.principal.id === p.principal.id && ap.policy?.decision === "allow";
|
|
445
|
+
const same = ap.receiptId === p.receiptId && ap.tool.name === p.tool.name && ap.request.argsDigest === p.request.argsDigest && ap.agent.id === p.agent.id && ap.principal.id === p.principal.id && (ap.policy?.decision === "allow" || ap.policy?.decision === "deny" && ap.policy.enforced === false);
|
|
241
446
|
add("authorization names this call", same, same ? `${ap.tool.name} for receipt ${short(ap.receiptId)}` : "committed for a different receipt, tool, arguments, agent, or decision");
|
|
447
|
+
if (ap.approval || p.approval) {
|
|
448
|
+
const stable = (approval) => approval ? { envelope: approval.envelope, requiredApprovers: approval.requiredApprovers, fields: approval.fields } : null;
|
|
449
|
+
const carries = canonicalize(stable(ap.approval)) === canonicalize(stable(p.approval));
|
|
450
|
+
add("authorization carries this approval", carries, "approval envelope, signer requirement, and argument mapping must match the precommit");
|
|
451
|
+
// A refusal needs no human keys, so the precommit's approval is checked for a forwarded call only.
|
|
452
|
+
if (forwarded) {
|
|
453
|
+
const ac = ap.approval;
|
|
454
|
+
// Under a private rule the precommit carries the receipt's commitment to the envelope: it is checked once restored.
|
|
455
|
+
const envelope = ac && isCommitment(ac.envelope) && carries ? full.approval?.envelope : ac?.envelope;
|
|
456
|
+
// an envelope withheld beside arguments in clear is not a private receipt: see "approval signatures (human keys)"
|
|
457
|
+
const sealed = isCommitment(envelope) && args.paths.length > 0;
|
|
458
|
+
const signed = ac && !sealed ? verifyApprovalStatement(envelope, opts.approvalKeys ?? [], ac.requiredApprovers) : null;
|
|
459
|
+
const valid = !!ac && ac.status === "approved" && ac.provenance === "observed" && isApprovalTime(ac.checkedAt) && (sealed || !!signed?.ok) &&
|
|
460
|
+
(!signed?.ok || (Date.parse(ac.checkedAt) >= Date.parse(signed.approval.issuedAt) && Date.parse(ac.checkedAt) < Date.parse(signed.approval.expiresAt))) &&
|
|
461
|
+
Date.parse(ac.checkedAt) >= Date.parse(p.timestamp) && Date.parse(ac.checkedAt) <= Date.parse(p.approval?.checkedAt ?? "") &&
|
|
462
|
+
Array.isArray(ac.approverKeyids) && new Set(ac.approverKeyids).size >= ac.requiredApprovers && (!signed?.ok || ac.approverKeyids.every((id) => signed.approverKeyids.includes(id)));
|
|
463
|
+
add("authorization approval was valid", valid, sealed ? "the envelope is withheld, so only the recorded status, times, and signer count are checked; disclose it or give the capture key to check the signatures" : "the precommit must record an approved statement with trusted signer observations and a check inside its validity window");
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (p.operation || ap.operation) {
|
|
467
|
+
const o = p.operation;
|
|
468
|
+
const aop = ap.operation;
|
|
469
|
+
add("authorization names this operation", !!o && !!aop && !operationProblem(aop) && aop.status === "submitted" && (aop.id === undefined || o.id === undefined || aop.id === o.id) && aop.idempotencyKey === o.idempotencyKey && aop.lookupDigest === o.lookupDigest && aop.originalReceiptId === o.originalReceiptId && canonicalize(aop.budget) === canonicalize(o.budget));
|
|
470
|
+
}
|
|
242
471
|
const ath = dsseVerify(a.treeHead, [...logKeys, ...opts.issuerKeys]);
|
|
243
472
|
add("authorization tree head signature", ath.ok && a.treeHead.payloadType === TREEHEAD_TYPE, ath.ok ? `keyid ${short(ath.keyid)}` : ath.error);
|
|
244
473
|
if (ath.ok) {
|
|
@@ -344,11 +573,16 @@ export function formatReport(r) {
|
|
|
344
573
|
}
|
|
345
574
|
else if (p.execution.status === "withheld")
|
|
346
575
|
row("authorization", "observed", "the log would not commit it; the call was not forwarded");
|
|
576
|
+
if (p.approval)
|
|
577
|
+
row("approval", p.approval.provenance, `${p.approval.status}; ${p.approval.requiredApprovers} approver(s) required${p.approval.consumedAt ? `; consumed ${p.approval.consumedAt}` : ""}${typeof p.approval.reason === "string" ? `; ${p.approval.reason}` : ""}`);
|
|
347
578
|
const upstreamCheck = r.checks.find((c) => c.name === "upstream signature (upstream key)" || c.name === "upstream signature (provider secret)");
|
|
348
579
|
const hasUpstream = (p.execution.status === "executed" || p.execution.status === "failed") && !!p.execution.upstream;
|
|
349
580
|
const byProvider = hasUpstream && isProviderAttestation(p.execution.upstream);
|
|
350
581
|
const attestedAs = upstreamCheck?.ok ? (byProvider ? "attested (shared secret)" : "attested") : p.execution.provenance;
|
|
351
582
|
const note = !hasUpstream ? "" : upstreamCheck ? (upstreamCheck.ok ? ` (${byProvider ? upstreamCheck.detail : `signed by upstream ${upstreamCheck.detail}`})` : " (upstream signature FAILED)") : byProvider ? " (carries a provider delivery; pass the provider secret to check it)" : " (carries an upstream signature; pass --upstream-key to check it)";
|
|
352
|
-
|
|
583
|
+
// a refusal says why, as the receipt records it; under a capture rule the reason is a commitment, and the report says so rather than printing it
|
|
584
|
+
const reason = "reason" in p.execution ? p.execution.reason : undefined;
|
|
585
|
+
const why = reason === undefined ? "" : typeof reason === "string" ? `: ${reason}` : ": (reason withheld under the capture rule)";
|
|
586
|
+
row("execution", attestedAs, `${p.execution.status}${why}${note}`);
|
|
353
587
|
return lines.join("\n");
|
|
354
588
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# Payload-bound human approvals
|
|
2
|
+
|
|
3
|
+
A delegation lets an agent use a tool. A human approval authorizes one exact call: this principal, this agent, this tool, and every argument, until a short expiry. The gateway requires the signed approval before forwarding a protected call. A flag such as `approved: true` in the arguments has no authority.
|
|
4
|
+
|
|
5
|
+
The approval is a DSSE envelope signed with an approver's Ed25519 key. Its payload carries `approvalId`, `principal`, `agent`, `tool`, a SHA-256 digest of the complete arguments, `issuedAt`, `expiresAt`, and the action's `amount`, `currency`, and `beneficiary` when those fields exist. Money is an integer in minor units: `2500` means £25.00 for `GBP`, never `25.00`. Extra arguments are covered by the digest too; changing a note or adding a field invalidates the approval.
|
|
6
|
+
|
|
7
|
+
## Configure the gateway
|
|
8
|
+
|
|
9
|
+
Generate approver keys with `agent-custody keygen --dir keys --name approver`, keep their private halves with the people approving actions, and add their public halves to the gateway:
|
|
10
|
+
|
|
11
|
+
```json
|
|
12
|
+
{
|
|
13
|
+
"approvals": {
|
|
14
|
+
"trustedKeys": ["keys/approver.pub", "keys/second-approver.pub"],
|
|
15
|
+
"usedDir": "approvals-used",
|
|
16
|
+
"maxLifetimeSeconds": 900,
|
|
17
|
+
"tools": [
|
|
18
|
+
{ "tool": "stripe.refund", "minApprovers": 2 }
|
|
19
|
+
]
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
This is an addition to the [gateway config](usage.md#setup-step-by-step), with paths relative to that file. `maxLifetimeSeconds` caps the approval lifetime, `expiresAt` minus `issuedAt`. The default is `3600`. The signer chooses the expiry, so the gateway refuses an approval with a longer lifetime, in every mode. This keeps an unused approval, which the agent holds, from staying usable for years. `minApprovers` is `1` by default, or `2` for two distinct trusted signing keys. A repeated signature or the same key listed twice counts once. The operator must assign those keys to distinct people; signatures establish possession of keys, not independent human identities.
|
|
25
|
+
|
|
26
|
+
`tool: "*"` protects every agent call, with an exact tool rule taking precedence. Wildcard rules do not require approvals for the gateway's internal fact lookups. A named fact-lookup tool cannot also have an exact approval rule: startup rejects that configuration. The gateway does not start with an empty trust list, an empty tools list, or duplicate tool rules.
|
|
27
|
+
|
|
28
|
+
The default action argument names are `amount`, `currency`, and `beneficiary`. For a refund whose recipient is `customer_id`, map it explicitly:
|
|
29
|
+
|
|
30
|
+
```json
|
|
31
|
+
{ "tool": "stripe.refund", "minApprovers": 1, "fields": { "beneficiary": "customer_id" } }
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Pass the same `fields` when creating the approval. These are top-level argument names, not dot paths. Each present amount must be a safe integer; a present currency or beneficiary must be a nonempty string. An omitted action field is still covered by the complete argument digest, but the approval cannot establish a business meaning for a differently named field unless it is mapped.
|
|
35
|
+
|
|
36
|
+
## Sign the exact action and send it
|
|
37
|
+
|
|
38
|
+
Use the TypeScript API from the process where the human reviews the action. Show the complete arguments before signing, including any fields beyond the displayed amount and recipient.
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import {
|
|
42
|
+
APPROVAL_META_KEY, createApproval, dsseCountersign, loadPrivateKey,
|
|
43
|
+
} from "@agent-custody/receipts";
|
|
44
|
+
|
|
45
|
+
const args = { customer_id: "cust_123", amount: 2500, currency: "GBP" };
|
|
46
|
+
const fields = { beneficiary: "customer_id" };
|
|
47
|
+
const first = createApproval(loadPrivateKey("keys/approver.key"), {
|
|
48
|
+
principal: "user_456",
|
|
49
|
+
agent: "support-agent",
|
|
50
|
+
tool: "stripe.refund",
|
|
51
|
+
args,
|
|
52
|
+
fields,
|
|
53
|
+
expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),
|
|
54
|
+
});
|
|
55
|
+
// For a two-person rule, the second person reviews and signs the same payload.
|
|
56
|
+
const approved = dsseCountersign(first, loadPrivateKey("keys/second-approver.key"));
|
|
57
|
+
const result = await agent.callTool({
|
|
58
|
+
name: "stripe.refund",
|
|
59
|
+
arguments: args,
|
|
60
|
+
_meta: { [APPROVAL_META_KEY]: approved },
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`createApproval` supplies a UUID `approvalId` and the current `issuedAt` unless given explicitly. `expiresAt` is required and must follow `issuedAt`. The window is half open: the approval is valid at issuance and invalid at expiry. `dsseCountersign` preserves the payload and adds a signature; it does not issue a different approval.
|
|
65
|
+
|
|
66
|
+
The gateway reads `agent-custody/approval` from the call's `_meta` and removes that key before forwarding. It checks the trusted signatures, threshold, lifetime cap, validity window, principal, agent, tool, complete argument digest, and action fields before fact lookups and Cedar evaluation. Missing, malformed, expired, or mismatched approval denies the call even in observe mode. A valid approval still needs a valid grant and an allowing policy.
|
|
67
|
+
|
|
68
|
+
After facts and any pre-commit authorization have completed, the gateway checks the approval again and atomically consumes its id immediately before forwarding. An approval that expired during those waits, or lost a concurrent race to use the same id, leaves the call `withheld`. Every refusal gets a signed receipt with its reason.
|
|
69
|
+
|
|
70
|
+
## Consumption and failure recovery
|
|
71
|
+
|
|
72
|
+
`usedDir` is part of the enforcement boundary. Keep it persistent across restarts and share the same directory between all gateway processes that accept the same approvals. The filesystem must support exclusive file creation consistently across those processes, and durable file and directory synchronization. A synchronization failure withholds the call. Separate directories let each gateway consume the same approval once.
|
|
73
|
+
|
|
74
|
+
Consumption is conservative: the id is burned before forwarding. A crash, a log error, or an unknown upstream outcome after consumption does not release it. Obtain a fresh approval after checking the upstream's actual state; retry and exactly-once outcome handling are separate work. Do not delete consumption records while their approvals can still be valid. There is no automatic pruning.
|
|
75
|
+
|
|
76
|
+
An offline receipt verifier checks the signed action and the gateway's recorded consumption time. It cannot prove that another gateway never used that approval: single use depends on this shared persistent store and the gateway enforcing it.
|
|
77
|
+
|
|
78
|
+
## Verify the evidence
|
|
79
|
+
|
|
80
|
+
The receipt's optional `approval` record embeds the envelope, the required threshold, checked time, status, observed signer keyids, configured field mapping when any, and consumption time when consumed. A missing, malformed, or untrusted approval envelope on a refused call is omitted. Only signature entries that verify against trusted approval keys are retained in an embedded envelope. Under a private capture rule the envelope and the reason are withheld as commitments; see [Privacy](#privacy-limits). Its provenance is `observed`: the gateway records what it checked; the embedded envelope supplies the independent approver signatures.
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
agent-custody verify receipts/<id>.json \
|
|
84
|
+
--issuer-key keys/gateway.pub --principal-key keys/principal.pub \
|
|
85
|
+
--approval-key keys/approver.pub --approval-key keys/second-approver.pub
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
In code, give `verifyBundle` an `approvalKeys` array of `PublicKeyRef`s, separate from `issuerKeys` and `principalKeys`. Those other keys never implicitly authorize an approval. For a forwarded call carrying an approval record, verification requires trusted approval signatures, the exact action binding, validity at the recorded check and consumption times, and an approved, consumed record. A call that the gateway did not forward needs none of these, and so needs no approval key. This covers a call that Cedar denied, a call outside the grant, and a call withheld after consumption, even when the approval was valid. The record of such a call is an authentic refusal. Verification does not turn its approval into an authorization.
|
|
89
|
+
|
|
90
|
+
`verifyApproval(envelope, trustedKeys, binding, { at?, minApprovers?, maxLifetimeSeconds? })` checks an envelope directly and returns either `{ ok: true, approval, approverKeyids }` or `{ ok: false, error }`. It does not consume it. `consumeApproval(usedDir, approvalId, receiptId, at)` creates the exclusive consumption marker and throws if the id has already been used. The gateway combines these steps; callers building another enforcement boundary must preserve their order.
|
|
91
|
+
|
|
92
|
+
## Privacy limits
|
|
93
|
+
|
|
94
|
+
The approval envelope arrives in the agent's `_meta`. It carries the amount, currency, beneficiary, and an **unsalted digest of the full arguments**. Under a private capture rule the receipt withholds the whole envelope as one commitment at `approval.envelope`. It is salted, and encrypted in mode `encrypted`. The precommit authorization carries the same commitment. A refusal `reason` can quote the statement, so it is withheld too. Without this, the receipt would publish the action fields, and the digest would confirm a guess of the arguments (issue #126).
|
|
95
|
+
|
|
96
|
+
The record keeps the gateway's own observations in clear: the status, the required threshold, the check and consumption times, the signer key ids, and the configured field mapping. A reviewer sees that an approval was checked and when. To check the signatures and the binding, the reviewer restores the envelope and the arguments with the capture key or a disclosure (`approval.envelope` and `request.args.$rest` in the disclosure file). Without them, the verifier passes the approval checks as committed, as it does for `request args digest`, and says so. A tool with a private rule and an approval therefore proves the approval only to a reviewer who holds the key or a disclosure. The browser verifier cannot restore them.
|
|
97
|
+
|
|
98
|
+
When the issuer withholds nothing under `request.args`, an approved envelope stays in clear. This happens when `args` is in mode `clear` with a private `result`. It also happens when a private `args` rule lists every argument of the call in `clear`, or the call has no arguments. The envelope payload then equals the public call, and the gateway checked that. A denied envelope is still withheld, because it can carry another call's fields. So is the envelope of a call whose tool name is masked. The verifiers use the same test: a forwarded, approved call whose note withholds the envelope, but withholds nothing under `request.args`, fails `approval signatures (human keys)`. Otherwise an issuer could skip the binding check whenever the arguments are public.
|
|
99
|
+
|
|
100
|
+
### What the receipt can prove about the approval
|
|
101
|
+
|
|
102
|
+
- The receipt proves the signatures, the binding, and the window only to a reviewer who has the envelope. Under a private rule that is the capture key (mode `encrypted`) or a disclosure of `approval.envelope`.
|
|
103
|
+
- In mode `digest` the gateway keeps no copy of the envelope. The salts file holds only salts. A disclosure can then come only from whoever kept the approval: the agent or the approver. If nobody kept it, the human approval cannot be proven afterwards. Use mode `encrypted` when you must prove it later.
|
|
104
|
+
- The receipt does not record `maxLifetimeSeconds`. The offline verifier cannot check the lifetime cap. Only the gateway enforces it, when it admits the approval.
|
|
105
|
+
- Single use is also not provable offline. See above.
|
|
106
|
+
|
|
107
|
+
[Tutorial 30](../examples/30-payload-bound-approvals.ts) runs a real gateway with two approvers, refuses changed arguments, an expired approval and an insufficient threshold, forwards the exact approved call, refuses its replay, and verifies every receipt.
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# A real Codex agent, a wrong plan, and recovery
|
|
2
|
+
|
|
3
|
+
The model handles a support request using MCP tools behind the custody gateway. The CRM import deliberately says `enterprise` when the account is actually on `free`. Codex decides whether to record benefits and issue a simulated service credit. An operator then introduces the correction, traces potentially affected actions and beliefs, reviews a recovery plan, and explicitly approves compensation.
|
|
4
|
+
|
|
5
|
+
The support calls come from `codex exec`, not a handwritten tool sequence. The correction and recovery are operator commands. Billing is a persistent local stand-in, not Stripe; a reversal compensates a simulated credit and preserves the original record. No real money moves.
|
|
6
|
+
|
|
7
|
+
See the [recorded live run](../../state/examples/codex-recovery/SAMPLE-RUN.md) for an actual result, including the final verification of 13 receipts.
|
|
8
|
+
|
|
9
|
+
## Before running
|
|
10
|
+
|
|
11
|
+
Use Node 22 with native TypeScript support (or later), Bun, and a Codex CLI that supports `exec`, MCP, `--ignore-user-config`, and `--ephemeral`. Tested with Node 24 and codex-cli 0.163.0. Codex needs working authentication and model access; use `codex login` if needed. An existing ChatGPT login works; an API key is not required when that login is available. Live runs consume the account's normal model usage and require network access to the model.
|
|
12
|
+
|
|
13
|
+
From the repository root:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
bun install --frozen-lockfile
|
|
17
|
+
bun run build
|
|
18
|
+
codex login status
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Run the support task
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
cd packages/state
|
|
25
|
+
node examples/codex-recovery/run.ts run
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Optionally select a model your Codex account supports:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
node examples/codex-recovery/run.ts run --model <model>
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The runner creates a fresh `examples-out/codex-recovery-*/case/` directory and prints its path. It imports the wrong plan, launches Codex with a task and business policy, waits up to three minutes, then simulates the operator learning about the CRM bug. The operator revokes the support grant, retracts the wrong plan, and writes `plan = free`. The runner verifies the receipts and prints a proposed recovery plan. It stops before applying that plan.
|
|
35
|
+
|
|
36
|
+
The expected story is:
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
CRM import: enterprise
|
|
40
|
+
→ Codex reads the account memory
|
|
41
|
+
→ Codex may record discount 20 / priority support and issue a 2500-pence credit
|
|
42
|
+
→ Operator corrects the plan to free and retires the support grant
|
|
43
|
+
→ Review possible dependencies and proposed recovery
|
|
44
|
+
→ Explicit approval: correct stale benefits and reverse the simulated credit
|
|
45
|
+
→ Check current state and all signed receipts
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The agent can decline, perform fewer actions, or encounter an error. Read `agent-answer.txt` and `codex-events.jsonl` to see what actually happened. The runner does not retry until the desired mistake appears or replace a failed model run with scripted calls. The plan reports `agentCalls` and `exposed`; zero gateway activity is explicitly labelled as not demonstrating an agent workflow. A credit without an observed dependency on the plan requires manual review rather than automatic recovery.
|
|
49
|
+
|
|
50
|
+
## Review and recover
|
|
51
|
+
|
|
52
|
+
Read `recovery-plan.json`. It names the exact beliefs to retract, corrected values to write, and simulated credits to reverse. The plan digest binds approval to those actions and the observed state. Changes after review invalidate it.
|
|
53
|
+
|
|
54
|
+
Copy the `recover` command printed by the runner, or use:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
node examples/codex-recovery/run.ts recover \
|
|
58
|
+
--dir /absolute/path/to/case \
|
|
59
|
+
--approve <printed-plan-digest>
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
For the typical enterprise-to-free run, expect:
|
|
63
|
+
|
|
64
|
+
- Current plan: `free`; discount: `0`; support tier: `standard`.
|
|
65
|
+
- Original simulated credit: preserved, with status `reversed` and its reversal receipt ID.
|
|
66
|
+
- Original beliefs: retained in history, with receipted retractions.
|
|
67
|
+
- `receiptsVerified` includes the original calls, correction, and recovery.
|
|
68
|
+
- The command ends with `OK: recovery complete; evidence verified.`
|
|
69
|
+
|
|
70
|
+
Repeat verification without issuing tool calls:
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
node examples/codex-recovery/run.ts verify --dir /absolute/path/to/case
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
To refresh a plan after intervening activity or a partially completed recovery:
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
node examples/codex-recovery/run.ts inspect --dir /absolute/path/to/case
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
If Codex fails, its artifacts remain. Check `codex-stderr.log` and `codex-events.jsonl`. To continue an operator investigation of that failed run, use `correct --dir /absolute/path/to/case`, then inspect its actual evidence. A new `run` always creates a separate case. Demo grants last 24 hours; after expiration, inspect/verify still work, but recovery needs newly issued operator authority.
|
|
83
|
+
|
|
84
|
+
## Demo commands and flags
|
|
85
|
+
|
|
86
|
+
These commands belong to the example runner, not the published `agent-custody` or `agent-custody-memory` CLI. Run them from `packages/state` as `node examples/codex-recovery/run.ts <command>`.
|
|
87
|
+
|
|
88
|
+
| Command | Flags | Behavior |
|
|
89
|
+
| --- | --- | --- |
|
|
90
|
+
| `run` | optional `--model <model>` | Creates a fresh case, runs Codex, introduces the operator correction, and saves a recovery plan; stops before recovery |
|
|
91
|
+
| `correct` | required `--dir <case>` | Revokes support authority, retracts the wrong plan, records the corrected plan, and saves a recovery plan; useful after a failed agent run |
|
|
92
|
+
| `inspect` | required `--dir <case>` | Verifies existing evidence and saves a fresh plan and approval digest without issuing tool calls |
|
|
93
|
+
| `recover` | required `--dir <case>` and `--approve <digest>` | Rejects a changed plan or state; applies the reviewed recovery, saves the verification report, and prints `OK` on success |
|
|
94
|
+
| `verify` | required `--dir <case>` | Checks evidence and current recovery state without issuing tool calls; prints the report and exits nonzero if recovery is incomplete |
|
|
95
|
+
| `help` | none | Lists the example runner's commands |
|
|
96
|
+
|
|
97
|
+
Here `--approve` is an explicit confirmation by the local operator running the command. The digest covers the reviewed plan and snapshot; it is not a separate cryptographically signed human-approval artifact. The gateway's [payload-bound human approvals](approvals.md) are a different feature. Recovery calls still use the operator's signed delegation grant and receive signed gateway receipts; the recovery-plan digest is included in retraction and credit-reversal reasons.
|
|
98
|
+
|
|
99
|
+
## What to inspect
|
|
100
|
+
|
|
101
|
+
| Artifact | What it tells you |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| `prompt.txt`, `codex-command.json` | The actual task and Codex invocation |
|
|
104
|
+
| `codex-events.jsonl`, `agent-answer.txt`, `agent-run.json` | Model events, final answer, and whether the live process completed |
|
|
105
|
+
| `ledger.jsonl` | Original beliefs, corrections, and retractions |
|
|
106
|
+
| `receipts/`, `log.jsonl`, `keys/*.pub` | Signed calls, precommitted billing authorizations, and verification material |
|
|
107
|
+
| `billing.json` | Simulated credits and compensation, linked to receipt IDs |
|
|
108
|
+
| `recovery-plan.json`, `approval.json`, `verification.json` | Reviewed actions, explicit approval, and final verification result |
|
|
109
|
+
|
|
110
|
+
The verifier checks receipt signatures, delegation, inclusion in the local log, signed upstream results, and consistency of the demo stores with those receipts. All demo keys and the log live on the same machine: this is a workflow demonstration, not evidence against a malicious operator controlling that machine.
|
|
111
|
+
|
|
112
|
+
## Boundaries
|
|
113
|
+
|
|
114
|
+
- Blast radius records prior exposure in a gateway session. It does not prove that the model reasoned from a fact or that the fact caused an action.
|
|
115
|
+
- A verified receipt authenticates recorded evidence, not the truth of the customer's plan or correctness of a business decision.
|
|
116
|
+
- The gateway caps credits and confines writes to this account's benefits. Entitlement is intentionally left to the agent in this incident; a production policy could independently check it and prevent the credit.
|
|
117
|
+
- Codex runs with read-only shell sandbox settings, shell tools disabled, web search disabled, and user-configured apps/plugins disabled. Its MCP server is required and configured for this invocation only. Calls to this local demo server are preapproved in Codex; the gateway still enforces the grant and Cedar policy. The gateway owns the signing keys and the billing service; the model is not given them as tool data. These settings demonstrate controlled tool access, not adversarial OS isolation of an untrusted process.
|
|
118
|
+
- Recovery is deliberately limited to the two benefit predicates and simulated service credits in this case. Real refunds, customer communications, downstream caches, and model context need their own recovery decisions.
|
|
119
|
+
- Run operator commands sequentially for one case. The plan freshness check is not a transactional lock against concurrent operators.
|
|
120
|
+
|
|
121
|
+
## Offline regression coverage
|
|
122
|
+
|
|
123
|
+
The regular suite never calls Codex or the network. It drives the same MCP servers and recovery functions with scripted calls, clearly labelled as scripted:
|
|
124
|
+
|
|
125
|
+
```sh
|
|
126
|
+
node examples/10-support-recovery.ts
|
|
127
|
+
bun run test test/codex-recovery.test.ts test/examples.test.ts
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The checks cover approval, stale plans, revoked support authority, duplicate-credit prevention, receipt tampering, store/evidence consistency, missing observed dependencies, and runs without agent activity.
|
|
131
|
+
|
|
132
|
+
Codex integration references: [non-interactive mode](https://learn.chatgpt.com/docs/non-interactive-mode), [MCP configuration](https://learn.chatgpt.com/docs/extend/mcp?surface=cli).
|