@coreguard/agent-commerce 0.1.5 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/wave3.mjs ADDED
@@ -0,0 +1,1173 @@
1
+ /**
2
+ * CoreGuard Agent Commerce — Wave 3 (CG-W3/1)
3
+ *
4
+ * Twenty deterministic tools in five families, all offline and zero-key:
5
+ *
6
+ * Policy reasoning compile · explain (with counterfactual) · simulate ·
7
+ * diff · boundary cases
8
+ * MCP supply chain server-manifest audit · tool-description poisoning scan ·
9
+ * lookalike check · tool-surface diff (rug pull) ·
10
+ * evidence-bundle verify
11
+ * Evidence redact a receipt · Merkle-attest a batch · verify a proof
12
+ * Operations freeze an agent · budget runway · spend anomaly · timeline
13
+ * Interop & meta translate a receipt · emit test vectors · describe surface
14
+ *
15
+ * BOUNDARIES: every answer is arithmetic over caller-supplied JSON. A finding is
16
+ * evidence for a human decision, not a verdict on a third party. Nothing here
17
+ * contacts a registry, a chain, a merchant or a payment network; time is supplied
18
+ * as pinned epoch seconds, never read from the wall clock into a commitment.
19
+ */
20
+
21
+ import { createHash } from "node:crypto";
22
+ import { createControlPlane, verifyAuditChain } from "./control-plane.mjs";
23
+
24
+ export const WAVE3_VERSION = "CG-W3/1";
25
+
26
+ export const WAVE3_BOUNDARY =
27
+ "Wave 3 is deterministic, offline reasoning over caller-supplied JSON: it checks structure, policy arithmetic and byte-level provenance, " +
28
+ "never truth, safety, identity or settlement. A finding is evidence for a human decision, not a verdict on a third party. " +
29
+ "VERIFIED ≠ SAFE; no network calls, no keys, no wall clock in any commitment.";
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Canonical JSON + digests (one representation for every commitment)
33
+ // ---------------------------------------------------------------------------
34
+
35
+ export function canonicalJson(value) {
36
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
37
+ if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
38
+ return "{" + Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
39
+ }
40
+
41
+ export function digestOf(value) {
42
+ return "sha256:" + createHash("sha256").update(canonicalJson(value)).digest("hex");
43
+ }
44
+
45
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
46
+
47
+ function decimal(v) {
48
+ if (typeof v === "string" && /^[0-9]+$/.test(v)) return BigInt(v);
49
+ if (Number.isInteger(v) && v >= 0) return BigInt(v);
50
+ return null;
51
+ }
52
+
53
+ function str(v) {
54
+ return typeof v === "string" ? v : undefined;
55
+ }
56
+
57
+ const now = (args) => (args.nowSeconds === undefined ? null : decimal(args.nowSeconds));
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Policy compilation and rule evaluation (CGEP/1 subset)
61
+ // ---------------------------------------------------------------------------
62
+
63
+ const RULE_TYPES = Object.freeze([
64
+ "VALUE_LIMIT",
65
+ "TARGET_ALLOWLIST",
66
+ "RECIPIENT_ALLOWLIST",
67
+ "SELECTOR_ALLOWLIST",
68
+ "CURRENCY_ALLOWLIST",
69
+ ]);
70
+
71
+ export function compilePolicy(args = {}) {
72
+ const spec = isObj(args.spec) ? args.spec : {};
73
+ const rules = [];
74
+ const max = decimal(spec.maxAmountMinor);
75
+ if (max !== null) rules.push({ ruleId: "VALUE_001", type: "VALUE_LIMIT", params: { max: String(max) }, severity: "CRITICAL" });
76
+ if (Array.isArray(spec.allowMerchants) && spec.allowMerchants.length) {
77
+ rules.push({ ruleId: "TARGET_001", type: "TARGET_ALLOWLIST", params: { targets: spec.allowMerchants.map(String) }, severity: "CRITICAL" });
78
+ }
79
+ if (Array.isArray(spec.allowRecipients) && spec.allowRecipients.length) {
80
+ rules.push({ ruleId: "RECIPIENT_001", type: "RECIPIENT_ALLOWLIST", params: { addresses: spec.allowRecipients.map(String) }, severity: "CRITICAL" });
81
+ }
82
+ if (Array.isArray(spec.allowSelectors) && spec.allowSelectors.length) {
83
+ // Selectors are bytes, not prose: normalise at compile time so a spec written
84
+ // as "0xA9059CBB" and an intent written as "0xa9059cbb" are the same rule.
85
+ rules.push({ ruleId: "SELECTOR_001", type: "SELECTOR_ALLOWLIST", params: { selectors: spec.allowSelectors.map((s) => String(s).toLowerCase()) }, severity: "CRITICAL" });
86
+ }
87
+ if (spec.currency) {
88
+ rules.push({ ruleId: "CURRENCY_001", type: "CURRENCY_ALLOWLIST", params: { currencies: [String(spec.currency).toUpperCase()] }, severity: "HIGH" });
89
+ }
90
+ const policy = {
91
+ version: "CGEP/1",
92
+ policyId: String(spec.policyId ?? "compiled-policy"),
93
+ name: String(spec.name ?? "Compiled agent commerce policy"),
94
+ rules,
95
+ };
96
+ return {
97
+ type: "compiled_policy",
98
+ spec: "CGEP/1",
99
+ policy,
100
+ policyDigest: digestOf(policy),
101
+ rules: rules.map((r) => ({ ruleId: r.ruleId, type: r.type, severity: r.severity })),
102
+ normalizations: [
103
+ "amounts are decimal strings; values are compared as integers, never floats",
104
+ "allowlists keep caller order and are compared byte-for-byte after String()",
105
+ "rule ids are stable so two compilations of the same spec have the same digest",
106
+ ],
107
+ boundary: WAVE3_BOUNDARY,
108
+ };
109
+ }
110
+
111
+ function ruleCheck(rule, intent) {
112
+ const p = isObj(rule.params) ? rule.params : {};
113
+ const ruleId = String(rule.ruleId ?? rule.type);
114
+ switch (rule.type) {
115
+ case "VALUE_LIMIT": {
116
+ const max = decimal(p.max);
117
+ const amt = decimal(intent.amount);
118
+ if (max === null) return { ruleId, type: rule.type, ok: false, detail: "rule has no usable max" };
119
+ if (amt === null) return { ruleId, type: rule.type, ok: false, detail: "intent has no usable amount" };
120
+ return { ruleId, type: rule.type, ok: amt <= max, detail: `amount ${amt} ${amt <= max ? "≤" : ">"} max ${max}` };
121
+ }
122
+ case "TARGET_ALLOWLIST": {
123
+ const targets = Array.isArray(p.targets) ? p.targets.map(String) : [];
124
+ const ok = typeof intent.target === "string" && targets.includes(intent.target);
125
+ return { ruleId, type: rule.type, ok, detail: ok ? `target ${intent.target} allowlisted` : `target ${String(intent.target)} not allowlisted` };
126
+ }
127
+ case "RECIPIENT_ALLOWLIST": {
128
+ const addresses = Array.isArray(p.addresses) ? p.addresses.map(String) : [];
129
+ const ok = typeof intent.recipient === "string" && addresses.includes(intent.recipient);
130
+ return { ruleId, type: rule.type, ok, detail: ok ? `recipient ${intent.recipient} allowlisted` : `recipient ${String(intent.recipient)} not allowlisted` };
131
+ }
132
+ case "SELECTOR_ALLOWLIST": {
133
+ const selectors = Array.isArray(p.selectors) ? p.selectors.map(String) : [];
134
+ const ok = typeof intent.selector === "string" && selectors.includes(intent.selector.toLowerCase());
135
+ return { ruleId, type: rule.type, ok, detail: ok ? `selector ${intent.selector} allowlisted` : `selector ${String(intent.selector)} not allowlisted` };
136
+ }
137
+ case "CURRENCY_ALLOWLIST": {
138
+ const currencies = Array.isArray(p.currencies) ? p.currencies.map(String) : [];
139
+ const ok = typeof intent.currency === "string" && currencies.includes(intent.currency.toUpperCase());
140
+ return { ruleId, type: rule.type, ok, detail: ok ? `currency ${intent.currency} allowed` : `currency ${String(intent.currency)} not allowed` };
141
+ }
142
+ default:
143
+ return { ruleId, type: String(rule.type), ok: false, detail: "unknown rule type — fail closed" };
144
+ }
145
+ }
146
+
147
+ function evaluateIntent(policy, intent, nowSeconds) {
148
+ const rules = Array.isArray(policy?.rules) ? policy.rules : [];
149
+ const checks = rules.map((r) => ruleCheck(r, isObj(intent) ? intent : {}));
150
+ const expires = decimal(intent?.validUntil);
151
+ if (expires !== null && nowSeconds !== null) {
152
+ checks.push({ ruleId: "__expiry", type: "WINDOW", ok: expires >= nowSeconds, detail: `validUntil ${expires} ${expires >= nowSeconds ? "≥" : "<"} now ${nowSeconds}` });
153
+ }
154
+ const blocking = checks.filter((c) => !c.ok);
155
+ return { allowed: blocking.length === 0, checks, blocking, policyDigest: digestOf(policy ?? {}) };
156
+ }
157
+
158
+ function counterfactualFor(blocking, intent, policy, nowSeconds) {
159
+ const first = blocking[0];
160
+ if (!first) return null;
161
+ const rule = (policy?.rules ?? []).find((r) => String(r.ruleId) === first.ruleId);
162
+ const p = isObj(rule?.params) ? rule.params : {};
163
+ switch (first.type) {
164
+ case "VALUE_LIMIT": return { ruleId: first.ruleId, change: { field: "intent.amount", from: String(intent.amount ?? ""), to: String(p.max) }, note: "lower the order to the approved maximum (or raise the limit deliberately)" };
165
+ case "TARGET_ALLOWLIST": return { ruleId: first.ruleId, change: { field: "intent.target", from: String(intent.target ?? ""), to: String((p.targets ?? [])[0] ?? "") }, note: "the target must be on the approved list" };
166
+ case "RECIPIENT_ALLOWLIST": return { ruleId: first.ruleId, change: { field: "intent.recipient", from: String(intent.recipient ?? ""), to: String((p.addresses ?? [])[0] ?? "") }, note: "the recipient must be on the approved list" };
167
+ case "SELECTOR_ALLOWLIST": return { ruleId: first.ruleId, change: { field: "intent.selector", from: String(intent.selector ?? ""), to: String((p.selectors ?? [])[0] ?? "") }, note: "the call selector must be on the approved list" };
168
+ case "CURRENCY_ALLOWLIST": return { ruleId: first.ruleId, change: { field: "intent.currency", from: String(intent.currency ?? ""), to: String((p.currencies ?? [])[0] ?? "") }, note: "settle in the approved currency" };
169
+ case "WINDOW": return { ruleId: first.ruleId, change: { field: "intent.validUntil", from: String(intent.validUntil ?? ""), to: nowSeconds === null ? "<pinned nowSeconds>" : String(nowSeconds) }, note: "the approval window had already closed" };
170
+ default: return { ruleId: first.ruleId, change: null, note: "no automatic counterfactual for this rule type" };
171
+ }
172
+ }
173
+
174
+ export function explainDecision(args = {}) {
175
+ const policy = isObj(args.policy) ? args.policy : {};
176
+ const intent = isObj(args.intent) ? args.intent : {};
177
+ const evaluated = evaluateIntent(policy, intent, now(args));
178
+ const counterfactual = counterfactualFor(evaluated.blocking, intent, policy, now(args));
179
+ return {
180
+ type: "policy_decision_explanation",
181
+ allowed: evaluated.allowed,
182
+ verdict: evaluated.allowed ? "ALLOW" : "DENY",
183
+ blockingRule: evaluated.blocking[0]?.ruleId ?? null,
184
+ checks: evaluated.checks,
185
+ counterfactual,
186
+ counterfactualNote: counterfactual ? "smallest single change that clears the first blocking rule; clearing it may reveal a second one" : null,
187
+ policyDigest: evaluated.policyDigest,
188
+ boundary: WAVE3_BOUNDARY,
189
+ };
190
+ }
191
+
192
+ export function simulateSpend(args = {}) {
193
+ const policy = isObj(args.policy) ? args.policy : {};
194
+ const intents = Array.isArray(args.intents) ? args.intents : [];
195
+ const nowSeconds = now(args);
196
+ const rows = intents.map((intent, index) => {
197
+ const evaluated = evaluateIntent(policy, intent, nowSeconds);
198
+ return {
199
+ index,
200
+ allowed: evaluated.allowed,
201
+ reasons: evaluated.blocking.map((c) => `${c.ruleId}:${c.type}`),
202
+ amount: String(intent?.amount ?? ""),
203
+ currency: str(intent?.currency) ?? null,
204
+ counterfactual: counterfactualFor(evaluated.blocking, intent, policy, nowSeconds),
205
+ };
206
+ });
207
+ const allowed = rows.filter((r) => r.allowed);
208
+ const total = allowed.reduce((sum, r) => sum + (decimal(r.amount) ?? 0n), 0n);
209
+ const deniedTotal = rows.filter((r) => !r.allowed).reduce((sum, r) => sum + (decimal(r.amount) ?? 0n), 0n);
210
+ return {
211
+ type: "spend_simulation",
212
+ dryRun: true,
213
+ policyDigest: digestOf(policy),
214
+ counts: { total: rows.length, allowed: allowed.length, denied: rows.length - allowed.length },
215
+ totals: { allowedMinor: String(total), deniedMinor: String(deniedTotal) },
216
+ rows,
217
+ boundary: "dry run only — no approval, spend counter, ledger or control-plane state is written. " + WAVE3_BOUNDARY,
218
+ };
219
+ }
220
+
221
+ export function diffPolicies(args = {}) {
222
+ const before = isObj(args.before) ? args.before : {};
223
+ const after = isObj(args.after) ? args.after : {};
224
+ const index = (p) => new Map((Array.isArray(p.rules) ? p.rules : []).map((r) => [String(r.ruleId ?? r.type), r]));
225
+ const a = index(before);
226
+ const b = index(after);
227
+ const removed = [...a.keys()].filter((k) => !b.has(k));
228
+ const added = [...b.keys()].filter((k) => !a.has(k));
229
+ const changed = [...a.keys()].filter((k) => b.has(k) && canonicalJson(a.get(k)) !== canonicalJson(b.get(k))).map((k) => ({
230
+ ruleId: k,
231
+ before: a.get(k),
232
+ after: b.get(k),
233
+ }));
234
+ const limits = (p) => {
235
+ const r = (p.rules ?? []).find((x) => x.type === "VALUE_LIMIT");
236
+ return decimal(r?.params?.max);
237
+ };
238
+ const lb = limits(before);
239
+ const la = limits(after);
240
+ const signals = [];
241
+ if (added.length > 0) signals.push("tighter"); // an added rule constrains more
242
+ if (removed.length > 0) signals.push("looser");
243
+ if (la !== null && lb !== null && la < lb) signals.push("tighter");
244
+ if (la !== null && lb !== null && la > lb) signals.push("looser");
245
+ const uniqueSignals = [...new Set(signals)];
246
+ return {
247
+ type: "policy_diff",
248
+ changed: removed.length + added.length + changed.length > 0,
249
+ addedRules: added.map((k) => b.get(k)),
250
+ removedRules: removed.map((k) => a.get(k)),
251
+ changedRules: changed,
252
+ limit: { before: lb === null ? null : String(lb), after: la === null ? null : String(la), deltaMinor: lb !== null && la !== null ? String(la - lb) : null },
253
+ strictness: uniqueSignals.length === 1 ? uniqueSignals[0] : uniqueSignals.length === 2 ? "mixed" : changed.length > 0 ? "changed" : "unchanged",
254
+ requiresReconsent: removed.length + added.length + changed.length > 0,
255
+ digests: { before: digestOf(before), after: digestOf(after) },
256
+ boundary: WAVE3_BOUNDARY,
257
+ };
258
+ }
259
+
260
+ export function generateBoundaryCases(args = {}) {
261
+ const policy = isObj(args.policy) ? args.policy : {};
262
+ const base = isObj(args.baseIntent) ? args.baseIntent : {};
263
+ const nowSeconds = now(args);
264
+ const limitRule = (policy.rules ?? []).find((r) => r.type === "VALUE_LIMIT");
265
+ const limit = decimal(limitRule?.params?.max);
266
+ const cases = [];
267
+ const push = (label, intent) => {
268
+ const evaluated = evaluateIntent(policy, intent, nowSeconds);
269
+ cases.push({ label, intent, expected: evaluated.allowed ? "ALLOW" : "DENY", blocking: evaluated.blocking.map((c) => c.ruleId) });
270
+ };
271
+ if (limit !== null) {
272
+ push("amount at the limit", { ...base, amount: String(limit) });
273
+ if (limit > 0n) push("amount one minor unit below the limit", { ...base, amount: String(limit - 1n) });
274
+ push("amount one minor unit above the limit", { ...base, amount: String(limit + 1n) });
275
+ }
276
+ const targetRule = (policy.rules ?? []).find((r) => r.type === "TARGET_ALLOWLIST");
277
+ if (targetRule && Array.isArray(targetRule.params?.targets) && targetRule.params.targets[0]) {
278
+ push("unlisted target", { ...base, target: "0x" + "ee".repeat(20) });
279
+ }
280
+ const recipientRule = (policy.rules ?? []).find((r) => r.type === "RECIPIENT_ALLOWLIST");
281
+ if (recipientRule && Array.isArray(recipientRule.params?.addresses) && recipientRule.params.addresses[0]) {
282
+ push("unlisted recipient", { ...base, recipient: "0x" + "ff".repeat(20) });
283
+ }
284
+ if (nowSeconds !== null) push("approval window already closed", { ...base, validUntil: String(nowSeconds - 1n) });
285
+ if (base.currency) push("currency outside the policy", { ...base, currency: base.currency === "USD" ? "EUR" : "USD" });
286
+ return {
287
+ type: "policy_boundary_cases",
288
+ spec: "CG-BC/1",
289
+ count: cases.length,
290
+ cases,
291
+ usage: "paste each case into coreguard_explain_decision or a test suite; expected is computed by the same rules the server enforces, not asserted by hand",
292
+ boundary: WAVE3_BOUNDARY,
293
+ };
294
+ }
295
+
296
+ // ---------------------------------------------------------------------------
297
+ // MCP supply-chain audit
298
+ // ---------------------------------------------------------------------------
299
+
300
+ const SECRET_ENV = /(SECRET|TOKEN|KEY|PASSWORD|PASSWD|PRIVATE|CREDENTIAL)/i;
301
+
302
+ export function auditServerManifest(args = {}) {
303
+ const manifest = isObj(args.manifest) ? args.manifest : {};
304
+ const findings = [];
305
+ const add = (id, severity, detail, evidence) => findings.push({ id, severity, detail, ...(evidence === undefined ? {} : { evidence }) });
306
+ const packages = Array.isArray(manifest.packages) ? manifest.packages : [];
307
+ const remotes = Array.isArray(manifest.remotes) ? manifest.remotes : [];
308
+ if (remotes.length > 0) add("REMOTE_ENDPOINT", "HIGH", "server declares a remote transport; the client trusts bytes it did not run", remotes.map((r) => r?.url ?? r).slice(0, 5));
309
+ for (const p of packages) {
310
+ if (p?.version === undefined || p?.identifier === undefined) add("UNPINNED_PACKAGE", "MEDIUM", "package entry has no pinned identifier/version", p ?? null);
311
+ if (p?.transport?.type && !["stdio", "sse"].includes(String(p.transport.type))) add("UNKNOWN_TRANSPORT", "LOW", `transport ${String(p.transport.type)} is not a documented MCP transport`, String(p.transport.type));
312
+ if (Array.isArray(p?.environmentVariables)) {
313
+ for (const env of p.environmentVariables) {
314
+ if (SECRET_ENV.test(String(env?.name ?? ""))) add("SECRET_REQUIRED", "INFO", `server asks the host for ${String(env.name)}; least-privilege review recommended`, String(env.name));
315
+ }
316
+ }
317
+ }
318
+ if (packages.length === 0 && remotes.length === 0) add("NO_DISTRIBUTION", "MEDIUM", "manifest declares neither a package nor a remote endpoint", null);
319
+ if (!str(manifest.repository?.url)) add("NO_REPOSITORY", "LOW", "no source repository in the manifest; provenance cannot be checked from the record alone", null);
320
+ if (!str(manifest.version) || manifest.version === "latest") add("VERSION_NOT_PINNED", "MEDIUM", "manifest version is missing or floating", manifest.version ?? null);
321
+ if (!manifest.description) add("NO_DESCRIPTION", "INFO", "no description; tool poisoning scans have nothing to read", null);
322
+ const severities = findings.map((f) => f.severity);
323
+ const risk = severities.includes("HIGH") ? "high" : severities.includes("MEDIUM") ? "medium" : "low";
324
+ return {
325
+ type: "mcp_manifest_audit",
326
+ spec: "CG-MM/1",
327
+ serverName: str(manifest.name) ?? null,
328
+ version: manifest.version ?? null,
329
+ transport: remotes.length > 0 ? "remote" : packages.length > 0 ? "package" : "undeclared",
330
+ risk,
331
+ findings,
332
+ counts: { total: findings.length, high: severities.filter((s) => s === "HIGH").length, medium: severities.filter((s) => s === "MEDIUM").length, low: severities.filter((s) => s === "LOW").length, info: severities.filter((s) => s === "INFO").length },
333
+ manifestDigest: digestOf(manifest),
334
+ note: "structural audit of the record only — it does not execute the server or attest its behaviour",
335
+ boundary: WAVE3_BOUNDARY,
336
+ };
337
+ }
338
+
339
+ const HIDDEN_CHAR_KINDS = Object.freeze([
340
+ [0x00ad, 0x00ad, "soft_hyphen"],
341
+ [0x200b, 0x200f, "zero_width"],
342
+ [0x202a, 0x202e, "bidi_override"],
343
+ [0x2060, 0x2064, "invisible_operator"],
344
+ [0x2066, 0x2069, "bidi_isolate"],
345
+ [0xfeff, 0xfeff, "bom"],
346
+ [0xe0000, 0xe007f, "unicode_tag"],
347
+ ]);
348
+
349
+ const INJECTION_PHRASES = Object.freeze([
350
+ "ignore previous", "ignore all previous", "disregard previous", "disregard all previous",
351
+ "system prompt", "developer mode", "do not tell the user", "don't tell the user",
352
+ "do not mention", "without asking", "without confirmation", "auto-approve", "always approve",
353
+ "bypass", "exfiltrate", "send to", "do not log", "hide from", "secretly", "hidden instruction",
354
+ ]);
355
+
356
+ export function scanToolDescriptions(args = {}) {
357
+ const tools = Array.isArray(args.tools) ? args.tools : [];
358
+ const findings = [];
359
+ tools.forEach((tool, toolIndex) => {
360
+ const name = String(tool?.name ?? `tool-${toolIndex}`);
361
+ const description = String(tool?.description ?? "");
362
+ for (let i = 0; i < description.length; i++) {
363
+ const start = i; // astral code points consume two UTF-16 units; report where the character STARTS
364
+ const cp = description.codePointAt(i);
365
+ if (cp > 0xffff) i++; // consume the low surrogate
366
+ const kind = HIDDEN_CHAR_KINDS.find(([lo, hi]) => cp >= lo && cp <= hi)?.[2];
367
+ if (kind) {
368
+ findings.push({ tool: name, toolIndex, index: start, codepoint: "U+" + cp.toString(16).toUpperCase().padStart(4, "0"), kind, severity: kind === "unicode_tag" || kind === "bidi_override" ? "HIGH" : "MEDIUM" });
369
+ }
370
+ }
371
+ const lower = description.toLowerCase();
372
+ for (const phrase of INJECTION_PHRASES) {
373
+ let at = lower.indexOf(phrase);
374
+ while (at !== -1) {
375
+ findings.push({ tool: name, toolIndex, index: at, phrase, kind: "injection_phrase", severity: "HIGH" });
376
+ at = lower.indexOf(phrase, at + phrase.length);
377
+ }
378
+ }
379
+ const comments = description.match(/<!--[\s\S]*?-->/g);
380
+ if (comments) findings.push({ tool: name, toolIndex, index: description.indexOf(comments[0]), kind: "html_comment", severity: "MEDIUM", count: comments.length });
381
+ });
382
+ const high = findings.filter((f) => f.severity === "HIGH").length;
383
+ const medium = findings.filter((f) => f.severity === "MEDIUM").length;
384
+ return {
385
+ type: "tool_description_scan",
386
+ spec: "CG-TS/1",
387
+ toolsScanned: tools.length,
388
+ verdict: high > 0 ? "DANGEROUS" : medium > 0 ? "SUSPICIOUS" : "CLEAN",
389
+ counts: { findings: findings.length, high, medium },
390
+ findings,
391
+ note: "detectors cover invisible/bidi/tag characters, HTML comments and a fixed imperative-phrase list; absence of findings is not proof of safety",
392
+ boundary: WAVE3_BOUNDARY,
393
+ };
394
+ }
395
+
396
+ const CONFUSABLES = Object.freeze({
397
+ "а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "у": "y", "х": "x", "і": "i", "ј": "j",
398
+ "ѕ": "s", "ԁ": "d", "һ": "h", "ӏ": "l", "ԛ": "q", "ԝ": "w", "ν": "v", "α": "a", "ο": "o",
399
+ "ε": "e", "ι": "i", "κ": "k", "ρ": "p", "τ": "t", "υ": "u", "χ": "x", "0": "o", "1": "l",
400
+ "5": "s", "3": "e", "8": "b", "|": "l", "!": "i",
401
+ });
402
+
403
+ /**
404
+ * Minimal RFC 3492 decoder for a single `xn--` label.
405
+ *
406
+ * Without this, an attacker writes the homoglyph in punycode and the string
407
+ * comparison sees two unrelated ASCII names — the exact trick the check exists
408
+ * to catch. Returns null when the label is not decodable (the caller then keeps
409
+ * the raw label and the `punycode` signal still fires).
410
+ */
411
+ function decodePunycodeLabel(label) {
412
+ const prefix = "xn--";
413
+ if (!label.startsWith(prefix)) return label;
414
+ const input = label.slice(prefix.length);
415
+ const base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128;
416
+ const adapt = (delta, numPoints, firstTime) => {
417
+ let d = firstTime ? Math.floor(delta / damp) : delta >> 1;
418
+ d += Math.floor(d / numPoints);
419
+ let k = 0;
420
+ while (d > ((base - tMin) * tMax) >> 1) {
421
+ d = Math.floor(d / (base - tMin));
422
+ k += base;
423
+ }
424
+ return Math.floor(k + ((base - tMin + 1) * d) / (d + skew));
425
+ };
426
+ const digitOf = (code) => {
427
+ if (code >= 0x30 && code <= 0x39) return code - 22;
428
+ if (code >= 0x41 && code <= 0x5a) return code - 0x41;
429
+ if (code >= 0x61 && code <= 0x7a) return code - 0x61;
430
+ return -1;
431
+ };
432
+ const output = [];
433
+ let n = initialN, i = 0, bias = initialBias;
434
+ const basic = input.lastIndexOf("-");
435
+ if (basic > 0) {
436
+ for (let j = 0; j < basic; j++) {
437
+ const code = input.charCodeAt(j);
438
+ if (code >= 0x80) return null;
439
+ output.push(String.fromCharCode(code));
440
+ }
441
+ }
442
+ let idx = basic > 0 ? basic + 1 : 0;
443
+ while (idx < input.length) {
444
+ const oldi = i;
445
+ let w = 1;
446
+ for (let k = base; ; k += base) {
447
+ if (idx >= input.length) return null;
448
+ const digit = digitOf(input.charCodeAt(idx++));
449
+ if (digit < 0) return null;
450
+ i += digit * w;
451
+ const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
452
+ if (digit < t) break;
453
+ w *= base - t;
454
+ }
455
+ const total = output.length + 1;
456
+ bias = adapt(i - oldi, total, oldi === 0);
457
+ n += Math.floor(i / total);
458
+ i %= total;
459
+ if (n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff)) return null;
460
+ output.splice(i, 0, String.fromCodePoint(n));
461
+ i++;
462
+ }
463
+ return output.join("");
464
+ }
465
+
466
+ function skeleton(domain) {
467
+ const labels = String(domain ?? "")
468
+ .toLowerCase()
469
+ .trim()
470
+ .replace(/^https?:\/\//, "")
471
+ .replace(/\/.*$/, "")
472
+ .replace(/\.$/, "")
473
+ .split(".")
474
+ .map((label) => decodePunycodeLabel(label) ?? label);
475
+ return labels
476
+ .join(".")
477
+ .replace(/[^a-z0-9.\-\u0080-\uffff]/g, "")
478
+ .split("")
479
+ .map((ch) => CONFUSABLES[ch] ?? ch)
480
+ .join("");
481
+ }
482
+
483
+ function scriptOf(ch) {
484
+ if (/[\u0400-\u04FF]/.test(ch)) return "cyrillic";
485
+ if (/[\u0370-\u03FF]/.test(ch)) return "greek";
486
+ if (/[a-z]/i.test(ch)) return "latin";
487
+ if (/[0-9]/.test(ch)) return "digit";
488
+ return null;
489
+ }
490
+
491
+ function levenshtein(a, b) {
492
+ const m = a.length, n = b.length;
493
+ if (m === 0 || n === 0) return Math.max(m, n);
494
+ let prev = Array.from({ length: n + 1 }, (_, j) => j);
495
+ for (let i = 1; i <= m; i++) {
496
+ const cur = [i];
497
+ for (let j = 1; j <= n; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
498
+ prev = cur;
499
+ }
500
+ return prev[n];
501
+ }
502
+
503
+ export function checkLookalike(args = {}) {
504
+ const candidate = String(args.candidate ?? "");
505
+ const reference = String(args.reference ?? "");
506
+ const sc = skeleton(candidate);
507
+ const sr = skeleton(reference);
508
+ const distance = levenshtein(sc, sr);
509
+ const scripts = [...new Set(candidate.split("").map(scriptOf).filter((s) => s === "cyrillic" || s === "greek" || s === "latin"))];
510
+ const mixedScript = scripts.length > 1;
511
+ const punycode = /(^|\.)xn--/.test(candidate.toLowerCase());
512
+ const identicalSkeleton = sc === sr && candidate.toLowerCase() !== reference.toLowerCase();
513
+ const threshold = Math.max(sc.length, sr.length) >= 12 ? 2 : 1;
514
+ const lookalike = identicalSkeleton || distance <= threshold;
515
+ return {
516
+ type: "lookalike_check",
517
+ spec: "CG-LK/1",
518
+ candidate,
519
+ reference,
520
+ candidateSkeleton: sc,
521
+ referenceSkeleton: sr,
522
+ distance,
523
+ verdict: candidate.toLowerCase() === reference.toLowerCase() ? "IDENTICAL" : lookalike ? "LOOKALIKE" : "DISTINCT",
524
+ signals: { mixedScript, punycode, mappedCharacters: candidate.split("").filter((ch) => CONFUSABLES[ch]).length, distance },
525
+ note: "a LOOKALIKE verdict is a reason to stop and check by hand; DISTINCT is not an endorsement of the candidate",
526
+ boundary: WAVE3_BOUNDARY,
527
+ };
528
+ }
529
+
530
+ function toolShape(tool) {
531
+ return { name: tool?.name, description: tool?.description, inputSchema: tool?.inputSchema ?? null };
532
+ }
533
+
534
+ function jaccard(a, b) {
535
+ const wa = new Set(String(a).toLowerCase().split(/\W+/).filter(Boolean));
536
+ const wb = new Set(String(b).toLowerCase().split(/\W+/).filter(Boolean));
537
+ if (wa.size === 0 && wb.size === 0) return 1;
538
+ let common = 0;
539
+ for (const w of wa) if (wb.has(w)) common++;
540
+ return common / (wa.size + wb.size - common);
541
+ }
542
+
543
+ export function diffToolSurface(args = {}) {
544
+ const before = Array.isArray(args.before) ? args.before : [];
545
+ const after = Array.isArray(args.after) ? args.after : [];
546
+ const b = new Map(before.map((t) => [String(t?.name), toolShape(t)]));
547
+ const a = new Map(after.map((t) => [String(t?.name), toolShape(t)]));
548
+ const added = [...a.keys()].filter((k) => !b.has(k));
549
+ const removed = [...b.keys()].filter((k) => !a.has(k));
550
+ const changed = [];
551
+ for (const name of [...b.keys()].filter((k) => a.has(k))) {
552
+ const oldT = b.get(name);
553
+ const newT = a.get(name);
554
+ const schemaChanged = digestOf(oldT.inputSchema) !== digestOf(newT.inputSchema);
555
+ const descriptionChanged = oldT.description !== newT.description;
556
+ if (schemaChanged || descriptionChanged) {
557
+ changed.push({
558
+ name,
559
+ schemaChanged,
560
+ descriptionChanged,
561
+ descriptionSimilarity: descriptionChanged ? Number(jaccard(oldT.description, newT.description).toFixed(3)) : 1,
562
+ oldDigest: digestOf(oldT),
563
+ newDigest: digestOf(newT),
564
+ });
565
+ }
566
+ }
567
+ const requiresReconsent = removed.length > 0 || changed.some((c) => c.schemaChanged);
568
+ return {
569
+ type: "tool_surface_diff",
570
+ spec: "CG-SD/1",
571
+ counts: { before: before.length, after: after.length, added: added.length, removed: removed.length, changed: changed.length },
572
+ added: added.map((k) => a.get(k).name),
573
+ removed: removed.map((k) => b.get(k).name),
574
+ changed,
575
+ severity: removed.length > 0 ? "HIGH" : changed.some((c) => c.schemaChanged) ? "HIGH" : changed.length > 0 || added.length > 0 ? "MEDIUM" : "NONE",
576
+ requiresReconsent,
577
+ note: "a surface change after approval is a rug-pull signal; pin the digest you approved and diff on every upgrade",
578
+ boundary: WAVE3_BOUNDARY,
579
+ };
580
+ }
581
+
582
+ export function verifyEvidenceBundle(args = {}) {
583
+ const bundle = isObj(args.bundle) ? args.bundle : {};
584
+ const items = Array.isArray(bundle.items) ? bundle.items : [];
585
+ const expected = str(bundle.digest);
586
+ const computed = digestOf({ spec: bundle.spec ?? "CG-EB/1", items });
587
+ const itemIssues = [];
588
+ items.forEach((item, i) => {
589
+ if (item?.digest && item.digest !== digestOf(item.body ?? item)) itemIssues.push({ index: i, issue: "ITEM_DIGEST_MISMATCH", id: item?.id ?? null });
590
+ });
591
+ const issues = [];
592
+ if (!expected) issues.push("BUNDLE_DIGEST_MISSING");
593
+ else if (expected !== computed) issues.push("BUNDLE_DIGEST_MISMATCH");
594
+ issues.push(...itemIssues.map((x) => x.issue));
595
+ return {
596
+ type: "evidence_bundle_verification",
597
+ spec: "CG-EB/1",
598
+ ok: issues.length === 0,
599
+ verdict: issues.length === 0 ? "VERIFIED" : "INVALID",
600
+ issues,
601
+ counts: { items: items.length, itemIssues: itemIssues.length },
602
+ expectedDigest: expected ?? null,
603
+ computedDigest: computed,
604
+ itemIssues,
605
+ boundary: "checks the bundle against its own digest; it does not attest that the events happened. " + WAVE3_BOUNDARY,
606
+ };
607
+ }
608
+
609
+ // ---------------------------------------------------------------------------
610
+ // Evidence: redaction and Merkle batch attestation
611
+ // ---------------------------------------------------------------------------
612
+
613
+ const SENSITIVE = /(credential|secret|token|password|passwd|private|pan|card|iban|email|phone|signature|api[-_]?key)/i;
614
+
615
+ export function redactReceipt(args = {}) {
616
+ const receipt = isObj(args.receipt) ? args.receipt : {};
617
+ const reveal = new Set(Array.isArray(args.reveal) ? args.reveal.map(String) : []);
618
+ const redactions = [];
619
+ const walk = (value, path) => {
620
+ if (Array.isArray(value)) return value.map((v, i) => walk(v, `${path}[${i}]`));
621
+ if (isObj(value)) {
622
+ const out = {};
623
+ for (const [k, v] of Object.entries(value)) {
624
+ const p = path ? `${path}.${k}` : k;
625
+ if (!reveal.has(p) && !reveal.has(k) && SENSITIVE.test(k) && v !== null && typeof v !== "object") {
626
+ out[k] = "[REDACTED]";
627
+ redactions.push({ path: p, reason: "field name matches the sensitive-data set", originalType: typeof v, originalLength: String(v).length });
628
+ } else if (!reveal.has(p) && !reveal.has(k) && SENSITIVE.test(k) && v && typeof v === "object") {
629
+ out[k] = "[REDACTED]";
630
+ redactions.push({ path: p, reason: "object under a sensitive field name", originalType: "object" });
631
+ } else {
632
+ out[k] = walk(v, p);
633
+ }
634
+ }
635
+ return out;
636
+ }
637
+ return value;
638
+ };
639
+ const redacted = walk(receipt, "");
640
+ return {
641
+ type: "redacted_receipt",
642
+ spec: "CG-RR/1",
643
+ redacted,
644
+ redactions,
645
+ counts: { redactions: redactions.length, fields: Object.keys(receipt).length },
646
+ originalDigest: digestOf(receipt),
647
+ redactedDigest: digestOf(redacted),
648
+ note: "keep originalDigest with the redacted copy: a holder of the original can prove it is the same record without revealing redacted fields",
649
+ boundary: WAVE3_BOUNDARY,
650
+ };
651
+ }
652
+
653
+ function leafHash(item) {
654
+ return "sha256:" + createHash("sha256").update(Buffer.concat([Buffer.from([0]), Buffer.from(canonicalJson(item))])).digest("hex");
655
+ }
656
+
657
+ function nodeHash(left, right) {
658
+ return "sha256:" + createHash("sha256").update(Buffer.concat([Buffer.from([1]), Buffer.from(left), Buffer.from(right)])).digest("hex");
659
+ }
660
+
661
+ function largestPowerOfTwoBelow(n) {
662
+ let k = 1;
663
+ while (k * 2 < n) k *= 2;
664
+ return k;
665
+ }
666
+
667
+ function merkleRoot(leaves) {
668
+ if (leaves.length === 0) return "sha256:" + createHash("sha256").update("").digest("hex");
669
+ if (leaves.length === 1) return leaves[0];
670
+ const k = largestPowerOfTwoBelow(leaves.length);
671
+ return nodeHash(merkleRoot(leaves.slice(0, k)), merkleRoot(leaves.slice(k)));
672
+ }
673
+
674
+ function merkleProof(leaves, index) {
675
+ if (leaves.length <= 1) return [];
676
+ const k = largestPowerOfTwoBelow(leaves.length);
677
+ if (index < k) return [...merkleProof(leaves.slice(0, k), index), { side: "right", hash: merkleRoot(leaves.slice(k)) }];
678
+ return [...merkleProof(leaves.slice(k), index - k), { side: "left", hash: merkleRoot(leaves.slice(0, k)) }];
679
+ }
680
+
681
+ export function attestBatch(args = {}) {
682
+ const receipts = Array.isArray(args.receipts) ? args.receipts : [];
683
+ const leaves = receipts.map((r) => leafHash(r));
684
+ const root = merkleRoot(leaves);
685
+ return {
686
+ type: "batch_attestation",
687
+ spec: "CG-MT/1",
688
+ algorithm: "sha256 Merkle over RFC 6962-style domain-separated nodes (0x00 leaf, 0x01 node)",
689
+ root,
690
+ count: receipts.length,
691
+ leaves: leaves.map((hash, index) => ({ index, hash, receiptDigest: digestOf(receipts[index]) })),
692
+ proofs: leaves.map((_, index) => merkleProof(leaves, index)),
693
+ usage: "publish/notarise only the root; hand each holder their proof so inclusion stays verifiable offline",
694
+ boundary: "the root commits to exactly these caller-supplied records; it does not prove they are true or that they happened. " + WAVE3_BOUNDARY,
695
+ };
696
+ }
697
+
698
+ export function verifyBatchProof(args = {}) {
699
+ const leaf = str(args.leafDigest);
700
+ const root = str(args.root);
701
+ const proof = Array.isArray(args.proof) ? args.proof : [];
702
+ let acc = leaf;
703
+ const steps = [];
704
+ for (const step of proof) {
705
+ if (!step || (step.side !== "left" && step.side !== "right") || typeof step.hash !== "string") {
706
+ return { type: "merkle_proof_verification", spec: "CG-MT/1", ok: false, verdict: "INVALID", issue: "MALFORMED_PROOF_STEP", boundary: WAVE3_BOUNDARY };
707
+ }
708
+ acc = step.side === "left" ? nodeHash(step.hash, acc) : nodeHash(acc, step.hash);
709
+ steps.push({ side: step.side, hash: step.hash });
710
+ }
711
+ const ok = acc === root;
712
+ return {
713
+ type: "merkle_proof_verification",
714
+ spec: "CG-MT/1",
715
+ ok,
716
+ verdict: ok ? "VERIFIED" : "INVALID",
717
+ issue: ok ? null : "ROOT_MISMATCH",
718
+ recomputedRoot: acc,
719
+ root: root ?? null,
720
+ steps,
721
+ boundary: "inclusion in the supplied root only; the root's own trustworthiness is a separate question. " + WAVE3_BOUNDARY,
722
+ };
723
+ }
724
+
725
+ // ---------------------------------------------------------------------------
726
+ // Operations
727
+ // ---------------------------------------------------------------------------
728
+
729
+ export function freezeAgent(args = {}) {
730
+ const storePath = String(args.storePath);
731
+ const agentId = String(args.agentId);
732
+ const reason = str(args.reason) ?? "frozen via MCP";
733
+ const decidedBy = str(args.decidedBy) ?? null;
734
+ const pinned = args.nowSeconds === undefined ? null : Number(args.nowSeconds);
735
+ const cp = createControlPlane({ storePath, create: true, ...(pinned === null ? {} : { now: () => new Date(pinned * 1000) }) });
736
+ const state = cp.getState();
737
+ const wasRevoked = state.agents?.[agentId]?.status === "revoked";
738
+ const pending = Object.values(state.approvals ?? {}).filter((a) => a.agentId === agentId && a.status === "pending");
739
+ // The ledger only transitions pending → approved/rejected. An approval that was
740
+ // already approved cannot be re-decided, so the freeze must not pretend it did:
741
+ // revocation already makes it fail closed at evaluate() time. Report it as
742
+ // superseded instead of counting a silent "rejection" that never happened.
743
+ // A second freeze must not re-report approvals the first one already superseded.
744
+ const approved = wasRevoked ? [] : Object.values(state.approvals ?? {}).filter((a) => a.agentId === agentId && a.status === "approved");
745
+ const revoked = cp.revokeAgent(agentId, reason);
746
+ const rejected = pending.map((a) => {
747
+ try {
748
+ return cp.decideApproval(a.id, { decision: "rejected", decidedBy: decidedBy ?? "freeze", reason: `agent frozen: ${reason}` });
749
+ } catch (err) {
750
+ return { id: a.id, error: err?.message ?? String(err) };
751
+ }
752
+ });
753
+ const report = cp.auditReport({ limit: 1 });
754
+ const rejectedOk = rejected.filter((r) => !r.error);
755
+ return {
756
+ type: "agent_freeze",
757
+ spec: "CG-FZ/1",
758
+ agentId,
759
+ reason,
760
+ revoked,
761
+ approvals: {
762
+ open: pending.length + approved.length,
763
+ rejected: rejectedOk.length,
764
+ failures: rejected.filter((r) => r.error).length,
765
+ approvedSuperseded: approved.length,
766
+ },
767
+ openApprovalIds: [...pending, ...approved].map((a) => a.id),
768
+ rejectedApprovalIds: rejectedOk.map((r) => r.id),
769
+ approvedSupersededIds: approved.map((a) => a.id),
770
+ note: "pending approvals are rejected in this operation; approved-but-unexecuted approvals cannot be re-decided by the ledger and are superseded by the agent revocation (evaluate() denies them)",
771
+ chain: { ok: report.chain?.ok ?? null, length: report.chain?.length ?? null, headHash: report.chain?.headHash ?? null },
772
+ boundary: "revocation and rejection are recorded in the local hash-chained ledger; they do not reach a chain, a merchant or a payment network. " + WAVE3_BOUNDARY,
773
+ };
774
+ }
775
+
776
+ export function budgetRunway(args = {}) {
777
+ const limit = decimal(args.policyLimitMinor);
778
+ const spent = decimal(args.spentMinor ?? "0");
779
+ const asOf = decimal(args.asOfSeconds);
780
+ const window = decimal(args.windowSeconds ?? "86400");
781
+ if (limit === null || spent === null || asOf === null || window === null || window === 0n) {
782
+ throw new Error("policyLimitMinor, spentMinor, asOfSeconds and windowSeconds must be non-negative integers, windowSeconds non-zero");
783
+ }
784
+ const events = Array.isArray(args.events) ? args.events : [];
785
+ const from = asOf - window;
786
+ const inWindow = events.filter((e) => {
787
+ const at = decimal(e?.atSeconds);
788
+ return at !== null && at > from && at <= asOf;
789
+ });
790
+ const windowSpend = inWindow.reduce((sum, e) => sum + (decimal(e?.amountMinor) ?? 0n), 0n);
791
+ const remaining = limit > spent ? limit - spent : 0n;
792
+ const perSecond = windowSpend === 0n ? 0 : Number(windowSpend) / Number(window);
793
+ const runwaySeconds = perSecond === 0 ? null : Math.floor(Number(remaining) / perSecond);
794
+ return {
795
+ type: "budget_runway",
796
+ spec: "CG-BR/1",
797
+ asOfSeconds: String(asOf),
798
+ windowSeconds: String(window),
799
+ limitMinor: String(limit),
800
+ spentMinor: String(spent),
801
+ remainingMinor: String(remaining),
802
+ windowSpendMinor: String(windowSpend),
803
+ burnPerDayMinor: perSecond === 0 ? "0" : String(BigInt(Math.round(perSecond * 86400))),
804
+ runwaySeconds: runwaySeconds === null ? null : String(runwaySeconds),
805
+ runwayDays: runwaySeconds === null ? null : Number((runwaySeconds / 86400).toFixed(2)),
806
+ exhausted: remaining === 0n,
807
+ exhaustedAtSeconds: runwaySeconds === null ? null : String(asOf + BigInt(runwaySeconds)),
808
+ note: "straight-line projection from the supplied window; no seasonal model, no forecast confidence interval",
809
+ boundary: WAVE3_BOUNDARY,
810
+ };
811
+ }
812
+
813
+ function median(values) {
814
+ if (values.length === 0) return 0;
815
+ const sorted = [...values].sort((x, y) => x - y);
816
+ const mid = Math.floor(sorted.length / 2);
817
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
818
+ }
819
+
820
+ export function detectSpendAnomaly(args = {}) {
821
+ const events = Array.isArray(args.events) ? args.events : [];
822
+ const amounts = events.map((e) => Number(decimal(e?.amountMinor) ?? 0n));
823
+ const med = median(amounts);
824
+ const deviations = amounts.map((x) => Math.abs(x - med));
825
+ const mad = median(deviations);
826
+ const sensitivity = str(args.sensitivity) ?? "medium";
827
+ const threshold = sensitivity === "high" ? 2.5 : sensitivity === "low" ? 3.5 : 3.0;
828
+ const anomalies = [];
829
+ events.forEach((e, i) => {
830
+ const x = amounts[i];
831
+ const denom = mad === 0 ? (deviations.reduce((s, d) => s + d, 0) / Math.max(1, deviations.length) || 1) : mad;
832
+ const score = mad === 0 ? (x === med ? 0 : Number(((0.7979 * Math.abs(x - med)) / denom).toFixed(3))) : Number(((0.6745 * Math.abs(x - med)) / mad).toFixed(3));
833
+ if (score >= threshold) {
834
+ anomalies.push({ index: i, id: e?.id ?? null, amountMinor: String(decimal(e?.amountMinor) ?? 0n), medianMinor: String(Math.round(med)), score, direction: x > med ? "above" : "below" });
835
+ }
836
+ });
837
+ return {
838
+ type: "spend_anomaly_scan",
839
+ spec: "CG-SA/1",
840
+ sensitivity,
841
+ threshold,
842
+ counts: { events: events.length, anomalies: anomalies.length },
843
+ baseline: { medianMinor: String(Math.round(med)), madMinor: String(Math.round(mad)) },
844
+ anomalies: anomalies.sort((a, b) => b.score - a.score),
845
+ note: "median/MAD is robust to a few large outliers; an anomaly is a question, not a finding of fraud",
846
+ boundary: WAVE3_BOUNDARY,
847
+ };
848
+ }
849
+
850
+ export function incidentTimeline(args = {}) {
851
+ let audit = [];
852
+ let chain = null;
853
+ if (isObj(args.report)) {
854
+ audit = Array.isArray(args.report.recentAudit) ? args.report.recentAudit : [];
855
+ chain = args.report.chain ?? null;
856
+ if (!chain && Array.isArray(args.report.audit)) audit = args.report.audit;
857
+ } else if (str(args.storePath)) {
858
+ const cp = createControlPlane({ storePath: String(args.storePath), create: true });
859
+ const state = cp.getState();
860
+ audit = Array.isArray(state.audit) ? state.audit : [];
861
+ chain = verifyAuditChain(state);
862
+ }
863
+ const events = audit
864
+ .map((e) => ({ seq: e?.seq ?? null, type: String(e?.type ?? "unknown"), at: String(e?.at ?? ""), detail: e?.detail ?? null, hash: e?.hash ?? null }))
865
+ .sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
866
+ const gaps = [];
867
+ for (let i = 1; i < events.length; i++) {
868
+ if (typeof events[i].seq === "number" && typeof events[i - 1].seq === "number" && events[i].seq !== events[i - 1].seq + 1) {
869
+ gaps.push({ afterSeq: events[i - 1].seq, beforeSeq: events[i].seq });
870
+ }
871
+ }
872
+ return {
873
+ type: "incident_timeline",
874
+ spec: "CG-IT/1",
875
+ count: events.length,
876
+ events,
877
+ gaps,
878
+ chain: chain ? { ok: chain.ok ?? null, length: chain.length ?? null, headHash: chain.headHash ?? null } : null,
879
+ note: "built from the ledger you supplied; ordering is by the ledger's own sequence number, never by arrival time",
880
+ boundary: WAVE3_BOUNDARY,
881
+ };
882
+ }
883
+
884
+ // ---------------------------------------------------------------------------
885
+ // Interop and meta
886
+ // ---------------------------------------------------------------------------
887
+
888
+ export function translateReceipt(args = {}) {
889
+ const receipt = isObj(args.receipt) ? args.receipt : {};
890
+ const to = String(args.to ?? "acp");
891
+ const amount = str(receipt.amount) ?? str(receipt.total) ?? str(receipt.amountMinor) ?? null;
892
+ const currency = str(receipt.currency) ?? null;
893
+ const merchant = str(receipt.merchant) ?? str(receipt.merchantName) ?? str(receipt.target) ?? null;
894
+ const id = str(receipt.receiptId) ?? str(receipt.id) ?? null;
895
+ const approvedAt = str(receipt.approvedAt) ?? str(receipt.createdAt) ?? null;
896
+ const losses = [];
897
+ let translated;
898
+ if (to === "x402") {
899
+ translated = { scheme: "exact", network: str(receipt.network) ?? null, asset: str(receipt.asset) ?? currency, payTo: str(receipt.payTo) ?? merchant, amount, resource: str(receipt.resource) ?? null, txRef: str(receipt.txRef) ?? null };
900
+ if (!receipt.network) losses.push("network not present in the source receipt");
901
+ if (!receipt.asset) losses.push("asset inferred from currency; x402 expects a token/asset id");
902
+ } else if (to === "acp") {
903
+ translated = { type: "acp.checkout_receipt", id, merchant, total: amount === null ? null : { amount, currency }, approvedAt, sourceDigest: digestOf(receipt) };
904
+ if (!approvedAt) losses.push("approval timestamp not present");
905
+ if (!merchant) losses.push("merchant not present");
906
+ } else if (to === "cgcr") {
907
+ translated = { version: "CGCR/1", receiptId: id, merchant, amount, currency, approvedAt, sourceDigest: digestOf(receipt), provenance: "translated — re-verify against the original bytes before relying on it" };
908
+ losses.push("translation cannot reproduce commitments the source did not carry");
909
+ } else {
910
+ throw new Error("to must be \"acp\", \"x402\" or \"cgcr\"");
911
+ }
912
+ return {
913
+ type: "receipt_translation",
914
+ to,
915
+ translated,
916
+ losses,
917
+ sourceDigest: digestOf(receipt),
918
+ lossless: losses.length === 0,
919
+ note: "structural mapping only — nothing is signed, verified or settled by this tool",
920
+ boundary: WAVE3_BOUNDARY,
921
+ };
922
+ }
923
+
924
+ export function emitTestVectors(args = {}) {
925
+ const policy = isObj(args.policy) ? args.policy : {};
926
+ const base = isObj(args.baseIntent) ? args.baseIntent : {};
927
+ const nowSeconds = args.nowSeconds === undefined ? "1794657600" : String(args.nowSeconds);
928
+ const amount = decimal(base.amount) ?? 0n;
929
+ const recipient = str(base.recipient) ?? "0x" + "11".repeat(20);
930
+ const vectors = [
931
+ { id: "allow-baseline", intent: { ...base }, expected: "ALLOW", why: "the approved baseline" },
932
+ { id: "deny-amount-drift", intent: { ...base, amount: String(amount + 1n) }, expected: "DENY", why: "one minor unit above the approved amount" },
933
+ { id: "deny-recipient-swap", intent: { ...base, recipient: "0x" + "ff".repeat(20) }, expected: "DENY", why: "recipient not on the allowlist" },
934
+ { id: "deny-expired-window", intent: { ...base, validUntil: String(BigInt(nowSeconds) - 1n) }, expected: "DENY", why: "approval window already closed" },
935
+ { id: "allow-at-limit", intent: { ...base, amount: String((decimal((policy.rules ?? []).find((r) => r.type === "VALUE_LIMIT")?.params?.max) ?? amount)) }, expected: "ALLOW", why: "exactly at the value limit" },
936
+ ].map((v) => ({ ...v, policyDigest: digestOf(policy), expectedBy: "the same rule engine coreguard_explain_decision uses" }));
937
+ return {
938
+ type: "integration_test_vectors",
939
+ spec: "CG-TV/1",
940
+ count: vectors.length,
941
+ vectors,
942
+ runWith: "coreguard_explain_decision({ policy, intent, nowSeconds }) — compare verdict to expected",
943
+ boundary: WAVE3_BOUNDARY,
944
+ };
945
+ }
946
+
947
+ export function describeSurface(args = {}, ctx = {}) {
948
+ const format = String(args.format ?? "card");
949
+ const names = Array.isArray(ctx.toolNames) ? ctx.toolNames : [];
950
+ const families = names.reduce((acc, n) => {
951
+ const key = n.replace(/^coreguard_/, "");
952
+ acc.total += 1;
953
+ return acc;
954
+ }, { total: 0 });
955
+ const card = {
956
+ type: "capability_card",
957
+ spec: "CG-CC/1",
958
+ server: ctx.serverName ?? "coreguard-agent-commerce",
959
+ version: ctx.version ?? null,
960
+ protocolVersion: ctx.protocolVersion ?? null,
961
+ transport: "stdio (newline-delimited JSON-RPC 2.0)",
962
+ tools: families.total,
963
+ categories: ["consent receipts (CGCR/1)", "execution verification (AGR/1)", "x402 payment evidence", "machine economy", "CGCP/1 control plane", "Wave 3 policy reasoning", "Wave 3 MCP supply-chain audit", "Wave 3 evidence and operations"],
964
+ specs: ["CGCR/1", "AGR/1", "CGCP/1", "CGXA/1", "CG-OBS/1", "CG-W3/1"],
965
+ boundary: WAVE3_BOUNDARY,
966
+ key: "offline · deterministic · zero keys · no custody · no broadcast · VERIFIED ≠ SAFE",
967
+ };
968
+ if (format === "badge") {
969
+ return { type: "capability_badge", spec: "CG-CC/1", badge: `coreguard-agent-commerce ${card.version ?? ""} · ${card.tools} tools · offline · deterministic`, card, boundary: WAVE3_BOUNDARY };
970
+ }
971
+ return { ...card, boundary: WAVE3_BOUNDARY };
972
+ }
973
+
974
+ // ---------------------------------------------------------------------------
975
+ // Schemas and handlers (one registry the MCP server spreads in)
976
+ // ---------------------------------------------------------------------------
977
+
978
+ const ctxProp = {
979
+ callerContext: { type: "object", description: "Optional caller-provided trace/context metadata. Echoed back; never a cryptographic input." },
980
+ };
981
+
982
+ const schema = (properties, required, description) => ({
983
+ type: "object",
984
+ description,
985
+ properties: { ...properties, ...ctxProp },
986
+ required,
987
+ additionalProperties: true,
988
+ });
989
+
990
+ const out = (description) => ({ type: "object", description, additionalProperties: true });
991
+
992
+ export const WAVE3_TOOLS = Object.freeze([
993
+ {
994
+ name: "coreguard_compile_policy",
995
+ description: "Compile a compact spending spec (limit, merchant/recipient/selector allowlists, currency) into a canonical CGEP/1 policy with a stable digest. Compiling the same spec twice yields the same digest; nothing is stored.",
996
+ inputSchema: schema({ spec: { type: "object", description: "policyId, name, maxAmountMinor (decimal string), allowMerchants[], allowRecipients[], allowSelectors[], currency" } }, ["spec"], "Compact policy spec to compile."),
997
+ outputSchema: out("Canonical CGEP/1 policy plus its digest and rule summary."),
998
+ },
999
+ {
1000
+ name: "coreguard_explain_decision",
1001
+ description: "Evaluate an intent against a policy and explain the verdict rule by rule, including the smallest single change (counterfactual) that clears the first blocking rule. Deterministic, no state written.",
1002
+ inputSchema: schema({ policy: { type: "object" }, intent: { type: "object" }, nowSeconds: { type: "string", pattern: "^[0-9]+$", description: "pinned epoch seconds used for expiry checks" } }, ["policy", "intent", "nowSeconds"], "Policy and intent to explain."),
1003
+ outputSchema: out("Verdict, per-rule checks and a counterfactual."),
1004
+ },
1005
+ {
1006
+ name: "coreguard_simulate_spend",
1007
+ description: "Dry-run a batch of intents against a policy: allowed/denied per row, blocking rules, totals and counterfactuals. No approval, spend counter or ledger state is written.",
1008
+ inputSchema: schema({ policy: { type: "object" }, intents: { type: "array", items: { type: "object" }, description: "intent objects in CGEP/1 shape" }, nowSeconds: { type: "string", pattern: "^[0-9]+$" } }, ["policy", "intents", "nowSeconds"], "Policy plus the batch of intents to simulate."),
1009
+ outputSchema: out("Per-intent verdicts and aggregate totals, marked dryRun."),
1010
+ },
1011
+ {
1012
+ name: "coreguard_diff_policies",
1013
+ description: "Semantic diff of two CGEP/1 policies by rule id: added, removed, changed rules, value-limit delta, strictness trend, and whether an agent must re-consent.",
1014
+ inputSchema: schema({ before: { type: "object" }, after: { type: "object" } }, ["before", "after"], "The two policies to compare."),
1015
+ outputSchema: out("Rule-level diff with strictness and reconsent flags."),
1016
+ },
1017
+ {
1018
+ name: "coreguard_generate_boundary_cases",
1019
+ description: "Generate the cases that break naive policy tests: at the limit, one unit below, one above, unlisted target/recipient, closed window, wrong currency — each with the verdict the real rule engine computes.",
1020
+ inputSchema: schema({ policy: { type: "object" }, baseIntent: { type: "object" }, nowSeconds: { type: "string", pattern: "^[0-9]+$" } }, ["policy", "baseIntent", "nowSeconds"], "Policy and a representative intent."),
1021
+ outputSchema: out("Boundary cases with expected verdicts computed by the server."),
1022
+ },
1023
+ {
1024
+ name: "coreguard_audit_server_manifest",
1025
+ description: "Audit an MCP server manifest (server.json) before installing it: remote transports, unpinned packages, missing provenance, secret env requests, undeclared distribution. Returns a deterministic risk card.",
1026
+ inputSchema: schema({ manifest: { type: "object", description: "the server.json record as published" } }, ["manifest"], "The MCP server manifest to audit."),
1027
+ outputSchema: out("Risk level, findings with severities and the manifest digest."),
1028
+ },
1029
+ {
1030
+ name: "coreguard_scan_tool_descriptions",
1031
+ description: "Scan MCP tool descriptions for hidden-instruction and spoofing payloads: bidi overrides, Unicode tag characters, zero-width and invisible operators, HTML comments, and a fixed imperative phrase list — with offsets.",
1032
+ inputSchema: schema({ tools: { type: "array", items: { type: "object" }, description: "tools from tools/list: name + description" } }, ["tools"], "Tool metadata to scan."),
1033
+ outputSchema: out("CLEAN/SUSPICIOUS/DANGEROUS verdict with byte-level findings."),
1034
+ },
1035
+ {
1036
+ name: "coreguard_check_lookalike",
1037
+ description: "Check a merchant domain or package name for homoglyph, mixed-script and punycode impersonation of a reference: confusable folding, skeleton edit distance and explicit signals.",
1038
+ inputSchema: schema({ candidate: { type: "string" }, reference: { type: "string" } }, ["candidate", "reference"], "Candidate string and the reference it claims to be."),
1039
+ outputSchema: out("IDENTICAL/LOOKALIKE/DISTINCT verdict with the signals behind it."),
1040
+ },
1041
+ {
1042
+ name: "coreguard_diff_tool_surface",
1043
+ description: "Diff two tools/list snapshots (before/after an upgrade) to catch rug pulls: added, removed and re-described tools, schema changes, description similarity, severity and whether re-consent is required.",
1044
+ inputSchema: schema({ before: { type: "array", items: { type: "object" } }, after: { type: "array", items: { type: "object" } } }, ["before", "after"], "The two tool surfaces."),
1045
+ outputSchema: out("Surface diff with severity and requiresReconsent."),
1046
+ },
1047
+ {
1048
+ name: "coreguard_verify_evidence_bundle",
1049
+ description: "Verify a portable evidence bundle against its own digest and each item's digest: detects edits, dropped items and digest substitution without any network or trust root.",
1050
+ inputSchema: schema({ bundle: { type: "object", description: "{ spec, digest, items:[{id, body, digest}] }" } }, ["bundle"], "The bundle to verify."),
1051
+ outputSchema: out("VERIFIED/INVALID with the computed digest and item issues."),
1052
+ },
1053
+ {
1054
+ name: "coreguard_redact_receipt",
1055
+ description: "Produce a shareable redacted receipt: sensitive fields (credentials, tokens, PAN/card, email, phone, keys) are masked, every redaction is listed, and both the original and redacted digests are returned so a holder can prove it is the same record.",
1056
+ inputSchema: schema({ receipt: { type: "object" }, reveal: { type: "array", items: { type: "string" }, description: "field names or dotted paths to keep visible" } }, ["receipt"], "Receipt to redact."),
1057
+ outputSchema: out("Redacted copy, redaction manifest and both digests."),
1058
+ },
1059
+ {
1060
+ name: "coreguard_attest_batch",
1061
+ description: "Commit many receipts with one Merkle root: domain-separated SHA-256 leaves, RFC 6962-style tree, per-item inclusion proof. Publish only the root; each holder keeps a verifiable proof.",
1062
+ inputSchema: schema({ receipts: { type: "array", items: { type: "object" } } }, ["receipts"], "Receipts to batch."),
1063
+ outputSchema: out("Merkle root, leaf digests and inclusion proofs."),
1064
+ },
1065
+ {
1066
+ name: "coreguard_verify_batch_proof",
1067
+ description: "Verify a Merkle inclusion proof offline: recompute the root from the leaf digest and the supplied left/right path, and report the exact root mismatch if any.",
1068
+ inputSchema: schema({ leafDigest: { type: "string" }, root: { type: "string" }, proof: { type: "array", items: { type: "object", description: "{ side: left|right, hash }" } } }, ["leafDigest", "root", "proof"], "Leaf, root and proof to verify."),
1069
+ outputSchema: out("VERIFIED or INVALID with the recomputed root, the issue code and the proof steps used."),
1070
+ },
1071
+ {
1072
+ name: "coreguard_freeze_agent",
1073
+ description: "Kill switch over a CGCP/1 control plane: revoke the agent, reject every pending approval it holds in one audited operation, and report approved-but-unexecuted approvals as superseded by the revocation. Returns the chain head and every affected id.",
1074
+ inputSchema: schema({ storePath: { type: "string" }, agentId: { type: "string" }, reason: { type: "string" }, decidedBy: { type: "string" }, nowSeconds: { type: "string", pattern: "^[0-9]+$", description: "optional pinned epoch seconds; omit to let the local ledger stamp call time" } }, ["storePath", "agentId"], "Control-plane path and the agent to freeze."),
1075
+ outputSchema: out("Revocation record, rejected and superseded approval ids, failure count and chain status."),
1076
+ },
1077
+ {
1078
+ name: "coreguard_budget_runway",
1079
+ description: "Project budget runway from pinned inputs: limit, spend to date, a pinned asOf and a spend window. Straight-line burn, remaining budget, runway seconds/days and the exhaustion epoch — no wall clock, no forecasting model.",
1080
+ inputSchema: schema({ asOfSeconds: { type: "string", pattern: "^[0-9]+$" }, policyLimitMinor: { type: "string", pattern: "^[0-9]+$" }, spentMinor: { type: "string", pattern: "^[0-9]+$" }, windowSeconds: { type: "string", pattern: "^[0-9]+$" }, events: { type: "array", items: { type: "object", description: "{ atSeconds, amountMinor }" } } }, ["asOfSeconds", "policyLimitMinor", "spentMinor", "windowSeconds"], "Pinned budget inputs."),
1081
+ outputSchema: out("Remaining budget, burn rate, runway and exhaustion epoch."),
1082
+ },
1083
+ {
1084
+ name: "coreguard_detect_spend_anomaly",
1085
+ description: "Flag unusual spend events with a median/MAD robust score (no training data, no clock): returns the baseline, the threshold for the chosen sensitivity, and each anomaly with its score and direction.",
1086
+ inputSchema: schema({ events: { type: "array", items: { type: "object", description: "{ id, amountMinor, atSeconds }" } }, sensitivity: { type: "string", enum: ["low", "medium", "high"] } }, ["events"], "Spend events to scan."),
1087
+ outputSchema: out("Baseline, anomaly list and the score threshold used."),
1088
+ },
1089
+ {
1090
+ name: "coreguard_incident_timeline",
1091
+ description: "Assemble an incident timeline from a control-plane ledger (storePath or an audit report): sequence-ordered events, detected sequence gaps and audit-chain status. Ordering comes from the ledger, never from arrival time.",
1092
+ inputSchema: schema({ report: { type: "object" }, storePath: { type: "string" } }, ["report"], "An audit report, or a storePath when no report is supplied."),
1093
+ outputSchema: out("Sequence-ordered events, detected sequence gaps and audit-chain status."),
1094
+ },
1095
+ {
1096
+ name: "coreguard_translate_receipt",
1097
+ description: "Structurally translate a receipt to ACP, x402 or CGCR/1 and list exactly what the target cannot carry. Translation only: nothing is signed, verified or settled.",
1098
+ inputSchema: schema({ receipt: { type: "object" }, to: { type: "string", enum: ["acp", "x402", "cgcr"] } }, ["receipt", "to"], "Receipt and target shape."),
1099
+ outputSchema: out("Translated object, loss list and source digest."),
1100
+ },
1101
+ {
1102
+ name: "coreguard_emit_test_vectors",
1103
+ description: "Emit deterministic integration test vectors for an SDK or gateway: baseline allow, amount drift, recipient swap, expired window and at-limit, each with the verdict the real rule engine computes.",
1104
+ inputSchema: schema({ policy: { type: "object" }, baseIntent: { type: "object" }, nowSeconds: { type: "string", pattern: "^[0-9]+$" } }, ["policy", "baseIntent"], "Policy and baseline intent."),
1105
+ outputSchema: out("Vectors with expected verdicts and how to run them."),
1106
+ },
1107
+ {
1108
+ name: "coreguard_describe_surface",
1109
+ description: "Return this server's capability card (or a one-line badge): version, transport, protocol, tool count, categories and the standing boundary — the record a directory, catalog or buyer can quote verbatim.",
1110
+ inputSchema: schema({ format: { type: "string", enum: ["card", "badge"] } }, ["format"], "card or badge."),
1111
+ outputSchema: out("Capability card with the server's own boundary."),
1112
+ },
1113
+ ]);
1114
+
1115
+ function reqString(args, key) {
1116
+ const v = args?.[key];
1117
+ if (typeof v !== "string" || v.length === 0) throw new Error(`${key} is required`);
1118
+ return v;
1119
+ }
1120
+ function reqObject(args, key) {
1121
+ if (!isObj(args?.[key])) throw new Error(`${key} must be a JSON object`);
1122
+ return args[key];
1123
+ }
1124
+ function reqArray(args, key) {
1125
+ if (!Array.isArray(args?.[key])) throw new Error(`${key} must be an array`);
1126
+ return args[key];
1127
+ }
1128
+
1129
+ export const WAVE3_HANDLERS = Object.freeze({
1130
+ coreguard_compile_policy: (a) => compilePolicy(a),
1131
+ coreguard_explain_decision: (a) => explainDecision(a),
1132
+ coreguard_simulate_spend: (a) => simulateSpend(a),
1133
+ coreguard_diff_policies: (a) => diffPolicies(a),
1134
+ coreguard_generate_boundary_cases: (a) => generateBoundaryCases(a),
1135
+ coreguard_audit_server_manifest: (a) => auditServerManifest(a),
1136
+ coreguard_scan_tool_descriptions: (a) => scanToolDescriptions(a),
1137
+ coreguard_check_lookalike: (a) => { reqString(a, "candidate"); reqString(a, "reference"); return checkLookalike(a); },
1138
+ coreguard_diff_tool_surface: (a) => diffToolSurface(a),
1139
+ coreguard_verify_evidence_bundle: (a) => verifyEvidenceBundle(a),
1140
+ coreguard_redact_receipt: (a) => redactReceipt(a),
1141
+ coreguard_attest_batch: (a) => attestBatch(a),
1142
+ coreguard_verify_batch_proof: (a) => { reqString(a, "leafDigest"); reqString(a, "root"); if (!Array.isArray(a.proof)) throw new Error("proof must be an array"); return verifyBatchProof(a); },
1143
+ coreguard_freeze_agent: (a) => freezeAgent(a),
1144
+ coreguard_budget_runway: (a) => budgetRunway(a),
1145
+ coreguard_detect_spend_anomaly: (a) => detectSpendAnomaly(a),
1146
+ coreguard_incident_timeline: (a) => { if (!isObj(a?.report)) reqString(a, "storePath"); return incidentTimeline(a); }, /** report wins; storePath is the stateless fallback */
1147
+ coreguard_translate_receipt: (a) => { reqObject(a, "receipt"); reqString(a, "to"); return translateReceipt(a); },
1148
+ coreguard_emit_test_vectors: (a) => emitTestVectors(a),
1149
+ coreguard_describe_surface: (a, ctx) => { reqString(a, "format"); return describeSurface(a, ctx); },
1150
+ });
1151
+
1152
+ export const WAVE3_VALIDATORS = Object.freeze({
1153
+ coreguard_compile_policy: (a) => (isObj(a.spec) ? null : { code: "MISSING_ARGUMENT", detail: "spec is required and must be an object" }),
1154
+ coreguard_explain_decision: (a) => (isObj(a.policy) && isObj(a.intent) ? null : { code: "MISSING_ARGUMENT", detail: "policy and intent are required objects" }),
1155
+ coreguard_simulate_spend: (a) => (isObj(a.policy) && Array.isArray(a.intents) ? null : { code: "MISSING_ARGUMENT", detail: "policy (object) and intents (array) are required" }),
1156
+ coreguard_diff_policies: (a) => (isObj(a.before) && isObj(a.after) ? null : { code: "MISSING_ARGUMENT", detail: "before and after are required objects" }),
1157
+ coreguard_generate_boundary_cases: (a) => (isObj(a.policy) && isObj(a.baseIntent) ? null : { code: "MISSING_ARGUMENT", detail: "policy and baseIntent are required objects" }),
1158
+ coreguard_audit_server_manifest: (a) => (isObj(a.manifest) ? null : { code: "MISSING_ARGUMENT", detail: "manifest is required and must be an object" }),
1159
+ coreguard_scan_tool_descriptions: (a) => (Array.isArray(a.tools) ? null : { code: "MISSING_ARGUMENT", detail: "tools is required and must be an array" }),
1160
+ coreguard_check_lookalike: (a) => (typeof a.candidate === "string" && typeof a.reference === "string" ? null : { code: "MISSING_ARGUMENT", detail: "candidate and reference are required strings" }),
1161
+ coreguard_diff_tool_surface: (a) => (Array.isArray(a.before) && Array.isArray(a.after) ? null : { code: "MISSING_ARGUMENT", detail: "before and after are required arrays" }),
1162
+ coreguard_verify_evidence_bundle: (a) => (isObj(a.bundle) ? null : { code: "MISSING_ARGUMENT", detail: "bundle is required and must be an object" }),
1163
+ coreguard_redact_receipt: (a) => (isObj(a.receipt) ? null : { code: "MISSING_ARGUMENT", detail: "receipt is required and must be an object" }),
1164
+ coreguard_attest_batch: (a) => (Array.isArray(a.receipts) ? null : { code: "MISSING_ARGUMENT", detail: "receipts is required and must be an array" }),
1165
+ coreguard_verify_batch_proof: (a) => (typeof a.leafDigest === "string" && typeof a.root === "string" && Array.isArray(a.proof) ? null : { code: "MISSING_ARGUMENT", detail: "leafDigest, root and proof are required" }),
1166
+ coreguard_freeze_agent: (a) => (typeof a.storePath === "string" && typeof a.agentId === "string" ? null : { code: "MISSING_ARGUMENT", detail: "storePath and agentId are required strings" }),
1167
+ coreguard_budget_runway: (a) => (typeof a.asOfSeconds === "string" && typeof a.policyLimitMinor === "string" && typeof a.spentMinor === "string" && typeof a.windowSeconds === "string" ? null : { code: "MISSING_ARGUMENT", detail: "asOfSeconds, policyLimitMinor, spentMinor and windowSeconds are required digit strings" }),
1168
+ coreguard_detect_spend_anomaly: (a) => (Array.isArray(a.events) ? null : { code: "MISSING_ARGUMENT", detail: "events is required and must be an array" }),
1169
+ coreguard_incident_timeline: (a) => (typeof a.storePath === "string" || isObj(a.report) ? null : { code: "MISSING_ARGUMENT", detail: "storePath (or report) is required" }),
1170
+ coreguard_translate_receipt: (a) => (isObj(a.receipt) && ["acp", "x402", "cgcr"].includes(a.to) ? null : { code: "MISSING_ARGUMENT", detail: "receipt (object) and to (acp|x402|cgcr) are required" }),
1171
+ coreguard_emit_test_vectors: (a) => (isObj(a.policy) && isObj(a.baseIntent) ? null : { code: "MISSING_ARGUMENT", detail: "policy and baseIntent are required objects" }),
1172
+ coreguard_describe_surface: (a) => (a.format === "card" || a.format === "badge" ? null : { code: "MISSING_ARGUMENT", detail: "format must be card or badge" }),
1173
+ });