@intentrax/sdk 1.3.0 → 1.7.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
@@ -9,7 +9,8 @@ npm install @intentrax/sdk
9
9
  The package is public on npm (Apache-2.0). Everything below that says
10
10
  "offline" or "local" runs today with no API key: `init --dry-run`,
11
11
  `check-init`, `verify-proof` (sandbox sample proofs, including tampered ones,
12
- are bundled at `examples/sandbox/`), and `verify-pdf-receipt`. Live execution
12
+ are bundled at `examples/sandbox/`), `verify-pdf-receipt`, and `sandbox` (the
13
+ local assurance sandbox below). Live execution
13
14
  keys and your sandbox base URL are issued after an architectural review at
14
15
  <https://www.intentrax.com/request-architectural-review>.
15
16
 
@@ -31,10 +32,45 @@ Public surfaces:
31
32
  and signer pinning against published key sets
32
33
  - `intentrax verify-pdf-receipt <receipt.pdf>` for local downloaded PDF receipt
33
34
  byte/hash verification
35
+ - `intentrax sandbox` for the local assurance sandbox: a signed decision, an
36
+ executor report, an independent read-only outcome check (`--check` runs your
37
+ own) and offline verification with ephemeral local keys, no account and no
38
+ network. Verdicts are capped at `LOCAL_NON_TRUST_BEARING`: never production
39
+ assurance. See [sandbox/README.md](sandbox/README.md) for the limitations.
34
40
 
35
41
  The published package exports Node-runnable `.js` modules with `.d.ts` type
36
42
  declarations and is gated on Node 20 and Node 24.
37
43
 
44
+ ## Local assurance sandbox (no key, no network)
45
+
46
+ `intentrax sandbox` runs one consequential action through the whole flow,
47
+ in-process: a signed decision before execution, an executor report (a
48
+ self-report), an independent read-only check of the outcome, a sealed bundle,
49
+ and offline verification (eight per-dimension assessments and the verdict rule).
50
+
51
+ ```bash
52
+ npx @intentrax/sdk sandbox # sample action; outcome confirmed
53
+ npx @intentrax/sdk sandbox --scenario contradicted # ALLOW + "SUCCEEDED", but the read disagrees
54
+ npx @intentrax/sdk sandbox --check ./my-check.mjs # a read-only check of YOUR system
55
+ ```
56
+
57
+ What it is not:
58
+ - **Not production assurance.** Every signature is made by an ephemeral key
59
+ generated on your machine (`environment: "local"`, `trust_bearing: false`,
60
+ written under the gitignored `.intentrax/local/`). The best possible verdict
61
+ is `LOCAL_NON_TRUST_BEARING`, never `VERIFIED_FOR_SCOPE`, whatever key set
62
+ you pin. A contradiction is still reported as `CONFLICTING_EVIDENCE`.
63
+ - **Not a production proof.** The bundle uses the preview effect-assurance
64
+ format. `verify-proof`, hosted verify and the Verification Mark reject it.
65
+ - **Your check is yours.** A `--check` read is labelled `SELF_REPORTED`, not an
66
+ Intentrax-pulled authoritative read. It runs in a worker thread, is
67
+ read-only by contract only, and is the only code in a run that could touch
68
+ a network.
69
+ - It never reads, derives or requests a production or published sandbox key.
70
+
71
+ Limitations, exit codes and the `verify` options (`--keys`, `--issuer-keys`,
72
+ `--require-external-issuer`): [sandbox/README.md](sandbox/README.md).
73
+
38
74
  One-command adapter onboarding:
39
75
 
40
76
  ```bash
@@ -160,11 +196,92 @@ production key set is bundled, so you don't need any flags. Pass extra key sets
160
196
  | `REVOKED_SIGNER`, `MIXED_TRUST` | 3 | Not a trusted result |
161
197
  | (none) | 2 | An integrity, signature, or binding check failed (failed closed) |
162
198
 
199
+ Policy binding (SDK 1.5.0). A proof issued under the AEP 1.1 policy-binding
200
+ profile carries `policy_binding` inside its signed AEP. The binding names the
201
+ hash-pinned policy the engine evaluated (`source_policy_hash`,
202
+ `compiled_policy_hash`), the evaluation (`evaluation_hash`,
203
+ `execution_event_hash`, `decision`, `rule_id`) and, when one exists, a
204
+ `mandate_hash`. It also lists every constraint of the matched rule with an
205
+ explicit `status`: `NOT_EVALUATED` (not checked, no evidence) or `SATISFIED`
206
+ (with the `evidence_hash` of a real approval artifact). Today every constraint
207
+ is `NOT_EVALUATED`. `verify-proof` copies the binding into the report as
208
+ `policy_binding`, and states it in words as `policy_binding_statement`. For
209
+ example, an execute proof reads "evaluated COMPLIANT … Constraint
210
+ constraint.operator-review (REQUIRE_APPROVAL): NOT CHECKED (NOT_EVALUATED)",
211
+ meaning allowed, approval not checked. Proofs without a binding verify exactly
212
+ as before, and their report has neither key. A binding fails closed (exit 2),
213
+ even when its signatures are genuine, if it is malformed, claims anything other
214
+ than `enforcement: "RECORD_ONLY"`, has `SATISFIED` without evidence or
215
+ `NOT_EVALUATED` with evidence, or has an unknown constraint status.
216
+ `RECORD_ONLY` means the decision was recorded when the proof was issued. It
217
+ does not mean the decision was enforced.
218
+
219
+ Re-checking the decision (SDK 1.6.0). A binding also seals the facts the policy evaluated
220
+ (`evaluated_facts`: `lane` and `mutation_performed`). `verify-proof` re-derives
221
+ the decision instead of trusting it:
222
+
223
+ 1. It rebuilds the evaluated event from those facts, and requires the lane to
224
+ match the one the signed proof itself names.
225
+ 2. It resolves the policy by its `source_policy_hash`: first a
226
+ `--policy-document <file>` (as served by
227
+ `GET https://api.intentrax.com/v1/policies/{source_policy_hash}`), then the
228
+ published registry bundled in `trust/policies/`.
229
+ 3. It re-runs the policy engine. The SDK carries a full port of it
230
+ (`reevaluatePolicy`, `compilePolicyDocument`, `evaluateCompiledPolicy`),
231
+ checked against vectors generated by the Go engine.
232
+
233
+ The report carries `policy_reevaluation`: `MATCH` (with `policy_source`) or
234
+ `NOT_RECHECKED` (with a `reason`). A re-run that does not reproduce every
235
+ sealed value fails closed (exit 2), even under genuine signatures. A `MATCH`
236
+ proves the decision follows from the sealed facts and the published rule. It
237
+ does not independently witness that the facts are true; the runtime's
238
+ signature attests to them.
239
+
163
240
  A passing verification shows the record is unaltered since signing, genuinely
164
241
  signed, and bound to its own AEP. It does not show that the described action was
165
242
  carried out or had its intended effect. The verifier also rejects private key
166
243
  material markers. It does not require the runtime server, network access, or
167
244
  private keys.
245
+
246
+ Since 1.4.0 the report also carries `verification_assessment`, printed as a
247
+ table. It states what the proof establishes and what it does not:
248
+
249
+ - `assurance_profile`: every proof issued today is `LEGACY_DECISION_RECORD`,
250
+ which requires only `RECORD_INTEGRITY`.
251
+ - `assessments[]`: one row per dimension (`RECORD_INTEGRITY`,
252
+ `SIGNER_AUTHENTICITY`, `AUTHORIZATION`, `EXECUTION_REPORTED`,
253
+ `EXECUTION_ATTESTED`, `EFFECT_OBSERVED`, `EFFECT_CONFIRMED`, `CAUSAL_CHAIN`)
254
+ with `result`, `provenance`, `reasons` and `limitations`. `SIGNER_AUTHENTICITY`
255
+ is `VERIFIED` only when the status is `PASS`; every dimension after it is
256
+ `NOT_ASSESSED` for a legacy proof.
257
+ - `verdict`: derived from the rows by a fixed rule, never asserted by a signer.
258
+ `VERIFIED_FOR_SCOPE` (record intact, trusted signers; the scope is the
259
+ required dimensions only), `INTEGRITY_ONLY` (signer not established),
260
+ `CONFLICTING_EVIDENCE` (since 1.7.0: any dimension is `CONTRADICTED`, required
261
+ or not, for example a sealed `NON_COMPLIANT` policy decision on a trusted
262
+ proof) or `VERIFICATION_FAILED` (for example a revoked signer).
263
+ - `limitations[]`: machine-readable codes with text. A legacy proof always lists
264
+ `EXECUTION_NOT_ATTESTED`, `EFFECT_NOT_VERIFIED`, `POLICY_BINDING_SYNTHETIC` and
265
+ `COMPLETENESS_NOT_ESTABLISHED`, plus `SIGNER_AUTHENTICITY_REQUIRES_PINNED_ANCHORS`
266
+ when the signer is not established.
267
+ - When the proof seals an AEP 1.1 `policy_binding` (RECORD_ONLY), only a
268
+ re-evaluation `MATCH` can lift `AUTHORIZATION` above `REPORTED`.
269
+ - A re-checked `COMPLIANT` decision whose matched rule has no unchecked
270
+ constraint is `VERIFIED` (provenance `VERIFIER_COMPUTED`), with
271
+ `POLICY_EVENT_SELF_REPORTED` and `POLICY_DECISION_NOT_ENFORCED`.
272
+ - With a `NOT_EVALUATED` constraint it stays `REPORTED`.
273
+ - When the decision was not re-checked, `COMPLIANT` is `REPORTED`
274
+ (provenance `INTENTRAX_DECISION`), with `POLICY_EVALUATION_NOT_RECHECKABLE`.
275
+ - `NON_COMPLIANT` is `CONTRADICTED` and `ERROR` is `INSUFFICIENT_EVIDENCE`
276
+ either way.
277
+ - `POLICY_CONSTRAINT_NOT_EVALUATED` is added when a constraint was not
278
+ checked. The verdict does not change.
279
+
280
+ The block is additive: `status`, `signer_trust` and the exit code are unchanged.
281
+ The model is exported (`deriveAssuranceVerdict`, `buildLegacyVerificationAssessment`,
282
+ `ASSURANCE_PROFILES`, ...) and matches the Go offline verifier's
283
+ `verification_assessment`.
284
+
168
285
  The JSON proof export remains authoritative. Downloaded PDF receipts are
169
286
  human-readable companions and should be checked against their exported hash
170
287
  metadata, not treated as replacement proof material.
@@ -260,3 +377,23 @@ strictly (exactly `content_hash`, `hash_algorithm`, `normalization`), and its
260
377
  `content_hash` must be 64 lowercase hex, optionally `sha256:`-prefixed. `/1.0`
261
378
  requests are unchanged. The execute lane is fail-closed per tenant (HTTP 423
262
379
  until live execution is enabled, HTTP 403 until the tenant is allowlisted).
380
+
381
+ Correlating an admission with the execution that follows it:
382
+
383
+ ```js
384
+ import { executeIdempotencyKeyHash } from "@intentrax/sdk";
385
+
386
+ // One raw key K per logical action. Execute sends K itself; the admission
387
+ // sends only its SHA-256 (no domain prefix). The engine links the execution
388
+ // under SHA-256(K), so the two correlate.
389
+ const key = "refund-8812-v1";
390
+ const admission = { /* ...agent admission fields... */ idempotency_key_hash: executeIdempotencyKeyHash(key) };
391
+ const execute = { /* ...execute fields... */ idempotency_key: key };
392
+ ```
393
+
394
+ Hooks generated by `intentrax agent init` admit under
395
+ `executeIdempotencyKeyHash(agentHookExecuteIdempotencyKey(request_payload_hash))`
396
+ and return that raw key as `execute_idempotency_key` in the hook result: send it
397
+ unchanged as the execute `idempotency_key`. The engine also uses these links for
398
+ durable idempotency: once a key has executed one request, a different request
399
+ under the same key is refused with HTTP 409, even after a runtime restart.
package/cli/intentrax.mjs CHANGED
@@ -3,9 +3,9 @@ import { createHash, createPublicKey, verify as verifySignatureBytes } from "nod
3
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
- import { buildAgentGatewayAdmissionEnvelope } from "../index.js";
6
+ import { buildAgentGatewayAdmissionEnvelope, buildLegacyVerificationAssessment, compilePolicyDocument, evaluateCompiledPolicy, policyReevaluationMismatches } from "../index.js";
7
7
 
8
- const VERSION = "1.3.0";
8
+ const VERSION = "1.7.0";
9
9
  const ADMISSION_SCHEMA_VERSION = "intentrax.runtime.agent_admission_request/1.0";
10
10
  const INIT_SCHEMA_VERSION = "intentrax.onboarding.agent_adapter_init/1.0";
11
11
  const ACTION_RECEIPT_SCHEMA_VERSION = "intentrax.onboarding.agent_adapter_action_receipt/1.0";
@@ -34,6 +34,11 @@ const BUILT_IN_KEY_SET_URLS = Object.freeze([
34
34
  // Published sandbox keys (not trust-bearing).
35
35
  new URL("../trust/sandbox-key-set.json", import.meta.url),
36
36
  ]);
37
+ // The published policy registry bundled with the SDK: byte-identical copies of
38
+ // engine/internal/policyengine/published/policies/<source_policy_hash>.json,
39
+ // the documents GET /v1/policies/{source_policy_hash} serves. Used to re-run a
40
+ // sealed policy evaluation offline.
41
+ const BUILT_IN_POLICY_REGISTRY_URL = new URL("../trust/policies/", import.meta.url);
37
42
  const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
38
43
  const SIGNER_TRUST_EXIT_CODE = 3;
39
44
  const LOCAL_PDF_RECEIPT_VERIFICATION_SCHEMA_VERSION = "intentrax.sdk.local_pdf_receipt_verification_report/1.0";
@@ -244,6 +249,12 @@ async function main(argv) {
244
249
  console.log(VERSION);
245
250
  return 0;
246
251
  }
252
+ if (command === "sandbox") {
253
+ // Local assurance sandbox: ephemeral local keys, no network, verdict capped at
254
+ // LOCAL_NON_TRUST_BEARING. Never production assurance. See sandbox/README.md.
255
+ const { sandboxMain } = await import("../sandbox/cli.mjs");
256
+ return sandboxMain([subject, ...rest].filter((value) => value !== undefined));
257
+ }
247
258
  if (command === "check-init") {
248
259
  const options = parseCheckInitOptions([subject, ...rest].filter((value) => value !== undefined));
249
260
  const output = await checkInitCommand(options);
@@ -267,6 +278,9 @@ async function main(argv) {
267
278
  } else if (output.status === "SANDBOX_NON_TRUST_BEARING") {
268
279
  console.log(`Intentrax proof export verification: SANDBOX — not trust-bearing. Integrity and ed25519 signatures check out, and the signers are published sandbox keys. This shows the verification mechanics, not production assurance. proof=${output.registry_entry_id} report=${output.report_path}`);
269
280
  }
281
+ if (!options.json) {
282
+ console.log(assessmentTable(output.verification_assessment));
283
+ }
270
284
  if (exitCode !== 0) {
271
285
  console.error(signerTrustMessage(output));
272
286
  }
@@ -318,6 +332,7 @@ async function main(argv) {
318
332
  console.log("Note: the default base URL http://127.0.0.1:8080 targets a locally run Intentrax engine; the hosted engine base URL is https://api.intentrax.com (override with --base-url or INTENTRAX_BASE_URL).");
319
333
  console.log("INTENTRAX_API_KEY and your sandbox base URL are issued after an architectural review: https://www.intentrax.com/request-architectural-review");
320
334
  console.log("Offline check that works right now with no key: npx @intentrax/sdk check-init");
335
+ console.log("See the whole assurance flow locally, no key or network (not production assurance): npx @intentrax/sdk sandbox");
321
336
  return 0;
322
337
  }
323
338
 
@@ -1068,6 +1083,7 @@ function parseVerifyProofOptions(args) {
1068
1083
  json: false,
1069
1084
  reportOut: ".intentrax/offline-proof-verification.report.json",
1070
1085
  trustedKeys: [],
1086
+ policyDocuments: [],
1071
1087
  };
1072
1088
  for (let index = 0; index < args.length; index += 1) {
1073
1089
  const arg = args[index];
@@ -1077,6 +1093,8 @@ function parseVerifyProofOptions(args) {
1077
1093
  options.reportOut = requireValue(args, ++index, arg);
1078
1094
  } else if (arg === "--trusted-keys") {
1079
1095
  options.trustedKeys.push(requireValue(args, ++index, arg));
1096
+ } else if (arg === "--policy-document") {
1097
+ options.policyDocuments.push(requireValue(args, ++index, arg));
1080
1098
  } else {
1081
1099
  fail(`unknown option: ${arg}`);
1082
1100
  }
@@ -1116,7 +1134,8 @@ function verifyProofExportCommand(proofExportPath, options) {
1116
1134
  }
1117
1135
  const proofExport = parseSingleJSON(source, "proof export");
1118
1136
  const keySets = loadPublishedKeySets(options.trustedKeys);
1119
- const report = buildLocalProofVerificationReport(proofExport, resolvedProofExportPath, resolve(options.reportOut), keySets);
1137
+ const policyDocuments = options.policyDocuments.map((path) => readFileSync(resolve(path), "utf8"));
1138
+ const report = buildLocalProofVerificationReport(proofExport, resolvedProofExportPath, resolve(options.reportOut), keySets, policyDocuments);
1120
1139
  const reportData = JSON.stringify(report, null, 2) + "\n";
1121
1140
  mkdirSync(dirname(resolve(options.reportOut)), { recursive: true });
1122
1141
  writeFileSync(resolve(options.reportOut), reportData, { mode: 0o600 });
@@ -1184,7 +1203,7 @@ function buildLocalPDFReceiptVerificationReport(bytes, pdfPath, reportPath, expe
1184
1203
  });
1185
1204
  }
1186
1205
 
1187
- function buildLocalProofVerificationReport(proofExport, proofExportPath, reportPath, keySets) {
1206
+ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportPath, keySets, policyDocuments = []) {
1188
1207
  const invalid = validateProofLookupExport(proofExport);
1189
1208
  if (invalid.length > 0) {
1190
1209
  fail(`proof export verification failed closed: ${invalid.join(",")}`);
@@ -1195,6 +1214,15 @@ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportP
1195
1214
  if (signatures.invalid.length > 0) {
1196
1215
  fail(`proof export verification failed closed: ${signatures.invalid.join(",")}`);
1197
1216
  }
1217
+ // The signed AEP bytes are verified above; a policy binding sealed in them
1218
+ // (aep.policy_binding, AEP 1.1 policy-binding profile) must be well formed
1219
+ // and is reported as sealed. Absence is never a failure.
1220
+ const policyBinding = sealedPolicyBinding(record.canonical_aep_json);
1221
+ if (policyBinding.invalid.length > 0) {
1222
+ fail(`proof export verification failed closed: ${policyBinding.invalid.join(",")}`);
1223
+ }
1224
+ // Re-run the sealed evaluation (P1-C step 2); a disagreement fails closed.
1225
+ const policyReevaluation = reevaluateSealedPolicyBinding(record.canonical_aep_json, policyBinding.binding, policyDocuments);
1198
1226
  const trust = classifySignerTrust(signatures.signers, keySets);
1199
1227
  const withoutHash = {
1200
1228
  schema_version: LOCAL_PROOF_VERIFICATION_SCHEMA_VERSION,
@@ -1227,6 +1255,21 @@ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportP
1227
1255
  proof_record_hash: record.record_hash,
1228
1256
  proof_lookup_hash: proofExport.result_hash,
1229
1257
  verification_bundle_hash: bundle.bundle_hash,
1258
+ // Present only when the signed AEP seals one: RECORD_ONLY means the
1259
+ // policy evaluation was recorded, never that it was enforced.
1260
+ // policy_binding_statement says the same in words (shared wording with
1261
+ // the Go verifier and the public verify page): every constraint's status
1262
+ // is spelled out, so an unchecked approval reads NOT CHECKED.
1263
+ ...(policyBinding.binding === null
1264
+ ? {}
1265
+ : {
1266
+ policy_binding: policyBinding.binding,
1267
+ policy_binding_statement: policyBindingStatement(policyBinding.binding),
1268
+ // MATCH when the sealed evaluation was re-run and came out identical;
1269
+ // NOT_RECHECKED (with a reason) when it could not be re-run. Never
1270
+ // silently passes: a re-run that disagrees fails verification.
1271
+ policy_reevaluation: policyReevaluation,
1272
+ }),
1230
1273
  hash_algorithm: "SHA-256",
1231
1274
  boundary_assertions: {
1232
1275
  offline_verifier_used: true,
@@ -1245,6 +1288,11 @@ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportP
1245
1288
  canonical_json_authoritative: true,
1246
1289
  pdf_receipt_non_authoritative: true,
1247
1290
  },
1291
+ // Additive: what this proof establishes and what it does not (assurance
1292
+ // profile, per-dimension results, verdict by the fixed rule,
1293
+ // machine-readable limitations). status, signer_trust and the exit code
1294
+ // are unchanged. Covered by report_hash.
1295
+ verification_assessment: buildLegacyVerificationAssessment({ signerTrust: trust.signer_trust, keySetSupplied: keySets.length > 0, policyBinding: policyBinding.binding, policyReevaluation }),
1248
1296
  report_hash: "",
1249
1297
  };
1250
1298
  return Object.freeze({
@@ -1253,6 +1301,223 @@ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportP
1253
1301
  });
1254
1302
  }
1255
1303
 
1304
+ // Policy re-evaluation (P1-C step 2). Mirrors the Go offline verifier
1305
+ // (engine/internal/verificationinfra/offlineproof/policy_reevaluation.go):
1306
+ // rebuild the evaluated event from the signed AEP, resolve the policy document
1307
+ // by its source policy hash (a --policy-document first, then the bundled
1308
+ // published registry), re-run it with the TS port of the policy engine and
1309
+ // require every sealed value to come out identical.
1310
+ // The runtime lane the signed AEP itself names (execution_id prefix and
1311
+ // policy.policy_id together), or "" when it names none.
1312
+ function signedRuntimeLane(canonicalAEPJSON) {
1313
+ let aep;
1314
+ try {
1315
+ aep = JSON.parse(canonicalAEPJSON);
1316
+ } catch {
1317
+ return "";
1318
+ }
1319
+ const executionID = isRecord(aep) && typeof aep.execution_id === "string" ? aep.execution_id : "";
1320
+ const policyID = isRecord(aep) && isRecord(aep.policy) && typeof aep.policy.policy_id === "string" ? aep.policy.policy_id : "";
1321
+ const marker = RUNTIME_LANE_MARKERS.find((entry) => executionID.startsWith(entry.executionIDPrefix) && policyID === entry.policyID);
1322
+ return marker === undefined ? "" : marker.lane;
1323
+ }
1324
+
1325
+ // Rebuilds the evaluated event from policy_binding.evaluated_facts, or null
1326
+ // for a binding sealed before step 2. The sealed lane must be the lane the
1327
+ // signed AEP itself names; otherwise verification fails closed.
1328
+ function reconstructPolicyEvent(canonicalAEPJSON, binding) {
1329
+ const facts = binding.evaluated_facts;
1330
+ if (facts === undefined) return null;
1331
+ const lane = signedRuntimeLane(canonicalAEPJSON);
1332
+ if (lane !== facts.lane) {
1333
+ fail(`proof export verification failed closed: policy re-evaluation: policy_binding.evaluated_facts.lane "${facts.lane}" does not match the signed proof's lane "${lane}"`);
1334
+ }
1335
+ return {
1336
+ event: { eeo: { execution_domain: { lane: facts.lane, mutation_performed: facts.mutation_performed } } },
1337
+ allowedEventFields: [...RUNTIME_POLICY_EVENT_FIELDS],
1338
+ };
1339
+ }
1340
+
1341
+ function resolvePolicyDocument(sourcePolicyHash, allowedEventFields, policyDocuments) {
1342
+ const compile = (document) => {
1343
+ try {
1344
+ const compiled = compilePolicyDocument(document, allowedEventFields);
1345
+ return compiled.source_policy_hash === sourcePolicyHash ? compiled : null;
1346
+ } catch {
1347
+ return null;
1348
+ }
1349
+ };
1350
+ for (const document of policyDocuments) {
1351
+ const compiled = compile(document);
1352
+ if (compiled !== null) return { compiled, source: "SUPPLIED_DOCUMENT" };
1353
+ }
1354
+ if (/^[a-f0-9]{64}$/.test(sourcePolicyHash)) {
1355
+ const url = new URL(`${sourcePolicyHash}.json`, BUILT_IN_POLICY_REGISTRY_URL);
1356
+ if (existsSync(url)) {
1357
+ const compiled = compile(readFileSync(url, "utf8"));
1358
+ if (compiled !== null) return { compiled, source: "PUBLISHED_REGISTRY" };
1359
+ }
1360
+ }
1361
+ return null;
1362
+ }
1363
+
1364
+ function reevaluateSealedPolicyBinding(canonicalAEPJSON, binding, policyDocuments) {
1365
+ if (binding === null) return null;
1366
+ const event = reconstructPolicyEvent(canonicalAEPJSON, binding);
1367
+ if (event === null) return { status: "NOT_RECHECKED", reason: "EVENT_NOT_RECONSTRUCTIBLE" };
1368
+ const resolved = resolvePolicyDocument(binding.source_policy_hash, event.allowedEventFields, policyDocuments);
1369
+ if (resolved === null) return { status: "NOT_RECHECKED", reason: "POLICY_SOURCE_UNAVAILABLE" };
1370
+ let recomputed;
1371
+ try {
1372
+ recomputed = evaluateCompiledPolicy(resolved.compiled, event.event);
1373
+ } catch (error) {
1374
+ fail(`proof export verification failed closed: policy re-evaluation failed: ${error.message}`);
1375
+ }
1376
+ const mismatches = policyReevaluationMismatches(binding, recomputed);
1377
+ if (mismatches.length > 0) {
1378
+ fail(`proof export verification failed closed: policy re-evaluation mismatch: ${mismatches.join(",")}`);
1379
+ }
1380
+ return { status: "MATCH", policy_source: resolved.source };
1381
+ }
1382
+
1383
+ // AEP 1.1 policy-binding profile (aep.policy_binding): the RECORD_ONLY
1384
+ // evaluation of a hash-pinned policy, sealed inside the signed AEP. Mirrors
1385
+ // the Go verifier (engine/internal/registrylayer/persistence/policy_binding.go):
1386
+ // absent => no binding and no failure; present => exactly these members, all
1387
+ // strings except constraints (mandate_hash optional), the supported
1388
+ // profile/algorithm/enforcement, a policy VM decision, 64-hex non-degenerate
1389
+ // hashes, and a constraints array whose entries carry an explicit status
1390
+ // (SATISFIED requires evidence_hash, NOT_EVALUATED forbids it, ids unique and
1391
+ // ascending); anything else fails closed. It never means the decision was
1392
+ // enforced.
1393
+ const POLICY_BINDING_PROFILE = "intentrax.aep.policy_binding/1.1";
1394
+ const POLICY_BINDING_OPTIONAL_MEMBERS = Object.freeze(["evaluated_facts", "mandate_hash"]);
1395
+ const POLICY_EVALUATED_LANES = new Set(["DRY_RUN", "LIVE_EXECUTE"]);
1396
+ // The runtime execution-event profile (engine recheck.RuntimeEventFields /
1397
+ // RuntimeExecutionEvent) and the lane markers the signed AEP itself carries
1398
+ // (engine proofproduction DryRunLane / LiveExecuteLane).
1399
+ const RUNTIME_POLICY_EVENT_FIELDS = Object.freeze(["eeo.execution_domain.lane", "eeo.execution_domain.mutation_performed"]);
1400
+ const RUNTIME_LANE_MARKERS = Object.freeze([
1401
+ Object.freeze({ lane: "DRY_RUN", executionIDPrefix: "runtime-dry-run-", policyID: "intentrax.runtime.private_alpha.dry_run" }),
1402
+ Object.freeze({ lane: "LIVE_EXECUTE", executionIDPrefix: "runtime-execute-", policyID: "intentrax.runtime.private_alpha.live_execute" }),
1403
+ ]);
1404
+ const POLICY_BINDING_REQUIRED_MEMBERS = Object.freeze([
1405
+ "binding_profile", "compiled_policy_hash", "constraints", "decision", "enforcement", "evaluation_hash",
1406
+ "execution_event_hash", "hash_algorithm", "policy_id", "policy_version", "rule_id", "source_policy_hash",
1407
+ ]);
1408
+ const POLICY_CONSTRAINT_MEMBERS = Object.freeze(["constraint_id", "status", "type"]);
1409
+ const POLICY_CONSTRAINT_SATISFIED = "SATISFIED";
1410
+ const POLICY_CONSTRAINT_NOT_EVALUATED = "NOT_EVALUATED";
1411
+ const POLICY_BINDING_HASH_MEMBERS = Object.freeze(["compiled_policy_hash", "evaluation_hash", "execution_event_hash", "source_policy_hash"]);
1412
+ const POLICY_BINDING_DECISIONS = new Set(["COMPLIANT", "NON_COMPLIANT", "ERROR"]);
1413
+
1414
+ function isPolicyBindingHash(value) {
1415
+ return isSHA256(value) && !/^(.)\1{63}$/.test(value);
1416
+ }
1417
+
1418
+ function sealedPolicyBinding(canonicalAEPJSON) {
1419
+ let aep;
1420
+ try {
1421
+ aep = JSON.parse(canonicalAEPJSON);
1422
+ } catch {
1423
+ return { binding: null, invalid: [] };
1424
+ }
1425
+ if (!isRecord(aep) || !Object.hasOwn(aep, "policy_binding")) return { binding: null, invalid: [] };
1426
+ const binding = aep.policy_binding;
1427
+ if (!isRecord(binding)) return { binding: null, invalid: ["policy_binding"] };
1428
+ const members = Object.keys(binding).sort();
1429
+ const expected = [...POLICY_BINDING_REQUIRED_MEMBERS, ...POLICY_BINDING_OPTIONAL_MEMBERS.filter((member) => Object.hasOwn(binding, member))].sort();
1430
+ if (members.length !== expected.length || members.some((member, index) => member !== expected[index])) {
1431
+ return { binding: null, invalid: ["policy_binding.members"] };
1432
+ }
1433
+ const invalid = [];
1434
+ for (const member of members) {
1435
+ if (member !== "constraints" && member !== "evaluated_facts" && typeof binding[member] !== "string") invalid.push(`policy_binding.${member}`);
1436
+ }
1437
+ if (invalid.length > 0) return { binding: null, invalid };
1438
+ // evaluated_facts (P1-C step 2): exactly a string lane and a boolean
1439
+ // mutation_performed. Optional: bindings sealed before step 2 omit it.
1440
+ let evaluatedFacts;
1441
+ if (Object.hasOwn(binding, "evaluated_facts")) {
1442
+ const facts = binding.evaluated_facts;
1443
+ const factMembers = isRecord(facts) ? Object.keys(facts).sort() : [];
1444
+ if (!isRecord(facts) || factMembers.length !== 2 || factMembers[0] !== "lane" || factMembers[1] !== "mutation_performed"
1445
+ || typeof facts.lane !== "string" || typeof facts.mutation_performed !== "boolean") {
1446
+ return { binding: null, invalid: ["policy_binding.evaluated_facts"] };
1447
+ }
1448
+ if (!POLICY_EVALUATED_LANES.has(facts.lane)) invalid.push("policy_binding.evaluated_facts.lane");
1449
+ evaluatedFacts = Object.freeze({ lane: facts.lane, mutation_performed: facts.mutation_performed });
1450
+ }
1451
+ const constraints = sealedPolicyConstraints(binding.constraints);
1452
+ if (constraints.malformed.length > 0) return { binding: null, invalid: constraints.malformed };
1453
+ invalid.push(...constraints.invalid);
1454
+ if (binding.binding_profile !== POLICY_BINDING_PROFILE) invalid.push("policy_binding.binding_profile");
1455
+ if (!POLICY_BINDING_DECISIONS.has(binding.decision)) invalid.push("policy_binding.decision");
1456
+ if (binding.enforcement !== "RECORD_ONLY") invalid.push("policy_binding.enforcement");
1457
+ if (binding.hash_algorithm !== "SHA-256") invalid.push("policy_binding.hash_algorithm");
1458
+ const hashMembers = Object.hasOwn(binding, "mandate_hash") ? [...POLICY_BINDING_HASH_MEMBERS, "mandate_hash"] : POLICY_BINDING_HASH_MEMBERS;
1459
+ for (const member of hashMembers) {
1460
+ if (!isPolicyBindingHash(binding[member])) invalid.push(`policy_binding.${member}`);
1461
+ }
1462
+ for (const member of ["policy_id", "policy_version", "rule_id"]) {
1463
+ if (binding[member] === "") invalid.push(`policy_binding.${member}`);
1464
+ }
1465
+ if (invalid.length > 0) return { binding: null, invalid: invalid.sort() };
1466
+ const normalized = {};
1467
+ for (const member of members) normalized[member] = member === "constraints" ? constraints.list : member === "evaluated_facts" ? evaluatedFacts : binding[member];
1468
+ return { binding: Object.freeze(normalized), invalid: [] };
1469
+ }
1470
+
1471
+ function sealedPolicyConstraints(value) {
1472
+ if (!Array.isArray(value)) return { list: [], malformed: ["policy_binding.constraints"], invalid: [] };
1473
+ const list = [];
1474
+ const invalid = [];
1475
+ for (const [index, constraint] of value.entries()) {
1476
+ const at = `policy_binding.constraints[${index}]`;
1477
+ if (!isRecord(constraint)) return { list: [], malformed: [at], invalid: [] };
1478
+ const members = Object.keys(constraint).sort();
1479
+ const expected = Object.hasOwn(constraint, "evidence_hash")
1480
+ ? [...POLICY_CONSTRAINT_MEMBERS, "evidence_hash"].sort()
1481
+ : [...POLICY_CONSTRAINT_MEMBERS];
1482
+ if (members.length !== expected.length || members.some((member, i) => member !== expected[i])) {
1483
+ return { list: [], malformed: [`${at}.members`], invalid: [] };
1484
+ }
1485
+ for (const member of members) {
1486
+ if (typeof constraint[member] !== "string") return { list: [], malformed: [`${at}.${member}`], invalid: [] };
1487
+ }
1488
+ if (constraint.constraint_id === "" || (index > 0 && constraint.constraint_id <= value[index - 1].constraint_id)) {
1489
+ invalid.push(`${at}.constraint_id`);
1490
+ }
1491
+ if (constraint.type === "") invalid.push(`${at}.type`);
1492
+ if (constraint.status === POLICY_CONSTRAINT_SATISFIED) {
1493
+ if (!isPolicyBindingHash(constraint.evidence_hash)) invalid.push(`${at}.evidence_hash`);
1494
+ } else if (constraint.status === POLICY_CONSTRAINT_NOT_EVALUATED) {
1495
+ if (Object.hasOwn(constraint, "evidence_hash")) invalid.push(`${at}.evidence_hash`);
1496
+ } else {
1497
+ invalid.push(`${at}.status`);
1498
+ }
1499
+ const normalized = {};
1500
+ for (const member of members) normalized[member] = constraint[member];
1501
+ list.push(Object.freeze(normalized));
1502
+ }
1503
+ return { list: Object.freeze(list), malformed: [], invalid };
1504
+ }
1505
+
1506
+ // The shared verifier wording for a verified policy binding (identical to
1507
+ // PolicyBindingStatement in the Go verifier and the public verify facade).
1508
+ function policyBindingStatement(binding) {
1509
+ const head = `Policy ${binding.policy_id}@${binding.policy_version} evaluated ${binding.decision} (rule ${binding.rule_id}); recorded only, never enforced.`;
1510
+ if (binding.constraints.length === 0) return `${head} The matched rule has no constraints.`;
1511
+ return [head, ...binding.constraints.map(policyConstraintStatement)].join(" ");
1512
+ }
1513
+
1514
+ function policyConstraintStatement(constraint) {
1515
+ if (constraint.status === POLICY_CONSTRAINT_SATISFIED) {
1516
+ return `Constraint ${constraint.constraint_id} (${constraint.type}): SATISFIED; evidence ${constraint.evidence_hash} is bound by this proof.`;
1517
+ }
1518
+ return `Constraint ${constraint.constraint_id} (${constraint.type}): NOT CHECKED (NOT_EVALUATED); this proof binds no evidence that it was met.`;
1519
+ }
1520
+
1256
1521
  // Verifies what the record's integrity hashes cannot: that the signatures are
1257
1522
  // genuine ed25519 signatures over the signed payload, that enough of them are
1258
1523
  // present, and that the signed payload carries this record's own AEP. Without
@@ -1508,6 +1773,22 @@ function classifySignerTrust(signers, keySets) {
1508
1773
  return { signer_trust: signerTrust, signers: resolved, min_trusted_signers: minTrustedSigners, distinct_trusted_signers: distinctTrustedSigners };
1509
1774
  }
1510
1775
 
1776
+ // Short human table of the verification_assessment block: dimension, result,
1777
+ // provenance, limitations.
1778
+ function assessmentTable(assessment) {
1779
+ const rows = [["DIMENSION", "RESULT", "PROVENANCE", "LIMITATIONS"]];
1780
+ for (const row of assessment.assessments) {
1781
+ rows.push([row.dimension, row.result, row.provenance ?? "-", row.limitations.length > 0 ? row.limitations.join(",") : "-"]);
1782
+ }
1783
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
1784
+ const lines = [`assurance: profile=${assessment.assurance_profile} verdict=${assessment.verdict} required=${assessment.required_dimensions.join(",")}`];
1785
+ for (const row of rows) {
1786
+ lines.push((" " + row.map((cell, column) => (column === row.length - 1 ? cell : cell.padEnd(widths[column] + 2))).join("")).trimEnd());
1787
+ }
1788
+ lines.push(`limitations: ${assessment.limitations.map((limitation) => limitation.code).join(", ")}`);
1789
+ return lines.join("\n");
1790
+ }
1791
+
1511
1792
  function signerTrustMessage(report) {
1512
1793
  if (report.signer_trust === "UNPINNED_SIGNER") {
1513
1794
  return "intentrax: signatures are mathematically valid, but at least one signing key is not in any trusted key set, so this proof does NOT establish who signed it. Pass the key set Intentrax publishes with --trusted-keys <file>.";
@@ -2258,6 +2539,11 @@ async function buildNativeHookResult(event = {}, options = {}) {
2258
2539
  admission_request,
2259
2540
  admission_response,
2260
2541
  original_event_ref: stableNativeHookEventRef(event),
2542
+ // Send this exact value as idempotency_key on /v1/intents/execute. The
2543
+ // engine links the execution under SHA-256(idempotency_key), which equals
2544
+ // admission_request.idempotency_key_hash, so the execution correlates with
2545
+ // this admission instead of reading as unadmitted.
2546
+ execute_idempotency_key: hookExecuteIdempotencyKey(admission_request.request_payload_hash),
2261
2547
  submitted: submit,
2262
2548
  mutation_performed: false,
2263
2549
  tool_execution_performed: false,
@@ -2266,6 +2552,12 @@ async function buildNativeHookResult(event = {}, options = {}) {
2266
2552
  });
2267
2553
  }
2268
2554
 
2555
+ // The raw execute idempotency key for an admission (same rule as the SDK's
2556
+ // agentHookExecuteIdempotencyKey). The admission carries only its SHA-256.
2557
+ function hookExecuteIdempotencyKey(requestPayloadHash) {
2558
+ return "INTENTRAX_AGENT_HOOK_IDEMPOTENCY_V1" + requestPayloadHash;
2559
+ }
2560
+
2269
2561
  async function buildNativeAdmissionForHook(event = {}) {
2270
2562
  const sample = JSON.parse(await readFile(SAMPLE_ADMISSION_REQUEST_URL, "utf8"));
2271
2563
  const requestPayloadHash = sha256Hex(canonicalJson({
@@ -2277,7 +2569,7 @@ async function buildNativeAdmissionForHook(event = {}) {
2277
2569
  ...sample,
2278
2570
  request_payload_hash: requestPayloadHash,
2279
2571
  protocol_payload_ref: \`sha256:\${requestPayloadHash}\`,
2280
- idempotency_key_hash: sha256Hex("INTENTRAX_AGENT_HOOK_IDEMPOTENCY_V1" + requestPayloadHash),
2572
+ idempotency_key_hash: sha256Hex(hookExecuteIdempotencyKey(requestPayloadHash)),
2281
2573
  });
2282
2574
  }
2283
2575
 
@@ -2704,8 +2996,10 @@ function printHelp() {
2704
2996
  Usage:
2705
2997
  intentrax init <adapter> [--dry-run] [--force] [--json] [--output-dir <dir>] [--base-url <url>] [--tenant-id <tenant>]
2706
2998
  intentrax check-init --output-dir <dir> [--json]
2707
- intentrax verify-proof <proof-export.json> [--trusted-keys <key-set.json>] [--json] [--report-out <file>]
2999
+ intentrax verify-proof <proof-export.json> [--trusted-keys <key-set.json>] [--policy-document <policy.json>] [--json] [--report-out <file>]
2708
3000
  intentrax verify-pdf-receipt <receipt.pdf> --pdf-hash <X-Intentrax-PDF-Hash> [--json] [--report-out <file>]
3001
+ intentrax sandbox [--scenario confirmed|contradicted] [--check <read-only-check.mjs>] [--dir <dir>] [--json]
3002
+ intentrax sandbox verify <bundle.json> [--keys <local-key-set.json>] [--issuer-keys <pinned-external-issuers.json>] [--require-external-issuer <issuer>]... [--json]
2709
3003
 
2710
3004
  Adapters:
2711
3005
  ${Object.keys(ADAPTERS).join(", ")}
@@ -2743,6 +3037,27 @@ Proof export verification:
2743
3037
  REVOKED_SIGNER / MIXED_TRUST 3
2744
3038
  any integrity or signature failure exits 2 (failed closed)
2745
3039
 
3040
+ A proof that seals a policy binding (AEP 1.1) also gets policy_reevaluation:
3041
+ verify-proof rebuilds the evaluated event from the signed proof, resolves the
3042
+ policy by its source_policy_hash (--policy-document, as served by
3043
+ GET /v1/policies/{source_policy_hash}, or the published registry bundled in
3044
+ trust/policies), re-runs the policy engine and requires every sealed value
3045
+ to come out identical. MATCH or NOT_RECHECKED (with a reason); a re-run that
3046
+ disagrees fails closed (exit 2).
3047
+
3048
+ The report also carries verification_assessment, printed as a table: the
3049
+ assurance profile (every proof issued today is LEGACY_DECISION_RECORD,
3050
+ which requires only RECORD_INTEGRITY), a result per dimension, a verdict
3051
+ derived by a fixed rule, and machine-readable limitations. Verdicts:
3052
+ VERIFIED_FOR_SCOPE record intact and signed by published trusted keys;
3053
+ the scope is the profile's required dimensions only
3054
+ INTEGRITY_ONLY record intact, signer not established
3055
+ VERIFICATION_FAILED a dimension failed (for example a REVOKED signer)
3056
+ A legacy proof never claims execution, effect or policy evaluation:
3057
+ EXECUTION_NOT_ATTESTED, EFFECT_NOT_VERIFIED, POLICY_BINDING_SYNTHETIC and
3058
+ COMPLETENESS_NOT_ESTABLISHED are always listed. The exit code does not
3059
+ depend on the assessment.
3060
+
2746
3061
  The SDK ships the production key set (trust/production-key-set.json,
2747
3062
  min_trusted_signers 2) and the sandbox key set (trust/sandbox-key-set.json).
2748
3063
  Add more sets, for example revocations, with --trusted-keys <file>
@@ -2768,6 +3083,9 @@ Examples:
2768
3083
  intentrax verify-proof node_modules/@intentrax/sdk/examples/sandbox/tampered-aep-swap.json
2769
3084
  intentrax verify-proof proof-export.json --trusted-keys intentrax-production-keys.json
2770
3085
  intentrax verify-pdf-receipt .intentrax/proof-001-aep-receipt.pdf --pdf-hash <X-Intentrax-PDF-Hash>
3086
+ intentrax sandbox
3087
+ intentrax sandbox --scenario contradicted
3088
+ intentrax sandbox --check ./my-check.mjs
2771
3089
  `);
2772
3090
  }
2773
3091