@coreguard/agent-commerce 0.1.2 → 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.
@@ -0,0 +1,923 @@
1
+ /**
2
+ * CoreGuard Policy & Evidence Control Plane (CGCP/1) — self-hosted, BUILT.
3
+ *
4
+ * One file-backed plane for the questions an operator asks about agent
5
+ * commerce: which agents exist, which policy each one is bound to, what that
6
+ * policy allows, what was approved, what was executed, what was verified, what
7
+ * has been spent, and what was revoked — with an append-only, hash-chained
8
+ * audit trail over every mutation.
9
+ *
10
+ * BUILT_NOW (this module, no external services, no dependencies):
11
+ * - agents: registry, status, one bound policy, metadata, revocation;
12
+ * - policies: immutable VERSION history per policy id (upsert appends a
13
+ * version; the active version is what evaluates), per-transaction limit,
14
+ * rolling-24h limit, lifetime limit, currency, merchant and address
15
+ * allow/deny lists, approval threshold;
16
+ * - approvals: request → approve/reject, expiry, amount/merchant/address
17
+ * binding (an approval for one order cannot authorise another);
18
+ * - decisions: deterministic allow/deny with named reasons and a per-check
19
+ * record;
20
+ * - executions: append-only ledger that re-evaluates at commit time (an agent
21
+ * revoked between authorise and commit is refused), records the spend, and
22
+ * refuses duplicate execution ids;
23
+ * - verifications: receipt/consent verdict records attached to executions;
24
+ * - revocation: agents and policies, with reason and audit entry;
25
+ * - audit: append-only hash-chained log + `verifyAuditChain()` that names the
26
+ * first broken sequence;
27
+ * - report: counts, active policy specs, spend totals, chain status, and a
28
+ * body hash over the canonical report.
29
+ *
30
+ * CONCURRENCY (honest): every mutation takes an exclusive lock file
31
+ * (`<store>.lock`, O_EXCL) and RELOADS the store under the lock, so two
32
+ * processes on one host cannot clobber each other. A stale lock (holder died)
33
+ * is broken after `staleLockMs`. This is a single-host guarantee.
34
+ *
35
+ * NOT_BUILT (explicit, and the reason this is not sold as enterprise SaaS):
36
+ * multi-tenant isolation, multi-user RBAC/ABAC/SSO/SCIM, distributed storage or
37
+ * consensus/HA, cross-region replication, KMS/HSM-backed secrets, managed
38
+ * hosting with an SLA, payment processing or custody. VERIFIED ≠ SAFE; this
39
+ * plane records decisions, it does not make an unsafe order safe.
40
+ */
41
+
42
+ import {
43
+ mkdirSync,
44
+ readFileSync,
45
+ writeFileSync,
46
+ renameSync,
47
+ openSync,
48
+ closeSync,
49
+ statSync,
50
+ unlinkSync,
51
+ } from "node:fs";
52
+ import { dirname } from "node:path";
53
+ import { randomUUID, createHash } from "node:crypto";
54
+
55
+ export const CONTROL_PLANE_VERSION = "CGCP/1";
56
+ export const CONTROL_PLANE_SCHEMA = "coreguard.control-plane/1";
57
+ export const CONTROL_PLANE_BOUNDARY =
58
+ "self-hosted single-host control plane (file-backed, lock-guarded, hash-chained audit); " +
59
+ "NOT_BUILT: multi-tenant RBAC/SSO/SCIM, distributed HA/consensus, KMS/HSM, managed SLA, payment custody; " +
60
+ "VERIFIED ≠ SAFE";
61
+
62
+ export const CONTROL_PLANE_DECISION_REASONS = Object.freeze([
63
+ "UNKNOWN_AGENT",
64
+ "AGENT_REVOKED_OR_INACTIVE",
65
+ "UNKNOWN_POLICY",
66
+ "POLICY_INACTIVE",
67
+ "POLICY_UNREADABLE",
68
+ "MERCHANT_DENIED",
69
+ "MERCHANT_NOT_ALLOWED",
70
+ "ADDRESS_DENIED",
71
+ "ADDRESS_NOT_ALLOWED",
72
+ "CURRENCY_MISMATCH",
73
+ "SPEND_LIMIT_EXCEEDED",
74
+ "DAILY_LIMIT_EXCEEDED",
75
+ "TOTAL_LIMIT_EXCEEDED",
76
+ "APPROVAL_REQUIRED",
77
+ "APPROVAL_NOT_APPROVED",
78
+ "APPROVAL_MISMATCH",
79
+ "APPROVAL_EXPIRED",
80
+ ]);
81
+
82
+ const ZERO_HASH = "sha256:" + "0".repeat(64);
83
+ const DECIMAL = /^[0-9]+$/;
84
+ const DAY_MS = 24 * 60 * 60 * 1000;
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // Canonical JSON + hashing (one representation, used for every commitment)
88
+ // ---------------------------------------------------------------------------
89
+
90
+ export function canonicalJson(value) {
91
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
92
+ if (Array.isArray(value)) return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
93
+ const keys = Object.keys(value).sort();
94
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
95
+ }
96
+
97
+ const sha256 = (s) => createHash("sha256").update(Buffer.from(s, "utf8")).digest("hex");
98
+ const digestOf = (value) => "sha256:" + sha256(canonicalJson(value));
99
+
100
+ // ---------------------------------------------------------------------------
101
+ // Input validation — malformed developer input throws; malformed BUSINESS data
102
+ // (an unreadable policy version) refuses with a named reason instead of guessing.
103
+ // ---------------------------------------------------------------------------
104
+
105
+ function optionalDecimal(value, field) {
106
+ if (value === undefined || value === null) return null;
107
+ const s = typeof value === "bigint" ? value.toString() : String(value);
108
+ if (!DECIMAL.test(s)) throw new TypeError(`${field} must be a non-negative integer string (minor units)`);
109
+ return BigInt(s).toString();
110
+ }
111
+
112
+ function requiredString(value, field) {
113
+ if (typeof value !== "string" || value.length === 0) throw new TypeError(`${field} must be a non-empty string`);
114
+ return value;
115
+ }
116
+
117
+ function stringArray(value, field) {
118
+ if (value === undefined || value === null) return [];
119
+ if (!Array.isArray(value)) throw new TypeError(`${field} must be an array of strings`);
120
+ for (const v of value) if (typeof v !== "string" || v.length === 0) throw new TypeError(`${field} must contain non-empty strings`);
121
+ return [...new Set(value)];
122
+ }
123
+
124
+ function normalizePolicySpec(policy = {}) {
125
+ return {
126
+ spendLimitMinor: optionalDecimal(policy.spendLimitMinor, "spendLimitMinor"),
127
+ dailyLimitMinor: optionalDecimal(policy.dailyLimitMinor, "dailyLimitMinor"),
128
+ totalLimitMinor: optionalDecimal(policy.totalLimitMinor, "totalLimitMinor"),
129
+ requireApprovalAboveMinor: optionalDecimal(policy.requireApprovalAboveMinor, "requireApprovalAboveMinor"),
130
+ currency: policy.currency == null ? null : String(policy.currency),
131
+ allowMerchants: stringArray(policy.allowMerchants, "allowMerchants"),
132
+ denyMerchants: stringArray(policy.denyMerchants, "denyMerchants"),
133
+ allowAddresses: stringArray(policy.allowAddresses, "allowAddresses"),
134
+ denyAddresses: stringArray(policy.denyAddresses, "denyAddresses"),
135
+ rules: Array.isArray(policy.rules) ? policy.rules : [],
136
+ };
137
+ }
138
+
139
+ // ---------------------------------------------------------------------------
140
+ // Store I/O
141
+ // ---------------------------------------------------------------------------
142
+
143
+ const sleep = (() => {
144
+ const cell = new Int32Array(new SharedArrayBuffer(4));
145
+ return (ms) => Atomics.wait(cell, 0, 0, ms);
146
+ })();
147
+
148
+ function defaultState() {
149
+ return {
150
+ version: CONTROL_PLANE_VERSION,
151
+ schema: CONTROL_PLANE_SCHEMA,
152
+ boundary: CONTROL_PLANE_BOUNDARY,
153
+ createdAt: null,
154
+ updatedAt: null,
155
+ agents: {},
156
+ policies: {},
157
+ approvals: {},
158
+ executions: [],
159
+ verifications: [],
160
+ revocations: {},
161
+ audit: [],
162
+ };
163
+ }
164
+
165
+ function loadState(path) {
166
+ try {
167
+ const data = JSON.parse(readFileSync(path, "utf8"));
168
+ if (!data || data.schema !== CONTROL_PLANE_SCHEMA) throw new Error("not a CGCP/1 control-plane store");
169
+ return data;
170
+ } catch (err) {
171
+ if (err && err.code === "ENOENT") return null;
172
+ throw err;
173
+ }
174
+ }
175
+
176
+ function saveState(path, state) {
177
+ mkdirSync(dirname(path), { recursive: true });
178
+ const tmp = path + ".tmp-" + process.pid + "-" + Math.random().toString(16).slice(2);
179
+ writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", "utf8");
180
+ renameSync(tmp, path);
181
+ }
182
+
183
+ function appendAudit(state, type, detail, at) {
184
+ const prevHash = state.audit.length ? state.audit[state.audit.length - 1].hash : ZERO_HASH;
185
+ const body = { seq: state.audit.length + 1, type, at, detail, prevHash };
186
+ const entry = { ...body, hash: digestOf(body) };
187
+ state.audit.push(entry);
188
+ return entry;
189
+ }
190
+
191
+ /**
192
+ * Re-derive the whole audit chain from the stored entries. Pure over the state:
193
+ * a rewritten entry, a removed entry, a reordered entry or a broken prevHash
194
+ * names the first sequence that does not recompute.
195
+ */
196
+ export function verifyAuditChain(state) {
197
+ const audit = Array.isArray(state?.audit) ? state.audit : [];
198
+ let prev = ZERO_HASH;
199
+ for (let i = 0; i < audit.length; i += 1) {
200
+ const entry = audit[i];
201
+ const expectedSeq = i + 1;
202
+ if (!entry || typeof entry !== "object") {
203
+ return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "entry is not an object", headHash: prev };
204
+ }
205
+ if (entry.seq !== expectedSeq) {
206
+ return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "sequence gap or reorder", headHash: prev };
207
+ }
208
+ if (entry.prevHash !== prev) {
209
+ return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "previous hash does not chain", headHash: prev };
210
+ }
211
+ const recomputed = digestOf({ seq: entry.seq, type: entry.type, at: entry.at, detail: entry.detail, prevHash: entry.prevHash });
212
+ if (entry.hash !== recomputed) {
213
+ return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "entry hash does not recompute", headHash: prev };
214
+ }
215
+ prev = entry.hash;
216
+ }
217
+ return { ok: true, length: audit.length, brokenAt: null, reason: null, headHash: prev };
218
+ }
219
+
220
+ // ---------------------------------------------------------------------------
221
+ // Evaluation
222
+ // ---------------------------------------------------------------------------
223
+
224
+ function activeVersion(policy) {
225
+ if (!policy || !Array.isArray(policy.versions) || policy.versions.length === 0) return null;
226
+ return policy.versions.find((v) => v.version === policy.currentVersion) ?? null;
227
+ }
228
+
229
+ function spendTotals(executions, { agentId, policyId, nowMs }) {
230
+ let rolling24h = 0n;
231
+ let total = 0n;
232
+ for (const e of executions) {
233
+ if (agentId != null && e.agentId !== agentId) continue;
234
+ if (policyId != null && e.policyId !== policyId) continue;
235
+ if (e.amountMinor == null) continue;
236
+ let amount;
237
+ try {
238
+ amount = BigInt(e.amountMinor);
239
+ } catch {
240
+ continue;
241
+ }
242
+ total += amount;
243
+ const at = Date.parse(e.at);
244
+ if (Number.isFinite(at) && nowMs - at <= DAY_MS) rolling24h += amount;
245
+ }
246
+ return { rolling24hMinor: rolling24h, totalMinor: total };
247
+ }
248
+
249
+ function approvalProblem({ state, approvalId, agentId, policyId, merchant, address, amountMinor, nowMs }) {
250
+ if (approvalId == null) return "APPROVAL_REQUIRED";
251
+ const approval = state.approvals[approvalId];
252
+ if (!approval) return "APPROVAL_REQUIRED";
253
+ if (approval.status !== "approved") return "APPROVAL_NOT_APPROVED";
254
+ if (approval.expiresAt && Date.parse(approval.expiresAt) < nowMs) return "APPROVAL_EXPIRED";
255
+ const same = (a, b) => (a == null ? b == null : String(a) === String(b));
256
+ if (!same(approval.agentId, agentId)) return "APPROVAL_MISMATCH";
257
+ if (approval.policyId != null && !same(approval.policyId, policyId)) return "APPROVAL_MISMATCH";
258
+ if (!same(approval.merchant, merchant)) return "APPROVAL_MISMATCH";
259
+ if (!same(approval.address, address)) return "APPROVAL_MISMATCH";
260
+ if (!same(approval.amountMinor, amountMinor)) return "APPROVAL_MISMATCH";
261
+ return null;
262
+ }
263
+
264
+ function evaluateRequest({ state, agentId, policyId, merchant, address, amountMinor, currency, approvalId, nowMs, nowIso }) {
265
+ const reasons = [];
266
+ const checks = {};
267
+
268
+ const agent = agentId != null ? state.agents[agentId] : null;
269
+ checks.agent = { ok: false, status: agent ? agent.status : null, boundPolicyId: agent?.policyId ?? null };
270
+ if (!agent) {
271
+ reasons.push("UNKNOWN_AGENT");
272
+ } else if (agent.status !== "active") {
273
+ reasons.push("AGENT_REVOKED_OR_INACTIVE");
274
+ } else {
275
+ checks.agent.ok = true;
276
+ }
277
+
278
+ const resolvedPolicyId = policyId ?? agent?.policyId ?? null;
279
+ const policy = resolvedPolicyId != null ? state.policies[resolvedPolicyId] : null;
280
+ const version = activeVersion(policy);
281
+ checks.policy = { ok: false, policyId: resolvedPolicyId, version: version?.version ?? null, status: policy?.status ?? null };
282
+
283
+ if (!policy) {
284
+ reasons.push("UNKNOWN_POLICY");
285
+ } else if (policy.status !== "active") {
286
+ reasons.push("POLICY_INACTIVE");
287
+ } else if (!version || !version.spec) {
288
+ reasons.push("POLICY_UNREADABLE");
289
+ } else {
290
+ checks.policy.ok = true;
291
+ }
292
+
293
+ const spec = version?.spec ?? null;
294
+ if (spec) {
295
+ checks.merchant = { ok: true, merchant: merchant ?? null, denied: false, notOnAllowlist: false };
296
+ if (merchant != null && spec.denyMerchants.includes(merchant)) {
297
+ reasons.push("MERCHANT_DENIED");
298
+ checks.merchant.denied = true;
299
+ checks.merchant.ok = false;
300
+ }
301
+ if (merchant != null && spec.allowMerchants.length > 0 && !spec.allowMerchants.includes(merchant)) {
302
+ reasons.push("MERCHANT_NOT_ALLOWED");
303
+ checks.merchant.notOnAllowlist = true;
304
+ checks.merchant.ok = false;
305
+ }
306
+
307
+ checks.address = { ok: true, address: address ?? null, denied: false, notOnAllowlist: false };
308
+ if (address != null && spec.denyAddresses.includes(address)) {
309
+ reasons.push("ADDRESS_DENIED");
310
+ checks.address.denied = true;
311
+ checks.address.ok = false;
312
+ }
313
+ if (address != null && spec.allowAddresses.length > 0 && !spec.allowAddresses.includes(address)) {
314
+ reasons.push("ADDRESS_NOT_ALLOWED");
315
+ checks.address.notOnAllowlist = true;
316
+ checks.address.ok = false;
317
+ }
318
+
319
+ checks.currency = { ok: true, expected: spec.currency, observed: currency ?? null };
320
+ if (spec.currency != null && currency != null && String(spec.currency) !== String(currency)) {
321
+ reasons.push("CURRENCY_MISMATCH");
322
+ checks.currency.ok = false;
323
+ }
324
+
325
+ const amount = amountMinor == null ? null : BigInt(amountMinor);
326
+ const totals = spendTotals(state.executions, {
327
+ agentId,
328
+ policyId: resolvedPolicyId,
329
+ nowMs,
330
+ });
331
+ const projected24h = totals.rolling24hMinor + (amount ?? 0n);
332
+ const projectedTotal = totals.totalMinor + (amount ?? 0n);
333
+
334
+ checks.amount = {
335
+ ok: true,
336
+ amountMinor: amountMinor ?? null,
337
+ perTransactionLimitMinor: spec.spendLimitMinor,
338
+ projected24hMinor: projected24h.toString(),
339
+ dailyLimitMinor: spec.dailyLimitMinor,
340
+ projectedTotalMinor: projectedTotal.toString(),
341
+ totalLimitMinor: spec.totalLimitMinor,
342
+ };
343
+ if (amount != null && spec.spendLimitMinor != null && amount > BigInt(spec.spendLimitMinor)) {
344
+ reasons.push("SPEND_LIMIT_EXCEEDED");
345
+ checks.amount.ok = false;
346
+ }
347
+ if (amount != null && spec.dailyLimitMinor != null && projected24h > BigInt(spec.dailyLimitMinor)) {
348
+ reasons.push("DAILY_LIMIT_EXCEEDED");
349
+ checks.amount.ok = false;
350
+ }
351
+ if (amount != null && spec.totalLimitMinor != null && projectedTotal > BigInt(spec.totalLimitMinor)) {
352
+ reasons.push("TOTAL_LIMIT_EXCEEDED");
353
+ checks.amount.ok = false;
354
+ }
355
+
356
+ const needsApproval =
357
+ spec.requireApprovalAboveMinor != null && amount != null && amount > BigInt(spec.requireApprovalAboveMinor);
358
+ checks.approval = { ok: true, required: needsApproval, approvalId: approvalId ?? null, problem: null };
359
+ if (needsApproval) {
360
+ const problem = approvalProblem({ state, approvalId, agentId, policyId: resolvedPolicyId, merchant, address, amountMinor, nowMs });
361
+ if (problem) {
362
+ reasons.push(problem);
363
+ checks.approval.ok = false;
364
+ checks.approval.problem = problem;
365
+ }
366
+ }
367
+ }
368
+
369
+ return {
370
+ version: CONTROL_PLANE_VERSION,
371
+ allowed: reasons.length === 0,
372
+ reasons,
373
+ checks,
374
+ agentId: agentId ?? null,
375
+ policyId: resolvedPolicyId,
376
+ policyVersion: version?.version ?? null,
377
+ merchant: merchant ?? null,
378
+ address: address ?? null,
379
+ amountMinor: amountMinor ?? null,
380
+ currency: currency ?? null,
381
+ approvalId: approvalId ?? null,
382
+ at: nowIso,
383
+ boundary: CONTROL_PLANE_BOUNDARY,
384
+ };
385
+ }
386
+
387
+ // ---------------------------------------------------------------------------
388
+ // The plane
389
+ // ---------------------------------------------------------------------------
390
+
391
+ /**
392
+ * Open (or create) a control plane at `storePath`.
393
+ *
394
+ * Options:
395
+ * now — () => Date, injectable clock (tests pin it)
396
+ * lockTimeoutMs— how long a mutation waits for the file lock (default 5000)
397
+ * staleLockMs — age after which an abandoned lock is broken (default 30000)
398
+ */
399
+ export function createControlPlane({
400
+ storePath,
401
+ now = () => new Date(),
402
+ lockTimeoutMs = 5000,
403
+ staleLockMs = 30000,
404
+ } = {}) {
405
+ if (typeof storePath !== "string" || storePath.length === 0) throw new TypeError("CGCP/1: storePath is required");
406
+ const lockPath = storePath + ".lock";
407
+ const nowIso = () => now().toISOString();
408
+ const nowMs = () => now().getTime();
409
+
410
+ function acquireLock() {
411
+ const deadline = Date.now() + lockTimeoutMs;
412
+ for (;;) {
413
+ try {
414
+ const fd = openSync(lockPath, "wx");
415
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));
416
+ closeSync(fd);
417
+ return;
418
+ } catch (err) {
419
+ if (err.code !== "EEXIST") throw err;
420
+ try {
421
+ const st = statSync(lockPath);
422
+ if (Date.now() - st.mtimeMs > staleLockMs) unlinkSync(lockPath);
423
+ } catch {
424
+ // The holder released between EEXIST and stat — retry immediately.
425
+ }
426
+ if (Date.now() > deadline) {
427
+ throw new Error(`CGCP/1: store is locked by another process (${lockPath})`);
428
+ }
429
+ sleep(3 + Math.floor(Math.random() * 5));
430
+ }
431
+ }
432
+ }
433
+
434
+ function releaseLock() {
435
+ try {
436
+ unlinkSync(lockPath);
437
+ } catch {
438
+ // Nothing to release.
439
+ }
440
+ }
441
+
442
+ function read() {
443
+ return loadState(storePath) ?? defaultState();
444
+ }
445
+
446
+ /** Every mutation: exclusive lock → reload → mutate → atomic save → unlock. */
447
+ function mutate(fn) {
448
+ acquireLock();
449
+ try {
450
+ const state = read();
451
+ if (!state.createdAt) state.createdAt = nowIso();
452
+ const result = fn(state);
453
+ state.updatedAt = nowIso();
454
+ saveState(storePath, state);
455
+ return result;
456
+ } finally {
457
+ releaseLock();
458
+ }
459
+ }
460
+
461
+ function view(fn) {
462
+ return fn(read());
463
+ }
464
+
465
+ // -- agents --------------------------------------------------------------
466
+
467
+ function upsertAgent(agent = {}) {
468
+ const id = requiredString(agent.id, "agent.id");
469
+ return mutate((state) => {
470
+ const prev = state.agents[id] ?? null;
471
+ const status = agent.status ?? prev?.status ?? "active";
472
+ if (!["active", "inactive", "revoked"].includes(status)) throw new TypeError("agent.status must be active, inactive or revoked");
473
+ if (prev?.status === "revoked" && status !== "revoked") {
474
+ throw new Error("CGCP/1: a revoked agent cannot be reactivated (create a new agent id)");
475
+ }
476
+ const record = {
477
+ ...(prev ?? {}),
478
+ ...agent,
479
+ id,
480
+ status,
481
+ policyId: agent.policyId ?? prev?.policyId ?? null,
482
+ metadata: agent.metadata ?? prev?.metadata ?? {},
483
+ createdAt: prev?.createdAt ?? nowIso(),
484
+ updatedAt: nowIso(),
485
+ };
486
+ state.agents[id] = record;
487
+ appendAudit(state, prev ? "agent.updated" : "agent.created", { agentId: id, status, policyId: record.policyId }, nowIso());
488
+ return record;
489
+ });
490
+ }
491
+
492
+ function getAgent(agentId) {
493
+ return view((state) => state.agents[agentId] ?? null);
494
+ }
495
+
496
+ function listAgents() {
497
+ return view((state) => Object.values(state.agents));
498
+ }
499
+
500
+ function bindPolicy(agentId, policyId) {
501
+ return mutate((state) => {
502
+ const agent = state.agents[agentId];
503
+ if (!agent) throw new Error("CGCP/1: unknown agent");
504
+ if (!state.policies[policyId]) throw new Error("CGCP/1: unknown policy");
505
+ agent.policyId = policyId;
506
+ agent.updatedAt = nowIso();
507
+ appendAudit(state, "agent.policy.bound", { agentId, policyId }, nowIso());
508
+ return agent;
509
+ });
510
+ }
511
+
512
+ function revokeAgent(agentId, reason = "") {
513
+ return mutate((state) => {
514
+ const agent = state.agents[agentId];
515
+ if (!agent) throw new Error("CGCP/1: unknown agent");
516
+ agent.status = "revoked";
517
+ agent.updatedAt = nowIso();
518
+ const record = { agentId, reason: String(reason ?? ""), at: nowIso() };
519
+ state.revocations[agentId] = record;
520
+ appendAudit(state, "agent.revoked", record, nowIso());
521
+ return agent;
522
+ });
523
+ }
524
+
525
+ // -- policies (immutable versions; upsert appends) -----------------------
526
+
527
+ function upsertPolicy(policy = {}) {
528
+ const id = requiredString(policy.id, "policy.id");
529
+ return mutate((state) => {
530
+ const prev = state.policies[id] ?? null;
531
+ const spec = normalizePolicySpec(policy);
532
+ const versionNumber = prev ? prev.currentVersion + 1 : 1;
533
+ const version = {
534
+ version: versionNumber,
535
+ hash: digestOf(spec),
536
+ at: nowIso(),
537
+ note: policy.note == null ? null : String(policy.note),
538
+ spec,
539
+ };
540
+ const record = {
541
+ id,
542
+ name: policy.name ?? prev?.name ?? id,
543
+ status: policy.status ?? prev?.status ?? "active",
544
+ currentVersion: versionNumber,
545
+ versions: [...(prev?.versions ?? []), version],
546
+ createdAt: prev?.createdAt ?? nowIso(),
547
+ updatedAt: nowIso(),
548
+ };
549
+ if (!["active", "inactive", "revoked"].includes(record.status)) {
550
+ throw new TypeError("policy.status must be active, inactive or revoked");
551
+ }
552
+ if (prev?.status === "revoked" && record.status !== "revoked") {
553
+ throw new Error("CGCP/1: a revoked policy cannot be reactivated (create a new policy id)");
554
+ }
555
+ state.policies[id] = record;
556
+ appendAudit(
557
+ state,
558
+ prev ? "policy.version.appended" : "policy.created",
559
+ { policyId: id, version: versionNumber, hash: version.hash, status: record.status },
560
+ nowIso(),
561
+ );
562
+ return record;
563
+ });
564
+ }
565
+
566
+ function getPolicy(policyId) {
567
+ return view((state) => state.policies[policyId] ?? null);
568
+ }
569
+
570
+ function listPolicies() {
571
+ return view((state) => Object.values(state.policies));
572
+ }
573
+
574
+ function revokePolicy(policyId, reason = "") {
575
+ return mutate((state) => {
576
+ const policy = state.policies[policyId];
577
+ if (!policy) throw new Error("CGCP/1: unknown policy");
578
+ policy.status = "revoked";
579
+ policy.updatedAt = nowIso();
580
+ appendAudit(state, "policy.revoked", { policyId, reason: String(reason ?? "") }, nowIso());
581
+ return policy;
582
+ });
583
+ }
584
+
585
+ // -- approvals -----------------------------------------------------------
586
+
587
+ function requestApproval(request = {}) {
588
+ const approvalId = request.id ?? "ap_" + randomUUID();
589
+ const agentId = requiredString(request.agentId, "approval.agentId");
590
+ return mutate((state) => {
591
+ if (!state.agents[agentId]) throw new Error("CGCP/1: unknown agent");
592
+ const record = {
593
+ id: approvalId,
594
+ agentId,
595
+ policyId: request.policyId ?? state.agents[agentId].policyId ?? null,
596
+ merchant: request.merchant ?? null,
597
+ address: request.address ?? null,
598
+ amountMinor: optionalDecimal(request.amountMinor, "approval.amountMinor"),
599
+ currency: request.currency ?? null,
600
+ status: "pending",
601
+ requestedAt: nowIso(),
602
+ requestedBy: request.requestedBy ?? null,
603
+ expiresAt: request.expiresAt ?? new Date(nowMs() + 15 * 60 * 1000).toISOString(),
604
+ decidedAt: null,
605
+ decidedBy: null,
606
+ reason: null,
607
+ hash: null,
608
+ };
609
+ record.hash = digestOf(record);
610
+ state.approvals[approvalId] = record;
611
+ appendAudit(state, "approval.requested", { approvalId, agentId, amountMinor: record.amountMinor }, nowIso());
612
+ return record;
613
+ });
614
+ }
615
+
616
+ function decideApproval(approvalId, { decision, decidedBy = null, reason = null } = {}) {
617
+ if (!["approved", "rejected"].includes(decision)) throw new TypeError("decision must be approved or rejected");
618
+ return mutate((state) => {
619
+ const approval = state.approvals[approvalId];
620
+ if (!approval) throw new Error("CGCP/1: unknown approval");
621
+ if (approval.status !== "pending") throw new Error(`CGCP/1: approval is already ${approval.status}`);
622
+ approval.status = decision;
623
+ approval.decidedAt = nowIso();
624
+ approval.decidedBy = decidedBy;
625
+ approval.reason = reason;
626
+ approval.hash = digestOf({ ...approval, hash: null });
627
+ appendAudit(state, `approval.${decision}`, { approvalId, decidedBy, reason }, nowIso());
628
+ return approval;
629
+ });
630
+ }
631
+
632
+ function getApproval(approvalId) {
633
+ return view((state) => state.approvals[approvalId] ?? null);
634
+ }
635
+
636
+ // -- decisions / executions / verifications ------------------------------
637
+
638
+ function evaluate(request = {}) {
639
+ return view((state) =>
640
+ evaluateRequest({
641
+ state,
642
+ agentId: request.agentId ?? null,
643
+ policyId: request.policyId ?? null,
644
+ merchant: request.merchant ?? null,
645
+ address: request.address ?? null,
646
+ amountMinor: request.amountMinor == null ? null : optionalDecimal(request.amountMinor, "amountMinor"),
647
+ currency: request.currency ?? null,
648
+ approvalId: request.approvalId ?? null,
649
+ nowMs: nowMs(),
650
+ nowIso: nowIso(),
651
+ }),
652
+ );
653
+ }
654
+
655
+ /**
656
+ * Dry-run authorisation that ALSO records the decision in the audit chain,
657
+ * so an operator can see what was authorised even when nothing was committed.
658
+ */
659
+ function authorize(request = {}) {
660
+ return mutate((state) => {
661
+ const decision = evaluateRequest({
662
+ state,
663
+ agentId: request.agentId ?? null,
664
+ policyId: request.policyId ?? null,
665
+ merchant: request.merchant ?? null,
666
+ address: request.address ?? null,
667
+ amountMinor: request.amountMinor == null ? null : optionalDecimal(request.amountMinor, "amountMinor"),
668
+ currency: request.currency ?? null,
669
+ approvalId: request.approvalId ?? null,
670
+ nowMs: nowMs(),
671
+ nowIso: nowIso(),
672
+ });
673
+ const decisionId = "dec_" + randomUUID();
674
+ appendAudit(
675
+ state,
676
+ "decision.authorized",
677
+ { decisionId, allowed: decision.allowed, reasons: decision.reasons, agentId: decision.agentId, amountMinor: decision.amountMinor },
678
+ nowIso(),
679
+ );
680
+ return { ...decision, decisionId };
681
+ });
682
+ }
683
+
684
+ /**
685
+ * Commit an execution. Re-evaluates at commit time (so a revocation or a
686
+ * limit breach between authorize and commit is caught), then appends the
687
+ * execution and its spend atomically under the lock.
688
+ */
689
+ function commitExecution(execution = {}) {
690
+ const executionId = execution.id ?? "ex_" + randomUUID();
691
+ return mutate((state) => {
692
+ if (state.executions.some((e) => e.id === executionId)) {
693
+ return {
694
+ committed: false,
695
+ duplicate: true,
696
+ reasons: ["DUPLICATE_EXECUTION"],
697
+ executionId,
698
+ boundary: CONTROL_PLANE_BOUNDARY,
699
+ };
700
+ }
701
+ const decision = evaluateRequest({
702
+ state,
703
+ agentId: execution.agentId ?? null,
704
+ policyId: execution.policyId ?? null,
705
+ merchant: execution.merchant ?? null,
706
+ address: execution.address ?? null,
707
+ amountMinor: execution.amountMinor == null ? null : optionalDecimal(execution.amountMinor, "execution.amountMinor"),
708
+ currency: execution.currency ?? null,
709
+ approvalId: execution.approvalId ?? null,
710
+ nowMs: nowMs(),
711
+ nowIso: nowIso(),
712
+ });
713
+ if (!decision.allowed) {
714
+ const refused = { executionId, decision, at: nowIso() };
715
+ appendAudit(state, "execution.refused", { executionId, reasons: decision.reasons, agentId: decision.agentId }, nowIso());
716
+ return {
717
+ committed: false,
718
+ duplicate: false,
719
+ reasons: decision.reasons,
720
+ executionId,
721
+ decision,
722
+ boundary: CONTROL_PLANE_BOUNDARY,
723
+ };
724
+ }
725
+ const record = {
726
+ id: executionId,
727
+ agentId: decision.agentId,
728
+ policyId: decision.policyId,
729
+ policyVersion: decision.policyVersion,
730
+ merchant: decision.merchant,
731
+ address: decision.address,
732
+ amountMinor: decision.amountMinor,
733
+ currency: decision.currency,
734
+ approvalId: decision.approvalId,
735
+ receiptId: execution.receiptId ?? null,
736
+ verdict: execution.verdict ?? null,
737
+ orderRef: execution.orderRef ?? null,
738
+ at: nowIso(),
739
+ decisionHash: digestOf(decision),
740
+ };
741
+ record.hash = digestOf({ ...record, hash: null });
742
+ state.executions.push(record);
743
+ appendAudit(
744
+ state,
745
+ "execution.committed",
746
+ { executionId, agentId: record.agentId, policyId: record.policyId, amountMinor: record.amountMinor, verdict: record.verdict },
747
+ nowIso(),
748
+ );
749
+ const totals = spendTotals(state.executions, { agentId: record.agentId, policyId: record.policyId, nowMs: nowMs() });
750
+ return {
751
+ committed: true,
752
+ duplicate: false,
753
+ execution: record,
754
+ decision,
755
+ spend: {
756
+ agentId: record.agentId,
757
+ policyId: record.policyId,
758
+ rolling24hMinor: totals.rolling24hMinor.toString(),
759
+ totalMinor: totals.totalMinor.toString(),
760
+ },
761
+ boundary: CONTROL_PLANE_BOUNDARY,
762
+ };
763
+ });
764
+ }
765
+
766
+ /** Kept for the v0 contract: record a pre-computed execution without gating. */
767
+ function recordExecution(execution = {}) {
768
+ const id = requiredString(execution.id, "execution.id");
769
+ return mutate((state) => {
770
+ const record = { ...execution, id, at: execution.at ?? nowIso() };
771
+ record.hash = digestOf({ ...record, hash: null });
772
+ state.executions.push(record);
773
+ appendAudit(state, "execution.recorded", { executionId: id, agentId: execution.agentId ?? null }, nowIso());
774
+ return record;
775
+ });
776
+ }
777
+
778
+ /** Kept for the v0 contract: record a pre-computed approval. */
779
+ function recordApproval(approval = {}) {
780
+ const id = requiredString(approval.id, "approval.id");
781
+ requiredString(approval.agentId, "approval.agentId");
782
+ return mutate((state) => {
783
+ const record = { ...approval, id, at: approval.at ?? nowIso() };
784
+ record.hash = digestOf({ ...record, hash: null });
785
+ state.approvals[id] = record;
786
+ appendAudit(state, "approval.recorded", { approvalId: id, agentId: approval.agentId }, nowIso());
787
+ return record;
788
+ });
789
+ }
790
+
791
+ function recordVerification(verification = {}) {
792
+ return mutate((state) => {
793
+ const record = {
794
+ id: verification.id ?? "vf_" + randomUUID(),
795
+ executionId: verification.executionId ?? null,
796
+ receiptId: verification.receiptId ?? null,
797
+ verdict: verification.verdict ?? null,
798
+ checks: verification.checks ?? [],
799
+ source: verification.source ?? null,
800
+ at: verification.at ?? nowIso(),
801
+ };
802
+ record.hash = digestOf(record);
803
+ state.verifications.push(record);
804
+ appendAudit(state, "verification.recorded", { verificationId: record.id, executionId: record.executionId, verdict: record.verdict }, nowIso());
805
+ return record;
806
+ });
807
+ }
808
+
809
+ // -- reads / reports -----------------------------------------------------
810
+
811
+ function listExecutions({ limit = 100 } = {}) {
812
+ return view((state) => state.executions.slice(-limit));
813
+ }
814
+
815
+ function listVerifications({ limit = 100 } = {}) {
816
+ return view((state) => state.verifications.slice(-limit));
817
+ }
818
+
819
+ function spend({ agentId = null, policyId = null } = {}) {
820
+ return view((state) => {
821
+ const totals = spendTotals(state.executions, { agentId, policyId, nowMs: nowMs() });
822
+ const executions = state.executions.filter(
823
+ (e) => (agentId == null || e.agentId === agentId) && (policyId == null || e.policyId === policyId),
824
+ );
825
+ return {
826
+ agentId,
827
+ policyId,
828
+ executions: executions.length,
829
+ rolling24hMinor: totals.rolling24hMinor.toString(),
830
+ totalMinor: totals.totalMinor.toString(),
831
+ boundary: CONTROL_PLANE_BOUNDARY,
832
+ };
833
+ });
834
+ }
835
+
836
+ function auditReport({ limit = 200 } = {}) {
837
+ return view((state) => {
838
+ const chain = verifyAuditChain(state);
839
+ const body = {
840
+ version: CONTROL_PLANE_VERSION,
841
+ schema: CONTROL_PLANE_SCHEMA,
842
+ boundary: CONTROL_PLANE_BOUNDARY,
843
+ generatedAt: nowIso(),
844
+ counts: {
845
+ agents: Object.keys(state.agents).length,
846
+ policies: Object.keys(state.policies).length,
847
+ policyVersions: Object.values(state.policies).reduce((n, p) => n + (p.versions?.length ?? 0), 0),
848
+ approvals: Object.keys(state.approvals).length,
849
+ executions: state.executions.length,
850
+ verifications: state.verifications.length,
851
+ revocations: Object.keys(state.revocations).length,
852
+ audit: state.audit.length,
853
+ },
854
+ chain,
855
+ agents: Object.values(state.agents),
856
+ policies: Object.values(state.policies).map((p) => ({ ...p, active: activeVersion(p) })),
857
+ revocations: Object.values(state.revocations),
858
+ recentExecutions: state.executions.slice(-limit),
859
+ recentVerifications: state.verifications.slice(-limit),
860
+ recentAudit: state.audit.slice(-limit),
861
+ };
862
+ return { ...body, reportHash: digestOf(body) };
863
+ });
864
+ }
865
+
866
+ function verifyLedger() {
867
+ return view((state) => {
868
+ const chain = verifyAuditChain(state);
869
+ const executionHashesOk = state.executions.every((e) => {
870
+ const { hash, ...rest } = e;
871
+ return hash === digestOf({ ...rest, hash: null });
872
+ });
873
+ const approvalHashesOk = Object.values(state.approvals).every((a) => {
874
+ const { hash, ...rest } = a;
875
+ return hash == null || hash === digestOf({ ...rest, hash: null });
876
+ });
877
+ return {
878
+ ok: chain.ok && executionHashesOk && approvalHashesOk,
879
+ chain,
880
+ executions: state.executions.length,
881
+ executionHashesOk,
882
+ approvals: Object.keys(state.approvals).length,
883
+ approvalHashesOk,
884
+ boundary: CONTROL_PLANE_BOUNDARY,
885
+ };
886
+ });
887
+ }
888
+
889
+ function getState() {
890
+ return view((state) => JSON.parse(JSON.stringify(state)));
891
+ }
892
+
893
+ return {
894
+ version: CONTROL_PLANE_VERSION,
895
+ schema: CONTROL_PLANE_SCHEMA,
896
+ boundary: CONTROL_PLANE_BOUNDARY,
897
+ storePath,
898
+ upsertAgent,
899
+ getAgent,
900
+ listAgents,
901
+ bindPolicy,
902
+ revokeAgent,
903
+ upsertPolicy,
904
+ getPolicy,
905
+ listPolicies,
906
+ revokePolicy,
907
+ requestApproval,
908
+ decideApproval,
909
+ getApproval,
910
+ recordApproval,
911
+ evaluate,
912
+ authorize,
913
+ commitExecution,
914
+ recordExecution,
915
+ recordVerification,
916
+ listExecutions,
917
+ listVerifications,
918
+ spend,
919
+ auditReport,
920
+ verifyLedger,
921
+ getState,
922
+ };
923
+ }