@gtrabanco/agentic-workflow-schema 3.3.0 → 3.5.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,9 @@
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 { canonicalizeContractInput, canonicalJSONValue, utf8Bytes, utf8ByteCompare, } from "./canonical-json.js";
12
+ import { sha256Hex } from "./sha256.js";
13
+ 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, validateStructure, } from "./verification-contract.js";
11
14
  // ---------------------------------------------------------------------------
12
15
  // Types (source of truth: this package; the internal skill carries policy only)
13
16
  // ---------------------------------------------------------------------------
@@ -341,10 +344,26 @@ export function isRunHalt(envelope) {
341
344
  // ---------------------------------------------------------------------------
342
345
  /** The strict, driver-facing interpretation of the legacy envelope. */
343
346
  const STRICT_V2_KEYS = [...REQUIRED_KEYS, "detail"];
347
+ /**
348
+ * Memo for the key vocabularies below: they are static contract data repeated
349
+ * per parsed envelope, so the `Set` is built once per distinct vocabulary
350
+ * instead of once per call. The key joins on NUL, which no JSON member name can
351
+ * contain here, so two vocabularies can never alias each other.
352
+ */
353
+ const _vocabularyKeys = new Map();
354
+ function vocabularyKeys(keys) {
355
+ const memo = keys.join("\0");
356
+ let allowed = _vocabularyKeys.get(memo);
357
+ if (allowed === undefined) {
358
+ allowed = new Set(keys);
359
+ _vocabularyKeys.set(memo, allowed);
360
+ }
361
+ return allowed;
362
+ }
344
363
  function rejectUnexpectedKeys(value, path, keys, errors) {
345
364
  if (!isObj(value))
346
365
  return;
347
- const allowed = new Set(keys);
366
+ const allowed = vocabularyKeys(keys);
348
367
  for (const key of Object.keys(value)) {
349
368
  if (!allowed.has(key))
350
369
  errors.push(`unexpected key: ${path}.${key}`);
@@ -432,7 +451,9 @@ export const WORKFLOW_INTENTS = [
432
451
  "discover-repository-state",
433
452
  "resolve-repository-state",
434
453
  "design-feature",
454
+ "review-spec",
435
455
  "plan-feature",
456
+ "review-plan",
436
457
  "plan-fix",
437
458
  "triage-issue",
438
459
  "execute-phase",
@@ -510,7 +531,9 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
510
531
  "discover-repository-state",
511
532
  "resolve-repository-state",
512
533
  "design-feature",
534
+ "review-spec",
513
535
  "plan-feature",
536
+ "review-plan",
514
537
  "plan-fix",
515
538
  "triage-issue",
516
539
  "execute-phase",
@@ -528,7 +551,9 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
528
551
  allowed: [
529
552
  "resolve-repository-state",
530
553
  "design-feature",
554
+ "review-spec",
531
555
  "plan-feature",
556
+ "review-plan",
532
557
  "plan-fix",
533
558
  "triage-issue",
534
559
  "execute-phase",
@@ -552,6 +577,7 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
552
577
  {
553
578
  key: "design-feature",
554
579
  allowed: [
580
+ "review-spec",
555
581
  "plan-feature",
556
582
  "plan-fix",
557
583
  "triage-issue",
@@ -566,10 +592,28 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
566
592
  + " or the named dependency unit recorded by the last outcome;"
567
593
  + " non-allowed target → stop-forbidden-transition",
568
594
  },
595
+ // review-spec → the Product gate. A PASS releases the roadmap unit into
596
+ // planning; a FAIL or needs-design returns it to design; execution is NOT
597
+ // reachable from here, because a reviewed Product is not an approved Plan.
598
+ {
599
+ key: "review-spec",
600
+ allowed: [
601
+ "plan-feature",
602
+ "plan-fix",
603
+ "design-feature",
604
+ "triage-issue",
605
+ "ask-human",
606
+ "stop",
607
+ ],
608
+ condition: "0..n allowed, each must be the unit whose Product snapshot was bound"
609
+ + " by the current spec-review receipt; execute-phase/audit-pr are unreachable"
610
+ + " without a plan review · PASS → plan-feature, FAIL/needs-design → design-feature",
611
+ },
569
612
  // plan-feature → active or dependency unit, max 1
570
613
  {
571
614
  key: "plan-feature",
572
615
  allowed: [
616
+ "review-plan",
573
617
  "triage-issue",
574
618
  "execute-phase",
575
619
  "review-change",
@@ -581,12 +625,31 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
581
625
  condition: "0..1 allowed; 0 → next roadmap unit; 1 → active unit id or named dependency;"
582
626
  + ">1 → stop-forbidden-transition",
583
627
  },
628
+ // review-plan → the Engineering gate, and the only pre-execution hop that can
629
+ // reach execution. It routes by the OWNER of the finding: a plan defect returns
630
+ // to the planner, a product defect returns to design (a Plan review may discover
631
+ // the Product itself was wrong), and an environment defect goes to a sensor.
632
+ {
633
+ key: "review-plan",
634
+ allowed: [
635
+ "execute-phase",
636
+ "plan-feature",
637
+ "plan-fix",
638
+ "design-feature",
639
+ "triage-issue",
640
+ "ask-human",
641
+ "stop",
642
+ ],
643
+ condition: "0..n allowed, each must be the unit whose Plan snapshot was bound"
644
+ + " by the current plan-review receipt · PASS → execute-phase, plan defect →"
645
+ + " plan-feature, product defect → design-feature, stale evidence → ask-human",
646
+ },
584
647
  // plan-fix → triage-issue only, exactly 1
585
648
  {
586
649
  key: "plan-fix",
587
- allowed: ["triage-issue"],
588
- condition: "exactly 1 target (the issue identity); 0 → sense-missing-evidence;"
589
- + ">1 → stop-forbidden-transition",
650
+ allowed: ["review-plan", "triage-issue"],
651
+ condition: "exactly 1 target (the issue identity, or the planned fix unit for"
652
+ + " review-plan); 0 → sense-missing-evidence; >1 → stop-forbidden-transition",
590
653
  },
591
654
  // triage-issue → issue identities, 1..n
592
655
  {
@@ -888,6 +951,7 @@ export const SKILL_REQUIRED_EVIDENCE = Object.freeze([
888
951
  "audit",
889
952
  "issue-state",
890
953
  "pull-request-state",
954
+ "pre-execution-review",
891
955
  ]);
892
956
  /** Recursively freezes exported metadata so runtime widening is impossible. */
893
957
  function deepFreeze(value) {
@@ -964,6 +1028,20 @@ export const WORKFLOW_SKILL_PROFILES = deepFreeze([
964
1028
  requiredEvidence: ["workflow-snapshot"],
965
1029
  },
966
1030
  },
1031
+ {
1032
+ skill: "review-spec",
1033
+ output: "skill-outcome-v1",
1034
+ nativeFallback: "none",
1035
+ capabilities: {
1036
+ role: "reviewer",
1037
+ reasoning: "critical",
1038
+ // A pre-execution review reads and records; it never edits the artifact it
1039
+ // judges, and it never touches the forge.
1040
+ effects: ["repository-read"],
1041
+ contextSources: ["repository", "semantic-context", "episodic-memory", "execution-state"],
1042
+ requiredEvidence: ["workflow-snapshot", "pre-execution-review"],
1043
+ },
1044
+ },
967
1045
  {
968
1046
  skill: "plan-feature",
969
1047
  output: "skill-outcome-v1",
@@ -976,6 +1054,18 @@ export const WORKFLOW_SKILL_PROFILES = deepFreeze([
976
1054
  requiredEvidence: ["workflow-snapshot"],
977
1055
  },
978
1056
  },
1057
+ {
1058
+ skill: "review-plan",
1059
+ output: "skill-outcome-v1",
1060
+ nativeFallback: "none",
1061
+ capabilities: {
1062
+ role: "reviewer",
1063
+ reasoning: "critical",
1064
+ effects: ["repository-read"],
1065
+ contextSources: ["repository", "semantic-context", "episodic-memory", "execution-state"],
1066
+ requiredEvidence: ["workflow-snapshot", "pre-execution-review"],
1067
+ },
1068
+ },
979
1069
  {
980
1070
  skill: "plan-fix",
981
1071
  output: "skill-outcome-v1",
@@ -1849,22 +1939,6 @@ function isGitObjectId(v) {
1849
1939
  function hasUndeclaredKeys(actual, known) {
1850
1940
  return Object.keys(actual).filter((k) => !known.includes(k));
1851
1941
  }
1852
- /**
1853
- * Compare two UTF-8 strings in ascending unsigned-byte order.
1854
- * Returns < 0 if a < b, > 0 if a > b, 0 if equal.
1855
- */
1856
- const _utf8Encoder = new TextEncoder();
1857
- function utf8ByteCompare(a, b) {
1858
- const ba = _utf8Encoder.encode(a);
1859
- const bb = _utf8Encoder.encode(b);
1860
- const len = Math.min(ba.length, bb.length);
1861
- for (let i = 0; i < len; i++) {
1862
- const diff = ba[i] - bb[i];
1863
- if (diff !== 0)
1864
- return diff;
1865
- }
1866
- return ba.length - bb.length;
1867
- }
1868
1942
  /**
1869
1943
  * Structural validation of a CandidateSnapshot v1.
1870
1944
  * Rejects undeclared fields, enforces GitObjectId format, path-byte ordering,
@@ -2204,24 +2278,6 @@ export const STALE_REASON_CODES = [
2204
2278
  // ---------------------------------------------------------------------------
2205
2279
  // D4 — Canonical serialization helpers
2206
2280
  // ---------------------------------------------------------------------------
2207
- function canonicalJSONValue(v) {
2208
- if (v === null)
2209
- return "null";
2210
- if (typeof v === "string")
2211
- return JSON.stringify(v);
2212
- if (typeof v === "number")
2213
- return JSON.stringify(v);
2214
- if (typeof v === "boolean")
2215
- return JSON.stringify(v);
2216
- if (Array.isArray(v)) {
2217
- return "[" + v.map(canonicalJSONValue).join(",") + "]";
2218
- }
2219
- if (typeof v === "object") {
2220
- const keys = Object.keys(v).sort();
2221
- return "{" + keys.map(k => JSON.stringify(k) + ":" + canonicalJSONValue(v[k])).join(",") + "}";
2222
- }
2223
- return JSON.stringify(v);
2224
- }
2225
2281
  /**
2226
2282
  * D4 — Canonicalize a CandidateSnapshotV1.
2227
2283
  * Produces deterministic JSON with declaration-order keys and sorted changedPaths.
@@ -2238,7 +2294,7 @@ export function canonicalizeCandidateSnapshot(snapshot) {
2238
2294
  acceptanceFingerprint: snapshot.acceptanceFingerprint,
2239
2295
  changedPaths: sortedPaths,
2240
2296
  };
2241
- return canonicalJSONValue(obj);
2297
+ return canonicalJSONValue(obj, "legacy");
2242
2298
  }
2243
2299
  /**
2244
2300
  * D4 — Canonicalize a ReviewReceiptV1.
@@ -2260,18 +2316,7 @@ export function canonicalizeReviewReceipt(receipt) {
2260
2316
  diagnostics: receipt.diagnostics,
2261
2317
  policyVersion: receipt.policyVersion,
2262
2318
  };
2263
- return canonicalJSONValue(obj);
2264
- }
2265
- // ---------------------------------------------------------------------------
2266
- // SHA-256 hashing
2267
- // ---------------------------------------------------------------------------
2268
- /** D4 — SHA-256 hex digest (async via Web Crypto). */
2269
- async function sha256Hex(data) {
2270
- const encoder = new TextEncoder();
2271
- const buf = encoder.encode(data);
2272
- const hashBuffer = await crypto.subtle.digest("SHA-256", buf);
2273
- const hashArray = new Uint8Array(hashBuffer);
2274
- return Array.from(hashArray).map(b => b.toString(16).padStart(2, "0")).join("");
2319
+ return canonicalJSONValue(obj, "legacy");
2275
2320
  }
2276
2321
  /** D4 — Digest a CandidateSnapshotV1 via canonical serialization. */
2277
2322
  export async function digestCandidateSnapshot(snapshot) {
@@ -2294,7 +2339,7 @@ export async function computeAcceptanceFingerprint(inputs) {
2294
2339
  const obj = {
2295
2340
  inputs: sorted,
2296
2341
  };
2297
- return sha256Hex(canonicalJSONValue(obj));
2342
+ return sha256Hex(canonicalJSONValue(obj, "legacy"));
2298
2343
  }
2299
2344
  // ---------------------------------------------------------------------------
2300
2345
  // D1 — Freshness predicate
@@ -2391,3 +2436,493 @@ export const CANONICAL_VECTORS = Object.freeze([
2391
2436
  description: "minimal valid receipt (single finding)",
2392
2437
  },
2393
2438
  ]);
2439
+ // ---------------------------------------------------------------------------
2440
+ // VerificationPlan v1 — staged verification contracts
2441
+ // ---------------------------------------------------------------------------
2442
+ /** Contract identifier for VerificationPlan v1 (re-exported from the canonical definition). */
2443
+ export { VERIFICATION_PLAN_CONTRACT_ID };
2444
+ /** Verification stages: fast and full (re-exported from the canonical definition). */
2445
+ export { VERIFICATION_STAGES };
2446
+ /** Cost classes declared by the project, not measured by the package. */
2447
+ export { VERIFICATION_COST_CLASSES };
2448
+ /**
2449
+ * D14 bounded usability — the published ceilings of the v1 contracts
2450
+ * (re-exported from the canonical definition, which is where they are enforced).
2451
+ */
2452
+ export { VERIFICATION_LIMITS };
2453
+ /**
2454
+ * D16 closed diagnostic result (re-exported from the canonical definition).
2455
+ *
2456
+ * A failure never carries a message or a submitted value — only the frozen code
2457
+ * and the RFC 6901 pointer to the offending location, capped at
2458
+ * `VERIFICATION_LIMITS.diagnostics` rows with `truncated` telling the consumer
2459
+ * the list is not the whole story.
2460
+ */
2461
+ export { VERIFICATION_DIAGNOSTIC_CODES };
2462
+ /**
2463
+ * D14 canonical payload budget (F77), measured BEFORE any diagnostic is
2464
+ * allocated, so a wide document is refused by the budget alone instead of
2465
+ * spending the diagnostic ceiling on its individual disliked fields.
2466
+ *
2467
+ * The measurement uses the same canonical serializer the canonicalizers use
2468
+ * (`canonicalJSONValue`: sorted keys, compact separators), so it is byte-identical
2469
+ * to the canonical payload size for every document the structural pass would
2470
+ * accept: undeclared keys are the only thing a submitted object can carry that a
2471
+ * normalized DTO drops, and the structural pass rejects those (F71 `unknown-field`).
2472
+ * Returns the refusal rows, or `null` when the payload fits (or cannot be
2473
+ * serialized at all, which the structural pass then rejects on type grounds).
2474
+ */
2475
+ function canonicalBudgetRefusal(value, limit) {
2476
+ let canonical;
2477
+ try {
2478
+ canonical = canonicalJSONValue(value);
2479
+ }
2480
+ catch {
2481
+ return null;
2482
+ }
2483
+ return utf8Bytes(canonical) > limit
2484
+ ? [Object.freeze({ code: "limit-exceeded", path: "" })]
2485
+ : null;
2486
+ }
2487
+ /**
2488
+ * F97/F99 — one captured observation of a submitted document, bounded by the
2489
+ * canonical byte budget.
2490
+ *
2491
+ * Every authority below runs on the snapshot, never on the submission: the byte
2492
+ * budget, the structural walk, the cross-rules and the DTO would otherwise read the
2493
+ * same accessor again and could decide on a document other than the one it blesses.
2494
+ * The capture aborts on the budget before the payload is fully copied (F99), and an
2495
+ * accessor that throws answers with the redacted `invalid-type` row F92 fixed.
2496
+ */
2497
+ function captureSubmittedVerificationInput(value, budgetBytes) {
2498
+ return captureVerificationInput(value, budgetBytes);
2499
+ }
2500
+ /** The single refusal row a bounded capture rejection earns (D16 shape). */
2501
+ function captureRejectionResult(rejected) {
2502
+ return {
2503
+ ok: false,
2504
+ diagnostics: [Object.freeze({ code: rejected.code, path: rejected.pointer })],
2505
+ truncated: false,
2506
+ };
2507
+ }
2508
+ /**
2509
+ * The sole plan-validation authority (D12).
2510
+ *
2511
+ * Every structural rule comes from the canonical verification-contract
2512
+ * definition: contract id, non-empty command list, unique non-empty ids,
2513
+ * closed vocabularies, executable/args shapes, working-directory policy
2514
+ * nullness and relative-path validation, positive-integer timeouts, and
2515
+ * undeclared or inherited fields at every level.
2516
+ *
2517
+ * The input domain is JSON documents — values `JSON.parse` produces or
2518
+ * equivalent literals. An input outside that domain (e.g. an object with a
2519
+ * throwing live getter) cannot smuggle its exception past this entry: the
2520
+ * walk failure is refused as a redacted `invalid-type` row, so callers
2521
+ * always observe the D16 diagnostic contract (F92).
2522
+ *
2523
+ * On success it returns a normalized own-property DTO — never the submitted
2524
+ * reference — so digests and downstream semantics see exactly the declared
2525
+ * contract fields. On failure it returns at most
2526
+ * `VERIFICATION_LIMITS.diagnostics` redacted code+path rows (D16).
2527
+ */
2528
+ export function validateVerificationPlanV1(value) {
2529
+ const submitted = captureSubmittedVerificationInput(value, VERIFICATION_LIMITS.planBytes);
2530
+ if (!submitted.ok)
2531
+ return captureRejectionResult(submitted);
2532
+ const document = submitted.value;
2533
+ // Exact UTF-8 measure on the snapshot unless the capture's running size WAS the
2534
+ // byte size (pure ASCII, every leaf measurable): a multibyte document can cross
2535
+ // the budget only here (F99 keeps both paths exact).
2536
+ if (!submitted.measureExact) {
2537
+ const oversized = canonicalBudgetRefusal(document, VERIFICATION_LIMITS.planBytes);
2538
+ if (oversized)
2539
+ return { ok: false, diagnostics: oversized, truncated: false };
2540
+ }
2541
+ const sink = createVerificationDiagnosticSink();
2542
+ const plan = validateStructure(VERIFICATION_CONTRACT.plan, VERIFICATION_CONTRACT.plan.root, document, "", sink);
2543
+ if (sink.count() > 0)
2544
+ return { ok: false, ...sink.finish() };
2545
+ return { ok: true, plan: plan };
2546
+ }
2547
+ // ---------------------------------------------------------------------------
2548
+ // VerificationReceipt v1 — staged verification contracts
2549
+ // ---------------------------------------------------------------------------
2550
+ /** Contract identifier for VerificationReceipt v1 (re-exported from the canonical definition). */
2551
+ export { VERIFICATION_RECEIPT_CONTRACT_ID };
2552
+ /** Possible per-command result statuses (re-exported from the canonical definition). */
2553
+ export { VERIFICATION_COMMAND_STATUSES };
2554
+ /**
2555
+ * The non-pass family, derived once from the frozen vocabulary so the D4
2556
+ * fail-fast sequencing scan and the D8 verdict derivation can never drift
2557
+ * apart (order follows the vocabulary: failed, timed-out, infrastructure-error).
2558
+ */
2559
+ const NON_PASSED_STATUSES = VERIFICATION_COMMAND_STATUSES.filter((s) => s !== "passed" && s !== "skipped");
2560
+ /** Verdict values derived from receipt content. */
2561
+ export { VERIFICATION_VERDICTS };
2562
+ /**
2563
+ * Package-internal structural shape check for VerificationReceipt v1, driven by
2564
+ * the canonical definition (`src/verification-contract.ts`).
2565
+ *
2566
+ * It is NOT a public entry point (D12): `validateVerificationReceiptAgainstPlan`
2567
+ * is the only receipt authority, so a structural PASS here is never an
2568
+ * alternate runtime validity claim.
2569
+ */
2570
+ function validateVerificationReceiptShape(value) {
2571
+ const submitted = captureSubmittedVerificationInput(value, VERIFICATION_LIMITS.receiptBytes);
2572
+ if (!submitted.ok)
2573
+ return captureRejectionResult(submitted);
2574
+ const document = submitted.value;
2575
+ if (!submitted.measureExact) {
2576
+ const oversized = canonicalBudgetRefusal(document, VERIFICATION_LIMITS.receiptBytes);
2577
+ if (oversized)
2578
+ return { ok: false, diagnostics: oversized, truncated: false };
2579
+ }
2580
+ const sink = createVerificationDiagnosticSink();
2581
+ const receipt = validateStructure(VERIFICATION_CONTRACT.receipt, VERIFICATION_CONTRACT.receipt.root, document, "", sink);
2582
+ if (sink.count() > 0)
2583
+ return { ok: false, ...sink.finish() };
2584
+ return { ok: true, receipt: receipt };
2585
+ }
2586
+ // ---------------------------------------------------------------------------
2587
+ // Verification semantic core
2588
+ // ---------------------------------------------------------------------------
2589
+ /**
2590
+ * The sole receipt-validation authority (D12): one call performs the
2591
+ * VerificationReceipt v1 structural shape check, the VerificationPlan v1
2592
+ * structural check, and every plan-bound rule — commandId existence, declared
2593
+ * order, fast-stage subset, complete `stopOnFailure` sequencing and attribution
2594
+ * (D3/S4), planDigest match and verdict consistency (D2).
2595
+ *
2596
+ * It accepts unknown input and returns a normalized own-property receipt DTO;
2597
+ * no standalone structural receipt validator is exported, so a structural
2598
+ * match alone can never claim runtime validity (D13). Async because the
2599
+ * planDigest check composes the async digest. The input domain is JSON
2600
+ * documents — like the plan entry, an out-of-domain object (a throwing live
2601
+ * getter) is refused as a redacted `invalid-type` row rather than escaping an
2602
+ * attacker-chosen exception (F92).
2603
+ */
2604
+ export async function validateVerificationReceiptAgainstPlan(receipt, plan) {
2605
+ const sink = createVerificationDiagnosticSink();
2606
+ // Validate the plan first: nothing about a receipt is meaningful against a
2607
+ // plan the authority itself rejects. Its diagnostics are already capped and
2608
+ // redacted, so they are propagated as-is rather than re-derived here.
2609
+ const pv = validateVerificationPlanV1(plan);
2610
+ if (!pv.ok)
2611
+ return pv;
2612
+ const rv = validateVerificationReceiptShape(receipt);
2613
+ if (!rv.ok)
2614
+ return rv;
2615
+ // Every semantic check below runs on the normalized DTOs, never on the
2616
+ // submitted references.
2617
+ const normalizedPlan = pv.plan;
2618
+ const normalizedReceipt = rv.receipt;
2619
+ // Build lookups
2620
+ const cmdIdx = new Map();
2621
+ const cmdMap = new Map();
2622
+ for (let i = 0; i < normalizedPlan.commands.length; i++) {
2623
+ cmdIdx.set(normalizedPlan.commands[i].id, i);
2624
+ cmdMap.set(normalizedPlan.commands[i].id, normalizedPlan.commands[i]);
2625
+ }
2626
+ /** `/results/<i>/<field>` — the only pointer shape the semantic block needs. */
2627
+ const atResult = (index, field) => `/results/${index}/${field}`;
2628
+ // 1. commandId existence + uniqueness
2629
+ const seen = new Set();
2630
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2631
+ const r = normalizedReceipt.results[i];
2632
+ if (!cmdIdx.has(r.commandId)) {
2633
+ sink.push("unknown-command", atResult(i, "commandId"));
2634
+ }
2635
+ else if (seen.has(r.commandId)) {
2636
+ sink.push("duplicate-id", atResult(i, "commandId"));
2637
+ }
2638
+ else {
2639
+ seen.add(r.commandId);
2640
+ }
2641
+ }
2642
+ // 2. Declared order
2643
+ if (sink.count() === 0) {
2644
+ let prev = -1;
2645
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2646
+ const idx = cmdIdx.get(normalizedReceipt.results[i].commandId);
2647
+ if (idx < prev) {
2648
+ sink.push("invalid-order", atResult(i, "commandId"));
2649
+ break;
2650
+ }
2651
+ prev = idx;
2652
+ }
2653
+ }
2654
+ // 3. Fast-stage subset: fast receipt only has fast results
2655
+ if (sink.count() === 0 && normalizedReceipt.stageRequested === "fast") {
2656
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2657
+ const c = cmdMap.get(normalizedReceipt.results[i].commandId);
2658
+ if (c && c.stage === "full")
2659
+ sink.push("invalid-stage", atResult(i, "commandId"));
2660
+ }
2661
+ }
2662
+ // 4. D3/S4 — complete `stopOnFailure` SEQUENCING (F65). The trigger is the
2663
+ // earliest declared command whose own result is non-passed
2664
+ // (`failed | timed-out | infrastructure-error`) AND whose plan entry declares
2665
+ // `stopOnFailure: true`. Nothing runs after it, so every later row must be
2666
+ // `skipped`, and a skipped row that carries a reason must name THAT trigger:
2667
+ // an earlier command that was itself skipped by the stop never ran, so it
2668
+ // cannot be a reason. A `skipped` row with a null reason stays representable
2669
+ // (D3 -> verdict `incomplete`), and a later command with no row stays
2670
+ // representable (D7) — neither is a schema error.
2671
+ let trigger = null;
2672
+ if (sink.count() === 0) {
2673
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2674
+ const r = normalizedReceipt.results[i];
2675
+ const c = cmdMap.get(r.commandId);
2676
+ if (!c)
2677
+ continue; // unknown ids were reported by check 1
2678
+ if (trigger === null) {
2679
+ if (NON_PASSED_STATUSES.includes(r.status) && c.stopOnFailure)
2680
+ trigger = r.commandId;
2681
+ continue;
2682
+ }
2683
+ if (r.status !== "skipped")
2684
+ sink.push("invalid-fail-fast", atResult(i, "status"));
2685
+ else if (r.skipReason !== null && r.skipReason !== trigger)
2686
+ sink.push("invalid-fail-fast", atResult(i, "skipReason"));
2687
+ }
2688
+ }
2689
+ // 5. D3 fail-fast attribution (per-row): a non-null reason must name an
2690
+ // earlier-declared, non-passed command that declares stopOnFailure.
2691
+ if (sink.count() === 0) {
2692
+ // F95 — the commandId → result index serves ONLY this check, so it is
2693
+ // built only when this check runs: an already-failing receipt never pays
2694
+ // for an O(n) map it cannot use (and the neighboring checks all gate the
2695
+ // same way).
2696
+ const resultByCmd = new Map(normalizedReceipt.results.map(r => [r.commandId, r]));
2697
+ for (let i = 0; i < normalizedReceipt.results.length; i++) {
2698
+ const r = normalizedReceipt.results[i];
2699
+ if (r.status !== "skipped" || r.skipReason === null)
2700
+ continue;
2701
+ const st = r.skipReason;
2702
+ if (!cmdIdx.has(st)) {
2703
+ sink.push("unknown-command", atResult(i, "skipReason"));
2704
+ continue;
2705
+ }
2706
+ const ri = cmdIdx.get(r.commandId);
2707
+ const ti = cmdIdx.get(st);
2708
+ if (ti >= ri) {
2709
+ sink.push("invalid-order", atResult(i, "skipReason"));
2710
+ continue;
2711
+ }
2712
+ const tr = resultByCmd.get(st);
2713
+ if (!tr || !NON_PASSED_STATUSES.includes(tr.status)) {
2714
+ sink.push("invalid-skip", atResult(i, "skipReason"));
2715
+ continue;
2716
+ }
2717
+ if (!cmdMap.get(st).stopOnFailure)
2718
+ sink.push("invalid-fail-fast", atResult(i, "skipReason"));
2719
+ }
2720
+ }
2721
+ // 6. planDigest match
2722
+ if (sink.count() === 0) {
2723
+ const d = await digestVerificationPlan(normalizedPlan);
2724
+ if (d !== normalizedReceipt.planDigest)
2725
+ sink.push("digest-mismatch", "/planDigest");
2726
+ }
2727
+ // 7. Verdict consistency
2728
+ if (sink.count() === 0) {
2729
+ // Inputs already validated above — use the unchecked derivation (no re-validation).
2730
+ const derived = deriveVerdictUnchecked(normalizedReceipt, normalizedPlan);
2731
+ if (derived !== normalizedReceipt.verdict)
2732
+ sink.push("verdict-mismatch", "/verdict");
2733
+ }
2734
+ return sink.count() > 0 ? { ok: false, ...sink.finish() } : { ok: true, receipt: normalizedReceipt };
2735
+ }
2736
+ /**
2737
+ * D2 — Verdict derivation: incomplete > fail > pass, assuming already-validated
2738
+ * inputs (no validation here — callers that pre-validate avoid a full re-scan).
2739
+ * A required row that is `skipped`-with-reason yields `fail`: D2's pass rule
2740
+ * requires every required result row to be `passed`, and a justified skip only
2741
+ * exists attributing to a failure (D3).
2742
+ */
2743
+ function deriveVerdictUnchecked(receipt, plan) {
2744
+ const reqStage = receipt.stageRequested;
2745
+ // Stage required set: fast → fast commands; full → every declared command.
2746
+ // One set is built here and reused by both scans below — the membership test
2747
+ // is the only thing either pass needs from it.
2748
+ const requiredSet = new Set(reqStage === "full"
2749
+ ? plan.commands.map((c) => c.id)
2750
+ : plan.commands.filter((c) => c.stage === "fast").map((c) => c.id));
2751
+ const received = new Set(receipt.results.map((r2) => r2.commandId));
2752
+ // Missing → incomplete
2753
+ for (const id of requiredSet) {
2754
+ if (!received.has(id))
2755
+ return "incomplete";
2756
+ }
2757
+ // Unjustified skip → incomplete
2758
+ for (const r2 of receipt.results) {
2759
+ if (r2.status === "skipped" && !r2.skipReason)
2760
+ return "incomplete";
2761
+ }
2762
+ // Failed/timed-out/infra, or a required row skipped-with-reason → fail
2763
+ for (const r2 of receipt.results) {
2764
+ if (NON_PASSED_STATUSES.includes(r2.status))
2765
+ return "fail";
2766
+ if (requiredSet.has(r2.commandId) && r2.status === "skipped")
2767
+ return "fail";
2768
+ }
2769
+ return "pass";
2770
+ }
2771
+ /**
2772
+ * D2 — Verdict derivation: incomplete > fail > pass. Validating wrapper around
2773
+ * {@link deriveVerdictUnchecked} — safe to call standalone on unvalidated inputs.
2774
+ */
2775
+ export function deriveVerificationVerdict(receipt, plan) {
2776
+ const pv = validateVerificationPlanV1(plan);
2777
+ const rv = validateVerificationReceiptShape(receipt);
2778
+ if (!pv.ok || !rv.ok)
2779
+ return "incomplete";
2780
+ return deriveVerdictUnchecked(rv.receipt, pv.plan);
2781
+ }
2782
+ /**
2783
+ * D6 — Canonical serialization of a verification contract, shared by both sides.
2784
+ *
2785
+ * The guards (F91 cardinality, F97/F99 one-capture, the byte budget) and the
2786
+ * own-property projection live in `canonicalizeContractInput`, which the
2787
+ * pre-execution canonicalizers use too: one serializer, so a digest cannot mean
2788
+ * one thing for a verification document and another for a snapshot or receipt.
2789
+ */
2790
+ function canonicalizeWithinContract(value, contract, collectionField, maxItems, budgetBytes, label) {
2791
+ return canonicalizeContractInput(value, contract, {
2792
+ collectionField,
2793
+ maxItems,
2794
+ budgetBytes,
2795
+ family: "verification",
2796
+ label,
2797
+ // Feature 26's F91 surface pins the D14 marker inside the over-budget
2798
+ // message; the shared serializer keeps it for this family only.
2799
+ budgetTag: "D14",
2800
+ });
2801
+ }
2802
+ /**
2803
+ * D6 — Canonical serialization of a validated `VerificationPlan v1`. The
2804
+ * input must first pass `validateVerificationPlanV1`; out-of-contract
2805
+ * cardinality or byte budgets throw a named TypeError (F91).
2806
+ */
2807
+ export function canonicalizeVerificationPlan(plan) {
2808
+ return canonicalizeWithinContract(plan, VERIFICATION_CONTRACT.plan, "commands", VERIFICATION_LIMITS.commands, VERIFICATION_LIMITS.planBytes, "plan");
2809
+ }
2810
+ /**
2811
+ * D6 — Canonical serialization of a validated `VerificationReceipt v1`. The
2812
+ * input must first pass `validateVerificationReceiptAgainstPlan`;
2813
+ * out-of-contract cardinality or byte budgets throw a named TypeError (F91).
2814
+ */
2815
+ export function canonicalizeVerificationReceipt(receipt) {
2816
+ return canonicalizeWithinContract(receipt, VERIFICATION_CONTRACT.receipt, "results", VERIFICATION_LIMITS.results, VERIFICATION_LIMITS.receiptBytes, "receipt");
2817
+ }
2818
+ /** D6 — Digest of a validated plan (inherits the F91 canonical-input guards). */
2819
+ export async function digestVerificationPlan(plan) {
2820
+ return sha256Hex(canonicalizeVerificationPlan(plan));
2821
+ }
2822
+ /** D6 — Digest of a validated receipt (inherits the F91 canonical-input guards). */
2823
+ export async function digestVerificationReceipt(receipt) {
2824
+ return sha256Hex(canonicalizeVerificationReceipt(receipt));
2825
+ }
2826
+ /**
2827
+ * D1 — Freshness predicate.
2828
+ *
2829
+ * Pure, async, deterministic and it throws nothing. Fixed check order (SPEC §
2830
+ * Stage, verdict, and freshness semantics): plan digest → candidate-snapshot
2831
+ * digest → acceptance fingerprint → a missing fast-stage result → an
2832
+ * unjustified skip → a missing full-stage result → `{ fresh: true }`.
2833
+ *
2834
+ * The two coverage codes are partitioned by the STAGE OF THE MISSING COMMAND,
2835
+ * which is what keeps them disjoint while `incomplete-missing-results` still
2836
+ * answers a full receipt that skipped a fast command:
2837
+ * `incomplete-stage-coverage` only fires on a `full` receipt whose declared
2838
+ * full-stage commands are not covered.
2839
+ */
2840
+ /** Verification-specific freshness reason codes (D1). */
2841
+ export const VERIFICATION_FRESHNESS_CODES = Object.freeze([
2842
+ "stale-plan", "stale-candidate-snapshot", "stale-acceptance-fingerprint",
2843
+ "incomplete-missing-results", "incomplete-unjustified-skip", "incomplete-stage-coverage",
2844
+ ]);
2845
+ export async function compareVerificationReceiptToCurrent(receipt, plan, candidateSnapshotDigest, acceptanceFingerprint) {
2846
+ // Validate plan/receipt FIRST so invalid (non-JSON-serializable) inputs return a
2847
+ // stable freshness result rather than throwing from canonicalJSONValue or
2848
+ // JSON.stringify — the SPEC promises this predicate is pure and throws nothing.
2849
+ // Validation rejects BigInt fields, circular references, and unknown fields
2850
+ // before any hashing runs. A payload that fails its own contract cannot
2851
+ // establish the plan binding, and the plan binding is the FIRST precedence
2852
+ // point, so the honest stable code is `stale-plan` — never an incomplete code,
2853
+ // which would claim a binding this predicate never verified (F63).
2854
+ const pv = validateVerificationPlanV1(plan);
2855
+ const rv = validateVerificationReceiptShape(receipt);
2856
+ if (!pv.ok || !rv.ok)
2857
+ return { fresh: false, reasonCode: "stale-plan" };
2858
+ const p = pv.plan;
2859
+ const r = rv.receipt;
2860
+ // Then check stale conditions (plain string comparisons — safe after validation).
2861
+ const pd = await digestVerificationPlan(p);
2862
+ if (pd !== r.planDigest)
2863
+ return { fresh: false, reasonCode: "stale-plan" };
2864
+ if (candidateSnapshotDigest !== r.candidateSnapshotDigest)
2865
+ return { fresh: false, reasonCode: "stale-candidate-snapshot" };
2866
+ if (acceptanceFingerprint !== r.acceptanceFingerprint)
2867
+ return { fresh: false, reasonCode: "stale-acceptance-fingerprint" };
2868
+ // All three bindings are current: from here on the predicate answers only
2869
+ // incompleteness, so the stale and incomplete blocks are mutually disjoint.
2870
+ const present = new Set(r.results.map((rr) => rr.commandId));
2871
+ const fastIds = [];
2872
+ const fullIds = [];
2873
+ for (const c of p.commands)
2874
+ (c.stage === "fast" ? fastIds : fullIds).push(c.id);
2875
+ // 1. a missing fast-stage result — every fast command is owed a row by a fast
2876
+ // AND a full receipt (D2 required set), in either case `missing-results`.
2877
+ for (const id of fastIds) {
2878
+ if (!present.has(id))
2879
+ return { fresh: false, reasonCode: "incomplete-missing-results" };
2880
+ }
2881
+ // 2. a skipped row without a reason.
2882
+ for (const rr of r.results) {
2883
+ if (rr.status === "skipped" && !rr.skipReason)
2884
+ return { fresh: false, reasonCode: "incomplete-unjustified-skip" };
2885
+ }
2886
+ // 3. a requested-full receipt that does not cover every declared full-stage
2887
+ // command. A fast receipt legitimately carries no full-stage rows (D7), so
2888
+ // the coverage gap is scoped to `stageRequested: "full"`.
2889
+ if (r.stageRequested === "full") {
2890
+ for (const id of fullIds) {
2891
+ if (!present.has(id))
2892
+ return { fresh: false, reasonCode: "incomplete-stage-coverage" };
2893
+ }
2894
+ }
2895
+ return { fresh: true };
2896
+ }
2897
+ // ---------------------------------------------------------------------------
2898
+ // Published canonical vectors (verification — D6)
2899
+ // ---------------------------------------------------------------------------
2900
+ /**
2901
+ * Published frozen canonical vectors for the verification contracts.
2902
+ *
2903
+ * Each vector is a minimal valid value whose canonical digest is deterministic
2904
+ * and reproducible. These vectors lock the canonicalization rules (D6) in place.
2905
+ * Changing any vector's expected digest would be a reviewed contract change.
2906
+ */
2907
+ export const VERIFICATION_CANONICAL_VECTORS = Object.freeze([
2908
+ Object.freeze({
2909
+ contract: VERIFICATION_PLAN_CONTRACT_ID,
2910
+ digest: "43ba52cb34490733f0f37dd6407f7c5ab088f20d928837213a75a25b7bc3eb80",
2911
+ description: "minimal valid VerificationPlan v1 (single fast command)",
2912
+ }),
2913
+ Object.freeze({
2914
+ contract: VERIFICATION_RECEIPT_CONTRACT_ID,
2915
+ digest: "c3d244efadf9d6ae8aa8626f8e252246ed63205eef3f4604b7ba5be2f8bc210d",
2916
+ description: "minimal valid VerificationReceipt v1 (single passed result)",
2917
+ }),
2918
+ ]);
2919
+ // ---------------------------------------------------------------------------
2920
+ // Pre-execution evidence contracts (feature 28) — the published surface
2921
+ // ---------------------------------------------------------------------------
2922
+ /**
2923
+ * Re-exported so a consumer imports ONE package root for every contract family.
2924
+ * The implementation lives in `pre-execution.ts`; the structural definition stays
2925
+ * package-internal, exactly as the verification family's does, and the generated
2926
+ * Draft-07 files are projections of it, not a second authority.
2927
+ */
2928
+ export { buildPreExecutionArtifactSnapshot, canonicalizePreExecutionArtifactSnapshot, canonicalizePreExecutionReviewReceipt, comparePreExecutionReceiptToSnapshot, digestPreExecutionArtifactSnapshot, digestPreExecutionReviewReceipt, selectSpecProduct, validatePreExecutionArtifactSnapshotV1, validatePreExecutionReceiptAgainstSnapshot, validatePreExecutionReviewReceiptV1, PRE_EXECUTION_ARTIFACT_KINDS, PRE_EXECUTION_AUTHOR_EXCLUSIONS, PRE_EXECUTION_CANONICAL_VECTORS, PRE_EXECUTION_CONTEXT_KINDS, PRE_EXECUTION_CONTEXT_PRESENCE, PRE_EXECUTION_DIAGNOSTIC_CODES, PRE_EXECUTION_FINDING_CLASSES, PRE_EXECUTION_FINDING_RESOLUTIONS, PRE_EXECUTION_FINDING_SEVERITIES, PRE_EXECUTION_FINDING_VERIFICATION, PRE_EXECUTION_FRESHNESS_CODES, PRE_EXECUTION_LIMITS, PRE_EXECUTION_MODEL_DIVERSITY, PRE_EXECUTION_PARENT_ROLES, PRE_EXECUTION_RECEIPT_CONTRACT_ID, PRE_EXECUTION_REVIEW_ROLES, PRE_EXECUTION_RUNTIME_RULES, PRE_EXECUTION_SELECTORS, PRE_EXECUTION_SNAPSHOT_CONTRACT_ID, PRE_EXECUTION_SNAPSHOT_SELECTOR, PRE_EXECUTION_STAGES, PRE_EXECUTION_UNIT_KINDS, PRE_EXECUTION_VERDICTS, SPEC_PRODUCT_REQUIRED_HEADINGS, } from "./pre-execution.js";