@gtrabanco/agentic-workflow-schema 3.4.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.
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Canonical JSON serialization primitives — the byte-level authority behind
3
+ * every digest in the package.
4
+ *
5
+ * Two domains, one walker:
6
+ * - `verification` (which the pre-execution contracts also use): a leaf
7
+ * outside the JSON data model is a NAMED refusal, so a digest can never be
8
+ * produced over a document the validators would refuse.
9
+ * - `legacy`: the 3.3.0 behaviour, kept byte-for-byte for the candidate-review
10
+ * family whose digests are already published in receipts. Non-finite numbers
11
+ * serialize as `null` there; that collision class stays on the legacy path
12
+ * and the cost is stated in `decisions.md`, not hidden.
13
+ *
14
+ * Extracted from the package root so the verification and pre-execution
15
+ * contracts share ONE serializer with the candidate family instead of restating
16
+ * it. Behaviour is unchanged and pinned by
17
+ * `test/fixtures/canonical-legacy-vectors.mjs` and the published vector sets.
18
+ */
19
+ import { type VerificationContractSpec } from "./verification-contract.js";
20
+ export type CanonicalLeafDomain = "legacy" | "verification";
21
+ /** Byte length of a string in UTF-8 — the only length any budget uses. */
22
+ export declare function utf8Bytes(text: string): number;
23
+ /**
24
+ * Unsigned UTF-8 byte comparison: the canonical ordering used for every ordered
25
+ * collection in the package (artifact paths, context identities, finding ids,
26
+ * acceptance inputs). JS's default string compare is code-unit order, which
27
+ * differs for non-ASCII, so it is never used for a digest input.
28
+ */
29
+ export declare function utf8ByteCompare(a: string, b: string): number;
30
+ /**
31
+ * D4/D6 — Canonical serialization of one value: object keys sorted, compact
32
+ * separators, and no formatting a second implementation could drift on.
33
+ */
34
+ export declare function canonicalJSONValue(v: unknown, domain?: CanonicalLeafDomain): string;
35
+ /**
36
+ * F91 — canonical serialization of a contract value, guarded by the contract's
37
+ * own ceilings.
38
+ *
39
+ * A digest must never be produced over a document the validators would refuse, so
40
+ * before any bytes are written this checks the declared-collection cardinality
41
+ * and the canonical byte budget, and it does both on ONE bounded capture of the
42
+ * input. Without the capture, the guard and the projection would read the same
43
+ * submission twice and an accessor that changes value could make a digest cover a
44
+ * document the guard never saw (F97/F99).
45
+ *
46
+ * A refusal is a named `TypeError` quoting only the violated limit — never the
47
+ * submitted content. `family`/`label` name the contract in the message
48
+ * (`verification plan`, `pre-execution receipt`) so the failure is self-locating.
49
+ * `budgetTag` optionally carries the decision tag a family pins on its byte
50
+ * budget (feature 26 pins `D14`; F91 asserts it), keeping each family's
51
+ * published message surface byte-identical across the shared serializer.
52
+ */
53
+ export declare function canonicalizeContractInput(value: unknown, contract: VerificationContractSpec, options: {
54
+ readonly collectionField: string;
55
+ readonly maxItems: number;
56
+ readonly budgetBytes: number;
57
+ readonly family: string;
58
+ readonly label: string;
59
+ readonly budgetTag?: string;
60
+ }): string;
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Canonical JSON serialization primitives — the byte-level authority behind
3
+ * every digest in the package.
4
+ *
5
+ * Two domains, one walker:
6
+ * - `verification` (which the pre-execution contracts also use): a leaf
7
+ * outside the JSON data model is a NAMED refusal, so a digest can never be
8
+ * produced over a document the validators would refuse.
9
+ * - `legacy`: the 3.3.0 behaviour, kept byte-for-byte for the candidate-review
10
+ * family whose digests are already published in receipts. Non-finite numbers
11
+ * serialize as `null` there; that collision class stays on the legacy path
12
+ * and the cost is stated in `decisions.md`, not hidden.
13
+ *
14
+ * Extracted from the package root so the verification and pre-execution
15
+ * contracts share ONE serializer with the candidate family instead of restating
16
+ * it. Behaviour is unchanged and pinned by
17
+ * `test/fixtures/canonical-legacy-vectors.mjs` and the published vector sets.
18
+ */
19
+ import { captureVerificationInput, projectStructure, } from "./verification-contract.js";
20
+ const _utf8Encoder = new TextEncoder();
21
+ /** Byte length of a string in UTF-8 — the only length any budget uses. */
22
+ export function utf8Bytes(text) {
23
+ return _utf8Encoder.encode(text).length;
24
+ }
25
+ /**
26
+ * Unsigned UTF-8 byte comparison: the canonical ordering used for every ordered
27
+ * collection in the package (artifact paths, context identities, finding ids,
28
+ * acceptance inputs). JS's default string compare is code-unit order, which
29
+ * differs for non-ASCII, so it is never used for a digest input.
30
+ */
31
+ export function utf8ByteCompare(a, b) {
32
+ const ba = _utf8Encoder.encode(a);
33
+ const bb = _utf8Encoder.encode(b);
34
+ const len = Math.min(ba.length, bb.length);
35
+ for (let i = 0; i < len; i++) {
36
+ const diff = ba[i] - bb[i];
37
+ if (diff !== 0)
38
+ return diff;
39
+ }
40
+ return ba.length - bb.length;
41
+ }
42
+ /**
43
+ * D4/D6 — Canonical serialization of one value: object keys sorted, compact
44
+ * separators, and no formatting a second implementation could drift on.
45
+ */
46
+ export function canonicalJSONValue(v, domain = "verification") {
47
+ if (v === null)
48
+ return "null";
49
+ const kind = typeof v;
50
+ if (kind === "string")
51
+ return JSON.stringify(v);
52
+ if (kind === "number") {
53
+ if (!Number.isFinite(v)) {
54
+ if (domain === "verification") {
55
+ throw new TypeError(`canonical JSON: unsupported leaf (non-finite ${kind})`);
56
+ }
57
+ return JSON.stringify(v); // 3.3.0: NaN / ±Infinity serialize as `null`
58
+ }
59
+ return JSON.stringify(v);
60
+ }
61
+ if (kind === "boolean")
62
+ return JSON.stringify(v);
63
+ if (Array.isArray(v)) {
64
+ // An explicit arrow, never `.map(canonicalJSONValue)`: `map` would pass the
65
+ // element INDEX as the domain, silently selecting the legacy fallback for
66
+ // every array leaf.
67
+ return "[" + v.map((item) => canonicalJSONValue(item, domain)).join(",") + "]";
68
+ }
69
+ if (kind === "object") {
70
+ const keys = Object.keys(v).sort();
71
+ return "{" + keys.map(k => JSON.stringify(k) + ":" + canonicalJSONValue(v[k], domain)).join(",") + "}";
72
+ }
73
+ if (domain === "verification") {
74
+ throw new TypeError(`canonical JSON: unsupported leaf (${kind})`);
75
+ }
76
+ return JSON.stringify(v);
77
+ }
78
+ /**
79
+ * F91 — canonical serialization of a contract value, guarded by the contract's
80
+ * own ceilings.
81
+ *
82
+ * A digest must never be produced over a document the validators would refuse, so
83
+ * before any bytes are written this checks the declared-collection cardinality
84
+ * and the canonical byte budget, and it does both on ONE bounded capture of the
85
+ * input. Without the capture, the guard and the projection would read the same
86
+ * submission twice and an accessor that changes value could make a digest cover a
87
+ * document the guard never saw (F97/F99).
88
+ *
89
+ * A refusal is a named `TypeError` quoting only the violated limit — never the
90
+ * submitted content. `family`/`label` name the contract in the message
91
+ * (`verification plan`, `pre-execution receipt`) so the failure is self-locating.
92
+ * `budgetTag` optionally carries the decision tag a family pins on its byte
93
+ * budget (feature 26 pins `D14`; F91 asserts it), keeping each family's
94
+ * published message surface byte-identical across the shared serializer.
95
+ */
96
+ export function canonicalizeContractInput(value, contract, options) {
97
+ const { collectionField, maxItems, budgetBytes, family, label, budgetTag } = options;
98
+ const budgetName = budgetTag ? `${budgetTag} ${budgetBytes}-byte` : `${budgetBytes}-byte`;
99
+ const submitted = captureVerificationInput(value, budgetBytes);
100
+ if (!submitted.ok) {
101
+ throw new TypeError(submitted.code === "limit-exceeded"
102
+ ? // The capture measured the canonical form past the budget — the same
103
+ // refusal F91 names, reached before the serializer could finish it.
104
+ `${family} ${label} canonical form exceeds the ${budgetName} budget — validate before canonicalizing`
105
+ : `${family} ${label} input is not a readable JSON document — validate before canonicalizing`);
106
+ }
107
+ const document = submitted.value;
108
+ if (document !== null && typeof document === "object") {
109
+ const items = document[collectionField];
110
+ if (Array.isArray(items) && items.length > maxItems) {
111
+ throw new TypeError(`${family} ${label} exceeds the limit of at most ${maxItems} ${collectionField} — validate before canonicalizing`);
112
+ }
113
+ }
114
+ const canonical = canonicalJSONValue(projectStructure(contract, contract.root, document));
115
+ if (utf8Bytes(canonical) > budgetBytes) {
116
+ throw new TypeError(`${family} ${label} canonical form exceeds the ${budgetName} budget — validate before canonicalizing`);
117
+ }
118
+ return canonical;
119
+ }
package/dist/index.d.ts CHANGED
@@ -172,7 +172,7 @@ export type StrictEnvelopeParseResult = {
172
172
  };
173
173
  /** Extract, parse, and validate the strict driver-facing v2 envelope. */
174
174
  export declare function parseEnvelopeV2Strict(text: string): StrictEnvelopeParseResult;
175
- export type WorkflowIntent = "init-workspace" | "status" | "discover-repository-state" | "resolve-repository-state" | "design-feature" | "plan-feature" | "plan-fix" | "triage-issue" | "execute-phase" | "review-change" | "loop-review-fold" | "audit-pr" | "merge" | "ask-human" | "stop" | "none";
175
+ export type WorkflowIntent = "init-workspace" | "status" | "discover-repository-state" | "resolve-repository-state" | "design-feature" | "review-spec" | "plan-feature" | "review-plan" | "plan-fix" | "triage-issue" | "execute-phase" | "review-change" | "loop-review-fold" | "audit-pr" | "merge" | "ask-human" | "stop" | "none";
176
176
  export declare const WORKFLOW_INTENTS: readonly WorkflowIntent[];
177
177
  /** Sense reason codes: transition cannot proceed without more sensor input. */
178
178
  export declare const WORKFLOW_DECISION_SENSE_CODES: readonly ["sense-initial", "sense-stale-revision", "sense-missing-evidence", "sense-unknown-state", "sense-unlisted-transition"];
@@ -277,7 +277,7 @@ export type SkillReasoning = (typeof SKILL_REASONING)[number];
277
277
  export declare const SKILL_CONTEXT_SOURCES: readonly ["repository", "semantic-context", "episodic-memory", "execution-state"];
278
278
  export type SkillContextSource = (typeof SKILL_CONTEXT_SOURCES)[number];
279
279
  /** Evidence a capability-aware driver should require before trusting results. */
280
- export declare const SKILL_REQUIRED_EVIDENCE: readonly ["workflow-snapshot", "current-candidate", "verification", "independent-review", "audit", "issue-state", "pull-request-state"];
280
+ export declare const SKILL_REQUIRED_EVIDENCE: readonly ["workflow-snapshot", "current-candidate", "verification", "independent-review", "audit", "issue-state", "pull-request-state", "pre-execution-review"];
281
281
  export type SkillRequiredEvidence = (typeof SKILL_REQUIRED_EVIDENCE)[number];
282
282
  /**
283
283
  * Declarative, closed-vocabulary capability metadata for a built-in profile.
@@ -881,3 +881,11 @@ export declare function compareVerificationReceiptToCurrent(receipt: Verificatio
881
881
  * Changing any vector's expected digest would be a reviewed contract change.
882
882
  */
883
883
  export declare const VERIFICATION_CANONICAL_VECTORS: ReadonlyArray<Readonly<CanonicalVectorV1>>;
884
+ /**
885
+ * Re-exported so a consumer imports ONE package root for every contract family.
886
+ * The implementation lives in `pre-execution.ts`; the structural definition stays
887
+ * package-internal, exactly as the verification family's does, and the generated
888
+ * Draft-07 files are projections of it, not a second authority.
889
+ */
890
+ 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";
891
+ export type { PreExecutionArtifactInput, PreExecutionArtifactKind, PreExecutionArtifactRow, PreExecutionArtifactSnapshotV1, PreExecutionAuthorExclusion, PreExecutionCanonicalVector, PreExecutionContextBinding, PreExecutionContextInput, PreExecutionContextKind, PreExecutionContextPresence, PreExecutionDiagnostic, PreExecutionDiagnosticCode, PreExecutionFinding, PreExecutionFindingClass, PreExecutionFindingResolution, PreExecutionFindingSeverity, PreExecutionFindingVerification, PreExecutionFreshnessCode, PreExecutionFreshnessResult, PreExecutionModelDiversity, PreExecutionParentReceipt, PreExecutionParentRole, PreExecutionReceiptValidationResult, PreExecutionReviewReceiptV1, PreExecutionReviewerRole, PreExecutionSelector, PreExecutionSnapshotBuildInput, PreExecutionSnapshotValidationResult, PreExecutionStage, PreExecutionUnitKind, PreExecutionVerdict, SpecProductSelection, SpecProductSelectorError, } from "./pre-execution.js";
package/dist/index.js CHANGED
@@ -8,7 +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 { 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
+ 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";
12
14
  // ---------------------------------------------------------------------------
13
15
  // Types (source of truth: this package; the internal skill carries policy only)
14
16
  // ---------------------------------------------------------------------------
@@ -449,7 +451,9 @@ export const WORKFLOW_INTENTS = [
449
451
  "discover-repository-state",
450
452
  "resolve-repository-state",
451
453
  "design-feature",
454
+ "review-spec",
452
455
  "plan-feature",
456
+ "review-plan",
453
457
  "plan-fix",
454
458
  "triage-issue",
455
459
  "execute-phase",
@@ -527,7 +531,9 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
527
531
  "discover-repository-state",
528
532
  "resolve-repository-state",
529
533
  "design-feature",
534
+ "review-spec",
530
535
  "plan-feature",
536
+ "review-plan",
531
537
  "plan-fix",
532
538
  "triage-issue",
533
539
  "execute-phase",
@@ -545,7 +551,9 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
545
551
  allowed: [
546
552
  "resolve-repository-state",
547
553
  "design-feature",
554
+ "review-spec",
548
555
  "plan-feature",
556
+ "review-plan",
549
557
  "plan-fix",
550
558
  "triage-issue",
551
559
  "execute-phase",
@@ -569,6 +577,7 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
569
577
  {
570
578
  key: "design-feature",
571
579
  allowed: [
580
+ "review-spec",
572
581
  "plan-feature",
573
582
  "plan-fix",
574
583
  "triage-issue",
@@ -583,10 +592,28 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
583
592
  + " or the named dependency unit recorded by the last outcome;"
584
593
  + " non-allowed target → stop-forbidden-transition",
585
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
+ },
586
612
  // plan-feature → active or dependency unit, max 1
587
613
  {
588
614
  key: "plan-feature",
589
615
  allowed: [
616
+ "review-plan",
590
617
  "triage-issue",
591
618
  "execute-phase",
592
619
  "review-change",
@@ -598,12 +625,31 @@ export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
598
625
  condition: "0..1 allowed; 0 → next roadmap unit; 1 → active unit id or named dependency;"
599
626
  + ">1 → stop-forbidden-transition",
600
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
+ },
601
647
  // plan-fix → triage-issue only, exactly 1
602
648
  {
603
649
  key: "plan-fix",
604
- allowed: ["triage-issue"],
605
- condition: "exactly 1 target (the issue identity); 0 → sense-missing-evidence;"
606
- + ">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",
607
653
  },
608
654
  // triage-issue → issue identities, 1..n
609
655
  {
@@ -905,6 +951,7 @@ export const SKILL_REQUIRED_EVIDENCE = Object.freeze([
905
951
  "audit",
906
952
  "issue-state",
907
953
  "pull-request-state",
954
+ "pre-execution-review",
908
955
  ]);
909
956
  /** Recursively freezes exported metadata so runtime widening is impossible. */
910
957
  function deepFreeze(value) {
@@ -981,6 +1028,20 @@ export const WORKFLOW_SKILL_PROFILES = deepFreeze([
981
1028
  requiredEvidence: ["workflow-snapshot"],
982
1029
  },
983
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
+ },
984
1045
  {
985
1046
  skill: "plan-feature",
986
1047
  output: "skill-outcome-v1",
@@ -993,6 +1054,18 @@ export const WORKFLOW_SKILL_PROFILES = deepFreeze([
993
1054
  requiredEvidence: ["workflow-snapshot"],
994
1055
  },
995
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
+ },
996
1069
  {
997
1070
  skill: "plan-fix",
998
1071
  output: "skill-outcome-v1",
@@ -1866,22 +1939,6 @@ function isGitObjectId(v) {
1866
1939
  function hasUndeclaredKeys(actual, known) {
1867
1940
  return Object.keys(actual).filter((k) => !known.includes(k));
1868
1941
  }
1869
- /**
1870
- * Compare two UTF-8 strings in ascending unsigned-byte order.
1871
- * Returns < 0 if a < b, > 0 if a > b, 0 if equal.
1872
- */
1873
- const _utf8Encoder = new TextEncoder();
1874
- function utf8ByteCompare(a, b) {
1875
- const ba = _utf8Encoder.encode(a);
1876
- const bb = _utf8Encoder.encode(b);
1877
- const len = Math.min(ba.length, bb.length);
1878
- for (let i = 0; i < len; i++) {
1879
- const diff = ba[i] - bb[i];
1880
- if (diff !== 0)
1881
- return diff;
1882
- }
1883
- return ba.length - bb.length;
1884
- }
1885
1942
  /**
1886
1943
  * Structural validation of a CandidateSnapshot v1.
1887
1944
  * Rejects undeclared fields, enforces GitObjectId format, path-byte ordering,
@@ -2218,49 +2275,9 @@ export const STALE_REASON_CODES = [
2218
2275
  "stale-acceptance-fingerprint",
2219
2276
  "stale-review-policy",
2220
2277
  ];
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") {
2233
- if (v === null)
2234
- return "null";
2235
- const kind = typeof v;
2236
- if (kind === "string")
2237
- return JSON.stringify(v);
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
- }
2245
- return JSON.stringify(v);
2246
- }
2247
- if (kind === "boolean")
2248
- return JSON.stringify(v);
2249
- if (Array.isArray(v)) {
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(",") + "]";
2254
- }
2255
- if (kind === "object") {
2256
- const keys = Object.keys(v).sort();
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})`);
2261
- }
2262
- return JSON.stringify(v);
2263
- }
2278
+ // ---------------------------------------------------------------------------
2279
+ // D4 — Canonical serialization helpers
2280
+ // ---------------------------------------------------------------------------
2264
2281
  /**
2265
2282
  * D4 — Canonicalize a CandidateSnapshotV1.
2266
2283
  * Produces deterministic JSON with declaration-order keys and sorted changedPaths.
@@ -2301,16 +2318,6 @@ export function canonicalizeReviewReceipt(receipt) {
2301
2318
  };
2302
2319
  return canonicalJSONValue(obj, "legacy");
2303
2320
  }
2304
- // ---------------------------------------------------------------------------
2305
- // SHA-256 hashing
2306
- // ---------------------------------------------------------------------------
2307
- /** D4 — SHA-256 hex digest (async via Web Crypto). */
2308
- async function sha256Hex(data) {
2309
- const buf = _utf8Encoder.encode(data);
2310
- const hashBuffer = await crypto.subtle.digest("SHA-256", buf);
2311
- const hashArray = new Uint8Array(hashBuffer);
2312
- return Array.from(hashArray).map(b => b.toString(16).padStart(2, "0")).join("");
2313
- }
2314
2321
  /** D4 — Digest a CandidateSnapshotV1 via canonical serialization. */
2315
2322
  export async function digestCandidateSnapshot(snapshot) {
2316
2323
  return sha256Hex(canonicalizeCandidateSnapshot(snapshot));
@@ -2452,10 +2459,6 @@ export { VERIFICATION_LIMITS };
2452
2459
  * the list is not the whole story.
2453
2460
  */
2454
2461
  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
2462
  /**
2460
2463
  * D14 canonical payload budget (F77), measured BEFORE any diagnostic is
2461
2464
  * allocated, so a wide document is refused by the budget alone instead of
@@ -2777,43 +2780,24 @@ export function deriveVerificationVerdict(receipt, plan) {
2777
2780
  return deriveVerdictUnchecked(rv.receipt, pv.plan);
2778
2781
  }
2779
2782
  /**
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.
2783
+ * D6 — Canonical serialization of a verification contract, shared by both sides.
2785
2784
  *
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.
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.
2791
2789
  */
2792
2790
  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;
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
+ });
2817
2801
  }
2818
2802
  /**
2819
2803
  * D6 — Canonical serialization of a validated `VerificationPlan v1`. The
@@ -2932,3 +2916,13 @@ export const VERIFICATION_CANONICAL_VECTORS = Object.freeze([
2932
2916
  description: "minimal valid VerificationReceipt v1 (single passed result)",
2933
2917
  }),
2934
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";