@intentrax/sdk 1.3.0 → 1.6.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
@@ -160,11 +160,90 @@ production key set is bundled, so you don't need any flags. Pass extra key sets
160
160
  | `REVOKED_SIGNER`, `MIXED_TRUST` | 3 | Not a trusted result |
161
161
  | (none) | 2 | An integrity, signature, or binding check failed (failed closed) |
162
162
 
163
+ Policy binding (SDK 1.5.0). A proof issued under the AEP 1.1 policy-binding
164
+ profile carries `policy_binding` inside its signed AEP. The binding names the
165
+ hash-pinned policy the engine evaluated (`source_policy_hash`,
166
+ `compiled_policy_hash`), the evaluation (`evaluation_hash`,
167
+ `execution_event_hash`, `decision`, `rule_id`) and, when one exists, a
168
+ `mandate_hash`. It also lists every constraint of the matched rule with an
169
+ explicit `status`: `NOT_EVALUATED` (not checked, no evidence) or `SATISFIED`
170
+ (with the `evidence_hash` of a real approval artifact). Today every constraint
171
+ is `NOT_EVALUATED`. `verify-proof` copies the binding into the report as
172
+ `policy_binding`, and states it in words as `policy_binding_statement`. For
173
+ example, an execute proof reads "evaluated COMPLIANT … Constraint
174
+ constraint.operator-review (REQUIRE_APPROVAL): NOT CHECKED (NOT_EVALUATED)",
175
+ meaning allowed, approval not checked. Proofs without a binding verify exactly
176
+ as before, and their report has neither key. A binding fails closed (exit 2),
177
+ even when its signatures are genuine, if it is malformed, claims anything other
178
+ than `enforcement: "RECORD_ONLY"`, has `SATISFIED` without evidence or
179
+ `NOT_EVALUATED` with evidence, or has an unknown constraint status.
180
+ `RECORD_ONLY` means the decision was recorded when the proof was issued. It
181
+ does not mean the decision was enforced.
182
+
183
+ Re-checking the decision (SDK 1.6.0). A binding also seals the facts the policy evaluated
184
+ (`evaluated_facts`: `lane` and `mutation_performed`). `verify-proof` re-derives
185
+ the decision instead of trusting it:
186
+
187
+ 1. It rebuilds the evaluated event from those facts, and requires the lane to
188
+ match the one the signed proof itself names.
189
+ 2. It resolves the policy by its `source_policy_hash`: first a
190
+ `--policy-document <file>` (as served by
191
+ `GET https://api.intentrax.com/v1/policies/{source_policy_hash}`), then the
192
+ published registry bundled in `trust/policies/`.
193
+ 3. It re-runs the policy engine. The SDK carries a full port of it
194
+ (`reevaluatePolicy`, `compilePolicyDocument`, `evaluateCompiledPolicy`),
195
+ checked against vectors generated by the Go engine.
196
+
197
+ The report carries `policy_reevaluation`: `MATCH` (with `policy_source`) or
198
+ `NOT_RECHECKED` (with a `reason`). A re-run that does not reproduce every
199
+ sealed value fails closed (exit 2), even under genuine signatures. A `MATCH`
200
+ proves the decision follows from the sealed facts and the published rule. It
201
+ does not independently witness that the facts are true; the runtime's
202
+ signature attests to them.
203
+
163
204
  A passing verification shows the record is unaltered since signing, genuinely
164
205
  signed, and bound to its own AEP. It does not show that the described action was
165
206
  carried out or had its intended effect. The verifier also rejects private key
166
207
  material markers. It does not require the runtime server, network access, or
167
208
  private keys.
209
+
210
+ Since 1.4.0 the report also carries `verification_assessment`, printed as a
211
+ table. It states what the proof establishes and what it does not:
212
+
213
+ - `assurance_profile`: every proof issued today is `LEGACY_DECISION_RECORD`,
214
+ which requires only `RECORD_INTEGRITY`.
215
+ - `assessments[]`: one row per dimension (`RECORD_INTEGRITY`,
216
+ `SIGNER_AUTHENTICITY`, `AUTHORIZATION`, `EXECUTION_REPORTED`,
217
+ `EXECUTION_ATTESTED`, `EFFECT_OBSERVED`, `EFFECT_CONFIRMED`, `CAUSAL_CHAIN`)
218
+ with `result`, `provenance`, `reasons` and `limitations`. `SIGNER_AUTHENTICITY`
219
+ is `VERIFIED` only when the status is `PASS`; every dimension after it is
220
+ `NOT_ASSESSED` for a legacy proof.
221
+ - `verdict`: derived from the rows by a fixed rule, never asserted by a signer.
222
+ `VERIFIED_FOR_SCOPE` (record intact, trusted signers; the scope is the
223
+ required dimensions only), `INTEGRITY_ONLY` (signer not established) or
224
+ `VERIFICATION_FAILED` (for example a revoked signer).
225
+ - `limitations[]`: machine-readable codes with text. A legacy proof always lists
226
+ `EXECUTION_NOT_ATTESTED`, `EFFECT_NOT_VERIFIED`, `POLICY_BINDING_SYNTHETIC` and
227
+ `COMPLETENESS_NOT_ESTABLISHED`, plus `SIGNER_AUTHENTICITY_REQUIRES_PINNED_ANCHORS`
228
+ when the signer is not established.
229
+ - When the proof seals an AEP 1.1 `policy_binding` (RECORD_ONLY), only a
230
+ re-evaluation `MATCH` can lift `AUTHORIZATION` above `REPORTED`.
231
+ - A re-checked `COMPLIANT` decision whose matched rule has no unchecked
232
+ constraint is `VERIFIED` (provenance `VERIFIER_COMPUTED`), with
233
+ `POLICY_EVENT_SELF_REPORTED` and `POLICY_DECISION_NOT_ENFORCED`.
234
+ - With a `NOT_EVALUATED` constraint it stays `REPORTED`.
235
+ - When the decision was not re-checked, `COMPLIANT` is `REPORTED`
236
+ (provenance `INTENTRAX_DECISION`), with `POLICY_EVALUATION_NOT_RECHECKABLE`.
237
+ - `NON_COMPLIANT` is `CONTRADICTED` and `ERROR` is `INSUFFICIENT_EVIDENCE`
238
+ either way.
239
+ - `POLICY_CONSTRAINT_NOT_EVALUATED` is added when a constraint was not
240
+ checked. The verdict does not change.
241
+
242
+ The block is additive: `status`, `signer_trust` and the exit code are unchanged.
243
+ The model is exported (`deriveAssuranceVerdict`, `buildLegacyVerificationAssessment`,
244
+ `ASSURANCE_PROFILES`, ...) and matches the Go offline verifier's
245
+ `verification_assessment`.
246
+
168
247
  The JSON proof export remains authoritative. Downloaded PDF receipts are
169
248
  human-readable companions and should be checked against their exported hash
170
249
  metadata, not treated as replacement proof material.
@@ -260,3 +339,23 @@ strictly (exactly `content_hash`, `hash_algorithm`, `normalization`), and its
260
339
  `content_hash` must be 64 lowercase hex, optionally `sha256:`-prefixed. `/1.0`
261
340
  requests are unchanged. The execute lane is fail-closed per tenant (HTTP 423
262
341
  until live execution is enabled, HTTP 403 until the tenant is allowlisted).
342
+
343
+ Correlating an admission with the execution that follows it:
344
+
345
+ ```js
346
+ import { executeIdempotencyKeyHash } from "@intentrax/sdk";
347
+
348
+ // One raw key K per logical action. Execute sends K itself; the admission
349
+ // sends only its SHA-256 (no domain prefix). The engine links the execution
350
+ // under SHA-256(K), so the two correlate.
351
+ const key = "refund-8812-v1";
352
+ const admission = { /* ...agent admission fields... */ idempotency_key_hash: executeIdempotencyKeyHash(key) };
353
+ const execute = { /* ...execute fields... */ idempotency_key: key };
354
+ ```
355
+
356
+ Hooks generated by `intentrax agent init` admit under
357
+ `executeIdempotencyKeyHash(agentHookExecuteIdempotencyKey(request_payload_hash))`
358
+ and return that raw key as `execute_idempotency_key` in the hook result: send it
359
+ unchanged as the execute `idempotency_key`. The engine also uses these links for
360
+ durable idempotency: once a key has executed one request, a different request
361
+ 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.6.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";
@@ -267,6 +272,9 @@ async function main(argv) {
267
272
  } else if (output.status === "SANDBOX_NON_TRUST_BEARING") {
268
273
  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
274
  }
275
+ if (!options.json) {
276
+ console.log(assessmentTable(output.verification_assessment));
277
+ }
270
278
  if (exitCode !== 0) {
271
279
  console.error(signerTrustMessage(output));
272
280
  }
@@ -1068,6 +1076,7 @@ function parseVerifyProofOptions(args) {
1068
1076
  json: false,
1069
1077
  reportOut: ".intentrax/offline-proof-verification.report.json",
1070
1078
  trustedKeys: [],
1079
+ policyDocuments: [],
1071
1080
  };
1072
1081
  for (let index = 0; index < args.length; index += 1) {
1073
1082
  const arg = args[index];
@@ -1077,6 +1086,8 @@ function parseVerifyProofOptions(args) {
1077
1086
  options.reportOut = requireValue(args, ++index, arg);
1078
1087
  } else if (arg === "--trusted-keys") {
1079
1088
  options.trustedKeys.push(requireValue(args, ++index, arg));
1089
+ } else if (arg === "--policy-document") {
1090
+ options.policyDocuments.push(requireValue(args, ++index, arg));
1080
1091
  } else {
1081
1092
  fail(`unknown option: ${arg}`);
1082
1093
  }
@@ -1116,7 +1127,8 @@ function verifyProofExportCommand(proofExportPath, options) {
1116
1127
  }
1117
1128
  const proofExport = parseSingleJSON(source, "proof export");
1118
1129
  const keySets = loadPublishedKeySets(options.trustedKeys);
1119
- const report = buildLocalProofVerificationReport(proofExport, resolvedProofExportPath, resolve(options.reportOut), keySets);
1130
+ const policyDocuments = options.policyDocuments.map((path) => readFileSync(resolve(path), "utf8"));
1131
+ const report = buildLocalProofVerificationReport(proofExport, resolvedProofExportPath, resolve(options.reportOut), keySets, policyDocuments);
1120
1132
  const reportData = JSON.stringify(report, null, 2) + "\n";
1121
1133
  mkdirSync(dirname(resolve(options.reportOut)), { recursive: true });
1122
1134
  writeFileSync(resolve(options.reportOut), reportData, { mode: 0o600 });
@@ -1184,7 +1196,7 @@ function buildLocalPDFReceiptVerificationReport(bytes, pdfPath, reportPath, expe
1184
1196
  });
1185
1197
  }
1186
1198
 
1187
- function buildLocalProofVerificationReport(proofExport, proofExportPath, reportPath, keySets) {
1199
+ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportPath, keySets, policyDocuments = []) {
1188
1200
  const invalid = validateProofLookupExport(proofExport);
1189
1201
  if (invalid.length > 0) {
1190
1202
  fail(`proof export verification failed closed: ${invalid.join(",")}`);
@@ -1195,6 +1207,15 @@ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportP
1195
1207
  if (signatures.invalid.length > 0) {
1196
1208
  fail(`proof export verification failed closed: ${signatures.invalid.join(",")}`);
1197
1209
  }
1210
+ // The signed AEP bytes are verified above; a policy binding sealed in them
1211
+ // (aep.policy_binding, AEP 1.1 policy-binding profile) must be well formed
1212
+ // and is reported as sealed. Absence is never a failure.
1213
+ const policyBinding = sealedPolicyBinding(record.canonical_aep_json);
1214
+ if (policyBinding.invalid.length > 0) {
1215
+ fail(`proof export verification failed closed: ${policyBinding.invalid.join(",")}`);
1216
+ }
1217
+ // Re-run the sealed evaluation (P1-C step 2); a disagreement fails closed.
1218
+ const policyReevaluation = reevaluateSealedPolicyBinding(record.canonical_aep_json, policyBinding.binding, policyDocuments);
1198
1219
  const trust = classifySignerTrust(signatures.signers, keySets);
1199
1220
  const withoutHash = {
1200
1221
  schema_version: LOCAL_PROOF_VERIFICATION_SCHEMA_VERSION,
@@ -1227,6 +1248,21 @@ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportP
1227
1248
  proof_record_hash: record.record_hash,
1228
1249
  proof_lookup_hash: proofExport.result_hash,
1229
1250
  verification_bundle_hash: bundle.bundle_hash,
1251
+ // Present only when the signed AEP seals one: RECORD_ONLY means the
1252
+ // policy evaluation was recorded, never that it was enforced.
1253
+ // policy_binding_statement says the same in words (shared wording with
1254
+ // the Go verifier and the public verify page): every constraint's status
1255
+ // is spelled out, so an unchecked approval reads NOT CHECKED.
1256
+ ...(policyBinding.binding === null
1257
+ ? {}
1258
+ : {
1259
+ policy_binding: policyBinding.binding,
1260
+ policy_binding_statement: policyBindingStatement(policyBinding.binding),
1261
+ // MATCH when the sealed evaluation was re-run and came out identical;
1262
+ // NOT_RECHECKED (with a reason) when it could not be re-run. Never
1263
+ // silently passes: a re-run that disagrees fails verification.
1264
+ policy_reevaluation: policyReevaluation,
1265
+ }),
1230
1266
  hash_algorithm: "SHA-256",
1231
1267
  boundary_assertions: {
1232
1268
  offline_verifier_used: true,
@@ -1245,6 +1281,11 @@ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportP
1245
1281
  canonical_json_authoritative: true,
1246
1282
  pdf_receipt_non_authoritative: true,
1247
1283
  },
1284
+ // Additive: what this proof establishes and what it does not (assurance
1285
+ // profile, per-dimension results, verdict by the fixed rule,
1286
+ // machine-readable limitations). status, signer_trust and the exit code
1287
+ // are unchanged. Covered by report_hash.
1288
+ verification_assessment: buildLegacyVerificationAssessment({ signerTrust: trust.signer_trust, keySetSupplied: keySets.length > 0, policyBinding: policyBinding.binding, policyReevaluation }),
1248
1289
  report_hash: "",
1249
1290
  };
1250
1291
  return Object.freeze({
@@ -1253,6 +1294,223 @@ function buildLocalProofVerificationReport(proofExport, proofExportPath, reportP
1253
1294
  });
1254
1295
  }
1255
1296
 
1297
+ // Policy re-evaluation (P1-C step 2). Mirrors the Go offline verifier
1298
+ // (engine/internal/verificationinfra/offlineproof/policy_reevaluation.go):
1299
+ // rebuild the evaluated event from the signed AEP, resolve the policy document
1300
+ // by its source policy hash (a --policy-document first, then the bundled
1301
+ // published registry), re-run it with the TS port of the policy engine and
1302
+ // require every sealed value to come out identical.
1303
+ // The runtime lane the signed AEP itself names (execution_id prefix and
1304
+ // policy.policy_id together), or "" when it names none.
1305
+ function signedRuntimeLane(canonicalAEPJSON) {
1306
+ let aep;
1307
+ try {
1308
+ aep = JSON.parse(canonicalAEPJSON);
1309
+ } catch {
1310
+ return "";
1311
+ }
1312
+ const executionID = isRecord(aep) && typeof aep.execution_id === "string" ? aep.execution_id : "";
1313
+ const policyID = isRecord(aep) && isRecord(aep.policy) && typeof aep.policy.policy_id === "string" ? aep.policy.policy_id : "";
1314
+ const marker = RUNTIME_LANE_MARKERS.find((entry) => executionID.startsWith(entry.executionIDPrefix) && policyID === entry.policyID);
1315
+ return marker === undefined ? "" : marker.lane;
1316
+ }
1317
+
1318
+ // Rebuilds the evaluated event from policy_binding.evaluated_facts, or null
1319
+ // for a binding sealed before step 2. The sealed lane must be the lane the
1320
+ // signed AEP itself names; otherwise verification fails closed.
1321
+ function reconstructPolicyEvent(canonicalAEPJSON, binding) {
1322
+ const facts = binding.evaluated_facts;
1323
+ if (facts === undefined) return null;
1324
+ const lane = signedRuntimeLane(canonicalAEPJSON);
1325
+ if (lane !== facts.lane) {
1326
+ 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}"`);
1327
+ }
1328
+ return {
1329
+ event: { eeo: { execution_domain: { lane: facts.lane, mutation_performed: facts.mutation_performed } } },
1330
+ allowedEventFields: [...RUNTIME_POLICY_EVENT_FIELDS],
1331
+ };
1332
+ }
1333
+
1334
+ function resolvePolicyDocument(sourcePolicyHash, allowedEventFields, policyDocuments) {
1335
+ const compile = (document) => {
1336
+ try {
1337
+ const compiled = compilePolicyDocument(document, allowedEventFields);
1338
+ return compiled.source_policy_hash === sourcePolicyHash ? compiled : null;
1339
+ } catch {
1340
+ return null;
1341
+ }
1342
+ };
1343
+ for (const document of policyDocuments) {
1344
+ const compiled = compile(document);
1345
+ if (compiled !== null) return { compiled, source: "SUPPLIED_DOCUMENT" };
1346
+ }
1347
+ if (/^[a-f0-9]{64}$/.test(sourcePolicyHash)) {
1348
+ const url = new URL(`${sourcePolicyHash}.json`, BUILT_IN_POLICY_REGISTRY_URL);
1349
+ if (existsSync(url)) {
1350
+ const compiled = compile(readFileSync(url, "utf8"));
1351
+ if (compiled !== null) return { compiled, source: "PUBLISHED_REGISTRY" };
1352
+ }
1353
+ }
1354
+ return null;
1355
+ }
1356
+
1357
+ function reevaluateSealedPolicyBinding(canonicalAEPJSON, binding, policyDocuments) {
1358
+ if (binding === null) return null;
1359
+ const event = reconstructPolicyEvent(canonicalAEPJSON, binding);
1360
+ if (event === null) return { status: "NOT_RECHECKED", reason: "EVENT_NOT_RECONSTRUCTIBLE" };
1361
+ const resolved = resolvePolicyDocument(binding.source_policy_hash, event.allowedEventFields, policyDocuments);
1362
+ if (resolved === null) return { status: "NOT_RECHECKED", reason: "POLICY_SOURCE_UNAVAILABLE" };
1363
+ let recomputed;
1364
+ try {
1365
+ recomputed = evaluateCompiledPolicy(resolved.compiled, event.event);
1366
+ } catch (error) {
1367
+ fail(`proof export verification failed closed: policy re-evaluation failed: ${error.message}`);
1368
+ }
1369
+ const mismatches = policyReevaluationMismatches(binding, recomputed);
1370
+ if (mismatches.length > 0) {
1371
+ fail(`proof export verification failed closed: policy re-evaluation mismatch: ${mismatches.join(",")}`);
1372
+ }
1373
+ return { status: "MATCH", policy_source: resolved.source };
1374
+ }
1375
+
1376
+ // AEP 1.1 policy-binding profile (aep.policy_binding): the RECORD_ONLY
1377
+ // evaluation of a hash-pinned policy, sealed inside the signed AEP. Mirrors
1378
+ // the Go verifier (engine/internal/registrylayer/persistence/policy_binding.go):
1379
+ // absent => no binding and no failure; present => exactly these members, all
1380
+ // strings except constraints (mandate_hash optional), the supported
1381
+ // profile/algorithm/enforcement, a policy VM decision, 64-hex non-degenerate
1382
+ // hashes, and a constraints array whose entries carry an explicit status
1383
+ // (SATISFIED requires evidence_hash, NOT_EVALUATED forbids it, ids unique and
1384
+ // ascending); anything else fails closed. It never means the decision was
1385
+ // enforced.
1386
+ const POLICY_BINDING_PROFILE = "intentrax.aep.policy_binding/1.1";
1387
+ const POLICY_BINDING_OPTIONAL_MEMBERS = Object.freeze(["evaluated_facts", "mandate_hash"]);
1388
+ const POLICY_EVALUATED_LANES = new Set(["DRY_RUN", "LIVE_EXECUTE"]);
1389
+ // The runtime execution-event profile (engine recheck.RuntimeEventFields /
1390
+ // RuntimeExecutionEvent) and the lane markers the signed AEP itself carries
1391
+ // (engine proofproduction DryRunLane / LiveExecuteLane).
1392
+ const RUNTIME_POLICY_EVENT_FIELDS = Object.freeze(["eeo.execution_domain.lane", "eeo.execution_domain.mutation_performed"]);
1393
+ const RUNTIME_LANE_MARKERS = Object.freeze([
1394
+ Object.freeze({ lane: "DRY_RUN", executionIDPrefix: "runtime-dry-run-", policyID: "intentrax.runtime.private_alpha.dry_run" }),
1395
+ Object.freeze({ lane: "LIVE_EXECUTE", executionIDPrefix: "runtime-execute-", policyID: "intentrax.runtime.private_alpha.live_execute" }),
1396
+ ]);
1397
+ const POLICY_BINDING_REQUIRED_MEMBERS = Object.freeze([
1398
+ "binding_profile", "compiled_policy_hash", "constraints", "decision", "enforcement", "evaluation_hash",
1399
+ "execution_event_hash", "hash_algorithm", "policy_id", "policy_version", "rule_id", "source_policy_hash",
1400
+ ]);
1401
+ const POLICY_CONSTRAINT_MEMBERS = Object.freeze(["constraint_id", "status", "type"]);
1402
+ const POLICY_CONSTRAINT_SATISFIED = "SATISFIED";
1403
+ const POLICY_CONSTRAINT_NOT_EVALUATED = "NOT_EVALUATED";
1404
+ const POLICY_BINDING_HASH_MEMBERS = Object.freeze(["compiled_policy_hash", "evaluation_hash", "execution_event_hash", "source_policy_hash"]);
1405
+ const POLICY_BINDING_DECISIONS = new Set(["COMPLIANT", "NON_COMPLIANT", "ERROR"]);
1406
+
1407
+ function isPolicyBindingHash(value) {
1408
+ return isSHA256(value) && !/^(.)\1{63}$/.test(value);
1409
+ }
1410
+
1411
+ function sealedPolicyBinding(canonicalAEPJSON) {
1412
+ let aep;
1413
+ try {
1414
+ aep = JSON.parse(canonicalAEPJSON);
1415
+ } catch {
1416
+ return { binding: null, invalid: [] };
1417
+ }
1418
+ if (!isRecord(aep) || !Object.hasOwn(aep, "policy_binding")) return { binding: null, invalid: [] };
1419
+ const binding = aep.policy_binding;
1420
+ if (!isRecord(binding)) return { binding: null, invalid: ["policy_binding"] };
1421
+ const members = Object.keys(binding).sort();
1422
+ const expected = [...POLICY_BINDING_REQUIRED_MEMBERS, ...POLICY_BINDING_OPTIONAL_MEMBERS.filter((member) => Object.hasOwn(binding, member))].sort();
1423
+ if (members.length !== expected.length || members.some((member, index) => member !== expected[index])) {
1424
+ return { binding: null, invalid: ["policy_binding.members"] };
1425
+ }
1426
+ const invalid = [];
1427
+ for (const member of members) {
1428
+ if (member !== "constraints" && member !== "evaluated_facts" && typeof binding[member] !== "string") invalid.push(`policy_binding.${member}`);
1429
+ }
1430
+ if (invalid.length > 0) return { binding: null, invalid };
1431
+ // evaluated_facts (P1-C step 2): exactly a string lane and a boolean
1432
+ // mutation_performed. Optional: bindings sealed before step 2 omit it.
1433
+ let evaluatedFacts;
1434
+ if (Object.hasOwn(binding, "evaluated_facts")) {
1435
+ const facts = binding.evaluated_facts;
1436
+ const factMembers = isRecord(facts) ? Object.keys(facts).sort() : [];
1437
+ if (!isRecord(facts) || factMembers.length !== 2 || factMembers[0] !== "lane" || factMembers[1] !== "mutation_performed"
1438
+ || typeof facts.lane !== "string" || typeof facts.mutation_performed !== "boolean") {
1439
+ return { binding: null, invalid: ["policy_binding.evaluated_facts"] };
1440
+ }
1441
+ if (!POLICY_EVALUATED_LANES.has(facts.lane)) invalid.push("policy_binding.evaluated_facts.lane");
1442
+ evaluatedFacts = Object.freeze({ lane: facts.lane, mutation_performed: facts.mutation_performed });
1443
+ }
1444
+ const constraints = sealedPolicyConstraints(binding.constraints);
1445
+ if (constraints.malformed.length > 0) return { binding: null, invalid: constraints.malformed };
1446
+ invalid.push(...constraints.invalid);
1447
+ if (binding.binding_profile !== POLICY_BINDING_PROFILE) invalid.push("policy_binding.binding_profile");
1448
+ if (!POLICY_BINDING_DECISIONS.has(binding.decision)) invalid.push("policy_binding.decision");
1449
+ if (binding.enforcement !== "RECORD_ONLY") invalid.push("policy_binding.enforcement");
1450
+ if (binding.hash_algorithm !== "SHA-256") invalid.push("policy_binding.hash_algorithm");
1451
+ const hashMembers = Object.hasOwn(binding, "mandate_hash") ? [...POLICY_BINDING_HASH_MEMBERS, "mandate_hash"] : POLICY_BINDING_HASH_MEMBERS;
1452
+ for (const member of hashMembers) {
1453
+ if (!isPolicyBindingHash(binding[member])) invalid.push(`policy_binding.${member}`);
1454
+ }
1455
+ for (const member of ["policy_id", "policy_version", "rule_id"]) {
1456
+ if (binding[member] === "") invalid.push(`policy_binding.${member}`);
1457
+ }
1458
+ if (invalid.length > 0) return { binding: null, invalid: invalid.sort() };
1459
+ const normalized = {};
1460
+ for (const member of members) normalized[member] = member === "constraints" ? constraints.list : member === "evaluated_facts" ? evaluatedFacts : binding[member];
1461
+ return { binding: Object.freeze(normalized), invalid: [] };
1462
+ }
1463
+
1464
+ function sealedPolicyConstraints(value) {
1465
+ if (!Array.isArray(value)) return { list: [], malformed: ["policy_binding.constraints"], invalid: [] };
1466
+ const list = [];
1467
+ const invalid = [];
1468
+ for (const [index, constraint] of value.entries()) {
1469
+ const at = `policy_binding.constraints[${index}]`;
1470
+ if (!isRecord(constraint)) return { list: [], malformed: [at], invalid: [] };
1471
+ const members = Object.keys(constraint).sort();
1472
+ const expected = Object.hasOwn(constraint, "evidence_hash")
1473
+ ? [...POLICY_CONSTRAINT_MEMBERS, "evidence_hash"].sort()
1474
+ : [...POLICY_CONSTRAINT_MEMBERS];
1475
+ if (members.length !== expected.length || members.some((member, i) => member !== expected[i])) {
1476
+ return { list: [], malformed: [`${at}.members`], invalid: [] };
1477
+ }
1478
+ for (const member of members) {
1479
+ if (typeof constraint[member] !== "string") return { list: [], malformed: [`${at}.${member}`], invalid: [] };
1480
+ }
1481
+ if (constraint.constraint_id === "" || (index > 0 && constraint.constraint_id <= value[index - 1].constraint_id)) {
1482
+ invalid.push(`${at}.constraint_id`);
1483
+ }
1484
+ if (constraint.type === "") invalid.push(`${at}.type`);
1485
+ if (constraint.status === POLICY_CONSTRAINT_SATISFIED) {
1486
+ if (!isPolicyBindingHash(constraint.evidence_hash)) invalid.push(`${at}.evidence_hash`);
1487
+ } else if (constraint.status === POLICY_CONSTRAINT_NOT_EVALUATED) {
1488
+ if (Object.hasOwn(constraint, "evidence_hash")) invalid.push(`${at}.evidence_hash`);
1489
+ } else {
1490
+ invalid.push(`${at}.status`);
1491
+ }
1492
+ const normalized = {};
1493
+ for (const member of members) normalized[member] = constraint[member];
1494
+ list.push(Object.freeze(normalized));
1495
+ }
1496
+ return { list: Object.freeze(list), malformed: [], invalid };
1497
+ }
1498
+
1499
+ // The shared verifier wording for a verified policy binding (identical to
1500
+ // PolicyBindingStatement in the Go verifier and the public verify facade).
1501
+ function policyBindingStatement(binding) {
1502
+ const head = `Policy ${binding.policy_id}@${binding.policy_version} evaluated ${binding.decision} (rule ${binding.rule_id}); recorded only, never enforced.`;
1503
+ if (binding.constraints.length === 0) return `${head} The matched rule has no constraints.`;
1504
+ return [head, ...binding.constraints.map(policyConstraintStatement)].join(" ");
1505
+ }
1506
+
1507
+ function policyConstraintStatement(constraint) {
1508
+ if (constraint.status === POLICY_CONSTRAINT_SATISFIED) {
1509
+ return `Constraint ${constraint.constraint_id} (${constraint.type}): SATISFIED; evidence ${constraint.evidence_hash} is bound by this proof.`;
1510
+ }
1511
+ return `Constraint ${constraint.constraint_id} (${constraint.type}): NOT CHECKED (NOT_EVALUATED); this proof binds no evidence that it was met.`;
1512
+ }
1513
+
1256
1514
  // Verifies what the record's integrity hashes cannot: that the signatures are
1257
1515
  // genuine ed25519 signatures over the signed payload, that enough of them are
1258
1516
  // present, and that the signed payload carries this record's own AEP. Without
@@ -1508,6 +1766,22 @@ function classifySignerTrust(signers, keySets) {
1508
1766
  return { signer_trust: signerTrust, signers: resolved, min_trusted_signers: minTrustedSigners, distinct_trusted_signers: distinctTrustedSigners };
1509
1767
  }
1510
1768
 
1769
+ // Short human table of the verification_assessment block: dimension, result,
1770
+ // provenance, limitations.
1771
+ function assessmentTable(assessment) {
1772
+ const rows = [["DIMENSION", "RESULT", "PROVENANCE", "LIMITATIONS"]];
1773
+ for (const row of assessment.assessments) {
1774
+ rows.push([row.dimension, row.result, row.provenance ?? "-", row.limitations.length > 0 ? row.limitations.join(",") : "-"]);
1775
+ }
1776
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
1777
+ const lines = [`assurance: profile=${assessment.assurance_profile} verdict=${assessment.verdict} required=${assessment.required_dimensions.join(",")}`];
1778
+ for (const row of rows) {
1779
+ lines.push((" " + row.map((cell, column) => (column === row.length - 1 ? cell : cell.padEnd(widths[column] + 2))).join("")).trimEnd());
1780
+ }
1781
+ lines.push(`limitations: ${assessment.limitations.map((limitation) => limitation.code).join(", ")}`);
1782
+ return lines.join("\n");
1783
+ }
1784
+
1511
1785
  function signerTrustMessage(report) {
1512
1786
  if (report.signer_trust === "UNPINNED_SIGNER") {
1513
1787
  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 +2532,11 @@ async function buildNativeHookResult(event = {}, options = {}) {
2258
2532
  admission_request,
2259
2533
  admission_response,
2260
2534
  original_event_ref: stableNativeHookEventRef(event),
2535
+ // Send this exact value as idempotency_key on /v1/intents/execute. The
2536
+ // engine links the execution under SHA-256(idempotency_key), which equals
2537
+ // admission_request.idempotency_key_hash, so the execution correlates with
2538
+ // this admission instead of reading as unadmitted.
2539
+ execute_idempotency_key: hookExecuteIdempotencyKey(admission_request.request_payload_hash),
2261
2540
  submitted: submit,
2262
2541
  mutation_performed: false,
2263
2542
  tool_execution_performed: false,
@@ -2266,6 +2545,12 @@ async function buildNativeHookResult(event = {}, options = {}) {
2266
2545
  });
2267
2546
  }
2268
2547
 
2548
+ // The raw execute idempotency key for an admission (same rule as the SDK's
2549
+ // agentHookExecuteIdempotencyKey). The admission carries only its SHA-256.
2550
+ function hookExecuteIdempotencyKey(requestPayloadHash) {
2551
+ return "INTENTRAX_AGENT_HOOK_IDEMPOTENCY_V1" + requestPayloadHash;
2552
+ }
2553
+
2269
2554
  async function buildNativeAdmissionForHook(event = {}) {
2270
2555
  const sample = JSON.parse(await readFile(SAMPLE_ADMISSION_REQUEST_URL, "utf8"));
2271
2556
  const requestPayloadHash = sha256Hex(canonicalJson({
@@ -2277,7 +2562,7 @@ async function buildNativeAdmissionForHook(event = {}) {
2277
2562
  ...sample,
2278
2563
  request_payload_hash: requestPayloadHash,
2279
2564
  protocol_payload_ref: \`sha256:\${requestPayloadHash}\`,
2280
- idempotency_key_hash: sha256Hex("INTENTRAX_AGENT_HOOK_IDEMPOTENCY_V1" + requestPayloadHash),
2565
+ idempotency_key_hash: sha256Hex(hookExecuteIdempotencyKey(requestPayloadHash)),
2281
2566
  });
2282
2567
  }
2283
2568
 
@@ -2704,7 +2989,7 @@ function printHelp() {
2704
2989
  Usage:
2705
2990
  intentrax init <adapter> [--dry-run] [--force] [--json] [--output-dir <dir>] [--base-url <url>] [--tenant-id <tenant>]
2706
2991
  intentrax check-init --output-dir <dir> [--json]
2707
- intentrax verify-proof <proof-export.json> [--trusted-keys <key-set.json>] [--json] [--report-out <file>]
2992
+ intentrax verify-proof <proof-export.json> [--trusted-keys <key-set.json>] [--policy-document <policy.json>] [--json] [--report-out <file>]
2708
2993
  intentrax verify-pdf-receipt <receipt.pdf> --pdf-hash <X-Intentrax-PDF-Hash> [--json] [--report-out <file>]
2709
2994
 
2710
2995
  Adapters:
@@ -2743,6 +3028,27 @@ Proof export verification:
2743
3028
  REVOKED_SIGNER / MIXED_TRUST 3
2744
3029
  any integrity or signature failure exits 2 (failed closed)
2745
3030
 
3031
+ A proof that seals a policy binding (AEP 1.1) also gets policy_reevaluation:
3032
+ verify-proof rebuilds the evaluated event from the signed proof, resolves the
3033
+ policy by its source_policy_hash (--policy-document, as served by
3034
+ GET /v1/policies/{source_policy_hash}, or the published registry bundled in
3035
+ trust/policies), re-runs the policy engine and requires every sealed value
3036
+ to come out identical. MATCH or NOT_RECHECKED (with a reason); a re-run that
3037
+ disagrees fails closed (exit 2).
3038
+
3039
+ The report also carries verification_assessment, printed as a table: the
3040
+ assurance profile (every proof issued today is LEGACY_DECISION_RECORD,
3041
+ which requires only RECORD_INTEGRITY), a result per dimension, a verdict
3042
+ derived by a fixed rule, and machine-readable limitations. Verdicts:
3043
+ VERIFIED_FOR_SCOPE record intact and signed by published trusted keys;
3044
+ the scope is the profile's required dimensions only
3045
+ INTEGRITY_ONLY record intact, signer not established
3046
+ VERIFICATION_FAILED a dimension failed (for example a REVOKED signer)
3047
+ A legacy proof never claims execution, effect or policy evaluation:
3048
+ EXECUTION_NOT_ATTESTED, EFFECT_NOT_VERIFIED, POLICY_BINDING_SYNTHETIC and
3049
+ COMPLETENESS_NOT_ESTABLISHED are always listed. The exit code does not
3050
+ depend on the assessment.
3051
+
2746
3052
  The SDK ships the production key set (trust/production-key-set.json,
2747
3053
  min_trusted_signers 2) and the sandbox key set (trust/sandbox-key-set.json).
2748
3054
  Add more sets, for example revocations, with --trusted-keys <file>