@agent-custody/receipts 0.16.1 → 0.16.3

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 CHANGED
@@ -36,6 +36,7 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
36
36
  - [Completeness](docs/completeness.md): an auditor's read-only key lists the provider's objects and matches each to a verified receipt, so an action taken outside the gateway shows up
37
37
  - [Payment mandates and agent identity](docs/mandates.md): the design for fitting grants and receipts to Google's AP2 mandates, Visa's Trusted Agent Protocol and Mastercard Agent Pay; not yet built
38
38
  - [Threat model](docs/threat-model.md): every party who could make a receipt false, the move, what stops it, and whether that is a property of the evidence or of the deployment; and what is not defended
39
+ - [What a receipt costs](docs/performance.md): each step of the issuer's hot path in microseconds, measured with `bun run bench`, what is and is not fsynced, and where the time goes
39
40
  - [Aligning with IETF SCITT](docs/scitt.md): the receipt as a SCITT signed statement, the log as a transparency service, our RFC 9162 proofs as COSE Receipts (RFC 9942), what differs and the options for each, an agent-action profile, and the steps toward the working group
40
41
 
41
42
  ## Getting started
@@ -307,11 +308,11 @@ src/cli.ts keygen, grant, gateway, door, egress, egress draft-policy, ac
307
308
  src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
308
309
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
309
310
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
310
- scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway, SDK, door (with a stand-in origin), and the egress witness (with a stand-in destination), the replay builder (`replay.ts`: example 27 and state example 07 as a folder of receipts and public keys anyone can verify with the published packages), demo
311
+ scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway, SDK, door (with a stand-in origin), and the egress witness (with a stand-in destination), the replay builder (`replay.ts`: example 27 and state example 07 as a folder of receipts and public keys anyone can verify with the published packages), demo, the site's numbers (`bench.ts`), and the per-step hot-path benchmark (`hot-path-bench.ts`, `bun run bench`)
311
312
  examples/ runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
312
313
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
313
314
  adapter tests against the real packages, and tests that run every policy in docs/policies.md and site/guide/egress-policies.md
314
- docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification
315
+ docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification, performance
315
316
  ```
316
317
 
317
318
  ## Plan
@@ -320,6 +321,7 @@ The design is several producers feeding one verifier. The SDK is the top of the
320
321
 
321
322
  **Done**
322
323
 
324
+ - A cheaper receipt hot path: a Cedar policy is parsed once per text instead of on every decision (a few slots, evicted oldest first), and the local log keeps one descriptor open for its appends, reopened when a prune replaces the file. The log lock reads its owner's start time once per process instead of running `ps` on every append on macOS. The receipt format, the decisions, and what is fsynced are unchanged. `bun run bench` times each step, Cedar and Rego both; [docs/performance.md](docs/performance.md) has the numbers.
323
325
  - The egress witness decides by Rego as well as Cedar: a `policyFile` ending in `.rego` is compiled with `opa build` as the gateway compiles one, the input is the Cedar request with plain strings, and a file that does not compile is not loaded. An OPA server is not supported for egress yet ([the egress witness](docs/egress.md#the-same-policy-in-rego), tutorial 44).
324
326
  - Drafting an egress policy: `agent-custody egress draft-policy --receipts <dir> --issuer-key <witness.pub>` verifies each egress receipt, keeps the connections the witness relayed for a verified agent, and prints one `permit` per agent and scheme over the `host:port` destinations it used, sorted, with a count and the first and last time seen for each. The output starts with a warning that it permits whatever the agents did, bad destinations included. [Writing egress policies](../../site/guide/egress-policies.md) is the guide, and its examples are tested; tutorial [42-egress-draft.ts](examples/42-egress-draft.ts).
325
327
  - An OWASP Agent Control Standard Guardian, as a spike: `agent-custody acs` answers `steps/toolCallRequest` and `steps/toolCallResult` with the Cedar policy's allow or deny, and every decision is a receipt with the new issuer kind `guardian`, signed with the Guardian's key and logged, which ACS's HMAC baseline cannot attribute (ACS §8.6). It publishes the ACS chain head, and its receipts in a log someone else runs answer two of the three directions in ACS issue #18 (a signed checkpoint of `chain_hash`, and signed heads in an external append-only log; Guardians exchanging heads is not done). Handshake, ACS signatures, the other hooks, modify/ask/defer, and provenance are not implemented; [the list](docs/acs.md#what-it-does-not-implement). Example 43.
@@ -361,7 +363,7 @@ The design is several producers feeding one verifier. The SDK is the top of the
361
363
  - The signer, keys, and checkpoints: the key in its own process (`signer`, `--signer-url`), the key document at `/.well-known/agent-custody-log.json` fetched and pinned by `verify --log-url` and `audit --log-url`, and signed checkpoints per log published to a directory and a table for a verifier who was not watching. Phase 3 of [issue #6](https://github.com/svayatta/agent-custody/issues/6).
362
364
  - The log over Postgres: `log --db-env`, leaves as hashes in one table keyed by tenant, one writer per tenant by advisory lock, tenants and hashed tokens in tables managed by `log-admin`, rate limits and a body cap, retries in the sink, and `import` for an existing file log. Phase 2 of [issue #6](https://github.com/svayatta/agent-custody/issues/6).
363
365
  - A log for someone else: `hashOnly` sends leaf hashes so the log never holds a receipt; the reference server runs several tenant logs at `/t/<tenant>/` with their own tokens and ids; tree heads name their log and the verifier checks it with `--log-id`. Phase 1 of the hosted log, [issue #6](https://github.com/svayatta/agent-custody/issues/6).
364
- - OpenTelemetry export: with `otel` in either config, every receipt is also one span at the collector the team already runs, trace id equal to the receipt id, attributes for tool, agent, principal, status, decision, and log position; after the receipt, best effort, never on the evidence path. A reconciliation receipt is marked and carries no policy decision, so a dashboard never counts it as a second allowed call.
366
+ - OpenTelemetry export: with `otel` in either config, every receipt is also one span at the collector the team already runs, trace id equal to the receipt id, attributes for tool, agent, principal, status, decision, and log position; after the receipt, best effort, never on the evidence path. A door receipt is a `SERVER` span, since it records an inbound request, and every other receipt is a `CLIENT` span. A reconciliation receipt is marked and carries no policy decision, so a dashboard never counts it as a second allowed call.
365
367
  - Delegation chains for sub-agents: a grant that names the agent's key lets it delegate a narrower grant, with the parent embedded, up to three deep; the verifier and the gateway walk the chain to the principal, refusing any link that escalates scope, widens the window, changes the principal, or is signed by the wrong key; the receipt names the sub-agent and the principal and carries the chain. Pinned by the `gateway-chain-*` vectors and mirrored in the browser verifier.
366
368
  - One gateway for many agents: `gateway --http` serves the gateway over Streamable HTTP, one session per connection under the grant that connection presents, sessions sharing the upstreams and the policy and nothing else; a platform team runs one gateway in front of the tools instead of one process per agent.
367
369
  - Splunk export: with `splunk` in either config, every receipt is also one event at the HTTP Event Collector, with the receipt id, tool, agent, principal, status, decision, and log position as searchable fields and the token from the environment; the same best-effort rule.
package/dist/check.d.ts CHANGED
@@ -25,5 +25,9 @@ export declare function isDoorConfig(configPath: string): boolean;
25
25
  export declare function permitsNamingAgentWithoutVerifiedArrival(policyText: string): string[];
26
26
  /** `agent-custody check` on a door config: what the door would fail on at startup, and what it would silently do less than the config seems to promise. */
27
27
  export declare function checkDoorConfig(configPath: string): CheckFinding[];
28
+ /** True when the file is an egress witness config: it names agents, and no upstream or origin. */
29
+ export declare function isEgressConfig(configPath: string): boolean;
30
+ /** `agent-custody check` on an egress witness config: what the witness would fail on at startup. */
31
+ export declare function checkEgressConfig(configPath: string): CheckFinding[];
28
32
  export declare function checkConfig(configPath: string, options?: CheckOptions): Promise<CheckFinding[]>;
29
33
  export declare function formatFindings(findings: CheckFinding[]): string;
package/dist/check.js CHANGED
@@ -6,7 +6,7 @@ import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
6
6
  import { accessSync, constants, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
9
- import { DoorConfigSchema, GatewayConfigSchema, loadConfig, loadDoorConfig, strictRefusals } from "./config.js";
9
+ import { DoorConfigSchema, EgressConfigSchema, GatewayConfigSchema, loadConfig, loadDoorConfig, loadEgressConfig, ONE_LOG, strictRefusals } from "./config.js";
10
10
  import { generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
11
11
  import { delegationValidAt, verifyDelegation } from "./delegation.js";
12
12
  import { hasPermitRule } from "./policy.js";
@@ -200,6 +200,98 @@ export function checkDoorConfig(configPath) {
200
200
  }
201
201
  return out;
202
202
  }
203
+ /** True when the file is an egress witness config: it names agents, and no upstream or origin. */
204
+ export function isEgressConfig(configPath) {
205
+ try {
206
+ const raw = JSON.parse(readFileSync(configPath, "utf8"));
207
+ return !!raw && typeof raw === "object" && !Array.isArray(raw) && "agents" in raw && !("upstream" in raw) && !("upstreams" in raw) && !("origin" in raw);
208
+ }
209
+ catch {
210
+ return false;
211
+ }
212
+ }
213
+ /** `agent-custody check` on an egress witness config: what the witness would fail on at startup. */
214
+ export function checkEgressConfig(configPath) {
215
+ const out = [];
216
+ const add = (level, check, message) => out.push({ level, check, message });
217
+ let raw;
218
+ try {
219
+ raw = JSON.parse(readFileSync(configPath, "utf8"));
220
+ }
221
+ catch (e) {
222
+ add("error", "config", `${configPath} is not readable JSON: ${e instanceof Error ? e.message : String(e)}`);
223
+ return out;
224
+ }
225
+ const known = Object.keys(EgressConfigSchema.shape);
226
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
227
+ for (const key of Object.keys(raw)) {
228
+ if (known.includes(key))
229
+ continue;
230
+ const near = known.find((k) => distance(k.toLowerCase(), key.toLowerCase()) <= 2);
231
+ add("error", "config", `unknown key "${key}" is ignored by the egress witness${near ? `; did you mean "${near}"?` : ""} A mistyped key leaves the setting it was meant for at its default`);
232
+ }
233
+ }
234
+ const parsed = EgressConfigSchema.safeParse(raw);
235
+ if (!parsed.success) {
236
+ for (const issue of parsed.error.issues)
237
+ add("error", issue.message === ONE_LOG ? "log" : "config", `${issue.path.join(".") || "(root)"}: ${issue.message}`);
238
+ return out;
239
+ }
240
+ add("ok", "config", "the config parses");
241
+ const cfg = loadEgressConfig(configPath);
242
+ add("ok", "log", cfg.logFile ? `receipts are logged to ${cfg.logFile}` : `receipts are logged to ${cfg.log.url}`);
243
+ if (!existsSync(cfg.identity.keyFile))
244
+ add("error", "key", `${cfg.identity.keyFile} does not exist, and the witness does not start without it; \`agent-custody keygen\` creates it, and the container creates it at EGRESS_KEY before it starts the witness`);
245
+ else {
246
+ try {
247
+ loadPrivateKey(cfg.identity.keyFile);
248
+ add("ok", "key", `the witness key at ${cfg.identity.keyFile} loads`);
249
+ if (process.platform !== "win32" && (statSync(cfg.identity.keyFile).mode & 0o077) !== 0)
250
+ add("warn", "key", `${cfg.identity.keyFile} is readable by other users; make it mode 0600`);
251
+ }
252
+ catch (e) {
253
+ add("error", "key", `${cfg.identity.keyFile}: ${e instanceof Error ? e.message : String(e)}`);
254
+ }
255
+ }
256
+ const unset = cfg.agents.filter((a) => !process.env[a.secretEnv]);
257
+ for (const a of unset)
258
+ add("error", "credentials", `agent ${a.id}: the secret variable ${a.secretEnv} is not set in this environment`);
259
+ if (!unset.length)
260
+ add("ok", "credentials", cfg.agents.length === 1 ? "the agent's secret variable is set" : `the secret variables of all ${cfg.agents.length} agents are set`);
261
+ if (!existsSync(cfg.policyFile))
262
+ add("error", "policy", `${cfg.policyFile} does not exist`);
263
+ else if (isRegoFile(cfg.policyFile)) {
264
+ const errors = compileRego(readFileSync(cfg.policyFile, "utf8")).errors;
265
+ for (const e of errors)
266
+ add("error", "policy", `${cfg.policyFile}: ${e}`);
267
+ if (!errors.length)
268
+ add("ok", "policy", "the Rego policy compiles");
269
+ }
270
+ else {
271
+ const text = readFileSync(cfg.policyFile, "utf8");
272
+ const r = cedar.checkParsePolicySet({ staticPolicies: text });
273
+ if (r.type !== "success")
274
+ for (const e of r.errors)
275
+ add("error", "policy", `${cfg.policyFile}: ${e.message}`);
276
+ else if (!hasPermitRule(text))
277
+ add("warn", "policy", `${cfg.policyFile} has no permit rule, so every connection is refused`);
278
+ else
279
+ add("ok", "policy", "the policy parses");
280
+ }
281
+ if (cfg.mode === "observe")
282
+ add("warn", "mode", "observe mode relays every connection from a known agent and records what the policy would have decided; nothing is refused by policy");
283
+ if (cfg.log?.tokenEnv && !process.env[cfg.log.tokenEnv])
284
+ add("error", "credentials", `log token variable ${cfg.log.tokenEnv} is not set in this environment`);
285
+ if (cfg.splunk?.tokenEnv && !process.env[cfg.splunk.tokenEnv])
286
+ add("error", "credentials", `splunk token variable ${cfg.splunk.tokenEnv} is not set in this environment`);
287
+ for (const v of Object.values(cfg.otel?.headersEnv ?? {}))
288
+ if (!process.env[v])
289
+ add("error", "credentials", `otel header variable ${v} is not set in this environment`);
290
+ for (const f of cfg.log?.keys ?? [])
291
+ if (!existsSync(f))
292
+ add("error", "log keys", `${f} does not exist`);
293
+ return out;
294
+ }
203
295
  export async function checkConfig(configPath, options = {}) {
204
296
  const out = [];
205
297
  const add = (level, check, message) => out.push({ level, check, message });
package/dist/cli.js CHANGED
@@ -30,7 +30,7 @@ import { CheckpointPublisher, fileResolver } from "./log-sink.js";
30
30
  import { createRequire } from "node:module";
31
31
  import { pruneLog } from "./retention.js";
32
32
  import { serveSidecar } from "./sidecar.js";
33
- import { checkConfig, checkDoorConfig, formatFindings, isDoorConfig } from "./check.js";
33
+ import { checkConfig, checkDoorConfig, checkEgressConfig, formatFindings, isDoorConfig, isEgressConfig } from "./check.js";
34
34
  import { serveConsole } from "./console.js";
35
35
  import { TREEHEAD_TYPE } from "./receipt.js";
36
36
  import { MerkleLog } from "./log.js";
@@ -307,7 +307,7 @@ async function main(argv) {
307
307
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, connect: { type: "boolean", default: false }, json: { type: "boolean", default: false } } });
308
308
  if (!values.config)
309
309
  throw new Error("check needs --config");
310
- const findings = isDoorConfig(values.config) ? checkDoorConfig(values.config) : await checkConfig(values.config, { connect: values.connect });
310
+ const findings = isDoorConfig(values.config) ? checkDoorConfig(values.config) : isEgressConfig(values.config) ? checkEgressConfig(values.config) : await checkConfig(values.config, { connect: values.connect });
311
311
  console.log(values.json ? JSON.stringify(findings, null, 2) : formatFindings(findings));
312
312
  return findings.some((f) => f.level === "error") ? 1 : 0;
313
313
  }
package/dist/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ export declare const ONE_LOG = "exactly one of logFile or log is required";
2
3
  /** One REST endpoint offered to the agent as a tool. `{name}` segments in the path come from the call's arguments; the rest go to the query on GET and DELETE, or to a JSON body otherwise. */
3
4
  declare const RestToolSchema: z.ZodObject<{
4
5
  name: z.ZodString;
package/dist/config.js CHANGED
@@ -3,7 +3,8 @@ import { readFileSync } from "node:fs";
3
3
  import { dirname, resolve } from "node:path";
4
4
  /** Where receipts are logged: a local file, or a log reached over HTTP whose bearer token comes from an environment variable. */
5
5
  const LogSchema = z.object({ url: z.string().url(), tokenEnv: z.string().min(1).optional(), /** send leaf hashes only; the log never holds the receipt. Use it for any log run by someone else */ hashOnly: z.boolean().optional(), /** milliseconds one append may take before the log counts as unreachable; default 10000 */ timeoutMs: z.number().int().positive().optional(), /** the log's public key files; every append's answer is checked against them before a call is forwarded. Without them the log's key document is fetched from the log itself on first use and pinned, which catches a log that turns dishonest later but not one dishonest from the start; required with precommit. */ keys: z.array(z.string().min(1)).optional(), /** the id the log must write into every tree head; an answer for another log is refused */ logId: z.string().min(1).optional() });
6
- const oneLog = { message: "exactly one of logFile or log is required" };
6
+ export const ONE_LOG = "exactly one of logFile or log is required";
7
+ const oneLog = { message: ONE_LOG };
7
8
  /** Optional OpenTelemetry export: every receipt also becomes a span at this OTLP/HTTP collector, after it is issued. Never on the evidence path. */
8
9
  const OtelSchema = z.object({ url: z.string().url(), headersEnv: z.record(z.string(), z.string().min(1)).optional(), serviceName: z.string().min(1).optional() });
9
10
  const SplunkSchema = z.object({ url: z.string().url(), tokenEnv: z.string().min(1), index: z.string().min(1).optional(), source: z.string().min(1).optional(), sourcetype: z.string().min(1).optional(), host: z.string().min(1).optional() });
package/dist/lock.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { closeSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
4
  import { hostname } from "node:os";
5
- import { ownerAlive, processStamp } from "./operations.js";
5
+ import { ownerAlive, ownProcessStamp } from "./operations.js";
6
6
  /** A lock file that holds no readable owner is a lock that is being written. After this age it is a leftover. */
7
7
  const UNREADABLE_STALE_MS = 60_000;
8
8
  const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
@@ -77,7 +77,7 @@ function breakLock(lockFile, judged) {
77
77
  */
78
78
  export function takeLock(lockFile, staleMs) {
79
79
  const token = randomUUID();
80
- const body = JSON.stringify({ token, pid: process.pid, start: processStamp(process.pid), host: hostname() });
80
+ const body = JSON.stringify({ token, pid: process.pid, start: ownProcessStamp(), host: hostname() });
81
81
  for (let attempt = 0; attempt < 3; attempt++) {
82
82
  try {
83
83
  const fd = openSync(lockFile, "wx", 0o600);
package/dist/log.d.ts CHANGED
@@ -33,6 +33,7 @@ export declare class MerkleLog {
33
33
  private readonly file;
34
34
  private bytes;
35
35
  private inode;
36
+ private readonly out;
36
37
  constructor(file: string);
37
38
  /**
38
39
  * Reads the leaves that another handle or process appended since the last read. A file that was replaced or cut
@@ -47,6 +48,15 @@ export declare class MerkleLog {
47
48
  private cutTornTail;
48
49
  /** Under the lock: reads what other writers appended, then writes this line, so each leaf gets the next index. */
49
50
  private appendLine;
51
+ /**
52
+ * Under the lock: writes the line through one descriptor opened for append, so the file is not opened and closed
53
+ * for every leaf. O_APPEND puts each write at the end, after a torn tail was cut too. The descriptor is reopened when
54
+ * the path names another file than the one it holds (a prune renames a new file into place) or no file. Nothing is
55
+ * fsynced, as before: the line is in the kernel's page cache when the append returns.
56
+ */
57
+ private write;
58
+ /** Closes the append descriptor. The log stays usable: the next append opens the file again. */
59
+ close(): void;
50
60
  get size(): number;
51
61
  /** Leaf hashes `from` (inclusive) to `to` (exclusive), as hex: what an export carries and what a copy is rebuilt from. */
52
62
  leafHashes(from: number, to?: number): string[];
package/dist/log.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Append-only Merkle log with RFC 6962 / RFC 9162 hashing and inclusion proofs.
2
2
  // Leaves are stored as JSONL so anyone holding the file can recompute the root.
3
3
  import { createHash } from "node:crypto";
4
- import { appendFileSync, closeSync, mkdirSync, openSync, readSync, statSync, truncateSync } from "node:fs";
4
+ import { appendFileSync, closeSync, fstatSync, mkdirSync, openSync, readSync, statSync, truncateSync, writeSync } from "node:fs";
5
5
  import { dirname } from "node:path";
6
6
  import { withLock } from "./lock.js";
7
7
  const h = (...parts) => {
@@ -182,16 +182,25 @@ const LOG_LOCK_WAIT_MS = 20_000;
182
182
  export function logLocked(file, fn) {
183
183
  return withLock(`${file}.lock`, { staleMs: LOCK_STALE_MS, waitMs: LOG_LOCK_WAIT_MS }, fn);
184
184
  }
185
+ const appenders = new FinalizationRegistry((out) => {
186
+ if (out.fd !== null)
187
+ try {
188
+ closeSync(out.fd);
189
+ }
190
+ catch { /* already closed */ }
191
+ });
185
192
  export class MerkleLog {
186
193
  hashes = [];
187
194
  tree = new SubtreeCache(this.hashes);
188
195
  file;
189
196
  bytes = 0;
190
197
  inode = -1;
198
+ out = { fd: null, dev: 0, ino: 0 };
191
199
  constructor(file) {
192
200
  this.file = file;
193
201
  mkdirSync(dirname(file), { recursive: true });
194
202
  this.catchUp();
203
+ appenders.register(this, this.out);
195
204
  }
196
205
  /**
197
206
  * Reads the leaves that another handle or process appended since the last read. A file that was replaced or cut
@@ -212,10 +221,10 @@ export class MerkleLog {
212
221
  this.bytes = 0;
213
222
  }
214
223
  if (!st)
215
- return;
224
+ return null;
216
225
  this.inode = st.ino;
217
226
  if (st.size === this.bytes)
218
- return;
227
+ return st;
219
228
  const buf = Buffer.alloc(st.size - this.bytes);
220
229
  const fd = openSync(this.file, "r");
221
230
  let got = 0;
@@ -240,6 +249,7 @@ export class MerkleLog {
240
249
  // roots, and every proof are the same either way.
241
250
  this.hashes.push(typeof parsed === "string" ? leafHash(parsed) : Buffer.from((parsed.pruned ?? parsed.hash), "hex"));
242
251
  }
252
+ return st;
243
253
  }
244
254
  /**
245
255
  * Under the lock: a last line with no newline is the remains of a writer that died in the middle of its write. No
@@ -269,13 +279,53 @@ export class MerkleLog {
269
279
  /** Under the lock: reads what other writers appended, then writes this line, so each leaf gets the next index. */
270
280
  appendLine(line, hash) {
271
281
  return logLocked(this.file, () => {
272
- this.catchUp();
282
+ const st = this.catchUp();
273
283
  this.cutTornTail();
274
- appendFileSync(this.file, line);
284
+ this.write(line, st);
275
285
  this.bytes += Buffer.byteLength(line);
276
286
  return this.pushHash(hash());
277
287
  });
278
288
  }
289
+ /**
290
+ * Under the lock: writes the line through one descriptor opened for append, so the file is not opened and closed
291
+ * for every leaf. O_APPEND puts each write at the end, after a torn tail was cut too. The descriptor is reopened when
292
+ * the path names another file than the one it holds (a prune renames a new file into place) or no file. Nothing is
293
+ * fsynced, as before: the line is in the kernel's page cache when the append returns.
294
+ */
295
+ write(line, st) {
296
+ const out = this.out;
297
+ if (out.fd === null || !st || st.ino !== out.ino || st.dev !== out.dev) {
298
+ this.close();
299
+ const fd = openSync(this.file, "a");
300
+ const now = fstatSync(fd);
301
+ if (st && (now.ino !== st.ino || now.dev !== st.dev)) {
302
+ closeSync(fd);
303
+ throw new Error(`${this.file} was replaced while its lock was held; the leaf was not appended`);
304
+ }
305
+ out.fd = fd;
306
+ out.dev = now.dev;
307
+ out.ino = now.ino;
308
+ this.inode = now.ino;
309
+ }
310
+ const buf = Buffer.from(line);
311
+ try {
312
+ for (let off = 0; off < buf.length;)
313
+ off += writeSync(out.fd, buf, off);
314
+ }
315
+ catch (e) {
316
+ // the bytes written so far are a torn tail, which the next append cuts; that append reopens the file
317
+ this.close();
318
+ throw e;
319
+ }
320
+ }
321
+ /** Closes the append descriptor. The log stays usable: the next append opens the file again. */
322
+ close() {
323
+ if (this.out.fd === null)
324
+ return;
325
+ const fd = this.out.fd;
326
+ this.out.fd = null;
327
+ closeSync(fd);
328
+ }
279
329
  get size() {
280
330
  return this.hashes.length;
281
331
  }
@@ -11,6 +11,11 @@ export declare function processStamp(pid: number): string | undefined;
11
11
  * UTC: a creator and an operator that run under different TZ values must still get the same text.
12
12
  */
13
13
  export declare function psStamp(pid: number): string | undefined;
14
+ /**
15
+ * This process's stamp. It cannot change while the process runs, so it is read once: without /proc, a read runs `ps`,
16
+ * and the log lock records its owner on every append. A read that failed is tried again on the next call.
17
+ */
18
+ export declare function ownProcessStamp(): string | undefined;
14
19
  /**
15
20
  * Whether the process that created an operation may still run. A process that is gone is not alive. A live process
16
21
  * with the same PID but another start time is a different process (a container restart gives PID 1 again). When a
@@ -36,6 +36,13 @@ export function psStamp(pid) {
36
36
  return undefined;
37
37
  }
38
38
  let own;
39
+ /**
40
+ * This process's stamp. It cannot change while the process runs, so it is read once: without /proc, a read runs `ps`,
41
+ * and the log lock records its owner on every append. A read that failed is tried again on the next call.
42
+ */
43
+ export function ownProcessStamp() {
44
+ return own ??= processStamp(process.pid);
45
+ }
39
46
  /**
40
47
  * Whether the process that created an operation may still run. A process that is gone is not alive. A live process
41
48
  * with the same PID but another start time is a different process (a container restart gives PID 1 again). When a
@@ -131,10 +138,11 @@ export class OperationStore {
131
138
  const reserved = this.db.prepare("SELECT amount FROM operations WHERE budget = ? AND period = ? AND status <> 'failed'").all(input.budget, period).reduce((sum, row) => sum + BigInt(row.amount), 0n);
132
139
  if (reserved + BigInt(input.amount) > BigInt(input.limit))
133
140
  throw new Error(`operation budget ${input.budget} exceeded for ${period}`);
141
+ const ownerStart = ownProcessStamp();
134
142
  const operation = {
135
143
  id: input.id,
136
144
  ownerPid: process.pid,
137
- ...((own ??= { stamp: processStamp(process.pid) }).stamp !== undefined ? { ownerStart: own.stamp } : {}),
145
+ ...(ownerStart !== undefined ? { ownerStart } : {}),
138
146
  issuerKeyid: input.issuerKeyid,
139
147
  ...(input.providerDigest !== undefined ? { providerDigest: input.providerDigest } : {}),
140
148
  idempotencyKey: digestOf({ issuerKeyid: input.issuerKeyid, providerDigest: input.providerDigest ?? null, tool: input.tool, principal: input.principal, agent: input.agent, id: input.id }),
package/dist/otel.js CHANGED
@@ -47,7 +47,7 @@ export function spanFor(p, bundle, serviceName) {
47
47
  traceId,
48
48
  spanId: traceId.slice(0, 16),
49
49
  name: reconciliation ? `${p.tool.name} reconciliation` : `${p.tool.name}`,
50
- kind: 3, // CLIENT: the agent calling out
50
+ kind: p.issuer.kind === "door" ? 2 : 3, // SERVER for an inbound request; CLIENT for the agent calling out
51
51
  startTimeUnixNano: start.toString(),
52
52
  endTimeUnixNano: (end > start ? end : start).toString(),
53
53
  attributes,
package/dist/policy.js CHANGED
@@ -62,17 +62,60 @@ export function reservedCedarForm(value, path = "args") {
62
62
  }
63
63
  return null;
64
64
  }
65
- export function evaluate(policyText, req) {
65
+ /** Policy sets kept parsed, most recently used last. A reload or a second gateway in the process takes another slot. */
66
+ const PARSED_SLOTS = 8;
67
+ const parsed = new Map();
68
+ /** Slot ids that no live entry holds. At most PARSED_SLOTS + 1 ids are ever made. */
69
+ const freeSlots = [];
70
+ let slotsMade = 0;
71
+ /**
72
+ * The policy set parsed once per text, so a decision no longer parses the whole file. Keyed by the text itself: an
73
+ * edited file is a new key, a new parse, and a new digest. A new text takes a slot that no live entry holds, and the
74
+ * least recently used entry is evicted, and its slot freed, only once the new entry is in place: a preparse that throws
75
+ * or fails never changes the set a live entry decides with. Reusing a freed id replaces the set held in cedar-wasm, so
76
+ * neither side grows past PARSED_SLOTS + 1. A failed preparse leaves the slot's previous set in place, so an entry with
77
+ * parse errors must never be evaluated.
78
+ */
79
+ function parsedPolicy(policyText) {
80
+ const hit = parsed.get(policyText);
81
+ if (hit) {
82
+ parsed.delete(policyText);
83
+ parsed.set(policyText, hit);
84
+ return hit;
85
+ }
66
86
  const digest = policyDigest(policyText);
87
+ const slot = freeSlots.pop() ?? `agent-custody-policy-${slotsMade++}`;
88
+ let answer;
89
+ try {
90
+ answer = cedar.preparsePolicySet(slot, { staticPolicies: policyText });
91
+ }
92
+ catch (e) {
93
+ freeSlots.push(slot);
94
+ throw e;
95
+ }
96
+ const entry = { slot, digest, parseErrors: answer.type === "success" ? [] : answer.errors.map((e) => e.message) };
97
+ parsed.set(policyText, entry);
98
+ if (parsed.size > PARSED_SLOTS) {
99
+ const [oldest, evicted] = parsed.entries().next().value;
100
+ parsed.delete(oldest);
101
+ freeSlots.push(evicted.slot);
102
+ }
103
+ return entry;
104
+ }
105
+ export function evaluate(policyText, req) {
106
+ const policy = parsedPolicy(policyText);
107
+ const digest = policy.digest;
67
108
  const reserved = reservedCedarForm(req.context.args);
68
109
  if (reserved)
69
110
  return { decision: "deny", reasons: [], errors: [`argument ${reserved} uses a reserved Cedar form; arguments are data, never entities or extension values`], policyDigest: digest };
70
- const answer = cedar.isAuthorized({
111
+ if (policy.parseErrors.length > 0)
112
+ return { decision: "deny", reasons: [], errors: [...policy.parseErrors], policyDigest: digest };
113
+ const answer = cedar.statefulIsAuthorized({
71
114
  principal: { type: "Agent", id: req.agentId },
72
115
  action: { type: "Action", id: req.tool },
73
116
  resource: { type: "Tool", id: req.tool },
74
117
  context: req.context,
75
- policies: { staticPolicies: policyText },
118
+ preparsedPolicySetId: policy.slot,
76
119
  entities: [],
77
120
  });
78
121
  if (answer.type === "failure") {
package/docs/door.md CHANGED
@@ -84,6 +84,173 @@ and a refused arrival that has not passed is told how in the 403 body: `challeng
84
84
 
85
85
  **A token serves one request.** Turnstile and hCaptcha refuse a token they have seen (`timeout-or-duplicate`, `already-seen-response`), and the door keeps no pass between requests: it does not set a cookie or remember an address. So the page must take a new token for every request it sends to a challenged route, and for every retry: call `turnstile.reset()` or `hcaptcha.reset()` after each request, and wait for the new token before the next. The door checks the token before it reads the body, so a request refused for its size (413), its path (400), or by the policy has used its token too. A second request that sends the same token is `failed`, and the person sees another 403. The outcome is a signal, not a class: a `verified` agent that also passes a challenge is still the agent its grant names, and an `unknown` arrival that passes is still `unknown`, with `challenge.outcome: "passed"` beside it. What the provider's pass means, and what it does not, is in [door signals](door-signals.md). Passkeys are not a provider here: a passkey proves possession of a credential the site registered, which is a login, not a challenge, and belongs to the origin.
86
86
 
87
+ ### A run against Turnstile's test keys
88
+
89
+ The tests stub `siteverify`. This run calls the real one once. Cloudflare publishes [test keys](https://developers.cloudflare.com/turnstile/troubleshooting/testing/) that need no account: the site key `1x00000000000000000000AA`, the secret `1x0000000000000000000000000000000AA` (validation always succeeds), the secret `2x0000000000000000000000000000000AA` (validation always fails), and the dummy token `XXXX.DUMMY.TOKEN.XXXX`. The test secrets accept only the dummy token. Cloudflare answers a test key with the hostname `example.com`, so the config names that hostname. These secrets are public. A real secret still goes only into the environment, never into the config or a flag.
90
+
91
+ The run used the CLI from this repository on 2026-11-10. `policy.cedar`:
92
+
93
+ ```cedar
94
+ // The form is for an arrival that has passed the challenge.
95
+ permit(principal, action == Action::"form", resource)
96
+ when { context.facts.arrival.challenge.outcome == "passed" };
97
+ ```
98
+
99
+ `door.json`:
100
+
101
+ ```json
102
+ {
103
+ "identity": { "keyFile": "keys/door.key" },
104
+ "origin": { "url": "http://127.0.0.1:3000" },
105
+ "routes": [{ "name": "form", "methods": ["POST"], "path": "/form" }],
106
+ "policyFile": "policy.cedar",
107
+ "receiptsDir": "receipts",
108
+ "logFile": "log.jsonl",
109
+ "challenge": {
110
+ "provider": "turnstile",
111
+ "siteKey": "1x00000000000000000000AA",
112
+ "secretEnv": "TURNSTILE_SECRET",
113
+ "hostnames": ["example.com"]
114
+ }
115
+ }
116
+ ```
117
+
118
+ A stand-in origin answers every request with `{"ok":true}`:
119
+
120
+ ```bash
121
+ agent-custody keygen --dir keys --name door
122
+ node -e 'require("http").createServer((q,s)=>{s.setHeader("content-type","application/json");s.end(JSON.stringify({ok:true}))}).listen(3000,"127.0.0.1")' &
123
+ ```
124
+
125
+ **The pass run.** Start the door with the secret that always succeeds, and send the dummy token:
126
+
127
+ ```bash
128
+ TURNSTILE_SECRET=1x0000000000000000000000000000000AA agent-custody door --config door.json --port 8780 &
129
+ curl -sS -i -X POST http://127.0.0.1:8780/form -H 'content-type: application/json' \
130
+ -H 'x-agent-custody-challenge: XXXX.DUMMY.TOKEN.XXXX' -d '{"name":"test"}'
131
+ ```
132
+
133
+ ```text
134
+ HTTP/1.1 200 OK
135
+ x-agent-custody-receipt: 74c1e645-3b3e-4306-a70c-057ea0e61d41
136
+ content-type: application/json
137
+ date: Tue, 10 Nov 2026 02:24:05 GMT
138
+ x-agent-custody-class: unknown
139
+ Connection: keep-alive
140
+ Keep-Alive: timeout=5
141
+ Transfer-Encoding: chunked
142
+
143
+ {"ok":true}
144
+ ```
145
+
146
+ **The fail run.** Stop the door. Start it again with the secret that always fails, and send the same request:
147
+
148
+ ```bash
149
+ TURNSTILE_SECRET=2x0000000000000000000000000000000AA agent-custody door --config door.json --port 8780 &
150
+ curl -sS -i -X POST http://127.0.0.1:8780/form -H 'content-type: application/json' \
151
+ -H 'x-agent-custody-challenge: XXXX.DUMMY.TOKEN.XXXX' -d '{"name":"test"}'
152
+ ```
153
+
154
+ ```text
155
+ HTTP/1.1 403 Forbidden
156
+ x-agent-custody-receipt: 01b840df-6a79-408a-9d3b-32dac88787d8
157
+ content-type: application/json
158
+ cache-control: no-store
159
+ x-agent-custody-class: unknown
160
+ Date: Tue, 10 Nov 2026 02:24:13 GMT
161
+ Connection: keep-alive
162
+ Keep-Alive: timeout=5
163
+ Transfer-Encoding: chunked
164
+
165
+ {"error":"refused by the door's policy","reason":"no permit policy matched","receipt":"01b840df-6a79-408a-9d3b-32dac88787d8","challenge":{"provider":"turnstile","siteKey":"1x00000000000000000000AA","header":"x-agent-custody-challenge"}}
166
+ ```
167
+
168
+ **Verify both receipts.** Both exit 0:
169
+
170
+ ```bash
171
+ agent-custody verify receipts/74c1e645-3b3e-4306-a70c-057ea0e61d41.json --issuer-key keys/door.pub --log log.jsonl
172
+ ```
173
+
174
+ ```text
175
+ PASS receipt signature (issuer key) (keyid e316d40ebc50)
176
+ PASS receipt payload type
177
+ PASS structural parts in clear
178
+ PASS issuer kind is known (door / http)
179
+ PASS issuer keyid matches signer
180
+ PASS door receipt carries a policy decision
181
+ PASS principal is claimed, not attested (no signed delegation in this receipt)
182
+ PASS request args digest (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
183
+ PASS execution result digest
184
+ PASS withheld facts.arrival.resultDigest (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
185
+ PASS policy decision consistent with execution (allow -> executed)
186
+ PASS no policy errors on an allow
187
+ PASS authorization signature (issuer key) (keyid e316d40ebc50)
188
+ PASS authorization names this call (form for receipt 74c1e645-3b3)
189
+ PASS authorization tree head signature (keyid e316d40ebc50)
190
+ PASS authorization log inclusion proof (leaf 0 of 1)
191
+ PASS authorization logged before execution (authorization leaf 0, receipt leaf 1)
192
+ PASS tree head signature (issuer key e316d40ebc50)
193
+ PASS tree head matches inclusion proof size
194
+ PASS log inclusion proof (leaf 1 of 2, root 67f4115b31c2)
195
+ PASS log file root matches tree head (recomputed 67f4115b31c2)
196
+
197
+ RESULT: VERIFIED
198
+
199
+ ISSUER: door (http), unknown issuer kind
200
+
201
+ field provenance value
202
+ principal claimed (none)
203
+ agent claimed unknown
204
+ model claimed (none supplied)
205
+ tool observed form
206
+ args claimed {"$rest":{"$custody":"withheld","sha256":"8f41daf2…"},"bodyBytes":15,"headers":{"accept":"*/*","content-type":"application/json","host":"127.0.0.1:8780","user-agent":"curl/8.7.1"},"method":"POST","path":"/form"}
207
+ fact.arrival observed {"challenge":{"outcome":"passed","provider":"turnstile"},"class":"unknown","grant":"absent","method":"POST","path":"/form","rate":{"burst":1,"by":"remote","minute":1},"remote":"127.0.0.1","route":"form","signature":false,"subject":"unknown"}
208
+ policy observed allow [policy0] policy 71e3eefa3599
209
+ authorization observed committed to the log as leaf 0, before the call was forwarded
210
+ execution observed executed
211
+ ```
212
+
213
+ ```bash
214
+ agent-custody verify receipts/01b840df-6a79-408a-9d3b-32dac88787d8.json --issuer-key keys/door.pub --log log.jsonl
215
+ ```
216
+
217
+ ```text
218
+ PASS receipt signature (issuer key) (keyid e316d40ebc50)
219
+ PASS receipt payload type
220
+ PASS structural parts in clear
221
+ PASS issuer kind is known (door / http)
222
+ PASS issuer keyid matches signer
223
+ PASS door receipt carries a policy decision
224
+ PASS principal is claimed, not attested (no signed delegation in this receipt)
225
+ PASS request args digest (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
226
+ PASS withheld facts.arrival.resultDigest (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
227
+ PASS withheld execution.reason (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
228
+ PASS policy decision consistent with execution (deny -> denied)
229
+ PASS no policy errors on an allow
230
+ PASS tree head signature (issuer key e316d40ebc50)
231
+ PASS tree head matches inclusion proof size
232
+ PASS log inclusion proof (leaf 2 of 3, root 54a065656fa2)
233
+ PASS log file root matches tree head (recomputed 54a065656fa2)
234
+
235
+ RESULT: VERIFIED
236
+
237
+ ISSUER: door (http), unknown issuer kind
238
+
239
+ field provenance value
240
+ principal claimed (none)
241
+ agent claimed unknown
242
+ model claimed (none supplied)
243
+ tool observed form
244
+ args claimed {"$rest":{"$custody":"withheld","sha256":"255b518c…"},"bodyBytes":15,"headers":{"accept":"*/*","content-type":"application/json","host":"127.0.0.1:8780","user-agent":"curl/8.7.1"},"method":"POST","path":"/form"}
245
+ fact.arrival observed {"challenge":{"error":"invalid-input-response","outcome":"failed","provider":"turnstile"},"class":"unknown","grant":"absent","method":"POST","path":"/form","rate":{"burst":1,"by":"remote","minute":1},"remote":"127.0.0.1","route":"form","signature":false,"subject":"unknown"}
246
+ policy observed deny [] policy 71e3eefa3599
247
+ execution observed denied: (reason withheld under the capture rule)
248
+ ```
249
+
250
+ The pass run's receipt records `challenge.outcome: "passed"`, and the door relayed the request. The fail run's receipt records `challenge.outcome: "failed"` with Cloudflare's code `invalid-input-response`, and the policy refused the request. The token does not appear in either receipt.
251
+
252
+ **What this run shows, and what it does not.** Test keys prove the wire path, not bot detection. The door reaches the real `siteverify`, sends the secret and the token, and records the answer. A test secret gives a fixed answer and no widget runs, so the run says nothing about how well Turnstile tells a person from a bot. The run did not exercise the `unavailable` outcome, a hostname mismatch, an action mismatch, the `timeout-or-duplicate` code, or `remoteip` (the config sets no `trustProxy`, so the door sent none). `test/door.test.ts` covers those against a stubbed `siteverify`. In the output above, the two `sha256` digests are shortened to eight characters and `…`. Nothing else is changed. The CLI was `agent-custody` 0.16.2, run from this repository at commit `64285ef`.
253
+
87
254
  ## How an arrival becomes a Cedar request
88
255
 
89
256
  | Cedar slot | value |
package/docs/egress.md CHANGED
@@ -44,6 +44,8 @@ Each receipt is an **observed bypass**: evidence that the agent connected to a d
44
44
 
45
45
  Run it with `agent-custody egress --config egress.json [--port 8791] [--host 127.0.0.1]`.
46
46
 
47
+ `agent-custody check --config egress.json` reports what it can find before the witness starts: unknown keys; a key file that is missing or does not load (the witness does not start without it); an unset secret variable of an agent, and an unset `log.tokenEnv`, `splunk.tokenEnv`, or `otel.headersEnv` variable (by name, never the value); a missing `log.keys` file; a policy that does not exist, a Cedar policy that does not parse, or a Rego policy that does not compile (this needs `opa` on PATH, as the witness does); and that exactly one of `logFile` and `log` is set. It warns on a key file that other users can read, a Cedar policy with no permit rule, and `mode: "observe"`. It exits 1 on an error.
48
+
47
49
  ## How an agent uses it
48
50
 
49
51
  The agent sets `HTTPS_PROXY` and `HTTP_PROXY` to `http://<agent id>:<secret>@<witness>:8791`, and `NO_PROXY` to the gateway's host, because the gateway receipts its own calls. Most HTTP clients send the credential from the URL as `Proxy-Authorization: Basic`. Node's `fetch` reads these variables when `NODE_USE_ENV_PROXY=1` is set, on versions that support it. Other clients need their own proxy setting.
@@ -171,7 +173,6 @@ Vectors `egress-*` and `resigned-egress-*` in `vectors/receipts.json` cover them
171
173
 
172
174
  - Record the byte counts of a connection open when the witness is killed: the committed authorization is in the log, the closing receipt is not.
173
175
  - Identify an agent by its source address or by a signed grant. Today only per-agent proxy credentials identify an agent.
174
- - `agent-custody check` does not read an egress config yet.
175
176
  - Ask an OPA server for the decision. A `.rego` file works; `opa: { url }` does not, because the decision is made synchronously before the relay.
176
177
 
177
178
  Tutorials: [41-egress.ts](../examples/41-egress.ts), and [44-egress-rego.ts](../examples/44-egress-rego.ts) for a Rego policy.
@@ -20,7 +20,7 @@ jobs:
20
20
  runs-on: ubuntu-latest
21
21
  steps:
22
22
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
23
- - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.1
23
+ - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.3
24
24
  with:
25
25
  path: .custody/receipts
26
26
  issuer-key: .custody/keys/agent.pub
@@ -37,7 +37,7 @@ Pin the action to the commit of a release, as you pin every other action. A movi
37
37
  | `principal-key` | the public key files of the principals whose grants a gateway receipt carries, one path on each line; SDK and Claude Code hook receipts need none | |
38
38
  | `log-url` | the URL of the log; the action fetches the log key from it (`verify --log-url`) | |
39
39
  | `log-id` | the id that every tree head must name (`verify --log-id`) | |
40
- | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.1` |
40
+ | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.3` |
41
41
  | `github-token` | a token that can write pull request comments; an empty value writes the job summary only | `github.token` |
42
42
  | `comment-author` | the login of the account that `github-token` posts as; the action edits only a comment from this account | `github-actions[bot]` |
43
43
 
@@ -0,0 +1,79 @@
1
+ # What a receipt costs
2
+
3
+ A receipt adds a policy decision, two Ed25519 signatures, and a log append to a tool call. This page says how long each step takes on one machine, how to measure it on yours, and what is written to disk.
4
+
5
+ ## Measuring it
6
+
7
+ From `packages/receipts`:
8
+
9
+ ```bash
10
+ bun run bench
11
+ ```
12
+
13
+ This runs `scripts/hot-path-bench.ts` (`node scripts/hot-path-bench.ts [iterations]`, default 20,000 after 2,000 warm-up). It is not part of `ci`. Each iteration issues one receipt the way the issuer does, and times each step on its own:
14
+
15
+ | step | what it times |
16
+ | --- | --- |
17
+ | cedar evaluate | `evaluate()` on the fixture's Cedar policy. The requests vary by tool, amount, customer, and verification, so a decision cache could not answer them from one entry. |
18
+ | receipt signature | `dsseSign` over a receipt statement |
19
+ | log append (all) | `MerkleLog.append` on a local file: the lock, reading what other writers appended, the torn-tail check, the write, and the Merkle push, inclusion proof, and root |
20
+ | of which Merkle | the push, proof, and root alone, on an in-memory copy of the tree |
21
+ | tree-head signature | `dsseSign` over the new tree head |
22
+ | rego evaluate (alternative) | the same requests decided by the same policy in Rego, compiled once with `opa build`. The script checks that both engines give the same decision for each request. It is skipped when `opa` is not on `PATH`. |
23
+
24
+ The reference rows time a bare `appendFileSync`, a bare write on a descriptor held open, and the lock owner stamp (see below). There is no network and no fsync. The script writes to a temporary directory and removes it. The site's three numbers (a decision, a gateway call, a verification) come from `scripts/bench.ts`.
25
+
26
+ ## On one machine
27
+
28
+ An Apple M5 laptop, macOS, Node 22.21.1, 9 November 2026, 20,000 receipts per run, means and medians in microseconds. The two runs were interleaved on a machine that was also running other work (load average about 5).
29
+
30
+ | step | before, mean | before, p50 | after, mean | after, p50 |
31
+ | --- | --- | --- | --- | --- |
32
+ | cedar evaluate | 196.5 | 187.8 | 85.9 | 78.8 |
33
+ | receipt signature | 30.4 | 26.9 | 29.7 | 25.5 |
34
+ | log append (all) | 1392.5 | 1305.6 | 1308.6 | 1218.9 |
35
+ | of which Merkle | 10.9 | 9.5 | 9.7 | 8.4 |
36
+ | tree-head signature | 26.1 | 23.1 | 25.0 | 21.7 |
37
+ | rego evaluate (alternative) | 11.3 | 10.0 | 10.0 | 8.4 |
38
+ | appendFileSync (reference) | 22.8 | 19.5 | 28.1 | 24.1 |
39
+ | write on open fd (reference) | 5.0 | 4.4 | 4.4 | 3.3 |
40
+ | lock owner stamp (reference) | 1170.2 | 1095.8 | 1124.8 | 1054.4 |
41
+
42
+ A second interleaved pair agreed: Cedar went from a mean of 178.1 µs to 91.8 µs, and the log append stayed at about 1.3 ms.
43
+
44
+ What changed:
45
+
46
+ - **Cedar parses each policy once.** `evaluate()` used to hand the policy text to Cedar on every call, so Cedar parsed the whole file for every decision, and the text was hashed for the digest every time. Each text is now parsed once with `preparsePolicySet`, and decided with `statefulIsAuthorized`. The cache is keyed by the text, so an edited file is parsed again and gets its new digest. It holds 8 policy sets and evicts the least recently used, only after the new set is in place, and a new text never takes a slot that a live entry holds. A text that does not parse is a deny with Cedar's errors, as before.
47
+ - **The log keeps its file open.** An append used to open and close the file. The log now keeps one descriptor open for append. It reopens the file when a prune has replaced it, when the file was removed, and after a failed write. On this machine the saving, about 20 µs, is smaller than the run-to-run spread of the lock, so the table cannot show it. The reference rows show the write itself.
48
+
49
+ Rego needed no change: a `.rego` file is compiled once per change, and the gateway passes the digest it computed when the file loaded.
50
+
51
+ ### The lock reads its owner stamp once
52
+
53
+ On macOS most of a log append was the lock that keeps the processes writing one log in order. Its owner record carries the process's start time, so that a later process with the same PID is not taken for the owner. On Linux that comes from `/proc/<pid>/stat`. macOS has no `/proc`, so each append ran `ps`, about 1.1 ms. A process's start time cannot change while it runs, so it is now read once per process (`ownProcessStamp`), which the operation store already did. A read that failed is tried again on the next lock. The lock record is the same.
54
+
55
+ The same machine and day, interleaved again, before and after this change alone (load average about 4 to 6):
56
+
57
+ | step | before, mean | before, p50 | after, mean | after, p50 |
58
+ | --- | --- | --- | --- | --- |
59
+ | cedar evaluate | 86.3 | 82.2 | 63.0 | 57.3 |
60
+ | receipt signature | 27.7 | 25.1 | 26.2 | 23.7 |
61
+ | log append (all) | 1275.9 | 1219.6 | 160.4 | 137.8 |
62
+ | of which Merkle | 9.4 | 8.5 | 8.3 | 7.4 |
63
+ | tree-head signature | 23.0 | 21.5 | 19.7 | 18.3 |
64
+ | rego evaluate (alternative) | 10.4 | 9.0 | 6.8 | 5.9 |
65
+ | lock owner stamp (reference) | 1090.9 | 1050.4 | 1140.4 | 1086.3 |
66
+
67
+ A second pair agreed: the log append went from a mean of 1350.9 µs to 159.9 µs. The reference row still times one read of the stamp, which a process now pays once. This change touches only the lock, so the lower Cedar and Rego numbers in the "after" runs are most likely the machine with one `ps` fewer per receipt, not anything in the evaluators. The site's gateway call (`scripts/bench.ts`) went from 2.1 ms to 0.7 ms.
68
+
69
+ ## Where the rest of the time goes
70
+
71
+ The rest of a log append, about 140 µs at the median, is the lock file itself (an exclusive create, the owner record written and read back, and a remove), reading what other writers appended, and the torn-tail check. A gateway on Linux never paid the `ps` cost.
72
+
73
+ No decision is cached, only the parsed policy. Receipts are signed and appended before the call returns, never after: `authorize` never defers, strict mode defers nothing, and a financial operation's receipt does not defer (see the security invariants in `CONTRIBUTING.md`).
74
+
75
+ ## What is on disk when an append returns
76
+
77
+ The log line has been written to the file with `O_APPEND`, so it is in the operating system's page cache. Nothing fsyncs the log: neither `appendFileSync` before nor the held descriptor now. A process crash loses nothing that was acknowledged. A power failure or a kernel crash can lose the last appends. A line cut short by a writer that died during its write is moved to `<log>.torn` by the next append, and that leaf was never acknowledged.
78
+
79
+ Some other files are fsynced: the issuer writes a receipt it keeps in the outbox with `fsync` on the file and its directory, and an approval's single-use record is synced the same way. A receipt bundle, its authorization file, its salts, and the log are not.
package/docs/usage.md CHANGED
@@ -125,7 +125,7 @@ At startup the gateway fetches the agent's card from `<url>/.well-known/agent-ca
125
125
 
126
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
- `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.
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. A door receipt records an inbound request, so its span kind is `SERVER`; every other issuer's span is `CLIENT`. 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
 
130
130
  `splunk`, optional in both configs and usable beside `otel`, sends every receipt to a Splunk HTTP Event Collector as one event: `"splunk": { "url": "https://splunk.example.com:8088", "tokenEnv": "HEC_TOKEN", "index": "agents" }`, with optional `source` (default `agent-custody`), `sourcetype` (default `agent-custody:receipt`), and `host`. The token is read from the named environment variable at startup and never appears in the config. Each event carries `receipt_id`, `tool`, `agent`, `principal`, `status`, `reason`, `policy_decision`, `policy_digest`, `args_digest`, `log_leaf_index`, `log_tree_size`, and `authorization_leaf_index` as plain fields, so a search like `sourcetype="agent-custody:receipt" status=denied` needs no field extraction and every alert leads to the receipt by id. The same rule holds: the event is a copy, the receipt is the evidence, and a collector outage costs a warning. Tutorial 19 shows it.
131
131
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.16.1",
3
+ "version": "0.16.3",
4
4
  "mcpName": "io.github.svayatta/agent-custody",
5
5
  "description": "Proof of what your AI agents did. Give your agents real power, without losing control of them: signed, verifiable receipts for tool calls, an MCP gateway with Cedar or Rego policy, and a Merkle transparency log.",
6
6
  "license": "Apache-2.0",
@@ -64,8 +64,10 @@
64
64
  "build": "tsc -p tsconfig.build.json",
65
65
  "typecheck": "tsc --noEmit",
66
66
  "test": "vitest run",
67
+ "coverage": "vitest run --coverage.enabled",
67
68
  "demo": "tsx scripts/demo.ts",
68
- "vectors": "tsx scripts/vectors.ts"
69
+ "vectors": "tsx scripts/vectors.ts",
70
+ "bench": "node scripts/hot-path-bench.ts"
69
71
  },
70
72
  "engines": {
71
73
  "node": ">=22"
@@ -82,6 +84,7 @@
82
84
  "@node-saml/node-saml": "5.1.0",
83
85
  "@openai/agents": "0.18.0",
84
86
  "@types/node": "26.4.1",
87
+ "@vitest/coverage-v8": "5.0.0",
85
88
  "ai": "7.0.93",
86
89
  "langchain": "1.5.15",
87
90
  "tsx": "4.23.13",