@coreguard/agent-commerce 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/anchor.mjs ADDED
@@ -0,0 +1,278 @@
1
+ /**
2
+ * CoreGuard Anchor Service (CG-ANCHOR/1) — our own append-only witness.
3
+ *
4
+ * A verification layer that cannot say WHERE it saw a record is a layer that
5
+ * asks to be trusted. This service is the smallest thing we can run ourselves
6
+ * and that a stranger can check without asking us:
7
+ *
8
+ * attestation a signed statement: "at T, I saw this digest" — Ed25519 over
9
+ * canonical JSON, carrying the signing public key, so it verifies
10
+ * offline and outlives the file it arrived in
11
+ * log append-only, hash-chained: entry n names the digest of entry
12
+ * n-1, so a silent rewrite anywhere is visible at the tail
13
+ * root one Merkle root over the log; that 32-byte value is the only
14
+ * thing that ever needs to reach a chain, a notary or a mirror
15
+ *
16
+ * That last line is the design decision worth stating: the log does not need a
17
+ * chain to be useful, and a chain does not make the log honest. Anchoring the
18
+ * root elsewhere is an upgrade, never a precondition.
19
+ *
20
+ * BOUNDARY (standing, load-bearing):
21
+ * - No clock, no network, no keys inside this repository. The caller passes
22
+ * `now` and a key; the CLI generates a key locally and prints the path.
23
+ * - Nothing here broadcasts. `prepareChainAnchor` returns the exact 32-byte
24
+ * memo a chain anchor would carry and refuses `mainnet` outright — the
25
+ * decision to write to a live network is not a library call.
26
+ * - An anchor says a digest existed at a time, in a place. It never says the
27
+ * record was correct, authorized or safe, and it cannot resurrect bytes.
28
+ */
29
+
30
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from "node:crypto";
31
+
32
+ export const ANCHOR_VERSION = "CG-ANCHOR/1";
33
+ export const ANCHOR_SCHEMA = "coreguard.anchor/1";
34
+
35
+ const HEX64 = /^[0-9a-f]{64}$/;
36
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
37
+ const sha256hex = (buf) => createHash("sha256").update(buf).digest("hex");
38
+
39
+ /** Canonical JSON: sorted keys, no whitespace, recursive. Byte-deterministic. */
40
+ function canonicalJson(value) {
41
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
42
+ if (Array.isArray(value)) return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
43
+ const keys = Object.keys(value).sort();
44
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
45
+ }
46
+
47
+ /** Normalize a subject digest to `sha256:<64 lowercase hex>`. */
48
+ export function normalizeSubject({ kind, digest } = {}) {
49
+ if (typeof kind !== "string" || kind.length === 0) throw new TypeError("subject.kind must be a non-empty string");
50
+ const raw = typeof digest === "string" ? digest.trim() : "";
51
+ const hex = raw.startsWith("sha256:") ? raw.slice(7) : raw;
52
+ if (!HEX64.test(hex)) throw new TypeError("subject.digest must be 32 bytes of lowercase hex (sha256:<hex>)");
53
+ return Object.freeze({ kind, digest: `sha256:${hex}` });
54
+ }
55
+
56
+ /** A fresh Ed25519 key pair. The private key is the caller's to keep. */
57
+ export function generateIssuerKey() {
58
+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");
59
+ return Object.freeze({
60
+ publicKeyPem: publicKey.export({ type: "spki", format: "pem" }).toString(),
61
+ privateKeyPem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
62
+ });
63
+ }
64
+
65
+ /** keyId = sha256 over the DER of the public key. Stable, and not a fingerprint. */
66
+ export function keyIdFor(publicKeyPem) {
67
+ const der = createPublicKey(publicKeyPem).export({ type: "spki", format: "der" });
68
+ return sha256hex(der);
69
+ }
70
+
71
+ /** Build and sign one attestation. `now` is an ISO-8601 string supplied by the caller. */
72
+ export function signAttestation({ subject, issuedAt, privateKeyPem, sequence = 0, previous = null } = {}) {
73
+ const normalized = normalizeSubject(subject);
74
+ if (typeof issuedAt !== "string" || Number.isNaN(Date.parse(issuedAt))) {
75
+ throw new TypeError("issuedAt must be an ISO-8601 timestamp");
76
+ }
77
+ if (typeof privateKeyPem !== "string" || !privateKeyPem.includes("PRIVATE KEY")) {
78
+ throw new TypeError("privateKeyPem must be a PKCS#8 PEM string");
79
+ }
80
+ const publicKeyPem = createPublicKeyFromPrivate(privateKeyPem);
81
+ const body = {
82
+ anchorVersion: ANCHOR_VERSION,
83
+ schema: ANCHOR_SCHEMA,
84
+ subject: normalized,
85
+ sequence,
86
+ previous: previous ?? null,
87
+ issuedAt,
88
+ issuer: { keyId: keyIdFor(publicKeyPem), publicKeyPem },
89
+ };
90
+ const signature = sign(null, Buffer.from(canonicalJson(body), "utf8"), privateKeyPem).toString("base64");
91
+ return Object.freeze({ ...body, signature });
92
+ }
93
+
94
+ function createPublicKeyFromPrivate(privateKeyPem) {
95
+ const priv = createPrivateKey(privateKeyPem);
96
+ return createPublicKey(priv).export({ type: "spki", format: "pem" }).toString();
97
+ }
98
+
99
+ /** Leaf hash of one attestation: sha256 over its canonical JSON, signature included. */
100
+ export function leafHash(attestation) {
101
+ return sha256hex(Buffer.from(canonicalJson(attestation), "utf8"));
102
+ }
103
+
104
+ /** Merkle root over leaf hashes, duplicated-last, empty tree = 64 zeros. */
105
+ export function merkleRoot(leaves) {
106
+ if (!Array.isArray(leaves)) throw new TypeError("merkleRoot requires an array of leaf hashes");
107
+ if (leaves.length === 0) return "0".repeat(64);
108
+ let level = leaves.map((l) => {
109
+ const hex = String(l).startsWith("sha256:") ? String(l).slice(7) : String(l);
110
+ if (!HEX64.test(hex)) throw new TypeError("every leaf must be 32 bytes of lowercase hex");
111
+ return hex;
112
+ });
113
+ while (level.length > 1) {
114
+ const next = [];
115
+ for (let i = 0; i < level.length; i += 2) {
116
+ const a = level[i];
117
+ const b = level[i + 1] ?? a;
118
+ next.push(sha256hex(Buffer.from(a + b, "hex")));
119
+ }
120
+ level = next;
121
+ }
122
+ return level[0];
123
+ }
124
+
125
+ /** A new, empty log. Logs are immutable by convention: append returns a copy. */
126
+ export function createLog() {
127
+ return Object.freeze({ anchorVersion: ANCHOR_VERSION, schema: ANCHOR_SCHEMA, entries: Object.freeze([]) });
128
+ }
129
+
130
+ /**
131
+ * Append one anchor. Returns a NEW log; the input is never mutated.
132
+ *
133
+ * The chain is over attestations, so `previous` is the leaf hash of the last
134
+ * entry — not its sequence number. Renumbering entries therefore breaks the
135
+ * chain, which is the point.
136
+ */
137
+ export function appendAnchor(log, { subject, issuedAt, privateKeyPem } = {}) {
138
+ if (!isObject(log) || !Array.isArray(log.entries)) throw new TypeError("appendAnchor requires a log");
139
+ const previous = log.entries.length === 0 ? null : leafHash(log.entries[log.entries.length - 1]);
140
+ const attestation = signAttestation({
141
+ subject,
142
+ issuedAt,
143
+ privateKeyPem,
144
+ sequence: log.entries.length,
145
+ previous,
146
+ });
147
+ const entries = Object.freeze([...log.entries, attestation]);
148
+ return Object.freeze({ ...log, entries, root: merkleRoot(entries.map(leafHash)) });
149
+ }
150
+
151
+ /** Verify one attestation, offline and self-contained. */
152
+ export function verifyAttestation(attestation) {
153
+ const checks = [];
154
+ if (!isObject(attestation)) return Object.freeze({ ok: false, checks: [{ name: "attestation is an object", ok: false }] });
155
+ const { signature, ...body } = attestation;
156
+ checks.push({ name: "anchor version is CG-ANCHOR/1", ok: body.anchorVersion === ANCHOR_VERSION });
157
+ try {
158
+ normalizeSubject(body.subject);
159
+ checks.push({ name: "subject digest is sha256:<64 hex>", ok: true });
160
+ } catch {
161
+ checks.push({ name: "subject digest is sha256:<64 hex>", ok: false });
162
+ }
163
+ const keyOk = isObject(body.issuer) && typeof body.issuer.publicKeyPem === "string";
164
+ checks.push({ name: "issuer carries a public key", ok: keyOk });
165
+ if (keyOk) checks.push({ name: "keyId matches the public key", ok: body.issuer.keyId === keyIdFor(body.issuer.publicKeyPem) });
166
+ let sigOk = false;
167
+ if (keyOk && typeof signature === "string") {
168
+ try {
169
+ sigOk = verify(null, Buffer.from(canonicalJson(body), "utf8"), body.issuer.publicKeyPem, Buffer.from(signature, "base64"));
170
+ } catch {
171
+ sigOk = false;
172
+ }
173
+ }
174
+ checks.push({ name: "Ed25519 signature verifies over canonical JSON", ok: sigOk });
175
+ return Object.freeze({ ok: checks.every((c) => c.ok), checks });
176
+ }
177
+
178
+ /** Verify a whole log: every signature, the previous-link chain, and the root. */
179
+ export function verifyLog(log) {
180
+ if (!isObject(log) || !Array.isArray(log.entries)) throw new TypeError("verifyLog requires a log");
181
+ const checks = [];
182
+ let prevLeaf = null;
183
+ for (let i = 0; i < log.entries.length; i++) {
184
+ const entry = log.entries[i];
185
+ const single = verifyAttestation(entry);
186
+ checks.push({ name: `entry ${i} verifies`, ok: single.ok });
187
+ checks.push({ name: `entry ${i} sequence is ${i}`, ok: entry.sequence === i });
188
+ checks.push({ name: `entry ${i} links to the previous entry`, ok: entry.previous === prevLeaf });
189
+ prevLeaf = leafHash(entry);
190
+ }
191
+ const root = merkleRoot(log.entries.map(leafHash));
192
+ checks.push({ name: "declared root matches the computed root", ok: log.root === undefined || log.root === root });
193
+ return Object.freeze({ ok: checks.every((c) => c.ok), checks, root });
194
+ }
195
+
196
+ /**
197
+ * Resolve a digest against a log, in CG-OUT/1's anchor vocabulary.
198
+ *
199
+ * { present, evaluated, outcome } outcome: verified | absent | unresolvable
200
+ *
201
+ * A digest with matching entries is `verified`. A digest addressed by a broken
202
+ * entry is `unresolvable` — we can see it was written, and we cannot stand
203
+ * behind it. A digest with no entry at all is `absent`: no one claimed it.
204
+ */
205
+ export function resolveAnchor(log, digest) {
206
+ let subject;
207
+ try {
208
+ subject = normalizeSubject({ kind: "unknown", digest });
209
+ } catch {
210
+ return Object.freeze({ present: false, evaluated: false, outcome: "absent", reason: "digest is not sha256:<64 hex>" });
211
+ }
212
+ if (!isObject(log) || !Array.isArray(log.entries)) {
213
+ return Object.freeze({ present: false, evaluated: false, outcome: "absent", reason: "no log was supplied" });
214
+ }
215
+ const matches = log.entries.filter((e) => e?.subject?.digest === subject.digest);
216
+ if (matches.length === 0) {
217
+ return Object.freeze({ present: false, evaluated: true, outcome: "absent", matches: 0 });
218
+ }
219
+ const allValid = matches.every((e) => verifyAttestation(e).ok);
220
+ return Object.freeze({
221
+ present: true,
222
+ evaluated: true,
223
+ outcome: allValid ? "verified" : "unresolvable",
224
+ matches: matches.length,
225
+ reason: allValid ? undefined : "an entry for this digest failed its own signature check",
226
+ });
227
+ }
228
+
229
+ /**
230
+ * The only thing that would need to reach a chain: the 32-byte root.
231
+ *
232
+ * `broadcast` is hard-coded false and `mainnet` is refused by name. Preparing a
233
+ * memo is not authorization to write it, and this repository has no path from
234
+ * here to a signed transaction.
235
+ */
236
+ export function prepareChainAnchor(log, { network = "testnet" } = {}) {
237
+ const verified = verifyLog(log);
238
+ if (!verified.ok) return Object.freeze({ ok: false, reason: "the log does not verify", checks: verified.checks });
239
+ if (network === "mainnet" || network === "public") {
240
+ return Object.freeze({
241
+ ok: false,
242
+ reason: "mainnet is refused here by name: anchoring the root to a live network is a deliberate, separate decision",
243
+ });
244
+ }
245
+ return Object.freeze({
246
+ ok: true,
247
+ adapter: "stellar",
248
+ network,
249
+ memoHashHex: verified.root,
250
+ memoType: "hash",
251
+ broadcast: false,
252
+ root: verified.root,
253
+ entries: log.entries.length,
254
+ });
255
+ }
256
+
257
+ /** Self-check: the service's own invariants, for callers that cannot run tests. */
258
+ export function selfCheck() {
259
+ const keys = generateIssuerKey();
260
+ const digest = sha256hex(Buffer.from("self-check"));
261
+ const t0 = "2026-01-01T00:00:00.000Z";
262
+ const log1 = appendAnchor(createLog(), { subject: { kind: "receipt", digest }, issuedAt: t0, privateKeyPem: keys.privateKeyPem });
263
+ const log2 = appendAnchor(log1, { subject: { kind: "receipt", digest }, issuedAt: t0, privateKeyPem: keys.privateKeyPem });
264
+ const tampered = Object.freeze({
265
+ ...log1,
266
+ entries: Object.freeze([{ ...log1.entries[0], issuedAt: "2026-01-02T00:00:00.000Z" }]),
267
+ });
268
+ const checks = [
269
+ { name: "a fresh log verifies", pass: verifyLog(log1).ok },
270
+ { name: "a two-entry log verifies", pass: verifyLog(log2).ok },
271
+ { name: "a re-signed-looking edit breaks the log", pass: verifyLog(tampered).ok === false },
272
+ { name: "a known digest resolves to verified", pass: resolveAnchor(log2, `sha256:${digest}`).outcome === "verified" },
273
+ { name: "an unknown digest is absent, not unresolvable", pass: resolveAnchor(log2, `sha256:${"a".repeat(64)}`).outcome === "absent" },
274
+ { name: "mainnet preparation is refused", pass: prepareChainAnchor(log1, { network: "mainnet" }).ok === false },
275
+ { name: "the chain memo is the Merkle root", pass: prepareChainAnchor(log1).memoHashHex === verifyLog(log1).root },
276
+ ];
277
+ return Object.freeze({ ok: checks.every((c) => c.pass), checks });
278
+ }
package/bin/mcp.mjs CHANGED
File without changes
@@ -0,0 +1,150 @@
1
+ /**
2
+ * CoreGuard Composition Policy (CG-COMPOSE/1) — one rule, two defensible answers.
3
+ *
4
+ * The record layer and the anchor layer answer different questions, and a
5
+ * consumer sometimes needs them merged and sometimes needs them apart. AER-1
6
+ * keeps them apart; our default merges them. Neither is a disagreement about
7
+ * the receipt, and pretending one of them is wrong costs a review round every
8
+ * time the topic comes up. So the choice is a value, not an argument:
9
+ *
10
+ * mode: "composed" the anchor outcome participates in the headline. A
11
+ * well-formed record whose anchor cannot be resolved reads
12
+ * UNRESOLVABLE_RECORD and may be presented as a refusal.
13
+ * Best for a commerce consumer that needs ONE answer now.
14
+ *
15
+ * mode: "layered" the record outcome never moves. The anchor layer reports
16
+ * its own fact, including `rejected: "unresolvable record"`,
17
+ * and the headline describes the record alone. Best for a
18
+ * record that must outlive any single anchor.
19
+ *
20
+ * The property worth writing down, because it is the whole difference:
21
+ *
22
+ * In "layered" mode, a second anchor that resolves LATER changes the anchor
23
+ * block and never the record outcome. In "composed" mode, the same event
24
+ * legitimately flips the headline — the composed answer was about the pair,
25
+ * not about the bytes.
26
+ *
27
+ * BOUNDARY (standing, load-bearing):
28
+ * - Neither mode may turn ABSENT into a refusal. Silence is not a failure in
29
+ * both, and that invariant is asserted rather than described.
30
+ * - Composition never upgrades a record: a failed record layer stays failed
31
+ * in both modes. The anchor layer can only make the pair weaker, never the
32
+ * record stronger.
33
+ * - No clock, no network, no keys. Facts in, decision out.
34
+ */
35
+
36
+ import { decideOutcome, OUTCOMES } from "./outcomes.mjs";
37
+
38
+ export const COMPOSITION_VERSION = "CG-COMPOSE/1";
39
+
40
+ /** The two policies. Adding a third is a schema change, not a preference. */
41
+ export const COMPOSITION_MODES = Object.freeze(["composed", "layered"]);
42
+
43
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
44
+
45
+ /**
46
+ * composeOutcome({ presented, record, anchor, mode })
47
+ *
48
+ * presented true only if a record was actually handed over
49
+ * record { evaluated, ok, code?, reason?, version? }
50
+ * anchor { present, evaluated, outcome? } in CG-OUT/1's vocabulary
51
+ * mode "composed" (default) | "layered"
52
+ */
53
+ export function composeOutcome({ presented, record, anchor, mode = "composed" } = {}) {
54
+ if (!COMPOSITION_MODES.includes(mode)) {
55
+ throw new Error(`unknown composition mode: ${JSON.stringify(mode)} (use one of ${COMPOSITION_MODES.join(", ")})`);
56
+ }
57
+
58
+ if (mode === "composed") {
59
+ const composed = decideOutcome({ presented, record, anchor });
60
+ return Object.freeze({
61
+ compositionVersion: COMPOSITION_VERSION,
62
+ mode,
63
+ headline: composed.outcome,
64
+ record: Object.freeze({ outcome: recordHeadline({ presented, record }), moved: false }),
65
+ anchor: anchorBlock(anchor),
66
+ blocks: composed.blocks,
67
+ resolutionSensitive: anchorContributed(anchor, composed.outcome),
68
+ code: composed.code,
69
+ reason: composed.reason,
70
+ layers: composed.layers,
71
+ });
72
+ }
73
+
74
+ // Layered: the headline is the record's own answer, computed without the
75
+ // anchor facts at all. That is what makes it stable under later resolution.
76
+ const recordOnly = decideOutcome({ presented, record });
77
+ const anchorFacts = anchorBlock(anchor);
78
+ return Object.freeze({
79
+ compositionVersion: COMPOSITION_VERSION,
80
+ mode,
81
+ headline: recordOnly.outcome,
82
+ record: Object.freeze({ outcome: recordOnly.outcome, moved: false }),
83
+ anchor: Object.freeze({ ...anchorFacts, rejected: anchorFacts.outcome === "unresolvable" ? "unresolvable record" : null }),
84
+ blocks: recordOnly.blocks,
85
+ resolutionSensitive: false,
86
+ code: recordOnly.code,
87
+ reason: recordOnly.reason,
88
+ layers: Object.freeze({
89
+ record: recordOnly.layers.record,
90
+ anchor: Object.freeze({ present: anchorFacts.present, evaluated: anchorFacts.evaluated, outcome: anchorFacts.outcome }),
91
+ }),
92
+ });
93
+ }
94
+
95
+ function recordHeadline({ presented, record }) {
96
+ return decideOutcome({ presented, record }).outcome;
97
+ }
98
+
99
+ function anchorBlock(anchor) {
100
+ const stated = isObject(anchor);
101
+ const outcome = stated && typeof anchor.outcome === "string" ? anchor.outcome : "not_checked";
102
+ return Object.freeze({
103
+ present: stated ? anchor.present === true : false,
104
+ evaluated: stated ? anchor.evaluated === true : false,
105
+ outcome,
106
+ rejected: outcome === "unresolvable" ? "unresolvable record" : null,
107
+ });
108
+ }
109
+
110
+ function anchorContributed(anchor, headline) {
111
+ return isObject(anchor) && anchor.evaluated === true && anchor.outcome === "unresolvable" && headline === "UNRESOLVABLE_RECORD";
112
+ }
113
+
114
+ /** A picture of the two modes over the same facts — used by the CLI and docs. */
115
+ export function compareModes(input) {
116
+ const composed = composeOutcome({ ...input, mode: "composed" });
117
+ const layered = composeOutcome({ ...input, mode: "layered" });
118
+ return Object.freeze({
119
+ compositionVersion: COMPOSITION_VERSION,
120
+ composed,
121
+ layered,
122
+ diverges: composed.headline !== layered.headline,
123
+ recordStable: composed.record.outcome === layered.record.outcome,
124
+ });
125
+ }
126
+
127
+ /** Self-check: the policy's own invariants, for callers that cannot run tests. */
128
+ export function selfCheck() {
129
+ const ok = { evaluated: true, ok: true };
130
+ const facts = { presented: true, record: ok };
131
+ const unresolvable = { present: true, evaluated: true, outcome: "unresolvable" };
132
+ const resolved = { present: true, evaluated: true, outcome: "verified" };
133
+
134
+ const c1 = compareModes({ ...facts, anchor: unresolvable });
135
+ const c2 = compareModes({ ...facts, anchor: resolved });
136
+ const silence = compareModes({ presented: false, anchor: unresolvable });
137
+ const failedRecord = compareModes({ presented: true, record: { evaluated: true, ok: false }, anchor: resolved });
138
+
139
+ const checks = [
140
+ { name: "the modes diverge only when the anchor is unresolvable", pass: c1.diverges === true && c2.diverges === false },
141
+ { name: "the record outcome is identical in both modes", pass: c1.recordStable && c2.recordStable },
142
+ { name: "composed mode blocks on an unresolvable anchor", pass: c1.composed.blocks === true },
143
+ { name: "layered mode never blocks on an unresolvable anchor", pass: c1.layered.blocks === false },
144
+ { name: "layered mode carries the rejection on the anchor layer", pass: c1.layered.anchor.rejected === "unresolvable record" },
145
+ { name: "silence is not a refusal in either mode", pass: silence.composed.headline === "ABSENT" && silence.layered.headline === "ABSENT" && !silence.layered.blocks },
146
+ { name: "a failed record stays failed in both modes", pass: failedRecord.composed.headline === "VERIFICATION_FAILED" && failedRecord.layered.headline === "VERIFICATION_FAILED" },
147
+ { name: "every headline is one of the five outcomes", pass: OUTCOMES.includes(c1.composed.headline) && OUTCOMES.includes(c1.layered.headline) },
148
+ ];
149
+ return Object.freeze({ ok: checks.every((c) => c.pass), checks });
150
+ }
@@ -3,33 +3,47 @@
3
3
  *
4
4
  * A Set-compatible consumption ledger adapter that persists consumed receipt
5
5
  * IDs to a JSON file so a single-use authorization cannot be replayed across
6
- * process restarts on the same host (the "shared-ledger/store adapter via
7
- * existing consumedSet injection" named by the spec's next step).
6
+ * process restarts — or across two live processes on the same host.
8
7
  *
9
- * Interface: `has(id)` / `add(id)` — the same shape `verifyExecution`, the
10
- * firewall, and `assessRisk` already accept via `consumedSet`, so this is a
11
- * drop-in replacement for the process-local `Set` with no change to the
12
- * verification semantics.
8
+ * Interface: `has(id)` / `add(id)` / `tryAdd(id)` — the same shape
9
+ * `verifyExecution`, the firewall, and `assessRisk` accept via `consumedSet`.
10
+ * `tryAdd(id)` is the correct single-use primitive: it reloads the ledger under
11
+ * an exclusive file lock and returns true only for the caller that actually
12
+ * added the id, so two racing processes cannot both believe they were first.
13
13
  *
14
- * Durability model (honest): file-backed, atomic rename-on-write within the
15
- * host process's visibility. It is NOT a distributed ledger, NOT an on-chain
16
- * single-use marker, and NOT a guarantee against concurrent writers racing on
17
- * the same file without external locking. An on-chain consumption marker is
18
- * OWNER-GATED / NOT_BUILT — this adapter closes the cross-process gap the spec
19
- * named, not the on-chain anchoring gap.
14
+ * Durability model (honest): every read is a fresh file read; every mutation
15
+ * takes `<file>.lock` (O_EXCL, stale-lock recovery) and rewrites the ledger with
16
+ * an atomic temp+rename. That closes the cross-PROCESS gap on one host. It is
17
+ * still NOT a distributed ledger and NOT an on-chain marker: two hosts with two
18
+ * local files can each consume the same receipt. The built answer for crossing
19
+ * hosts is the append-only signed log in `spend.mjs` (CG-SPEND/1, `mergeLogs`),
20
+ * which makes a double-spend across exchanged logs a named `conflict`; a global
21
+ * on-chain marker remains OWNER-GATED / NOT_BUILT.
20
22
  *
21
23
  * BOUNDARY (standing): VERIFIED ≠ SAFE; consumption anchoring here is a local
22
24
  * persistence aid, never a broadcast, never chain state.
23
25
  */
24
26
 
25
- import { readFileSync, writeFileSync, mkdirSync, renameSync } from "node:fs";
27
+ import {
28
+ readFileSync,
29
+ writeFileSync,
30
+ mkdirSync,
31
+ renameSync,
32
+ openSync,
33
+ closeSync,
34
+ statSync,
35
+ unlinkSync,
36
+ } from "node:fs";
26
37
  import { dirname } from "node:path";
27
38
 
28
39
  export const CONSUMPTION_STORE_VERSION = "AC-CS/1";
29
40
  export const CONSUMPTION_STORE_BOUNDARY =
30
- "file-backed consumption ledger — durable across process restarts on this host; " +
41
+ "file-backed consumption ledger — durable across process restarts and lock-guarded across processes on this host; " +
31
42
  "NOT a distributed ledger, NOT an on-chain marker (on-chain anchoring OWNER-GATED / NOT_BUILT); " +
32
- "VERIFIED ≠ SAFE";
43
+ "cross-host reconciliation is CG-SPEND/1 merge (spend.mjs), not this file; VERIFIED ≠ SAFE";
44
+
45
+ const SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
46
+ const sleep = (ms) => Atomics.wait(SLEEP_CELL, 0, 0, ms);
33
47
 
34
48
  function loadIds(filePath) {
35
49
  try {
@@ -57,57 +71,119 @@ function persist(filePath, ids) {
57
71
  null,
58
72
  2,
59
73
  ) + "\n";
60
- const tmp = `${filePath}.tmp`;
74
+ const tmp = `${filePath}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
61
75
  writeFileSync(tmp, payload, "utf8");
62
76
  renameSync(tmp, filePath);
63
77
  }
64
78
 
79
+ /** Exclusive lock around a read-modify-write of one ledger file. */
80
+ function withLock(filePath, fn, { lockTimeoutMs = 2000, staleLockMs = 10000 } = {}) {
81
+ const lockPath = `${filePath}.lock`;
82
+ mkdirSync(dirname(lockPath), { recursive: true });
83
+ const deadline = Date.now() + lockTimeoutMs;
84
+ for (;;) {
85
+ try {
86
+ const fd = openSync(lockPath, "wx");
87
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));
88
+ closeSync(fd);
89
+ break;
90
+ } catch (err) {
91
+ if (err.code !== "EEXIST") throw err;
92
+ try {
93
+ const st = statSync(lockPath);
94
+ if (Date.now() - st.mtimeMs > staleLockMs) unlinkSync(lockPath);
95
+ } catch {
96
+ // Released between EEXIST and stat.
97
+ }
98
+ if (Date.now() > deadline) throw new Error(`AC-CS/1: ledger is locked by another process (${lockPath})`);
99
+ sleep(3 + Math.floor(Math.random() * 5));
100
+ }
101
+ }
102
+ try {
103
+ return fn();
104
+ } finally {
105
+ try {
106
+ unlinkSync(lockPath);
107
+ } catch {
108
+ // Nothing to release.
109
+ }
110
+ }
111
+ }
112
+
65
113
  /**
66
114
  * Create (or open) a file-backed consumption store.
67
115
  *
68
116
  * `filePath` — path to the JSON ledger file (created if absent).
69
- * The returned object is Set-compatible for `has`/`add` and also exposes
70
- * `size`, `ids()` (sorted snapshot), `spec`, `filePath`, and `boundary`.
117
+ * Options: `lockTimeoutMs`, `staleLockMs` for the cross-process lock.
71
118
  */
72
- export function createConsumptionStore(filePath) {
119
+ export function createConsumptionStore(filePath, { lockTimeoutMs = 2000, staleLockMs = 10000 } = {}) {
73
120
  if (!filePath || typeof filePath !== "string") {
74
121
  throw new Error("AC-CS/1: createConsumptionStore requires a filePath string");
75
122
  }
76
- const ids = loadIds(filePath);
123
+ const lockOptions = { lockTimeoutMs, staleLockMs };
77
124
 
78
125
  const store = {
79
126
  spec: CONSUMPTION_STORE_VERSION,
80
127
  filePath,
81
128
  boundary: CONSUMPTION_STORE_BOUNDARY,
129
+ /** Fresh read: another process's commit is visible immediately. */
82
130
  has(id) {
83
- return ids.has(id);
131
+ return loadIds(filePath).has(id);
84
132
  },
85
133
  add(id) {
86
- if (!ids.has(id)) {
87
- ids.add(id);
88
- persist(filePath, ids);
89
- }
134
+ store.tryAdd(id);
90
135
  return store;
91
136
  },
137
+ /**
138
+ * Atomic cross-process claim. Returns true only for the caller that added
139
+ * the id; a concurrent process that already added it gets false.
140
+ */
141
+ tryAdd(id) {
142
+ if (typeof id !== "string" || id.length === 0) throw new Error("AC-CS/1: id must be a non-empty string");
143
+ return withLock(
144
+ filePath,
145
+ () => {
146
+ const ids = loadIds(filePath);
147
+ if (ids.has(id)) return false;
148
+ ids.add(id);
149
+ persist(filePath, ids);
150
+ return true;
151
+ },
152
+ lockOptions,
153
+ );
154
+ },
92
155
  delete(id) {
93
- const removed = ids.delete(id);
94
- if (removed) persist(filePath, ids);
95
- return removed;
156
+ return withLock(
157
+ filePath,
158
+ () => {
159
+ const ids = loadIds(filePath);
160
+ const removed = ids.delete(id);
161
+ if (removed) persist(filePath, ids);
162
+ return removed;
163
+ },
164
+ lockOptions,
165
+ );
96
166
  },
97
167
  clear() {
98
- ids.clear();
99
- persist(filePath, ids);
168
+ withLock(
169
+ filePath,
170
+ () => {
171
+ persist(filePath, new Set());
172
+ return true;
173
+ },
174
+ lockOptions,
175
+ );
100
176
  },
101
177
  get size() {
102
- return ids.size;
178
+ return loadIds(filePath).size;
103
179
  },
104
180
  ids() {
105
- return [...ids].sort();
181
+ return [...loadIds(filePath)].sort();
106
182
  },
107
183
  toJSON() {
108
184
  return {
109
185
  spec: CONSUMPTION_STORE_VERSION,
110
- ids: [...ids].sort(),
186
+ ids: [...loadIds(filePath)].sort(),
111
187
  boundary: CONSUMPTION_STORE_BOUNDARY,
112
188
  };
113
189
  },
@@ -115,7 +191,7 @@ export function createConsumptionStore(filePath) {
115
191
 
116
192
  // Iterable like a Set for consumers that spread/iterate.
117
193
  store[Symbol.iterator] = function* () {
118
- yield* [...ids].sort();
194
+ yield* store.ids();
119
195
  };
120
196
 
121
197
  return store;
@@ -124,24 +200,24 @@ export function createConsumptionStore(filePath) {
124
200
  /**
125
201
  * Open an existing store as a read-only snapshot (no writes; mutation methods
126
202
  * are absent). Useful for inspection/audit without mutating the ledger.
203
+ * `has`/`ids`/`size` stay live reads, so an inspector sees new commits.
127
204
  */
128
205
  export function openConsumptionStore(filePath) {
129
206
  if (!filePath || typeof filePath !== "string") {
130
207
  throw new Error("AC-CS/1: openConsumptionStore requires a filePath string");
131
208
  }
132
- const ids = loadIds(filePath);
133
209
  return Object.freeze({
134
210
  spec: CONSUMPTION_STORE_VERSION,
135
211
  filePath,
136
212
  boundary: CONSUMPTION_STORE_BOUNDARY,
137
213
  has(id) {
138
- return ids.has(id);
214
+ return loadIds(filePath).has(id);
139
215
  },
140
216
  get size() {
141
- return ids.size;
217
+ return loadIds(filePath).size;
142
218
  },
143
219
  ids() {
144
- return [...ids].sort();
220
+ return [...loadIds(filePath)].sort();
145
221
  },
146
222
  });
147
223
  }