@coreguard/agent-commerce 0.1.2 → 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,1177 @@
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
+ fsyncSync,
52
+ existsSync,
53
+ } from "node:fs";
54
+ import { dirname } from "node:path";
55
+ import { randomUUID, createHash, createHmac } from "node:crypto";
56
+
57
+ export const CONTROL_PLANE_VERSION = "CGCP/1";
58
+ export const CONTROL_PLANE_SCHEMA = "coreguard.control-plane/1";
59
+ export const CONTROL_PLANE_BOUNDARY =
60
+ "self-hosted single-host control plane (file-backed, lock-guarded, hash-chained audit); " +
61
+ "NOT_BUILT: multi-tenant RBAC/SSO/SCIM, distributed HA/consensus, KMS/HSM, managed SLA, payment custody; " +
62
+ "VERIFIED ≠ SAFE";
63
+
64
+ export const CONTROL_PLANE_DECISION_REASONS = Object.freeze([
65
+ "UNKNOWN_AGENT",
66
+ "AGENT_REVOKED_OR_INACTIVE",
67
+ "UNKNOWN_POLICY",
68
+ "POLICY_INACTIVE",
69
+ "POLICY_UNREADABLE",
70
+ "AMOUNT_REQUIRED",
71
+ "MERCHANT_DENIED",
72
+ "MERCHANT_NOT_ALLOWED",
73
+ "MERCHANT_MISSING",
74
+ "ADDRESS_DENIED",
75
+ "ADDRESS_NOT_ALLOWED",
76
+ "ADDRESS_MISSING",
77
+ "CURRENCY_MISMATCH",
78
+ "CURRENCY_MISSING",
79
+ "SPEND_LIMIT_EXCEEDED",
80
+ "DAILY_LIMIT_EXCEEDED",
81
+ "TOTAL_LIMIT_EXCEEDED",
82
+ "APPROVAL_REQUIRED",
83
+ "APPROVAL_NOT_APPROVED",
84
+ "APPROVAL_MISMATCH",
85
+ "APPROVAL_EXPIRED",
86
+ "APPROVAL_EXPIRES_AT_INVALID",
87
+ ]);
88
+
89
+ const ZERO_HASH = "sha256:" + "0".repeat(64);
90
+ const DECIMAL = /^[0-9]+$/;
91
+ const DAY_MS = 24 * 60 * 60 * 1000;
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // Canonical JSON + hashing (one representation, used for every commitment)
95
+ // ---------------------------------------------------------------------------
96
+
97
+ export function canonicalJson(value) {
98
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
99
+ if (Array.isArray(value)) return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
100
+ const keys = Object.keys(value).sort();
101
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
102
+ }
103
+
104
+ const sha256 = (s) => createHash("sha256").update(Buffer.from(s, "utf8")).digest("hex");
105
+ const digestOf = (value) => "sha256:" + sha256(canonicalJson(value));
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // Input validation — malformed developer input throws; malformed BUSINESS data
109
+ // (an unreadable policy version) refuses with a named reason instead of guessing.
110
+ // ---------------------------------------------------------------------------
111
+
112
+ function optionalDecimal(value, field) {
113
+ if (value === undefined || value === null) return null;
114
+ const s = typeof value === "bigint" ? value.toString() : String(value);
115
+ if (!DECIMAL.test(s)) throw new TypeError(`${field} must be a non-negative integer string (minor units)`);
116
+ return BigInt(s).toString();
117
+ }
118
+
119
+ const RESERVED_IDS = new Set(["__proto__", "prototype", "constructor"]);
120
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
121
+
122
+ function requiredString(value, field) {
123
+ if (typeof value !== "string" || value.length === 0) throw new TypeError(`${field} must be a non-empty string`);
124
+ return value;
125
+ }
126
+
127
+ function requiredId(value, field) {
128
+ const id = requiredString(value, field);
129
+ if (RESERVED_IDS.has(id) || !SAFE_ID.test(id)) {
130
+ throw new TypeError(`${field} must match ${SAFE_ID} and not be a reserved key`);
131
+ }
132
+ return id;
133
+ }
134
+
135
+ function stringArray(value, field) {
136
+ if (value === undefined || value === null) return [];
137
+ if (!Array.isArray(value)) throw new TypeError(`${field} must be an array of strings`);
138
+ for (const v of value) if (typeof v !== "string" || v.length === 0) throw new TypeError(`${field} must contain non-empty strings`);
139
+ return [...new Set(value)];
140
+ }
141
+
142
+ function normalizePolicySpec(policy = {}) {
143
+ return {
144
+ spendLimitMinor: optionalDecimal(policy.spendLimitMinor, "spendLimitMinor"),
145
+ dailyLimitMinor: optionalDecimal(policy.dailyLimitMinor, "dailyLimitMinor"),
146
+ totalLimitMinor: optionalDecimal(policy.totalLimitMinor, "totalLimitMinor"),
147
+ requireApprovalAboveMinor: optionalDecimal(policy.requireApprovalAboveMinor, "requireApprovalAboveMinor"),
148
+ currency: policy.currency == null ? null : String(policy.currency),
149
+ allowMerchants: stringArray(policy.allowMerchants, "allowMerchants"),
150
+ denyMerchants: stringArray(policy.denyMerchants, "denyMerchants"),
151
+ allowAddresses: stringArray(policy.allowAddresses, "allowAddresses"),
152
+ denyAddresses: stringArray(policy.denyAddresses, "denyAddresses"),
153
+ rules: Array.isArray(policy.rules) ? policy.rules : [],
154
+ };
155
+ }
156
+
157
+ // ---------------------------------------------------------------------------
158
+ // Store I/O
159
+ // ---------------------------------------------------------------------------
160
+
161
+ const sleep = (() => {
162
+ const cell = new Int32Array(new SharedArrayBuffer(4));
163
+ return (ms) => Atomics.wait(cell, 0, 0, ms);
164
+ })();
165
+
166
+ function nullMap(obj) {
167
+ const out = Object.create(null);
168
+ if (obj && typeof obj === "object") {
169
+ for (const [k, v] of Object.entries(obj)) out[k] = v;
170
+ }
171
+ return out;
172
+ }
173
+
174
+ function defaultState() {
175
+ return {
176
+ version: CONTROL_PLANE_VERSION,
177
+ schema: CONTROL_PLANE_SCHEMA,
178
+ boundary: CONTROL_PLANE_BOUNDARY,
179
+ createdAt: null,
180
+ updatedAt: null,
181
+ agents: Object.create(null),
182
+ policies: Object.create(null),
183
+ approvals: Object.create(null),
184
+ executions: [],
185
+ verifications: [],
186
+ revocations: Object.create(null),
187
+ audit: [],
188
+ };
189
+ }
190
+
191
+ function normalizeState(data) {
192
+ if (!data || typeof data !== "object") throw new Error("not a CGCP/1 control-plane store");
193
+ if (data.schema !== CONTROL_PLANE_SCHEMA) throw new Error("not a CGCP/1 control-plane store");
194
+ data.agents = nullMap(data.agents);
195
+ data.policies = nullMap(data.policies);
196
+ data.approvals = nullMap(data.approvals);
197
+ data.revocations = nullMap(data.revocations);
198
+ if (!Array.isArray(data.executions)) data.executions = [];
199
+ if (!Array.isArray(data.verifications)) data.verifications = [];
200
+ if (!Array.isArray(data.audit)) data.audit = [];
201
+ return data;
202
+ }
203
+
204
+ function loadState(path) {
205
+ try {
206
+ const data = JSON.parse(readFileSync(path, "utf8"));
207
+ return normalizeState(data);
208
+ } catch (err) {
209
+ if (err && err.code === "ENOENT") return null;
210
+ throw err;
211
+ }
212
+ }
213
+
214
+ function saveState(path, state, { fsync = false } = {}) {
215
+ mkdirSync(dirname(path), { recursive: true });
216
+ const tmp = path + ".tmp-" + process.pid + "-" + Math.random().toString(16).slice(2);
217
+ const fd = openSync(tmp, "w");
218
+ try {
219
+ writeFileSync(fd, JSON.stringify(state, null, 2) + "\n", "utf8");
220
+ if (fsync) fsyncSync(fd);
221
+ } finally {
222
+ closeSync(fd);
223
+ }
224
+ renameSync(tmp, path);
225
+ if (fsync) {
226
+ try {
227
+ const dirFd = openSync(dirname(path), "r");
228
+ try { fsyncSync(dirFd); } finally { closeSync(dirFd); }
229
+ } catch {
230
+ // Best-effort directory fsync; not supported on all platforms/filesystems.
231
+ }
232
+ }
233
+ }
234
+
235
+ function appendAudit(state, type, detail, at, meta = null) {
236
+ const prevHash = state.audit.length ? state.audit[state.audit.length - 1].hash : ZERO_HASH;
237
+ const body = { seq: state.audit.length + 1, type, at, detail, prevHash };
238
+ const m = meta && typeof meta === "object" ? meta : (state?._auditMeta && typeof state._auditMeta === "object" ? state._auditMeta : null);
239
+ if (m) {
240
+ if (m.actor != null) body.actor = String(m.actor);
241
+ if (m.requestId != null) body.requestId = String(m.requestId);
242
+ if (m.source != null) body.source = String(m.source);
243
+ }
244
+ const entry = { ...body, hash: digestOf(body) };
245
+ state.audit.push(entry);
246
+ return entry;
247
+ }
248
+
249
+ /**
250
+ * Re-derive the whole audit chain from the stored entries. Pure over the state:
251
+ * a rewritten entry, a removed entry, a reordered entry or a broken prevHash
252
+ * names the first sequence that does not recompute.
253
+ */
254
+ export function verifyAuditChain(state) {
255
+ const audit = Array.isArray(state?.audit) ? state.audit : [];
256
+ let prev = ZERO_HASH;
257
+ for (let i = 0; i < audit.length; i += 1) {
258
+ const entry = audit[i];
259
+ const expectedSeq = i + 1;
260
+ if (!entry || typeof entry !== "object") {
261
+ return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "entry is not an object", headHash: prev };
262
+ }
263
+ if (entry.seq !== expectedSeq) {
264
+ return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "sequence gap or reorder", headHash: prev };
265
+ }
266
+ if (entry.prevHash !== prev) {
267
+ return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "previous hash does not chain", headHash: prev };
268
+ }
269
+ const body = { seq: entry.seq, type: entry.type, at: entry.at, detail: entry.detail, prevHash: entry.prevHash };
270
+ if (entry.actor != null) body.actor = entry.actor;
271
+ if (entry.requestId != null) body.requestId = entry.requestId;
272
+ if (entry.source != null) body.source = entry.source;
273
+ const recomputed = digestOf(body);
274
+ if (entry.hash !== recomputed) {
275
+ return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "entry hash does not recompute", headHash: prev };
276
+ }
277
+ prev = entry.hash;
278
+ }
279
+ return { ok: true, length: audit.length, brokenAt: null, reason: null, headHash: prev };
280
+ }
281
+
282
+ // ---------------------------------------------------------------------------
283
+ // Evaluation
284
+ // ---------------------------------------------------------------------------
285
+
286
+ function activeVersion(policy) {
287
+ if (!policy || !Array.isArray(policy.versions) || policy.versions.length === 0) return null;
288
+ return policy.versions.find((v) => v.version === policy.currentVersion) ?? null;
289
+ }
290
+
291
+ function spendTotals(executions, { agentId, policyId, nowMs }) {
292
+ let rolling24h = 0n;
293
+ let total = 0n;
294
+ for (const e of executions) {
295
+ if (agentId != null && e.agentId !== agentId) continue;
296
+ if (policyId != null && e.policyId !== policyId) continue;
297
+ if (e.amountMinor == null) continue;
298
+ let amount;
299
+ try {
300
+ amount = BigInt(e.amountMinor);
301
+ } catch {
302
+ continue;
303
+ }
304
+ total += amount;
305
+ const at = Date.parse(e.at);
306
+ if (Number.isFinite(at) && nowMs - at <= DAY_MS) rolling24h += amount;
307
+ }
308
+ return { rolling24hMinor: rolling24h, totalMinor: total };
309
+ }
310
+
311
+ function approvalProblem({ state, approvalId, agentId, policyId, merchant, address, amountMinor, nowMs }) {
312
+ if (approvalId == null) return "APPROVAL_REQUIRED";
313
+ const approval = state.approvals[approvalId];
314
+ if (!approval) return "APPROVAL_REQUIRED";
315
+ if (approval.status !== "approved") return "APPROVAL_NOT_APPROVED";
316
+ if (approval.expiresAt) {
317
+ const exp = Date.parse(approval.expiresAt);
318
+ if (!Number.isFinite(exp)) return "APPROVAL_EXPIRES_AT_INVALID";
319
+ if (exp < nowMs) return "APPROVAL_EXPIRED";
320
+ }
321
+ const same = (a, b) => (a == null ? b == null : String(a) === String(b));
322
+ if (!same(approval.agentId, agentId)) return "APPROVAL_MISMATCH";
323
+ if (approval.policyId != null && !same(approval.policyId, policyId)) return "APPROVAL_MISMATCH";
324
+ if (!same(approval.merchant, merchant)) return "APPROVAL_MISMATCH";
325
+ if (!same(approval.address, address)) return "APPROVAL_MISMATCH";
326
+ if (!same(approval.amountMinor, amountMinor)) return "APPROVAL_MISMATCH";
327
+ return null;
328
+ }
329
+
330
+ function evaluateRequest({ state, agentId, policyId, merchant, address, amountMinor, currency, approvalId, nowMs, nowIso }) {
331
+ const reasons = [];
332
+ const checks = {};
333
+
334
+ const agent = agentId != null ? state.agents[agentId] : null;
335
+ checks.agent = { ok: false, status: agent ? agent.status : null, boundPolicyId: agent?.policyId ?? null };
336
+ if (!agent) {
337
+ reasons.push("UNKNOWN_AGENT");
338
+ } else if (agent.status !== "active") {
339
+ reasons.push("AGENT_REVOKED_OR_INACTIVE");
340
+ } else {
341
+ checks.agent.ok = true;
342
+ }
343
+
344
+ const resolvedPolicyId = policyId ?? agent?.policyId ?? null;
345
+ const policy = resolvedPolicyId != null ? state.policies[resolvedPolicyId] : null;
346
+ const version = activeVersion(policy);
347
+ checks.policy = { ok: false, policyId: resolvedPolicyId, version: version?.version ?? null, status: policy?.status ?? null };
348
+
349
+ if (!policy) {
350
+ reasons.push("UNKNOWN_POLICY");
351
+ } else if (policy.status !== "active") {
352
+ reasons.push("POLICY_INACTIVE");
353
+ } else if (!version || !version.spec) {
354
+ reasons.push("POLICY_UNREADABLE");
355
+ } else {
356
+ checks.policy.ok = true;
357
+ }
358
+
359
+ const spec = version?.spec ?? null;
360
+ if (spec) {
361
+ const amount = amountMinor == null ? null : BigInt(amountMinor);
362
+ const monetaryPolicy = spec.spendLimitMinor != null || spec.dailyLimitMinor != null || spec.totalLimitMinor != null || spec.requireApprovalAboveMinor != null;
363
+
364
+ checks.merchant = { ok: true, merchant: merchant ?? null, denied: false, notOnAllowlist: false, missing: false };
365
+ if (merchant == null && (spec.denyMerchants.length > 0 || spec.allowMerchants.length > 0)) {
366
+ reasons.push("MERCHANT_MISSING");
367
+ checks.merchant.missing = true;
368
+ checks.merchant.ok = false;
369
+ }
370
+ if (merchant != null && spec.denyMerchants.includes(merchant)) {
371
+ reasons.push("MERCHANT_DENIED");
372
+ checks.merchant.denied = true;
373
+ checks.merchant.ok = false;
374
+ }
375
+ if (merchant != null && spec.allowMerchants.length > 0 && !spec.allowMerchants.includes(merchant)) {
376
+ reasons.push("MERCHANT_NOT_ALLOWED");
377
+ checks.merchant.notOnAllowlist = true;
378
+ checks.merchant.ok = false;
379
+ }
380
+
381
+ checks.address = { ok: true, address: address ?? null, denied: false, notOnAllowlist: false, missing: false };
382
+ if (address == null && (spec.denyAddresses.length > 0 || spec.allowAddresses.length > 0)) {
383
+ reasons.push("ADDRESS_MISSING");
384
+ checks.address.missing = true;
385
+ checks.address.ok = false;
386
+ }
387
+ if (address != null && spec.denyAddresses.includes(address)) {
388
+ reasons.push("ADDRESS_DENIED");
389
+ checks.address.denied = true;
390
+ checks.address.ok = false;
391
+ }
392
+ if (address != null && spec.allowAddresses.length > 0 && !spec.allowAddresses.includes(address)) {
393
+ reasons.push("ADDRESS_NOT_ALLOWED");
394
+ checks.address.notOnAllowlist = true;
395
+ checks.address.ok = false;
396
+ }
397
+
398
+ checks.currency = { ok: true, expected: spec.currency, observed: currency ?? null, missing: false };
399
+ if (spec.currency != null && currency == null) {
400
+ reasons.push("CURRENCY_MISSING");
401
+ checks.currency.missing = true;
402
+ checks.currency.ok = false;
403
+ }
404
+ if (spec.currency != null && currency != null && String(spec.currency) !== String(currency)) {
405
+ reasons.push("CURRENCY_MISMATCH");
406
+ checks.currency.ok = false;
407
+ }
408
+
409
+ const totals = spendTotals(state.executions, {
410
+ agentId,
411
+ policyId: resolvedPolicyId,
412
+ nowMs,
413
+ });
414
+ const projected24h = totals.rolling24hMinor + (amount ?? 0n);
415
+ const projectedTotal = totals.totalMinor + (amount ?? 0n);
416
+
417
+ checks.amount = {
418
+ ok: true,
419
+ amountMinor: amountMinor ?? null,
420
+ perTransactionLimitMinor: spec.spendLimitMinor,
421
+ projected24hMinor: projected24h.toString(),
422
+ dailyLimitMinor: spec.dailyLimitMinor,
423
+ projectedTotalMinor: projectedTotal.toString(),
424
+ totalLimitMinor: spec.totalLimitMinor,
425
+ missing: false,
426
+ };
427
+ if (amount == null && monetaryPolicy) {
428
+ reasons.push("AMOUNT_REQUIRED");
429
+ checks.amount.missing = true;
430
+ checks.amount.ok = false;
431
+ }
432
+ if (amount != null && spec.spendLimitMinor != null && amount > BigInt(spec.spendLimitMinor)) {
433
+ reasons.push("SPEND_LIMIT_EXCEEDED");
434
+ checks.amount.ok = false;
435
+ }
436
+ if (amount != null && spec.dailyLimitMinor != null && projected24h > BigInt(spec.dailyLimitMinor)) {
437
+ reasons.push("DAILY_LIMIT_EXCEEDED");
438
+ checks.amount.ok = false;
439
+ }
440
+ if (amount != null && spec.totalLimitMinor != null && projectedTotal > BigInt(spec.totalLimitMinor)) {
441
+ reasons.push("TOTAL_LIMIT_EXCEEDED");
442
+ checks.amount.ok = false;
443
+ }
444
+
445
+ const needsApproval =
446
+ spec.requireApprovalAboveMinor != null && amount != null && amount > BigInt(spec.requireApprovalAboveMinor);
447
+ checks.approval = { ok: true, required: needsApproval, approvalId: approvalId ?? null, problem: null };
448
+ if (needsApproval) {
449
+ const problem = approvalProblem({ state, approvalId, agentId, policyId: resolvedPolicyId, merchant, address, amountMinor, nowMs });
450
+ if (problem) {
451
+ reasons.push(problem);
452
+ checks.approval.ok = false;
453
+ checks.approval.problem = problem;
454
+ }
455
+ }
456
+ }
457
+
458
+ return {
459
+ version: CONTROL_PLANE_VERSION,
460
+ allowed: reasons.length === 0,
461
+ reasons,
462
+ checks,
463
+ agentId: agentId ?? null,
464
+ policyId: resolvedPolicyId,
465
+ policyVersion: version?.version ?? null,
466
+ merchant: merchant ?? null,
467
+ address: address ?? null,
468
+ amountMinor: amountMinor ?? null,
469
+ currency: currency ?? null,
470
+ approvalId: approvalId ?? null,
471
+ at: nowIso,
472
+ boundary: CONTROL_PLANE_BOUNDARY,
473
+ };
474
+ }
475
+
476
+ // ---------------------------------------------------------------------------
477
+ // The plane
478
+ // ---------------------------------------------------------------------------
479
+
480
+ /**
481
+ * Open (or create) a control plane at `storePath`.
482
+ *
483
+ * Options:
484
+ * now — () => Date, injectable clock (tests pin it)
485
+ * lockTimeoutMs— how long a mutation waits for the file lock (default 5000)
486
+ * staleLockMs — age after which an abandoned lock is broken (default 30000)
487
+ */
488
+ export function createControlPlane({
489
+ storePath,
490
+ now = () => new Date(),
491
+ lockTimeoutMs = 5000,
492
+ staleLockMs = 30000,
493
+ create = false,
494
+ fsync = false,
495
+ } = {}) {
496
+ if (typeof storePath !== "string" || storePath.length === 0) throw new TypeError("CGCP/1: storePath is required");
497
+ const lockPath = storePath + ".lock";
498
+ const nowIso = () => now().toISOString();
499
+ const nowMs = () => now().getTime();
500
+ let storeInitialized = existsSync(storePath);
501
+ if (!create && !storeInitialized) {
502
+ const missing = new Error("CGCP/1: store missing (pass create: true to initialize a new plane)");
503
+ missing.code = "STORE_MISSING";
504
+ missing.statusCode = 503;
505
+ throw missing;
506
+ }
507
+
508
+ function readLock() {
509
+ try {
510
+ const raw = JSON.parse(readFileSync(lockPath, "utf8"));
511
+ return raw && typeof raw === "object" ? raw : null;
512
+ } catch {
513
+ return null;
514
+ }
515
+ }
516
+
517
+ function pidAlive(pid) {
518
+ if (!Number.isInteger(pid) || pid <= 0) return false;
519
+ try {
520
+ process.kill(pid, 0);
521
+ return true;
522
+ } catch (err) {
523
+ // EPERM means process exists but we lack permission to signal it.
524
+ return err?.code === "EPERM";
525
+ }
526
+ }
527
+
528
+ function tryBreakStaleLock() {
529
+ let lock;
530
+ let st;
531
+ try {
532
+ lock = readLock();
533
+ st = statSync(lockPath);
534
+ } catch {
535
+ return false; // released or unreadable; caller retries
536
+ }
537
+ const ageMs = Date.now() - (Number(lock?.at) || st.mtimeMs);
538
+ if (ageMs <= staleLockMs) return false;
539
+ // CP-05: never break by age alone when holder pid is still alive.
540
+ if (lock && pidAlive(lock.pid)) return false;
541
+ try {
542
+ // Best-effort ownership-safe break: only remove if same inode/file still looks like this lock.
543
+ const st2 = statSync(lockPath);
544
+ if (st2.ino !== st.ino || st2.mtimeMs !== st.mtimeMs) return false;
545
+ unlinkSync(lockPath);
546
+ return true;
547
+ } catch {
548
+ return false;
549
+ }
550
+ }
551
+
552
+ function acquireLock() {
553
+ const deadline = Date.now() + lockTimeoutMs;
554
+ const ownerToken = randomUUID();
555
+ for (;;) {
556
+ try {
557
+ const fd = openSync(lockPath, "wx");
558
+ try {
559
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now(), ownerToken }));
560
+ } finally {
561
+ closeSync(fd);
562
+ }
563
+ return ownerToken;
564
+ } catch (err) {
565
+ if (err.code !== "EEXIST") throw err;
566
+ tryBreakStaleLock();
567
+ if (Date.now() > deadline) {
568
+ const lockErr = new Error("CGCP/1: store is locked by another process");
569
+ lockErr.code = "STORE_LOCKED";
570
+ lockErr.statusCode = 503;
571
+ throw lockErr;
572
+ }
573
+ sleep(3 + Math.floor(Math.random() * 5));
574
+ }
575
+ }
576
+ }
577
+
578
+ function releaseLock(ownerToken) {
579
+ try {
580
+ const lock = readLock();
581
+ // CP-04: only the owner may remove its lock.
582
+ if (lock && lock.ownerToken && lock.ownerToken !== ownerToken) return;
583
+ unlinkSync(lockPath);
584
+ } catch {
585
+ // Nothing to release or already removed.
586
+ }
587
+ }
588
+
589
+ function read() {
590
+ const state = loadState(storePath);
591
+ if (state) {
592
+ storeInitialized = true;
593
+ return state;
594
+ }
595
+ if (!create && !storeInitialized) {
596
+ const missing = new Error("CGCP/1: store missing (pass create: true to initialize a new plane)");
597
+ missing.code = "STORE_MISSING";
598
+ missing.statusCode = 503;
599
+ throw missing;
600
+ }
601
+ return defaultState();
602
+ }
603
+
604
+ let pendingAuditMeta = null;
605
+ function withAuditMeta(meta, fn) {
606
+ const prev = pendingAuditMeta;
607
+ pendingAuditMeta = meta && typeof meta === "object" ? meta : null;
608
+ let out;
609
+ try {
610
+ out = fn();
611
+ } catch (err) {
612
+ pendingAuditMeta = prev;
613
+ throw err;
614
+ }
615
+ if (out && typeof out.then === "function") {
616
+ return Promise.resolve(out).finally(() => { pendingAuditMeta = prev; });
617
+ }
618
+ pendingAuditMeta = prev;
619
+ return out;
620
+ }
621
+
622
+ /** Every mutation: exclusive lock → reload → mutate → atomic save → unlock. */
623
+ function mutate(fn, meta = null) {
624
+ const ownerToken = acquireLock();
625
+ try {
626
+ const state = read();
627
+ if (!state.createdAt) state.createdAt = nowIso();
628
+ const m = meta || pendingAuditMeta;
629
+ if (m && typeof m === "object") {
630
+ Object.defineProperty(state, "_auditMeta", { value: m, enumerable: false, configurable: true, writable: true });
631
+ }
632
+ const result = fn(state);
633
+ state.updatedAt = nowIso();
634
+ saveState(storePath, state, { fsync });
635
+ return result;
636
+ } finally {
637
+ releaseLock(ownerToken);
638
+ }
639
+ }
640
+
641
+ function view(fn) {
642
+ return fn(read());
643
+ }
644
+
645
+ // -- agents --------------------------------------------------------------
646
+
647
+ function upsertAgent(agent = {}) {
648
+ const id = requiredId(agent.id, "agent.id");
649
+ return mutate((state) => {
650
+ const prev = state.agents[id] ?? null;
651
+ const status = agent.status ?? prev?.status ?? "active";
652
+ if (!["active", "inactive", "revoked"].includes(status)) throw new TypeError("agent.status must be active, inactive or revoked");
653
+ if (prev?.status === "revoked" && status !== "revoked") {
654
+ throw new Error("CGCP/1: a revoked agent cannot be reactivated (create a new agent id)");
655
+ }
656
+ const record = {
657
+ ...(prev ?? {}),
658
+ ...agent,
659
+ id,
660
+ status,
661
+ policyId: agent.policyId ?? prev?.policyId ?? null,
662
+ metadata: agent.metadata ?? prev?.metadata ?? {},
663
+ createdAt: prev?.createdAt ?? nowIso(),
664
+ updatedAt: nowIso(),
665
+ };
666
+ state.agents[id] = record;
667
+ appendAudit(state, prev ? "agent.updated" : "agent.created", { agentId: id, status, policyId: record.policyId }, nowIso());
668
+ return record;
669
+ });
670
+ }
671
+
672
+ function getAgent(agentId) {
673
+ return view((state) => state.agents[agentId] ?? null);
674
+ }
675
+
676
+ function listAgents() {
677
+ return view((state) => Object.values(state.agents));
678
+ }
679
+
680
+ function bindPolicy(agentId, policyId) {
681
+ return mutate((state) => {
682
+ const agent = state.agents[agentId];
683
+ if (!agent) throw new Error("CGCP/1: unknown agent");
684
+ if (!state.policies[policyId]) throw new Error("CGCP/1: unknown policy");
685
+ agent.policyId = policyId;
686
+ agent.updatedAt = nowIso();
687
+ appendAudit(state, "agent.policy.bound", { agentId, policyId }, nowIso());
688
+ return agent;
689
+ });
690
+ }
691
+
692
+ function revokeAgent(agentId, reason = "") {
693
+ return mutate((state) => {
694
+ const agent = state.agents[agentId];
695
+ if (!agent) throw new Error("CGCP/1: unknown agent");
696
+ agent.status = "revoked";
697
+ agent.updatedAt = nowIso();
698
+ const record = { agentId, reason: String(reason ?? ""), at: nowIso() };
699
+ state.revocations[agentId] = record;
700
+ appendAudit(state, "agent.revoked", record, nowIso());
701
+ return agent;
702
+ });
703
+ }
704
+
705
+ // -- policies (immutable versions; upsert appends) -----------------------
706
+
707
+ function upsertPolicy(policy = {}) {
708
+ const id = requiredId(policy.id, "policy.id");
709
+ return mutate((state) => {
710
+ const prev = state.policies[id] ?? null;
711
+ const spec = normalizePolicySpec(policy);
712
+ const versionNumber = prev ? prev.currentVersion + 1 : 1;
713
+ const version = {
714
+ version: versionNumber,
715
+ hash: digestOf(spec),
716
+ at: nowIso(),
717
+ note: policy.note == null ? null : String(policy.note),
718
+ spec,
719
+ };
720
+ const record = {
721
+ id,
722
+ name: policy.name ?? prev?.name ?? id,
723
+ status: policy.status ?? prev?.status ?? "active",
724
+ currentVersion: versionNumber,
725
+ versions: [...(prev?.versions ?? []), version],
726
+ createdAt: prev?.createdAt ?? nowIso(),
727
+ updatedAt: nowIso(),
728
+ };
729
+ if (!["active", "inactive", "revoked"].includes(record.status)) {
730
+ throw new TypeError("policy.status must be active, inactive or revoked");
731
+ }
732
+ if (prev?.status === "revoked" && record.status !== "revoked") {
733
+ throw new Error("CGCP/1: a revoked policy cannot be reactivated (create a new policy id)");
734
+ }
735
+ state.policies[id] = record;
736
+ appendAudit(
737
+ state,
738
+ prev ? "policy.version.appended" : "policy.created",
739
+ { policyId: id, version: versionNumber, hash: version.hash, status: record.status },
740
+ nowIso(),
741
+ );
742
+ return record;
743
+ });
744
+ }
745
+
746
+ function getPolicy(policyId) {
747
+ return view((state) => state.policies[policyId] ?? null);
748
+ }
749
+
750
+ function listPolicies() {
751
+ return view((state) => Object.values(state.policies));
752
+ }
753
+
754
+ function revokePolicy(policyId, reason = "") {
755
+ return mutate((state) => {
756
+ const policy = state.policies[policyId];
757
+ if (!policy) throw new Error("CGCP/1: unknown policy");
758
+ policy.status = "revoked";
759
+ policy.updatedAt = nowIso();
760
+ appendAudit(state, "policy.revoked", { policyId, reason: String(reason ?? "") }, nowIso());
761
+ return policy;
762
+ });
763
+ }
764
+
765
+ // -- approvals -----------------------------------------------------------
766
+
767
+ function requestApproval(request = {}) {
768
+ const approvalId = requiredId(request.id ?? "ap_" + randomUUID(), "approval.id");
769
+ const agentId = requiredId(request.agentId, "approval.agentId");
770
+ return mutate((state) => {
771
+ if (!state.agents[agentId]) throw new Error("CGCP/1: unknown agent");
772
+ const record = {
773
+ id: approvalId,
774
+ agentId,
775
+ policyId: request.policyId == null ? (state.agents[agentId].policyId ?? null) : requiredId(request.policyId, "approval.policyId"),
776
+ merchant: request.merchant ?? null,
777
+ address: request.address ?? null,
778
+ amountMinor: optionalDecimal(request.amountMinor, "approval.amountMinor"),
779
+ currency: request.currency ?? null,
780
+ status: "pending",
781
+ requestedAt: nowIso(),
782
+ requestedBy: request.requestedBy ?? null,
783
+ expiresAt: (() => {
784
+ const v = request.expiresAt ?? new Date(nowMs() + 15 * 60 * 1000).toISOString();
785
+ const t = Date.parse(v);
786
+ if (!Number.isFinite(t)) throw new TypeError("approval.expiresAt must be a valid ISO-8601 datetime");
787
+ return new Date(t).toISOString();
788
+ })(),
789
+ decidedAt: null,
790
+ decidedBy: null,
791
+ reason: null,
792
+ hash: null,
793
+ };
794
+ record.hash = digestOf(record);
795
+ state.approvals[approvalId] = record;
796
+ appendAudit(state, "approval.requested", { approvalId, agentId, amountMinor: record.amountMinor }, nowIso());
797
+ return record;
798
+ });
799
+ }
800
+
801
+ function decideApproval(approvalId, { decision, decidedBy = null, reason = null } = {}) {
802
+ if (!["approved", "rejected"].includes(decision)) throw new TypeError("decision must be approved or rejected");
803
+ return mutate((state) => {
804
+ const approval = state.approvals[approvalId];
805
+ if (!approval) throw new Error("CGCP/1: unknown approval");
806
+ if (approval.status !== "pending") throw new Error(`CGCP/1: approval is already ${approval.status}`);
807
+ approval.status = decision;
808
+ approval.decidedAt = nowIso();
809
+ approval.decidedBy = decidedBy;
810
+ approval.reason = reason;
811
+ approval.hash = digestOf({ ...approval, hash: null });
812
+ appendAudit(state, `approval.${decision}`, { approvalId, decidedBy, reason }, nowIso());
813
+ return approval;
814
+ });
815
+ }
816
+
817
+ function getApproval(approvalId) {
818
+ return view((state) => state.approvals[approvalId] ?? null);
819
+ }
820
+
821
+ // -- decisions / executions / verifications ------------------------------
822
+
823
+ function evaluate(request = {}) {
824
+ return view((state) =>
825
+ evaluateRequest({
826
+ state,
827
+ agentId: request.agentId ?? null,
828
+ policyId: request.policyId ?? null,
829
+ merchant: request.merchant ?? null,
830
+ address: request.address ?? null,
831
+ amountMinor: request.amountMinor == null ? null : optionalDecimal(request.amountMinor, "amountMinor"),
832
+ currency: request.currency ?? null,
833
+ approvalId: request.approvalId ?? null,
834
+ nowMs: nowMs(),
835
+ nowIso: nowIso(),
836
+ }),
837
+ );
838
+ }
839
+
840
+ /**
841
+ * Dry-run authorisation that ALSO records the decision in the audit chain,
842
+ * so an operator can see what was authorised even when nothing was committed.
843
+ */
844
+ function authorize(request = {}) {
845
+ return mutate((state) => {
846
+ const decision = evaluateRequest({
847
+ state,
848
+ agentId: request.agentId ?? null,
849
+ policyId: request.policyId ?? null,
850
+ merchant: request.merchant ?? null,
851
+ address: request.address ?? null,
852
+ amountMinor: request.amountMinor == null ? null : optionalDecimal(request.amountMinor, "amountMinor"),
853
+ currency: request.currency ?? null,
854
+ approvalId: request.approvalId ?? null,
855
+ nowMs: nowMs(),
856
+ nowIso: nowIso(),
857
+ });
858
+ const decisionId = "dec_" + randomUUID();
859
+ appendAudit(
860
+ state,
861
+ "decision.authorized",
862
+ { decisionId, allowed: decision.allowed, reasons: decision.reasons, agentId: decision.agentId, amountMinor: decision.amountMinor },
863
+ nowIso(),
864
+ );
865
+ return { ...decision, decisionId };
866
+ });
867
+ }
868
+
869
+ /**
870
+ * Commit an execution. Re-evaluates at commit time (so a revocation or a
871
+ * limit breach between authorize and commit is caught), then appends the
872
+ * execution and its spend atomically under the lock.
873
+ */
874
+ function commitExecution(execution = {}) {
875
+ const executionId = execution.id ?? "ex_" + randomUUID();
876
+ return mutate((state) => {
877
+ if (state.executions.some((e) => e.id === executionId)) {
878
+ return {
879
+ committed: false,
880
+ duplicate: true,
881
+ reasons: ["DUPLICATE_EXECUTION"],
882
+ executionId,
883
+ boundary: CONTROL_PLANE_BOUNDARY,
884
+ };
885
+ }
886
+ const amountMinor = optionalDecimal(execution.amountMinor, "execution.amountMinor");
887
+ if (amountMinor == null) {
888
+ appendAudit(state, "execution.refused", { executionId, reasons: ["AMOUNT_REQUIRED"], agentId: execution.agentId ?? null }, nowIso());
889
+ return {
890
+ committed: false,
891
+ duplicate: false,
892
+ reasons: ["AMOUNT_REQUIRED"],
893
+ executionId,
894
+ boundary: CONTROL_PLANE_BOUNDARY,
895
+ };
896
+ }
897
+ const decision = evaluateRequest({
898
+ state,
899
+ agentId: execution.agentId ?? null,
900
+ policyId: execution.policyId ?? null,
901
+ merchant: execution.merchant ?? null,
902
+ address: execution.address ?? null,
903
+ amountMinor,
904
+ currency: execution.currency ?? null,
905
+ approvalId: execution.approvalId ?? null,
906
+ nowMs: nowMs(),
907
+ nowIso: nowIso(),
908
+ });
909
+ if (!decision.allowed) {
910
+ const refused = { executionId, decision, at: nowIso() };
911
+ appendAudit(state, "execution.refused", { executionId, reasons: decision.reasons, agentId: decision.agentId }, nowIso());
912
+ return {
913
+ committed: false,
914
+ duplicate: false,
915
+ reasons: decision.reasons,
916
+ executionId,
917
+ decision,
918
+ boundary: CONTROL_PLANE_BOUNDARY,
919
+ };
920
+ }
921
+ const record = {
922
+ id: executionId,
923
+ agentId: decision.agentId,
924
+ policyId: decision.policyId,
925
+ policyVersion: decision.policyVersion,
926
+ merchant: decision.merchant,
927
+ address: decision.address,
928
+ amountMinor: decision.amountMinor,
929
+ currency: decision.currency,
930
+ approvalId: decision.approvalId,
931
+ receiptId: execution.receiptId ?? null,
932
+ verdict: execution.verdict ?? null,
933
+ orderRef: execution.orderRef ?? null,
934
+ at: nowIso(),
935
+ decisionHash: digestOf(decision),
936
+ };
937
+ record.hash = digestOf({ ...record, hash: null });
938
+ state.executions.push(record);
939
+ appendAudit(
940
+ state,
941
+ "execution.committed",
942
+ { executionId, agentId: record.agentId, policyId: record.policyId, amountMinor: record.amountMinor, verdict: record.verdict },
943
+ nowIso(),
944
+ );
945
+ const totals = spendTotals(state.executions, { agentId: record.agentId, policyId: record.policyId, nowMs: nowMs() });
946
+ return {
947
+ committed: true,
948
+ duplicate: false,
949
+ execution: record,
950
+ decision,
951
+ spend: {
952
+ agentId: record.agentId,
953
+ policyId: record.policyId,
954
+ rolling24hMinor: totals.rolling24hMinor.toString(),
955
+ totalMinor: totals.totalMinor.toString(),
956
+ },
957
+ boundary: CONTROL_PLANE_BOUNDARY,
958
+ };
959
+ });
960
+ }
961
+
962
+ /** Kept for the v0 contract: record a pre-computed execution without gating. */
963
+ function recordExecution(execution = {}) {
964
+ const id = requiredId(execution.id, "execution.id");
965
+ return mutate((state) => {
966
+ const record = { ...execution, id, at: execution.at ?? nowIso() };
967
+ record.hash = digestOf({ ...record, hash: null });
968
+ state.executions.push(record);
969
+ appendAudit(state, "execution.recorded", { executionId: id, agentId: execution.agentId ?? null }, nowIso());
970
+ return record;
971
+ });
972
+ }
973
+
974
+ /** Kept for the v0 contract: record a pre-computed approval. */
975
+ function recordApproval(approval = {}) {
976
+ const id = requiredId(approval.id, "approval.id");
977
+ requiredId(approval.agentId, "approval.agentId");
978
+ return mutate((state) => {
979
+ const record = { ...approval, id, at: approval.at ?? nowIso() };
980
+ record.hash = digestOf({ ...record, hash: null });
981
+ state.approvals[id] = record;
982
+ appendAudit(state, "approval.recorded", { approvalId: id, agentId: approval.agentId }, nowIso());
983
+ return record;
984
+ });
985
+ }
986
+
987
+ function recordVerification(verification = {}) {
988
+ return mutate((state) => {
989
+ const record = {
990
+ id: verification.id ?? "vf_" + randomUUID(),
991
+ executionId: verification.executionId ?? null,
992
+ receiptId: verification.receiptId ?? null,
993
+ verdict: verification.verdict ?? null,
994
+ checks: verification.checks ?? [],
995
+ source: verification.source ?? null,
996
+ at: verification.at ?? nowIso(),
997
+ };
998
+ record.hash = digestOf(record);
999
+ state.verifications.push(record);
1000
+ appendAudit(state, "verification.recorded", { verificationId: record.id, executionId: record.executionId, verdict: record.verdict }, nowIso());
1001
+ return record;
1002
+ });
1003
+ }
1004
+
1005
+ // -- reads / reports -----------------------------------------------------
1006
+
1007
+ function listExecutions({ limit = 100 } = {}) {
1008
+ return view((state) => state.executions.slice(-limit));
1009
+ }
1010
+
1011
+ function listVerifications({ limit = 100 } = {}) {
1012
+ return view((state) => state.verifications.slice(-limit));
1013
+ }
1014
+
1015
+ function spend({ agentId = null, policyId = null } = {}) {
1016
+ return view((state) => {
1017
+ const totals = spendTotals(state.executions, { agentId, policyId, nowMs: nowMs() });
1018
+ const executions = state.executions.filter(
1019
+ (e) => (agentId == null || e.agentId === agentId) && (policyId == null || e.policyId === policyId),
1020
+ );
1021
+ return {
1022
+ agentId,
1023
+ policyId,
1024
+ executions: executions.length,
1025
+ rolling24hMinor: totals.rolling24hMinor.toString(),
1026
+ totalMinor: totals.totalMinor.toString(),
1027
+ boundary: CONTROL_PLANE_BOUNDARY,
1028
+ };
1029
+ });
1030
+ }
1031
+
1032
+ function auditReport({ limit = 200 } = {}) {
1033
+ return view((state) => {
1034
+ const chain = verifyAuditChain(state);
1035
+ const body = {
1036
+ version: CONTROL_PLANE_VERSION,
1037
+ schema: CONTROL_PLANE_SCHEMA,
1038
+ boundary: CONTROL_PLANE_BOUNDARY,
1039
+ generatedAt: nowIso(),
1040
+ counts: {
1041
+ agents: Object.keys(state.agents).length,
1042
+ policies: Object.keys(state.policies).length,
1043
+ policyVersions: Object.values(state.policies).reduce((n, p) => n + (p.versions?.length ?? 0), 0),
1044
+ approvals: Object.keys(state.approvals).length,
1045
+ executions: state.executions.length,
1046
+ verifications: state.verifications.length,
1047
+ revocations: Object.keys(state.revocations).length,
1048
+ audit: state.audit.length,
1049
+ },
1050
+ chain,
1051
+ agents: Object.values(state.agents),
1052
+ policies: Object.values(state.policies).map((p) => ({ ...p, active: activeVersion(p) })),
1053
+ revocations: Object.values(state.revocations),
1054
+ recentExecutions: state.executions.slice(-limit),
1055
+ recentVerifications: state.verifications.slice(-limit),
1056
+ recentAudit: state.audit.slice(-limit),
1057
+ };
1058
+ return { ...body, reportHash: digestOf(body) };
1059
+ });
1060
+ }
1061
+
1062
+ function auditAnchor(options = {}) {
1063
+ return view((state) => {
1064
+ const chain = verifyAuditChain(state);
1065
+ const anchor = {
1066
+ ok: chain.ok,
1067
+ headHash: chain.headHash,
1068
+ length: chain.length,
1069
+ at: nowIso(),
1070
+ };
1071
+ const hmacKey = options.hmacKey ?? process.env.COREGUARD_CONTROL_PLANE_ANCHOR_HMAC_KEY ?? null;
1072
+ if (hmacKey) {
1073
+ anchor.hmacSha256 = createHmac("sha256", String(hmacKey)).update(canonicalJson({ headHash: anchor.headHash, length: anchor.length })).digest("hex");
1074
+ anchor.hmac = "hmac-sha256";
1075
+ }
1076
+ anchor.boundary = "Local audit head anchor. Optional HMAC is local shared-key integrity only. NOT_BUILT: external witness/anchoring service, KMS/HSM signatures, or on-chain anchoring.";
1077
+ return anchor;
1078
+ });
1079
+ }
1080
+
1081
+ function verifyAnchor(expected = {}) {
1082
+ return view((state) => {
1083
+ const chain = verifyAuditChain(state);
1084
+ const expectedHead = expected.headHash ?? null;
1085
+ const expectedLength = expected.length ?? null;
1086
+ const headOk = expectedHead == null ? true : chain.headHash === expectedHead;
1087
+ const lengthOk = expectedLength == null ? true : chain.length === expectedLength;
1088
+ let hmacOk = true;
1089
+ const hmacKey = expected.hmacKey ?? process.env.COREGUARD_CONTROL_PLANE_ANCHOR_HMAC_KEY ?? null;
1090
+ if (expected.hmacSha256) {
1091
+ if (!hmacKey) hmacOk = false;
1092
+ else {
1093
+ const actual = createHmac("sha256", String(hmacKey)).update(canonicalJson({ headHash: chain.headHash, length: chain.length })).digest("hex");
1094
+ hmacOk = actual === String(expected.hmacSha256);
1095
+ }
1096
+ }
1097
+ return {
1098
+ ok: chain.ok && headOk && lengthOk && hmacOk,
1099
+ chainOk: chain.ok,
1100
+ headOk,
1101
+ lengthOk,
1102
+ hmacOk,
1103
+ expectedHead,
1104
+ expectedLength,
1105
+ actualHead: chain.headHash,
1106
+ actualLength: chain.length,
1107
+ boundary: "Local anchor comparison only. Optional HMAC is local shared-key integrity only. NOT_BUILT: external witness/anchoring service.",
1108
+ };
1109
+ });
1110
+ }
1111
+
1112
+ function verifyLedger() {
1113
+ return view((state) => {
1114
+ const chain = verifyAuditChain(state);
1115
+ const executionHashesOk = state.executions.every((e) => {
1116
+ const { hash, ...rest } = e;
1117
+ return hash === digestOf({ ...rest, hash: null });
1118
+ });
1119
+ const approvalHashesOk = Object.values(state.approvals).every((a) => {
1120
+ const { hash, ...rest } = a;
1121
+ return hash == null || hash === digestOf({ ...rest, hash: null });
1122
+ });
1123
+ return {
1124
+ ok: chain.ok && executionHashesOk && approvalHashesOk,
1125
+ chain,
1126
+ executions: state.executions.length,
1127
+ executionHashesOk,
1128
+ approvals: Object.keys(state.approvals).length,
1129
+ approvalHashesOk,
1130
+ anchor: {
1131
+ headHash: chain.headHash,
1132
+ length: chain.length,
1133
+ boundary: "Local anchor only; external witness NOT_BUILT.",
1134
+ },
1135
+ boundary: CONTROL_PLANE_BOUNDARY,
1136
+ };
1137
+ });
1138
+ }
1139
+
1140
+ function getState() {
1141
+ return view((state) => JSON.parse(JSON.stringify(state)));
1142
+ }
1143
+
1144
+ return {
1145
+ version: CONTROL_PLANE_VERSION,
1146
+ schema: CONTROL_PLANE_SCHEMA,
1147
+ boundary: CONTROL_PLANE_BOUNDARY,
1148
+ storePath,
1149
+ upsertAgent,
1150
+ getAgent,
1151
+ listAgents,
1152
+ bindPolicy,
1153
+ revokeAgent,
1154
+ upsertPolicy,
1155
+ getPolicy,
1156
+ listPolicies,
1157
+ revokePolicy,
1158
+ requestApproval,
1159
+ decideApproval,
1160
+ getApproval,
1161
+ recordApproval,
1162
+ evaluate,
1163
+ authorize,
1164
+ commitExecution,
1165
+ recordExecution,
1166
+ recordVerification,
1167
+ listExecutions,
1168
+ listVerifications,
1169
+ spend,
1170
+ auditReport,
1171
+ verifyLedger,
1172
+ auditAnchor,
1173
+ verifyAnchor,
1174
+ getState,
1175
+ withAuditMeta,
1176
+ };
1177
+ }