@gtrabanco/agentic-workflow-schema 3.4.0 → 4.0.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,43 @@
1
+ /**
2
+ * SHA-256 for the package's digest surface.
3
+ *
4
+ * Two entry points over one implementation contract:
5
+ * - `sha256Hex` (async, Web Crypto) — the historical path the published candidate
6
+ * and verification digests use;
7
+ * - `sha256HexSync` — the same function over the same bytes, needed because
8
+ * `buildPreExecutionArtifactSnapshot` derives digests from caller-supplied
9
+ * document text in ONE synchronous pass (feature 28 AC2): a builder that had
10
+ * to await per artifact row would either force the whole pre-execution API
11
+ * async or hash the wrong bytes when a caller mutated content mid-flight.
12
+ * Since the fold of F67 the pre-execution family uses the SYNC path end to end —
13
+ * builder, canonicalizers, digests, blessing and freshness comparator answer in
14
+ * one calling style, because a half-async family forces `await` ceremony on every
15
+ * caller of a contract whose bytes are already in hand.
16
+ *
17
+ * Both return one identical lowercase 64-hex digest for identical bytes:
18
+ * `test/pre-execution-canonical.test.mjs` pins that agreement over an
19
+ * ASCII/multibyte/oversized corpus — the async path against `node:crypto` and,
20
+ * since feature 28 P17, the host-native sync path, the pure-JS sync path and the
21
+ * WebCrypto async path against each other — so no path can silently drift.
22
+ */
23
+ /**
24
+ * FIPS 180-4 SHA-256 over raw bytes. The message-schedule buffer is reused across
25
+ * every 64-byte block of ONE call, and the padded tail is written into a scratch
26
+ * block instead of copying the whole message. The buffers themselves are allocated
27
+ * per call (`h`, `w`, the padding block, the digest): what this function keeps
28
+ * allocation-free is the per-block work, not the repeated hashing across calls
29
+ * (C9, P16 fold — the sentence used to claim the latter, which is the kind of
30
+ * comment↔code drift this unit's own AC15 exists to refuse).
31
+ */
32
+ export declare function sha256Bytes(message: Uint8Array): Uint8Array;
33
+ /**
34
+ * Lowercase 64-hex SHA-256 of UTF-8 bytes, computed without awaiting.
35
+ *
36
+ * Routed: the host's native SHA-256 where the host exposes one, this package's
37
+ * pure-JS FIPS 180-4 core otherwise. Both branches hash the same UTF-8 bytes
38
+ * and emit the same lowercase 64-hex string — the guarantee AC21 states and the
39
+ * three-path case in `test/pre-execution-canonical.test.mjs` pins.
40
+ */
41
+ export declare function sha256HexSync(data: string): string;
42
+ /** D4 — SHA-256 hex digest (async via Web Crypto). Same bytes as the sync path. */
43
+ export declare function sha256Hex(data: string): Promise<string>;
package/dist/sha256.js ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * SHA-256 for the package's digest surface.
3
+ *
4
+ * Two entry points over one implementation contract:
5
+ * - `sha256Hex` (async, Web Crypto) — the historical path the published candidate
6
+ * and verification digests use;
7
+ * - `sha256HexSync` — the same function over the same bytes, needed because
8
+ * `buildPreExecutionArtifactSnapshot` derives digests from caller-supplied
9
+ * document text in ONE synchronous pass (feature 28 AC2): a builder that had
10
+ * to await per artifact row would either force the whole pre-execution API
11
+ * async or hash the wrong bytes when a caller mutated content mid-flight.
12
+ * Since the fold of F67 the pre-execution family uses the SYNC path end to end —
13
+ * builder, canonicalizers, digests, blessing and freshness comparator answer in
14
+ * one calling style, because a half-async family forces `await` ceremony on every
15
+ * caller of a contract whose bytes are already in hand.
16
+ *
17
+ * Both return one identical lowercase 64-hex digest for identical bytes:
18
+ * `test/pre-execution-canonical.test.mjs` pins that agreement over an
19
+ * ASCII/multibyte/oversized corpus — the async path against `node:crypto` and,
20
+ * since feature 28 P17, the host-native sync path, the pure-JS sync path and the
21
+ * WebCrypto async path against each other — so no path can silently drift.
22
+ */
23
+ const K = [
24
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
25
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
26
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
27
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
28
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
29
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
30
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
31
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
32
+ ];
33
+ const HEX = "0123456789abcdef";
34
+ const _encoder = new TextEncoder();
35
+ function rotr(x, n) {
36
+ return (x >>> n) | (x << (32 - n));
37
+ }
38
+ /**
39
+ * FIPS 180-4 SHA-256 over raw bytes. The message-schedule buffer is reused across
40
+ * every 64-byte block of ONE call, and the padded tail is written into a scratch
41
+ * block instead of copying the whole message. The buffers themselves are allocated
42
+ * per call (`h`, `w`, the padding block, the digest): what this function keeps
43
+ * allocation-free is the per-block work, not the repeated hashing across calls
44
+ * (C9, P16 fold — the sentence used to claim the latter, which is the kind of
45
+ * comment↔code drift this unit's own AC15 exists to refuse).
46
+ */
47
+ export function sha256Bytes(message) {
48
+ const h = new Uint32Array([
49
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
50
+ ]);
51
+ const w = new Uint32Array(64);
52
+ // The contract's own ceilings (4 MiB per artifact, 64 KiB per payload) keep the
53
+ // length in the low 32 bits, so the high word is always 0 here; it is computed
54
+ // rather than assumed so a future budget raise cannot truncate the padding.
55
+ const bitLengthHigh = Math.floor(message.length / 0x20000000);
56
+ const bitLengthLow = (message.length % 0x20000000) * 8;
57
+ const compress = (block, offset) => {
58
+ for (let i = 0; i < 16; i++) {
59
+ const p = offset + i * 4;
60
+ w[i] = ((block[p] << 24) | (block[p + 1] << 16) | (block[p + 2] << 8) | block[p + 3]) >>> 0;
61
+ }
62
+ for (let i = 16; i < 64; i++) {
63
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
64
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
65
+ w[i] = (w[i - 16] + (s0 >>> 0) + w[i - 7] + (s1 >>> 0)) >>> 0;
66
+ }
67
+ let [a, b, c, d, e, f, g, hh] = h;
68
+ for (let i = 0; i < 64; i++) {
69
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
70
+ const ch = ((e & f) ^ (~e & g)) >>> 0;
71
+ const temp1 = (hh + (S1 >>> 0) + ch + K[i] + w[i]) >>> 0;
72
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
73
+ const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0;
74
+ const temp2 = ((S0 >>> 0) + maj) >>> 0;
75
+ hh = g;
76
+ g = f;
77
+ f = e;
78
+ e = (d + temp1) >>> 0;
79
+ d = c;
80
+ c = b;
81
+ b = a;
82
+ a = (temp1 + temp2) >>> 0;
83
+ }
84
+ h[0] = (h[0] + a) >>> 0;
85
+ h[1] = (h[1] + b) >>> 0;
86
+ h[2] = (h[2] + c) >>> 0;
87
+ h[3] = (h[3] + d) >>> 0;
88
+ h[4] = (h[4] + e) >>> 0;
89
+ h[5] = (h[5] + f) >>> 0;
90
+ h[6] = (h[6] + g) >>> 0;
91
+ h[7] = (h[7] + hh) >>> 0;
92
+ };
93
+ const fullBlocks = Math.floor(message.length / 64);
94
+ for (let i = 0; i < fullBlocks; i++)
95
+ compress(message, i * 64);
96
+ const tail = message.length % 64;
97
+ // One or two padding blocks: 0x80, zeros, then the 64-bit big-endian length.
98
+ const padLength = tail < 56 ? 64 : 128;
99
+ const pad = new Uint8Array(padLength);
100
+ pad.set(message.subarray(fullBlocks * 64), 0);
101
+ pad[tail] = 0x80;
102
+ pad[padLength - 8] = (bitLengthHigh >>> 24) & 0xff;
103
+ pad[padLength - 7] = (bitLengthHigh >>> 16) & 0xff;
104
+ pad[padLength - 6] = (bitLengthHigh >>> 8) & 0xff;
105
+ pad[padLength - 5] = bitLengthHigh & 0xff;
106
+ pad[padLength - 4] = (bitLengthLow >>> 24) & 0xff;
107
+ pad[padLength - 3] = (bitLengthLow >>> 16) & 0xff;
108
+ pad[padLength - 2] = (bitLengthLow >>> 8) & 0xff;
109
+ pad[padLength - 1] = bitLengthLow & 0xff;
110
+ for (let i = 0; i < padLength; i += 64)
111
+ compress(pad, i);
112
+ const out = new Uint8Array(32);
113
+ for (let i = 0; i < 8; i++) {
114
+ out[i * 4] = (h[i] >>> 24) & 0xff;
115
+ out[i * 4 + 1] = (h[i] >>> 16) & 0xff;
116
+ out[i * 4 + 2] = (h[i] >>> 8) & 0xff;
117
+ out[i * 4 + 3] = h[i] & 0xff;
118
+ }
119
+ return out;
120
+ }
121
+ /**
122
+ * The native path, or `null` when this host exposes none.
123
+ *
124
+ * Sourced through `globalThis.process?.getBuiltinModule?.("crypto")` — the
125
+ * presence-check AC21 names — because the package targets browsers too and may
126
+ * be bundled by a toolchain that leaves `crypto` un-resolvable. The duck-typed
127
+ * `NativeCrypto` interface above is what keeps that lookup type-checked without
128
+ * a static `node:` specifier and without `@types/node` (AC21).
129
+ *
130
+ * Deliberately NOT cached in a module-level variable: a host that answers once
131
+ * can stop answering later (bundle moved between runtimes, the builtin
132
+ * unregistered), and a cached verdict — either way — is a wrong-host assumption
133
+ * that would either strand Node on the JS path or throw in a browser. The
134
+ * lookup is three `typeof` checks and one guarded call; measured against the
135
+ * digest it costs, caching is not worth the risk (unit 28 D36).
136
+ */
137
+ function nativeSha256() {
138
+ const host = globalThis;
139
+ const getBuiltinModule = host.process?.getBuiltinModule;
140
+ if (typeof getBuiltinModule !== "function")
141
+ return null;
142
+ let builtin;
143
+ try {
144
+ builtin = getBuiltinModule.call(host.process, "crypto");
145
+ }
146
+ catch {
147
+ return null;
148
+ }
149
+ if (typeof builtin !== "object" || builtin === null)
150
+ return null;
151
+ const createHash = builtin.createHash;
152
+ if (typeof createHash !== "function")
153
+ return null;
154
+ return (bytes) => builtin.createHash("sha256").update(bytes).digest();
155
+ }
156
+ function toHex(bytes) {
157
+ let out = "";
158
+ for (const byte of bytes)
159
+ out += HEX[byte >> 4] + HEX[byte & 0x0f];
160
+ return out;
161
+ }
162
+ /**
163
+ * Lowercase 64-hex SHA-256 of UTF-8 bytes, computed without awaiting.
164
+ *
165
+ * Routed: the host's native SHA-256 where the host exposes one, this package's
166
+ * pure-JS FIPS 180-4 core otherwise. Both branches hash the same UTF-8 bytes
167
+ * and emit the same lowercase 64-hex string — the guarantee AC21 states and the
168
+ * three-path case in `test/pre-execution-canonical.test.mjs` pins.
169
+ */
170
+ export function sha256HexSync(data) {
171
+ const bytes = _encoder.encode(data);
172
+ const native = nativeSha256();
173
+ if (native !== null) {
174
+ try {
175
+ return toHex(native(bytes));
176
+ }
177
+ catch {
178
+ // The binding was there a moment ago and failed now: answer from the
179
+ // JS core rather than propagating a host error out of a digest.
180
+ }
181
+ }
182
+ return toHex(sha256Bytes(bytes));
183
+ }
184
+ /** D4 — SHA-256 hex digest (async via Web Crypto). Same bytes as the sync path. */
185
+ export async function sha256Hex(data) {
186
+ const buf = _encoder.encode(data);
187
+ const hashBuffer = await crypto.subtle.digest("SHA-256", buf);
188
+ return toHex(new Uint8Array(hashBuffer));
189
+ }
@@ -61,25 +61,62 @@ export interface VerificationFieldSpec {
61
61
  readonly rules?: readonly VerificationPatternRule[];
62
62
  }
63
63
  export type VerificationRuleKind = "exactly-one-non-null" | "null-when" | "non-null-when" | "unique" | "timestamp-order" | "calendar-roundtrip"
64
- /** `fields` must stay ≤ `maximum` while `when` holds (stage-scoped ceiling). */
64
+ /** `fields` must stay ≤ `maximum` while `when` holds (a numeric field's value or an array field's length). */
65
65
  | "maximum-when"
66
66
  /** Sum of `fields` over `collection` items matching `when` stays ≤ `maximum`. */
67
- | "stage-aggregate-budget";
67
+ | "stage-aggregate-budget"
68
+ /** `collection` must be `uniqueItems` as a Draft-07 floor (a family may enforce a stronger key offline). */
69
+ | "unique-items"
70
+ /**
71
+ * While `when` holds, each field in `fields` must be one of `values`. This is the
72
+ * one form of "a sibling field narrows my vocabulary" Draft 07 can state, so a
73
+ * consumer's editor refuses e.g. a SPEC-stage receipt carrying a Plan verdict
74
+ * instead of letting it pass a structural validation it cannot survive.
75
+ */
76
+ | "enum-when";
77
+ /** One predicate over a sibling field's value. */
78
+ export interface VerificationWhenCondition {
79
+ readonly field: string;
80
+ readonly equals?: string;
81
+ readonly in?: readonly string[];
82
+ readonly notIn?: readonly string[];
83
+ /** Predicate holds while the sibling array carries at least this many rows. */
84
+ readonly minItems?: number;
85
+ }
68
86
  /** Cross-field rule declared once; projected whenever Draft-07 can express it. */
69
87
  export interface VerificationCrossRule {
70
88
  readonly id: string;
71
89
  readonly description: string;
72
- /** D16 code to report instead of this kind's default (see `CROSS_RULE_DEFAULT_CODE`). */
73
- readonly code?: VerificationDiagnosticCodeV1;
90
+ /**
91
+ * D16 code to report instead of this kind's default (see `CROSS_RULE_DEFAULT_CODE`).
92
+ * A contract family may pin one of its OWN codes here (the pre-execution family
93
+ * pins `invalid-topology`), so the declared type accepts any string while the
94
+ * shared engine keeps its closed vocabulary for the codes it emits itself.
95
+ */
96
+ readonly code?: VerificationDiagnosticCodeV1 | (string & {});
74
97
  /** false → enforced by the authoritative validator only, disclosed in the projection. */
75
98
  readonly projectable: boolean;
99
+ /**
100
+ * Where the runtime enforces the rule. Default `"walk"`: every structural pass
101
+ * (so a well-formedness validator refuses it too). `"binding"` marks a rule a
102
+ * well-formed document may violate — the projection still renders it, but only
103
+ * the family's binding authority (which blesses a verdict) applies it, so a
104
+ * recorded topology a plain review carried is refused exactly where it would
105
+ * be acted on.
106
+ */
107
+ readonly enforcement?: "walk" | "binding";
76
108
  readonly kind: VerificationRuleKind;
77
- /** Predicate over a sibling field's value. */
78
- readonly when?: {
79
- readonly field: string;
80
- readonly equals?: string;
81
- readonly in?: readonly string[];
82
- readonly notIn?: readonly string[];
109
+ /**
110
+ * Predicate over a sibling field's value, or the conjunction of several under
111
+ * `allOf`. The conjunction exists because one real rule is discriminated by TWO
112
+ * siblings at once (`parentSpecSnapshotDigest` is required when `stage == plan`
113
+ * AND `unitKind == feature` — finding RS14); a family that needs to name the
114
+ * discriminator it fired on — `exactly-one-non-null` and `stage-aggregate-budget`
115
+ * report a row at `<when.field>` — stays on the single-condition form, because no
116
+ * single field names a conjunction.
117
+ */
118
+ readonly when?: VerificationWhenCondition | {
119
+ readonly allOf: readonly VerificationWhenCondition[];
83
120
  };
84
121
  /** Constrained fields (`exactly-one-non-null`, `null-when`, `non-null-when`, timestamp/ calendar rules). */
85
122
  readonly fields?: readonly string[];
@@ -87,6 +124,8 @@ export interface VerificationCrossRule {
87
124
  readonly collection?: string;
88
125
  /** `maximum-when` / `stage-aggregate-budget` — the declared ceiling. */
89
126
  readonly maximum?: number;
127
+ /** `enum-when` — the only values each `fields` entry may take while `when` holds. */
128
+ readonly values?: readonly string[];
90
129
  }
91
130
  /** One contract object: its fields and its cross-field rules. */
92
131
  export interface VerificationObjectSpec {
@@ -210,6 +249,15 @@ export type VerificationInputCapture = {
210
249
  readonly pointer: string;
211
250
  };
212
251
  export declare function captureVerificationInput(value: unknown, budgetBytes?: number): VerificationInputCapture;
252
+ /**
253
+ * The `when` predicates of one rule as a list: the single-condition form is the
254
+ * one-element case, so every reader handles exactly one shape.
255
+ *
256
+ * A rule with no `when` applies unconditionally; `stage-aggregate-budget` and
257
+ * `exactly-one-non-null` report the discriminator they fired on, which only the
258
+ * single-condition form can name (see `VerificationCrossRule.when`).
259
+ */
260
+ export declare function whenConditions(when?: VerificationCrossRule["when"]): readonly VerificationWhenCondition[];
213
261
  /**
214
262
  * Validate one contract object against its spec, recording D16 diagnostics in
215
263
  * `sink`, and return its normalized own-property DTO — or `undefined` when
@@ -225,3 +273,22 @@ export declare function captureVerificationInput(value: unknown, budgetBytes?: n
225
273
  * echoing — the submitted value.
226
274
  */
227
275
  export declare function validateStructure(contract: VerificationContractSpec, spec: VerificationObjectSpec, value: unknown, path: string, sink: VerificationDiagnosticSink): Record<string, unknown> | undefined;
276
+ /**
277
+ * Apply one cross-field rule to a captured, normalized document. Exported for a
278
+ * family's binding authority, which re-applies the `binding`-enforcement rules
279
+ * the shared walk deliberately skipped.
280
+ */
281
+ export declare function applyCrossRule(spec: VerificationObjectSpec, rule: VerificationCrossRule, value: Record<string, unknown>, path: string, sink: VerificationDiagnosticSink): void;
282
+ /**
283
+ * Every cross rule that pins a diagnostic must pin a code the family publishes.
284
+ *
285
+ * `VerificationCrossRule.code` is widened to `string` on purpose — a contract family
286
+ * reports one of its OWN codes there — and `applyCrossRule` casts the value back to
287
+ * the closed code type without checking it, so the type said "closed vocabulary"
288
+ * while the runtime said nothing: a mistyped code, or one borrowed from another
289
+ * family, would reach a caller as a diagnostic no consumer can match (F71). This is
290
+ * the checked half of that cast, run against the declarations at load time, where
291
+ * the failure is a broken import rather than a wrong verdict. It answers the codes it
292
+ * verified so a caller can prove the scan was not vacuous.
293
+ */
294
+ export declare function assertCrossRuleVocabulary(contracts: Record<string, VerificationContractSpec>, vocabulary: readonly string[], owner: string): readonly string[];
@@ -14,6 +14,10 @@
14
14
  * published `exports` map does not expose it. The generated JSON Schemas are
15
15
  * structural projections of this definition, never a second semantic authority.
16
16
  */
17
+ // Function-level import (used only inside `applyCrossRule`, never at module
18
+ // init): the canonical serializer is the shared authority in
19
+ // `canonical-json.ts`, which itself imports this module's capture primitives.
20
+ import { canonicalJSONValue } from "./canonical-json.js";
17
21
  const NUL_MESSAGE = "must not contain NUL characters";
18
22
  const ISO_8601_PATTERN = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$";
19
23
  const LOWERCASE_64HEX_PATTERN = "^[a-f0-9]{64}$";
@@ -692,18 +696,42 @@ function verificationFieldSpec(spec, key) {
692
696
  return spec.fields.find((field) => field.key === key);
693
697
  }
694
698
  /**
695
- * True when a cross rule's `when` predicate matches the submitted sibling value.
699
+ * The `when` predicates of one rule as a list: the single-condition form is the
700
+ * one-element case, so every reader handles exactly one shape.
701
+ *
702
+ * A rule with no `when` applies unconditionally; `stage-aggregate-budget` and
703
+ * `exactly-one-non-null` report the discriminator they fired on, which only the
704
+ * single-condition form can name (see `VerificationCrossRule.when`).
705
+ */
706
+ export function whenConditions(when) {
707
+ if (!when)
708
+ return [];
709
+ return "allOf" in when ? when.allOf : [when];
710
+ }
711
+ /**
712
+ * True when a cross rule's `when` predicate(s) match the submitted siblings.
696
713
  *
697
714
  * `notIn` only fires for values inside the sibling's declared vocabulary, so a
698
- * garbage enum value yields one vocabulary error instead of a cascade.
715
+ * garbage enum value yields one vocabulary error instead of a cascade. A
716
+ * conjunction (`allOf`) holds when EVERY condition holds, and a condition whose
717
+ * sibling is absent does not hold — an incomplete document is refused by the
718
+ * field walk, never by a rule that silently treated the missing sibling as equal.
699
719
  */
700
720
  function ruleApplies(spec, rule, obj) {
701
- const when = rule.when;
702
- if (!when)
721
+ const conditions = whenConditions(rule.when);
722
+ if (conditions.length === 0)
703
723
  return true;
724
+ return conditions.every((when) => conditionApplies(spec, when, obj));
725
+ }
726
+ function conditionApplies(spec, when, obj) {
704
727
  if (!Object.prototype.hasOwnProperty.call(obj, when.field))
705
728
  return false;
706
729
  const value = obj[when.field];
730
+ // A `minItems` predicate reads an ARRAY sibling, not a string one; the two
731
+ // predicate families never mix on one rule.
732
+ if (when.minItems !== undefined) {
733
+ return Array.isArray(value) && value.length >= when.minItems;
734
+ }
707
735
  if (typeof value !== "string")
708
736
  return false;
709
737
  if (when.equals !== undefined)
@@ -967,6 +995,11 @@ function validateStructureFields(contract, spec, value, path, sink) {
967
995
  }
968
996
  }
969
997
  for (const rule of spec.rules) {
998
+ // Binding-only rules describe how a verdict may be ACTED ON, not what
999
+ // well-formed data is: the plain walk skips them, the binding authority
1000
+ // applies them explicitly over the same captured document.
1001
+ if (rule.enforcement === "binding")
1002
+ continue;
970
1003
  applyCrossRule(spec, rule, value, path, sink);
971
1004
  }
972
1005
  return sink.count() === before ? normalized : undefined;
@@ -981,9 +1014,16 @@ const CROSS_RULE_DEFAULT_CODE = Object.freeze({
981
1014
  "calendar-roundtrip": "invalid-value",
982
1015
  "maximum-when": "limit-exceeded",
983
1016
  "stage-aggregate-budget": "budget-exceeded",
1017
+ "unique-items": "duplicate-id",
1018
+ "enum-when": "invalid-value",
984
1019
  });
985
- function applyCrossRule(spec, rule, value, path, sink) {
986
- const code = rule.code ?? CROSS_RULE_DEFAULT_CODE[rule.kind];
1020
+ /**
1021
+ * Apply one cross-field rule to a captured, normalized document. Exported for a
1022
+ * family's binding authority, which re-applies the `binding`-enforcement rules
1023
+ * the shared walk deliberately skipped.
1024
+ */
1025
+ export function applyCrossRule(spec, rule, value, path, sink) {
1026
+ const code = (rule.code ?? CROSS_RULE_DEFAULT_CODE[rule.kind]);
987
1027
  const at = (key) => `${path}/${key}`;
988
1028
  switch (rule.kind) {
989
1029
  case "unique": {
@@ -1009,7 +1049,7 @@ function applyCrossRule(spec, rule, value, path, sink) {
1009
1049
  if (!ruleApplies(spec, rule, value))
1010
1050
  break;
1011
1051
  const fields = rule.fields ?? [];
1012
- const whenField = rule.when?.field ?? "";
1052
+ const whenField = whenConditions(rule.when)[0]?.field ?? "";
1013
1053
  const present = fields.filter((key) => Object.prototype.hasOwnProperty.call(value, key) && value[key] !== null);
1014
1054
  // One row at the discriminator: the combination of its value with the
1015
1055
  // nullness of `fields` is the violation, and D16 forbids naming the values.
@@ -1038,24 +1078,70 @@ function applyCrossRule(spec, rule, value, path, sink) {
1038
1078
  }
1039
1079
  break;
1040
1080
  }
1081
+ case "enum-when": {
1082
+ if (!ruleApplies(spec, rule, value))
1083
+ break;
1084
+ const allowed = rule.values ?? [];
1085
+ for (const key of rule.fields ?? []) {
1086
+ const raw = value[key];
1087
+ // A non-string is refused by the field's own type/vocabulary check; this
1088
+ // rule only narrows the set of well-formed values.
1089
+ if (typeof raw === "string" && !allowed.includes(raw))
1090
+ sink.push(code, at(key));
1091
+ }
1092
+ break;
1093
+ }
1041
1094
  case "maximum-when": {
1042
1095
  if (!ruleApplies(spec, rule, value))
1043
1096
  break;
1044
1097
  for (const key of rule.fields ?? []) {
1045
1098
  const raw = value[key];
1046
- if (typeof raw === "number" && rule.maximum !== undefined && raw > rule.maximum) {
1099
+ // A numeric field is compared by value; an array field by row count, so
1100
+ // one kind states both "at most N" shapes (e.g. an empty-array ceiling).
1101
+ const count = typeof raw === "number" ? raw : Array.isArray(raw) ? raw.length : undefined;
1102
+ if (count !== undefined && rule.maximum !== undefined && count > rule.maximum) {
1047
1103
  sink.push(code, at(key));
1048
1104
  }
1049
1105
  }
1050
1106
  break;
1051
1107
  }
1108
+ case "unique-items": {
1109
+ // The Draft-07 floor: no two rows of `collection` are the same VALUE. A
1110
+ // family that needs key-level uniqueness declares its own stronger rule
1111
+ // (the pre-execution receipt pins digest uniqueness beside this floor).
1112
+ const collectionName = rule.collection ?? "";
1113
+ const collection = Array.isArray(value[collectionName]) ? value[collectionName] : [];
1114
+ const seen = new Set();
1115
+ for (let i = 0; i < collection.length; i++) {
1116
+ const item = collection[i];
1117
+ if (!isPlainRecord(item))
1118
+ continue;
1119
+ // Canonical form, not JSON.stringify: two own-property copies of one
1120
+ // row may carry different key orders but must mean one identity. A row
1121
+ // outside the canonical domain is refused by the field walk anyway, so
1122
+ // it is skipped here instead of masking those rows with a throw.
1123
+ let key;
1124
+ try {
1125
+ key = canonicalJSONValue(item);
1126
+ }
1127
+ catch {
1128
+ continue;
1129
+ }
1130
+ if (seen.has(key))
1131
+ sink.push(code, `${at(collectionName)}/${i}`);
1132
+ else
1133
+ seen.add(key);
1134
+ }
1135
+ break;
1136
+ }
1052
1137
  case "stage-aggregate-budget": {
1053
1138
  // Sum the stage's declared timeouts in declared order and report the ONE
1054
1139
  // command that crossed — the earliest pointer that explains the overflow.
1055
1140
  const collectionName = rule.collection ?? "";
1056
1141
  const collection = Array.isArray(value[collectionName]) ? value[collectionName] : [];
1057
- const discriminator = rule.when?.field ?? "";
1058
- const stage = rule.when?.equals ?? "";
1142
+ const discriminatorCondition = whenConditions(rule.when)[0];
1143
+ const discriminator = discriminatorCondition?.field ?? "";
1144
+ const stage = discriminatorCondition?.equals ?? "";
1059
1145
  const field = rule.fields?.[0] ?? "";
1060
1146
  const ceiling = rule.maximum;
1061
1147
  if (ceiling === undefined || !discriminator || !stage || !field)
@@ -1109,3 +1195,35 @@ function applyCrossRule(spec, rule, value, path, sink) {
1109
1195
  }
1110
1196
  }
1111
1197
  }
1198
+ /**
1199
+ * Every cross rule that pins a diagnostic must pin a code the family publishes.
1200
+ *
1201
+ * `VerificationCrossRule.code` is widened to `string` on purpose — a contract family
1202
+ * reports one of its OWN codes there — and `applyCrossRule` casts the value back to
1203
+ * the closed code type without checking it, so the type said "closed vocabulary"
1204
+ * while the runtime said nothing: a mistyped code, or one borrowed from another
1205
+ * family, would reach a caller as a diagnostic no consumer can match (F71). This is
1206
+ * the checked half of that cast, run against the declarations at load time, where
1207
+ * the failure is a broken import rather than a wrong verdict. It answers the codes it
1208
+ * verified so a caller can prove the scan was not vacuous.
1209
+ */
1210
+ export function assertCrossRuleVocabulary(contracts, vocabulary, owner) {
1211
+ const pinned = [];
1212
+ for (const [contractName, spec] of Object.entries(contracts)) {
1213
+ for (const object of [spec.root, ...Object.values(spec.objects)]) {
1214
+ for (const rule of object.rules) {
1215
+ if (rule.code === undefined)
1216
+ continue;
1217
+ if (!vocabulary.includes(rule.code)) {
1218
+ throw new TypeError(`${owner}/${contractName}: cross rule "${rule.id}" reports "${rule.code}", which ` +
1219
+ `the ${vocabulary.length}-code ${owner} vocabulary does not publish`);
1220
+ }
1221
+ pinned.push(rule.code);
1222
+ }
1223
+ }
1224
+ }
1225
+ return Object.freeze(pinned);
1226
+ }
1227
+ // The family declared in this file, checked against its own closed list. The
1228
+ // pre-execution family runs the same guard with its wider vocabulary.
1229
+ assertCrossRuleVocabulary(VERIFICATION_CONTRACT, VERIFICATION_DIAGNOSTIC_CODES, "verification");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/agentic-workflow-schema",
3
- "version": "3.4.0",
3
+ "version": "4.0.0",
4
4
  "description": "Versioned machine contracts, JSON Schemas, parsers, and deterministic document snapshots for agentic-workflow orchestration.",
5
5
  "keywords": [
6
6
  "agentic-workflow",
@@ -32,7 +32,9 @@
32
32
  "./candidate-snapshot.schema.json": "./candidate-snapshot.schema.json",
33
33
  "./review-receipt.schema.json": "./review-receipt.schema.json",
34
34
  "./verification-receipt.schema.json": "./verification-receipt.schema.json",
35
- "./verification-plan.schema.json": "./verification-plan.schema.json"
35
+ "./verification-plan.schema.json": "./verification-plan.schema.json",
36
+ "./pre-execution-artifact-snapshot.schema.json": "./pre-execution-artifact-snapshot.schema.json",
37
+ "./pre-execution-review-receipt.schema.json": "./pre-execution-review-receipt.schema.json"
36
38
  },
37
39
  "files": [
38
40
  "dist",
@@ -43,6 +45,8 @@
43
45
  "review-receipt.schema.json",
44
46
  "verification-receipt.schema.json",
45
47
  "verification-plan.schema.json",
48
+ "pre-execution-artifact-snapshot.schema.json",
49
+ "pre-execution-review-receipt.schema.json",
46
50
  "README.md",
47
51
  "README.es.md",
48
52
  "LICENSE"
@@ -59,9 +63,14 @@
59
63
  "prepublishOnly": "npm test",
60
64
  "check:verification-schemas": "tsc && node scripts/generate-verification-schemas.mjs --check",
61
65
  "check:verification-package": "node scripts/check-verification-package.mjs",
66
+ "check:pre-execution-schemas": "tsc && node scripts/generate-pre-execution-schemas.mjs --check",
67
+ "check:pre-execution-package": "node scripts/check-pre-execution-package.mjs",
68
+ "test:pre-execution-docs": "node --test test/pre-execution-docs.test.mjs",
62
69
  "bench:verification": "node scripts/bench-verification.mjs",
70
+ "probe:sha256-paths": "node scripts/probe-sha256-paths.mjs",
63
71
  "test:verification-docs": "node --test test/verification-docs.test.mjs",
64
- "gate:verification": "npm test && npm run check:verification-schemas && npm run check:verification-package && npm run test:verification-docs && npm run bench:verification -- --commands 128"
72
+ "gate:verification": "npm test && npm run check:verification-schemas && npm run check:verification-package && npm run test:verification-docs && npm run bench:verification -- --commands 128",
73
+ "gate:pre-execution": "npm test && npm run check:pre-execution-schemas && npm run check:pre-execution-package && npm run test:pre-execution-docs"
65
74
  },
66
75
  "devDependencies": {
67
76
  "ajv": "^8.20.0",