@agent-custody/state 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -10
- package/dist/case-file.d.ts +56 -0
- package/dist/case-file.js +258 -0
- package/dist/cli.js +91 -22
- package/dist/http.js +22 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.js +5 -3
- package/dist/ledger.d.ts +34 -1
- package/dist/ledger.js +41 -1
- package/dist/review.d.ts +22 -4
- package/dist/review.js +165 -31
- package/dist/search.d.ts +28 -0
- package/dist/search.js +177 -0
- package/dist/server.d.ts +6 -1
- package/dist/server.js +124 -30
- package/dist/stores.d.ts +86 -7
- package/dist/stores.js +171 -23
- package/dist/verify-web.d.ts +91 -0
- package/dist/verify-web.js +858 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -23,7 +23,9 @@ await ledger.retract({ factId: a.fact.factId, actor: "user:admin", reason: "pois
|
|
|
23
23
|
await ledger.asOf({ validAt: "2026-09-01T00:00:00Z", txAt: "2026-09-01T00:00:00Z" });
|
|
24
24
|
```
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
Runnable examples, all executed by the test suite. [10-support-recovery.ts](examples/10-support-recovery.ts) corrects stale benefits and compensates a simulated credit after a wrong-plan incident, with verified evidence. [09-repair.ts](examples/09-repair.ts) loses a ledger append after a store took the write, then finds and removes the orphan entry with `memory.repair`. [08-review-console.ts](examples/08-review-console.ts) makes a refund through the gateway, finds it by transaction and customer, and exports an offline case file that verifies independently. [07-incomplete-evidence.ts](examples/07-incomplete-evidence.ts) makes the refund of example 06 private under a capture rule: blast radius without the customer's key lists the refund as INCOMPLETE rather than leaving it out, and with the key finds it. [06-actions-on-beliefs.ts](examples/06-actions-on-beliefs.ts) puts memory and a payments API behind one gateway and finds the refund in a belief's blast radius. [05-blast-radius.ts](examples/05-blast-radius.ts) walks from a retracted belief to everything that relied on it. [04-evals.ts](examples/04-evals.ts) scores the ledger and a naive store on the same memory incidents. [03-memory-behind-the-gateway.ts](examples/03-memory-behind-the-gateway.ts) runs the memory server as the gateway's upstream. [01-ledger.ts](examples/01-ledger.ts) walks through a wrong write and its undo. [02-receipt-to-belief.ts](examples/02-receipt-to-belief.ts) runs the whole loop with the receipts package: a tool call gets a signed receipt, the receipt is verified, the belief taken from it is recorded citing the receipt, and later retracted. Run them with `node examples/<file>` from this directory, after `bun run build` at the repository root.
|
|
27
|
+
|
|
28
|
+
For a real model choosing its own tools, run the opt-in [Codex support recovery demo](../receipts/docs/codex-recovery.md). Headless Codex handles a support request against incorrect CRM memory; an operator then reviews and approves recovery. It uses your Codex login and simulated billing. The regular test suite stays offline.
|
|
27
29
|
|
|
28
30
|
## The memory server
|
|
29
31
|
|
|
@@ -49,8 +51,9 @@ In the gateway's config, the memory server is the upstream, and the grant names
|
|
|
49
51
|
| `pack` (CLI) | one fact's history, receipts, holds, blast radius, and forget certificate as one signed artefact, verifiable offline | |
|
|
50
52
|
| `memory.hold`, `memory.release` | legal hold: while it stands the fact cannot be forgotten by request or sweep | `factId`, `reason` |
|
|
51
53
|
| `memory.sweep` | retention: forget what was learned before an instant, in a space or all, skipping held facts, reaching every store | `before`, `space`, `reason` |
|
|
54
|
+
| `memory.repair` | finds the store entries that the ledger has no fact for, stored before a cutoff, and removes them once they are older than a cutoff; see [Write order and repair](#write-order-and-repair) | `reason`, `before` (earlier cutoff only) |
|
|
52
55
|
| `memory.get` | one fact by id in any state, for the gateway's policy lookups | `factId` |
|
|
53
|
-
| `memory.history` | every event that touched a fact | `factId` |
|
|
56
|
+
| `memory.history` | every event that touched a fact, a repair of an orphan entry included | `factId` |
|
|
54
57
|
|
|
55
58
|
**Quarantine.** Every fact carries a provenance: `claimed`, `attested`, or `verified`. A write that came through the gateway is `attested`: its actor is the agent named in a human-signed grant and its receipt exists. A write that arrived any other way is `claimed`, and claimed facts are quarantined: `memory.read` leaves them out unless the caller asks for `includeClaimed`, and the policy can refuse that. `memory.confirm`, accepted only through the gateway, lifts a claimed fact to attested with its own receipt and transaction time, so "was this fact still in quarantine on Tuesday" is answerable. A tool result an SDK-only agent wrote down cannot become something the rest of the fleet believes until an attested party says so. Over stdio the server has one client; shared over HTTP, below, gateways and direct writers feed one ledger and quarantine does its job.
|
|
56
59
|
|
|
@@ -74,7 +77,7 @@ The lookup for writes is optional, so a write that supersedes nothing needs no l
|
|
|
74
77
|
|
|
75
78
|
**Attested executions.** Started with `--key memory.key`, the server signs every result for the receipt the gateway is issuing. A verifier given `memory.pub` then reports the execution of each memory call as attested by the memory server, not only observed by the gateway; the test suite verifies a write this way.
|
|
76
79
|
|
|
77
|
-
**Shared over HTTP.** `agent-custody-memory serve --ledger ./ledger.jsonl --http --port 8790 --token-env MEMORY_TOKEN --allow-direct --direct-token-env MEMORY_DIRECT_TOKEN` serves the same tools over Streamable HTTP, so several gateways, one per agent host, and, with `--allow-direct`, SDK-only agents share one ledger. The two kinds of caller hold different tokens, and the token decides what the server believes: a gateway's call carries the receipt id, the agent, and the facts the gateway observed in its `_meta`, and that is what makes a write attested or verified; a direct writer's `_meta` is dropped before the server reads it, so it can claim a fact and never attest one, whatever its call says. Never give a direct writer the gateway's token. That is the deployment quarantine was built for: writes arriving through a gateway are attested, writes arriving directly are claimed and hidden until a gateway confirms them, and the ledger tells them apart. A gateway reaches it with `"upstream": { "url": "http://127.0.0.1:8790/mcp", "tokenEnv": "MEMORY_TOKEN" }` in its config. The server does not start over HTTP without the gateway token, because without it any caller that reaches the port could pass as a gateway. The test suite runs exactly this: one gateway writer, one direct writer, one ledger.
|
|
80
|
+
**Shared over HTTP.** `agent-custody-memory serve --ledger ./ledger.jsonl --http --port 8790 --token-env MEMORY_TOKEN --allow-direct --direct-token-env MEMORY_DIRECT_TOKEN` serves the same tools over Streamable HTTP, so several gateways, one per agent host, and, with `--allow-direct`, SDK-only agents share one ledger. The two kinds of caller hold different tokens, and the token decides what the server believes: a gateway's call carries the receipt id, the agent, and the facts the gateway observed in its `_meta`, and that is what makes a write attested or verified; a direct writer's `_meta` is dropped before the server reads it, so it can claim a fact and never attest one, whatever its call says. Never give a direct writer the gateway's token. That is the deployment quarantine was built for: writes arriving through a gateway are attested, writes arriving directly are claimed and hidden until a gateway confirms them, and the ledger tells them apart. A gateway reaches it with `"upstream": { "url": "http://127.0.0.1:8790/mcp", "tokenEnv": "MEMORY_TOKEN" }` in its config. The server does not start over HTTP without the gateway token, because without it any caller that reaches the port could pass as a gateway. The test suite runs exactly this: one gateway writer, one direct writer, one ledger. SIGINT or SIGTERM closes the server and the ledger, so a container runtime or systemd stops it cleanly; the review console does the same. The server stops listening, closes idle connections at once, and lets a request in flight finish. After 3 seconds it cuts the connections that remain, for example a request whose body never arrives. The server opens no GET stream (it answers GET with 405, which the gateway's client accepts), so a connected gateway does not hold the stop.
|
|
78
81
|
|
|
79
82
|
[Writing policies](../receipts/docs/policies.md#policies-for-memory) in the receipts guide has six tested policies for the memory tools, from confining an agent to its team's space to a complete support-agent policy. Trust tiers are Cedar policies over the space and, through `includeClaimed`, over quarantine: `permit(principal, action == Action::"memory.write", resource) when { context.args.space == "team:support" };` lets this agent write team memory and nothing else. A read's receipt carries, as `observed`, the exact facts returned, so the ids the agent relied on are already on the record.
|
|
80
83
|
|
|
@@ -144,7 +147,20 @@ WHAT NEEDS REVERSAL 2 belief(s) still believed, and 3 later call(s) to
|
|
|
144
147
|
|
|
145
148
|
The first eight lines come from the receipt alone and work without a ledger; the last two are answered from the ledger, and without one they say `unknown without a ledger` rather than pretending nothing depended on the call. `--out action.json --sign keys/pack.key` writes the same answers as one signed action pack with the receipt and every downstream receipt inside it, and `explain --verify action.json --key keys/pack.pub --issuer-key ... --principal-key ...` checks the pack's signature and digest, the receipt, every downstream receipt, and that the written beliefs cite this receipt. Touch one receipt inside and the pack fails. The custody pack below is the same artefact seen from a fact instead of an action.
|
|
146
149
|
|
|
147
|
-
**The review
|
|
150
|
+
**The review console.** `agent-custody-memory review --receipts receipts --ledger ledger.sqlite --issuer-key keys/gateway.pub --principal-key keys/principal.pub` serves the same answers as pages on loopback: an index with transaction and customer ids, when, tool, outcome, agent, principal, producer, and its verdict. Search by transaction, customer, agent, or an inclusive time range; each receipt opens the ten answers, the verification report, the issued bundle, and a portable case download. It runs where the receipts are, because nobody else holds them; it has no login of its own, so expose it only behind one you already have.
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
agent-custody-memory review --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --transaction re_123 --customer cust_123 --agent support-agent --from 2026-10-01T00:00:00Z --to 2026-10-31T23:59:59Z
|
|
154
|
+
agent-custody-memory review --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --out review-site/
|
|
155
|
+
agent-custody-memory review --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --case <receiptId> --out refund.case.html
|
|
156
|
+
agent-custody-memory review --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --case <receiptId> --out refund.case.json
|
|
157
|
+
agent-custody-memory review --verify-case refund.case.json --issuer-key keys/gateway.pub --principal-key keys/principal.pub --json
|
|
158
|
+
agent-custody-memory review --verify-case refund.case.html --issuer-key keys/gateway.pub --principal-key keys/principal.pub
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Filters combine with AND, match exact case-sensitive ids, and search only public arguments, results, and gateway facts. Times must be ISO 8601 date-times with `Z` or a UTC offset. An identifier withheld by a capture rule cannot be searched. A record that lacks a part the pages read (it fails the verifier's structural check) is shown as NOT VERIFIED with the reason, and it does not stop an export. A ledger or file error is not a defect of the record: it fails the export, and the live page answers 500. Search stops at 64 levels of nesting and ignores JSON text longer than 64 KiB, so one hostile argument cannot stall the index. A receipt with a value that search skipped is marked "partially indexed", and an id filter keeps it in the list, because the id may be in the skipped value. The index never drops a record: a file whose receipt id differs from its name is listed as NOT VERIFIED ("file name does not match receipt id"), and the header counts the files that could not be read. `--out <dir>` writes an index, receipt pages and bundles, and each receipt's `.case.html` and `.case.json`; its browser search covers only the receipts included in that export. Add `--approval-key` (once for each human approver) when the receipts are for calls that a human approved: without those keys such a receipt is NOT VERIFIED. Add `--log-key`, `--log-id`, and `--upstream-key` when those signatures need independent keys.
|
|
162
|
+
|
|
163
|
+
A portable HTML case contains the signed receipts, embedded signed authorizations, inclusion proofs, signed log heads, public keys (issuer, principal, approval, log, and upstream) and their fingerprints, the ten answers, and any ledger snapshot. Open it locally: its embedded WebCrypto verifier runs fresh checks on the signed evidence without external requests. That result is not independent, because the script is in the same file as the data: whoever edits the file can edit the script too, and the page does not compare the ten answers with the receipts. `review --verify-case` is the independent check. It takes the format from the file name: a name that ends in `.json` is read as JSON, and every other name as a page. Content that does not match the name fails. It reads the file, rebuilds the ten answers from the signed receipt and prints them (a saved answer that differs fails the check "ten answers match the signed receipt and the unsigned ledger snapshot"), and exits 1 on failed verification. For a `.case.html` it also fails unless the page is exactly what its data renders, so a changed visible answer or a second copy of the data fails. Trust the answers that the command prints, not the page. The check covers the answers that come from the signed receipt. The belief, dependency, and reversal lines come from the ledger snapshot in the file, which nobody signs, so a forged snapshot with matching answers passes: those lines are not attested. Without key flags it uses the bundled keys; supplied public keys replace the entire bundled trust set. Confirm bundled fingerprints through a trusted source. The explanation and ledger snapshot are unsigned exporter assertions; verification establishes the recorded gateway decision and detects receipt tampering, not that an external payment occurred. Without a ledger, belief dependencies remain `unknown without a ledger`. Capture keys, private keys, salts, and restored withheld values are never added to a case file.
|
|
148
164
|
|
|
149
165
|
## Write-through to the stores you already use
|
|
150
166
|
|
|
@@ -168,7 +184,66 @@ const stores = [
|
|
|
168
184
|
createMemoryServer(new Ledger("./ledger.jsonl"), { stores });
|
|
169
185
|
```
|
|
170
186
|
|
|
171
|
-
|
|
187
|
+
The `Store` interface is small. A custom store implements `name`, `put`, and `delete`, and can add `verifyDeleted` and `list`:
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
interface StoreEntry { externalId: string; factId: string; text: string; storedAt?: string } // one entry a store holds for a fact; storedAt is the ISO time of the store write
|
|
191
|
+
interface Store {
|
|
192
|
+
name: string;
|
|
193
|
+
put(fact): Promise<string>; // writes the fact, returns the store's own id
|
|
194
|
+
delete(entry: StoreEntry): Promise<void>;
|
|
195
|
+
verifyDeleted?(entry: StoreEntry): Promise<boolean>; // optional; without it a removal is "unverified"
|
|
196
|
+
list?(): Promise<StoreEntry[]>; // optional; every entry with custody metadata, for memory.repair
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
**Breaking change for custom stores.** `remove(externalId, fact)` is now `delete(entry)`, and `verifyRemoved(externalId, fact)` is now `verifyDeleted(entry)`. Each takes one `StoreEntry`. Change `remove(id, fact)` to `delete({ externalId, factId, text })`. The names changed with the arguments: `createMemoryServer` refuses a store that has no `delete`, so a store written for the earlier interface fails at startup. It is never called with the wrong arguments, and its old check can never report an entry as verified. The `text` field is the text that `factText(fact)` returns, so a store no longer needs the whole fact. The `entryOf(fact, externalId)` function builds an entry from a fact. The adapters in this package use the new signature already. Every adapter implements `list`: pgvector and Cognee always, LangGraph when the store has `search`, and Mem0, Zep, and Letta when their client has a method that lists entries.
|
|
201
|
+
|
|
202
|
+
The adapters are typed structurally and carry no runtime dependency on either vendor; the tests drive the real `mem0ai` and `@getzep/zep-cloud` clients against fake endpoints, offline.
|
|
203
|
+
|
|
204
|
+
### Write order and repair
|
|
205
|
+
|
|
206
|
+
The write order is fixed: validate, stores, ledger.
|
|
207
|
+
|
|
208
|
+
1. The ledger's checks run first. A write that the ledger refuses never reaches a store.
|
|
209
|
+
2. The stores are written next. The server needs the store ids to record them on the fact.
|
|
210
|
+
3. The ledger appends last.
|
|
211
|
+
|
|
212
|
+
A store that refuses the write fails the write, and nothing is recorded anywhere. A write whose stores take more than five minutes is refused before its ledger append; see the repair sweep below. The retraction order is the reverse: ledger, then stores. Custody must not depend on a store being up. A store that fails to remove is named in the error, so the caller knows that recall can still serve the value.
|
|
213
|
+
|
|
214
|
+
The order has one cost. If the ledger append fails after the stores took the write, a store keeps an entry that the ledger has no fact for. That entry is an orphan: recall can serve it, and no event explains it. The repair sweep removes orphans.
|
|
215
|
+
|
|
216
|
+
A write that is in progress looks like an orphan too: its entries are in the stores and not yet in the ledger. Two rules keep the sweep away from it. Each entry records `storedAt`, the time of its store write. The sweep removes only entries stored before a cutoff, which is ten minutes ago (the exported `REPAIR_MIN_AGE_MS`). And a write whose stores take more than five minutes, half of `REPAIR_MIN_AGE_MS`, is refused before its ledger append. So the entries of a write in progress are never older than the cutoff. This holds across server processes that share the stores. If a ledger append stalls for longer than that, the repair event decides: whichever record of the fact id reaches the ledger first wins, and the other fails with an error. In one server process, the ledger makes the check and the append of the two records one step. For servers in different processes, the window is the time between the check and the commit of one append. To close it, the check and the append must be one transaction in the shared ledger store, for example with a per-fact-id advisory lock. This version does not do that. A unique constraint on `fact_id` does not work: retract, confirm, hold, release, and forget events share the fact id of the fact, and an orphan in two stores has one repair event for each store.
|
|
217
|
+
|
|
218
|
+
`memory.repair { reason, before? }` runs the sweep. The CLI runs it through a gateway, so the sweep has a receipt and runs as the principal in the gateway's grant:
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
agent-custody-memory repair --via repair-gateway.json --reason "ledger outage on 14 October" [--before <ISO instant>]
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
The cutoff is the earlier of `before` and ten minutes ago. `before` can move the cutoff earlier only, never later.
|
|
225
|
+
|
|
226
|
+
For each store that has `list`, the sweep reads every entry with custody metadata. It removes an entry once only, if a listing holds it twice. It skips an entry whose fact id the ledger knows. It skips an entry that was not stored before the cutoff. For each other entry, the sweep first appends a `repair` event, as a retraction does with its ledger event. The event has the fact id from the entry's metadata, the actor, the reason, the receipt id, the store, and the store's id for the entry. Then the sweep removes the entry and asks the store's search whether the entry is gone (the same retries and outcomes as a forget). The outcome is in the result and in the receipt of the call: `verified`, `stillIndexed`, `unverified`, or `failed`. `memory.history` of the orphan's fact id shows the event. The first record of a fact id wins. The ledger refuses a repair for a fact id that it knows, and it refuses an assert for a fact id that has a repair event, so a late write fails with an error and the ledger never believes a fact that no store holds. In one server process, a repair of an entry that already has a repair event adds no second event: a retry after a failed removal uses the first event. One sweep runs at a time in a server process. If a store fails a delete and its listing then no longer holds the entry, the sweep treats the delete as done and verifies the entry as usual, so the outcome is `verified`, `stillIndexed`, or `unverified` by the same rules.
|
|
227
|
+
|
|
228
|
+
The result is `{ before, repaired, unlisted, stillHeld, unrecorded }`:
|
|
229
|
+
|
|
230
|
+
- `before` is the cutoff that the sweep used, as an ISO instant.
|
|
231
|
+
- `repaired` is `[{ store, externalId, factId, outcome, eventId }]`.
|
|
232
|
+
- `unlisted` is the names of the stores that have no `list`.
|
|
233
|
+
- `stillHeld` is the errors of removals that failed. It also holds `<store>: cannot list: <error>` for a store whose listing failed. The sweep goes on with the other stores.
|
|
234
|
+
- `unrecorded` is `[{ store, externalId, factId, error }]`: the entries that the sweep did not remove, because the ledger did not take the repair event. The next sweep tries them again.
|
|
235
|
+
|
|
236
|
+
The result is an error when `stillHeld` or `unrecorded` is not empty. Run the sweep again after you fix the store or the ledger.
|
|
237
|
+
|
|
238
|
+
Limits:
|
|
239
|
+
|
|
240
|
+
- An entry whose `storedAt` is missing or does not parse counts as young. The sweep never removes it. When the metadata has no `storedAt`, the adapters fall back to the creation time of the store: the `created_at` column for pgvector, and the creation time that the client reports for Mem0, Zep, Letta, and LangGraph. Cognee has a fallback only if its listing has a creation time. Letta records `storedAt` in the tag `stored:<iso>`.
|
|
241
|
+
- One store scope belongs to one ledger. A store scope is a pgvector table, a Mem0 user, a Zep user or graph, a Letta agent with its exact tag set, a LangGraph namespace, or a Cognee dataset. Two ledgers that share a scope already leak recall between them, and a repair on one ledger removes the entries of the other.
|
|
242
|
+
- A change to the tag set of a Letta store strands the passages that the store wrote under the old tags. The exact tag set is the scope, as the namespace is for LangGraph. The new store does not list the old passages, and `memory.repair` cannot remove the orphans among them. `lettaStore` throws on a tag that is `agent-custody` or starts with `fact:`, `space:`, `stored:`, or `receipt:`.
|
|
243
|
+
- The clocks of the memory servers must agree to within a few minutes. `storedAt` comes from the clock of the writer, and the cutoff comes from the clock of the repairer.
|
|
244
|
+
- A store without `list` is reported in `unlisted` and is not swept. Mem0, Zep, and Letta get `list` when their client has a method to list entries.
|
|
245
|
+
- The sweep finds only entries that carry custody metadata (`source: "agent-custody"` and a fact id). It does not touch other entries in the store.
|
|
246
|
+
- The Cognee data listing carries no text, so its entries have empty `text`. The adapter verifies by id, so this does not matter for the sweep.
|
|
172
247
|
|
|
173
248
|
## Scoring memory mutations
|
|
174
249
|
|
|
@@ -218,16 +293,19 @@ The ledger refuses to supersede a fact that is unknown, already superseded, or r
|
|
|
218
293
|
## Layout
|
|
219
294
|
|
|
220
295
|
```
|
|
221
|
-
src/ledger.ts the fact record, the event kinds, as-of queries, supersession, retraction, forget, holds, sweeps
|
|
296
|
+
src/ledger.ts the fact record, the event kinds, as-of queries, supersession, retraction, forget, holds, sweeps, repairs
|
|
222
297
|
src/storage.ts the store interface and its three stores: JSONL (default, auditable), SQLite (indexed, one machine), Postgres (shared); chosen by path or URL
|
|
223
298
|
src/server.ts the ledger as MCP tools; source and actor taken from the gateway's _meta
|
|
224
299
|
src/http.ts the memory server over Streamable HTTP with bearer auth, for a shared ledger
|
|
225
300
|
src/explain.ts one action explained: the ten answers from a receipt and the ledger, and the signed action pack
|
|
226
|
-
src/review.ts the review
|
|
301
|
+
src/review.ts the searchable review console: explain pages and portable case downloads, served on loopback or written as files
|
|
302
|
+
src/search.ts exact transaction, customer, agent and time filters over the public receipt view
|
|
303
|
+
src/case-file.ts portable HTML/JSON evidence with public keys, fresh offline verification and the ten answers
|
|
304
|
+
src/verify-web.ts the browser verifier embedded in portable HTML case files
|
|
227
305
|
src/pack.ts the custody pack: build, sign, verify, format
|
|
228
|
-
src/cli.ts agent-custody-memory serve (stdio or --http, with --retention and --forget-key-env), sweep (ledger-only or --via a gateway), eval, explain, review, pack, export, blast
|
|
306
|
+
src/cli.ts agent-custody-memory serve (stdio or --http, with --retention and --forget-key-env), sweep (ledger-only or --via a gateway), repair (--via a gateway), eval, explain, review, pack, export, blast
|
|
229
307
|
src/blast.ts blast radius: from receipts' consumed facts and the ledger's source receipts, forward
|
|
230
|
-
src/stores.ts write-through adapters: Mem0, Zep, pgvector, Letta, a LangGraph store (LangMem), and Cognee, and the Store interface for others
|
|
308
|
+
src/stores.ts write-through adapters: Mem0, Zep, pgvector, Letta, a LangGraph store (LangMem), and Cognee, and the Store interface (put, delete, verifyDeleted, list) for others
|
|
231
309
|
src/evals.ts the memory-mutation harness: scenarios, scoring, report
|
|
232
310
|
src/evals-ledger.ts the ledger and a naive overwrite store behind the harness interface
|
|
233
311
|
src/evals-file.ts scenario files, validated; signed eval reports and their verification
|
|
@@ -245,10 +323,11 @@ tsconfig.build.json emits dist/ for consumers; the repo itself runs the .ts dir
|
|
|
245
323
|
- The memory server: the ledger as MCP tools behind the receipts gateway, with the source receipt id and the attested actor supplied by the gateway, policy over spaces, and a denial receipt for every refused write.
|
|
246
324
|
- Forget digests are keyed under a server-held secret, or absent on request, so an erased value cannot be guessed back from the file.
|
|
247
325
|
- Retention windows per space in the server, sweeps that default to them, and a `sweep --via` trigger that runs retention through a gateway as a named principal, on any timer.
|
|
248
|
-
- The review
|
|
326
|
+
- The review console: search public receipt fields by transaction, customer, agent or time, inspect the ten answers and verification report, and export a portable HTML/JSON case with fresh offline verification; served on loopback or written as static files.
|
|
249
327
|
- Explain one action: from a receipt id, who, who authorized it, what was allowed, what the agent saw, what it did, why, the evidence, whether it verifies, what depended on it, and what needs reversal; the same as a signed action pack that carries every downstream receipt.
|
|
250
328
|
- The custody pack: a fact's history with receipts, holds, blast radius, and forget certificate as one signed artefact, verified as a whole.
|
|
251
329
|
- Removal verification: after a retraction, forget, or sweep the server asks each store's search whether the value still surfaces and records verified, stillIndexed, unverified, or failed per store, in the receipt.
|
|
330
|
+
- Repair of a failed ledger append: `memory.repair` and `repair --via` find the store entries that the ledger has no fact for, remove and verify them, and record a `repair` event under the entry's fact id. The Store interface takes a `StoreEntry` and has an optional `list`.
|
|
252
331
|
- Retention and legal hold: a receipted sweep forgets what was learned before an instant and reaches the stores; a hold refuses forget and sweep until released, as events on the fact's history.
|
|
253
332
|
- Value-level quarantine: a write may cite a fact the gateway fetched itself; the value must match it and the fact is then `verified`, the provenance level above attested, or the write is refused.
|
|
254
333
|
- Attested executions: with a key, the memory server signs its results for the gateway's receipt, so a verifier holding its public key sees memory calls as attested.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type VerifyOptions, type VerifyResult } from "@agent-custody/receipts";
|
|
2
|
+
import { type ActionPack, type ActionPackCheck } from "./explain.ts";
|
|
3
|
+
import type { Ledger } from "./ledger.ts";
|
|
4
|
+
export interface CaseFileOptions {
|
|
5
|
+
receiptsDir: string;
|
|
6
|
+
ledger?: Ledger;
|
|
7
|
+
/** Public keys only. Capture keys, disclosures, salts, and provider secrets are deliberately unsupported. */
|
|
8
|
+
keys?: Pick<VerifyOptions, "issuerKeys" | "principalKeys" | "approvalKeys" | "logKeys" | "upstreamKeys" | "logId">;
|
|
9
|
+
}
|
|
10
|
+
export interface CaseFileKey {
|
|
11
|
+
keyid: string;
|
|
12
|
+
pem: string;
|
|
13
|
+
}
|
|
14
|
+
export interface CaseFileKeys {
|
|
15
|
+
issuerKeys: CaseFileKey[];
|
|
16
|
+
principalKeys: CaseFileKey[];
|
|
17
|
+
approvalKeys: CaseFileKey[];
|
|
18
|
+
logKeys: CaseFileKey[];
|
|
19
|
+
upstreamKeys: CaseFileKey[];
|
|
20
|
+
logId?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface CaseFileVerification {
|
|
23
|
+
ok: boolean;
|
|
24
|
+
/** False when receipts/beliefs are absent or unknown, consumed ids are withheld, or no ledger was supplied. */
|
|
25
|
+
complete: boolean;
|
|
26
|
+
trust: "bundled" | "independent" | "none";
|
|
27
|
+
checks: ActionPackCheck[];
|
|
28
|
+
receipts: Record<string, VerifyResult>;
|
|
29
|
+
/** The ten answers rebuilt from the signed receipt and the file's ledger snapshot. A reader trusts these, never a saved copy. */
|
|
30
|
+
answers?: string;
|
|
31
|
+
}
|
|
32
|
+
export interface CaseFile {
|
|
33
|
+
version: "0.1";
|
|
34
|
+
generatedAt: string;
|
|
35
|
+
receiptId: string;
|
|
36
|
+
withLedger: boolean;
|
|
37
|
+
pack: ActionPack;
|
|
38
|
+
keys: CaseFileKeys;
|
|
39
|
+
/** Exporter snapshot, not a separately signed assertion about the ledger. */
|
|
40
|
+
explanation: string;
|
|
41
|
+
/** Informational export-time report. Verification always recomputes this. */
|
|
42
|
+
verification: CaseFileVerification;
|
|
43
|
+
}
|
|
44
|
+
export declare function buildCaseFile(options: CaseFileOptions, receiptId: string): Promise<CaseFile>;
|
|
45
|
+
/** Reads the case file from the `case-data` script of a rendered `.case.html`. It does not validate: `verifyCaseFile` does. */
|
|
46
|
+
export declare function parseCaseHtml(html: string): CaseFile;
|
|
47
|
+
/** Checks signed receipts and their embedded authorizations/proofs afresh. The exporter report is never trusted. */
|
|
48
|
+
export declare function verifyCaseFile(file: CaseFile, trustedKeys?: CaseFileOptions["keys"]): CaseFileVerification;
|
|
49
|
+
/**
|
|
50
|
+
* Checks a rendered `.case.html`. The data in the page is checked as for the JSON. The page itself is checked too: it must be
|
|
51
|
+
* byte for byte what the data renders, so a changed visible answer, or a second copy of the data, fails. A page from another
|
|
52
|
+
* build of this package fails as well; then the reader trusts the rebuilt `answers` and not the page.
|
|
53
|
+
*/
|
|
54
|
+
export declare function verifyCaseHtml(html: string, trustedKeys?: CaseFileOptions["keys"]): CaseFileVerification;
|
|
55
|
+
/** A single local HTML file: no server, fetch, imported scripts, fonts, images, secrets, or restored values. */
|
|
56
|
+
export declare function renderCaseFile(file: CaseFile): string;
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// A portable evidence file. Its public keys travel with the evidence; their presence is not a trust anchor.
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import * as nodeModule from "node:module";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { keyidOf, publicKeyFromPem, publicKeyToPem, verifyBundle } from "@agent-custody/receipts";
|
|
8
|
+
import { buildActionPack, formatExplain } from "./explain.js";
|
|
9
|
+
// Keep this pure and self-contained: the same validation function runs inside the offline page.
|
|
10
|
+
function caseProblem(file) {
|
|
11
|
+
const object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
12
|
+
const id = (v) => typeof v === "string" && /^[0-9a-f-]{36}$/.test(v);
|
|
13
|
+
const fact = (f) => object(f) && typeof f.factId === "string" && object(f.source) && (f.source.receiptId === null || id(f.source.receiptId));
|
|
14
|
+
const summary = (r) => object(r) && id(r.receiptId);
|
|
15
|
+
if (!object(file) || file.version !== "0.1" || !id(file.receiptId) || typeof file.generatedAt !== "string" || typeof file.withLedger !== "boolean" || typeof file.explanation !== "string")
|
|
16
|
+
return "malformed case file";
|
|
17
|
+
const p = file.pack;
|
|
18
|
+
if (!object(p) || p.version !== "0.1" || p.receiptId !== file.receiptId || !object(p.receipt) || !object(p.receipts))
|
|
19
|
+
return "case file and action pack must name the same receipt";
|
|
20
|
+
if (!object(p.consumed) || !Array.isArray(p.consumed.facts) || !p.consumed.facts.every(fact) || !Array.isArray(p.consumed.unknown) || !p.consumed.unknown.every((v) => typeof v === "string") || typeof p.consumedWithheld !== "boolean" || !Array.isArray(p.written) || !p.written.every(fact) || !object(p.status))
|
|
21
|
+
return "malformed belief snapshot";
|
|
22
|
+
const d = p.downstream;
|
|
23
|
+
if (!object(d) || !Array.isArray(d.receipts) || !d.receipts.every(summary) || !Array.isArray(d.withheld) || !d.withheld.every(summary) || !Array.isArray(d.derivedFacts) || !d.derivedFacts.every(fact) || !Array.isArray(d.stillBelieved) || !d.stillBelieved.every(fact) || !Array.isArray(p.missingReceipts) || !p.missingReceipts.every(id))
|
|
24
|
+
return "malformed downstream snapshot";
|
|
25
|
+
if (Object.keys(p.receipts).some((k) => !id(k)) || Object.values(p.receipts).some((b) => !object(b)))
|
|
26
|
+
return "malformed receipt map";
|
|
27
|
+
if (!object(file.keys))
|
|
28
|
+
return "malformed public key set";
|
|
29
|
+
for (const role of ["issuerKeys", "principalKeys", "approvalKeys", "logKeys", "upstreamKeys"]) {
|
|
30
|
+
if (!Array.isArray(file.keys[role]) || file.keys[role].some((k) => !object(k) || typeof k.keyid !== "string" || !/^[0-9a-f]{64}$/.test(k.keyid) || typeof k.pem !== "string" || !/^-----BEGIN PUBLIC KEY-----[\s\S]*-----END PUBLIC KEY-----\s*$/.test(k.pem)))
|
|
31
|
+
return "malformed public keys (only public SPKI PEM is accepted)";
|
|
32
|
+
}
|
|
33
|
+
if (file.keys.logId !== undefined && typeof file.keys.logId !== "string")
|
|
34
|
+
return "malformed log id";
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
function citedIds(pack) {
|
|
38
|
+
return [...new Set([...pack.downstream.receipts.map((r) => r.receiptId), ...pack.downstream.withheld.map((r) => r.receiptId), ...[...pack.consumed.facts, ...pack.written, ...pack.downstream.derivedFacts].map((f) => f.source.receiptId).filter((id) => !!id)])];
|
|
39
|
+
}
|
|
40
|
+
export async function buildCaseFile(options, receiptId) {
|
|
41
|
+
if (!/^[0-9a-f-]{36}$/.test(receiptId))
|
|
42
|
+
throw new Error("invalid receipt id");
|
|
43
|
+
// No capture key is accepted here: the portable file preserves the issued private view.
|
|
44
|
+
const pack = await buildActionPack(options.receiptsDir, receiptId, options.ledger);
|
|
45
|
+
// A withheld consumed-id list still cites a receipt: include its signed evidence and keep the caveat.
|
|
46
|
+
for (const id of citedIds(pack)) {
|
|
47
|
+
if (!/^[0-9a-f-]{36}$/.test(id))
|
|
48
|
+
throw new Error("invalid cited receipt id");
|
|
49
|
+
if (id === receiptId || Object.hasOwn(pack.receipts, id))
|
|
50
|
+
continue;
|
|
51
|
+
try {
|
|
52
|
+
pack.receipts[id] = JSON.parse(readFileSync(join(options.receiptsDir, `${id}.json`), "utf8"));
|
|
53
|
+
pack.missingReceipts = pack.missingReceipts.filter((missing) => missing !== id);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
if (!pack.missingReceipts.includes(id))
|
|
57
|
+
pack.missingReceipts.push(id);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const keys = { issuerKeys: [], principalKeys: [], approvalKeys: [], logKeys: [], upstreamKeys: [] };
|
|
61
|
+
for (const role of ["issuerKeys", "principalKeys", "approvalKeys", "logKeys", "upstreamKeys"]) {
|
|
62
|
+
keys[role] = (options.keys?.[role] ?? []).map((key) => {
|
|
63
|
+
if (key.publicKey.type !== "public" || key.publicKey.asymmetricKeyType !== "ed25519" || keyidOf(key.publicKey) !== key.keyid)
|
|
64
|
+
throw new Error(`invalid ${role} public key or fingerprint`);
|
|
65
|
+
return { keyid: key.keyid, pem: publicKeyToPem(key.publicKey) };
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
if (options.keys?.logId !== undefined)
|
|
69
|
+
keys.logId = options.keys.logId;
|
|
70
|
+
const file = {
|
|
71
|
+
version: "0.1", generatedAt: new Date().toISOString(), receiptId, withLedger: !!options.ledger, pack, keys,
|
|
72
|
+
explanation: "", verification: { ok: false, complete: false, trust: "none", checks: [], receipts: {} },
|
|
73
|
+
};
|
|
74
|
+
// The answers carry the receipt's verdict, and the verification checks the answers. Verify once to get the verdict.
|
|
75
|
+
file.explanation = formatExplain(pack, verifyCaseFile(file).receipts[receiptId] ?? null, file.withLedger);
|
|
76
|
+
file.verification = verifyCaseFile(file);
|
|
77
|
+
return file;
|
|
78
|
+
}
|
|
79
|
+
/** Reads the case file from the `case-data` script of a rendered `.case.html`. It does not validate: `verifyCaseFile` does. */
|
|
80
|
+
export function parseCaseHtml(html) {
|
|
81
|
+
// The renderer escapes every "<" in the data, so the first closing tag ends the data.
|
|
82
|
+
const data = /<script id="case-data" type="application\/json">([\s\S]*?)<\/script>/.exec(html)?.[1];
|
|
83
|
+
if (data === undefined)
|
|
84
|
+
throw new Error("this HTML file has no case-data script");
|
|
85
|
+
return JSON.parse(data);
|
|
86
|
+
}
|
|
87
|
+
/** Checks signed receipts and their embedded authorizations/proofs afresh. The exporter report is never trusted. */
|
|
88
|
+
export function verifyCaseFile(file, trustedKeys) {
|
|
89
|
+
const checks = [];
|
|
90
|
+
const receipts = Object.create(null);
|
|
91
|
+
let complete = false;
|
|
92
|
+
let rebuilt;
|
|
93
|
+
let trust = "none";
|
|
94
|
+
const add = (name, ok, detail) => checks.push({ name, ok, ...(detail ? { detail } : {}) });
|
|
95
|
+
try {
|
|
96
|
+
const problem = caseProblem(file);
|
|
97
|
+
add("case file structure", !problem, problem ?? undefined);
|
|
98
|
+
if (problem)
|
|
99
|
+
return { ok: false, complete, trust, checks, receipts };
|
|
100
|
+
const imported = (role) => file.keys[role].map((key) => {
|
|
101
|
+
const ref = publicKeyFromPem(key.pem);
|
|
102
|
+
if (ref.publicKey.type !== "public" || ref.publicKey.asymmetricKeyType !== "ed25519" || ref.keyid !== key.keyid)
|
|
103
|
+
throw new Error(`${role} public key fingerprint mismatch`);
|
|
104
|
+
return ref;
|
|
105
|
+
});
|
|
106
|
+
const bundled = { issuerKeys: imported("issuerKeys"), principalKeys: imported("principalKeys"), approvalKeys: imported("approvalKeys"), logKeys: imported("logKeys"), upstreamKeys: imported("upstreamKeys"), ...(file.keys.logId === undefined ? {} : { logId: file.keys.logId }) };
|
|
107
|
+
// Validate the supplied independent fingerprints too; don't silently accept a wrongly labelled trust anchor.
|
|
108
|
+
const keys = trustedKeys ?? bundled;
|
|
109
|
+
for (const role of ["issuerKeys", "principalKeys", "approvalKeys", "logKeys", "upstreamKeys"]) {
|
|
110
|
+
for (const key of keys[role] ?? [])
|
|
111
|
+
if (key.publicKey.type !== "public" || key.publicKey.asymmetricKeyType !== "ed25519" || keyidOf(key.publicKey) !== key.keyid)
|
|
112
|
+
throw new Error(`${role} public key fingerprint mismatch`);
|
|
113
|
+
}
|
|
114
|
+
const hasKeys = keys.issuerKeys.length > 0;
|
|
115
|
+
trust = !hasKeys ? "none" : trustedKeys ? "independent" : "bundled";
|
|
116
|
+
add("issuer public keys supplied", hasKeys, hasKeys ? (trustedKeys ? "checked against independently supplied keys" : "bundled keys only; confirm fingerprints through an independent channel") : "NOT CHECKED: no issuer public keys supplied");
|
|
117
|
+
for (const [id, bundle] of [[file.receiptId, file.pack.receipt], ...Object.entries(file.pack.receipts)]) {
|
|
118
|
+
let result;
|
|
119
|
+
try {
|
|
120
|
+
result = verifyBundle(bundle, keys);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
result = { ok: false, checks: [{ name: "well-formed receipt bundle", ok: false }], statement: null };
|
|
124
|
+
}
|
|
125
|
+
receipts[id] = result;
|
|
126
|
+
add(`receipt ${id} verifies`, result.ok, result.checks.filter((c) => !c.ok).map((c) => c.name).join(", "));
|
|
127
|
+
add(`receipt ${id} matches its id`, result.statement?.predicate.receiptId === id);
|
|
128
|
+
}
|
|
129
|
+
// The saved answers are text from the exporter. Most of them come from signed data, so rebuild them from the receipt.
|
|
130
|
+
// The exporter wrote the verdict line with the bundled keys, so rebuild it with the same keys.
|
|
131
|
+
let own = receipts[file.receiptId];
|
|
132
|
+
if (trustedKeys) {
|
|
133
|
+
try {
|
|
134
|
+
own = verifyBundle(file.pack.receipt, bundled);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
own = undefined;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
let answers = null;
|
|
141
|
+
try {
|
|
142
|
+
answers = formatExplain(file.pack, own ?? null, file.withLedger);
|
|
143
|
+
}
|
|
144
|
+
catch { /* a receipt that cannot be decoded has no answers to compare */ }
|
|
145
|
+
if (answers !== null)
|
|
146
|
+
rebuilt = answers;
|
|
147
|
+
// The belief, dependency and reversal answers come from the pack's ledger snapshot, which nobody signs. Say so in the name.
|
|
148
|
+
add("ten answers match the signed receipt and the unsigned ledger snapshot", answers !== null && answers === file.explanation, answers === null ? "the receipt cannot be read" : answers === file.explanation ? "the lines on beliefs, dependencies and reversals come from the unsigned ledger snapshot in this file and are not attested" : "the saved answers differ from the answers that the signed receipt and the snapshot give");
|
|
149
|
+
const missing = citedIds(file.pack).filter((id) => id !== file.receiptId && !Object.hasOwn(file.pack.receipts, id));
|
|
150
|
+
add("all cited receipts included", !file.pack.missingReceipts.length && !missing.length, [...new Set([...file.pack.missingReceipts, ...missing])].join(", "));
|
|
151
|
+
add("written beliefs cite this receipt", file.pack.written.every((f) => f.source.receiptId === file.receiptId));
|
|
152
|
+
complete = !file.pack.missingReceipts.length && !missing.length && !file.pack.consumedWithheld && !file.pack.consumed.unknown.length && !file.pack.downstream.withheld.length && file.withLedger;
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
add("case file is readable", false, error instanceof Error ? error.message : "malformed artifact");
|
|
156
|
+
}
|
|
157
|
+
return { ok: checks.every((c) => c.ok), complete, trust, checks, receipts, ...(rebuilt === undefined ? {} : { answers: rebuilt }) };
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Checks a rendered `.case.html`. The data in the page is checked as for the JSON. The page itself is checked too: it must be
|
|
161
|
+
* byte for byte what the data renders, so a changed visible answer, or a second copy of the data, fails. A page from another
|
|
162
|
+
* build of this package fails as well; then the reader trusts the rebuilt `answers` and not the page.
|
|
163
|
+
*/
|
|
164
|
+
export function verifyCaseHtml(html, trustedKeys) {
|
|
165
|
+
const file = parseCaseHtml(html);
|
|
166
|
+
const result = verifyCaseFile(file, trustedKeys);
|
|
167
|
+
let same = false;
|
|
168
|
+
try {
|
|
169
|
+
same = renderCaseFile(file) === html;
|
|
170
|
+
}
|
|
171
|
+
catch { /* data that cannot be rendered is not what the page shows */ }
|
|
172
|
+
const check = { name: "page is exactly what its case data renders", ok: same, ...(same ? {} : { detail: "the page differs from its data (an edit, a second copy of the data, or another build); do not trust the page, trust the answers printed here" }) };
|
|
173
|
+
return { ...result, ok: result.ok && same, checks: [check, ...result.checks] };
|
|
174
|
+
}
|
|
175
|
+
let cachedBrowserSource;
|
|
176
|
+
function browserVerifierSource() {
|
|
177
|
+
if (cachedBrowserSource !== undefined)
|
|
178
|
+
return cachedBrowserSource;
|
|
179
|
+
// Published packages include the compiled canonical verifier. Source checkouts use Node's native eraser.
|
|
180
|
+
let source;
|
|
181
|
+
try {
|
|
182
|
+
source = readFileSync(fileURLToPath(new URL("./verify-web.js", import.meta.url)), "utf8");
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
const typescript = readFileSync(fileURLToPath(new URL("./verify-web.ts", import.meta.url)), "utf8");
|
|
186
|
+
if (typeof nodeModule.stripTypeScriptTypes === "function")
|
|
187
|
+
source = nodeModule.stripTypeScriptTypes(typescript, { mode: "strip" });
|
|
188
|
+
else {
|
|
189
|
+
const bun = globalThis.Bun;
|
|
190
|
+
if (!bun?.Transpiler)
|
|
191
|
+
throw new Error("Build @agent-custody/state first, or render from source using Node 22.13+ or Bun");
|
|
192
|
+
source = new bun.Transpiler({ loader: "ts", target: "browser" }).transformSync(typescript);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
cachedBrowserSource = source.replace(/^export\s+(?=(?:async\s+)?(?:function|const|let|class)\b)/gm, "").replace(/^export\s*\{\s*\};?\s*$/gm, "").replace(/^\/\/# sourceMappingURL=.*$/gm, "");
|
|
196
|
+
return cachedBrowserSource;
|
|
197
|
+
}
|
|
198
|
+
const escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]);
|
|
199
|
+
/** A single local HTML file: no server, fetch, imported scripts, fonts, images, secrets, or restored values. */
|
|
200
|
+
export function renderCaseFile(file) {
|
|
201
|
+
const report = verifyCaseFile(file);
|
|
202
|
+
const problem = caseProblem(file);
|
|
203
|
+
const data = JSON.stringify(file).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
204
|
+
// HTML normalizes CRLF before CSP hashing in the browser, including files exported on Windows.
|
|
205
|
+
const script = `"use strict";\n${browserVerifierSource()}\nconst caseProblem = ${caseProblem.toString()};\n${BROWSER_CASE_SCRIPT}`.replace(/\r\n?/g, "\n");
|
|
206
|
+
const hash = createHash("sha256").update(script).digest("base64");
|
|
207
|
+
const text = (value) => escapeHtml(typeof value === "string" ? value : JSON.stringify(value, null, 2));
|
|
208
|
+
const keyText = problem ? "Malformed public key set" : Object.entries(file.keys).filter(([role]) => role !== "logId").map(([role, keys]) => `${role}:\n${keys.map((key) => `SHA-256 ${key.keyid}\n${key.pem}`).join("\n") || "(none)"}`).join("\n\n");
|
|
209
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${hash}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><title>Custody case ${text(file?.receiptId ?? "invalid")}</title><style>body{font:16px/1.6 system-ui,sans-serif;max-width:1040px;margin:2rem auto;padding:0 1rem;color:#202020;background:#faf9f6}h1,h2{line-height:1.2}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#fff;border:1px solid #ccc;border-radius:6px;padding:1rem}button{font:inherit;padding:.5rem 1rem;cursor:pointer}summary{cursor:pointer}#fresh-report{border-left:4px solid #a66c00}small{color:#555}</style></head><body><h1>Custody case file</h1><p>Receipt <code>${text(file?.receiptId ?? "invalid")}</code>. Saved ${text(file?.generatedAt ?? "unknown")}.</p><p>This file contains signed receipts, embedded signed authorizations, log heads and inclusion proofs, and public keys. It works offline when opened locally.</p><p><strong>Trust:</strong> bundled keys demonstrate internal consistency. Confirm each SHA-256 fingerprint with the issuer, principal, log operator, or upstream through an independent channel before trusting their identity. A signed receipt records a claim about execution; it does not by itself prove that an external side effect occurred.</p><p>Withheld values remain commitments; their hidden contents are not recomputed here. The ten answers and belief/ledger data are an exporter snapshot, not independently attested facts. The exporter report below is historical; the browser recomputes signatures, authorizations, digests and inclusion proofs.</p><h2>Fresh browser verification</h2><p><strong>This page does not check itself independently.</strong> Its result comes from the script in this same file, and whoever edits the file can edit the script and the answers too. This page does not compare the ten answers with the receipts. To check this file, run <code>agent-custody-memory review --verify-case <this file> --issuer-key <issuer.pub> --principal-key <principal.pub></code>. The command reads this .html file and checks that the page is exactly what its data renders. It prints the ten answers that it rebuilds from the signed receipt. Trust the answers that the command prints, not the answers on this page.</p><button id="verify" type="button">Verify again offline</button><pre id="fresh-report" role="status" aria-live="polite">NOT CHECKED: waiting for WebCrypto verification. If this stays unchanged, this browser could not run the verifier.</pre><noscript><p>NOT CHECKED: JavaScript is disabled. Use the independent command-line verifier: <code>agent-custody-memory review --verify-case <this file> --issuer-key <issuer.pub> --principal-key <principal.pub></code>.</p></noscript><h2>Ten answers (saved text, NOT CHECKED in this page)</h2><pre>${text(problem ?? file.explanation)}</pre><h2>Export-time verification (recomputed when rendering)</h2><pre>${text(report)}</pre><h2>Public keys and fingerprints</h2><pre>${text(keyText)}</pre><details><summary>All receipts, authorizations, proofs and ledger snapshot (JSON)</summary><pre>${text(file)}</pre></details><script id="case-data" type="application/json">${data}</script><script>${script}</script></body></html>`;
|
|
210
|
+
}
|
|
211
|
+
const BROWSER_CASE_SCRIPT = `
|
|
212
|
+
const caseFile = JSON.parse(document.getElementById("case-data").textContent);
|
|
213
|
+
async function verifyCaseOffline() {
|
|
214
|
+
const output = document.getElementById("fresh-report");
|
|
215
|
+
output.textContent = "CHECKING: fresh WebCrypto verification…";
|
|
216
|
+
const lines = [];
|
|
217
|
+
let good = true;
|
|
218
|
+
const check = (name, ok, detail) => { if (!ok) good = false; lines.push((ok ? "PASS " : "FAIL ") + name + (detail ? " (" + detail + ")" : "")); };
|
|
219
|
+
try {
|
|
220
|
+
const problem = caseProblem(caseFile);
|
|
221
|
+
if (problem) throw new Error(problem);
|
|
222
|
+
if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error("WebCrypto is unavailable in this browser. Verification was not performed.");
|
|
223
|
+
const keys = {};
|
|
224
|
+
for (const role of ["issuerKeys", "principalKeys", "approvalKeys", "logKeys", "upstreamKeys"]) {
|
|
225
|
+
keys[role] = [];
|
|
226
|
+
for (const ref of caseFile.keys[role]) {
|
|
227
|
+
const key = await publicKeyFromPem(ref.pem);
|
|
228
|
+
if (key.keyid !== ref.keyid) throw new Error(role + " public key fingerprint mismatch");
|
|
229
|
+
keys[role].push(key);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (caseFile.keys.logId !== undefined) keys.logId = caseFile.keys.logId;
|
|
233
|
+
check("issuer public keys supplied", keys.issuerKeys.length > 0, keys.issuerKeys.length ? "BUNDLED KEYS ONLY: confirm fingerprints independently" : "NOT CHECKED: no issuer public keys supplied");
|
|
234
|
+
const pack = caseFile.pack;
|
|
235
|
+
for (const [id, bundle] of [[caseFile.receiptId, pack.receipt], ...Object.entries(pack.receipts)]) {
|
|
236
|
+
lines.push("", "Receipt " + id);
|
|
237
|
+
let result;
|
|
238
|
+
try { result = await verifyBundle(bundle, keys); }
|
|
239
|
+
catch (error) { result = { ok: false, statement: null, checks: [{ name: "well-formed receipt bundle", ok: false, detail: String(error) }] }; }
|
|
240
|
+
for (const c of result.checks) check(c.name, c.ok, c.detail);
|
|
241
|
+
check("receipt matches its id", result.statement?.predicate.receiptId === id);
|
|
242
|
+
if (!result.ok) good = false;
|
|
243
|
+
}
|
|
244
|
+
const cited = [...pack.downstream.receipts, ...pack.downstream.withheld].map(r => r.receiptId).concat([...pack.consumed.facts, ...pack.written, ...pack.downstream.derivedFacts].map(f => f.source.receiptId).filter(Boolean));
|
|
245
|
+
const missing = cited.filter(id => id !== caseFile.receiptId && !Object.hasOwn(pack.receipts, id));
|
|
246
|
+
check("all cited receipts included", pack.missingReceipts.length === 0 && missing.length === 0, [...new Set([...pack.missingReceipts, ...missing])].join(", "));
|
|
247
|
+
check("written beliefs cite this receipt", pack.written.every(f => f.source.receiptId === caseFile.receiptId));
|
|
248
|
+
const incomplete = missing.length || pack.missingReceipts.length || pack.consumedWithheld || pack.consumed.unknown.length || pack.downstream.withheld.length || !caseFile.withLedger;
|
|
249
|
+
lines.push("", good ? "RESULT: VERIFIED AGAINST BUNDLED KEYS (confirm fingerprints independently)" : "RESULT: NOT VERIFIED");
|
|
250
|
+
if (incomplete) lines.push("INCOMPLETE: missing evidence, withheld consumed ids, or no ledger. Dependency and reversal answers remain limited.");
|
|
251
|
+
lines.push("This checks signed evidence, not external side effects or the exporter's ledger snapshot.");
|
|
252
|
+
lines.push("NOT CHECKED here: the ten answers. They are the exporter's saved text. This result is not independent, because the script is in the same file as the data. Run: agent-custody-memory review --verify-case <this file> --issuer-key <issuer.pub> --principal-key <principal.pub>");
|
|
253
|
+
} catch (error) { lines.push("RESULT: NOT VERIFIED / NOT CHECKED: " + String(error)); }
|
|
254
|
+
output.textContent = lines.join("\\n");
|
|
255
|
+
}
|
|
256
|
+
document.getElementById("verify").addEventListener("click", verifyCaseOffline);
|
|
257
|
+
void verifyCaseOffline();
|
|
258
|
+
`;
|