@coreguard/agent-commerce 0.1.3 → 0.1.4

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.
@@ -0,0 +1,524 @@
1
+ /**
2
+ * CoreGuard Observation Ledger (CG-OBS/1) — a verification is an event, not a
3
+ * property of the run.
4
+ *
5
+ * The outcome layer (CG-OUT/1) answers what a consumer may conclude about a
6
+ * record it was handed. It cannot answer two questions that keep deciding real
7
+ * disputes:
8
+ *
9
+ * who looked two callers on the same run, one with a file scope and one
10
+ * without, do not hold the same evidence — and the one that
11
+ * got a 403 did not fail a check, it never ran one
12
+ * when they looked the bytes had a digest before the decision and the same
13
+ * digest after it; a read at 18:00 is evidence about 18:00,
14
+ * and backdating it to 09:00 invents knowledge the approver
15
+ * never had
16
+ *
17
+ * So this layer records observations, one immutable event per (observer, read).
18
+ * An event carries the observer, the scope that observer held, the bytes they
19
+ * actually recomputed, the read time, and the action time it refers to — which
20
+ * is never substituted for the read time. Five outcomes, the same five words the
21
+ * AER-1 corpus uses, plus a named reason on `not_checked`, because "not checked"
22
+ * with no why is the vague answer that makes the remedy unknowable: wait, or
23
+ * re-scope the caller.
24
+ *
25
+ * What the ledger is for, concretely:
26
+ * - A later read adds evidence. `accrue()` reports the run as verified-by two
27
+ * observers without rewriting the first observer's 403 into a failure, and
28
+ * without a second execution (executions stays 1).
29
+ * - Access is time-varying. 403 at T1, matched at T2, 401 at T3 are three true
30
+ * statements about one run, and all three stay in the history.
31
+ * - A contradiction is a contest, not an edit. A later `verification_failed`
32
+ * marks the aggregate `contested: true` instead of silently replacing the
33
+ * verified row.
34
+ *
35
+ * BOUNDARY (standing, load-bearing):
36
+ * - This layer never asserts that an outside effect occurred. Matching bytes
37
+ * settle what the saved record says; nothing here observes the world.
38
+ * - It is pure and deterministic: no clock, no network, no keys. Every time in
39
+ * an event is supplied by the caller, which is what makes a replay exact.
40
+ * - `absent` cannot carry bytes, `not_checked` cannot omit a reason, and a
41
+ * failure cannot be anonymous. Each refusal is a named code, tested.
42
+ * - The ledger is append-only and chronological. An event whose read time
43
+ * precedes the last appended event is refused (`OUT_OF_ORDER`), because
44
+ * inserting a read "before" the moment it was needed is precisely how a
45
+ * verdict nobody had gets inherited downstream.
46
+ */
47
+
48
+ import { createHash } from "node:crypto";
49
+
50
+ export const OBSERVATION_VERSION = "CG-OBS/1";
51
+
52
+ /** The five outcomes, spelled exactly as the AER-1 corpus spells them. */
53
+ export const CHECK_OUTCOMES = Object.freeze([
54
+ "verified",
55
+ "verification_failed",
56
+ "not_checked",
57
+ "absent",
58
+ "unresolvable_record",
59
+ ]);
60
+
61
+ /**
62
+ * Why a check did not happen. The reason decides the remedy, so it is frozen:
63
+ * `access_refused` is re-scope the caller, `access_revoked` is the key is gone,
64
+ * `not_attempted` is nobody tried, `outside_scope` is this verifier never
65
+ * claims that layer, `unsupported_family` and `schema_not_implemented` are a
66
+ * build limitation named as such.
67
+ */
68
+ export const NOT_CHECKED_REASONS = Object.freeze([
69
+ "not_attempted",
70
+ "access_refused",
71
+ "access_revoked",
72
+ "outside_scope",
73
+ "unsupported_family",
74
+ "schema_not_implemented",
75
+ ]);
76
+
77
+ /** Named refusals. A rejected observation is never a generic error string. */
78
+ export const OBSERVATION_CODES = Object.freeze({
79
+ BAD_INPUT: "BAD_INPUT",
80
+ UNKNOWN_OUTCOME: "UNKNOWN_OUTCOME",
81
+ MISSING_OBSERVER: "MISSING_OBSERVER",
82
+ MISSING_ACTION: "MISSING_ACTION",
83
+ MISSING_RECORD: "MISSING_RECORD",
84
+ MISSING_SUBJECT_DIGEST: "MISSING_SUBJECT_DIGEST",
85
+ MISSING_READ_TIME: "MISSING_READ_TIME",
86
+ BAD_READ_TIME: "BAD_READ_TIME",
87
+ READ_BEFORE_ACTION: "READ_BEFORE_ACTION",
88
+ NOT_CHECKED_WITHOUT_REASON: "NOT_CHECKED_WITHOUT_REASON",
89
+ UNKNOWN_REASON: "UNKNOWN_REASON",
90
+ REASON_ON_CHECKED: "REASON_ON_CHECKED",
91
+ VERIFIED_WITHOUT_BYTES: "VERIFIED_WITHOUT_BYTES",
92
+ VERIFIED_ON_DIFFERENT_BYTES: "VERIFIED_ON_DIFFERENT_BYTES",
93
+ UNNAMED_FAILURE: "UNNAMED_FAILURE",
94
+ ABSENT_WITH_BYTES: "ABSENT_WITH_BYTES",
95
+ UNRESOLVABLE_WITHOUT_POINTER: "UNRESOLVABLE_WITHOUT_POINTER",
96
+ OUT_OF_ORDER: "OUT_OF_ORDER",
97
+ });
98
+
99
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
100
+ const text = (v) => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
101
+
102
+ /**
103
+ * RFC 3339 instant, calendar-valid, with an explicit offset. Deliberately
104
+ * strict: a date without a zone is a wall-clock guess, and two observers in two
105
+ * zones would order the same history differently.
106
+ */
107
+ const INSTANT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/;
108
+
109
+ export function parseInstant(value) {
110
+ const s = text(value);
111
+ if (!s) return null;
112
+ const m = INSTANT.exec(s);
113
+ if (!m) return null;
114
+ const [, y, mo, d, h, mi, sec] = m;
115
+ const year = Number(y);
116
+ const month = Number(mo);
117
+ const day = Number(d);
118
+ const hour = Number(h);
119
+ const minute = Number(mi);
120
+ const second = Number(sec);
121
+ if (month < 1 || month > 12) return null;
122
+ if (day < 1 || day > 31) return null;
123
+ if (hour > 23 || minute > 59 || second > 60) return null;
124
+ // Calendar validation, not just range validation: Date.parse silently rolls
125
+ // 2026-02-30 forward to 2026-03-02, which would let an impossible read time
126
+ // into an append-only history. Compare the components back, in UTC so the
127
+ // offset does not shift them, and treat a leap second as the second it names.
128
+ const calendarSecond = second === 60 ? 59 : second;
129
+ const probe = new Date(Date.UTC(year, month - 1, day, hour, minute, calendarSecond));
130
+ if (
131
+ probe.getUTCFullYear() !== year ||
132
+ probe.getUTCMonth() !== month - 1 ||
133
+ probe.getUTCDate() !== day ||
134
+ probe.getUTCHours() !== hour ||
135
+ probe.getUTCMinutes() !== minute ||
136
+ probe.getUTCSeconds() !== calendarSecond
137
+ ) {
138
+ return null;
139
+ }
140
+ const ms = Date.parse(s);
141
+ if (!Number.isFinite(ms)) return null;
142
+ return { ms, lexeme: s };
143
+ }
144
+
145
+ const sha256 = (value) => `sha256:${createHash("sha256").update(value).digest("hex")}`;
146
+
147
+ const normaliseDigest = (value) => {
148
+ const s = text(value);
149
+ if (!s) return null;
150
+ const bare = s.replace(/^sha256:/i, "").toLowerCase();
151
+ return /^[0-9a-f]{64}$/.test(bare) ? `sha256:${bare}` : null;
152
+ };
153
+
154
+ /** Deterministic event identity: same observation, same id, in every replay. */
155
+ export function observationId(event) {
156
+ const identity = JSON.stringify({
157
+ v: OBSERVATION_VERSION,
158
+ observer: event.observer,
159
+ scope: event.scope,
160
+ action_id: event.action_id,
161
+ record_id: event.record_id,
162
+ subject_digest: event.subject_digest,
163
+ observed_digest: event.observed_digest,
164
+ outcome: event.outcome,
165
+ code: event.code,
166
+ reason: event.reason,
167
+ checked_at: event.checked_at,
168
+ });
169
+ return sha256(identity);
170
+ }
171
+
172
+ /**
173
+ * Validate one observation and freeze it. Pure: no clock is read, nothing is
174
+ * inferred, and every refusal names the rule that produced it.
175
+ *
176
+ * observer who ran the check (a caller identity, not a host name)
177
+ * scope the access that observer held, e.g. "files:orders/*"
178
+ * action_id the run this observation is about; never re-executed
179
+ * record_id the record/pointer that was checked, when one exists
180
+ * subject_digest the digest the claim is about
181
+ * observed_digest what the observer actually recomputed (null if not read)
182
+ * outcome one of CHECK_OUTCOMES
183
+ * code required for verification_failed: a named reject code
184
+ * reason required for not_checked, forbidden elsewhere
185
+ * checked_at the read time, supplied by the caller
186
+ * action_at when the action happened; never used as checked_at
187
+ * evidence optional caller facts (bytes_decoded, note) — opaque here
188
+ */
189
+ export function recordObservation(input) {
190
+ if (!isObject(input)) return reject(OBSERVATION_CODES.BAD_INPUT, "an observation must be an object");
191
+
192
+ const observer = text(input.observer);
193
+ if (!observer) return reject(OBSERVATION_CODES.MISSING_OBSERVER, "an observation without an observer is an anonymous verdict");
194
+
195
+ const actionId = text(input.action_id);
196
+ if (!actionId) return reject(OBSERVATION_CODES.MISSING_ACTION, "an observation must name the run it is about");
197
+
198
+ const recordId = text(input.record_id);
199
+
200
+ const outcome = text(input.outcome);
201
+ if (!outcome) return reject(OBSERVATION_CODES.UNKNOWN_OUTCOME, `outcome is required; one of ${CHECK_OUTCOMES.join(", ")}`);
202
+ if (!CHECK_OUTCOMES.includes(outcome)) {
203
+ // Fail closed: an unrecognised outcome from somebody else's report never
204
+ // becomes a pass, and never becomes a pass by being ignored either.
205
+ return reject(OBSERVATION_CODES.UNKNOWN_OUTCOME, `unknown outcome "${outcome}"`);
206
+ }
207
+
208
+ const subjectDigest = normaliseDigest(input.subject_digest);
209
+ if (!subjectDigest) return reject(OBSERVATION_CODES.MISSING_SUBJECT_DIGEST, "an observation must name the digest it is about");
210
+
211
+ const observedRaw = input.observed_digest;
212
+ const observedDigest = observedRaw === null || observedRaw === undefined ? null : normaliseDigest(observedRaw);
213
+ if (observedRaw !== null && observedRaw !== undefined && !observedDigest) {
214
+ return reject(OBSERVATION_CODES.BAD_INPUT, "observed_digest must be a sha256 digest or null");
215
+ }
216
+
217
+ const checked = parseInstant(input.checked_at);
218
+ if (!text(input.checked_at)) return reject(OBSERVATION_CODES.MISSING_READ_TIME, "checked_at is required: the checker's read time is part of the claim");
219
+ if (!checked) return reject(OBSERVATION_CODES.BAD_READ_TIME, "checked_at must be a calendar-valid RFC 3339 instant with an explicit offset");
220
+
221
+ const action = input.action_at === null || input.action_at === undefined ? null : parseInstant(input.action_at);
222
+ if (input.action_at !== null && input.action_at !== undefined && !action) {
223
+ return reject(OBSERVATION_CODES.BAD_INPUT, "action_at must be a calendar-valid RFC 3339 instant when supplied");
224
+ }
225
+ if (action && checked.ms < action.ms) {
226
+ return reject(OBSERVATION_CODES.READ_BEFORE_ACTION, "checked_at precedes action_at: bytes cannot be read before the action that produced them");
227
+ }
228
+
229
+ const reason = text(input.reason);
230
+ const code = text(input.code);
231
+
232
+ if (outcome === "not_checked") {
233
+ if (!reason) return reject(OBSERVATION_CODES.NOT_CHECKED_WITHOUT_REASON, "not_checked must carry its reason, because the remedy differs");
234
+ if (!NOT_CHECKED_REASONS.includes(reason)) return reject(OBSERVATION_CODES.UNKNOWN_REASON, `unknown not_checked reason "${reason}"`);
235
+ } else if (reason) {
236
+ return reject(OBSERVATION_CODES.REASON_ON_CHECKED, `reason is reserved for not_checked; "${outcome}" carries a finding, not a excuse`);
237
+ }
238
+
239
+ if (outcome === "verified") {
240
+ if (!observedDigest) return reject(OBSERVATION_CODES.VERIFIED_WITHOUT_BYTES, "verified requires the bytes the observer recomputed");
241
+ if (observedDigest !== subjectDigest) {
242
+ return reject(OBSERVATION_CODES.VERIFIED_ON_DIFFERENT_BYTES, "verified requires the recomputed digest to equal the subject digest");
243
+ }
244
+ }
245
+
246
+ if (outcome === "verification_failed" && !code) {
247
+ return reject(OBSERVATION_CODES.UNNAMED_FAILURE, "verification_failed requires a named code; an anonymous no is not a finding");
248
+ }
249
+
250
+ if (outcome === "absent" && observedDigest) {
251
+ return reject(OBSERVATION_CODES.ABSENT_WITH_BYTES, "absent means nothing was read; bytes on the record make it a different outcome");
252
+ }
253
+
254
+ if (outcome === "unresolvable_record" && !recordId) {
255
+ return reject(OBSERVATION_CODES.UNRESOLVABLE_WITHOUT_POINTER, "unresolvable_record needs the pointer that could not be resolved");
256
+ }
257
+
258
+ const event = {
259
+ observation_version: OBSERVATION_VERSION,
260
+ observer,
261
+ scope: text(input.scope),
262
+ action_id: actionId,
263
+ record_id: recordId,
264
+ subject_digest: subjectDigest,
265
+ observed_digest: observedDigest,
266
+ outcome,
267
+ code: code ?? null,
268
+ reason: reason ?? null,
269
+ checked_at: checked.lexeme,
270
+ action_at: action?.lexeme ?? null,
271
+ evidence: isObject(input.evidence) ? Object.freeze({ ...input.evidence }) : null,
272
+ };
273
+ const frozen = Object.freeze({ ...event, observation_id: observationId(event) });
274
+ return Object.freeze({ ok: true, code: null, event: frozen });
275
+ }
276
+
277
+ function reject(code, detail) {
278
+ return Object.freeze({ ok: false, code, detail, event: null });
279
+ }
280
+
281
+ /** An empty ledger. Events are append-only and ordered by read time. */
282
+ export function createLedger() {
283
+ return Object.freeze({ observation_version: OBSERVATION_VERSION, events: Object.freeze([]) });
284
+ }
285
+
286
+ /**
287
+ * Append one observation. Refuses out-of-order reads: a read appended with an
288
+ * earlier `checked_at` than the ledger's newest event is a backfill, and a
289
+ * backfilled read can be made to look like evidence that existed before the
290
+ * decision. The reader who actually looked at 09:00 should have appended then.
291
+ */
292
+ export function appendObservation(ledger, input) {
293
+ const base = isObject(ledger) && Array.isArray(ledger.events) ? ledger : createLedger();
294
+ const recorded = recordObservation(input);
295
+ if (!recorded.ok) return Object.freeze({ ok: false, code: recorded.code, detail: recorded.detail, ledger: base, event: null });
296
+
297
+ const last = base.events[base.events.length - 1] ?? null;
298
+ if (last) {
299
+ const lastAt = parseInstant(last.checked_at);
300
+ const nextAt = parseInstant(recorded.event.checked_at);
301
+ if (lastAt && nextAt && nextAt.ms < lastAt.ms) {
302
+ return Object.freeze({
303
+ ok: false,
304
+ code: OBSERVATION_CODES.OUT_OF_ORDER,
305
+ detail: `read at ${recorded.event.checked_at} precedes the ledger's last read at ${last.checked_at}`,
306
+ ledger: base,
307
+ event: null,
308
+ });
309
+ }
310
+ }
311
+
312
+ const duplicate = base.events.some((e) => e.observation_id === recorded.event.observation_id);
313
+ if (duplicate) {
314
+ // Same observer, same bytes, same read time: the event already exists. Not
315
+ // an error — a replay of the same read should not double-count.
316
+ return Object.freeze({ ok: true, code: null, detail: "duplicate observation ignored", ledger: base, event: recorded.event, duplicate: true });
317
+ }
318
+
319
+ const events = Object.freeze([...base.events, recorded.event]);
320
+ return Object.freeze({
321
+ ok: true,
322
+ code: null,
323
+ detail: null,
324
+ duplicate: false,
325
+ ledger: Object.freeze({ observation_version: OBSERVATION_VERSION, events }),
326
+ event: recorded.event,
327
+ });
328
+ }
329
+
330
+ /** Build a ledger from a list of observations, refusing the whole batch on the first defect. */
331
+ export function buildLedger(inputs = []) {
332
+ let ledger = createLedger();
333
+ for (const input of inputs) {
334
+ const appended = appendObservation(ledger, input);
335
+ if (!appended.ok) return Object.freeze({ ok: false, code: appended.code, detail: appended.detail, ledger: appended.ledger });
336
+ ledger = appended.ledger;
337
+ }
338
+ return Object.freeze({ ok: true, code: null, detail: null, ledger });
339
+ }
340
+
341
+ const at = (event) => parseInstant(event.checked_at).ms;
342
+
343
+ /**
344
+ * accrue(ledger, { action_id, subject_digest? }) — what the recorded reads
345
+ * support, per observer, with the history kept intact.
346
+ *
347
+ * The aggregate is deliberately not a single verdict. It reports who confirmed
348
+ * the bytes and when, who could not and why, and whether a later read contests
349
+ * an earlier confirmation. `executions` is always 1: a re-read adds evidence, it
350
+ * never replays the action.
351
+ */
352
+ export function accrue(ledger, { action_id, subject_digest } = {}) {
353
+ const events = (isObject(ledger) && Array.isArray(ledger.events) ? ledger.events : [])
354
+ .filter((e) => (action_id ? e.action_id === action_id : true))
355
+ .filter((e) => (subject_digest ? e.subject_digest === normaliseDigest(subject_digest) : true))
356
+ .slice()
357
+ .sort((a, b) => at(a) - at(b));
358
+
359
+ if (events.length === 0) {
360
+ return Object.freeze({
361
+ observation_version: OBSERVATION_VERSION,
362
+ action_id: action_id ?? null,
363
+ events: 0,
364
+ observers: Object.freeze([]),
365
+ verified_by: Object.freeze([]),
366
+ not_checked_by: Object.freeze([]),
367
+ first_read_at: null,
368
+ last_read_at: null,
369
+ composite: "absent",
370
+ contested: false,
371
+ executions: 1,
372
+ detail: "nothing has been read for this run — silence is not a failed verification",
373
+ });
374
+ }
375
+
376
+ const byObserver = new Map();
377
+ for (const event of events) {
378
+ const entry = byObserver.get(event.observer) ?? { observer: event.observer, history: [], scopes: new Set() };
379
+ entry.history.push(event);
380
+ if (event.scope) entry.scopes.add(event.scope);
381
+ byObserver.set(event.observer, entry);
382
+ }
383
+
384
+ const observers = [...byObserver.values()].map((entry) => {
385
+ const latest = entry.history[entry.history.length - 1];
386
+ return Object.freeze({
387
+ observer: entry.observer,
388
+ latest_outcome: latest.outcome,
389
+ latest_code: latest.code,
390
+ latest_reason: latest.reason,
391
+ latest_checked_at: latest.checked_at,
392
+ scopes: Object.freeze([...entry.scopes]),
393
+ reads: entry.history.length,
394
+ observation_ids: Object.freeze(entry.history.map((e) => e.observation_id)),
395
+ });
396
+ });
397
+
398
+ const verifiedBy = observers.filter((o) => o.latest_outcome === "verified").map((o) => o.observer);
399
+ const notCheckedBy = observers
400
+ .filter((o) => o.latest_outcome === "not_checked")
401
+ .map((o) => Object.freeze({ observer: o.observer, reason: o.latest_reason, at: o.latest_checked_at }));
402
+ const failedBy = observers.filter((o) => o.latest_outcome === "verification_failed").map((o) => o.observer);
403
+ const absentBy = observers.filter((o) => o.latest_outcome === "absent").map((o) => o.observer);
404
+
405
+ // A contest is a later read that disagrees with an earlier confirmation. It is
406
+ // reported, never resolved here: resolving it is a policy decision, and this
407
+ // layer does not decide policy.
408
+ // Only a read that looked at bytes and refused them contests a confirmation.
409
+ // An access refusal afterwards is a different observer's state, not a
410
+ // contradiction: it says the second observer could not look, not that the
411
+ // first observer's match was wrong. Treating those as contests would make
412
+ // every partial-access run permanently disputed and teach readers to ignore
413
+ // the flag.
414
+ const firstVerified = events.find((e) => e.outcome === "verified") ?? null;
415
+ const contested = firstVerified !== null && events.some((e) => at(e) > at(firstVerified) && e.outcome === "verification_failed");
416
+
417
+ let composite;
418
+ if (firstVerified) {
419
+ composite = "verified";
420
+ } else if (failedBy.length > 0) {
421
+ composite = "verification_failed";
422
+ } else if (absentBy.length > 0 && absentBy.length === observers.length) {
423
+ composite = "absent";
424
+ } else if (notCheckedBy.length > 0) {
425
+ composite = "not_checked";
426
+ } else {
427
+ composite = "unresolvable_record";
428
+ }
429
+
430
+ return Object.freeze({
431
+ observation_version: OBSERVATION_VERSION,
432
+ action_id: action_id ?? events[0].action_id,
433
+ events: events.length,
434
+ observers: Object.freeze(observers),
435
+ verified_by: Object.freeze(verifiedBy),
436
+ not_checked_by: Object.freeze(notCheckedBy),
437
+ failed_by: Object.freeze(failedBy),
438
+ absent_by: Object.freeze(absentBy),
439
+ first_read_at: events[0].checked_at,
440
+ first_verified_at: firstVerified?.checked_at ?? null,
441
+ last_read_at: events[events.length - 1].checked_at,
442
+ composite,
443
+ contested,
444
+ executions: 1,
445
+ detail: null,
446
+ });
447
+ }
448
+
449
+ /**
450
+ * The one-line statement the layer exists to make printable: who saw what, for
451
+ * which bytes, at which time. Never collapses two observers into one verdict.
452
+ */
453
+ export function describeAccrual(accrual) {
454
+ if (!accrual || accrual.events === 0) return "no read recorded for this run";
455
+ // Confirmations first: the sentence a risk system quotes is "who matched the
456
+ // bytes", and burying that after two observers who could not read invites the
457
+ // reader to scan for the refusal and stop there.
458
+ const ordered = [...accrual.observers].sort((a, b) => {
459
+ const rank = (o) => (o.latest_outcome === "verified" ? 0 : o.latest_outcome === "not_checked" ? 2 : 1);
460
+ return rank(a) - rank(b) || a.observer.localeCompare(b.observer);
461
+ });
462
+ const parts = ordered.map((o) => {
463
+ const verb =
464
+ o.latest_outcome === "verified"
465
+ ? "matched the bytes"
466
+ : o.latest_outcome === "not_checked"
467
+ ? `did not check (${o.latest_reason})`
468
+ : o.latest_outcome === "verification_failed"
469
+ ? `refused (${o.latest_code})`
470
+ : o.latest_outcome === "absent"
471
+ ? "found nothing to read"
472
+ : "could not resolve the record";
473
+ return `${o.observer} ${verb} at ${o.latest_checked_at}`;
474
+ });
475
+ const contested = accrual.contested ? " · contested by a later read" : "";
476
+ const confirmations = accrual.verified_by.length;
477
+ return `${confirmations} independent confirmation${confirmations === 1 ? "" : "s"}: ${parts.join("; ")}${contested} · 1 execution`;
478
+ }
479
+
480
+ /** Self-check for callers that cannot run the test suite. */
481
+ export function selfCheck() {
482
+ const subject = `sha256:${"0".repeat(64)}`;
483
+ const base = {
484
+ observer: "psp:risk-eu",
485
+ action_id: "run-1",
486
+ record_id: "130da435-e157-498e-af90-605866a86a27",
487
+ subject_digest: subject,
488
+ observed_digest: subject,
489
+ action_at: "2026-11-19T16:00:00Z",
490
+ };
491
+ const verified = recordObservation({ ...base, outcome: "verified", checked_at: "2026-11-19T16:40:00Z" });
492
+ const unchecked = recordObservation({
493
+ ...base,
494
+ observed_digest: null,
495
+ outcome: "not_checked",
496
+ reason: "access_refused",
497
+ checked_at: "2026-11-19T16:40:00Z",
498
+ });
499
+ const noReason = recordObservation({
500
+ ...base,
501
+ observed_digest: null,
502
+ outcome: "not_checked",
503
+ checked_at: "2026-11-19T16:40:00Z",
504
+ });
505
+ const backdated = recordObservation({ ...base, outcome: "verified", checked_at: "2026-11-19T15:00:00Z" });
506
+ const built = buildLedger([
507
+ { ...base, observed_digest: null, outcome: "not_checked", reason: "access_refused", checked_at: "2026-11-19T16:10:00Z" },
508
+ { ...base, observer: "auditor:files", outcome: "verified", checked_at: "2026-11-19T16:40:00Z" },
509
+ ]);
510
+ const checks = [
511
+ { name: "verified observation recorded", pass: verified.ok === true },
512
+ { name: "not_checked keeps its reason", pass: unchecked.ok === true && unchecked.event.reason === "access_refused" },
513
+ { name: "not_checked without a reason is refused", pass: noReason.code === OBSERVATION_CODES.NOT_CHECKED_WITHOUT_REASON },
514
+ { name: "a read before the action is refused", pass: backdated.code === OBSERVATION_CODES.READ_BEFORE_ACTION },
515
+ { name: "two observers accrue two independent facts", pass: built.ok === true && accrue(built.ledger, { action_id: "run-1" }).verified_by.length === 1 },
516
+ ];
517
+ return Object.freeze({
518
+ observationVersion: OBSERVATION_VERSION,
519
+ outcomes: CHECK_OUTCOMES,
520
+ reasons: NOT_CHECKED_REASONS,
521
+ checks,
522
+ ok: checks.every((c) => c.pass),
523
+ });
524
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@coreguard/agent-commerce",
3
- "version": "0.1.3",
4
- "description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases \u2014 SDK, REST surface, and a stdio MCP server (JSON-RPC 2.0, offline, zero keys)",
3
+ "version": "0.1.4",
4
+ "description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases — SDK, REST surface, and a stdio MCP server (26 tools, JSON-RPC 2.0, offline, zero keys)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "exports": {
@@ -18,6 +18,7 @@
18
18
  "./profile-ref.mjs": "./profile-ref.mjs",
19
19
  "./attest.mjs": "./attest.mjs",
20
20
  "./aer1.mjs": "./aer1.mjs",
21
+ "./observations.mjs": "./observations.mjs",
21
22
  "./anchor.mjs": "./anchor.mjs",
22
23
  "./composition.mjs": "./composition.mjs",
23
24
  "./reference.mjs": "./reference.mjs",
@@ -26,7 +27,15 @@
26
27
  "./decision.mjs": "./decision.mjs",
27
28
  "./control-plane.mjs": "./control-plane.mjs",
28
29
  "./control-plane-http.mjs": "./control-plane-http.mjs",
29
- "./control-plane-cli.mjs": "./control-plane-cli.mjs"
30
+ "./control-plane-cli.mjs": "./control-plane-cli.mjs",
31
+ "./prod/schema.mjs": "./prod/schema.mjs",
32
+ "./prod/sqlite-storage.mjs": "./prod/sqlite-storage.mjs",
33
+ "./prod/migrate.mjs": "./prod/migrate.mjs",
34
+ "./prod/rbac.mjs": "./prod/rbac.mjs",
35
+ "./prod/observability.mjs": "./prod/observability.mjs",
36
+ "./prod/kms-anchor.mjs": "./prod/kms-anchor.mjs",
37
+ "./machine-economy.mjs": "./machine-economy.mjs",
38
+ "./cgcp-mcp-tools.mjs": "./cgcp-mcp-tools.mjs"
30
39
  },
31
40
  "bin": {
32
41
  "coreguard-agent-commerce-mcp": "./bin/mcp.mjs"
@@ -37,22 +46,31 @@
37
46
  "anchor.mjs",
38
47
  "attest.mjs",
39
48
  "bin/mcp.mjs",
49
+ "cgcp-mcp-tools.mjs",
40
50
  "client.mjs",
41
51
  "composition.mjs",
42
52
  "consumption-store.mjs",
43
- "control-plane.mjs",
44
- "control-plane-http.mjs",
45
53
  "control-plane-cli.mjs",
54
+ "control-plane-http.mjs",
55
+ "control-plane.mjs",
46
56
  "decision.mjs",
47
57
  "firewall.mjs",
48
58
  "http.mjs",
49
59
  "identity.mjs",
50
60
  "index.d.ts",
51
61
  "index.mjs",
62
+ "machine-economy.mjs",
52
63
  "mcp.mjs",
64
+ "observations.mjs",
53
65
  "outcomes-bridge.mjs",
54
66
  "outcomes.mjs",
55
67
  "policy-context.mjs",
68
+ "prod/kms-anchor.mjs",
69
+ "prod/migrate.mjs",
70
+ "prod/observability.mjs",
71
+ "prod/rbac.mjs",
72
+ "prod/schema.mjs",
73
+ "prod/sqlite-storage.mjs",
56
74
  "profile-ref.mjs",
57
75
  "reference.mjs",
58
76
  "risk-cli.mjs",
@@ -86,7 +104,11 @@
86
104
  "fail-closed",
87
105
  "agentic-payments",
88
106
  "cgep",
89
- "coreguard"
107
+ "coreguard",
108
+ "x402",
109
+ "machine-economy",
110
+ "robotics",
111
+ "delegation"
90
112
  ],
91
113
  "license": "MIT"
92
114
  }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * M4 (BUILT as interfaces/local adapters): KMS and audit anchor abstractions.
3
+ * NOT_BUILT: real KMS/HSM integration, managed external witness/on-chain anchor service.
4
+ */
5
+ import { createHash, createHmac, randomUUID } from "node:crypto";
6
+
7
+ export function createLocalKeyProvider({ keys = {} } = {}) {
8
+ const store = new Map(Object.entries(keys));
9
+ return {
10
+ kind: "local-dev-only",
11
+ async getActiveKey(keyId = "default") {
12
+ const k = store.get(keyId);
13
+ if (!k) throw new Error(`key not found: ${keyId}`);
14
+ return { keyId, material: k };
15
+ },
16
+ async rotateKey(keyId = "default", material) {
17
+ const next = material || randomUUID().replace(/-/g, "") + randomUUID().replace(/-/g, "");
18
+ store.set(keyId, next);
19
+ return { keyId, rotatedAt: new Date().toISOString(), fingerprint: fingerprint(next) };
20
+ },
21
+ async sign(keyId, payload) {
22
+ const { material } = await this.getActiveKey(keyId);
23
+ const sig = createHmac("sha256", String(material)).update(payload).digest("hex");
24
+ return { alg: "HMAC-SHA256", keyId, sig, fingerprint: fingerprint(material) };
25
+ },
26
+ };
27
+ }
28
+
29
+ function fingerprint(material) { return "sha256:" + createHash("sha256").update(String(material)).digest("hex").slice(0, 16); }
30
+
31
+ export function createAnchorProvider({ mode = "local-file", hmacKey = null } = {}) {
32
+ return {
33
+ kind: mode,
34
+ async anchor(head) {
35
+ const base = { headHash: head.headHash, length: head.length, at: new Date().toISOString(), mode };
36
+ if (hmacKey) base.hmacSha256 = createHmac("sha256", String(hmacKey)).update(JSON.stringify({ headHash: base.headHash, length: base.length })).digest("hex");
37
+ base.receiptId = "anchor_" + randomUUID();
38
+ base.boundary = mode === "local-file" ? "local witness only; NOT_BUILT external witness" : "adapter boundary; external service NOT_BUILT in this environment";
39
+ return base;
40
+ },
41
+ async verify(receipt, head) {
42
+ const headOk = receipt.headHash === head.headHash && receipt.length === head.length;
43
+ let hmacOk = true;
44
+ if (receipt.hmacSha256) {
45
+ if (!hmacKey) hmacOk = false;
46
+ else hmacOk = receipt.hmacSha256 === createHmac("sha256", String(hmacKey)).update(JSON.stringify({ headHash: head.headHash, length: head.length })).digest("hex");
47
+ }
48
+ return { ok: headOk && hmacOk, headOk, hmacOk, mode };
49
+ },
50
+ };
51
+ }