@agent-custody/state 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -17,6 +17,8 @@ import { loadScenarios, signReport, verifyReport } from "./evals-file.js";
17
17
  import { buildPack, formatPack, signPack, verifyPack } from "./pack.js";
18
18
  import { buildActionPack, formatExplain, signActionPack, verifyActionPack } from "./explain.js";
19
19
  import { serveReview, writeReview } from "./review.js";
20
+ import { buildCaseFile, renderCaseFile, verifyCaseFile, verifyCaseHtml } from "./case-file.js";
21
+ import { validateReceiptSearch } from "./search.js";
20
22
  import { fileURLToPath } from "node:url";
21
23
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
22
24
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
@@ -40,6 +42,23 @@ function parseRetention(spec) {
40
42
  }
41
43
  return out;
42
44
  }
45
+ /**
46
+ * Spawns the gateway from its config and makes one call through it, so the call runs as the principal named in that
47
+ * gateway's grant and its receipt is the record. Prints the result text; exits 1 when the result is an error.
48
+ */
49
+ async function callVia(config, tool, args) {
50
+ const gatewayCli = fileURLToPath(import.meta.resolve("@agent-custody/receipts/cli"));
51
+ const client = new Client({ name: "agent-custody-memory-cli", version: "0" });
52
+ await client.connect(new StdioClientTransport({ command: process.execPath, args: [gatewayCli, "gateway", "--config", config], stderr: "inherit" }));
53
+ try {
54
+ const r = await client.callTool({ name: tool, arguments: args });
55
+ console.log((r.content.find((c) => c.type === "text")?.text) ?? "");
56
+ return r.isError ? 1 : 0;
57
+ }
58
+ finally {
59
+ await client.close();
60
+ }
61
+ }
43
62
  const USAGE = `agent-custody-memory <command>
44
63
 
45
64
  serve --ledger <ledger.jsonl|ledger.sqlite|postgres://…> [--allow-direct] [--key <memory.key>] [--forget-key-env NAME] [--retention 'org=P365D,team:*=P90D']
@@ -58,6 +77,10 @@ const USAGE = `agent-custody-memory <command>
58
77
  Without --before, the memory server's --retention windows decide. Put this on a timer.
59
78
  sweep --ledger <ledger.jsonl> --before <ISO instant> [--space <space>] --reason <text> [--actor <id>] [--forget-key-env NAME] [--no-digest]
60
79
  retention on the ledger file alone, for ledgers with no gateway or stores in front of them.
80
+ repair --via <gateway.json> --reason <text> [--before <ISO instant>]
81
+ runs memory.repair through that gateway: removes the store entries that the ledger has no fact
82
+ for (a write whose ledger append failed), verifies each removal, and records a repair event.
83
+ Only entries stored more than ten minutes ago; --before can only move that cutoff earlier.
61
84
  eval [--scenarios <file.json>] [--baseline] [--json] [--sign <key> --out <report.json>]
62
85
  runs the memory-mutation scenarios on a fresh ledger; --baseline also scores a naive
63
86
  overwrite store; --sign writes a signed report. Exits 1 if the ledger regresses.
@@ -74,13 +97,19 @@ const USAGE = `agent-custody-memory <command>
74
97
  explain ... --out <action.json> --sign <key> the same as one signed action pack, every downstream receipt inside
75
98
  explain --verify <action.json> --key <pub> [--issuer-key <pub>] [--principal-key <pub>] [--log-key <pub>]
76
99
  checks the pack, the receipt inside it, and every downstream receipt
77
- review --receipts <dir> [--ledger <ledger>] [--issuer-key <pub>] [--principal-key <pub>] [--log-key <pub>] [--log-id <id>] [--port 8791] [--host 127.0.0.1] [--title <text>]
100
+ review --receipts <dir> [--ledger <ledger>] [--issuer-key <pub>] [--principal-key <pub>] [--approval-key <pub>] [--log-key <pub>] [--log-id <id>] [--port 8791] [--host 127.0.0.1] [--title <text>]
78
101
  the explain output as pages, for the reviewer who will not open a terminal: an index of every
79
102
  receipt with its verdict, one page per receipt with the ten answers and the verification report.
80
103
  Serves on loopback; put it behind your own login if you expose it.
81
- review ... --out <dir> the same as static files, for a case file or a shared drive
104
+ review ... [--transaction <id>] [--customer <id>] [--agent <id>] [--from <ISO>] [--to <ISO>] [--upstream-key <pub>]
105
+ search public receipt fields by exact IDs and an inclusive time window
106
+ review ... --out <dir> static pages with search and downloadable offline case files
107
+ review ... --case <receiptId> --out <case.html|case.json>
108
+ one portable case, with public keys and fresh offline verification in the HTML
109
+ review --verify-case <case.json|case.html> [--issuer-key <pub>] [--principal-key <pub>] [--approval-key <pub>] [--log-key <pub>] [--upstream-key <pub>] [--log-id <id>] [--json]
110
+ repeat every receipt check offline; supplied keys replace the bundled trust set
82
111
  export --ledger <ledger.sqlite|postgres://…> --out <ledger.jsonl> the auditable JSONL of any ledger, one event per line; also the feed for a warehouse
83
- blast --ledger <ledger.jsonl> --receipts <dir> --fact <factId> [--json]
112
+ blast --ledger <ledger.jsonl> --receipts <dir> --fact <factId> [--capture-key-env NAME] [--json]
84
113
  everything that relied on a fact: later calls, derived beliefs, and whether it was retracted
85
114
  `;
86
115
  async function main(argv) {
@@ -124,22 +153,10 @@ async function main(argv) {
124
153
  case "sweep": {
125
154
  const { values } = parseArgs({ args: rest, options: { ledger: { type: "string" }, via: { type: "string" }, before: { type: "string" }, space: { type: "string" }, reason: { type: "string" }, actor: { type: "string", default: "cli" }, "forget-key-env": { type: "string" }, "no-digest": { type: "boolean", default: false } } });
126
155
  if (values.via) {
127
- // Retention as a receipted call: spawn the gateway from its config and call memory.sweep through it, so the
128
- // sweep runs as the principal named in that gateway's grant and its receipt is the record.
156
+ // Retention as a receipted call, through the gateway.
129
157
  if (!values.reason)
130
158
  throw new Error("sweep --via needs --reason");
131
- const gatewayCli = fileURLToPath(import.meta.resolve("@agent-custody/receipts/cli"));
132
- const client = new Client({ name: "agent-custody-memory-sweep", version: "0" });
133
- await client.connect(new StdioClientTransport({ command: process.execPath, args: [gatewayCli, "gateway", "--config", values.via], stderr: "inherit" }));
134
- try {
135
- const r = await client.callTool({ name: "memory.sweep", arguments: { reason: values.reason, ...(values.before ? { before: new Date(values.before).toISOString() } : {}), ...(values.space ? { space: values.space } : {}), ...(values["no-digest"] ? { keepDigest: false } : {}) } });
136
- const text = (r.content.find((c) => c.type === "text")?.text) ?? "";
137
- console.log(text);
138
- return r.isError ? 1 : 0;
139
- }
140
- finally {
141
- await client.close();
142
- }
159
+ return callVia(values.via, "memory.sweep", { reason: values.reason, ...(values.before ? { before: new Date(values.before).toISOString() } : {}), ...(values.space ? { space: values.space } : {}), ...(values["no-digest"] ? { keepDigest: false } : {}) });
143
160
  }
144
161
  if (!values.ledger || !values.before || !values.reason)
145
162
  throw new Error("sweep needs --ledger, --before, and --reason, or --via <gateway.json> --reason");
@@ -151,6 +168,13 @@ async function main(argv) {
151
168
  await sweeper.close();
152
169
  return 0;
153
170
  }
171
+ case "repair": {
172
+ // Only through the gateway: the stores are configured on the memory server, not here.
173
+ const { values } = parseArgs({ args: rest, options: { via: { type: "string" }, reason: { type: "string" }, before: { type: "string" } } });
174
+ if (!values.via || !values.reason)
175
+ throw new Error("repair needs --via <gateway.json> and --reason");
176
+ return callVia(values.via, "memory.repair", { reason: values.reason, ...(values.before ? { before: new Date(values.before).toISOString() } : {}) });
177
+ }
154
178
  case "eval": {
155
179
  const { values } = parseArgs({ args: rest, options: { scenarios: { type: "string" }, baseline: { type: "boolean", default: false }, json: { type: "boolean", default: false }, sign: { type: "string" }, out: { type: "string" }, verify: { type: "string" }, key: { type: "string", multiple: true } } });
156
180
  if (values.verify) {
@@ -252,12 +276,46 @@ async function main(argv) {
252
276
  return verification && !verification.ok ? 1 : pack.missingReceipts.length ? 1 : 0;
253
277
  }
254
278
  case "review": {
255
- const { values } = parseArgs({ args: rest, options: { receipts: { type: "string" }, ledger: { type: "string" }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, "log-key": { type: "string", multiple: true }, "log-id": { type: "string" }, port: { type: "string", default: "8791" }, host: { type: "string", default: "127.0.0.1" }, title: { type: "string" }, out: { type: "string" } } });
279
+ const { values } = parseArgs({ args: rest, options: { receipts: { type: "string" }, ledger: { type: "string" }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, "approval-key": { type: "string", multiple: true }, "log-key": { type: "string", multiple: true }, "upstream-key": { type: "string", multiple: true }, "log-id": { type: "string" }, port: { type: "string", default: "8791" }, host: { type: "string", default: "127.0.0.1" }, title: { type: "string" }, out: { type: "string" }, transaction: { type: "string" }, customer: { type: "string" }, agent: { type: "string" }, from: { type: "string" }, to: { type: "string" }, case: { type: "string" }, "verify-case": { type: "string" }, json: { type: "boolean", default: false } } });
280
+ const hasKeys = [values["issuer-key"], values["principal-key"], values["approval-key"], values["log-key"], values["upstream-key"]].some((k) => k?.length) || !!values["log-id"];
281
+ const keys = hasKeys ? { issuerKeys: (values["issuer-key"] ?? []).map(loadPublicKey), principalKeys: (values["principal-key"] ?? []).map(loadPublicKey), ...(values["approval-key"]?.length ? { approvalKeys: values["approval-key"].map(loadPublicKey) } : {}), ...(values["log-key"]?.length ? { logKeys: values["log-key"].map(loadPublicKey) } : {}), ...(values["upstream-key"]?.length ? { upstreamKeys: values["upstream-key"].map(loadPublicKey) } : {}), ...(values["log-id"] ? { logId: values["log-id"] } : {}) } : undefined;
282
+ if (values["verify-case"]) {
283
+ const text = readFileSync(values["verify-case"], "utf8");
284
+ // Only a name that ends in .json is read as JSON. A browser renders many other names (.html, .shtml, .ehtml) as HTML, so those get the byte check.
285
+ const result = /\.json$/i.test(values["verify-case"]) ? verifyCaseFile(JSON.parse(text), keys) : verifyCaseHtml(text, keys);
286
+ if (values.json)
287
+ console.log(JSON.stringify(result, null, 2));
288
+ else {
289
+ for (const c of result.checks)
290
+ console.log(`${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? ` (${c.detail})` : ""}`);
291
+ if (result.answers !== undefined)
292
+ console.log(`\nTHE TEN ANSWERS, rebuilt from the signed receipt and the file's ledger snapshot (trust these, not a saved copy):\n${result.answers}`);
293
+ console.log(`\nRESULT: ${result.ok ? "VERIFIED" : "NOT VERIFIED"}`);
294
+ if (!result.complete)
295
+ console.log("INCOMPLETE: missing evidence, unknown or withheld beliefs, or no ledger; dependency and reversal answers remain limited.");
296
+ console.log(keys ? "Checked against independently supplied public keys." : "Checked against bundled public keys; confirm their fingerprints with a trusted source.");
297
+ }
298
+ return result.ok ? 0 : 1;
299
+ }
256
300
  if (!values.receipts)
257
- throw new Error("review needs --receipts");
258
- const keys = values["issuer-key"]?.length ? { issuerKeys: values["issuer-key"].map(loadPublicKey), principalKeys: (values["principal-key"] ?? []).map(loadPublicKey), ...(values["log-key"]?.length ? { logKeys: values["log-key"].map(loadPublicKey) } : {}), ...(values["log-id"] ? { logId: values["log-id"] } : {}) } : undefined;
301
+ throw new Error("review needs --receipts, or --verify-case <case.json|case.html>");
302
+ if (values.case && (!values.out || !/\.(?:html|json)$/.test(values.out)))
303
+ throw new Error("review --case needs --out <case.html|case.json>");
304
+ const search = { ...(values.transaction ? { transaction: values.transaction } : {}), ...(values.customer ? { customer: values.customer } : {}), ...(values.agent ? { agent: values.agent } : {}), ...(values.from ? { from: values.from } : {}), ...(values.to ? { to: values.to } : {}) };
305
+ validateReceiptSearch(search);
259
306
  const ledger = values.ledger ? new Ledger(values.ledger) : undefined;
260
- const o = { receiptsDir: values.receipts, ...(ledger ? { ledger } : {}), ...(keys ? { keys } : {}), ...(values.title ? { title: values.title } : {}) };
307
+ const o = { receiptsDir: values.receipts, search, ...(ledger ? { ledger } : {}), ...(keys ? { keys } : {}), ...(values.title ? { title: values.title } : {}) };
308
+ if (values.case) {
309
+ try {
310
+ const file = await buildCaseFile(o, values.case);
311
+ writeFileSync(values.out, values.out.endsWith('.html') ? renderCaseFile(file) : JSON.stringify(file, null, 2));
312
+ console.log(`wrote offline case file to ${values.out}`);
313
+ return 0;
314
+ }
315
+ finally {
316
+ await ledger?.close();
317
+ }
318
+ }
261
319
  if (values.out) {
262
320
  const r = await writeReview(o, values.out);
263
321
  console.log(`wrote ${r.receipts} receipt page(s) and the index to ${values.out}`);
package/dist/explain.js CHANGED
@@ -144,7 +144,9 @@ export function formatExplain(pack, verification, withLedger) {
144
144
  // under a capture rule a message is a commitment in the receipt; the explanation says so rather than printing it
145
145
  const text = (v) => (typeof v === "string" ? v : "(withheld under the capture rule)");
146
146
  const errors = Array.isArray(p.policy?.errors) ? p.policy.errors : p.policy?.errors ? [text(p.policy.errors)] : [];
147
- if (p.policy)
147
+ if (p.reconciliation)
148
+ more("no policy was evaluated: this receipt records a provider read that closes an earlier call");
149
+ else if (p.policy)
148
150
  more(`policy ${p.policy.policyDigest.slice(0, 12)} decided ${p.policy.decision}${p.policy.reasons.length ? ` by ${p.policy.reasons.join(", ")}` : ""}${errors.length ? `; errors: ${errors.join("; ")}` : ""}`);
149
151
  const facts = Object.entries(p.facts);
150
152
  row("WHAT THE AGENT SAW", facts.length ? facts.map(([k, f]) => `${k} = ${JSON.stringify(f.value)} (fetched by the gateway via ${f.tool})`).join("; ") : "no facts fetched for this call");
@@ -163,8 +165,11 @@ export function formatExplain(pack, verification, withLedger) {
163
165
  for (const id of pack.consumed.unknown)
164
166
  more(` ${id.slice(0, 8)} (not in this ledger)`);
165
167
  }
166
- row("WHAT IT DID", `${p.tool.name} ${JSON.stringify(p.request.args)} -> ${p.execution.status}${p.execution.status === "denied" ? `: ${text(p.execution.reason)}` : p.execution.status === "withheld" ? `: ${text(p.execution.reason)}` : p.execution.status === "error" ? `: ${text(p.execution.error)}` : ""}`);
167
- row("WHY", p.policy ? (p.policy.decision === "allow" ? `the policy permitted it${p.policy.reasons.length ? ` (${p.policy.reasons.join(", ")})` : ""}` : p.policy.enforced === false ? `the policy would have refused it, and was in observe mode, so the call went through: ${[...p.policy.reasons, ...errors].join("; ") || "no permit matched"}` : `the policy refused it: ${[...p.policy.reasons, ...errors].join("; ") || "no permit matched"}`) : "no policy was evaluated");
168
+ if (p.reconciliation)
169
+ row("WHAT IT DID", `reconciliation: the gateway read ${p.reconciliation.lookup.tool} for ${p.tool.name}; the operation is ${p.operation?.status ?? "unknown"} (the tool did not run again)`);
170
+ else
171
+ row("WHAT IT DID", `${p.tool.name} ${JSON.stringify(p.request.args)} -> ${p.execution.status}${p.execution.status === "denied" ? `: ${text(p.execution.reason)}` : p.execution.status === "withheld" ? `: ${text(p.execution.reason)}` : p.execution.status === "error" ? `: ${text(p.execution.error)}` : ""}`);
172
+ row("WHY", p.reconciliation ? "no policy was evaluated; the gateway read the provider record to close an earlier call" : p.policy ? (p.policy.decision === "allow" ? `the policy permitted it${p.policy.reasons.length ? ` (${p.policy.reasons.join(", ")})` : ""}` : p.policy.enforced === false ? `the policy would have refused it, and was in observe mode, so the call went through: ${[...p.policy.reasons, ...errors].join("; ") || "no permit matched"}` : `the policy refused it: ${[...p.policy.reasons, ...errors].join("; ") || "no permit matched"}`) : "no policy was evaluated");
168
173
  const th = pack.receipt.treeHead.signatures[0]?.keyid ?? "?";
169
174
  row("WHAT EVIDENCE", `receipt ${p.receiptId}, leaf ${pack.receipt.inclusion.leafIndex} of a log whose head is signed by ${th.slice(0, 12)}`);
170
175
  if (p.authorization)
package/dist/index.d.ts CHANGED
@@ -1,23 +1,27 @@
1
1
  export { Ledger } from "./ledger.ts";
2
2
  export { JsonlStore, PostgresStore, SqliteStore, openStore, selectAbout, selectFor } from "./storage.ts";
3
3
  export type { EventQuery, EventStore, PostgresLike, PostgresOptions } from "./storage.ts";
4
- export type { AsOf, AssertEvent, AssertInput, ConfirmEvent, ConfirmInput, Fact, FactProvenance, DigestKind, ForgetEvent, ForgetInput, HoldEvent, HoldInput, LedgerEvent, SweepInput, RetractEvent, RetractInput, Source } from "./ledger.ts";
5
- export { AGENT_META_KEY, FACTS_META_KEY, OBSERVED_META_KEY, RECEIPT_META_KEY, SERVER_VERSION, TOOLS, createMemoryServer, durationMs, retentionCutoff, serveStdio } from "./server.ts";
4
+ export type { AsOf, AssertEvent, AssertInput, ConfirmEvent, ConfirmInput, Fact, FactProvenance, DigestKind, ForgetEvent, ForgetInput, HoldEvent, HoldInput, LedgerEvent, RepairEvent, RepairInput, SweepInput, RetractEvent, RetractInput, Source } from "./ledger.ts";
5
+ export { AGENT_META_KEY, FACTS_META_KEY, OBSERVED_META_KEY, RECEIPT_META_KEY, REPAIR_MIN_AGE_MS, SERVER_VERSION, TOOLS, createMemoryServer, durationMs, retentionCutoff, serveStdio } from "./server.ts";
6
6
  export type { MemoryServerOptions } from "./server.ts";
7
7
  export { SCENARIOS, formatReport, runAll, runScenario } from "./evals.ts";
8
8
  export type { MemoryUnderTest, Op, Report, Scenario, ScenarioScore } from "./evals.ts";
9
9
  export { ledgerUnderTest, overwriteStoreUnderTest } from "./evals-ledger.ts";
10
10
  export { EVAL_REPORT_TYPE, ScenarioFileSchema, loadScenarios, signReport, verifyReport } from "./evals-file.ts";
11
11
  export type { EvalReportPredicate, ReportCheck, ScenarioFile } from "./evals-file.ts";
12
- export { cogneeStore, factMetadata, factText, langgraphStore, lettaStore, mem0Store, pgvectorStore, zepStore } from "./stores.ts";
12
+ export { cogneeStore, entryOf, factMetadata, factText, langgraphStore, lettaStore, mem0Store, pgvectorStore, zepStore } from "./stores.ts";
13
13
  export { blastRadius, formatBlastRadius, loadReceipts } from "./blast.ts";
14
14
  export { memoryHttpHandler, serveMemoryHttp } from "./http.ts";
15
15
  export { PACK_TYPE, buildPack, formatPack, signPack, verifyPack } from "./pack.ts";
16
16
  export { ACTION_PACK_TYPE, buildActionPack, decodeStatement, formatExplain, signActionPack, verifyActionPack } from "./explain.ts";
17
- export { listReceipts, renderIndex, renderReceipt, reviewHandler, serveReview, writeReview } from "./review.ts";
17
+ export { listReceipts, scanReceipts, renderIndex, renderReceipt, reviewHandler, serveReview, writeReview } from "./review.ts";
18
18
  export type { ReceiptRow, ReviewOptions, RunningReview } from "./review.ts";
19
+ export { matchesReceiptSearch, receiptSearchTerms, validateReceiptSearch } from "./search.ts";
20
+ export type { ReceiptSearch } from "./search.ts";
21
+ export { buildCaseFile, parseCaseHtml, renderCaseFile, verifyCaseFile, verifyCaseHtml } from "./case-file.ts";
22
+ export type { CaseFile, CaseFileKey, CaseFileKeys, CaseFileOptions, CaseFileVerification } from "./case-file.ts";
19
23
  export type { ActionPack, ActionPackCheck, ActionPackVerification, ReceiptKeys } from "./explain.ts";
20
24
  export type { CustodyPack, PackCheck, PackVerification } from "./pack.ts";
21
25
  export type { MemoryHttpOptions, RunningMemoryServer } from "./http.ts";
22
26
  export type { BlastRadius, ReceiptSummary } from "./blast.ts";
23
- export type { CogneeOptions, LangGraphStoreLike, LangGraphStoreOptions, LettaLike, LettaOptions, Mem0Like, Mem0Options, PgLike, PgvectorOptions, RemovalOutcome, Store, ZepLike, ZepOptions } from "./stores.ts";
27
+ export type { CogneeOptions, LangGraphStoreLike, LangGraphStoreOptions, LettaLike, LettaOptions, Mem0Like, Mem0Options, PgLike, PgvectorOptions, RemovalOutcome, Store, StoreEntry, ZepLike, ZepOptions } from "./stores.ts";
package/dist/index.js CHANGED
@@ -1,13 +1,15 @@
1
1
  // Public surface of @agent-custody/state.
2
2
  export { Ledger } from "./ledger.js";
3
3
  export { JsonlStore, PostgresStore, SqliteStore, openStore, selectAbout, selectFor } from "./storage.js";
4
- export { AGENT_META_KEY, FACTS_META_KEY, OBSERVED_META_KEY, RECEIPT_META_KEY, SERVER_VERSION, TOOLS, createMemoryServer, durationMs, retentionCutoff, serveStdio } from "./server.js";
4
+ export { AGENT_META_KEY, FACTS_META_KEY, OBSERVED_META_KEY, RECEIPT_META_KEY, REPAIR_MIN_AGE_MS, SERVER_VERSION, TOOLS, createMemoryServer, durationMs, retentionCutoff, serveStdio } from "./server.js";
5
5
  export { SCENARIOS, formatReport, runAll, runScenario } from "./evals.js";
6
6
  export { ledgerUnderTest, overwriteStoreUnderTest } from "./evals-ledger.js";
7
7
  export { EVAL_REPORT_TYPE, ScenarioFileSchema, loadScenarios, signReport, verifyReport } from "./evals-file.js";
8
- export { cogneeStore, factMetadata, factText, langgraphStore, lettaStore, mem0Store, pgvectorStore, zepStore } from "./stores.js";
8
+ export { cogneeStore, entryOf, factMetadata, factText, langgraphStore, lettaStore, mem0Store, pgvectorStore, zepStore } from "./stores.js";
9
9
  export { blastRadius, formatBlastRadius, loadReceipts } from "./blast.js";
10
10
  export { memoryHttpHandler, serveMemoryHttp } from "./http.js";
11
11
  export { PACK_TYPE, buildPack, formatPack, signPack, verifyPack } from "./pack.js";
12
12
  export { ACTION_PACK_TYPE, buildActionPack, decodeStatement, formatExplain, signActionPack, verifyActionPack } from "./explain.js";
13
- export { listReceipts, renderIndex, renderReceipt, reviewHandler, serveReview, writeReview } from "./review.js";
13
+ export { listReceipts, scanReceipts, renderIndex, renderReceipt, reviewHandler, serveReview, writeReview } from "./review.js";
14
+ export { matchesReceiptSearch, receiptSearchTerms, validateReceiptSearch } from "./search.js";
15
+ export { buildCaseFile, parseCaseHtml, renderCaseFile, verifyCaseFile, verifyCaseHtml } from "./case-file.js";
package/dist/ledger.d.ts CHANGED
@@ -94,7 +94,24 @@ export interface HoldEvent {
94
94
  reason: string;
95
95
  source: Source;
96
96
  }
97
- export type LedgerEvent = AssertEvent | RetractEvent | ConfirmEvent | ForgetEvent | HoldEvent;
97
+ /**
98
+ * A repair records the claim on a store entry that the ledger has no fact for: the stores were written, then the
99
+ * ledger append failed. The memory server appends it before it removes the entry. The factId is the id in the
100
+ * entry's custody metadata, which no assert carries. After a repair event, the ledger refuses an assert of that id.
101
+ */
102
+ export interface RepairEvent {
103
+ eventId: string;
104
+ kind: "repair";
105
+ txTime: string;
106
+ factId: string;
107
+ actor: string;
108
+ reason: string;
109
+ source: Source;
110
+ /** the store the entry was in, and the store's id for it */
111
+ store: string;
112
+ externalId: string;
113
+ }
114
+ export type LedgerEvent = AssertEvent | RetractEvent | ConfirmEvent | ForgetEvent | HoldEvent | RepairEvent;
98
115
  export interface AssertInput {
99
116
  /** the fact's id, when the caller had to know it before the append, as the memory server does for its stores; default a fresh UUID */
100
117
  factId?: string;
@@ -130,6 +147,9 @@ export interface HoldInput {
130
147
  reason: string;
131
148
  source?: Source;
132
149
  }
150
+ export type RepairInput = Omit<RepairEvent, "eventId" | "kind" | "txTime" | "source"> & {
151
+ source?: Source;
152
+ };
133
153
  export interface SweepInput {
134
154
  /** every fact the ledger learned of before this instant is forgotten, unless held or already forgotten */
135
155
  before: string;
@@ -160,6 +180,7 @@ export declare class Ledger {
160
180
  private readonly store;
161
181
  private readonly now;
162
182
  private readonly forgetKey;
183
+ private readonly locks;
163
184
  /**
164
185
  * `location` is a path (JSONL by default, SQLite when it ends in .sqlite or .db) or a postgres:// URL; or pass a
165
186
  * store. The ledger holds no events itself: every question is a query to the store, so a shared store means a
@@ -181,12 +202,24 @@ export declare class Ledger {
181
202
  /** The checks assert makes, without appending. For callers that must do something irreversible before the append. */
182
203
  validateAssert(input: AssertInput): Promise<void>;
183
204
  assert(input: AssertInput): Promise<AssertEvent>;
205
+ private appendAssert;
184
206
  retract(input: RetractInput): Promise<RetractEvent>;
185
207
  confirm(input: ConfirmInput): Promise<ConfirmEvent>;
186
208
  /** Whether a legal hold currently stands on the fact. */
187
209
  held(factId: string): Promise<boolean>;
188
210
  hold(input: HoldInput): Promise<HoldEvent>;
189
211
  release(input: HoldInput): Promise<HoldEvent>;
212
+ /**
213
+ * Records the claim on a store entry with no fact in the ledger. Refuses a fact id that the ledger knows. The first
214
+ * record of a fact id wins: an assert of an id with a repair event is refused, and so is a repair of an id with an
215
+ * assert. A repair of an entry that has a repair event returns that event, so a retry adds none.
216
+ */
217
+ repair(input: RepairInput): Promise<RepairEvent>;
218
+ /**
219
+ * Runs one step at a time per fact id in this process, so the check of an assert and of a repair cannot interleave.
220
+ * Two processes that share a store need the check and the append in one transaction (for example a per-fact-id advisory lock), which this version does not do.
221
+ */
222
+ private exclusive;
190
223
  /** The facts the ledger learned of before an instant, in one space or all, that have not been forgotten: what a retention sweep decides about. */
191
224
  learnedBefore(before: string, space?: string): Promise<Fact[]>;
192
225
  /** Retention: forgets every fact the ledger learned of before the cutoff, in one space or all, skipping held and already-forgotten facts. Returns what it forgot and what it skipped. */
package/dist/ledger.js CHANGED
@@ -9,6 +9,7 @@ export class Ledger {
9
9
  store;
10
10
  now;
11
11
  forgetKey;
12
+ locks = new Map();
12
13
  /**
13
14
  * `location` is a path (JSONL by default, SQLite when it ends in .sqlite or .db) or a postgres:// URL; or pass a
14
15
  * store. The ledger holds no events itself: every question is a query to the store, so a shared store means a
@@ -53,8 +54,14 @@ export class Ledger {
53
54
  throw new Error(`replacement cannot start before the fact it supersedes`);
54
55
  }
55
56
  }
56
- async assert(input) {
57
+ assert(input) {
58
+ return input.factId === undefined ? this.appendAssert(input) : this.exclusive(input.factId, () => this.appendAssert(input));
59
+ }
60
+ async appendAssert(input) {
57
61
  await this.validateAssert(input);
62
+ // A repair removed the stores' entries of this id, so an assert now would give the ledger a fact that no store holds.
63
+ if (input.factId !== undefined && (await this.store.eventsFor(input.factId)).some((e) => e.kind === "repair"))
64
+ throw new Error(`fact ${input.factId} was claimed by a repair, so the ledger refuses to record it`);
58
65
  const txTime = this.now().toISOString();
59
66
  const validFrom = input.validFrom ?? txTime;
60
67
  const event = {
@@ -136,6 +143,39 @@ export class Ledger {
136
143
  await this.store.append(event);
137
144
  return event;
138
145
  }
146
+ /**
147
+ * Records the claim on a store entry with no fact in the ledger. Refuses a fact id that the ledger knows. The first
148
+ * record of a fact id wins: an assert of an id with a repair event is refused, and so is a repair of an id with an
149
+ * assert. A repair of an entry that has a repair event returns that event, so a retry adds none.
150
+ */
151
+ repair(input) {
152
+ return this.exclusive(input.factId, async () => {
153
+ if (await this.factById(input.factId))
154
+ throw new Error(`fact ${input.factId} is in the ledger; repair removes only entries the ledger has no fact for`);
155
+ const prior = (await this.store.eventsFor(input.factId)).find((e) => e.kind === "repair" && e.store === input.store && e.externalId === input.externalId);
156
+ if (prior)
157
+ return prior;
158
+ const event = { eventId: randomUUID(), kind: "repair", txTime: this.now().toISOString(), factId: input.factId, actor: input.actor, reason: input.reason, source: input.source ?? { receiptId: null }, store: input.store, externalId: input.externalId };
159
+ await this.store.append(event);
160
+ return event;
161
+ });
162
+ }
163
+ /**
164
+ * Runs one step at a time per fact id in this process, so the check of an assert and of a repair cannot interleave.
165
+ * Two processes that share a store need the check and the append in one transaction (for example a per-fact-id advisory lock), which this version does not do.
166
+ */
167
+ async exclusive(factId, step) {
168
+ const run = (this.locks.get(factId) ?? Promise.resolve()).then(step);
169
+ const tail = run.then(() => { }, () => { });
170
+ this.locks.set(factId, tail);
171
+ try {
172
+ return await run;
173
+ }
174
+ finally {
175
+ if (this.locks.get(factId) === tail)
176
+ this.locks.delete(factId);
177
+ }
178
+ }
139
179
  /** The facts the ledger learned of before an instant, in one space or all, that have not been forgotten: what a retention sweep decides about. */
140
180
  async learnedBefore(before, space) {
141
181
  const events = await this.store.eventsAbout({ txBefore: before, ...(space === undefined ? {} : { space }) });
package/dist/review.d.ts CHANGED
@@ -2,13 +2,16 @@ import { type IncomingMessage, type ServerResponse } from "node:http";
2
2
  import { type VerifyOptions, type VerifyResult } from "@agent-custody/receipts";
3
3
  import { type ActionPack } from "./explain.ts";
4
4
  import type { Ledger } from "./ledger.ts";
5
+ import { type ReceiptSearch } from "./search.ts";
5
6
  export interface ReviewOptions {
6
7
  receiptsDir: string;
7
8
  ledger?: Ledger;
8
9
  /** with these, every receipt page carries its verification report */
9
- keys?: Pick<VerifyOptions, "issuerKeys" | "principalKeys" | "logKeys" | "logId">;
10
+ keys?: Pick<VerifyOptions, "issuerKeys" | "principalKeys" | "approvalKeys" | "logKeys" | "upstreamKeys" | "logId">;
10
11
  /** shown in the page header, e.g. the team or the deployment */
11
12
  title?: string;
13
+ /** Initial search; static exports include only the matching receipts. Only public receipt fields are searched. */
14
+ search?: ReceiptSearch;
12
15
  }
13
16
  export interface ReceiptRow {
14
17
  receiptId: string;
@@ -19,11 +22,26 @@ export interface ReceiptRow {
19
22
  principal: string | null;
20
23
  issuer: string;
21
24
  verified: boolean | null;
25
+ transactionIds: string[];
26
+ customerIds: string[];
27
+ /** A value was too deep or too long to search. An id filter keeps this row in the list, because the id may be in that value. */
28
+ truncated?: true;
29
+ /** The file name without `.json`. Links use it, because a tampered receipt can name another id inside. */
30
+ file: string;
31
+ /** Set when the record is not what its file name says it is. The row is then never verified. */
32
+ problem?: string;
22
33
  }
23
- /** Every receipt in the directory, newest first, with its verdict when keys were given. Damaged files are skipped. */
24
- export declare function listReceipts(o: ReviewOptions): ReceiptRow[];
34
+ /**
35
+ * Every receipt in the directory, newest first, with its verdict when keys were given. A record that does not match
36
+ * its file name is listed as NOT VERIFIED, never dropped. A file that cannot be decoded is counted in `unreadable`.
37
+ */
38
+ export declare function scanReceipts(o: ReviewOptions, query?: ReceiptSearch): {
39
+ rows: ReceiptRow[];
40
+ unreadable: number;
41
+ };
42
+ export declare const listReceipts: (o: ReviewOptions, query?: ReceiptSearch) => ReceiptRow[];
25
43
  /** The index: one row per receipt, newest first. */
26
- export declare function renderIndex(rows: ReceiptRow[], o: ReviewOptions, link: (id: string) => string): string;
44
+ export declare function renderIndex(rows: ReceiptRow[], o: ReviewOptions, link: (id: string) => string, staticPage?: boolean, unreadable?: number): string;
27
45
  /** One receipt's page: the ten answers, the verification report, and the receipt itself. */
28
46
  export declare function renderReceipt(pack: ActionPack, verification: VerifyResult | null, o: ReviewOptions, backLink: string, rawLink: string): string;
29
47
  /** Serves the review on loopback: / is the index, /r/<id> a receipt, /r/<id>.json the bundle. */