@coreguard/agent-commerce 0.1.5 → 0.2.0

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/README.md CHANGED
@@ -12,7 +12,7 @@ bytes approved, and for verifying any executed trace against that receipt.
12
12
  - **Fail-closed execution verification** — a consent plus an executed trace
13
13
  yields a verdict with named drift classes (AGR/1 taxonomy); incomplete or
14
14
  ambiguous evidence is never treated as a pass.
15
- - **stdio MCP server** (JSON-RPC 2.0, protocol `2025-06-18`) exposing twenty-six tools,
15
+ - **stdio MCP server** (JSON-RPC 2.0, protocol `2025-06-18`) exposing forty-six tools,
16
16
  all offline, all deterministic, zero keys.
17
17
 
18
18
  MIT. Node ≥ 18. No network calls, no stored credentials, no wall clock.
@@ -217,6 +217,35 @@ These 10 tools extend CoreGuard into x402/machine/delegation evidence flows. **B
217
217
  | `coreguard_revoke_consent` | `decideApproval` / `revokeAgent` / `revokePolicy` |
218
218
  | `coreguard_audit_transaction` | `auditReport` with optional filters |
219
219
 
220
+ ### Wave 3 — reasoning, supply chain, evidence, operations (CG-W3/1)
221
+
222
+ 20 deterministic tools that answer questions the receipt layer could only imply. All offline, zero keys, no wall clock in any commitment.
223
+
224
+ | Tool | Purpose |
225
+ |---|---|
226
+ | `coreguard_compile_policy` | Compile a compact spend spec into a canonical CGEP/1 policy + stable digest. |
227
+ | `coreguard_explain_decision` | Per-rule verdict plus the smallest single change that clears the first block. |
228
+ | `coreguard_simulate_spend` | Dry-run a batch against a policy; no state written. |
229
+ | `coreguard_diff_policies` | Rule-level diff, limit delta, tightness, re-consent flag. |
230
+ | `coreguard_generate_boundary_cases` | At/±1 the limit, unlisted target/recipient, closed window, wrong currency — verdicts computed by the engine. |
231
+ | `coreguard_audit_server_manifest` | Risk card for a third-party MCP `server.json` before install. |
232
+ | `coreguard_scan_tool_descriptions` | Byte-level scan for bidi/tag/zero-width characters, HTML comments, imperative payloads. |
233
+ | `coreguard_check_lookalike` | Homoglyph, mixed-script and punycode impersonation check. |
234
+ | `coreguard_diff_tool_surface` | Rug-pull detector between two `tools/list` snapshots. |
235
+ | `coreguard_verify_evidence_bundle` | Recompute bundle + item digests offline. |
236
+ | `coreguard_redact_receipt` | Share a receipt with a redaction manifest and both digests. |
237
+ | `coreguard_attest_batch` | Merkle root + per-item inclusion proofs over many receipts. |
238
+ | `coreguard_verify_batch_proof` | Offline inclusion proof verification. |
239
+ | `coreguard_freeze_agent` | Revoke an agent and reject its open approvals in one audited operation. |
240
+ | `coreguard_budget_runway` | Straight-line runway from pinned inputs; exhaustion epoch. |
241
+ | `coreguard_detect_spend_anomaly` | Median/MAD outlier scan with explicit threshold. |
242
+ | `coreguard_incident_timeline` | Sequence-ordered ledger events, gaps and chain status. |
243
+ | `coreguard_translate_receipt` | Structural ACP/x402/CGCR mapping with an explicit loss list. |
244
+ | `coreguard_emit_test_vectors` | Integration vectors with the verdicts the enforcer computes. |
245
+ | `coreguard_describe_surface` | Capability card/badge a directory can quote verbatim. |
246
+
247
+ **Wave 3 boundary:** every answer is arithmetic over caller-supplied JSON. A finding is evidence for a human decision, not a verdict on a third party; the manifest and description audits do not execute the server. `VERIFIED ≠ SAFE`.
248
+
220
249
  ## Errors
221
250
 
222
251
  Failures are tool results, never exceptions and never a process exit:
package/mcp.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  * (one JSON object per line, both directions) — the same shape MCP clients
8
8
  * speak for stdio servers.
9
9
  *
10
- * Tools (all offline/self-hosted, deterministic, zero network keys): 10 core consent/verification tools + 10 Wave 1 Machine Economy tools + 6 Wave 2 CGCP/1 mapping tools (intent/receipt/limits/revoke/audit) = 26 total. Optional trust roots enable Ed25519 signature verification for telemetry/delegation; no custody, no broadcast, no network calls; external settlement/physical truth/device identity beyond supplied key material NOT proven.
10
+ * Tools (all offline/self-hosted, deterministic, zero network keys): 10 core consent/verification tools + 10 Wave 1 Machine Economy tools + 6 Wave 2 CGCP/1 mapping tools (intent/receipt/limits/revoke/audit) + 20 Wave 3 tools (policy reasoning, MCP supply-chain audit, evidence, operations, interop) = 46 total. Optional trust roots enable Ed25519 signature verification for telemetry/delegation; no custody, no broadcast, no network calls; external settlement/physical truth/device identity beyond supplied key material NOT proven.
11
11
  *
12
12
  * BOUNDARIES (standing): synthetic demo data is the caller's; nothing here
13
13
  * contacts any platform or payment network (no contact/integration/endorsement
@@ -57,6 +57,7 @@ import {
57
57
  MACHINE_ECONOMY_BOUNDARY,
58
58
  } from "./machine-economy.mjs";
59
59
  import { createIntent, issueReceipt, verifyReceipt as verifyCgcpReceipt, checkLimits, revokeConsent, auditTransaction, CGCP_MCP_BOUNDARY } from "./cgcp-mcp-tools.mjs";
60
+ import { WAVE3_TOOLS, WAVE3_HANDLERS, WAVE3_VALIDATORS, WAVE3_BOUNDARY } from "./wave3.mjs";
60
61
 
61
62
  const PROTOCOL_VERSION = "2025-06-18";
62
63
 
@@ -104,6 +105,28 @@ const TOOL_NAMES = Object.freeze([
104
105
  "coreguard_check_limits",
105
106
  "coreguard_revoke_consent",
106
107
  "coreguard_audit_transaction",
108
+ // Wave 3 (CG-W3/1) — deterministic policy reasoning, MCP supply-chain audit,
109
+ // evidence, operations and interop. Same transport, same error contract.
110
+ "coreguard_compile_policy",
111
+ "coreguard_explain_decision",
112
+ "coreguard_simulate_spend",
113
+ "coreguard_diff_policies",
114
+ "coreguard_generate_boundary_cases",
115
+ "coreguard_audit_server_manifest",
116
+ "coreguard_scan_tool_descriptions",
117
+ "coreguard_check_lookalike",
118
+ "coreguard_diff_tool_surface",
119
+ "coreguard_verify_evidence_bundle",
120
+ "coreguard_redact_receipt",
121
+ "coreguard_attest_batch",
122
+ "coreguard_verify_batch_proof",
123
+ "coreguard_freeze_agent",
124
+ "coreguard_budget_runway",
125
+ "coreguard_detect_spend_anomaly",
126
+ "coreguard_incident_timeline",
127
+ "coreguard_translate_receipt",
128
+ "coreguard_emit_test_vectors",
129
+ "coreguard_describe_surface",
107
130
  ]);
108
131
 
109
132
  /**
@@ -157,6 +180,7 @@ function requireString(args, key) {
157
180
 
158
181
  /** Per-tool input validation. Returns null when the arguments are usable. */
159
182
  const VALIDATORS = Object.freeze({
183
+ ...WAVE3_VALIDATORS,
160
184
  coreguard_authorize(args) {
161
185
  const missing = requireObjects(args, ["intent", "policy", "declaredTrace"]);
162
186
  if (missing) return missing;
@@ -660,6 +684,7 @@ const TOOLS = Object.freeze([
660
684
  inputSchema: { type: "object", properties: { storePath: { type: "string" }, txRef: { type: "string" }, approvalId: { type: "string" }, agentId: { type: "string" }, limit: { type: "integer", minimum: 1 }, ...CALLER_CONTEXT_PROPERTY }, required: ["storePath"] },
661
685
  outputSchema: { type: "object", description: "CGCP/1 audit report with chain status and optional filters.", properties: { type: { type: "string" }, spec: { type: "string" }, report: { type: "object" }, mapping: { type: "string" }, boundary: { type: "string" }, callerContext: { type: "object" } }, additionalProperties: true },
662
686
  },
687
+ ...WAVE3_TOOLS,
663
688
  ]);
664
689
 
665
690
  function withCallerContext(value, args) {
@@ -747,6 +772,10 @@ async function callTool(name, args, { consumedSet } = {}) {
747
772
  if (name === "coreguard_check_limits") return success(withCallerContext(checkLimits(a), a));
748
773
  if (name === "coreguard_revoke_consent") return success(withCallerContext(revokeConsent(a), a));
749
774
  if (name === "coreguard_audit_transaction") return success(withCallerContext(auditTransaction(a), a));
775
+ if (WAVE3_HANDLERS[name]) {
776
+ const ctx = { toolNames: TOOL_NAMES, version: PACKAGE.version, serverName: SERVER_INFO.name, protocolVersion: PROTOCOL_VERSION };
777
+ return success(withCallerContext(WAVE3_HANDLERS[name](a, ctx), a));
778
+ }
750
779
  return failure(ERROR_CODES.UNKNOWN_TOOL, `unknown tool: ${String(name)}`);
751
780
  } catch (err) {
752
781
  return failure(ERROR_CODES.TOOL_ERROR, err?.message ?? String(err));
@@ -811,7 +840,9 @@ export function createMcpHandler({ write } = {}) {
811
840
 
812
841
  export function selfCheck() {
813
842
  return [
814
- ["tools exposed", TOOL_NAMES.length === 26 && TOOL_NAMES[0] === "coreguard_authorize" && TOOL_NAMES[9] === "coreguard_consumption_status" && TOOL_NAMES[19] === "coreguard_verify_delegation_chain" && TOOL_NAMES[25] === "coreguard_audit_transaction"],
843
+ ["tools exposed", TOOL_NAMES.length === 46 && TOOL_NAMES[0] === "coreguard_authorize" && TOOL_NAMES[9] === "coreguard_consumption_status" && TOOL_NAMES[19] === "coreguard_verify_delegation_chain" && TOOL_NAMES[25] === "coreguard_audit_transaction" && TOOL_NAMES[45] === "coreguard_describe_surface"],
844
+ ["wave 3 declares schemas for every tool", WAVE3_TOOLS.length === 20 && WAVE3_TOOLS.every((t) => t.name.startsWith("coreguard_") && t.inputSchema?.required?.length > 0 && t.outputSchema?.type === "object" && WAVE3_HANDLERS[t.name])],
845
+ ["wave 3 boundary travels", WAVE3_BOUNDARY.includes("VERIFIED ≠ SAFE")],
815
846
  ["protocol version pinned", PROTOCOL_VERSION === "2025-06-18"],
816
847
  ["spec surfaced", CONSENT_SPEC === "CGCR/1" && AGENT_COMMERCE_VERSION === "AC-SDK/1"],
817
848
  ["boundary travels", SERVER_BOUNDARY.includes("VERIFIED ≠ SAFE") && SERVER_BOUNDARY.includes("NOT_BUILT")],
@@ -824,7 +855,7 @@ export function selfCheck() {
824
855
  ];
825
856
  }
826
857
 
827
- export { SERVER_INFO, PROTOCOL_VERSION, TOOLS };
858
+ export { SERVER_INFO, PROTOCOL_VERSION, TOOLS, TOOL_NAMES };
828
859
 
829
860
  export async function main() {
830
861
  const handle = createMcpHandler();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@coreguard/agent-commerce",
3
- "version": "0.1.5",
4
- "description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases — SDK, REST surface, and a stdio MCP server (26 tools, JSON-RPC 2.0, offline, zero keys)",
3
+ "version": "0.2.0",
4
+ "description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases — SDK, REST surface, and a stdio MCP server (46 tools, JSON-RPC 2.0, offline, zero keys)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "exports": {
@@ -77,7 +77,8 @@
77
77
  "risk.mjs",
78
78
  "server.json",
79
79
  "spend.mjs",
80
- "trust.mjs"
80
+ "trust.mjs",
81
+ "wave3.mjs"
81
82
  ],
82
83
  "engines": {
83
84
  "node": ">=18"
package/server.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.EslaM-X/coreguard-agent-commerce",
4
- "description": "Fail-closed consent receipts and execution verification for agentic purchases. 26 MCP tools.",
4
+ "description": "Fail-closed consent receipts and execution verification for agentic purchases. 46 MCP tools.",
5
5
  "repository": {
6
6
  "url": "https://github.com/coreguard-global/CoreGuard",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.1.5",
9
+ "version": "0.2.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "@coreguard/agent-commerce",
14
- "version": "0.1.5",
14
+ "version": "0.2.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  }
package/wave3.mjs ADDED
@@ -0,0 +1,1087 @@
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
+ rules.push({ ruleId: "SELECTOR_001", type: "SELECTOR_ALLOWLIST", params: { selectors: spec.allowSelectors.map(String) }, severity: "CRITICAL" });
84
+ }
85
+ if (spec.currency) {
86
+ rules.push({ ruleId: "CURRENCY_001", type: "CURRENCY_ALLOWLIST", params: { currencies: [String(spec.currency)] }, severity: "HIGH" });
87
+ }
88
+ const policy = {
89
+ version: "CGEP/1",
90
+ policyId: String(spec.policyId ?? "compiled-policy"),
91
+ name: String(spec.name ?? "Compiled agent commerce policy"),
92
+ rules,
93
+ };
94
+ return {
95
+ type: "compiled_policy",
96
+ spec: "CGEP/1",
97
+ policy,
98
+ policyDigest: digestOf(policy),
99
+ rules: rules.map((r) => ({ ruleId: r.ruleId, type: r.type, severity: r.severity })),
100
+ normalizations: [
101
+ "amounts are decimal strings; values are compared as integers, never floats",
102
+ "allowlists keep caller order and are compared byte-for-byte after String()",
103
+ "rule ids are stable so two compilations of the same spec have the same digest",
104
+ ],
105
+ boundary: WAVE3_BOUNDARY,
106
+ };
107
+ }
108
+
109
+ function ruleCheck(rule, intent) {
110
+ const p = isObj(rule.params) ? rule.params : {};
111
+ const ruleId = String(rule.ruleId ?? rule.type);
112
+ switch (rule.type) {
113
+ case "VALUE_LIMIT": {
114
+ const max = decimal(p.max);
115
+ const amt = decimal(intent.amount);
116
+ if (max === null) return { ruleId, type: rule.type, ok: false, detail: "rule has no usable max" };
117
+ if (amt === null) return { ruleId, type: rule.type, ok: false, detail: "intent has no usable amount" };
118
+ return { ruleId, type: rule.type, ok: amt <= max, detail: `amount ${amt} ${amt <= max ? "≤" : ">"} max ${max}` };
119
+ }
120
+ case "TARGET_ALLOWLIST": {
121
+ const targets = Array.isArray(p.targets) ? p.targets.map(String) : [];
122
+ const ok = typeof intent.target === "string" && targets.includes(intent.target);
123
+ return { ruleId, type: rule.type, ok, detail: ok ? `target ${intent.target} allowlisted` : `target ${String(intent.target)} not allowlisted` };
124
+ }
125
+ case "RECIPIENT_ALLOWLIST": {
126
+ const addresses = Array.isArray(p.addresses) ? p.addresses.map(String) : [];
127
+ const ok = typeof intent.recipient === "string" && addresses.includes(intent.recipient);
128
+ return { ruleId, type: rule.type, ok, detail: ok ? `recipient ${intent.recipient} allowlisted` : `recipient ${String(intent.recipient)} not allowlisted` };
129
+ }
130
+ case "SELECTOR_ALLOWLIST": {
131
+ const selectors = Array.isArray(p.selectors) ? p.selectors.map(String) : [];
132
+ const ok = typeof intent.selector === "string" && selectors.includes(intent.selector.toLowerCase());
133
+ return { ruleId, type: rule.type, ok, detail: ok ? `selector ${intent.selector} allowlisted` : `selector ${String(intent.selector)} not allowlisted` };
134
+ }
135
+ case "CURRENCY_ALLOWLIST": {
136
+ const currencies = Array.isArray(p.currencies) ? p.currencies.map(String) : [];
137
+ const ok = typeof intent.currency === "string" && currencies.includes(intent.currency.toUpperCase());
138
+ return { ruleId, type: rule.type, ok, detail: ok ? `currency ${intent.currency} allowed` : `currency ${String(intent.currency)} not allowed` };
139
+ }
140
+ default:
141
+ return { ruleId, type: String(rule.type), ok: false, detail: "unknown rule type — fail closed" };
142
+ }
143
+ }
144
+
145
+ function evaluateIntent(policy, intent, nowSeconds) {
146
+ const rules = Array.isArray(policy?.rules) ? policy.rules : [];
147
+ const checks = rules.map((r) => ruleCheck(r, isObj(intent) ? intent : {}));
148
+ const expires = decimal(intent?.validUntil);
149
+ if (expires !== null && nowSeconds !== null) {
150
+ checks.push({ ruleId: "__expiry", type: "WINDOW", ok: expires >= nowSeconds, detail: `validUntil ${expires} ${expires >= nowSeconds ? "≥" : "<"} now ${nowSeconds}` });
151
+ }
152
+ const blocking = checks.filter((c) => !c.ok);
153
+ return { allowed: blocking.length === 0, checks, blocking, policyDigest: digestOf(policy ?? {}) };
154
+ }
155
+
156
+ function counterfactualFor(blocking, intent, policy, nowSeconds) {
157
+ const first = blocking[0];
158
+ if (!first) return null;
159
+ const rule = (policy?.rules ?? []).find((r) => String(r.ruleId) === first.ruleId);
160
+ const p = isObj(rule?.params) ? rule.params : {};
161
+ switch (first.type) {
162
+ 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)" };
163
+ 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" };
164
+ 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" };
165
+ 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" };
166
+ 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" };
167
+ 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" };
168
+ default: return { ruleId: first.ruleId, change: null, note: "no automatic counterfactual for this rule type" };
169
+ }
170
+ }
171
+
172
+ export function explainDecision(args = {}) {
173
+ const policy = isObj(args.policy) ? args.policy : {};
174
+ const intent = isObj(args.intent) ? args.intent : {};
175
+ const evaluated = evaluateIntent(policy, intent, now(args));
176
+ const counterfactual = counterfactualFor(evaluated.blocking, intent, policy, now(args));
177
+ return {
178
+ type: "policy_decision_explanation",
179
+ allowed: evaluated.allowed,
180
+ verdict: evaluated.allowed ? "ALLOW" : "DENY",
181
+ blockingRule: evaluated.blocking[0]?.ruleId ?? null,
182
+ checks: evaluated.checks,
183
+ counterfactual,
184
+ counterfactualNote: counterfactual ? "smallest single change that clears the first blocking rule; clearing it may reveal a second one" : null,
185
+ policyDigest: evaluated.policyDigest,
186
+ boundary: WAVE3_BOUNDARY,
187
+ };
188
+ }
189
+
190
+ export function simulateSpend(args = {}) {
191
+ const policy = isObj(args.policy) ? args.policy : {};
192
+ const intents = Array.isArray(args.intents) ? args.intents : [];
193
+ const nowSeconds = now(args);
194
+ const rows = intents.map((intent, index) => {
195
+ const evaluated = evaluateIntent(policy, intent, nowSeconds);
196
+ return {
197
+ index,
198
+ allowed: evaluated.allowed,
199
+ reasons: evaluated.blocking.map((c) => `${c.ruleId}:${c.type}`),
200
+ amount: String(intent?.amount ?? ""),
201
+ currency: str(intent?.currency) ?? null,
202
+ counterfactual: counterfactualFor(evaluated.blocking, intent, policy, nowSeconds),
203
+ };
204
+ });
205
+ const allowed = rows.filter((r) => r.allowed);
206
+ const total = allowed.reduce((sum, r) => sum + (decimal(r.amount) ?? 0n), 0n);
207
+ const deniedTotal = rows.filter((r) => !r.allowed).reduce((sum, r) => sum + (decimal(r.amount) ?? 0n), 0n);
208
+ return {
209
+ type: "spend_simulation",
210
+ dryRun: true,
211
+ policyDigest: digestOf(policy),
212
+ counts: { total: rows.length, allowed: allowed.length, denied: rows.length - allowed.length },
213
+ totals: { allowedMinor: String(total), deniedMinor: String(deniedTotal) },
214
+ rows,
215
+ boundary: "dry run only — no approval, spend counter, ledger or control-plane state is written. " + WAVE3_BOUNDARY,
216
+ };
217
+ }
218
+
219
+ export function diffPolicies(args = {}) {
220
+ const before = isObj(args.before) ? args.before : {};
221
+ const after = isObj(args.after) ? args.after : {};
222
+ const index = (p) => new Map((Array.isArray(p.rules) ? p.rules : []).map((r) => [String(r.ruleId ?? r.type), r]));
223
+ const a = index(before);
224
+ const b = index(after);
225
+ const removed = [...a.keys()].filter((k) => !b.has(k));
226
+ const added = [...b.keys()].filter((k) => !a.has(k));
227
+ const changed = [...a.keys()].filter((k) => b.has(k) && canonicalJson(a.get(k)) !== canonicalJson(b.get(k))).map((k) => ({
228
+ ruleId: k,
229
+ before: a.get(k),
230
+ after: b.get(k),
231
+ }));
232
+ const limits = (p) => {
233
+ const r = (p.rules ?? []).find((x) => x.type === "VALUE_LIMIT");
234
+ return decimal(r?.params?.max);
235
+ };
236
+ const lb = limits(before);
237
+ const la = limits(after);
238
+ const signals = [];
239
+ if (added.length > 0) signals.push("tighter"); // an added rule constrains more
240
+ if (removed.length > 0) signals.push("looser");
241
+ if (la !== null && lb !== null && la < lb) signals.push("tighter");
242
+ if (la !== null && lb !== null && la > lb) signals.push("looser");
243
+ const uniqueSignals = [...new Set(signals)];
244
+ return {
245
+ type: "policy_diff",
246
+ changed: removed.length + added.length + changed.length > 0,
247
+ addedRules: added.map((k) => b.get(k)),
248
+ removedRules: removed.map((k) => a.get(k)),
249
+ changedRules: changed,
250
+ limit: { before: lb === null ? null : String(lb), after: la === null ? null : String(la), deltaMinor: lb !== null && la !== null ? String(la - lb) : null },
251
+ strictness: uniqueSignals.length === 1 ? uniqueSignals[0] : uniqueSignals.length === 2 ? "mixed" : changed.length > 0 ? "changed" : "unchanged",
252
+ requiresReconsent: removed.length + added.length + changed.length > 0,
253
+ digests: { before: digestOf(before), after: digestOf(after) },
254
+ boundary: WAVE3_BOUNDARY,
255
+ };
256
+ }
257
+
258
+ export function generateBoundaryCases(args = {}) {
259
+ const policy = isObj(args.policy) ? args.policy : {};
260
+ const base = isObj(args.baseIntent) ? args.baseIntent : {};
261
+ const nowSeconds = now(args);
262
+ const limitRule = (policy.rules ?? []).find((r) => r.type === "VALUE_LIMIT");
263
+ const limit = decimal(limitRule?.params?.max);
264
+ const cases = [];
265
+ const push = (label, intent) => {
266
+ const evaluated = evaluateIntent(policy, intent, nowSeconds);
267
+ cases.push({ label, intent, expected: evaluated.allowed ? "ALLOW" : "DENY", blocking: evaluated.blocking.map((c) => c.ruleId) });
268
+ };
269
+ if (limit !== null) {
270
+ push("amount at the limit", { ...base, amount: String(limit) });
271
+ if (limit > 0n) push("amount one minor unit below the limit", { ...base, amount: String(limit - 1n) });
272
+ push("amount one minor unit above the limit", { ...base, amount: String(limit + 1n) });
273
+ }
274
+ const targetRule = (policy.rules ?? []).find((r) => r.type === "TARGET_ALLOWLIST");
275
+ if (targetRule && Array.isArray(targetRule.params?.targets) && targetRule.params.targets[0]) {
276
+ push("unlisted target", { ...base, target: "0x" + "ee".repeat(20) });
277
+ }
278
+ const recipientRule = (policy.rules ?? []).find((r) => r.type === "RECIPIENT_ALLOWLIST");
279
+ if (recipientRule && Array.isArray(recipientRule.params?.addresses) && recipientRule.params.addresses[0]) {
280
+ push("unlisted recipient", { ...base, recipient: "0x" + "ff".repeat(20) });
281
+ }
282
+ if (nowSeconds !== null) push("approval window already closed", { ...base, validUntil: String(nowSeconds - 1n) });
283
+ if (base.currency) push("currency outside the policy", { ...base, currency: base.currency === "USD" ? "EUR" : "USD" });
284
+ return {
285
+ type: "policy_boundary_cases",
286
+ spec: "CG-BC/1",
287
+ count: cases.length,
288
+ cases,
289
+ 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",
290
+ boundary: WAVE3_BOUNDARY,
291
+ };
292
+ }
293
+
294
+ // ---------------------------------------------------------------------------
295
+ // MCP supply-chain audit
296
+ // ---------------------------------------------------------------------------
297
+
298
+ const SECRET_ENV = /(SECRET|TOKEN|KEY|PASSWORD|PASSWD|PRIVATE|CREDENTIAL)/i;
299
+
300
+ export function auditServerManifest(args = {}) {
301
+ const manifest = isObj(args.manifest) ? args.manifest : {};
302
+ const findings = [];
303
+ const add = (id, severity, detail, evidence) => findings.push({ id, severity, detail, ...(evidence === undefined ? {} : { evidence }) });
304
+ const packages = Array.isArray(manifest.packages) ? manifest.packages : [];
305
+ const remotes = Array.isArray(manifest.remotes) ? manifest.remotes : [];
306
+ 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));
307
+ for (const p of packages) {
308
+ if (p?.version === undefined || p?.identifier === undefined) add("UNPINNED_PACKAGE", "MEDIUM", "package entry has no pinned identifier/version", p ?? null);
309
+ 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));
310
+ if (Array.isArray(p?.environmentVariables)) {
311
+ for (const env of p.environmentVariables) {
312
+ 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));
313
+ }
314
+ }
315
+ }
316
+ if (packages.length === 0 && remotes.length === 0) add("NO_DISTRIBUTION", "MEDIUM", "manifest declares neither a package nor a remote endpoint", null);
317
+ if (!str(manifest.repository?.url)) add("NO_REPOSITORY", "LOW", "no source repository in the manifest; provenance cannot be checked from the record alone", null);
318
+ if (!str(manifest.version) || manifest.version === "latest") add("VERSION_NOT_PINNED", "MEDIUM", "manifest version is missing or floating", manifest.version ?? null);
319
+ if (!manifest.description) add("NO_DESCRIPTION", "INFO", "no description; tool poisoning scans have nothing to read", null);
320
+ const severities = findings.map((f) => f.severity);
321
+ const risk = severities.includes("HIGH") ? "high" : severities.includes("MEDIUM") ? "medium" : "low";
322
+ return {
323
+ type: "mcp_manifest_audit",
324
+ spec: "CG-MM/1",
325
+ serverName: str(manifest.name) ?? null,
326
+ version: manifest.version ?? null,
327
+ transport: remotes.length > 0 ? "remote" : packages.length > 0 ? "package" : "undeclared",
328
+ risk,
329
+ findings,
330
+ 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 },
331
+ manifestDigest: digestOf(manifest),
332
+ note: "structural audit of the record only — it does not execute the server or attest its behaviour",
333
+ boundary: WAVE3_BOUNDARY,
334
+ };
335
+ }
336
+
337
+ const HIDDEN_CHAR_KINDS = Object.freeze([
338
+ [0x00ad, 0x00ad, "soft_hyphen"],
339
+ [0x200b, 0x200f, "zero_width"],
340
+ [0x202a, 0x202e, "bidi_override"],
341
+ [0x2060, 0x2064, "invisible_operator"],
342
+ [0x2066, 0x2069, "bidi_isolate"],
343
+ [0xfeff, 0xfeff, "bom"],
344
+ [0xe0000, 0xe007f, "unicode_tag"],
345
+ ]);
346
+
347
+ const INJECTION_PHRASES = Object.freeze([
348
+ "ignore previous", "ignore all previous", "disregard previous", "disregard all previous",
349
+ "system prompt", "developer mode", "do not tell the user", "don't tell the user",
350
+ "do not mention", "without asking", "without confirmation", "auto-approve", "always approve",
351
+ "bypass", "exfiltrate", "send to", "do not log", "hide from", "secretly", "hidden instruction",
352
+ ]);
353
+
354
+ export function scanToolDescriptions(args = {}) {
355
+ const tools = Array.isArray(args.tools) ? args.tools : [];
356
+ const findings = [];
357
+ tools.forEach((tool, toolIndex) => {
358
+ const name = String(tool?.name ?? `tool-${toolIndex}`);
359
+ const description = String(tool?.description ?? "");
360
+ for (let i = 0; i < description.length; i++) {
361
+ const cp = description.codePointAt(i);
362
+ if (cp > 0xffff) i++; // surrogate pair consumed
363
+ const kind = HIDDEN_CHAR_KINDS.find(([lo, hi]) => cp >= lo && cp <= hi)?.[2];
364
+ if (kind) {
365
+ findings.push({ tool: name, toolIndex, index: i, codepoint: "U+" + cp.toString(16).toUpperCase().padStart(4, "0"), kind, severity: kind === "unicode_tag" || kind === "bidi_override" ? "HIGH" : "MEDIUM" });
366
+ }
367
+ }
368
+ const lower = description.toLowerCase();
369
+ for (const phrase of INJECTION_PHRASES) {
370
+ let at = lower.indexOf(phrase);
371
+ while (at !== -1) {
372
+ findings.push({ tool: name, toolIndex, index: at, phrase, kind: "injection_phrase", severity: "HIGH" });
373
+ at = lower.indexOf(phrase, at + phrase.length);
374
+ }
375
+ }
376
+ const comments = description.match(/<!--[\s\S]*?-->/g);
377
+ if (comments) findings.push({ tool: name, toolIndex, index: description.indexOf(comments[0]), kind: "html_comment", severity: "MEDIUM", count: comments.length });
378
+ });
379
+ const high = findings.filter((f) => f.severity === "HIGH").length;
380
+ const medium = findings.filter((f) => f.severity === "MEDIUM").length;
381
+ return {
382
+ type: "tool_description_scan",
383
+ spec: "CG-TS/1",
384
+ toolsScanned: tools.length,
385
+ verdict: high > 0 ? "DANGEROUS" : medium > 0 ? "SUSPICIOUS" : "CLEAN",
386
+ counts: { findings: findings.length, high, medium },
387
+ findings,
388
+ note: "detectors cover invisible/bidi/tag characters, HTML comments and a fixed imperative-phrase list; absence of findings is not proof of safety",
389
+ boundary: WAVE3_BOUNDARY,
390
+ };
391
+ }
392
+
393
+ const CONFUSABLES = Object.freeze({
394
+ "а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "у": "y", "х": "x", "і": "i", "ј": "j",
395
+ "ѕ": "s", "ԁ": "d", "һ": "h", "ӏ": "l", "ԛ": "q", "ԝ": "w", "ν": "v", "α": "a", "ο": "o",
396
+ "ε": "e", "ι": "i", "κ": "k", "ρ": "p", "τ": "t", "υ": "u", "χ": "x", "0": "o", "1": "l",
397
+ "5": "s", "3": "e", "8": "b", "|": "l", "!": "i",
398
+ });
399
+
400
+ function skeleton(domain) {
401
+ return String(domain ?? "")
402
+ .toLowerCase()
403
+ .trim()
404
+ .replace(/^https?:\/\//, "")
405
+ .replace(/\/.*$/, "")
406
+ .replace(/\.$/, "")
407
+ .replace(/[^a-z0-9.\-\u0080-\uffff]/g, "")
408
+ .split("")
409
+ .map((ch) => CONFUSABLES[ch] ?? ch)
410
+ .join("");
411
+ }
412
+
413
+ function scriptOf(ch) {
414
+ if (/[\u0400-\u04FF]/.test(ch)) return "cyrillic";
415
+ if (/[\u0370-\u03FF]/.test(ch)) return "greek";
416
+ if (/[a-z]/i.test(ch)) return "latin";
417
+ if (/[0-9]/.test(ch)) return "digit";
418
+ return null;
419
+ }
420
+
421
+ function levenshtein(a, b) {
422
+ const m = a.length, n = b.length;
423
+ if (m === 0 || n === 0) return Math.max(m, n);
424
+ let prev = Array.from({ length: n + 1 }, (_, j) => j);
425
+ for (let i = 1; i <= m; i++) {
426
+ const cur = [i];
427
+ 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));
428
+ prev = cur;
429
+ }
430
+ return prev[n];
431
+ }
432
+
433
+ export function checkLookalike(args = {}) {
434
+ const candidate = String(args.candidate ?? "");
435
+ const reference = String(args.reference ?? "");
436
+ const sc = skeleton(candidate);
437
+ const sr = skeleton(reference);
438
+ const distance = levenshtein(sc, sr);
439
+ const scripts = [...new Set(candidate.split("").map(scriptOf).filter((s) => s === "cyrillic" || s === "greek" || s === "latin"))];
440
+ const mixedScript = scripts.length > 1;
441
+ const punycode = /(^|\.)xn--/.test(candidate.toLowerCase());
442
+ const identicalSkeleton = sc === sr && candidate.toLowerCase() !== reference.toLowerCase();
443
+ const threshold = Math.max(sc.length, sr.length) >= 12 ? 2 : 1;
444
+ const lookalike = identicalSkeleton || distance <= threshold;
445
+ return {
446
+ type: "lookalike_check",
447
+ spec: "CG-LK/1",
448
+ candidate,
449
+ reference,
450
+ candidateSkeleton: sc,
451
+ referenceSkeleton: sr,
452
+ distance,
453
+ verdict: candidate.toLowerCase() === reference.toLowerCase() ? "IDENTICAL" : lookalike ? "LOOKALIKE" : "DISTINCT",
454
+ signals: { mixedScript, punycode, mappedCharacters: candidate.split("").filter((ch) => CONFUSABLES[ch]).length, distance },
455
+ note: "a LOOKALIKE verdict is a reason to stop and check by hand; DISTINCT is not an endorsement of the candidate",
456
+ boundary: WAVE3_BOUNDARY,
457
+ };
458
+ }
459
+
460
+ function toolShape(tool) {
461
+ return { name: tool?.name, description: tool?.description, inputSchema: tool?.inputSchema ?? null };
462
+ }
463
+
464
+ function jaccard(a, b) {
465
+ const wa = new Set(String(a).toLowerCase().split(/\W+/).filter(Boolean));
466
+ const wb = new Set(String(b).toLowerCase().split(/\W+/).filter(Boolean));
467
+ if (wa.size === 0 && wb.size === 0) return 1;
468
+ let common = 0;
469
+ for (const w of wa) if (wb.has(w)) common++;
470
+ return common / (wa.size + wb.size - common);
471
+ }
472
+
473
+ export function diffToolSurface(args = {}) {
474
+ const before = Array.isArray(args.before) ? args.before : [];
475
+ const after = Array.isArray(args.after) ? args.after : [];
476
+ const b = new Map(before.map((t) => [String(t?.name), toolShape(t)]));
477
+ const a = new Map(after.map((t) => [String(t?.name), toolShape(t)]));
478
+ const added = [...a.keys()].filter((k) => !b.has(k));
479
+ const removed = [...b.keys()].filter((k) => !a.has(k));
480
+ const changed = [];
481
+ for (const name of [...b.keys()].filter((k) => a.has(k))) {
482
+ const oldT = b.get(name);
483
+ const newT = a.get(name);
484
+ const schemaChanged = digestOf(oldT.inputSchema) !== digestOf(newT.inputSchema);
485
+ const descriptionChanged = oldT.description !== newT.description;
486
+ if (schemaChanged || descriptionChanged) {
487
+ changed.push({
488
+ name,
489
+ schemaChanged,
490
+ descriptionChanged,
491
+ descriptionSimilarity: descriptionChanged ? Number(jaccard(oldT.description, newT.description).toFixed(3)) : 1,
492
+ oldDigest: digestOf(oldT),
493
+ newDigest: digestOf(newT),
494
+ });
495
+ }
496
+ }
497
+ const requiresReconsent = removed.length > 0 || changed.some((c) => c.schemaChanged);
498
+ return {
499
+ type: "tool_surface_diff",
500
+ spec: "CG-SD/1",
501
+ counts: { before: before.length, after: after.length, added: added.length, removed: removed.length, changed: changed.length },
502
+ added: added.map((k) => a.get(k).name),
503
+ removed: removed.map((k) => b.get(k).name),
504
+ changed,
505
+ severity: removed.length > 0 ? "HIGH" : changed.some((c) => c.schemaChanged) ? "HIGH" : changed.length > 0 || added.length > 0 ? "MEDIUM" : "NONE",
506
+ requiresReconsent,
507
+ note: "a surface change after approval is a rug-pull signal; pin the digest you approved and diff on every upgrade",
508
+ boundary: WAVE3_BOUNDARY,
509
+ };
510
+ }
511
+
512
+ export function verifyEvidenceBundle(args = {}) {
513
+ const bundle = isObj(args.bundle) ? args.bundle : {};
514
+ const items = Array.isArray(bundle.items) ? bundle.items : [];
515
+ const expected = str(bundle.digest);
516
+ const computed = digestOf({ spec: bundle.spec ?? "CG-EB/1", items });
517
+ const itemIssues = [];
518
+ items.forEach((item, i) => {
519
+ if (item?.digest && item.digest !== digestOf(item.body ?? item)) itemIssues.push({ index: i, issue: "ITEM_DIGEST_MISMATCH", id: item?.id ?? null });
520
+ });
521
+ const issues = [];
522
+ if (!expected) issues.push("BUNDLE_DIGEST_MISSING");
523
+ else if (expected !== computed) issues.push("BUNDLE_DIGEST_MISMATCH");
524
+ issues.push(...itemIssues.map((x) => x.issue));
525
+ return {
526
+ type: "evidence_bundle_verification",
527
+ spec: "CG-EB/1",
528
+ ok: issues.length === 0,
529
+ verdict: issues.length === 0 ? "VERIFIED" : "INVALID",
530
+ issues,
531
+ counts: { items: items.length, itemIssues: itemIssues.length },
532
+ expectedDigest: expected ?? null,
533
+ computedDigest: computed,
534
+ itemIssues,
535
+ boundary: "checks the bundle against its own digest; it does not attest that the events happened. " + WAVE3_BOUNDARY,
536
+ };
537
+ }
538
+
539
+ // ---------------------------------------------------------------------------
540
+ // Evidence: redaction and Merkle batch attestation
541
+ // ---------------------------------------------------------------------------
542
+
543
+ const SENSITIVE = /(credential|secret|token|password|passwd|private|pan|card|iban|email|phone|signature|api[-_]?key)/i;
544
+
545
+ export function redactReceipt(args = {}) {
546
+ const receipt = isObj(args.receipt) ? args.receipt : {};
547
+ const reveal = new Set(Array.isArray(args.reveal) ? args.reveal.map(String) : []);
548
+ const redactions = [];
549
+ const walk = (value, path) => {
550
+ if (Array.isArray(value)) return value.map((v, i) => walk(v, `${path}[${i}]`));
551
+ if (isObj(value)) {
552
+ const out = {};
553
+ for (const [k, v] of Object.entries(value)) {
554
+ const p = path ? `${path}.${k}` : k;
555
+ if (!reveal.has(p) && !reveal.has(k) && SENSITIVE.test(k) && v !== null && typeof v !== "object") {
556
+ out[k] = "[REDACTED]";
557
+ redactions.push({ path: p, reason: "field name matches the sensitive-data set", originalType: typeof v, originalLength: String(v).length });
558
+ } else if (!reveal.has(p) && !reveal.has(k) && SENSITIVE.test(k) && v && typeof v === "object") {
559
+ out[k] = "[REDACTED]";
560
+ redactions.push({ path: p, reason: "object under a sensitive field name", originalType: "object" });
561
+ } else {
562
+ out[k] = walk(v, p);
563
+ }
564
+ }
565
+ return out;
566
+ }
567
+ return value;
568
+ };
569
+ const redacted = walk(receipt, "");
570
+ return {
571
+ type: "redacted_receipt",
572
+ spec: "CG-RR/1",
573
+ redacted,
574
+ redactions,
575
+ counts: { redactions: redactions.length, fields: Object.keys(receipt).length },
576
+ originalDigest: digestOf(receipt),
577
+ redactedDigest: digestOf(redacted),
578
+ note: "keep originalDigest with the redacted copy: a holder of the original can prove it is the same record without revealing redacted fields",
579
+ boundary: WAVE3_BOUNDARY,
580
+ };
581
+ }
582
+
583
+ function leafHash(item) {
584
+ return "sha256:" + createHash("sha256").update(Buffer.concat([Buffer.from([0]), Buffer.from(canonicalJson(item))])).digest("hex");
585
+ }
586
+
587
+ function nodeHash(left, right) {
588
+ return "sha256:" + createHash("sha256").update(Buffer.concat([Buffer.from([1]), Buffer.from(left), Buffer.from(right)])).digest("hex");
589
+ }
590
+
591
+ function largestPowerOfTwoBelow(n) {
592
+ let k = 1;
593
+ while (k * 2 < n) k *= 2;
594
+ return k;
595
+ }
596
+
597
+ function merkleRoot(leaves) {
598
+ if (leaves.length === 0) return "sha256:" + createHash("sha256").update("").digest("hex");
599
+ if (leaves.length === 1) return leaves[0];
600
+ const k = largestPowerOfTwoBelow(leaves.length);
601
+ return nodeHash(merkleRoot(leaves.slice(0, k)), merkleRoot(leaves.slice(k)));
602
+ }
603
+
604
+ function merkleProof(leaves, index) {
605
+ if (leaves.length <= 1) return [];
606
+ const k = largestPowerOfTwoBelow(leaves.length);
607
+ if (index < k) return [...merkleProof(leaves.slice(0, k), index), { side: "right", hash: merkleRoot(leaves.slice(k)) }];
608
+ return [...merkleProof(leaves.slice(k), index - k), { side: "left", hash: merkleRoot(leaves.slice(0, k)) }];
609
+ }
610
+
611
+ export function attestBatch(args = {}) {
612
+ const receipts = Array.isArray(args.receipts) ? args.receipts : [];
613
+ const leaves = receipts.map((r) => leafHash(r));
614
+ const root = merkleRoot(leaves);
615
+ return {
616
+ type: "batch_attestation",
617
+ spec: "CG-MT/1",
618
+ algorithm: "sha256 Merkle over RFC 6962-style domain-separated nodes (0x00 leaf, 0x01 node)",
619
+ root,
620
+ count: receipts.length,
621
+ leaves: leaves.map((hash, index) => ({ index, hash, receiptDigest: digestOf(receipts[index]) })),
622
+ proofs: leaves.map((_, index) => merkleProof(leaves, index)),
623
+ usage: "publish/notarise only the root; hand each holder their proof so inclusion stays verifiable offline",
624
+ boundary: "the root commits to exactly these caller-supplied records; it does not prove they are true or that they happened. " + WAVE3_BOUNDARY,
625
+ };
626
+ }
627
+
628
+ export function verifyBatchProof(args = {}) {
629
+ const leaf = str(args.leafDigest);
630
+ const root = str(args.root);
631
+ const proof = Array.isArray(args.proof) ? args.proof : [];
632
+ let acc = leaf;
633
+ const steps = [];
634
+ for (const step of proof) {
635
+ if (!step || (step.side !== "left" && step.side !== "right") || typeof step.hash !== "string") {
636
+ return { type: "merkle_proof_verification", spec: "CG-MT/1", ok: false, verdict: "INVALID", issue: "MALFORMED_PROOF_STEP", boundary: WAVE3_BOUNDARY };
637
+ }
638
+ acc = step.side === "left" ? nodeHash(step.hash, acc) : nodeHash(acc, step.hash);
639
+ steps.push({ side: step.side, hash: step.hash });
640
+ }
641
+ const ok = acc === root;
642
+ return {
643
+ type: "merkle_proof_verification",
644
+ spec: "CG-MT/1",
645
+ ok,
646
+ verdict: ok ? "VERIFIED" : "INVALID",
647
+ issue: ok ? null : "ROOT_MISMATCH",
648
+ recomputedRoot: acc,
649
+ root: root ?? null,
650
+ steps,
651
+ boundary: "inclusion in the supplied root only; the root's own trustworthiness is a separate question. " + WAVE3_BOUNDARY,
652
+ };
653
+ }
654
+
655
+ // ---------------------------------------------------------------------------
656
+ // Operations
657
+ // ---------------------------------------------------------------------------
658
+
659
+ export function freezeAgent(args = {}) {
660
+ const storePath = String(args.storePath);
661
+ const agentId = String(args.agentId);
662
+ const reason = str(args.reason) ?? "frozen via MCP";
663
+ const decidedBy = str(args.decidedBy) ?? null;
664
+ const pinned = args.nowSeconds === undefined ? null : Number(args.nowSeconds);
665
+ const cp = createControlPlane({ storePath, create: true, ...(pinned === null ? {} : { now: () => new Date(pinned * 1000) }) });
666
+ const state = cp.getState();
667
+ const open = Object.values(state.approvals ?? {}).filter((a) => a.agentId === agentId && (a.status === "pending" || a.status === "approved"));
668
+ const revoked = cp.revokeAgent(agentId, reason);
669
+ const rejected = open.map((a) => {
670
+ try {
671
+ return cp.decideApproval(a.id, { decision: "rejected", decidedBy: decidedBy ?? "freeze", reason: `agent frozen: ${reason}` });
672
+ } catch (err) {
673
+ return { id: a.id, error: err?.message ?? String(err) };
674
+ }
675
+ });
676
+ const report = cp.auditReport({ limit: 1 });
677
+ return {
678
+ type: "agent_freeze",
679
+ spec: "CG-FZ/1",
680
+ agentId,
681
+ reason,
682
+ revoked,
683
+ approvals: { open: open.length, rejected: rejected.filter((r) => !r.error).length, failures: rejected.filter((r) => r.error).length },
684
+ openApprovalIds: open.map((a) => a.id),
685
+ chain: { ok: report.chain?.ok ?? null, length: report.chain?.length ?? null, headHash: report.chain?.headHash ?? null },
686
+ 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,
687
+ };
688
+ }
689
+
690
+ export function budgetRunway(args = {}) {
691
+ const limit = decimal(args.policyLimitMinor);
692
+ const spent = decimal(args.spentMinor ?? "0");
693
+ const asOf = decimal(args.asOfSeconds);
694
+ const window = decimal(args.windowSeconds ?? "86400");
695
+ if (limit === null || spent === null || asOf === null || window === null || window === 0n) {
696
+ throw new Error("policyLimitMinor, spentMinor, asOfSeconds and windowSeconds must be non-negative integers, windowSeconds non-zero");
697
+ }
698
+ const events = Array.isArray(args.events) ? args.events : [];
699
+ const from = asOf - window;
700
+ const inWindow = events.filter((e) => {
701
+ const at = decimal(e?.atSeconds);
702
+ return at !== null && at > from && at <= asOf;
703
+ });
704
+ const windowSpend = inWindow.reduce((sum, e) => sum + (decimal(e?.amountMinor) ?? 0n), 0n);
705
+ const remaining = limit > spent ? limit - spent : 0n;
706
+ const perSecond = windowSpend === 0n ? 0 : Number(windowSpend) / Number(window);
707
+ const runwaySeconds = perSecond === 0 ? null : Math.floor(Number(remaining) / perSecond);
708
+ return {
709
+ type: "budget_runway",
710
+ spec: "CG-BR/1",
711
+ asOfSeconds: String(asOf),
712
+ windowSeconds: String(window),
713
+ limitMinor: String(limit),
714
+ spentMinor: String(spent),
715
+ remainingMinor: String(remaining),
716
+ windowSpendMinor: String(windowSpend),
717
+ burnPerDayMinor: perSecond === 0 ? "0" : String(BigInt(Math.round(perSecond * 86400))),
718
+ runwaySeconds: runwaySeconds === null ? null : String(runwaySeconds),
719
+ runwayDays: runwaySeconds === null ? null : Number((runwaySeconds / 86400).toFixed(2)),
720
+ exhausted: remaining === 0n,
721
+ exhaustedAtSeconds: runwaySeconds === null ? null : String(asOf + BigInt(runwaySeconds)),
722
+ note: "straight-line projection from the supplied window; no seasonal model, no forecast confidence interval",
723
+ boundary: WAVE3_BOUNDARY,
724
+ };
725
+ }
726
+
727
+ function median(values) {
728
+ if (values.length === 0) return 0;
729
+ const sorted = [...values].sort((x, y) => x - y);
730
+ const mid = Math.floor(sorted.length / 2);
731
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
732
+ }
733
+
734
+ export function detectSpendAnomaly(args = {}) {
735
+ const events = Array.isArray(args.events) ? args.events : [];
736
+ const amounts = events.map((e) => Number(decimal(e?.amountMinor) ?? 0n));
737
+ const med = median(amounts);
738
+ const deviations = amounts.map((x) => Math.abs(x - med));
739
+ const mad = median(deviations);
740
+ const sensitivity = str(args.sensitivity) ?? "medium";
741
+ const threshold = sensitivity === "high" ? 2.5 : sensitivity === "low" ? 3.5 : 3.0;
742
+ const anomalies = [];
743
+ events.forEach((e, i) => {
744
+ const x = amounts[i];
745
+ const denom = mad === 0 ? (deviations.reduce((s, d) => s + d, 0) / Math.max(1, deviations.length) || 1) : mad;
746
+ 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));
747
+ if (score >= threshold) {
748
+ 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" });
749
+ }
750
+ });
751
+ return {
752
+ type: "spend_anomaly_scan",
753
+ spec: "CG-SA/1",
754
+ sensitivity,
755
+ threshold,
756
+ counts: { events: events.length, anomalies: anomalies.length },
757
+ baseline: { medianMinor: String(Math.round(med)), madMinor: String(Math.round(mad)) },
758
+ anomalies: anomalies.sort((a, b) => b.score - a.score),
759
+ note: "median/MAD is robust to a few large outliers; an anomaly is a question, not a finding of fraud",
760
+ boundary: WAVE3_BOUNDARY,
761
+ };
762
+ }
763
+
764
+ export function incidentTimeline(args = {}) {
765
+ let audit = [];
766
+ let chain = null;
767
+ if (isObj(args.report)) {
768
+ audit = Array.isArray(args.report.recentAudit) ? args.report.recentAudit : [];
769
+ chain = args.report.chain ?? null;
770
+ if (!chain && Array.isArray(args.report.audit)) audit = args.report.audit;
771
+ } else if (str(args.storePath)) {
772
+ const cp = createControlPlane({ storePath: String(args.storePath), create: true });
773
+ const state = cp.getState();
774
+ audit = Array.isArray(state.audit) ? state.audit : [];
775
+ chain = verifyAuditChain(state);
776
+ }
777
+ const events = audit
778
+ .map((e) => ({ seq: e?.seq ?? null, type: String(e?.type ?? "unknown"), at: String(e?.at ?? ""), detail: e?.detail ?? null, hash: e?.hash ?? null }))
779
+ .sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
780
+ const gaps = [];
781
+ for (let i = 1; i < events.length; i++) {
782
+ if (typeof events[i].seq === "number" && typeof events[i - 1].seq === "number" && events[i].seq !== events[i - 1].seq + 1) {
783
+ gaps.push({ afterSeq: events[i - 1].seq, beforeSeq: events[i].seq });
784
+ }
785
+ }
786
+ return {
787
+ type: "incident_timeline",
788
+ spec: "CG-IT/1",
789
+ count: events.length,
790
+ events,
791
+ gaps,
792
+ chain: chain ? { ok: chain.ok ?? null, length: chain.length ?? null, headHash: chain.headHash ?? null } : null,
793
+ note: "built from the ledger you supplied; ordering is by the ledger's own sequence number, never by arrival time",
794
+ boundary: WAVE3_BOUNDARY,
795
+ };
796
+ }
797
+
798
+ // ---------------------------------------------------------------------------
799
+ // Interop and meta
800
+ // ---------------------------------------------------------------------------
801
+
802
+ export function translateReceipt(args = {}) {
803
+ const receipt = isObj(args.receipt) ? args.receipt : {};
804
+ const to = String(args.to ?? "acp");
805
+ const amount = str(receipt.amount) ?? str(receipt.total) ?? str(receipt.amountMinor) ?? null;
806
+ const currency = str(receipt.currency) ?? null;
807
+ const merchant = str(receipt.merchant) ?? str(receipt.merchantName) ?? str(receipt.target) ?? null;
808
+ const id = str(receipt.receiptId) ?? str(receipt.id) ?? null;
809
+ const approvedAt = str(receipt.approvedAt) ?? str(receipt.createdAt) ?? null;
810
+ const losses = [];
811
+ let translated;
812
+ if (to === "x402") {
813
+ 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 };
814
+ if (!receipt.network) losses.push("network not present in the source receipt");
815
+ if (!receipt.asset) losses.push("asset inferred from currency; x402 expects a token/asset id");
816
+ } else if (to === "acp") {
817
+ translated = { type: "acp.checkout_receipt", id, merchant, total: amount === null ? null : { amount, currency }, approvedAt, sourceDigest: digestOf(receipt) };
818
+ if (!approvedAt) losses.push("approval timestamp not present");
819
+ if (!merchant) losses.push("merchant not present");
820
+ } else if (to === "cgcr") {
821
+ 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" };
822
+ losses.push("translation cannot reproduce commitments the source did not carry");
823
+ } else {
824
+ throw new Error("to must be \"acp\", \"x402\" or \"cgcr\"");
825
+ }
826
+ return {
827
+ type: "receipt_translation",
828
+ to,
829
+ translated,
830
+ losses,
831
+ sourceDigest: digestOf(receipt),
832
+ lossless: losses.length === 0,
833
+ note: "structural mapping only — nothing is signed, verified or settled by this tool",
834
+ boundary: WAVE3_BOUNDARY,
835
+ };
836
+ }
837
+
838
+ export function emitTestVectors(args = {}) {
839
+ const policy = isObj(args.policy) ? args.policy : {};
840
+ const base = isObj(args.baseIntent) ? args.baseIntent : {};
841
+ const nowSeconds = args.nowSeconds === undefined ? "1794657600" : String(args.nowSeconds);
842
+ const amount = decimal(base.amount) ?? 0n;
843
+ const recipient = str(base.recipient) ?? "0x" + "11".repeat(20);
844
+ const vectors = [
845
+ { id: "allow-baseline", intent: { ...base }, expected: "ALLOW", why: "the approved baseline" },
846
+ { id: "deny-amount-drift", intent: { ...base, amount: String(amount + 1n) }, expected: "DENY", why: "one minor unit above the approved amount" },
847
+ { id: "deny-recipient-swap", intent: { ...base, recipient: "0x" + "ff".repeat(20) }, expected: "DENY", why: "recipient not on the allowlist" },
848
+ { id: "deny-expired-window", intent: { ...base, validUntil: String(BigInt(nowSeconds) - 1n) }, expected: "DENY", why: "approval window already closed" },
849
+ { 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" },
850
+ ].map((v) => ({ ...v, policyDigest: digestOf(policy), expectedBy: "the same rule engine coreguard_explain_decision uses" }));
851
+ return {
852
+ type: "integration_test_vectors",
853
+ spec: "CG-TV/1",
854
+ count: vectors.length,
855
+ vectors,
856
+ runWith: "coreguard_explain_decision({ policy, intent, nowSeconds }) — compare verdict to expected",
857
+ boundary: WAVE3_BOUNDARY,
858
+ };
859
+ }
860
+
861
+ export function describeSurface(args = {}, ctx = {}) {
862
+ const format = String(args.format ?? "card");
863
+ const names = Array.isArray(ctx.toolNames) ? ctx.toolNames : [];
864
+ const families = names.reduce((acc, n) => {
865
+ const key = n.replace(/^coreguard_/, "");
866
+ acc.total += 1;
867
+ return acc;
868
+ }, { total: 0 });
869
+ const card = {
870
+ type: "capability_card",
871
+ spec: "CG-CC/1",
872
+ server: ctx.serverName ?? "coreguard-agent-commerce",
873
+ version: ctx.version ?? null,
874
+ protocolVersion: ctx.protocolVersion ?? null,
875
+ transport: "stdio (newline-delimited JSON-RPC 2.0)",
876
+ tools: families.total,
877
+ 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"],
878
+ specs: ["CGCR/1", "AGR/1", "CGCP/1", "CGXA/1", "CG-OBS/1", "CG-W3/1"],
879
+ boundary: WAVE3_BOUNDARY,
880
+ key: "offline · deterministic · zero keys · no custody · no broadcast · VERIFIED ≠ SAFE",
881
+ };
882
+ if (format === "badge") {
883
+ return { type: "capability_badge", spec: "CG-CC/1", badge: `coreguard-agent-commerce ${card.version ?? ""} · ${card.tools} tools · offline · deterministic`, card, boundary: WAVE3_BOUNDARY };
884
+ }
885
+ return { ...card, boundary: WAVE3_BOUNDARY };
886
+ }
887
+
888
+ // ---------------------------------------------------------------------------
889
+ // Schemas and handlers (one registry the MCP server spreads in)
890
+ // ---------------------------------------------------------------------------
891
+
892
+ const ctxProp = {
893
+ callerContext: { type: "object", description: "Optional caller-provided trace/context metadata. Echoed back; never a cryptographic input." },
894
+ };
895
+
896
+ const schema = (properties, required, description) => ({
897
+ type: "object",
898
+ description,
899
+ properties: { ...properties, ...ctxProp },
900
+ required,
901
+ additionalProperties: true,
902
+ });
903
+
904
+ const out = (description) => ({ type: "object", description, additionalProperties: true });
905
+
906
+ export const WAVE3_TOOLS = Object.freeze([
907
+ {
908
+ name: "coreguard_compile_policy",
909
+ 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.",
910
+ inputSchema: schema({ spec: { type: "object", description: "policyId, name, maxAmountMinor (decimal string), allowMerchants[], allowRecipients[], allowSelectors[], currency" } }, ["spec"], "Compact policy spec to compile."),
911
+ outputSchema: out("Canonical CGEP/1 policy plus its digest and rule summary."),
912
+ },
913
+ {
914
+ name: "coreguard_explain_decision",
915
+ 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.",
916
+ 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."),
917
+ outputSchema: out("Verdict, per-rule checks and a counterfactual."),
918
+ },
919
+ {
920
+ name: "coreguard_simulate_spend",
921
+ 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.",
922
+ 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."),
923
+ outputSchema: out("Per-intent verdicts and aggregate totals, marked dryRun."),
924
+ },
925
+ {
926
+ name: "coreguard_diff_policies",
927
+ 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.",
928
+ inputSchema: schema({ before: { type: "object" }, after: { type: "object" } }, ["before", "after"], "The two policies to compare."),
929
+ outputSchema: out("Rule-level diff with strictness and reconsent flags."),
930
+ },
931
+ {
932
+ name: "coreguard_generate_boundary_cases",
933
+ 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.",
934
+ inputSchema: schema({ policy: { type: "object" }, baseIntent: { type: "object" }, nowSeconds: { type: "string", pattern: "^[0-9]+$" } }, ["policy", "baseIntent", "nowSeconds"], "Policy and a representative intent."),
935
+ outputSchema: out("Boundary cases with expected verdicts computed by the server."),
936
+ },
937
+ {
938
+ name: "coreguard_audit_server_manifest",
939
+ 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.",
940
+ inputSchema: schema({ manifest: { type: "object", description: "the server.json record as published" } }, ["manifest"], "The MCP server manifest to audit."),
941
+ outputSchema: out("Risk level, findings with severities and the manifest digest."),
942
+ },
943
+ {
944
+ name: "coreguard_scan_tool_descriptions",
945
+ 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.",
946
+ inputSchema: schema({ tools: { type: "array", items: { type: "object" }, description: "tools from tools/list: name + description" } }, ["tools"], "Tool metadata to scan."),
947
+ outputSchema: out("CLEAN/SUSPICIOUS/DANGEROUS verdict with byte-level findings."),
948
+ },
949
+ {
950
+ name: "coreguard_check_lookalike",
951
+ 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.",
952
+ inputSchema: schema({ candidate: { type: "string" }, reference: { type: "string" } }, ["candidate", "reference"], "Candidate string and the reference it claims to be."),
953
+ outputSchema: out("IDENTICAL/LOOKALIKE/DISTINCT verdict with the signals behind it."),
954
+ },
955
+ {
956
+ name: "coreguard_diff_tool_surface",
957
+ 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.",
958
+ inputSchema: schema({ before: { type: "array", items: { type: "object" } }, after: { type: "array", items: { type: "object" } } }, ["before", "after"], "The two tool surfaces."),
959
+ outputSchema: out("Surface diff with severity and requiresReconsent."),
960
+ },
961
+ {
962
+ name: "coreguard_verify_evidence_bundle",
963
+ 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.",
964
+ inputSchema: schema({ bundle: { type: "object", description: "{ spec, digest, items:[{id, body, digest}] }" } }, ["bundle"], "The bundle to verify."),
965
+ outputSchema: out("VERIFIED/INVALID with the computed digest and item issues."),
966
+ },
967
+ {
968
+ name: "coreguard_redact_receipt",
969
+ 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.",
970
+ inputSchema: schema({ receipt: { type: "object" }, reveal: { type: "array", items: { type: "string" }, description: "field names or dotted paths to keep visible" } }, ["receipt"], "Receipt to redact."),
971
+ outputSchema: out("Redacted copy, redaction manifest and both digests."),
972
+ },
973
+ {
974
+ name: "coreguard_attest_batch",
975
+ 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.",
976
+ inputSchema: schema({ receipts: { type: "array", items: { type: "object" } } }, ["receipts"], "Receipts to batch."),
977
+ outputSchema: out("Merkle root, leaf digests and inclusion proofs."),
978
+ },
979
+ {
980
+ name: "coreguard_verify_batch_proof",
981
+ 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.",
982
+ 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."),
983
+ outputSchema: out("VERIFIED or INVALID with the recomputed root, the issue code and the proof steps used."),
984
+ },
985
+ {
986
+ name: "coreguard_freeze_agent",
987
+ description: "Kill switch over a CGCP/1 control plane: revoke the agent and reject every open approval it holds in one audited operation, returning the chain head and the rejected approval ids.",
988
+ 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."),
989
+ outputSchema: out("Revocation record, rejected approvals and chain status."),
990
+ },
991
+ {
992
+ name: "coreguard_budget_runway",
993
+ 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.",
994
+ 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."),
995
+ outputSchema: out("Remaining budget, burn rate, runway and exhaustion epoch."),
996
+ },
997
+ {
998
+ name: "coreguard_detect_spend_anomaly",
999
+ 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.",
1000
+ inputSchema: schema({ events: { type: "array", items: { type: "object", description: "{ id, amountMinor, atSeconds }" } }, sensitivity: { type: "string", enum: ["low", "medium", "high"] } }, ["events"], "Spend events to scan."),
1001
+ outputSchema: out("Baseline, anomaly list and the score threshold used."),
1002
+ },
1003
+ {
1004
+ name: "coreguard_incident_timeline",
1005
+ 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.",
1006
+ inputSchema: schema({ report: { type: "object" }, storePath: { type: "string" } }, ["report"], "An audit report, or a storePath when no report is supplied."),
1007
+ outputSchema: out("Sequence-ordered events, detected sequence gaps and audit-chain status."),
1008
+ },
1009
+ {
1010
+ name: "coreguard_translate_receipt",
1011
+ 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.",
1012
+ inputSchema: schema({ receipt: { type: "object" }, to: { type: "string", enum: ["acp", "x402", "cgcr"] } }, ["receipt", "to"], "Receipt and target shape."),
1013
+ outputSchema: out("Translated object, loss list and source digest."),
1014
+ },
1015
+ {
1016
+ name: "coreguard_emit_test_vectors",
1017
+ 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.",
1018
+ inputSchema: schema({ policy: { type: "object" }, baseIntent: { type: "object" }, nowSeconds: { type: "string", pattern: "^[0-9]+$" } }, ["policy", "baseIntent"], "Policy and baseline intent."),
1019
+ outputSchema: out("Vectors with expected verdicts and how to run them."),
1020
+ },
1021
+ {
1022
+ name: "coreguard_describe_surface",
1023
+ 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.",
1024
+ inputSchema: schema({ format: { type: "string", enum: ["card", "badge"] } }, ["format"], "card or badge."),
1025
+ outputSchema: out("Capability card with the server's own boundary."),
1026
+ },
1027
+ ]);
1028
+
1029
+ function reqString(args, key) {
1030
+ const v = args?.[key];
1031
+ if (typeof v !== "string" || v.length === 0) throw new Error(`${key} is required`);
1032
+ return v;
1033
+ }
1034
+ function reqObject(args, key) {
1035
+ if (!isObj(args?.[key])) throw new Error(`${key} must be a JSON object`);
1036
+ return args[key];
1037
+ }
1038
+ function reqArray(args, key) {
1039
+ if (!Array.isArray(args?.[key])) throw new Error(`${key} must be an array`);
1040
+ return args[key];
1041
+ }
1042
+
1043
+ export const WAVE3_HANDLERS = Object.freeze({
1044
+ coreguard_compile_policy: (a) => compilePolicy(a),
1045
+ coreguard_explain_decision: (a) => explainDecision(a),
1046
+ coreguard_simulate_spend: (a) => simulateSpend(a),
1047
+ coreguard_diff_policies: (a) => diffPolicies(a),
1048
+ coreguard_generate_boundary_cases: (a) => generateBoundaryCases(a),
1049
+ coreguard_audit_server_manifest: (a) => auditServerManifest(a),
1050
+ coreguard_scan_tool_descriptions: (a) => scanToolDescriptions(a),
1051
+ coreguard_check_lookalike: (a) => { reqString(a, "candidate"); reqString(a, "reference"); return checkLookalike(a); },
1052
+ coreguard_diff_tool_surface: (a) => diffToolSurface(a),
1053
+ coreguard_verify_evidence_bundle: (a) => verifyEvidenceBundle(a),
1054
+ coreguard_redact_receipt: (a) => redactReceipt(a),
1055
+ coreguard_attest_batch: (a) => attestBatch(a),
1056
+ 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); },
1057
+ coreguard_freeze_agent: (a) => freezeAgent(a),
1058
+ coreguard_budget_runway: (a) => budgetRunway(a),
1059
+ coreguard_detect_spend_anomaly: (a) => detectSpendAnomaly(a),
1060
+ coreguard_incident_timeline: (a) => { if (!isObj(a?.report)) reqString(a, "storePath"); return incidentTimeline(a); }, /** report wins; storePath is the stateless fallback */
1061
+ coreguard_translate_receipt: (a) => { reqObject(a, "receipt"); reqString(a, "to"); return translateReceipt(a); },
1062
+ coreguard_emit_test_vectors: (a) => emitTestVectors(a),
1063
+ coreguard_describe_surface: (a, ctx) => { reqString(a, "format"); return describeSurface(a, ctx); },
1064
+ });
1065
+
1066
+ export const WAVE3_VALIDATORS = Object.freeze({
1067
+ coreguard_compile_policy: (a) => (isObj(a.spec) ? null : { code: "MISSING_ARGUMENT", detail: "spec is required and must be an object" }),
1068
+ coreguard_explain_decision: (a) => (isObj(a.policy) && isObj(a.intent) ? null : { code: "MISSING_ARGUMENT", detail: "policy and intent are required objects" }),
1069
+ coreguard_simulate_spend: (a) => (isObj(a.policy) && Array.isArray(a.intents) ? null : { code: "MISSING_ARGUMENT", detail: "policy (object) and intents (array) are required" }),
1070
+ coreguard_diff_policies: (a) => (isObj(a.before) && isObj(a.after) ? null : { code: "MISSING_ARGUMENT", detail: "before and after are required objects" }),
1071
+ coreguard_generate_boundary_cases: (a) => (isObj(a.policy) && isObj(a.baseIntent) ? null : { code: "MISSING_ARGUMENT", detail: "policy and baseIntent are required objects" }),
1072
+ coreguard_audit_server_manifest: (a) => (isObj(a.manifest) ? null : { code: "MISSING_ARGUMENT", detail: "manifest is required and must be an object" }),
1073
+ coreguard_scan_tool_descriptions: (a) => (Array.isArray(a.tools) ? null : { code: "MISSING_ARGUMENT", detail: "tools is required and must be an array" }),
1074
+ coreguard_check_lookalike: (a) => (typeof a.candidate === "string" && typeof a.reference === "string" ? null : { code: "MISSING_ARGUMENT", detail: "candidate and reference are required strings" }),
1075
+ coreguard_diff_tool_surface: (a) => (Array.isArray(a.before) && Array.isArray(a.after) ? null : { code: "MISSING_ARGUMENT", detail: "before and after are required arrays" }),
1076
+ coreguard_verify_evidence_bundle: (a) => (isObj(a.bundle) ? null : { code: "MISSING_ARGUMENT", detail: "bundle is required and must be an object" }),
1077
+ coreguard_redact_receipt: (a) => (isObj(a.receipt) ? null : { code: "MISSING_ARGUMENT", detail: "receipt is required and must be an object" }),
1078
+ coreguard_attest_batch: (a) => (Array.isArray(a.receipts) ? null : { code: "MISSING_ARGUMENT", detail: "receipts is required and must be an array" }),
1079
+ 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" }),
1080
+ coreguard_freeze_agent: (a) => (typeof a.storePath === "string" && typeof a.agentId === "string" ? null : { code: "MISSING_ARGUMENT", detail: "storePath and agentId are required strings" }),
1081
+ 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" }),
1082
+ coreguard_detect_spend_anomaly: (a) => (Array.isArray(a.events) ? null : { code: "MISSING_ARGUMENT", detail: "events is required and must be an array" }),
1083
+ coreguard_incident_timeline: (a) => (typeof a.storePath === "string" || isObj(a.report) ? null : { code: "MISSING_ARGUMENT", detail: "storePath (or report) is required" }),
1084
+ 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" }),
1085
+ coreguard_emit_test_vectors: (a) => (isObj(a.policy) && isObj(a.baseIntent) ? null : { code: "MISSING_ARGUMENT", detail: "policy and baseIntent are required objects" }),
1086
+ coreguard_describe_surface: (a) => (a.format === "card" || a.format === "badge" ? null : { code: "MISSING_ARGUMENT", detail: "format must be card or badge" }),
1087
+ });