@agent-custody/state 0.1.5 → 0.1.7

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
@@ -22,7 +22,7 @@ ledger.retract({ factId: a.fact.factId, actor: "user:admin", reason: "poisoned b
22
22
  ledger.asOf({ validAt: "2026-09-01T00:00:00Z", txAt: "2026-09-01T00:00:00Z" });
23
23
  ```
24
24
 
25
- Five runnable examples, all executed by the test suite. [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.
25
+ Six runnable examples, all executed by the test suite. [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.
26
26
 
27
27
  ## The memory server
28
28
 
@@ -45,10 +45,14 @@ In the gateway's config, the memory server is the upstream, and the grant names
45
45
  | `memory.confirm` | lifts a quarantined fact to attested; accepted only through the gateway | `factId` |
46
46
  | `memory.retract` | undoes a belief, keeping it visible to questions about the past | `factId`, `reason` |
47
47
  | `memory.forget` | erases the value from the ledger and every store, keeping the digest; the receipt is the certificate | `factId`, `reason` |
48
+ | `memory.hold`, `memory.release` | legal hold: while it stands the fact cannot be forgotten by request or sweep | `factId`, `reason` |
49
+ | `memory.sweep` | retention: forget what was learned before an instant, in a space or all, skipping held facts, reaching every store | `before`, `space`, `reason` |
48
50
  | `memory.get` | one fact by id in any state, for the gateway's policy lookups | `factId` |
49
51
  | `memory.history` | every event that touched a fact | `factId` |
50
52
 
51
- **Quarantine.** Every fact carries a provenance. 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.
53
+ **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.
54
+
55
+ **Value-level quarantine.** An attested write still carries whatever value the agent chose to write. When the agent can say where a value came from, the gateway's own observation decides. A `memory.write` may name `evidence: { fact, path }`, a fact the gateway fetched itself for this call through its fact-lookup mechanism (a CRM record, say) and optionally a field in it. The memory server compares the value with the observation: equal, and the fact is written as `verified`, the third provenance level, where both the actor and the value are vouched for by something other than the agent; different, and the write is refused. A policy can require evidence for a space (`context.args has evidence`), and `memory.read` with `requireVerified` returns only verified facts. The test suite runs this with a CRM lookup behind the same gateway as the memory server.
52
56
 
53
57
  **Policy over the fact being changed.** The gateway can look up the fact a write supersedes or a retraction targets before deciding, through its fact-lookup mechanism and the `memory.get` tool, and the policy then sees that fact's space, actor, and provenance as observed facts. This is the second half of trust tiers: a self-reported note in the org space can be superseded by anyone the grant allows, while an attested org fact cannot be displaced or retracted except by whoever the policy names. In the gateway config:
54
58
 
@@ -70,17 +74,19 @@ The lookup for writes is optional, so a write that supersedes nothing needs no l
70
74
 
71
75
  **Shared over HTTP.** `agent-custody-memory serve --ledger ./ledger.jsonl --http --port 8790 --token-env MEMORY_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. 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. Bind wider than loopback only behind the token. The test suite runs exactly this: one gateway writer, one direct writer, one ledger.
72
76
 
73
- 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.
77
+ [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.
74
78
 
75
79
  `--allow-direct` lets the server take calls without a gateway; then `source.receiptId` is null and `actor` is whatever the caller said, recorded as such. [examples/03-memory-behind-the-gateway.ts](examples/03-memory-behind-the-gateway.ts) runs the whole loop, including a denied write and a retraction that cites its own receipt.
76
80
 
77
81
  ## Certified forget
78
82
 
79
- A deletion demand is different from a correction. Retract keeps the record; forget erases the value. `memory.forget` removes the fact's value from the ledger file itself, replacing it with the value's digest so the ledger can still prove what it held without holding it, stops believing the fact, and removes it from every store behind the server. The result says exactly what happened: erased from the ledger, removed from which stores, still held by which, with the digest, the actor, and the reason.
83
+ A deletion demand is different from a correction. Retract keeps the record; forget erases the value. `memory.forget` removes the fact's value from the ledger file itself, stops believing the fact, and removes it from every store behind the server. What it keeps in place of the value is a choice, recorded on the event as `digestKind`: a plain `sha256` of the value, which lets the ledger prove what it erased but is guessable for short values such as an email by anyone holding the file; an `hmac-sha256` under a forget key the server holds outside the file (`serve --forget-key-env NAME`), which proves the same to anyone shown the key and nothing to anyone else; or `none`, with `keepDigest: false`, for the case where counsel wants nothing derived from the value retained. Use the keyed form unless you have a reason not to. The result says exactly what happened: erased from the ledger, removed from which stores, still held by which, with the digest, the actor, and the reason.
84
+
85
+ **Retention and legal hold.** `memory.sweep` forgets every fact the ledger learned of before an instant, in one space or all, and removes each from every store; it is retention as a receipted call, with the receipt as the record of what was erased. Retention windows live in the server: `serve --retention 'org=P365D,team:*=P90D,user:*=P30D'`, ISO 8601 durations by space pattern, and a sweep with no `before` uses them per space. To run it on a schedule without a daemon, `agent-custody-memory sweep --via retention-gateway.json --reason "quarterly retention"` spawns that gateway and calls `memory.sweep` through it, so the sweep runs as the principal named in the gateway's grant, a retention job with the single scope `memory.sweep`, and its receipt records when retention ran, by whom, what it erased, and what a hold kept. Any cron, systemd timer, or CI schedule drives that one command. `memory.hold` puts a legal hold on a fact: while it stands, neither a deletion request nor a sweep can forget it, and `memory.release` lifts it. Holds and releases are events with actor, reason, and receipt, so the history of a fact shows the hold as plainly as the write. `agent-custody-memory sweep --ledger ... --before ... --reason ...` runs retention on the ledger file alone, for ledgers with no stores behind them.
80
86
 
81
87
  The certificate is the receipt. Through the gateway, `memory.forget` is a receipted call whose result the gateway observed, so the signed, logged receipt records that the erasure happened, who asked for it, and what the stores answered. Hand that receipt to whoever demanded the deletion; anyone with the gateway's public key can verify it.
82
88
 
83
- What forget does not reach, and the docs will not pretend otherwise: receipts. The receipt that recorded the original write carries the value in its request arguments, and the receipts of reads carry it in their results; they are signed and in a Merkle log, so they cannot be edited. Erasure from the receipt log is a retention policy on the log, and selective redaction of receipts is on the receipts roadmap.
89
+ Receipts are the other place a value lives: the receipt that recorded the write carries it in its request arguments, and the receipts of reads carry it in their results, signed and in a Merkle log. The receipts package's `prune` command is retention for the log: it replaces older leaves with their hashes, so every root and every proof still verifies while the content is gone, and removes the pruned receipts' bundle files. Run it on the same schedule as the sweep.
84
90
 
85
91
  ## Blast radius
86
92
 
@@ -101,6 +107,8 @@ retracted at 2026-09-07T10:12:04.118Z by support-agent: CRM sync bug: account is
101
107
  acct:42 support_tier = "priority" fact e77d… STILL BELIEVED
102
108
  ```
103
109
 
110
+ With the gateway fronting several upstreams, memory and the tools the agent acts with, the radius reaches the actions too: a refund issued after the agent read a belief carries that belief's id and is listed. [examples/06-actions-on-beliefs.ts](examples/06-actions-on-beliefs.ts) shows it.
111
+
104
112
  It is an upper bound by design: a call made after the agent had seen the fact is in the radius whether or not the agent used it, because no receipt can prove what a model attended to. What it never misses is the thing that matters, a downstream action or belief that did depend on the fact. [examples/05-blast-radius.ts](examples/05-blast-radius.ts) runs the whole loop.
105
113
 
106
114
  ## Write-through to the stores you already use
@@ -154,7 +162,7 @@ The ledger refuses to supersede a fact that is unknown, already superseded, or r
154
162
  src/ledger.ts the fact record, the two event kinds, as-of queries, supersession, retraction, JSONL persistence
155
163
  src/server.ts the ledger as MCP tools; source and actor taken from the gateway's _meta
156
164
  src/http.ts the memory server over Streamable HTTP with bearer auth, for a shared ledger
157
- src/cli.ts agent-custody-memory serve (stdio or --http), blast
165
+ src/cli.ts agent-custody-memory serve (stdio or --http, with --retention and --forget-key-env), sweep (ledger-only or --via a gateway), blast
158
166
  src/blast.ts blast radius: from receipts' consumed facts and the ledger's source receipts, forward
159
167
  src/stores.ts write-through adapters: Mem0 and Zep, and the Store interface for others
160
168
  src/evals.ts the memory-mutation harness: scenarios, scoring, report
@@ -171,6 +179,10 @@ tsconfig.build.json emits dist/ for consumers; the repo itself runs the .ts dir
171
179
 
172
180
  - Bitemporal fact ledger with supersession, retraction, as-of and history queries, persisted as JSONL.
173
181
  - 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.
182
+ - Forget digests are keyed under a server-held secret, or absent on request, so an erased value cannot be guessed back from the file.
183
+ - 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.
184
+ - 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.
185
+ - 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.
174
186
  - 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.
175
187
  - The memory server over HTTP: one ledger shared by several gateways and direct writers, bearer-token auth, quarantine live.
176
188
  - Certified forget: `memory.forget` erases a value from the ledger file keeping its digest, stops believing it, removes it from every store, and reports exactly what happened; the gateway's receipt of that call is the certificate.
@@ -182,8 +194,8 @@ tsconfig.build.json emits dist/ for consumers; the repo itself runs the .ts dir
182
194
 
183
195
  **Next, in the order it pays off**
184
196
 
185
- 1. Value-level quarantine: a value that came from untrusted tool output stays quarantined even when the actor is attested, until a second source or a human agrees.
186
- 2. Retention windows and legal hold on the ledger: forget on a schedule, and a hold that refuses forget for named facts until lifted.
187
- 3. A gateway with several upstreams under one grant, so memory and the tools an agent acts with share a session and blast radius reaches the emails sent, not only the beliefs written.
188
- 4. The memory tools from Python, through the sidecar, so SDK-only Python agents can write claimed facts to a shared ledger.
197
+ 1. A storage interface for the ledger with SQLite as the first alternative to JSONL, for durability, concurrent readers, and indexed queries at scale; JSONL stays the default and the auditable export. [Issue #1](https://github.com/ch4r10t33r/agent-custody/issues/1).
198
+ 2. Write-through adapters for Letta, LangMem, and Cognee, one per user who asks. [Issue #4](https://github.com/ch4r10t33r/agent-custody/issues/4).
199
+ 3. The eval harness as a CLI with customer scenario files and a signed report. [Issue #5](https://github.com/ch4r10t33r/agent-custody/issues/5).
200
+ 4. The hosted plane, behind early access: tenanted log, then memory, then reports and a control plane. [Issue #6](https://github.com/ch4r10t33r/agent-custody/issues/6).
189
201
 
package/dist/cli.js CHANGED
@@ -5,14 +5,43 @@ import { createMemoryServer, serveStdio } from "./server.js";
5
5
  import { blastRadius, formatBlastRadius, loadReceipts } from "./blast.js";
6
6
  import { serveMemoryHttp } from "./http.js";
7
7
  import { loadPrivateKey } from "@agent-custody/receipts";
8
+ import { fileURLToPath } from "node:url";
9
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
10
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
11
+ /** The forget key from an environment variable, when named; a named but unset variable is an error at startup. */
12
+ function forgetKeyFrom(envName) {
13
+ if (!envName)
14
+ return {};
15
+ const v = process.env[envName];
16
+ if (!v)
17
+ throw new Error(`forget key: environment variable ${envName} is not set`);
18
+ return { forgetKey: v };
19
+ }
20
+ /** "org=P365D,team:*=P90D" into retention windows. */
21
+ function parseRetention(spec) {
22
+ const out = {};
23
+ for (const part of spec.split(",")) {
24
+ const [pattern, duration] = part.split("=").map((x) => x.trim());
25
+ if (!pattern || !duration)
26
+ throw new Error(`retention: expected space=duration, got "${part}"`);
27
+ out[pattern] = duration;
28
+ }
29
+ return out;
30
+ }
8
31
  const USAGE = `agent-custody-memory <command>
9
32
 
10
- serve --ledger <ledger.jsonl> [--allow-direct] [--key <memory.key>]
33
+ serve --ledger <ledger.jsonl> [--allow-direct] [--key <memory.key>] [--forget-key-env NAME] [--retention 'org=P365D,team:*=P90D']
34
+ --forget-key-env names a secret kept outside the ledger; forgotten values then leave an HMAC, not a guessable hash.
11
35
  the memory server over stdio; run it as the receipts gateway's upstream.
12
36
  --key signs every result for its receipt, so executions verify as attested by this server.
13
37
  By default it refuses calls that did not come through the gateway.
14
38
  serve --ledger <ledger.jsonl> --http [--port 8790] [--host 127.0.0.1] [--token-env NAME] [--allow-direct]
15
39
  the same server shared over HTTP: several gateways, one ledger
40
+ sweep --via <gateway.json> --reason <text> [--before <ISO instant>] [--space <space>] [--no-digest]
41
+ retention as a receipted call: runs memory.sweep through that gateway, as the principal in its grant.
42
+ Without --before, the memory server's --retention windows decide. Put this on a timer.
43
+ sweep --ledger <ledger.jsonl> --before <ISO instant> [--space <space>] --reason <text> [--actor <id>] [--forget-key-env NAME] [--no-digest]
44
+ retention on the ledger file alone, for ledgers with no gateway or stores in front of them.
16
45
  blast --ledger <ledger.jsonl> --receipts <dir> --fact <factId> [--json]
17
46
  everything that relied on a fact: later calls, derived beliefs, and whether it was retracted
18
47
  `;
@@ -20,23 +49,53 @@ async function main(argv) {
20
49
  const [cmd, ...rest] = argv;
21
50
  switch (cmd) {
22
51
  case "serve": {
23
- const { values } = parseArgs({ args: rest, options: { ledger: { type: "string" }, "allow-direct": { type: "boolean", default: false }, http: { type: "boolean", default: false }, port: { type: "string", default: "8790" }, host: { type: "string", default: "127.0.0.1" }, "token-env": { type: "string" }, key: { type: "string" } } });
52
+ const { values } = parseArgs({ args: rest, options: { ledger: { type: "string" }, "allow-direct": { type: "boolean", default: false }, http: { type: "boolean", default: false }, port: { type: "string", default: "8790" }, host: { type: "string", default: "127.0.0.1" }, "token-env": { type: "string" }, key: { type: "string" }, "forget-key-env": { type: "string" }, retention: { type: "string" } } });
24
53
  if (!values.ledger)
25
54
  throw new Error("serve needs --ledger");
26
- const ledger = new Ledger(values.ledger);
55
+ const ledger = new Ledger(values.ledger, forgetKeyFrom(values["forget-key-env"]));
27
56
  const identity = values.key ? loadPrivateKey(values.key) : undefined;
57
+ const retention = values.retention ? parseRetention(values.retention) : undefined;
58
+ const common = { requireGateway: !values["allow-direct"], ...(identity ? { identity } : {}), ...(retention ? { retention } : {}) };
28
59
  if (values.http) {
29
60
  const token = values["token-env"] ? process.env[values["token-env"]] : undefined;
30
61
  if (values["token-env"] && !token)
31
62
  throw new Error(`serve: environment variable ${values["token-env"]} is not set`);
32
- const running = await serveMemoryHttp(ledger, { port: Number(values.port), host: values.host, requireGateway: !values["allow-direct"], ...(token ? { tokens: [token] } : {}), ...(identity ? { identity } : {}) });
63
+ const running = await serveMemoryHttp(ledger, { port: Number(values.port), host: values.host, ...common, ...(token ? { tokens: [token] } : {}) });
33
64
  console.error(`agent-custody-memory: ${running.url} ledger=${values.ledger} events=${ledger.size} ${token ? "bearer token required" : "open"} ${values["allow-direct"] ? "direct calls allowed" : "gateway calls only"}`);
34
65
  await new Promise((resolve) => process.once("SIGINT", resolve));
35
66
  await running.close();
36
67
  return 0;
37
68
  }
38
69
  console.error(`agent-custody-memory: ledger=${values.ledger} events=${ledger.size} ${values["allow-direct"] ? "direct calls allowed" : "gateway calls only"}`);
39
- await serveStdio(createMemoryServer(ledger, { requireGateway: !values["allow-direct"], ...(identity ? { identity } : {}) }));
70
+ await serveStdio(createMemoryServer(ledger, common));
71
+ return 0;
72
+ }
73
+ case "sweep": {
74
+ 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 } } });
75
+ if (values.via) {
76
+ // Retention as a receipted call: spawn the gateway from its config and call memory.sweep through it, so the
77
+ // sweep runs as the principal named in that gateway's grant and its receipt is the record.
78
+ if (!values.reason)
79
+ throw new Error("sweep --via needs --reason");
80
+ const gatewayCli = fileURLToPath(import.meta.resolve("@agent-custody/receipts/cli"));
81
+ const client = new Client({ name: "agent-custody-memory-sweep", version: "0" });
82
+ await client.connect(new StdioClientTransport({ command: process.execPath, args: [gatewayCli, "gateway", "--config", values.via], stderr: "inherit" }));
83
+ try {
84
+ 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 } : {}) } });
85
+ const text = (r.content.find((c) => c.type === "text")?.text) ?? "";
86
+ console.log(text);
87
+ return r.isError ? 1 : 0;
88
+ }
89
+ finally {
90
+ await client.close();
91
+ }
92
+ }
93
+ if (!values.ledger || !values.before || !values.reason)
94
+ throw new Error("sweep needs --ledger, --before, and --reason, or --via <gateway.json> --reason");
95
+ const r = new Ledger(values.ledger, forgetKeyFrom(values["forget-key-env"])).sweep({ before: new Date(values.before).toISOString(), ...(values.space ? { space: values.space } : {}), actor: values.actor, reason: values.reason, ...(values["no-digest"] ? { keepDigest: false } : {}) });
96
+ console.log(`forgot ${r.forgotten.length} fact(s); ${r.held.length} on hold, kept`);
97
+ for (const f of r.forgotten)
98
+ console.log(` ${f.factId} ${f.digestKind}${f.valueDigest ? ` ${f.valueDigest.slice(0, 12)}` : ""}`);
40
99
  return 0;
41
100
  }
42
101
  case "blast": {
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { Ledger } from "./ledger.ts";
2
- export type { AsOf, AssertEvent, AssertInput, ConfirmEvent, ConfirmInput, Fact, FactProvenance, ForgetEvent, ForgetInput, LedgerEvent, RetractEvent, RetractInput, Source } from "./ledger.ts";
3
- export { AGENT_META_KEY, FACTS_META_KEY, RECEIPT_META_KEY, SERVER_VERSION, TOOLS, createMemoryServer, serveStdio } from "./server.ts";
2
+ export type { AsOf, AssertEvent, AssertInput, ConfirmEvent, ConfirmInput, Fact, FactProvenance, DigestKind, ForgetEvent, ForgetInput, HoldEvent, HoldInput, LedgerEvent, SweepInput, RetractEvent, RetractInput, Source } from "./ledger.ts";
3
+ export { AGENT_META_KEY, FACTS_META_KEY, OBSERVED_META_KEY, RECEIPT_META_KEY, SERVER_VERSION, TOOLS, createMemoryServer, durationMs, retentionCutoff, serveStdio } from "./server.ts";
4
4
  export type { MemoryServerOptions } from "./server.ts";
5
5
  export { SCENARIOS, formatReport, runAll, runScenario } from "./evals.ts";
6
6
  export type { MemoryUnderTest, Op, Report, Scenario, ScenarioScore } from "./evals.ts";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Public surface of @agent-custody/state.
2
2
  export { Ledger } from "./ledger.js";
3
- export { AGENT_META_KEY, FACTS_META_KEY, RECEIPT_META_KEY, SERVER_VERSION, TOOLS, createMemoryServer, serveStdio } from "./server.js";
3
+ export { AGENT_META_KEY, FACTS_META_KEY, OBSERVED_META_KEY, RECEIPT_META_KEY, SERVER_VERSION, TOOLS, createMemoryServer, durationMs, retentionCutoff, serveStdio } from "./server.js";
4
4
  export { SCENARIOS, formatReport, runAll, runScenario } from "./evals.js";
5
5
  export { ledgerUnderTest, overwriteStoreUnderTest } from "./evals-ledger.js";
6
6
  export { factMetadata, factText, mem0Store, zepStore } from "./stores.js";
package/dist/ledger.d.ts CHANGED
@@ -3,11 +3,14 @@ export interface Source {
3
3
  receiptId: string | null;
4
4
  }
5
5
  /**
6
- * How far the write can be trusted. attested: it came through the receipts gateway, so the actor is the agent named in
7
- * a human-signed grant and the receipt exists. claimed: it came from somewhere that only says who it is. A claimed
8
- * fact is quarantined: the memory server does not return it by default until an attested party confirms it.
6
+ * How far the write can be trusted.
7
+ * - claimed: it came from somewhere that only says who it is. Quarantined: not returned by default until confirmed.
8
+ * - attested: it came through the receipts gateway, so the actor is the agent named in a human-signed grant and the
9
+ * receipt exists. The value is still what the agent said.
10
+ * - verified: attested, and the value equals what the gateway itself fetched from the source system for this call.
11
+ * The actor and the value are both vouched for by something other than the agent.
9
12
  */
10
- export type FactProvenance = "attested" | "claimed";
13
+ export type FactProvenance = "claimed" | "attested" | "verified";
11
14
  export interface Fact {
12
15
  factId: string;
13
16
  subject: string;
@@ -19,9 +22,10 @@ export interface Fact {
19
22
  actor: string;
20
23
  source: Source;
21
24
  provenance: FactProvenance;
22
- /** present once the value has been erased: the value field is null and this is the digest of what it was */
25
+ /** present once the value has been erased: the value field is null and this is the digest of what it was, or null when none was kept */
23
26
  forgotten?: {
24
- valueDigest: string;
27
+ valueDigest: string | null;
28
+ digestKind: DigestKind;
25
29
  at: string;
26
30
  };
27
31
  /** ids of this fact in the retrieval stores it was written through to, by store name; absent when there are none */
@@ -58,6 +62,11 @@ export interface ConfirmEvent {
58
62
  actor: string;
59
63
  source: Source;
60
64
  }
65
+ /**
66
+ * How a forgotten value's digest was made. sha256 is guessable for short values by anyone holding the file;
67
+ * hmac-sha256 needs the ledger's forget key, kept outside the file; none keeps nothing derived from the value.
68
+ */
69
+ export type DigestKind = "sha256" | "hmac-sha256" | "none";
61
70
  /**
62
71
  * A forget is erasure, not correction. The fact's value is removed from the ledger file itself and replaced by its
63
72
  * digest, so the ledger can still prove which value it held without holding it. The fact stops being believed.
@@ -70,10 +79,21 @@ export interface ForgetEvent {
70
79
  actor: string;
71
80
  reason: string;
72
81
  source: Source;
73
- /** sha256 of the canonical JSON of the erased value */
74
- valueDigest: string;
82
+ /** digest of the canonical JSON of the erased value, per digestKind; null when none was kept */
83
+ valueDigest: string | null;
84
+ digestKind: DigestKind;
85
+ }
86
+ /** A legal hold: while it stands, the fact cannot be forgotten, by request or by retention sweep. Release lifts it. */
87
+ export interface HoldEvent {
88
+ eventId: string;
89
+ kind: "hold" | "release";
90
+ txTime: string;
91
+ factId: string;
92
+ actor: string;
93
+ reason: string;
94
+ source: Source;
75
95
  }
76
- export type LedgerEvent = AssertEvent | RetractEvent | ConfirmEvent | ForgetEvent;
96
+ export type LedgerEvent = AssertEvent | RetractEvent | ConfirmEvent | ForgetEvent | HoldEvent;
77
97
  export interface AssertInput {
78
98
  subject: string;
79
99
  predicate: string;
@@ -98,6 +118,23 @@ export interface ForgetInput {
98
118
  actor: string;
99
119
  reason: string;
100
120
  source?: Source;
121
+ /** false keeps no digest at all; default true */
122
+ keepDigest?: boolean;
123
+ }
124
+ export interface HoldInput {
125
+ factId: string;
126
+ actor: string;
127
+ reason: string;
128
+ source?: Source;
129
+ }
130
+ export interface SweepInput {
131
+ /** every fact the ledger learned of before this instant is forgotten, unless held or already forgotten */
132
+ before: string;
133
+ space?: string;
134
+ actor: string;
135
+ reason: string;
136
+ source?: Source;
137
+ keepDigest?: boolean;
101
138
  }
102
139
  export interface RetractInput {
103
140
  factId: string;
@@ -113,15 +150,18 @@ export interface AsOf {
113
150
  space?: string;
114
151
  subject?: string;
115
152
  predicate?: string;
116
- /** "attested" returns only facts that were attested at txAt; default "all" */
117
- include?: "attested" | "all";
153
+ /** the least provenance to return: "attested" leaves out quarantined facts, "verified" leaves out everything the agent only asserted; default "all" */
154
+ include?: "attested" | "verified" | "all";
118
155
  }
119
156
  export declare class Ledger {
120
157
  private readonly events;
121
158
  private readonly file;
122
159
  private readonly now;
160
+ private readonly forgetKey;
161
+ /** forgetKey: a secret kept outside the file; with it, forgotten values leave an HMAC rather than a plain hash. */
123
162
  constructor(file: string, opts?: {
124
163
  now?: () => Date;
164
+ forgetKey?: string | Buffer;
125
165
  });
126
166
  get size(): number;
127
167
  /** The checks assert makes, without appending. For callers that must do something irreversible before the append. */
@@ -134,6 +174,15 @@ export declare class Ledger {
134
174
  * place, which is the one thing an append-only ledger must do for a deletion demand. Everything else about the fact
135
175
  * stays: who wrote it, when, from which receipt, and now who erased it and why.
136
176
  */
177
+ /** Whether a legal hold currently stands on the fact. */
178
+ held(factId: string): boolean;
179
+ hold(input: HoldInput): HoldEvent;
180
+ release(input: HoldInput): HoldEvent;
181
+ /** 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. */
182
+ sweep(input: SweepInput): {
183
+ forgotten: ForgetEvent[];
184
+ held: string[];
185
+ };
137
186
  forget(input: ForgetInput): ForgetEvent;
138
187
  /** The facts believed at a moment. Valid time answers "was it true then"; transaction time answers "did the ledger know it then". */
139
188
  asOf(q?: AsOf): Fact[];
package/dist/ledger.js CHANGED
@@ -2,16 +2,20 @@
2
2
  // Bitemporal. Valid time is when a fact was true in the world; transaction time is when the ledger learned of it.
3
3
  // Nothing is ever edited in place. Correcting a belief is a new event, so "what did the agent believe at T" is always answerable.
4
4
  import { randomUUID } from "node:crypto";
5
- import { createHash } from "node:crypto";
5
+ import { createHash, createHmac } from "node:crypto";
6
6
  import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
7
  import { dirname } from "node:path";
8
+ const RANK = { claimed: 0, attested: 1, verified: 2 };
8
9
  export class Ledger {
9
10
  events = [];
10
11
  file;
11
12
  now;
13
+ forgetKey;
14
+ /** forgetKey: a secret kept outside the file; with it, forgotten values leave an HMAC rather than a plain hash. */
12
15
  constructor(file, opts = {}) {
13
16
  this.file = file;
14
17
  this.now = opts.now ?? (() => new Date());
18
+ this.forgetKey = opts.forgetKey ? Buffer.from(opts.forgetKey) : null;
15
19
  if (existsSync(file)) {
16
20
  for (const line of readFileSync(file, "utf8").split("\n")) {
17
21
  if (line.trim())
@@ -90,7 +94,7 @@ export class Ledger {
90
94
  throw new Error(`cannot confirm unknown fact ${input.factId}`);
91
95
  if (this.retractedAt(input.factId))
92
96
  throw new Error(`fact ${input.factId} is retracted`);
93
- if (prior.fact.provenance === "attested" || this.confirmedAt(input.factId))
97
+ if (prior.fact.provenance !== "claimed" || this.confirmedAt(input.factId))
94
98
  throw new Error(`fact ${input.factId} is already attested`);
95
99
  const event = { eventId: randomUUID(), kind: "confirm", txTime: this.now().toISOString(), factId: input.factId, actor: input.actor, source: input.source ?? { receiptId: null } };
96
100
  this.append(event);
@@ -101,21 +105,66 @@ export class Ledger {
101
105
  * place, which is the one thing an append-only ledger must do for a deletion demand. Everything else about the fact
102
106
  * stays: who wrote it, when, from which receipt, and now who erased it and why.
103
107
  */
108
+ /** Whether a legal hold currently stands on the fact. */
109
+ held(factId) {
110
+ let held = false;
111
+ for (const e of this.events)
112
+ if ((e.kind === "hold" || e.kind === "release") && e.factId === factId)
113
+ held = e.kind === "hold";
114
+ return held;
115
+ }
116
+ hold(input) {
117
+ const prior = this.factById(input.factId);
118
+ if (!prior)
119
+ throw new Error(`cannot hold unknown fact ${input.factId}`);
120
+ if (prior.fact.forgotten)
121
+ throw new Error(`fact ${input.factId} is already forgotten`);
122
+ if (this.held(input.factId))
123
+ throw new Error(`fact ${input.factId} is already on hold`);
124
+ const event = { eventId: randomUUID(), kind: "hold", txTime: this.now().toISOString(), factId: input.factId, actor: input.actor, reason: input.reason, source: input.source ?? { receiptId: null } };
125
+ this.append(event);
126
+ return event;
127
+ }
128
+ release(input) {
129
+ if (!this.held(input.factId))
130
+ throw new Error(`fact ${input.factId} is not on hold`);
131
+ const event = { eventId: randomUUID(), kind: "release", txTime: this.now().toISOString(), factId: input.factId, actor: input.actor, reason: input.reason, source: input.source ?? { receiptId: null } };
132
+ this.append(event);
133
+ return event;
134
+ }
135
+ /** 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. */
136
+ sweep(input) {
137
+ const forgotten = [];
138
+ const held = [];
139
+ const targets = this.events.filter((e) => e.kind === "assert" && e.txTime < input.before && (input.space === undefined || e.fact.space === input.space) && !e.fact.forgotten);
140
+ for (const e of targets) {
141
+ if (this.held(e.fact.factId)) {
142
+ held.push(e.fact.factId);
143
+ continue;
144
+ }
145
+ forgotten.push(this.forget({ factId: e.fact.factId, actor: input.actor, reason: input.reason, ...(input.source ? { source: input.source } : {}), ...(input.keepDigest === undefined ? {} : { keepDigest: input.keepDigest }) }));
146
+ }
147
+ return { forgotten, held };
148
+ }
104
149
  forget(input) {
105
150
  const prior = this.factById(input.factId);
106
151
  if (!prior)
107
152
  throw new Error(`cannot forget unknown fact ${input.factId}`);
108
153
  if (prior.fact.forgotten)
109
154
  throw new Error(`fact ${input.factId} is already forgotten`);
155
+ if (this.held(input.factId))
156
+ throw new Error(`fact ${input.factId} is on legal hold; release it first`);
110
157
  const txTime = this.now().toISOString();
111
- const valueDigest = createHash("sha256").update(canonical(prior.fact.value)).digest("hex");
158
+ const text = canonical(prior.fact.value);
159
+ const digestKind = input.keepDigest === false ? "none" : this.forgetKey ? "hmac-sha256" : "sha256";
160
+ const valueDigest = digestKind === "none" ? null : digestKind === "hmac-sha256" ? createHmac("sha256", this.forgetKey).update(text).digest("hex") : createHash("sha256").update(text).digest("hex");
112
161
  for (const e of this.events) {
113
162
  if (e.kind === "assert" && e.fact.factId === input.factId) {
114
163
  e.fact.value = null;
115
- e.fact.forgotten = { valueDigest, at: txTime };
164
+ e.fact.forgotten = { valueDigest, digestKind, at: txTime };
116
165
  }
117
166
  }
118
- const event = { eventId: randomUUID(), kind: "forget", txTime, factId: input.factId, actor: input.actor, reason: input.reason, source: input.source ?? { receiptId: null }, valueDigest };
167
+ const event = { eventId: randomUUID(), kind: "forget", txTime, factId: input.factId, actor: input.actor, reason: input.reason, source: input.source ?? { receiptId: null }, valueDigest, digestKind };
119
168
  this.events.push(event);
120
169
  const tmp = `${this.file}.tmp`;
121
170
  writeFileSync(tmp, this.events.map((e) => JSON.stringify(e)).join("\n") + "\n");
@@ -144,7 +193,7 @@ export class Ledger {
144
193
  (q.space === undefined || f.space === q.space) &&
145
194
  (q.subject === undefined || f.subject === q.subject) &&
146
195
  (q.predicate === undefined || f.predicate === q.predicate) &&
147
- (q.include !== "attested" || f.provenance === "attested"));
196
+ (q.include === undefined || q.include === "all" || RANK[f.provenance] >= RANK[q.include]));
148
197
  }
149
198
  /** Every fact ever asserted, with supersession applied and retracted ones included, for audits that must see everything. */
150
199
  facts() {
package/dist/server.d.ts CHANGED
@@ -9,6 +9,8 @@ export declare const RECEIPT_META_KEY = "agent-custody/receipt";
9
9
  export declare const AGENT_META_KEY = "agent-custody/agent";
10
10
  /** Set on read results: the ids of the facts served, so the gateway can record what the agent was shown. */
11
11
  export declare const FACTS_META_KEY = "agent-custody/facts";
12
+ /** Set by the gateway on the forwarded call: the values it fetched itself for this call, by fact name. */
13
+ export declare const OBSERVED_META_KEY = "agent-custody/observed";
12
14
  export declare const TOOLS: Tool[];
13
15
  export interface MemoryServerOptions {
14
16
  /** Refuse calls that did not come through the gateway, i.e. carry no receipt id. On by default when served from the CLI. */
@@ -17,7 +19,13 @@ export interface MemoryServerOptions {
17
19
  stores?: Store[];
18
20
  /** With a key, every result to a gateway call is signed for that receipt, so a verifier holding the public key sees the execution as attested by this server. */
19
21
  identity?: KeyPair;
22
+ /** Retention windows by space pattern, ISO 8601 durations: { "org": "P365D", "team:*": "P90D" }. memory.sweep without `before` uses them. */
23
+ retention?: Record<string, string>;
20
24
  }
25
+ /** Parses the ISO 8601 duration subset retention needs: P<n>W, P<n>D, PT<n>H, and combinations of D and H. */
26
+ export declare function durationMs(iso: string): number;
27
+ /** The retention cutoff for a space, from the first pattern that matches it; null when none does. */
28
+ export declare function retentionCutoff(retention: Record<string, string>, space: string, now: Date): string | null;
21
29
  export declare function createMemoryServer(ledger: Ledger, opts?: MemoryServerOptions): Server;
22
30
  /** Serves over stdio, the way the gateway spawns it. Diagnostics must go to stderr. */
23
31
  export declare function serveStdio(server: Server): Promise<void>;
package/dist/server.js CHANGED
@@ -14,6 +14,8 @@ export const RECEIPT_META_KEY = "agent-custody/receipt";
14
14
  export const AGENT_META_KEY = "agent-custody/agent";
15
15
  /** Set on read results: the ids of the facts served, so the gateway can record what the agent was shown. */
16
16
  export const FACTS_META_KEY = "agent-custody/facts";
17
+ /** Set by the gateway on the forwarded call: the values it fetched itself for this call, by fact name. */
18
+ export const OBSERVED_META_KEY = "agent-custody/observed";
17
19
  const iso = z.string().datetime({ offset: true });
18
20
  const Write = z.object({
19
21
  subject: z.string().min(1),
@@ -25,24 +27,28 @@ const Write = z.object({
25
27
  validFrom: iso.optional(),
26
28
  confidence: z.number().min(0).max(1).optional(),
27
29
  supersedes: z.string().min(1).optional(),
30
+ /** names a fact the gateway fetched for this call, and optionally a dot path into it, that the value must equal; the write is then verified, or refused */
31
+ evidence: z.object({ fact: z.string().min(1), path: z.string().optional() }).optional(),
28
32
  });
29
- const Read = z.object({ subject: z.string().min(1).optional(), predicate: z.string().min(1).optional(), space: z.string().min(1).optional(), validAt: iso.optional(), txAt: iso.optional(), includeClaimed: z.boolean().optional() });
33
+ const Read = z.object({ subject: z.string().min(1).optional(), predicate: z.string().min(1).optional(), space: z.string().min(1).optional(), validAt: iso.optional(), txAt: iso.optional(), includeClaimed: z.boolean().optional(), requireVerified: z.boolean().optional() });
30
34
  const Confirm = z.object({ factId: z.string().min(1) });
31
35
  const Retract = z.object({ factId: z.string().min(1), reason: z.string().min(1), actor: z.string().min(1).optional() });
32
36
  const History = z.object({ factId: z.string().min(1) });
33
37
  const Get = z.object({ factId: z.string().min(1) });
34
- const Forget = z.object({ factId: z.string().min(1), reason: z.string().min(1) });
38
+ const Forget = z.object({ factId: z.string().min(1), reason: z.string().min(1), keepDigest: z.boolean().optional() });
39
+ const Hold = z.object({ factId: z.string().min(1), reason: z.string().min(1) });
40
+ const Sweep = z.object({ before: iso.optional(), space: z.string().min(1).optional(), reason: z.string().min(1), keepDigest: z.boolean().optional() });
35
41
  const str = { type: "string" };
36
42
  export const TOOLS = [
37
43
  {
38
44
  name: "memory.write",
39
- description: "Record a belief: subject, predicate, value, in a space. Optionally supersede an earlier fact. Returns the new fact with its id, transaction time, actor, and source receipt.",
40
- inputSchema: { type: "object", properties: { subject: str, predicate: str, value: {}, space: str, actor: str, validFrom: str, confidence: { type: "number" }, supersedes: str }, required: ["subject", "predicate", "value", "space"] },
45
+ description: "Record a belief: subject, predicate, value, in a space. Optionally supersede an earlier fact. With evidence naming a fact the gateway fetched for this call, the value must equal it (or the field at path) and the write is verified; otherwise it is refused. Returns the new fact with its id, transaction time, actor, provenance, and source receipt.",
46
+ inputSchema: { type: "object", properties: { subject: str, predicate: str, value: {}, space: str, actor: str, validFrom: str, confidence: { type: "number" }, supersedes: str, evidence: { type: "object", properties: { fact: str, path: str }, required: ["fact"] } }, required: ["subject", "predicate", "value", "space"] },
41
47
  },
42
48
  {
43
49
  name: "memory.read",
44
- description: "The facts believed at a moment. validAt asks whether a fact was true then; txAt asks whether the ledger knew it then. Both default to now. Filter by space, subject, predicate. Quarantined (claimed, unconfirmed) facts are left out unless includeClaimed is true.",
45
- inputSchema: { type: "object", properties: { subject: str, predicate: str, space: str, validAt: str, txAt: str, includeClaimed: { type: "boolean" } } },
50
+ description: "The facts believed at a moment. validAt asks whether a fact was true then; txAt asks whether the ledger knew it then. Both default to now. Filter by space, subject, predicate. Quarantined (claimed, unconfirmed) facts are left out unless includeClaimed is true; requireVerified returns only facts whose value the gateway checked against its source.",
51
+ inputSchema: { type: "object", properties: { subject: str, predicate: str, space: str, validAt: str, txAt: str, includeClaimed: { type: "boolean" }, requireVerified: { type: "boolean" } } },
46
52
  },
47
53
  {
48
54
  name: "memory.confirm",
@@ -56,9 +62,24 @@ export const TOOLS = [
56
62
  },
57
63
  {
58
64
  name: "memory.forget",
59
- description: "Erase a fact's value: from the ledger file, keeping only its digest, and from every store behind the server. The fact stops being believed. The receipt for this call, with the result the gateway observed, is the certificate that the erasure happened.",
65
+ description: "Erase a fact's value: from the ledger file, keeping only its digest (keyed when the server has a forget key; none when keepDigest is false), and from every store behind the server. The fact stops being believed. The receipt for this call, with the result the gateway observed, is the certificate that the erasure happened.",
66
+ inputSchema: { type: "object", properties: { factId: str, reason: str, keepDigest: { type: "boolean" } }, required: ["factId", "reason"] },
67
+ },
68
+ {
69
+ name: "memory.hold",
70
+ description: "Legal hold: while it stands the fact cannot be forgotten, by request or by retention sweep.",
71
+ inputSchema: { type: "object", properties: { factId: str, reason: str }, required: ["factId", "reason"] },
72
+ },
73
+ {
74
+ name: "memory.release",
75
+ description: "Lift a legal hold.",
60
76
  inputSchema: { type: "object", properties: { factId: str, reason: str }, required: ["factId", "reason"] },
61
77
  },
78
+ {
79
+ name: "memory.sweep",
80
+ description: "Retention: forget every fact the ledger learned of before an instant, in one space or all, skipping held facts, and remove each from every store. Without `before`, the server's configured retention windows decide per space. The receipt is the record of the sweep.",
81
+ inputSchema: { type: "object", properties: { before: str, space: str, reason: str, keepDigest: { type: "boolean" } }, required: ["reason"] },
82
+ },
62
83
  {
63
84
  name: "memory.get",
64
85
  description: "One fact by id, whatever its state: its space, actor, provenance, source receipt, validity. Meant for the gateway's fact lookups, so policy can decide on the fact a write supersedes or a retraction targets.",
@@ -70,6 +91,23 @@ export const TOOLS = [
70
91
  inputSchema: { type: "object", properties: { factId: str }, required: ["factId"] },
71
92
  },
72
93
  ];
94
+ /** Parses the ISO 8601 duration subset retention needs: P<n>W, P<n>D, PT<n>H, and combinations of D and H. */
95
+ export function durationMs(iso) {
96
+ const m = /^P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/.exec(iso);
97
+ if (!m || iso === "P" || iso === "PT")
98
+ throw new Error(`retention: cannot parse duration ${iso}; use forms like P90D, P2W, PT12H`);
99
+ const [, w = "0", d = "0", h = "0", min = "0"] = m;
100
+ return ((Number(w) * 7 + Number(d)) * 24 + Number(h)) * 3_600_000 + Number(min) * 60_000;
101
+ }
102
+ /** The retention cutoff for a space, from the first pattern that matches it; null when none does. */
103
+ export function retentionCutoff(retention, space, now) {
104
+ for (const [pattern, duration] of Object.entries(retention)) {
105
+ const matches = pattern.endsWith("*") ? space.startsWith(pattern.slice(0, -1)) : space === pattern;
106
+ if (matches)
107
+ return new Date(now.getTime() - durationMs(duration)).toISOString();
108
+ }
109
+ return null;
110
+ }
73
111
  const json = (v) => ({ content: [{ type: "text", text: JSON.stringify(v) }] });
74
112
  const fail = (msg) => ({ isError: true, content: [{ type: "text", text: msg }] });
75
113
  export function createMemoryServer(ledger, opts = {}) {
@@ -81,6 +119,27 @@ export function createMemoryServer(ledger, opts = {}) {
81
119
  const result = await handle(req.params.name, req.params.arguments ?? {}, meta, receiptId);
82
120
  return opts.identity && receiptId ? signResult(result, opts.identity, receiptId, req.params.name) : result;
83
121
  });
122
+ async function forgetOne(factId, reason, keepDigest) {
123
+ const fact = ledger.facts().find((f) => f.factId === factId);
124
+ const ev = ledger.forget({ factId, actor: currentActor, reason, source: { receiptId: currentReceipt }, ...(keepDigest === undefined ? {} : { keepDigest }) });
125
+ const removedFrom = [];
126
+ const stillHeld = [];
127
+ for (const store of opts.stores ?? []) {
128
+ const id = fact?.external?.[store.name];
129
+ if (!id)
130
+ continue;
131
+ try {
132
+ await store.remove(id, fact);
133
+ removedFrom.push(store.name);
134
+ }
135
+ catch (e) {
136
+ stillHeld.push(`${store.name}: ${e instanceof Error ? e.message : String(e)}`);
137
+ }
138
+ }
139
+ return { factId: ev.factId, valueDigest: ev.valueDigest, digestKind: ev.digestKind, txTime: ev.txTime, actor: ev.actor, reason: ev.reason, source: ev.source, erasedFromLedger: true, removedFrom, stillHeld };
140
+ }
141
+ let currentActor = "anonymous";
142
+ let currentReceipt = null;
84
143
  async function handle(name, args, meta, receiptId) {
85
144
  const gatewayAgent = typeof meta[AGENT_META_KEY] === "string" ? meta[AGENT_META_KEY] : null;
86
145
  if (opts.requireGateway && !receiptId)
@@ -88,11 +147,26 @@ export function createMemoryServer(ledger, opts = {}) {
88
147
  const actorFor = (claimed) => gatewayAgent ?? claimed ?? "anonymous";
89
148
  // A write is attested when it came through the gateway: the actor is from a signed grant and the receipt exists.
90
149
  const provenance = receiptId && gatewayAgent ? "attested" : "claimed";
150
+ const observed = (meta[OBSERVED_META_KEY] ?? {});
151
+ currentActor = actorFor(undefined);
152
+ currentReceipt = receiptId;
91
153
  try {
92
154
  switch (name) {
93
155
  case "memory.write": {
94
156
  const a = Write.parse(args);
95
- const input = { subject: a.subject, predicate: a.predicate, value: a.value ?? null, space: a.space, actor: actorFor(a.actor), source: { receiptId }, provenance, ...(a.validFrom ? { validFrom: a.validFrom } : {}), ...(a.confidence !== undefined ? { confidence: a.confidence } : {}), ...(a.supersedes ? { supersedes: a.supersedes } : {}) };
157
+ let writeProvenance = provenance;
158
+ if (a.evidence) {
159
+ // Value-level quarantine: the agent may say where the value came from, and the gateway's own observation decides.
160
+ if (provenance !== "attested")
161
+ return fail("evidence needs the gateway: only a fact the gateway fetched itself can verify a value");
162
+ if (!(a.evidence.fact in observed))
163
+ return fail(`no fact named "${a.evidence.fact}" was fetched by the gateway for this call; configure a fact lookup for memory.write`);
164
+ const expected = a.evidence.path ? a.evidence.path.split(".").reduce((v, k) => (v && typeof v === "object" ? v[k] : undefined), observed[a.evidence.fact]) : observed[a.evidence.fact];
165
+ if (JSON.stringify(sortKeys(expected)) !== JSON.stringify(sortKeys(a.value ?? null)))
166
+ return fail(`value differs from what the gateway observed in "${a.evidence.fact}${a.evidence.path ? "." + a.evidence.path : ""}"; write refused`);
167
+ writeProvenance = "verified";
168
+ }
169
+ const input = { subject: a.subject, predicate: a.predicate, value: a.value ?? null, space: a.space, actor: actorFor(a.actor), source: { receiptId }, provenance: writeProvenance, ...(a.validFrom ? { validFrom: a.validFrom } : {}), ...(a.confidence !== undefined ? { confidence: a.confidence } : {}), ...(a.supersedes ? { supersedes: a.supersedes } : {}) };
96
170
  // The stores are written first, so their ids can be recorded on the fact; the ledger's checks run beforehand
97
171
  // so a write the ledger would refuse never reaches a store.
98
172
  ledger.validateAssert(input);
@@ -104,8 +178,8 @@ export function createMemoryServer(ledger, opts = {}) {
104
178
  return json({ fact: ev.fact, eventId: ev.eventId, txTime: ev.txTime, supersedes: ev.supersedes });
105
179
  }
106
180
  case "memory.read": {
107
- const { includeClaimed, ...q } = Read.parse(args);
108
- const facts = ledger.asOf({ ...q, include: includeClaimed ? "all" : "attested" });
181
+ const { includeClaimed, requireVerified, ...q } = Read.parse(args);
182
+ const facts = ledger.asOf({ ...q, include: requireVerified ? "verified" : includeClaimed ? "all" : "attested" });
109
183
  return { ...json({ facts }), _meta: { [FACTS_META_KEY]: facts.map((f) => f.factId) } };
110
184
  }
111
185
  case "memory.retract": {
@@ -140,25 +214,45 @@ export function createMemoryServer(ledger, opts = {}) {
140
214
  }
141
215
  case "memory.forget": {
142
216
  const a = Forget.parse(args);
143
- const fact = ledger.facts().find((f) => f.factId === a.factId);
144
- const ev = ledger.forget({ factId: a.factId, actor: actorFor(undefined), reason: a.reason, source: { receiptId } });
145
- const removedFrom = [];
146
- const stillHeld = [];
147
- for (const store of opts.stores ?? []) {
148
- const id = fact?.external?.[store.name];
149
- if (!id)
217
+ const out = await forgetOne(a.factId, a.reason, a.keepDigest);
218
+ if (out.stillHeld.length > 0)
219
+ return { isError: true, content: [{ type: "text", text: `erased from the ledger, but still held by ${out.stillHeld.join("; ")}` }, { type: "text", text: JSON.stringify(out) }] };
220
+ return json(out);
221
+ }
222
+ case "memory.hold": {
223
+ const a = Hold.parse(args);
224
+ return json(ledger.hold({ factId: a.factId, actor: actorFor(undefined), reason: a.reason, source: { receiptId } }));
225
+ }
226
+ case "memory.release": {
227
+ const a = Hold.parse(args);
228
+ return json(ledger.release({ factId: a.factId, actor: actorFor(undefined), reason: a.reason, source: { receiptId } }));
229
+ }
230
+ case "memory.sweep": {
231
+ const a = Sweep.parse(args);
232
+ if (!a.before && !opts.retention)
233
+ return fail("sweep needs `before`, or a server started with retention windows");
234
+ const now = new Date();
235
+ const cutoffFor = (space) => a.before ?? retentionCutoff(opts.retention ?? {}, space, now);
236
+ const targets = ledger.facts().filter((f) => !f.forgotten && (a.space === undefined || f.space === a.space));
237
+ const learnedBefore = new Set(ledger.facts().filter((f) => {
238
+ const cutoff = cutoffFor(f.space);
239
+ return cutoff !== null && ledger.history(f.factId).find((e) => e.kind === "assert" && e.fact.factId === f.factId).txTime < cutoff;
240
+ }).map((f) => f.factId));
241
+ const forgotten = [];
242
+ const held = [];
243
+ for (const f of targets) {
244
+ if (!learnedBefore.has(f.factId))
245
+ continue;
246
+ if (ledger.held(f.factId)) {
247
+ held.push(f.factId);
150
248
  continue;
151
- try {
152
- await store.remove(id, fact);
153
- removedFrom.push(store.name);
154
- }
155
- catch (e) {
156
- stillHeld.push(`${store.name}: ${e instanceof Error ? e.message : String(e)}`);
157
249
  }
250
+ forgotten.push(await forgetOne(f.factId, a.reason, a.keepDigest));
158
251
  }
159
- const out = { factId: ev.factId, valueDigest: ev.valueDigest, txTime: ev.txTime, actor: ev.actor, reason: ev.reason, source: ev.source, erasedFromLedger: true, removedFrom, stillHeld };
252
+ const stillHeld = forgotten.flatMap((o) => o.stillHeld);
253
+ const out = { before: a.before ?? null, retention: a.before ? null : (opts.retention ?? null), space: a.space ?? null, forgotten: forgotten.map((o) => ({ factId: o.factId, valueDigest: o.valueDigest, digestKind: o.digestKind, removedFrom: o.removedFrom })), held, stillHeld };
160
254
  if (stillHeld.length > 0)
161
- return { isError: true, content: [{ type: "text", text: `erased from the ledger, but still held by ${stillHeld.join("; ")}` }, { type: "text", text: JSON.stringify(out) }] };
255
+ return { isError: true, content: [{ type: "text", text: `swept the ledger, but some values are still held by stores: ${stillHeld.join("; ")}` }, { type: "text", text: JSON.stringify(out) }] };
162
256
  return json(out);
163
257
  }
164
258
  case "memory.get": {
@@ -190,3 +284,14 @@ export async function serveStdio(server) {
190
284
  server.onclose = resolve;
191
285
  });
192
286
  }
287
+ function sortKeys(v) {
288
+ if (Array.isArray(v))
289
+ return v.map(sortKeys);
290
+ if (v && typeof v === "object") {
291
+ const o = {};
292
+ for (const k of Object.keys(v).sort())
293
+ o[k] = sortKeys(v[k]);
294
+ return o;
295
+ }
296
+ return v;
297
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/state",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Governed memory for AI agents: a fact ledger with provenance, valid time, rollback, and lineage, built on @agent-custody/receipts",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -33,7 +33,7 @@
33
33
  "node": ">=22"
34
34
  },
35
35
  "dependencies": {
36
- "@agent-custody/receipts": "0.1.5",
36
+ "@agent-custody/receipts": "0.1.7",
37
37
  "@modelcontextprotocol/sdk": "^1.30.0",
38
38
  "zod": "^4.5.4"
39
39
  },