@gtrabanco/agentic-workflow-schema 3.3.0 → 3.4.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/dist/index.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * take the LAST fenced ```json block of the assistant's final message;
9
9
  * exactly one envelope per turn; all top-level keys always present.
10
10
  */
11
+ import { VERIFICATION_COMMAND_STATUSES, VERIFICATION_CONTRACT, VERIFICATION_COST_CLASSES, VERIFICATION_DIAGNOSTIC_CODES, VERIFICATION_LIMITS, VERIFICATION_PLAN_CONTRACT_ID, VERIFICATION_RECEIPT_CONTRACT_ID, VERIFICATION_STAGES, VERIFICATION_VERDICTS, createVerificationDiagnosticSink, captureVerificationInput, projectStructure, validateStructure, } from "./verification-contract.js";
11
12
  // ---------------------------------------------------------------------------
12
13
  // Types (source of truth: this package; the internal skill carries policy only)
13
14
  // ---------------------------------------------------------------------------
@@ -341,10 +342,26 @@ export function isRunHalt(envelope) {
341
342
  // ---------------------------------------------------------------------------
342
343
  /** The strict, driver-facing interpretation of the legacy envelope. */
343
344
  const STRICT_V2_KEYS = [...REQUIRED_KEYS, "detail"];
345
+ /**
346
+ * Memo for the key vocabularies below: they are static contract data repeated
347
+ * per parsed envelope, so the `Set` is built once per distinct vocabulary
348
+ * instead of once per call. The key joins on NUL, which no JSON member name can
349
+ * contain here, so two vocabularies can never alias each other.
350
+ */
351
+ const _vocabularyKeys = new Map();
352
+ function vocabularyKeys(keys) {
353
+ const memo = keys.join("\0");
354
+ let allowed = _vocabularyKeys.get(memo);
355
+ if (allowed === undefined) {
356
+ allowed = new Set(keys);
357
+ _vocabularyKeys.set(memo, allowed);
358
+ }
359
+ return allowed;
360
+ }
344
361
  function rejectUnexpectedKeys(value, path, keys, errors) {
345
362
  if (!isObj(value))
346
363
  return;
347
- const allowed = new Set(keys);
364
+ const allowed = vocabularyKeys(keys);
348
365
  for (const key of Object.keys(value)) {
349
366
  if (!allowed.has(key))
350
367
  errors.push(`unexpected key: ${path}.${key}`);
@@ -2201,24 +2218,46 @@ export const STALE_REASON_CODES = [
2201
2218
  "stale-acceptance-fingerprint",
2202
2219
  "stale-review-policy",
2203
2220
  ];
2204
- // ---------------------------------------------------------------------------
2205
- // D4 — Canonical serialization helpers
2206
- // ---------------------------------------------------------------------------
2207
- function canonicalJSONValue(v) {
2221
+ /**
2222
+ * D4/D6 — Canonical serialization of one value.
2223
+ *
2224
+ * The domain is the JSON data model: `null`, string, finite number, boolean, array
2225
+ * and plain object. What happens *outside* it is the `domain` argument above — a
2226
+ * named refusal for the verification contracts, the 3.3.0 fallback for the legacy
2227
+ * ones. This function is the byte-level authority behind every digest in the
2228
+ * package, so the two domains are pinned by golden vectors
2229
+ * (`test/fixtures/canonical-legacy-vectors.mjs`) and by the AC5 verification
2230
+ * vectors, never by prose.
2231
+ */
2232
+ function canonicalJSONValue(v, domain = "verification") {
2208
2233
  if (v === null)
2209
2234
  return "null";
2210
- if (typeof v === "string")
2235
+ const kind = typeof v;
2236
+ if (kind === "string")
2211
2237
  return JSON.stringify(v);
2212
- if (typeof v === "number")
2238
+ if (kind === "number") {
2239
+ if (!Number.isFinite(v)) {
2240
+ if (domain === "verification") {
2241
+ throw new TypeError(`canonical JSON: unsupported leaf (non-finite ${kind})`);
2242
+ }
2243
+ return JSON.stringify(v); // 3.3.0: NaN / ±Infinity serialize as `null`
2244
+ }
2213
2245
  return JSON.stringify(v);
2214
- if (typeof v === "boolean")
2246
+ }
2247
+ if (kind === "boolean")
2215
2248
  return JSON.stringify(v);
2216
2249
  if (Array.isArray(v)) {
2217
- return "[" + v.map(canonicalJSONValue).join(",") + "]";
2250
+ // An explicit arrow, never `.map(canonicalJSONValue)`: `map` would pass the
2251
+ // element INDEX as the domain, silently selecting the legacy fallback for
2252
+ // every array leaf.
2253
+ return "[" + v.map((item) => canonicalJSONValue(item, domain)).join(",") + "]";
2218
2254
  }
2219
- if (typeof v === "object") {
2255
+ if (kind === "object") {
2220
2256
  const keys = Object.keys(v).sort();
2221
- return "{" + keys.map(k => JSON.stringify(k) + ":" + canonicalJSONValue(v[k])).join(",") + "}";
2257
+ return "{" + keys.map(k => JSON.stringify(k) + ":" + canonicalJSONValue(v[k], domain)).join(",") + "}";
2258
+ }
2259
+ if (domain === "verification") {
2260
+ throw new TypeError(`canonical JSON: unsupported leaf (${kind})`);
2222
2261
  }
2223
2262
  return JSON.stringify(v);
2224
2263
  }
@@ -2238,7 +2277,7 @@ export function canonicalizeCandidateSnapshot(snapshot) {
2238
2277
  acceptanceFingerprint: snapshot.acceptanceFingerprint,
2239
2278
  changedPaths: sortedPaths,
2240
2279
  };
2241
- return canonicalJSONValue(obj);
2280
+ return canonicalJSONValue(obj, "legacy");
2242
2281
  }
2243
2282
  /**
2244
2283
  * D4 — Canonicalize a ReviewReceiptV1.
@@ -2260,15 +2299,14 @@ export function canonicalizeReviewReceipt(receipt) {
2260
2299
  diagnostics: receipt.diagnostics,
2261
2300
  policyVersion: receipt.policyVersion,
2262
2301
  };
2263
- return canonicalJSONValue(obj);
2302
+ return canonicalJSONValue(obj, "legacy");
2264
2303
  }
2265
2304
  // ---------------------------------------------------------------------------
2266
2305
  // SHA-256 hashing
2267
2306
  // ---------------------------------------------------------------------------
2268
2307
  /** D4 — SHA-256 hex digest (async via Web Crypto). */
2269
2308
  async function sha256Hex(data) {
2270
- const encoder = new TextEncoder();
2271
- const buf = encoder.encode(data);
2309
+ const buf = _utf8Encoder.encode(data);
2272
2310
  const hashBuffer = await crypto.subtle.digest("SHA-256", buf);
2273
2311
  const hashArray = new Uint8Array(hashBuffer);
2274
2312
  return Array.from(hashArray).map(b => b.toString(16).padStart(2, "0")).join("");
@@ -2294,7 +2332,7 @@ export async function computeAcceptanceFingerprint(inputs) {
2294
2332
  const obj = {
2295
2333
  inputs: sorted,
2296
2334
  };
2297
- return sha256Hex(canonicalJSONValue(obj));
2335
+ return sha256Hex(canonicalJSONValue(obj, "legacy"));
2298
2336
  }
2299
2337
  // ---------------------------------------------------------------------------
2300
2338
  // D1 — Freshness predicate
@@ -2391,3 +2429,506 @@ export const CANONICAL_VECTORS = Object.freeze([
2391
2429
  description: "minimal valid receipt (single finding)",
2392
2430
  },
2393
2431
  ]);
2432
+ // ---------------------------------------------------------------------------
2433
+ // VerificationPlan v1 — staged verification contracts
2434
+ // ---------------------------------------------------------------------------
2435
+ /** Contract identifier for VerificationPlan v1 (re-exported from the canonical definition). */
2436
+ export { VERIFICATION_PLAN_CONTRACT_ID };
2437
+ /** Verification stages: fast and full (re-exported from the canonical definition). */
2438
+ export { VERIFICATION_STAGES };
2439
+ /** Cost classes declared by the project, not measured by the package. */
2440
+ export { VERIFICATION_COST_CLASSES };
2441
+ /**
2442
+ * D14 bounded usability — the published ceilings of the v1 contracts
2443
+ * (re-exported from the canonical definition, which is where they are enforced).
2444
+ */
2445
+ export { VERIFICATION_LIMITS };
2446
+ /**
2447
+ * D16 closed diagnostic result (re-exported from the canonical definition).
2448
+ *
2449
+ * A failure never carries a message or a submitted value — only the frozen code
2450
+ * and the RFC 6901 pointer to the offending location, capped at
2451
+ * `VERIFICATION_LIMITS.diagnostics` rows with `truncated` telling the consumer
2452
+ * the list is not the whole story.
2453
+ */
2454
+ export { VERIFICATION_DIAGNOSTIC_CODES };
2455
+ /** UTF-8 byte length of a canonical form — the unit D14 payload budgets use. */
2456
+ function utf8Bytes(text) {
2457
+ return _utf8Encoder.encode(text).length;
2458
+ }
2459
+ /**
2460
+ * D14 canonical payload budget (F77), measured BEFORE any diagnostic is
2461
+ * allocated, so a wide document is refused by the budget alone instead of
2462
+ * spending the diagnostic ceiling on its individual disliked fields.
2463
+ *
2464
+ * The measurement uses the same canonical serializer the canonicalizers use
2465
+ * (`canonicalJSONValue`: sorted keys, compact separators), so it is byte-identical
2466
+ * to the canonical payload size for every document the structural pass would
2467
+ * accept: undeclared keys are the only thing a submitted object can carry that a
2468
+ * normalized DTO drops, and the structural pass rejects those (F71 `unknown-field`).
2469
+ * Returns the refusal rows, or `null` when the payload fits (or cannot be
2470
+ * serialized at all, which the structural pass then rejects on type grounds).
2471
+ */
2472
+ function canonicalBudgetRefusal(value, limit) {
2473
+ let canonical;
2474
+ try {
2475
+ canonical = canonicalJSONValue(value);
2476
+ }
2477
+ catch {
2478
+ return null;
2479
+ }
2480
+ return utf8Bytes(canonical) > limit
2481
+ ? [Object.freeze({ code: "limit-exceeded", path: "" })]
2482
+ : null;
2483
+ }
2484
+ /**
2485
+ * F97/F99 — one captured observation of a submitted document, bounded by the
2486
+ * canonical byte budget.
2487
+ *
2488
+ * Every authority below runs on the snapshot, never on the submission: the byte
2489
+ * budget, the structural walk, the cross-rules and the DTO would otherwise read the
2490
+ * same accessor again and could decide on a document other than the one it blesses.
2491
+ * The capture aborts on the budget before the payload is fully copied (F99), and an
2492
+ * accessor that throws answers with the redacted `invalid-type` row F92 fixed.
2493
+ */
2494
+ function captureSubmittedVerificationInput(value, budgetBytes) {
2495
+ return captureVerificationInput(value, budgetBytes);
2496
+ }
2497
+ /** The single refusal row a bounded capture rejection earns (D16 shape). */
2498
+ function captureRejectionResult(rejected) {
2499
+ return {
2500
+ ok: false,
2501
+ diagnostics: [Object.freeze({ code: rejected.code, path: rejected.pointer })],
2502
+ truncated: false,
2503
+ };
2504
+ }
2505
+ /**
2506
+ * The sole plan-validation authority (D12).
2507
+ *
2508
+ * Every structural rule comes from the canonical verification-contract
2509
+ * definition: contract id, non-empty command list, unique non-empty ids,
2510
+ * closed vocabularies, executable/args shapes, working-directory policy
2511
+ * nullness and relative-path validation, positive-integer timeouts, and
2512
+ * undeclared or inherited fields at every level.
2513
+ *
2514
+ * The input domain is JSON documents — values `JSON.parse` produces or
2515
+ * equivalent literals. An input outside that domain (e.g. an object with a
2516
+ * throwing live getter) cannot smuggle its exception past this entry: the
2517
+ * walk failure is refused as a redacted `invalid-type` row, so callers
2518
+ * always observe the D16 diagnostic contract (F92).
2519
+ *
2520
+ * On success it returns a normalized own-property DTO — never the submitted
2521
+ * reference — so digests and downstream semantics see exactly the declared
2522
+ * contract fields. On failure it returns at most
2523
+ * `VERIFICATION_LIMITS.diagnostics` redacted code+path rows (D16).
2524
+ */
2525
+ export function validateVerificationPlanV1(value) {
2526
+ const submitted = captureSubmittedVerificationInput(value, VERIFICATION_LIMITS.planBytes);
2527
+ if (!submitted.ok)
2528
+ return captureRejectionResult(submitted);
2529
+ const document = submitted.value;
2530
+ // Exact UTF-8 measure on the snapshot unless the capture's running size WAS the
2531
+ // byte size (pure ASCII, every leaf measurable): a multibyte document can cross
2532
+ // the budget only here (F99 keeps both paths exact).
2533
+ if (!submitted.measureExact) {
2534
+ const oversized = canonicalBudgetRefusal(document, VERIFICATION_LIMITS.planBytes);
2535
+ if (oversized)
2536
+ return { ok: false, diagnostics: oversized, truncated: false };
2537
+ }
2538
+ const sink = createVerificationDiagnosticSink();
2539
+ const plan = validateStructure(VERIFICATION_CONTRACT.plan, VERIFICATION_CONTRACT.plan.root, document, "", sink);
2540
+ if (sink.count() > 0)
2541
+ return { ok: false, ...sink.finish() };
2542
+ return { ok: true, plan: plan };
2543
+ }
2544
+ // ---------------------------------------------------------------------------
2545
+ // VerificationReceipt v1 — staged verification contracts
2546
+ // ---------------------------------------------------------------------------
2547
+ /** Contract identifier for VerificationReceipt v1 (re-exported from the canonical definition). */
2548
+ export { VERIFICATION_RECEIPT_CONTRACT_ID };
2549
+ /** Possible per-command result statuses (re-exported from the canonical definition). */
2550
+ export { VERIFICATION_COMMAND_STATUSES };
2551
+ /**
2552
+ * The non-pass family, derived once from the frozen vocabulary so the D4
2553
+ * fail-fast sequencing scan and the D8 verdict derivation can never drift
2554
+ * apart (order follows the vocabulary: failed, timed-out, infrastructure-error).
2555
+ */
2556
+ const NON_PASSED_STATUSES = VERIFICATION_COMMAND_STATUSES.filter((s) => s !== "passed" && s !== "skipped");
2557
+ /** Verdict values derived from receipt content. */
2558
+ export { VERIFICATION_VERDICTS };
2559
+ /**
2560
+ * Package-internal structural shape check for VerificationReceipt v1, driven by
2561
+ * the canonical definition (`src/verification-contract.ts`).
2562
+ *
2563
+ * It is NOT a public entry point (D12): `validateVerificationReceiptAgainstPlan`
2564
+ * is the only receipt authority, so a structural PASS here is never an
2565
+ * alternate runtime validity claim.
2566
+ */
2567
+ function validateVerificationReceiptShape(value) {
2568
+ const submitted = captureSubmittedVerificationInput(value, VERIFICATION_LIMITS.receiptBytes);
2569
+ if (!submitted.ok)
2570
+ return captureRejectionResult(submitted);
2571
+ const document = submitted.value;
2572
+ if (!submitted.measureExact) {
2573
+ const oversized = canonicalBudgetRefusal(document, VERIFICATION_LIMITS.receiptBytes);
2574
+ if (oversized)
2575
+ return { ok: false, diagnostics: oversized, truncated: false };
2576
+ }
2577
+ const sink = createVerificationDiagnosticSink();
2578
+ const receipt = validateStructure(VERIFICATION_CONTRACT.receipt, VERIFICATION_CONTRACT.receipt.root, document, "", sink);
2579
+ if (sink.count() > 0)
2580
+ return { ok: false, ...sink.finish() };
2581
+ return { ok: true, receipt: receipt };
2582
+ }
2583
+ // ---------------------------------------------------------------------------
2584
+ // Verification semantic core
2585
+ // ---------------------------------------------------------------------------
2586
+ /**
2587
+ * The sole receipt-validation authority (D12): one call performs the
2588
+ * VerificationReceipt v1 structural shape check, the VerificationPlan v1
2589
+ * structural check, and every plan-bound rule — commandId existence, declared
2590
+ * order, fast-stage subset, complete `stopOnFailure` sequencing and attribution
2591
+ * (D3/S4), planDigest match and verdict consistency (D2).
2592
+ *
2593
+ * It accepts unknown input and returns a normalized own-property receipt DTO;
2594
+ * no standalone structural receipt validator is exported, so a structural
2595
+ * match alone can never claim runtime validity (D13). Async because the
2596
+ * planDigest check composes the async digest. The input domain is JSON
2597
+ * documents — like the plan entry, an out-of-domain object (a throwing live
2598
+ * getter) is refused as a redacted `invalid-type` row rather than escaping an
2599
+ * attacker-chosen exception (F92).
2600
+ */
2601
+ export async function validateVerificationReceiptAgainstPlan(receipt, plan) {
2602
+ const sink = createVerificationDiagnosticSink();
2603
+ // Validate the plan first: nothing about a receipt is meaningful against a
2604
+ // plan the authority itself rejects. Its diagnostics are already capped and
2605
+ // redacted, so they are propagated as-is rather than re-derived here.
2606
+ const pv = validateVerificationPlanV1(plan);
2607
+ if (!pv.ok)
2608
+ return pv;
2609
+ const rv = validateVerificationReceiptShape(receipt);
2610
+ if (!rv.ok)
2611
+ return rv;
2612
+ // Every semantic check below runs on the normalized DTOs, never on the
2613
+ // submitted references.
2614
+ const normalizedPlan = pv.plan;
2615
+ const normalizedReceipt = rv.receipt;
2616
+ // Build lookups
2617
+ const cmdIdx = new Map();
2618
+ const cmdMap = new Map();
2619
+ for (let i = 0; i < normalizedPlan.commands.length; i++) {
2620
+ cmdIdx.set(normalizedPlan.commands[i].id, i);
2621
+ cmdMap.set(normalizedPlan.commands[i].id, normalizedPlan.commands[i]);
2622
+ }
2623
+ /** `/results/<i>/<field>` — the only pointer shape the semantic block needs. */
2624
+ const atResult = (index, field) => `/results/${index}/${field}`;
2625
+ // 1. commandId existence + uniqueness
2626
+ const seen = new Set();
2627
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2628
+ const r = normalizedReceipt.results[i];
2629
+ if (!cmdIdx.has(r.commandId)) {
2630
+ sink.push("unknown-command", atResult(i, "commandId"));
2631
+ }
2632
+ else if (seen.has(r.commandId)) {
2633
+ sink.push("duplicate-id", atResult(i, "commandId"));
2634
+ }
2635
+ else {
2636
+ seen.add(r.commandId);
2637
+ }
2638
+ }
2639
+ // 2. Declared order
2640
+ if (sink.count() === 0) {
2641
+ let prev = -1;
2642
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2643
+ const idx = cmdIdx.get(normalizedReceipt.results[i].commandId);
2644
+ if (idx < prev) {
2645
+ sink.push("invalid-order", atResult(i, "commandId"));
2646
+ break;
2647
+ }
2648
+ prev = idx;
2649
+ }
2650
+ }
2651
+ // 3. Fast-stage subset: fast receipt only has fast results
2652
+ if (sink.count() === 0 && normalizedReceipt.stageRequested === "fast") {
2653
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2654
+ const c = cmdMap.get(normalizedReceipt.results[i].commandId);
2655
+ if (c && c.stage === "full")
2656
+ sink.push("invalid-stage", atResult(i, "commandId"));
2657
+ }
2658
+ }
2659
+ // 4. D3/S4 — complete `stopOnFailure` SEQUENCING (F65). The trigger is the
2660
+ // earliest declared command whose own result is non-passed
2661
+ // (`failed | timed-out | infrastructure-error`) AND whose plan entry declares
2662
+ // `stopOnFailure: true`. Nothing runs after it, so every later row must be
2663
+ // `skipped`, and a skipped row that carries a reason must name THAT trigger:
2664
+ // an earlier command that was itself skipped by the stop never ran, so it
2665
+ // cannot be a reason. A `skipped` row with a null reason stays representable
2666
+ // (D3 -> verdict `incomplete`), and a later command with no row stays
2667
+ // representable (D7) — neither is a schema error.
2668
+ let trigger = null;
2669
+ if (sink.count() === 0) {
2670
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2671
+ const r = normalizedReceipt.results[i];
2672
+ const c = cmdMap.get(r.commandId);
2673
+ if (!c)
2674
+ continue; // unknown ids were reported by check 1
2675
+ if (trigger === null) {
2676
+ if (NON_PASSED_STATUSES.includes(r.status) && c.stopOnFailure)
2677
+ trigger = r.commandId;
2678
+ continue;
2679
+ }
2680
+ if (r.status !== "skipped")
2681
+ sink.push("invalid-fail-fast", atResult(i, "status"));
2682
+ else if (r.skipReason !== null && r.skipReason !== trigger)
2683
+ sink.push("invalid-fail-fast", atResult(i, "skipReason"));
2684
+ }
2685
+ }
2686
+ // 5. D3 fail-fast attribution (per-row): a non-null reason must name an
2687
+ // earlier-declared, non-passed command that declares stopOnFailure.
2688
+ if (sink.count() === 0) {
2689
+ // F95 — the commandId → result index serves ONLY this check, so it is
2690
+ // built only when this check runs: an already-failing receipt never pays
2691
+ // for an O(n) map it cannot use (and the neighboring checks all gate the
2692
+ // same way).
2693
+ const resultByCmd = new Map(normalizedReceipt.results.map(r => [r.commandId, r]));
2694
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2695
+ const r = normalizedReceipt.results[i];
2696
+ if (r.status !== "skipped" || r.skipReason === null)
2697
+ continue;
2698
+ const st = r.skipReason;
2699
+ if (!cmdIdx.has(st)) {
2700
+ sink.push("unknown-command", atResult(i, "skipReason"));
2701
+ continue;
2702
+ }
2703
+ const ri = cmdIdx.get(r.commandId);
2704
+ const ti = cmdIdx.get(st);
2705
+ if (ti >= ri) {
2706
+ sink.push("invalid-order", atResult(i, "skipReason"));
2707
+ continue;
2708
+ }
2709
+ const tr = resultByCmd.get(st);
2710
+ if (!tr || !NON_PASSED_STATUSES.includes(tr.status)) {
2711
+ sink.push("invalid-skip", atResult(i, "skipReason"));
2712
+ continue;
2713
+ }
2714
+ if (!cmdMap.get(st).stopOnFailure)
2715
+ sink.push("invalid-fail-fast", atResult(i, "skipReason"));
2716
+ }
2717
+ }
2718
+ // 6. planDigest match
2719
+ if (sink.count() === 0) {
2720
+ const d = await digestVerificationPlan(normalizedPlan);
2721
+ if (d !== normalizedReceipt.planDigest)
2722
+ sink.push("digest-mismatch", "/planDigest");
2723
+ }
2724
+ // 7. Verdict consistency
2725
+ if (sink.count() === 0) {
2726
+ // Inputs already validated above — use the unchecked derivation (no re-validation).
2727
+ const derived = deriveVerdictUnchecked(normalizedReceipt, normalizedPlan);
2728
+ if (derived !== normalizedReceipt.verdict)
2729
+ sink.push("verdict-mismatch", "/verdict");
2730
+ }
2731
+ return sink.count() > 0 ? { ok: false, ...sink.finish() } : { ok: true, receipt: normalizedReceipt };
2732
+ }
2733
+ /**
2734
+ * D2 — Verdict derivation: incomplete > fail > pass, assuming already-validated
2735
+ * inputs (no validation here — callers that pre-validate avoid a full re-scan).
2736
+ * A required row that is `skipped`-with-reason yields `fail`: D2's pass rule
2737
+ * requires every required result row to be `passed`, and a justified skip only
2738
+ * exists attributing to a failure (D3).
2739
+ */
2740
+ function deriveVerdictUnchecked(receipt, plan) {
2741
+ const reqStage = receipt.stageRequested;
2742
+ // Stage required set: fast → fast commands; full → every declared command.
2743
+ // One set is built here and reused by both scans below — the membership test
2744
+ // is the only thing either pass needs from it.
2745
+ const requiredSet = new Set(reqStage === "full"
2746
+ ? plan.commands.map((c) => c.id)
2747
+ : plan.commands.filter((c) => c.stage === "fast").map((c) => c.id));
2748
+ const received = new Set(receipt.results.map((r2) => r2.commandId));
2749
+ // Missing → incomplete
2750
+ for (const id of requiredSet) {
2751
+ if (!received.has(id))
2752
+ return "incomplete";
2753
+ }
2754
+ // Unjustified skip → incomplete
2755
+ for (const r2 of receipt.results) {
2756
+ if (r2.status === "skipped" && !r2.skipReason)
2757
+ return "incomplete";
2758
+ }
2759
+ // Failed/timed-out/infra, or a required row skipped-with-reason → fail
2760
+ for (const r2 of receipt.results) {
2761
+ if (NON_PASSED_STATUSES.includes(r2.status))
2762
+ return "fail";
2763
+ if (requiredSet.has(r2.commandId) && r2.status === "skipped")
2764
+ return "fail";
2765
+ }
2766
+ return "pass";
2767
+ }
2768
+ /**
2769
+ * D2 — Verdict derivation: incomplete > fail > pass. Validating wrapper around
2770
+ * {@link deriveVerdictUnchecked} — safe to call standalone on unvalidated inputs.
2771
+ */
2772
+ export function deriveVerificationVerdict(receipt, plan) {
2773
+ const pv = validateVerificationPlanV1(plan);
2774
+ const rv = validateVerificationReceiptShape(receipt);
2775
+ if (!pv.ok || !rv.ok)
2776
+ return "incomplete";
2777
+ return deriveVerdictUnchecked(rv.receipt, pv.plan);
2778
+ }
2779
+ /**
2780
+ * D6 — Canonical serialization, shared by both contract sides.
2781
+ *
2782
+ * Inputs are projected through the canonical definition first, so the bytes —
2783
+ * and therefore every digest — describe the normalized own-property contract
2784
+ * fields, never an inherited prototype value or an undeclared extra.
2785
+ *
2786
+ * The SPEC precondition ("inputs must first pass their validators") is
2787
+ * enforced defensively here (F91): a declared-array cardinality beyond D14 is
2788
+ * refused BEFORE any serialization work runs, and the canonical form itself
2789
+ * must fit the contract's byte budget. A refusal is a named TypeError that
2790
+ * quotes only the violated limit — never the submitted content.
2791
+ */
2792
+ function canonicalizeWithinContract(value, contract, collectionField, maxItems, budgetBytes, label) {
2793
+ // F97/F99 — one bounded observation, then every guard and the serialization itself
2794
+ // consume that snapshot. Without the capture the cardinality guard above and
2795
+ // `projectStructure` below would read the same submission twice, so a flipping
2796
+ // accessor could make the digest cover a document the guard never saw.
2797
+ const submitted = captureSubmittedVerificationInput(value, budgetBytes);
2798
+ if (!submitted.ok) {
2799
+ throw new TypeError(submitted.code === "limit-exceeded"
2800
+ ? // The capture measured the canonical form past the budget — the same
2801
+ // refusal F91 names, reached before the serializer could finish it.
2802
+ `verification ${label} canonical form exceeds the D14 ${budgetBytes}-byte budget — validate before canonicalizing`
2803
+ : `verification ${label} input is not a readable JSON document — validate before canonicalizing`);
2804
+ }
2805
+ const document = submitted.value;
2806
+ if (document !== null && typeof document === "object") {
2807
+ const items = document[collectionField];
2808
+ if (Array.isArray(items) && items.length > maxItems) {
2809
+ throw new TypeError(`verification ${label} exceeds the D14 limit of at most ${maxItems} ${collectionField} — validate before canonicalizing`);
2810
+ }
2811
+ }
2812
+ const canonical = canonicalJSONValue(projectStructure(contract, contract.root, document));
2813
+ if (utf8Bytes(canonical) > budgetBytes) {
2814
+ throw new TypeError(`verification ${label} canonical form exceeds the D14 ${budgetBytes}-byte budget — validate before canonicalizing`);
2815
+ }
2816
+ return canonical;
2817
+ }
2818
+ /**
2819
+ * D6 — Canonical serialization of a validated `VerificationPlan v1`. The
2820
+ * input must first pass `validateVerificationPlanV1`; out-of-contract
2821
+ * cardinality or byte budgets throw a named TypeError (F91).
2822
+ */
2823
+ export function canonicalizeVerificationPlan(plan) {
2824
+ return canonicalizeWithinContract(plan, VERIFICATION_CONTRACT.plan, "commands", VERIFICATION_LIMITS.commands, VERIFICATION_LIMITS.planBytes, "plan");
2825
+ }
2826
+ /**
2827
+ * D6 — Canonical serialization of a validated `VerificationReceipt v1`. The
2828
+ * input must first pass `validateVerificationReceiptAgainstPlan`;
2829
+ * out-of-contract cardinality or byte budgets throw a named TypeError (F91).
2830
+ */
2831
+ export function canonicalizeVerificationReceipt(receipt) {
2832
+ return canonicalizeWithinContract(receipt, VERIFICATION_CONTRACT.receipt, "results", VERIFICATION_LIMITS.results, VERIFICATION_LIMITS.receiptBytes, "receipt");
2833
+ }
2834
+ /** D6 — Digest of a validated plan (inherits the F91 canonical-input guards). */
2835
+ export async function digestVerificationPlan(plan) {
2836
+ return sha256Hex(canonicalizeVerificationPlan(plan));
2837
+ }
2838
+ /** D6 — Digest of a validated receipt (inherits the F91 canonical-input guards). */
2839
+ export async function digestVerificationReceipt(receipt) {
2840
+ return sha256Hex(canonicalizeVerificationReceipt(receipt));
2841
+ }
2842
+ /**
2843
+ * D1 — Freshness predicate.
2844
+ *
2845
+ * Pure, async, deterministic and it throws nothing. Fixed check order (SPEC §
2846
+ * Stage, verdict, and freshness semantics): plan digest → candidate-snapshot
2847
+ * digest → acceptance fingerprint → a missing fast-stage result → an
2848
+ * unjustified skip → a missing full-stage result → `{ fresh: true }`.
2849
+ *
2850
+ * The two coverage codes are partitioned by the STAGE OF THE MISSING COMMAND,
2851
+ * which is what keeps them disjoint while `incomplete-missing-results` still
2852
+ * answers a full receipt that skipped a fast command:
2853
+ * `incomplete-stage-coverage` only fires on a `full` receipt whose declared
2854
+ * full-stage commands are not covered.
2855
+ */
2856
+ /** Verification-specific freshness reason codes (D1). */
2857
+ export const VERIFICATION_FRESHNESS_CODES = Object.freeze([
2858
+ "stale-plan", "stale-candidate-snapshot", "stale-acceptance-fingerprint",
2859
+ "incomplete-missing-results", "incomplete-unjustified-skip", "incomplete-stage-coverage",
2860
+ ]);
2861
+ export async function compareVerificationReceiptToCurrent(receipt, plan, candidateSnapshotDigest, acceptanceFingerprint) {
2862
+ // Validate plan/receipt FIRST so invalid (non-JSON-serializable) inputs return a
2863
+ // stable freshness result rather than throwing from canonicalJSONValue or
2864
+ // JSON.stringify — the SPEC promises this predicate is pure and throws nothing.
2865
+ // Validation rejects BigInt fields, circular references, and unknown fields
2866
+ // before any hashing runs. A payload that fails its own contract cannot
2867
+ // establish the plan binding, and the plan binding is the FIRST precedence
2868
+ // point, so the honest stable code is `stale-plan` — never an incomplete code,
2869
+ // which would claim a binding this predicate never verified (F63).
2870
+ const pv = validateVerificationPlanV1(plan);
2871
+ const rv = validateVerificationReceiptShape(receipt);
2872
+ if (!pv.ok || !rv.ok)
2873
+ return { fresh: false, reasonCode: "stale-plan" };
2874
+ const p = pv.plan;
2875
+ const r = rv.receipt;
2876
+ // Then check stale conditions (plain string comparisons — safe after validation).
2877
+ const pd = await digestVerificationPlan(p);
2878
+ if (pd !== r.planDigest)
2879
+ return { fresh: false, reasonCode: "stale-plan" };
2880
+ if (candidateSnapshotDigest !== r.candidateSnapshotDigest)
2881
+ return { fresh: false, reasonCode: "stale-candidate-snapshot" };
2882
+ if (acceptanceFingerprint !== r.acceptanceFingerprint)
2883
+ return { fresh: false, reasonCode: "stale-acceptance-fingerprint" };
2884
+ // All three bindings are current: from here on the predicate answers only
2885
+ // incompleteness, so the stale and incomplete blocks are mutually disjoint.
2886
+ const present = new Set(r.results.map((rr) => rr.commandId));
2887
+ const fastIds = [];
2888
+ const fullIds = [];
2889
+ for (const c of p.commands)
2890
+ (c.stage === "fast" ? fastIds : fullIds).push(c.id);
2891
+ // 1. a missing fast-stage result — every fast command is owed a row by a fast
2892
+ // AND a full receipt (D2 required set), in either case `missing-results`.
2893
+ for (const id of fastIds) {
2894
+ if (!present.has(id))
2895
+ return { fresh: false, reasonCode: "incomplete-missing-results" };
2896
+ }
2897
+ // 2. a skipped row without a reason.
2898
+ for (const rr of r.results) {
2899
+ if (rr.status === "skipped" && !rr.skipReason)
2900
+ return { fresh: false, reasonCode: "incomplete-unjustified-skip" };
2901
+ }
2902
+ // 3. a requested-full receipt that does not cover every declared full-stage
2903
+ // command. A fast receipt legitimately carries no full-stage rows (D7), so
2904
+ // the coverage gap is scoped to `stageRequested: "full"`.
2905
+ if (r.stageRequested === "full") {
2906
+ for (const id of fullIds) {
2907
+ if (!present.has(id))
2908
+ return { fresh: false, reasonCode: "incomplete-stage-coverage" };
2909
+ }
2910
+ }
2911
+ return { fresh: true };
2912
+ }
2913
+ // ---------------------------------------------------------------------------
2914
+ // Published canonical vectors (verification — D6)
2915
+ // ---------------------------------------------------------------------------
2916
+ /**
2917
+ * Published frozen canonical vectors for the verification contracts.
2918
+ *
2919
+ * Each vector is a minimal valid value whose canonical digest is deterministic
2920
+ * and reproducible. These vectors lock the canonicalization rules (D6) in place.
2921
+ * Changing any vector's expected digest would be a reviewed contract change.
2922
+ */
2923
+ export const VERIFICATION_CANONICAL_VECTORS = Object.freeze([
2924
+ Object.freeze({
2925
+ contract: VERIFICATION_PLAN_CONTRACT_ID,
2926
+ digest: "43ba52cb34490733f0f37dd6407f7c5ab088f20d928837213a75a25b7bc3eb80",
2927
+ description: "minimal valid VerificationPlan v1 (single fast command)",
2928
+ }),
2929
+ Object.freeze({
2930
+ contract: VERIFICATION_RECEIPT_CONTRACT_ID,
2931
+ digest: "c3d244efadf9d6ae8aa8626f8e252246ed63205eef3f4604b7ba5be2f8bc210d",
2932
+ description: "minimal valid VerificationReceipt v1 (single passed result)",
2933
+ }),
2934
+ ]);