@agent-custody/receipts 0.12.0 → 0.14.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/docs/sdk.md CHANGED
@@ -38,6 +38,88 @@ Policies see `context.args` and an empty `context.facts`. A policy that reads `c
38
38
 
39
39
  ## Claude Code
40
40
 
41
+ ### One command
42
+
43
+ ```bash
44
+ npx @agent-custody/receipts init claude-code
45
+ ```
46
+
47
+ The command sets up custody for your own Claude Code sessions. It prints each step.
48
+
49
+ 1. It makes an agent key in `~/.config/agent-custody/keys/`.
50
+ 2. It writes `sdk.json` in `~/.config/agent-custody/` with `"mode": "observe"` and a `receiptsDir`. No log is configured, so the receipts stay on your machine.
51
+ 3. It writes a starter deny set to `policy.cedar`: force push, `rm -rf` on `/`, `~`, and `$HOME`, `terraform destroy`, `terraform apply -destroy`, and `drop database` in both cases. Each rule has a `@reason`, so the denial text says what the rule forbids. The policy permits every other call, and it permits `git push --force-with-lease` (see [The starter deny set](#the-starter-deny-set)).
52
+ 4. It registers the `PreToolUse`, `PostToolUse`, and `PostToolUseFailure` hooks in `.claude/settings.local.json` of the current directory. Claude Code adds that file to your global git ignore only when Claude Code itself creates it, so `init` does not rely on that. When the project is a git repository and git does not ignore the file, `init` prints a warning with the line to add to `.gitignore`: `.claude/settings.local.json`. The file holds absolute paths of your home directory. `init` never edits `.gitignore`. With `--user`, the hooks go to `~/.claude/settings.json` and apply to every project.
53
+ 5. It prints the next step: start a Claude Code session, then run the report.
54
+
55
+ The hook command in the settings file uses absolute paths: the Node binary, the CLI script that runs now, and the absolute path of `sdk.json`. The command merges into an existing settings file. It keeps every other key and every other hook, and it does not add a hook that is already there. If the settings file is not valid JSON, the command stops with an error and changes nothing.
56
+
57
+ Each hook is its own process, and Claude Code runs hooks at the same time for parallel tool calls, subagents, and several sessions. The local log `log.jsonl` takes the lock file `log.jsonl.lock` for each append, reads the leaves that other processes appended, and then writes its own leaf. A lock file that is older than ten seconds belongs to a process that died, and the next append removes it.
58
+
59
+ The hook command pins the path of the Node binary that runs `init`. With nvm, a removed Node version breaks the hook, and every tool call then prints an error. After you remove a Node version, run `init` again. The second run updates the path.
60
+
61
+ You can run the command two times. It never overwrites an existing key, `sdk.json`, `policy.cedar`, or `log.pub`, so your edits and your pinned log key stay. When `sdk.json` exists, the command ignores `--enforce` and the log options, and it prints a warning that names each flag that it did not apply. A second run does update the path in a hook of ours. When the first run came from the npx cache (a path with `/_npx/`), the command prints a warning, because npm can clear that cache and the hooks then stop working. Install the package globally with `npm install -g @agent-custody/receipts` and run the command again. The second run replaces the old path.
62
+
63
+ | option | effect |
64
+ | --- | --- |
65
+ | `--dir <dir>` | the directory for the key, the config, the policy, and the receipts. Default: `~/.config/agent-custody` |
66
+ | `--user` | write the hooks to `~/.claude/settings.json` |
67
+ | `--enforce` | leave out `"mode": "observe"`, so a denied call is blocked |
68
+ | `--log-url <url>` | send the receipts to a log as hashes (`hashOnly`, a 3 second timeout) instead of a local `log.jsonl`. It needs `--log-key`: without the key of the log, `report` cannot check the tree head of any receipt, so the command stops with an error |
69
+ | `--log-id <id>` | the log id that the tree heads must name |
70
+ | `--log-token-env NAME` | the NAME of the environment variable that holds the log token. Default: `AGENT_CUSTODY_LOG_TOKEN`. The command refuses a value that is not an uppercase variable name, so a token never enters a file |
71
+ | `--log-key <pub>` | the log's public key file, in PEM form. The command refuses a private key and any other file. It copies the file to `log.pub` and pins it in `log.keys` when it writes a new `sdk.json`. A second run does not replace `log.pub` |
72
+
73
+ ### The starter deny set
74
+
75
+ Each rule matches the text of a Bash command with the Cedar `like` operator, and `*` is the only wildcard of `like`. The rules catch the plain form of each command. They are not a sandbox.
76
+
77
+ | command | the policy |
78
+ | --- | --- |
79
+ | `git push --force`, `git push -f`, `git push origin main -f` | denied |
80
+ | `git push --force-with-lease` | allowed. It is a force push that fails when the remote has new commits, so it is the safer form. The `@reason` of the rule says so |
81
+ | `git push origin main && rm -f stale.lock`, `git push origin fix-f` | allowed |
82
+ | `rm -rf /`, `rm -fr /`, `rm -rf /*`, `rm -rf ~`, `rm -rf $HOME`, `rm -rf ${HOME}` | denied |
83
+ | `rm -rf /tmp/build`, `rm -rf ~/projects/app/dist` | allowed |
84
+ | `terraform destroy`, `terraform apply -destroy` | denied |
85
+ | `terraform plan`, `terraform plan -destroy` | allowed |
86
+
87
+ A `--force` flag matches anywhere after `git push`. A `-f` flag matches right after `git push` or at the end of the command. A `-f` in the middle of a command does not match. The reason is that `like` cannot find where one shell command ends and the next starts, and a match there would block `git push origin main && rm -f stale.lock`. `test/claude-init.test.ts` runs every command of this table.
88
+
89
+ ### The denial text
90
+
91
+ A Cedar policy can carry a `@reason("...")` annotation. When a rule that denies a call has one, the hook returns its text. When several rules deny the call, the hook joins their reasons with `; ` in file order and lists the rules.
92
+
93
+ ```cedar
94
+ @reason("terraform destroy deletes infrastructure")
95
+ forbid(principal, action == Action::"Bash", resource)
96
+ when { context.args has command && context.args.command like "*terraform destroy*" };
97
+ ```
98
+
99
+ ```text
100
+ agent-custody denied this call: terraform destroy deletes infrastructure (rule policy5, receipt 47eb52af-...)
101
+ ```
102
+
103
+ A rule with no annotation gives its id in place of the reason: `agent-custody denied this call: policy3 (rule policy3, receipt ...)`. A deny that names no rule keeps the plain text, such as `agent-custody: no permit policy matched (receipt ...)` or the evaluation error. The issuer parses the annotations one time, when it loads the policy.
104
+
105
+ The receipt does not change. It keeps the policy ids and the policy digest, and its `execution.reason` stays the list of ids. The reason text is for the agent and for the person who reads the session. The other adapters in this file still return the rule ids.
106
+
107
+ ### The report
108
+
109
+ ```bash
110
+ agent-custody report --config ~/.config/agent-custody/sdk.json
111
+ ```
112
+
113
+ `init` prints this command with absolute paths. The report reads the receipts directory of the config and verifies each receipt with the agent's key. Then it prints `would have denied N calls`, and for each call the tool, the command or the file path, the `@reason` of the rule when it has one, the Cedar rule, and the receipt id. A receipt that does not verify is counted apart, listed with the reason, and never counted as a denial. The command then exits with code 1. The report ends with the next step: remove the `"mode": "observe"` line from `sdk.json` to enforce the policy. A denial that the policy enforced (a config without the observe line) is listed apart as `denied`.
114
+
115
+ `policy simulate` answers another question: what a proposed policy would change in recorded history. Use `report` to read what the policy in the config decided in observe mode.
116
+
117
+ ### An incident replay
118
+
119
+ `node examples/38-incident-replay.ts` runs the hook in enforce mode with scripted events. `terraform plan` runs. `terraform destroy -auto-approve` and `rm -rf ~` are denied before they run, and a reviewer verifies the denial receipts with the public key only. The page [An incident replay](../../../site/guide/incident-replay.md) shows the output and the limit: a credential in the agent's environment goes around the hook.
120
+
121
+ ### Register the hook by hand
122
+
41
123
  Register the hook command in `.claude/settings.json`. The same command handles all three events.
42
124
 
43
125
  ```json
@@ -58,7 +140,7 @@ Register the hook command in `.claude/settings.json`. The same command handles a
58
140
 
59
141
  `AGENT_CUSTODY_CONFIG` works instead of `--config`. Behaviour per event:
60
142
 
61
- - **PreToolUse.** Evaluates the policy. On deny, issues a denial receipt and returns `permissionDecision: "deny"` with the receipt id in the reason. On allow, or with no policy, returns no decision, so Claude Code's own permission prompts still apply. The hook never auto-approves.
143
+ - **PreToolUse.** Evaluates the policy. On deny, issues a denial receipt and returns `permissionDecision: "deny"` with a reason that says what the rule forbids: `agent-custody denied this call: terraform destroy deletes infrastructure (rule policy5, receipt <id>)`. See [The denial text](#the-denial-text). If the log does not take the receipt, the hook still denies the call, and the text ends with `no receipt` and why instead of the receipt id. On allow, or with no policy, returns no decision, so Claude Code's own permission prompts still apply. The hook never auto-approves.
62
144
  - **PostToolUse.** Issues an executed receipt carrying `tool_response`.
63
145
  - **PostToolUseFailure.** Issues a failed receipt.
64
146
 
@@ -53,6 +53,7 @@ Each row names the attacker, the move, the defence, and whether the defence is a
53
53
  | Rewrite a receipt after the fact | The receipt's envelope is signed by the gateway key, which the operator holds, so the signature alone does not stop this. What stops it is the log: the leaf hash of the original envelope is in a tree whose head the log signed, and a rewritten receipt has a different hash with no inclusion proof. | evidence, with a remote log; deployment, with a local log the operator can rewrite |
54
54
  | Drop a receipt | The log's tree only grows, and consistency proofs between any two heads show nothing was removed. A receipt the operator never logged never existed as evidence, which is the point of `precommit` for consequential calls: the authorization leaf goes in before the action. [Strict mode](usage.md#strict-mode) does that for every call, with a remote hash-only log and no outbox, and its receipts say so, so a verifier can require it; a modified gateway can still claim strict mode. | evidence for logged receipts; withheld calls for pre-committed tools, and for every call under strict mode |
55
55
  | Forge a receipt for an action that never happened | Nothing in the log stops the operator logging a fabricated receipt; the log commits to existence, not truth. What limits it: the upstream's signature over the result when the upstream signs, provider attestations where the provider delivers them, and the principal's signature on the grant. A forged receipt for a signing upstream fails its `upstream` checks. | evidence, where the upstream signs; otherwise the operator's word |
56
+ | Act outside the gateway with the provider's own credentials | Nothing on the gateway's side sees it. `agent-custody completeness` lists the provider's objects with the auditor's own read-only key and reports each one that no verified receipt names; a forged receipt file fails verification and cannot cover for it. | evidence, for a provider that lists its objects (Stripe today) |
56
57
  | Replace the policy and claim a different one decided | The receipt carries the sha256 of the policy text; a verifier with the policy file can check it, and a policy change is a different digest in every later receipt. | evidence |
57
58
  | Produce a second, cleaner history | With a remote log, both histories would need heads signed by the log's key at the same size with different roots; the checkpoints host and the witness make that detectable. With a local log, a copy taken earlier by someone else is the only defence. | evidence with a witnessed remote log |
58
59
  | Erase what an agent believed | `forget` erases the value and leaves a digest keyed by a forget key held outside the ledger, so the erasure is provable without the value. A forget with `none` leaves nothing and the custody pack says so. | evidence |
package/docs/tutorials.md CHANGED
@@ -44,6 +44,9 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
44
44
  | 32 | the gateway console | [32-console.ts](../examples/32-console.ts) | a gateway that has made two receipts, and its operator's console: a token on every route, the receipts with a verdict each, a stricter policy replayed against the recorded calls before it is saved, the save recorded with the old version kept and a stale edit refused, and a grant inspected, revoked, and then refused by the gateway | `src/console.ts`, `src/console-page.ts` |
45
45
  | 33 | anchoring the log on a chain | [33-chain-anchor.ts](../examples/33-chain-anchor.ts) | a log publishes a checkpoint, the anchor commits it to a stand-in chain in one transaction, and `log-check` passes against the chain; the operator swaps in a rewritten log under the same key and log id, and `log-check` fails it from the chain alone |
46
46
  | 34 | strict mode | [34-strict-mode.ts](../examples/34-strict-mode.ts) | `check` lists what strict mode would refuse; a local log and a log that is not hash-only are refused at startup; behind a hash-only log with a pinned key, a read is precommitted and its receipt says `issuer.strict`; `requireStrict` accepts it and refuses an ordinary receipt; with the log down the call is not forwarded and the outbox stays empty | `src/config.ts`, `src/gateway.ts`, `src/check.ts`, `src/verify.ts` |
47
+ | 35 | completeness from the provider's side | [35-completeness.ts](../examples/35-completeness.ts) | two refunds through the gateway and a third issued straight through the provider; the auditor lists the provider's refunds with a read-only key, matches two to verified receipts, and reports the third as an action with no receipt |
48
+ | 36 | one command for Claude Code | [36-claude-code-init.ts](../examples/36-claude-code-init.ts) | `init claude-code` in a temporary home: the key, the observe-mode config, the starter policy, and the three hooks; a second run adds nothing; a session of four calls; the report that lists the two calls the policy would have denied | `src/claude-init.ts`, `src/deny-report.ts` |
49
+ | 38 | an incident replay | [38-incident-replay.ts](../examples/38-incident-replay.ts) | the same setup as `init claude-code --enforce`, in a temporary home; a scripted Claude Code session that runs the real hook command for each event: `terraform plan` runs and gets an executed receipt, `terraform destroy -auto-approve` and `rm -rf ~` are denied before they run, with the denial text and the receipt id; a reviewer with only the public key verifies all three receipts, and a stranger's key fails | `src/sdk/claude.ts`, `src/claude-init.ts`, `templates/claude-code.cedar` |
47
50
 
48
51
  ## How policies are defined, in one paragraph
49
52
 
@@ -55,6 +58,7 @@ A policy is a Cedar file. The gateway turns each tool call into a Cedar request:
55
58
  - [codex-recovery.md](codex-recovery.md): the opt-in live Codex support incident, operator-reviewed recovery, and its offline state example
56
59
  - [approvals.md](approvals.md): exact-action signatures, two-person thresholds, consumption, and privacy limits
57
60
  - [console.md](console.md): the admin console: run it, what each tab does, how it is protected, and its limits
61
+ - [completeness.md](completeness.md): matching the provider's own records against verified receipts, to find actions taken outside the gateway
58
62
  - [anchoring.md](anchoring.md): the log's checkpoints on Ethereum: what an anchor proves, running it, and checking a log against the chain
59
63
  - [financial-operations.md](financial-operations.md): payment retries, budget reservations, provider contract, and operator reconciliation
60
64
  - [sdk.md](sdk.md): the interceptor and every adapter
package/docs/usage.md CHANGED
@@ -123,7 +123,7 @@ At startup the gateway fetches the agent's card from `<url>/.well-known/agent-ca
123
123
  "log": { "url": "https://log.example.com/", "tokenEnv": "AGENT_CUSTODY_LOG_TOKEN" }
124
124
  ```
125
125
 
126
- Exactly one of the two. The bearer token comes from the named environment variable, never from the file, and a missing variable fails at startup. Add `"hashOnly": true` for any log run by someone else: the gateway then sends only the leaf hash, sha256 of the receipt envelope with the RFC 6962 prefix, so the log commits to the receipt without ever holding it, and the receipts with their arguments and results stay in `receiptsDir`. The verifier does not change; it hashes the envelope itself. A log that serves several tenants is reached at `<url>/t/<tenant>/`, and each of its tree heads names its log, which a verifier checks with `--log-id`. With a remote log the tree head in each receipt is signed by the log's key, and a verifier must be given that key with `--log-key`. The gateway does not take the log's answer on trust either: the tree head in every append's answer must verify against the log's keys, name the expected log, match the proof's size, and the inclusion proof must place that very leaf under the signed root, all before a pre-committed call is forwarded and before any receipt is handed out; an answer that fails any of it is a refusal. `"keys": ["keys/log.pub"]` pins the log's public keys, `"logId"` the id its heads must carry; without `keys` the log's key document at `/.well-known/agent-custody-log.json` is fetched from the log itself once, on the first append, and pinned. That catches a log that turns dishonest later, not one that is dishonest from the start, so a gateway config with `precommit` and a remote log must list `keys`. When the log rotates its key, add the new public key to `keys`; a gateway that fetched the keys needs a restart. An append that gets no answer within `timeoutMs` (default 10000) counts as unreachable and is retried like a server error, so a log that accepts connections and never answers cannot hold a call forever. If the log does not take a receipt, the gateway keeps the signed receipt in `receipts/outbox/<receiptId>.json` and returns the real outcome of the call to the agent, with the receipt id and `_meta["agent-custody/log-pending"]: true`. The gateway appends the outbox at startup and every 30 seconds, and writes `receipts/<receiptId>.json` when the log takes the receipt. Until then no bundle exists, so no receipt that was never logged is handed out. The table [below](#when-the-log-fails) gives each case. For a tool named in `precommit` the order is reversed, below, and the action never happens. A fact lookup is different: it runs before the policy decides, because the policy decides on it, and only once the intercepted tool is in the grant's scope, so a fact tool must be a read. Naming a fact tool in `precommit` is refused at startup; `"*"` covers the tools the agent calls, not the gateway's own lookups. Every lookup is on the receipt with its arguments. The reference log server is `node src/cli.ts log --file log.jsonl --key keys/log.key --port 8787 --token-env AGENT_CUSTODY_LOG_TOKEN [--log-id <id>] [--tenants tenants.json]`. It serves `POST /append` with `{leaf}` or `{leafHash}` (token required when one is configured), `GET /root?size=N`, `GET /consistency?old=M&new=N`, and `GET /head`; [verification.md](verification.md) says what each proves. `--log-id` writes that id into every tree head. `--tenants` names a JSON file, `{ "acme": { "file": "acme.jsonl", "tokenEnv": "ACME_TOKEN", "logId": "acme-eu" } }`, and each tenant is its own log at `/t/acme/…` with its own token and id; the default log stays at the root paths. With `--hash-only` the server refuses `{leaf}` at append and accepts only `{leafHash}`, so a log run for other people never receives a receipt regardless of the client's configuration; the hosted deployment sets it. With `--db-env DATABASE_URL` the server keeps its logs in Postgres instead of files, and needs the `pg` package beside it: leaves as hashes in one table keyed by tenant, one writer per tenant enforced with an advisory lock so a second instance is safe, tenants and their tokens in tables of their own with tokens stored only as hashes, and rate limits per token (50 appends a second, burst 100, a 64 KB body cap; a refused append answers 429 with `retry-after`, and the gateway's sink retries a few times). Tenants are managed with `log-admin --db-env DATABASE_URL`: `tenant add <id> [--log-id <id>]`, `token add <tenant> --label <text>` (the token is printed once), `token revoke <tenant> <hash-prefix>`, `tenant disable <id>`, `tenant plan <id> <free|team|enterprise>`, and `import --file log.jsonl [--tenant default]` to bring an existing file log in as hashes. Every tenant is on a plan, `free` unless moved: free allows ten thousand appends a calendar month, team a million, enterprise has no allowance. An append past the allowance is refused with 429, the numbers, and a `retry-after` that reaches the start of next month; the gateway behind it then withholds pre-committed calls, so a tenant out of quota never acts without evidence. The tenant's own `GET /t/<name>/usage` reports the plan and quota beside the month's appends. The tenant portal, `agent-custody portal --db-env DATABASE_URL --secret-env PORTAL_SECRET --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]`, is the self-serve front of the same tables: a team registers with an email, a password (scrypt), and a tenant id and gets the tenant and its first key shown once with the welcome sheet; the dashboard shows appends against the plan, the tree size and root, the latest checkpoint, the log's URLs, keys, and the audit rows; keys are minted and revoked there, recorded as `portal:<email>`; the export command is on the page; and with the three Stripe variables the team plan is bought through Stripe Checkout, the signed webhook moving the plan (`stripe:<event>` in the audit trail) and the customer portal handling cancellation. Sessions are a signed cookie, `SameSite=Strict`, and every write needs a JSON body. Each member has a role (`owner`, `admin`, `reviewer`, `readonly`), an account can turn on TOTP MFA, and the operator can set up single sign-on through the tenant's own OIDC or SAML identity provider with `log-admin sso set`; the [hosted log reference](https://docs.agent-custody.dev/reference/hosted) lists the routes. SAML needs `@node-saml/node-saml` beside the CLI. The compose file runs it as the `portal` service at `PORTAL_HOST`. The root paths serve the tenant `default`, created on first start with `--log-id`, and `--token-env` still works for it. The key that signs tree heads can live in its own process: `agent-custody signer --key keys/log.key --port 8790 --token-env SIGNER_TOKEN` holds it and answers `POST /sign` with the shared secret and `GET /keys` to anyone; the log server then runs with `--signer-url http://signer:8790/ --signer-token-env SIGNER_TOKEN` instead of `--key`, and the process that faces the internet never holds the key. Either way the log serves its keys at `/.well-known/agent-custody-log.json`, current key first and retired keys (`--retired-key old.pub`) after it, so verifiers fetch and pin them with `verify --log-url` and `audit --log-url` rather than receiving a key file from the operator. With `--checkpoint-dir <dir>` the server publishes a signed checkpoint, every `--checkpoint-every` seconds (default 300), for each log whose tree has grown, and every `--checkpoint-heartbeat` seconds (default 21600, six hours) for a log that has not, so a quiet log's latest checkpoint is never more than six hours old and the monitor can tell quiet from stalled, as `<dir>/<tenant>/<treeSize>.json` and `latest.json`, and with a database also as rows; `GET /checkpoints?since=<size>` and `GET /t/<tenant>/checkpoints` list them. Serve the directory read-only from a second host, so the record of what the log signed does not depend on the log's API being up; a verifier who kept an earlier head audits against a later checkpoint with `audit --older <bundle> --newer <checkpoint> --log-url <url>`. With `--admin-token-env ADMIN_TOKEN` (Postgres only) the server also serves the operator's page at `/admin` and its API under `/admin/`: list and create tenants, mint a token that is shown once beside the tenant's welcome sheet, revoke tokens, disable tenants. Everything under `/admin`, the page included, needs the admin token: the browser asks for it (any user name, the token as the password) and an API client sends it as a bearer; a handful of wrong attempts from one address are throttled for a minute. Every change made there or with `log-admin` is recorded: who (the name entered at the browser prompt and the address, `bearer` for an API client, or the user and host for the command line), what (`tenant.add`, `tenant.disable`, `token.add`, `token.revoke`), which tenant, and the detail, never the token itself; the page shows it under Activity, `GET /admin/audit?tenant=&limit=` and `log-admin audit` list it, and a tenant reads their own rows at `GET /t/<name>/audit` with their token. Nothing else is stored by the page. Behind a reverse proxy, start the server with `--trust-proxy` so those per-address limits key on `X-Forwarded-For` instead of on the proxy's own address, and only there, since the header is otherwise the client's to forge. `--public-url` and `--checkpoints-url` fill the sheet in. The witness closes the last gap: `agent-custody witness --key witness.key --log-url <url> --checkpoints-url <url> --out <dir> [--tenant <name>]...` runs on a machine the log's operator does not control, fetches each watched log's latest checkpoint, verifies it against the log's published keys, proves with the log's consistency proof that it extends the last head the witness signed, and countersigns it into `<dir>/<tenant>/<size>.json` and `latest.json`; a checkpoint that does not extend, or a second history at the same size, gets `ALARM.json` instead. Its key document is `<dir>/.well-known/agent-custody-witness.json`. Serve `<dir>` from the witness's own host; verifiers add `--witness-url` (or `--witness-key`) to `audit`, and the newer head must then carry the witness's signature. Two more things an operator needs. `agent-custody log-check --log-url <url> --checkpoints-url <url> [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]` is the outside monitor: it verifies the head against the published keys, that the latest checkpoint verifies and keeps up with the head, that the head extends the checkpoint, and, with a witness, that the witness has countersigned, keeps up, and has raised no alarm; it exits 1 on any failure, so cron or a scheduled workflow on a machine that is not the log's turns it into an alert. `GET /health` on the server is the liveness check for a load balancer. And `GET /admin/usage?month=YYYY-MM`, on the admin page and as `/admin/usage.csv`, is the metering: appends per tenant for the month, leaves in total, live tokens, the numbers any invoice rests on. A tenant needs none of that to leave with their evidence: `agent-custody log-export --log-url <url> --tenant <name> --token-env AGENT_CUSTODY_LOG_TOKEN --out <dir>` fetches, with their own token, every leaf hash (`GET /t/<name>/leaves?since=&limit=`, pages of up to ten thousand), the signed head, the published keys, the signed checkpoints, their own usage (`GET /t/<name>/usage?month=`), and the administrative actions on their tenant (`GET /t/<name>/audit`, into `audit.json`), checks that the head and every checkpoint verify against the keys and that the leaves fetched hash to their roots, and writes `log.jsonl` in the format `verify --log` and `audit --log` read, so the export verifies receipts with no server at all. It exits 1 and says what did not add up if anything does not. Both routes answer only to that tenant's token. [deploy/](../../deploy/README.md) runs the server, the signer, Postgres, and the checkpoints host as containers, and [deploy/witness/](../../deploy/witness/) the witness.
126
+ Exactly one of the two. The bearer token comes from the named environment variable, never from the file, and a missing variable fails at startup. Add `"hashOnly": true` for any log run by someone else: the gateway then sends only the leaf hash, sha256 of the receipt envelope with the RFC 6962 prefix, so the log commits to the receipt without ever holding it, and the receipts with their arguments and results stay in `receiptsDir`. The verifier does not change; it hashes the envelope itself. A log that serves several tenants is reached at `<url>/t/<tenant>/`, and each of its tree heads names its log, which a verifier checks with `--log-id`. With a remote log the tree head in each receipt is signed by the log's key, and a verifier must be given that key with `--log-key`. The gateway does not take the log's answer on trust either: the tree head in every append's answer must verify against the log's keys, name the expected log, match the proof's size, and the inclusion proof must place that very leaf under the signed root, all before a pre-committed call is forwarded and before any receipt is handed out; an answer that fails any of it is a refusal. `"keys": ["keys/log.pub"]` pins the log's public keys, `"logId"` the id its heads must carry; without `keys` the log's key document at `/.well-known/agent-custody-log.json` is fetched from the log itself once, on the first append, and pinned. That catches a log that turns dishonest later, not one that is dishonest from the start, so a gateway config with `precommit` and a remote log must list `keys`. When the log rotates its key, add the new public key to `keys`; a gateway that fetched the keys needs a restart. An append that gets no answer within `timeoutMs` (default 10000) counts as unreachable and is retried like a server error, so a log that accepts connections and never answers cannot hold a call forever. If the log does not take a receipt, the gateway keeps the signed receipt in `receipts/outbox/<receiptId>.json` and returns the real outcome of the call to the agent, with the receipt id and `_meta["agent-custody/log-pending"]: true`. The gateway appends the outbox at startup and every 30 seconds, and writes `receipts/<receiptId>.json` when the log takes the receipt. Until then no bundle exists, so no receipt that was never logged is handed out. The table [below](#when-the-log-fails) gives each case. For a tool named in `precommit` the order is reversed, below, and the action never happens. A fact lookup is different: it runs before the policy decides, because the policy decides on it, and only once the intercepted tool is in the grant's scope, so a fact tool must be a read. Naming a fact tool in `precommit` is refused at startup; `"*"` covers the tools the agent calls, not the gateway's own lookups. Every lookup is on the receipt with its arguments. The reference log server is `node src/cli.ts log --file log.jsonl --key keys/log.key --port 8787 --token-env AGENT_CUSTODY_LOG_TOKEN [--log-id <id>] [--tenants tenants.json]`. It serves `POST /append` with `{leaf}` or `{leafHash}` (token required when one is configured), `GET /root?size=N`, `GET /consistency?old=M&new=N`, and `GET /head`; [verification.md](verification.md) says what each proves. `--log-id` writes that id into every tree head. `--tenants` names a JSON file, `{ "acme": { "file": "acme.jsonl", "tokenEnv": "ACME_TOKEN", "logId": "acme-eu" } }`, and each tenant is its own log at `/t/acme/…` with its own token and id; the default log stays at the root paths. With `--hash-only` the server refuses `{leaf}` at append and accepts only `{leafHash}`, so a log run for other people never receives a receipt regardless of the client's configuration; the hosted deployment sets it. With `--db-env DATABASE_URL` the server keeps its logs in Postgres instead of files, and needs the `pg` package beside it: leaves as hashes in one table keyed by tenant, one writer per tenant enforced with an advisory lock so a second instance is safe, tenants and their tokens in tables of their own with tokens stored only as hashes, and rate limits per token (50 appends a second, burst 100, a 64 KB body cap; a refused append answers 429 with `retry-after`, and the gateway's sink retries a few times). Tenants are managed with `log-admin --db-env DATABASE_URL`: `tenant add <id> [--log-id <id>]`, `token add <tenant> --label <text>` (the token is printed once), `token revoke <tenant> <hash-prefix>`, `tenant disable <id>`, `tenant plan <id> <free|team|enterprise>`, and `import --file log.jsonl [--tenant default]` to bring an existing file log in as hashes. Every tenant is on a plan, `free` unless moved: free allows ten thousand appends a calendar month, team a million, enterprise has no allowance. An append past the allowance is refused with 429, the numbers, and a `retry-after` that reaches the start of next month; the gateway behind it then withholds pre-committed calls and financial operations, so a tenant out of quota never acts on those without evidence. Any other call is forwarded, and its receipt waits in the outbox ([below](#when-the-log-fails)). The tenant's own `GET /t/<name>/usage` reports the plan and quota beside the month's appends. The tenant portal, `agent-custody portal --db-env DATABASE_URL --secret-env PORTAL_SECRET --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]`, is the self-serve front of the same tables: a team registers with an email, a password (scrypt), and a tenant id and gets the tenant and its first key shown once with the welcome sheet; the dashboard shows appends against the plan, the tree size and root, the latest checkpoint, the log's URLs, keys, and the audit rows; keys are minted and revoked there, recorded as `portal:<email>`; the export command is on the page; and with the three Stripe variables the team plan is bought through Stripe Checkout, the signed webhook moving the plan (`stripe:<event>` in the audit trail) and the customer portal handling cancellation. Sessions are a signed cookie, `SameSite=Strict`, and every write needs a JSON body. Each member has a role (`owner`, `admin`, `reviewer`, `readonly`), an account can turn on TOTP MFA, and the operator can set up single sign-on through the tenant's own OIDC or SAML identity provider with `log-admin sso set`; the [hosted log reference](https://docs.agent-custody.dev/reference/hosted) lists the routes. SAML needs `@node-saml/node-saml` beside the CLI. The compose file runs it as the `portal` service at `PORTAL_HOST`. The root paths serve the tenant `default`, created on first start with `--log-id`, and `--token-env` still works for it. The key that signs tree heads can live in its own process: `agent-custody signer --key keys/log.key --port 8790 --token-env SIGNER_TOKEN` holds it and answers `POST /sign` with the shared secret and `GET /keys` to anyone; the log server then runs with `--signer-url http://signer:8790/ --signer-token-env SIGNER_TOKEN` instead of `--key`, and the process that faces the internet never holds the key. Either way the log serves its keys at `/.well-known/agent-custody-log.json`, current key first and retired keys (`--retired-key old.pub`) after it, so verifiers fetch and pin them with `verify --log-url` and `audit --log-url` rather than receiving a key file from the operator. With `--checkpoint-dir <dir>` the server publishes a signed checkpoint, every `--checkpoint-every` seconds (default 300), for each log whose tree has grown, and every `--checkpoint-heartbeat` seconds (default 21600, six hours) for a log that has not, so a quiet log's latest checkpoint is never more than six hours old and the monitor can tell quiet from stalled, as `<dir>/<tenant>/<treeSize>.json` and `latest.json`, and with a database also as rows; `GET /checkpoints?since=<size>` and `GET /t/<tenant>/checkpoints` list them. Serve the directory read-only from a second host, so the record of what the log signed does not depend on the log's API being up; a verifier who kept an earlier head audits against a later checkpoint with `audit --older <bundle> --newer <checkpoint> --log-url <url>`. With `--admin-token-env ADMIN_TOKEN` (Postgres only) the server also serves the operator's page at `/admin` and its API under `/admin/`: list and create tenants, mint a token that is shown once beside the tenant's welcome sheet, revoke tokens, disable tenants. Everything under `/admin`, the page included, needs the admin token: the browser asks for it (any user name, the token as the password) and an API client sends it as a bearer; a handful of wrong attempts from one address are throttled for a minute. Every change made there or with `log-admin` is recorded: who (the name entered at the browser prompt and the address, `bearer` for an API client, or the user and host for the command line), what (`tenant.add`, `tenant.disable`, `token.add`, `token.revoke`), which tenant, and the detail, never the token itself; the page shows it under Activity, `GET /admin/audit?tenant=&limit=` and `log-admin audit` list it, and a tenant reads their own rows at `GET /t/<name>/audit` with their token. Nothing else is stored by the page. Behind a reverse proxy, start the server with `--trust-proxy` so those per-address limits key on `X-Forwarded-For` instead of on the proxy's own address, and only there, since the header is otherwise the client's to forge. `--public-url` and `--checkpoints-url` fill the sheet in. The witness closes the last gap: `agent-custody witness --key witness.key --log-url <url> --checkpoints-url <url> --out <dir> [--tenant <name>]...` runs on a machine the log's operator does not control, fetches each watched log's latest checkpoint, verifies it against the log's published keys, proves with the log's consistency proof that it extends the last head the witness signed, and countersigns it into `<dir>/<tenant>/<size>.json` and `latest.json`; a checkpoint that does not extend, or a second history at the same size, gets `ALARM.json` instead. Its key document is `<dir>/.well-known/agent-custody-witness.json`. Serve `<dir>` from the witness's own host; verifiers add `--witness-url` (or `--witness-key`) to `audit`, and the newer head must then carry the witness's signature. Two more things an operator needs. `agent-custody log-check --log-url <url> --checkpoints-url <url> [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]` is the outside monitor: it verifies the head against the published keys, that the latest checkpoint verifies and keeps up with the head, that the head extends the checkpoint, and, with a witness, that the witness has countersigned, keeps up, and has raised no alarm; it exits 1 on any failure, so cron or a scheduled workflow on a machine that is not the log's turns it into an alert. `GET /health` on the server is the liveness check for a load balancer. And `GET /admin/usage?month=YYYY-MM`, on the admin page and as `/admin/usage.csv`, is the metering: appends per tenant for the month, leaves in total, live tokens, the numbers any invoice rests on. A tenant needs none of that to leave with their evidence: `agent-custody log-export --log-url <url> --tenant <name> --token-env AGENT_CUSTODY_LOG_TOKEN --out <dir>` fetches, with their own token, every leaf hash (`GET /t/<name>/leaves?since=&limit=`, pages of up to ten thousand), the signed head, the published keys, the signed checkpoints, their own usage (`GET /t/<name>/usage?month=`), and the administrative actions on their tenant (`GET /t/<name>/audit`, into `audit.json`), checks that the head and every checkpoint verify against the keys and that the leaves fetched hash to their roots, and writes `log.jsonl` in the format `verify --log` and `audit --log` read, so the export verifies receipts with no server at all. It exits 1 and says what did not add up if anything does not. Both routes answer only to that tenant's token. [deploy/](../../deploy/README.md) runs the server, the signer, Postgres, and the checkpoints host as containers, and [deploy/witness/](../../deploy/witness/) the witness.
127
127
 
128
128
  `otel`, optional in both the gateway and SDK configs, sends every receipt to the collector you already run as one span over OTLP/HTTP, after the receipt is issued: `"otel": { "url": "http://localhost:4318", "headersEnv": { "x-api-key": "OTEL_KEY" }, "serviceName": "support-agents" }`. The span's trace id is the receipt id, its attributes carry the tool, agent, principal, execution status, policy decision, and log position, and its status is an error only when the upstream failed or errored, since a denial is the policy working. Export is best effort: a collector that is down or refuses costs a line on stderr, never a receipt. Tutorial 18 shows it against a stand-in collector.
129
129
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "mcpName": "io.github.svayatta/agent-custody",
5
5
  "description": "Chain of custody for AI agents: signed, independently verifiable receipts for tool calls. MCP gateway + Cedar policy + Merkle transparency log",
6
6
  "license": "Apache-2.0",
@@ -57,6 +57,7 @@
57
57
  "files": [
58
58
  "dist",
59
59
  "docs",
60
+ "templates",
60
61
  "vectors"
61
62
  ],
62
63
  "scripts": {
@@ -70,7 +71,7 @@
70
71
  "node": ">=22"
71
72
  },
72
73
  "dependencies": {
73
- "@cedar-policy/cedar-wasm": "^4.12.0",
74
+ "@cedar-policy/cedar-wasm": "4.12.0",
74
75
  "@modelcontextprotocol/sdk": "^1.30.0",
75
76
  "zod": "^4.5.4"
76
77
  },
@@ -0,0 +1,96 @@
1
+ // Starter policy for `agent-custody init claude-code`.
2
+ // The policy permits every call and forbids a short list of destructive Bash commands.
3
+ // A pattern matches the text of the command. It is not a sandbox: it catches the plain form of each command.
4
+ // Each rule has a `@reason`. The hook shows it to the agent and to the person who reads the session.
5
+ // The `like` operator is case-sensitive, and `*` is its only wildcard, so each SQL keyword has a rule for each case.
6
+ permit(principal, action, resource);
7
+
8
+ // Rewriting shared history.
9
+ // `--force-with-lease` is a force push that fails when the remote has new commits. The policy allows it.
10
+ // A `--force` flag matches anywhere after `git push`. A `-f` flag matches right after `git push` or at the end of the
11
+ // command. A `-f` in the middle of a command is not matched, because `git push origin main && rm -f x` must pass.
12
+ @reason("force push rewrites shared history (git push --force-with-lease is allowed)")
13
+ forbid(principal, action == Action::"Bash", resource)
14
+ when {
15
+ context.args has command && (
16
+ context.args.command like "*git push*--force *"
17
+ || context.args.command like "*git push*--force"
18
+ || context.args.command like "*git push -f*"
19
+ || context.args.command like "*git push* -f"
20
+ )
21
+ };
22
+
23
+ // Deleting the root directory or the home directory.
24
+ @reason("rm -rf on the root directory")
25
+ forbid(principal, action == Action::"Bash", resource)
26
+ when {
27
+ context.args has command && (
28
+ context.args.command like "*rm -rf /"
29
+ || context.args.command like "*rm -rf / *"
30
+ || context.args.command like "*rm -rf /\*"
31
+ || context.args.command like "*rm -fr /"
32
+ || context.args.command like "*rm -fr / *"
33
+ || context.args.command like "*rm -fr /\*"
34
+ )
35
+ };
36
+
37
+ @reason("rm -rf on the home directory")
38
+ forbid(principal, action == Action::"Bash", resource)
39
+ when {
40
+ context.args has command && (
41
+ context.args.command like "*rm -rf ~"
42
+ || context.args.command like "*rm -rf ~ *"
43
+ || context.args.command like "*rm -rf ~/"
44
+ || context.args.command like "*rm -rf ~/ *"
45
+ || context.args.command like "*rm -rf ~/\*"
46
+ || context.args.command like "*rm -fr ~"
47
+ || context.args.command like "*rm -fr ~ *"
48
+ || context.args.command like "*rm -fr ~/"
49
+ || context.args.command like "*rm -fr ~/ *"
50
+ || context.args.command like "*rm -fr ~/\*"
51
+ )
52
+ };
53
+
54
+ @reason("rm -rf on the home directory")
55
+ forbid(principal, action == Action::"Bash", resource)
56
+ when {
57
+ context.args has command && (
58
+ context.args.command like "*rm -rf $HOME"
59
+ || context.args.command like "*rm -rf $HOME *"
60
+ || context.args.command like "*rm -rf $HOME/"
61
+ || context.args.command like "*rm -rf $HOME/ *"
62
+ || context.args.command like "*rm -rf $HOME/\*"
63
+ || context.args.command like "*rm -fr $HOME"
64
+ || context.args.command like "*rm -fr $HOME *"
65
+ || context.args.command like "*rm -fr $HOME/"
66
+ || context.args.command like "*rm -fr $HOME/ *"
67
+ || context.args.command like "*rm -fr $HOME/\*"
68
+ || context.args.command like "*rm -rf ${HOME}"
69
+ || context.args.command like "*rm -rf ${HOME} *"
70
+ || context.args.command like "*rm -rf ${HOME}/"
71
+ || context.args.command like "*rm -rf ${HOME}/ *"
72
+ || context.args.command like "*rm -rf ${HOME}/\*"
73
+ || context.args.command like "*rm -fr ${HOME}"
74
+ || context.args.command like "*rm -fr ${HOME} *"
75
+ || context.args.command like "*rm -fr ${HOME}/"
76
+ || context.args.command like "*rm -fr ${HOME}/ *"
77
+ || context.args.command like "*rm -fr ${HOME}/\*"
78
+ )
79
+ };
80
+
81
+ // Destroying infrastructure or a database.
82
+ @reason("terraform destroy deletes infrastructure")
83
+ forbid(principal, action == Action::"Bash", resource)
84
+ when { context.args has command && context.args.command like "*terraform destroy*" };
85
+
86
+ @reason("terraform apply -destroy deletes infrastructure")
87
+ forbid(principal, action == Action::"Bash", resource)
88
+ when { context.args has command && context.args.command like "*terraform apply* -destroy*" };
89
+
90
+ @reason("drop database deletes a database")
91
+ forbid(principal, action == Action::"Bash", resource)
92
+ when { context.args has command && context.args.command like "*drop database*" };
93
+
94
+ @reason("drop database deletes a database")
95
+ forbid(principal, action == Action::"Bash", resource)
96
+ when { context.args has command && context.args.command like "*DROP DATABASE*" };