@gtrabanco/agentic-workflow-schema 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1111 @@
1
+ /**
2
+ * Canonical internal definition of the two staged-verification contracts.
3
+ *
4
+ * This module is the SINGLE source of the VerificationPlan v1 /
5
+ * VerificationReceipt v1 structural contract: the closed field lists,
6
+ * vocabularies, bounds, patterns and cross-field rules declared here are
7
+ * consumed by
8
+ * - runtime validation (`validateStructure` below, used by the two public
9
+ * authoritative entries in `index.ts`), and
10
+ * - the deterministic Draft-07 structural projection generator
11
+ * (`scripts/generate-verification-schemas.mjs`).
12
+ *
13
+ * It is package-internal: it is not re-exported from the package root and the
14
+ * published `exports` map does not expose it. The generated JSON Schemas are
15
+ * structural projections of this definition, never a second semantic authority.
16
+ */
17
+ const NUL_MESSAGE = "must not contain NUL characters";
18
+ const ISO_8601_PATTERN = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$";
19
+ const LOWERCASE_64HEX_PATTERN = "^[a-f0-9]{64}$";
20
+ /** Contract ids, declared once; the package root re-exports them publicly. */
21
+ export const VERIFICATION_PLAN_CONTRACT_ID = "agentic-workflow/verification-plan@1";
22
+ export const VERIFICATION_RECEIPT_CONTRACT_ID = "agentic-workflow/verification-receipt@1";
23
+ /** Closed vocabularies, declared once; the root re-exports them publicly. */
24
+ export const VERIFICATION_STAGES = Object.freeze(["fast", "full"]);
25
+ export const VERIFICATION_COST_CLASSES = Object.freeze(["cheap", "moderate", "expensive"]);
26
+ export const VERIFICATION_COMMAND_STATUSES = Object.freeze(["passed", "failed", "timed-out", "skipped", "infrastructure-error"]);
27
+ export const VERIFICATION_VERDICTS = Object.freeze(["pass", "fail", "incomplete"]);
28
+ export const WORKING_DIRECTORY_POLICIES = ["candidate-root", "relative-path"];
29
+ /**
30
+ * D14 — bounded usability: the SHAPE ceilings (cardinality + string length).
31
+ *
32
+ * Every number the validator enforces is read from this object, and the same
33
+ * object is published publicly so a consumer can size fixtures without
34
+ * restating a literal. `VERIFICATION_LIMITS` is extended with the payload
35
+ * budgets by P11 and the timeout budgets by P12; the canonical plan/receipt
36
+ * byte budgets and the aggregate stage sums are enforced at runtime and are
37
+ * listed here once those phases land.
38
+ */
39
+ export const VERIFICATION_LIMITS = Object.freeze({
40
+ commands: 128,
41
+ results: 128,
42
+ argsPerCommand: 64,
43
+ idChars: 128,
44
+ pathChars: 1024,
45
+ argChars: 4096,
46
+ skipReasonChars: 1024,
47
+ evidenceRefChars: 1024,
48
+ planBytes: 256 * 1024,
49
+ receiptBytes: 512 * 1024,
50
+ // D14 time bounds, in milliseconds: 10/15 minutes for the fast stage and
51
+ // 60/120 minutes for the full stage (per command / whole stage).
52
+ fastCommandTimeoutMs: 10 * 60_000,
53
+ fastStageTimeoutMs: 15 * 60_000,
54
+ fullCommandTimeoutMs: 60 * 60_000,
55
+ fullStageTimeoutMs: 120 * 60_000,
56
+ diagnostics: 50,
57
+ });
58
+ /**
59
+ * D16 — the closed diagnostic vocabulary. Every validation failure row carries
60
+ * exactly one of these codes plus an RFC 6901 path; adding a code is a reviewed,
61
+ * versioned contract change, and no code ever names the submitted value.
62
+ */
63
+ export const VERIFICATION_DIAGNOSTIC_CODES = Object.freeze([
64
+ "invalid-type",
65
+ "missing-field",
66
+ "unknown-field",
67
+ "invalid-value",
68
+ "limit-exceeded",
69
+ "duplicate-id",
70
+ "unknown-command",
71
+ "invalid-order",
72
+ "invalid-stage",
73
+ "invalid-exit-state",
74
+ "invalid-evidence",
75
+ "invalid-skip",
76
+ "invalid-fail-fast",
77
+ "digest-mismatch",
78
+ "verdict-mismatch",
79
+ "budget-exceeded",
80
+ ]);
81
+ export function createVerificationDiagnosticSink(limit = VERIFICATION_LIMITS.diagnostics) {
82
+ const rows = [];
83
+ let dropped = 0;
84
+ return {
85
+ push(code, path) {
86
+ if (rows.length < limit)
87
+ rows.push({ code, path });
88
+ else
89
+ dropped += 1;
90
+ },
91
+ count() {
92
+ return rows.length + dropped;
93
+ },
94
+ finish() {
95
+ return {
96
+ diagnostics: Object.freeze(rows.map((row) => Object.freeze({ code: row.code, path: row.path }))),
97
+ truncated: dropped > 0,
98
+ };
99
+ },
100
+ };
101
+ }
102
+ // ---------------------------------------------------------------------------
103
+ // VerificationPlan v1
104
+ // ---------------------------------------------------------------------------
105
+ const COMMAND_SPEC = {
106
+ description: "A single verification command within a plan.",
107
+ fields: [
108
+ {
109
+ key: "id",
110
+ type: "string",
111
+ minLength: 1,
112
+ maxLength: VERIFICATION_LIMITS.idChars,
113
+ nulFree: true,
114
+ description: `Stable, non-empty, NUL-free, at most ${VERIFICATION_LIMITS.idChars} chars, unique within the plan.`,
115
+ },
116
+ { key: "stage", type: "enum", enum: VERIFICATION_STAGES, description: "Verification stage." },
117
+ {
118
+ key: "executable",
119
+ type: "string",
120
+ minLength: 1,
121
+ maxLength: VERIFICATION_LIMITS.pathChars,
122
+ nulFree: true,
123
+ description: `Non-empty executable path; NUL-free, at most ${VERIFICATION_LIMITS.pathChars} chars. Never a shell string.`,
124
+ },
125
+ {
126
+ key: "args",
127
+ type: "stringArray",
128
+ itemNulFree: true,
129
+ maxItems: VERIFICATION_LIMITS.argsPerCommand,
130
+ itemMaxLength: VERIFICATION_LIMITS.argChars,
131
+ description: `Ordered arguments; at most ${VERIFICATION_LIMITS.argsPerCommand} items, each NUL-free and at most ${VERIFICATION_LIMITS.argChars} chars.`,
132
+ },
133
+ {
134
+ key: "workingDirectoryPolicy",
135
+ type: "enum",
136
+ enum: WORKING_DIRECTORY_POLICIES,
137
+ description: "Working directory policy.",
138
+ },
139
+ {
140
+ key: "workingDirectory",
141
+ type: "nullable",
142
+ nullableOf: "string",
143
+ minLength: 1,
144
+ maxLength: VERIFICATION_LIMITS.pathChars,
145
+ nulFree: true,
146
+ rules: [
147
+ { regex: "^(?!/)", message: 'must not be an absolute path (leading "/")' },
148
+ { regex: "^(?![A-Za-z]:)", message: "must not be a Windows drive-letter path" },
149
+ { regex: "^(?!.*\\\\)", message: "must not contain backslashes" },
150
+ { regex: "^(?!.*(\\/|^)\\.\\.($|\\/))", message: 'must not contain ".." segments (path traversal)' },
151
+ ],
152
+ description: "Null iff candidate-root; validated relative path iff relative-path.",
153
+ },
154
+ {
155
+ key: "timeoutMs",
156
+ type: "integer",
157
+ exclusiveMinimum: 0,
158
+ // The stage-independent ceiling; `fast-command-timeout` tightens it for the
159
+ // fast stage, exactly as the projection's conditional fragment does (AC10).
160
+ maximum: VERIFICATION_LIMITS.fullCommandTimeoutMs,
161
+ description: `Positive integer timeout in milliseconds; at most ${VERIFICATION_LIMITS.fullCommandTimeoutMs} (full stage) or ${VERIFICATION_LIMITS.fastCommandTimeoutMs} (fast stage).`,
162
+ },
163
+ {
164
+ key: "stopOnFailure",
165
+ type: "boolean",
166
+ description: "Whether to stop executing subsequent commands on failure.",
167
+ },
168
+ {
169
+ key: "costClass",
170
+ type: "enum",
171
+ enum: VERIFICATION_COST_CLASSES,
172
+ description: "Project-declared cost class.",
173
+ },
174
+ ],
175
+ rules: [
176
+ {
177
+ id: "working-directory-null-at-root",
178
+ kind: "null-when",
179
+ projectable: true,
180
+ when: { field: "workingDirectoryPolicy", equals: "candidate-root" },
181
+ fields: ["workingDirectory"],
182
+ description: "workingDirectory is null when workingDirectoryPolicy is candidate-root.",
183
+ },
184
+ {
185
+ id: "fast-command-timeout",
186
+ kind: "maximum-when",
187
+ projectable: true,
188
+ when: { field: "stage", equals: "fast" },
189
+ fields: ["timeoutMs"],
190
+ maximum: VERIFICATION_LIMITS.fastCommandTimeoutMs,
191
+ description: `A fast-stage command times out within ${VERIFICATION_LIMITS.fastCommandTimeoutMs} ms (D14).`,
192
+ },
193
+ {
194
+ id: "working-directory-set-for-relative-path",
195
+ kind: "non-null-when",
196
+ projectable: true,
197
+ when: { field: "workingDirectoryPolicy", equals: "relative-path" },
198
+ fields: ["workingDirectory"],
199
+ description: "workingDirectory is a validated relative path when workingDirectoryPolicy is relative-path.",
200
+ },
201
+ ],
202
+ };
203
+ // ---------------------------------------------------------------------------
204
+ // VerificationReceipt v1
205
+ // ---------------------------------------------------------------------------
206
+ const EVIDENCE_SPEC = {
207
+ description: "Bounded reference to captured evidence (stdout/stderr output).",
208
+ fields: [
209
+ {
210
+ key: "ref",
211
+ type: "string",
212
+ minLength: 1,
213
+ maxLength: VERIFICATION_LIMITS.evidenceRefChars,
214
+ nulFree: true,
215
+ violationCode: "invalid-evidence",
216
+ description: "Non-empty opaque pointer to stored evidence; NUL-free.",
217
+ },
218
+ {
219
+ key: "bytes",
220
+ type: "integer",
221
+ minimum: 0,
222
+ description: "Size of the captured evidence in bytes.",
223
+ },
224
+ {
225
+ key: "sha256",
226
+ type: "string",
227
+ pattern: LOWERCASE_64HEX_PATTERN,
228
+ violationCode: "invalid-evidence",
229
+ description: "Lowercase 64-hex SHA-256 digest of the captured evidence.",
230
+ },
231
+ ],
232
+ rules: [],
233
+ };
234
+ const RESULT_SPEC = {
235
+ description: "Per-command verification result.",
236
+ fields: [
237
+ {
238
+ key: "commandId",
239
+ type: "string",
240
+ minLength: 1,
241
+ maxLength: VERIFICATION_LIMITS.idChars,
242
+ nulFree: true,
243
+ description: `Must exist in the bound plan's commands; NUL-free, at most ${VERIFICATION_LIMITS.idChars} chars.`,
244
+ },
245
+ {
246
+ key: "status",
247
+ type: "enum",
248
+ enum: VERIFICATION_COMMAND_STATUSES,
249
+ description: "The terminal status of this command execution.",
250
+ },
251
+ {
252
+ key: "exitCode",
253
+ type: "nullable",
254
+ nullableOf: "integer",
255
+ description: "Per the D4 exit-code/signal matrix.",
256
+ },
257
+ {
258
+ key: "signal",
259
+ type: "nullable",
260
+ nullableOf: "string",
261
+ minLength: 1,
262
+ // F50 hardening, not a D14 limit: the SPEC's ceiling list does not name
263
+ // `signal`, so this bound stays local to the field it protects.
264
+ maxLength: 1024,
265
+ nulFree: true,
266
+ description: "Per the D4 exit-code/signal matrix; NUL-free, at most 1024 chars.",
267
+ },
268
+ {
269
+ key: "startedAt",
270
+ type: "string",
271
+ pattern: ISO_8601_PATTERN,
272
+ description: "ISO-8601 UTC start timestamp.",
273
+ },
274
+ {
275
+ key: "endedAt",
276
+ type: "string",
277
+ pattern: ISO_8601_PATTERN,
278
+ description: "ISO-8601 UTC end timestamp, >= startedAt.",
279
+ },
280
+ {
281
+ key: "stdout",
282
+ type: "nullable",
283
+ nullableOf: "object",
284
+ specName: "EvidenceReferenceV1",
285
+ description: "Bounded stdout evidence reference or null.",
286
+ },
287
+ {
288
+ key: "stderr",
289
+ type: "nullable",
290
+ nullableOf: "object",
291
+ specName: "EvidenceReferenceV1",
292
+ description: "Bounded stderr evidence reference or null.",
293
+ },
294
+ {
295
+ key: "skipReason",
296
+ type: "nullable",
297
+ nullableOf: "string",
298
+ minLength: 1,
299
+ maxLength: VERIFICATION_LIMITS.skipReasonChars,
300
+ nulFree: true,
301
+ description: "Null on non-skipped rows; non-empty NUL-free string ≤ 1024 chars on skipped.",
302
+ },
303
+ ],
304
+ rules: [
305
+ {
306
+ id: "d4-exactly-one-terminal-result",
307
+ kind: "exactly-one-non-null",
308
+ projectable: true,
309
+ when: { field: "status", in: ["passed", "failed"] },
310
+ fields: ["exitCode", "signal"],
311
+ description: "D4 exit-code/signal matrix: passed/failed carry exactly one of exitCode (integer) or signal (non-empty string).",
312
+ },
313
+ {
314
+ id: "d4-timed-out-has-no-exit-code",
315
+ kind: "null-when",
316
+ projectable: true,
317
+ code: "invalid-exit-state",
318
+ when: { field: "status", equals: "timed-out" },
319
+ fields: ["exitCode"],
320
+ description: "D4: timed-out carries exitCode null and an optional captured kill signal.",
321
+ },
322
+ {
323
+ id: "d4-no-terminal-result",
324
+ kind: "null-when",
325
+ projectable: true,
326
+ code: "invalid-exit-state",
327
+ when: { field: "status", in: ["infrastructure-error", "skipped"] },
328
+ fields: ["exitCode", "signal"],
329
+ description: "D4: infrastructure-error and skipped carry neither exitCode nor signal.",
330
+ },
331
+ {
332
+ id: "skip-reason-only-when-skipped",
333
+ kind: "null-when",
334
+ projectable: true,
335
+ code: "invalid-skip",
336
+ when: { field: "status", notIn: ["skipped"] },
337
+ fields: ["skipReason"],
338
+ description: "Non-skipped rows carry skipReason null.",
339
+ },
340
+ {
341
+ id: "timestamp-order",
342
+ kind: "timestamp-order",
343
+ projectable: false,
344
+ fields: ["startedAt", "endedAt"],
345
+ description: "endedAt must not precede startedAt.",
346
+ },
347
+ {
348
+ id: "timestamp-calendar-valid",
349
+ kind: "calendar-roundtrip",
350
+ projectable: false,
351
+ fields: ["startedAt", "endedAt"],
352
+ description: "ISO-8601 timestamps must be calendar-valid (rejects 2025-99-99T99:99:99Z).",
353
+ },
354
+ ],
355
+ };
356
+ /** VerificationPlan v1 root object: `contract` + non-empty `commands`. */
357
+ const PLAN_ROOT_SPEC = {
358
+ description: "An ordered, non-empty command list for staged verification (fast/full).",
359
+ fields: [
360
+ {
361
+ key: "contract",
362
+ type: "const",
363
+ value: VERIFICATION_PLAN_CONTRACT_ID,
364
+ description: "Contract identifier.",
365
+ },
366
+ {
367
+ key: "commands",
368
+ type: "array",
369
+ specName: "VerificationCommandV1",
370
+ minItems: 1,
371
+ maxItems: VERIFICATION_LIMITS.commands,
372
+ description: `Non-empty command list of at most ${VERIFICATION_LIMITS.commands} commands, in declared order.`,
373
+ },
374
+ ],
375
+ rules: [
376
+ {
377
+ id: "unique-command-ids",
378
+ kind: "unique",
379
+ projectable: false,
380
+ collection: "commands",
381
+ fields: ["id"],
382
+ description: "Command ids are unique within the plan.",
383
+ },
384
+ {
385
+ id: "fast-stage-aggregate-budget",
386
+ kind: "stage-aggregate-budget",
387
+ projectable: false,
388
+ collection: "commands",
389
+ when: { field: "stage", equals: "fast" },
390
+ fields: ["timeoutMs"],
391
+ maximum: VERIFICATION_LIMITS.fastStageTimeoutMs,
392
+ description: `Declared fast-stage timeouts sum to at most ${VERIFICATION_LIMITS.fastStageTimeoutMs} ms (D14).`,
393
+ },
394
+ {
395
+ id: "full-stage-aggregate-budget",
396
+ kind: "stage-aggregate-budget",
397
+ projectable: false,
398
+ collection: "commands",
399
+ when: { field: "stage", equals: "full" },
400
+ fields: ["timeoutMs"],
401
+ maximum: VERIFICATION_LIMITS.fullStageTimeoutMs,
402
+ description: `Declared full-stage timeouts sum to at most ${VERIFICATION_LIMITS.fullStageTimeoutMs} ms (D14).`,
403
+ },
404
+ ],
405
+ };
406
+ /** VerificationReceipt v1 root object. */
407
+ const RECEIPT_ROOT_SPEC = {
408
+ description: "A verification receipt bound to a plan, candidate snapshot, and acceptance fingerprint.",
409
+ fields: [
410
+ {
411
+ key: "contract",
412
+ type: "const",
413
+ value: VERIFICATION_RECEIPT_CONTRACT_ID,
414
+ description: "Contract identifier.",
415
+ },
416
+ {
417
+ key: "planDigest",
418
+ type: "string",
419
+ pattern: LOWERCASE_64HEX_PATTERN,
420
+ description: "Lowercase 64-hex SHA-256 digest of the bound plan.",
421
+ },
422
+ {
423
+ key: "candidateSnapshotDigest",
424
+ type: "string",
425
+ pattern: LOWERCASE_64HEX_PATTERN,
426
+ description: "Lowercase 64-hex SHA-256 from #138's candidate-snapshot digest.",
427
+ },
428
+ {
429
+ key: "acceptanceFingerprint",
430
+ type: "string",
431
+ pattern: LOWERCASE_64HEX_PATTERN,
432
+ description: "Lowercase 64-hex acceptance fingerprint from #138.",
433
+ },
434
+ { key: "stageRequested", type: "enum", enum: VERIFICATION_STAGES, description: "Which stage was requested." },
435
+ {
436
+ key: "results",
437
+ type: "array",
438
+ specName: "VerificationResultV1",
439
+ maxItems: VERIFICATION_LIMITS.results,
440
+ description: `Ordered per-command results; at most ${VERIFICATION_LIMITS.results} rows in declared order.`,
441
+ },
442
+ {
443
+ key: "verdict",
444
+ type: "enum",
445
+ enum: VERIFICATION_VERDICTS,
446
+ description: "Must equal deriveVerificationVerdict.",
447
+ },
448
+ ],
449
+ rules: [
450
+ {
451
+ id: "unique-result-command-ids",
452
+ kind: "unique",
453
+ projectable: false,
454
+ collection: "results",
455
+ fields: ["commandId"],
456
+ description: "Each declared command carries at most one result row.",
457
+ },
458
+ ],
459
+ };
460
+ export const VERIFICATION_CONTRACT = Object.freeze({
461
+ plan: Object.freeze({
462
+ contractId: VERIFICATION_PLAN_CONTRACT_ID,
463
+ fileName: "verification-plan.schema.json",
464
+ title: "VerificationPlan v1",
465
+ description: "An ordered, non-empty command list for staged verification (fast/full).",
466
+ authority: "validateVerificationPlanV1",
467
+ rootLabel: "plan",
468
+ root: PLAN_ROOT_SPEC,
469
+ objects: Object.freeze({ VerificationCommandV1: COMMAND_SPEC }),
470
+ }),
471
+ receipt: Object.freeze({
472
+ contractId: VERIFICATION_RECEIPT_CONTRACT_ID,
473
+ fileName: "verification-receipt.schema.json",
474
+ title: "VerificationReceipt v1",
475
+ description: "A verification receipt bound to a plan, candidate snapshot, and acceptance fingerprint.",
476
+ authority: "validateVerificationReceiptAgainstPlan",
477
+ rootLabel: "receipt",
478
+ root: RECEIPT_ROOT_SPEC,
479
+ objects: Object.freeze({
480
+ EvidenceReferenceV1: EVIDENCE_SPEC,
481
+ VerificationResultV1: RESULT_SPEC,
482
+ }),
483
+ }),
484
+ });
485
+ /**
486
+ * Non-validating own-property projection of a contract value.
487
+ *
488
+ * `canonicalize*`/`digest*` run this first so a digest always describes the
489
+ * normalized DTO — never an accidental prototype value or an undeclared field.
490
+ * It performs no checks (callers validate first) and copies only declared own
491
+ * properties, so the walk is one pass with no regex and no error buffers.
492
+ */
493
+ export function projectStructure(contract, spec, value) {
494
+ if (!isPlainRecord(value))
495
+ return value;
496
+ const projected = {};
497
+ for (const field of spec.fields) {
498
+ if (!Object.prototype.hasOwnProperty.call(value, field.key))
499
+ continue;
500
+ const raw = value[field.key];
501
+ if (field.type === "array") {
502
+ const nested = verificationObjectSpec(contract, field.specName ?? "");
503
+ projected[field.key] = Array.isArray(raw)
504
+ ? raw.map((item) => projectStructure(contract, nested, item))
505
+ : raw;
506
+ }
507
+ else if (field.type === "nullable" && field.nullableOf === "object" && raw !== null) {
508
+ const nested = verificationObjectSpec(contract, field.specName ?? "");
509
+ projected[field.key] = projectStructure(contract, nested, raw);
510
+ }
511
+ else {
512
+ projected[field.key] = raw;
513
+ }
514
+ }
515
+ return projected;
516
+ }
517
+ /** Nested object spec by `$defs` name. */
518
+ function verificationObjectSpec(contract, defName) {
519
+ const spec = contract.objects[defName];
520
+ if (!spec)
521
+ throw new Error(`unknown verification object ${defName}`);
522
+ return spec;
523
+ }
524
+ /** A JSON object literal (or null-prototype object) — never an array or a class instance. */
525
+ function isPlainRecord(value) {
526
+ if (typeof value !== "object" || value === null || Array.isArray(value))
527
+ return false;
528
+ const proto = Object.getPrototypeOf(value);
529
+ return proto === Object.prototype || proto === null;
530
+ }
531
+ /**
532
+ * F97 — the submitted accessor that cannot be observed as plain data.
533
+ *
534
+ * Carries the RFC 6901 pointer of the frame that owns the failing read plus the
535
+ * D16 code that frame earns: `invalid-type` for a walk failure (F92 parity) or
536
+ * `limit-exceeded` for the canonical byte budget (F99). The message never names
537
+ * the submitted key or value.
538
+ */
539
+ class VerificationInputCaptureError extends Error {
540
+ pointer;
541
+ code;
542
+ constructor(pointer, code = "invalid-type") {
543
+ super(code === "limit-exceeded" ? "verification input: over canonical byte budget" : "verification input: unreadable accessor");
544
+ this.pointer = pointer;
545
+ this.code = code;
546
+ this.name = "VerificationInputCaptureError";
547
+ }
548
+ }
549
+ /** True when the fragment survives canonical serialization as pure ASCII. */
550
+ function isAscii(text) {
551
+ for (let index = 0; index < text.length; index += 1) {
552
+ if (text.charCodeAt(index) > 0x7f)
553
+ return false;
554
+ }
555
+ return true;
556
+ }
557
+ function charge(context, units) {
558
+ if (!context.applicable)
559
+ return;
560
+ context.size += units;
561
+ if (context.budget !== null && context.size > context.budget) {
562
+ throw new VerificationInputCaptureError("", "limit-exceeded");
563
+ }
564
+ }
565
+ /** UTF-16 length of a leaf's canonical fragment — the unit `canonicalJSONValue` emits. */
566
+ function canonicalLeafUnits(value) {
567
+ return JSON.stringify(value).length;
568
+ }
569
+ /**
570
+ * F97 — capture one submitted value as data, reading every accessor exactly once.
571
+ *
572
+ * Plain objects become own-enumerable-key copies, arrays become element copies, and
573
+ * every container is frozen, so no later pass can observe a different document than
574
+ * the one the entry decided on. Two submissions are deliberately NOT rewritten by the
575
+ * capture, because the structural walk — not the capture — owns every refusal:
576
+ * - a non-plain object (class instance, array-like prototype) is copied by
577
+ * reference, so its frame still refuses it as `invalid-type`;
578
+ * - an unsupported leaf (function, symbol, bigint, `undefined`, non-finite number)
579
+ * is copied as submitted, so the field check still refuses it.
580
+ * An accessor that throws is reported at the frame that owns the read.
581
+ */
582
+ function captureContractValue(value, pointer, context) {
583
+ if (value === null) {
584
+ charge(context, 4);
585
+ return null;
586
+ }
587
+ if (typeof value === "string") {
588
+ if (!context.nonAscii)
589
+ context.nonAscii = !isAscii(value);
590
+ charge(context, canonicalLeafUnits(value));
591
+ return value;
592
+ }
593
+ if (typeof value === "boolean") {
594
+ charge(context, canonicalLeafUnits(value));
595
+ return value;
596
+ }
597
+ if (typeof value === "number") {
598
+ if (!Number.isFinite(value)) {
599
+ // The canonical serializer has no form for it: the budget can no longer be
600
+ // measured exactly, and the walk owns the refusal (F91-era behaviour).
601
+ context.applicable = false;
602
+ return value;
603
+ }
604
+ charge(context, canonicalLeafUnits(value));
605
+ return value;
606
+ }
607
+ if (typeof value !== "object") {
608
+ // function / symbol / bigint / undefined — outside the canonical form.
609
+ context.applicable = false;
610
+ return value;
611
+ }
612
+ if (Array.isArray(value)) {
613
+ const items = [];
614
+ for (let index = 0; index < value.length; index += 1) {
615
+ let item;
616
+ try {
617
+ item = Object.freeze(captureContractValue(value[index], `${pointer}/${index}`, context));
618
+ }
619
+ catch (failure) {
620
+ throw failure instanceof VerificationInputCaptureError
621
+ ? failure
622
+ : new VerificationInputCaptureError(pointer);
623
+ }
624
+ items.push(item);
625
+ }
626
+ charge(context, 2 + Math.max(items.length - 1, 0));
627
+ return Object.freeze(items);
628
+ }
629
+ const proto = Object.getPrototypeOf(value);
630
+ if (proto !== Object.prototype && proto !== null) {
631
+ // Copied by reference; its canonical size is unknowable and its frame is
632
+ // refused by the walk, so the measure is no longer exact from here on.
633
+ context.applicable = false;
634
+ return value;
635
+ }
636
+ const source = value;
637
+ const keys = Object.keys(source);
638
+ const captured = {};
639
+ let keyUnits = 0;
640
+ for (const key of keys) {
641
+ let item;
642
+ try {
643
+ item = Object.freeze(captureContractValue(source[key], `${pointer}/${key}`, context));
644
+ }
645
+ catch (failure) {
646
+ // The frame that owns the read answers for it — the same pointer rule F92
647
+ // established for a walk failure, and it also bounds a self-referential
648
+ // submission (the recursion's RangeError lands on the frame that opened it).
649
+ throw failure instanceof VerificationInputCaptureError
650
+ ? failure
651
+ : new VerificationInputCaptureError(pointer);
652
+ }
653
+ if (!context.nonAscii)
654
+ context.nonAscii = !isAscii(key);
655
+ keyUnits += JSON.stringify(key).length + 1;
656
+ // `defineProperty`, never assignment: a submitted own `__proto__` key (what
657
+ // `JSON.parse` produces) is an ordinary data property, but plain assignment
658
+ // would hit the inherited `Object.prototype.__proto__` setter and drop the key
659
+ // the structural pass exists to refuse (P7).
660
+ Object.defineProperty(captured, key, {
661
+ value: item,
662
+ enumerable: true,
663
+ writable: false,
664
+ configurable: false,
665
+ });
666
+ }
667
+ charge(context, 2 + keyUnits + Math.max(keys.length - 1, 0));
668
+ return Object.freeze(captured);
669
+ }
670
+ export function captureVerificationInput(value, budgetBytes) {
671
+ const context = {
672
+ budget: budgetBytes ?? null,
673
+ size: 0,
674
+ applicable: true,
675
+ nonAscii: false,
676
+ };
677
+ try {
678
+ return {
679
+ ok: true,
680
+ value: Object.freeze(captureContractValue(value, "", context)),
681
+ measureExact: context.applicable && !context.nonAscii,
682
+ };
683
+ }
684
+ catch (failure) {
685
+ if (failure instanceof VerificationInputCaptureError) {
686
+ return { ok: false, code: failure.code, pointer: failure.pointer };
687
+ }
688
+ return { ok: false, code: "invalid-type", pointer: "" };
689
+ }
690
+ }
691
+ function verificationFieldSpec(spec, key) {
692
+ return spec.fields.find((field) => field.key === key);
693
+ }
694
+ /**
695
+ * True when a cross rule's `when` predicate matches the submitted sibling value.
696
+ *
697
+ * `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.
699
+ */
700
+ function ruleApplies(spec, rule, obj) {
701
+ const when = rule.when;
702
+ if (!when)
703
+ return true;
704
+ if (!Object.prototype.hasOwnProperty.call(obj, when.field))
705
+ return false;
706
+ const value = obj[when.field];
707
+ if (typeof value !== "string")
708
+ return false;
709
+ if (when.equals !== undefined)
710
+ return value === when.equals;
711
+ if (when.in !== undefined)
712
+ return when.in.includes(value);
713
+ if (when.notIn !== undefined) {
714
+ const vocabulary = verificationFieldSpec(spec, when.field)?.enum ?? [];
715
+ return vocabulary.includes(value) && !when.notIn.includes(value);
716
+ }
717
+ return false;
718
+ }
719
+ /**
720
+ * Diagnostic code for a value that is not the declared shape of `field`: a
721
+ * const/enum mismatch is a wrong VALUE of an otherwise correct type, everything
722
+ * else is a type failure. D16 keeps the row to code + path, so a submitted value
723
+ * is never carried out of the validator.
724
+ */
725
+ function typeCode(field) {
726
+ return field.type === "const" || field.type === "enum" ? "invalid-value" : "invalid-type";
727
+ }
728
+ /** Specialize a value-content failure to the field's own code (D5 evidence). */
729
+ function valueCode(field) {
730
+ return field.violationCode ?? "invalid-value";
731
+ }
732
+ /**
733
+ * Compiled-pattern memo.
734
+ *
735
+ * Every pattern validated here is declared once in the frozen field-spec table
736
+ * above, so re-parsing it per string field of every walked document was pure
737
+ * repeat work; the cache holds that fixed handful of entries for the process
738
+ * lifetime. Safe to share instances: these patterns are compiled without `g`/`y`,
739
+ * so `test()` carries no lastIndex state between calls.
740
+ */
741
+ const _compiledPatterns = new Map();
742
+ function compiledPattern(pattern) {
743
+ let re = _compiledPatterns.get(pattern);
744
+ if (re === undefined) {
745
+ re = new RegExp(pattern);
746
+ _compiledPatterns.set(pattern, re);
747
+ }
748
+ return re;
749
+ }
750
+ function checkString(field, value, path, sink) {
751
+ if (typeof value !== "string") {
752
+ sink.push(typeCode(field), path);
753
+ return undefined;
754
+ }
755
+ if (field.minLength !== undefined && value.length < field.minLength) {
756
+ sink.push("limit-exceeded", path);
757
+ return undefined;
758
+ }
759
+ if (field.nulFree && value.includes("\0")) {
760
+ sink.push(valueCode(field), path);
761
+ return undefined;
762
+ }
763
+ if (field.maxLength !== undefined && value.length > field.maxLength) {
764
+ sink.push("limit-exceeded", path);
765
+ }
766
+ if (field.pattern !== undefined && !compiledPattern(field.pattern).test(value)) {
767
+ sink.push(valueCode(field), path);
768
+ return undefined;
769
+ }
770
+ for (const rule of field.rules ?? []) {
771
+ if (!compiledPattern(rule.regex).test(value))
772
+ sink.push(valueCode(field), path);
773
+ }
774
+ return value;
775
+ }
776
+ function checkInteger(field, value, path, sink) {
777
+ if (typeof value !== "number" || !Number.isInteger(value)) {
778
+ sink.push("invalid-type", path);
779
+ return undefined;
780
+ }
781
+ // A declared bound that Draft-07 can express is a limit failure; the positivity
782
+ // rule for `timeoutMs` is a value rule, which is what the projection states as
783
+ // `exclusiveMinimum`.
784
+ if (field.exclusiveMinimum !== undefined && value <= field.exclusiveMinimum) {
785
+ sink.push("limit-exceeded", path);
786
+ return undefined;
787
+ }
788
+ if (field.minimum !== undefined && value < field.minimum) {
789
+ sink.push("limit-exceeded", path);
790
+ return undefined;
791
+ }
792
+ if (field.maximum !== undefined && value > field.maximum) {
793
+ sink.push("limit-exceeded", path);
794
+ return undefined;
795
+ }
796
+ return value;
797
+ }
798
+ /**
799
+ * Validate one contract object against its spec, recording D16 diagnostics in
800
+ * `sink`, and return its normalized own-property DTO — or `undefined` when
801
+ * anything in this object (or below it) failed.
802
+ *
803
+ * Only own properties of declared keys are read, so inherited or prototype
804
+ * values can never be mistaken for contract data; the returned object is a
805
+ * fresh plain literal, so mutating the input afterwards cannot change it.
806
+ *
807
+ * Every path is an RFC 6901 JSON Pointer built from declared contract property
808
+ * names and decimal array indices (`/commands/3/id`; `""` is the document root),
809
+ * so a diagnostic identifies the offending location without naming — let alone
810
+ * echoing — the submitted value.
811
+ */
812
+ export function validateStructure(contract, spec, value, path, sink) {
813
+ // F92 — the walk reads only declared keys of a JSON document (the input
814
+ // domain every public authority documents). An object outside that domain —
815
+ // a live getter that throws, not constructible by JSON.parse — must never
816
+ // smuggle an attacker-chosen exception past the D16 contract: the failure
817
+ // is refused here as exactly one redacted `invalid-type` row on this frame.
818
+ // Because the throw is caught by the frame that owns the read, nested rows
819
+ // report their own pointer (e.g. `/results/0`) and nothing else re-throws.
820
+ try {
821
+ return validateStructureFields(contract, spec, value, path, sink);
822
+ }
823
+ catch {
824
+ sink.push("invalid-type", path);
825
+ return undefined;
826
+ }
827
+ }
828
+ function validateStructureFields(contract, spec, value, path, sink) {
829
+ if (!isPlainRecord(value)) {
830
+ sink.push("invalid-type", path);
831
+ return undefined;
832
+ }
833
+ const before = sink.count();
834
+ const at = (key) => `${path}/${key}`;
835
+ for (const key of Object.keys(value)) {
836
+ if (!spec.fields.some((field) => field.key === key)) {
837
+ // The path names the CONTAINER, never the submitted key: an undeclared key
838
+ // is input data, and D16 allows only contract property names and indices in
839
+ // a pointer (so a probe like `__proto__` cannot echo itself back out).
840
+ sink.push("unknown-field", path);
841
+ }
842
+ }
843
+ const normalized = {};
844
+ for (const field of spec.fields) {
845
+ const fieldPath = at(field.key);
846
+ if (!Object.prototype.hasOwnProperty.call(value, field.key)) {
847
+ sink.push("missing-field", fieldPath);
848
+ continue;
849
+ }
850
+ const raw = value[field.key];
851
+ switch (field.type) {
852
+ case "const": {
853
+ if (raw !== field.value)
854
+ sink.push(valueCode(field), fieldPath);
855
+ else
856
+ normalized[field.key] = raw;
857
+ break;
858
+ }
859
+ case "enum": {
860
+ const vocabulary = field.enum ?? [];
861
+ if (!vocabulary.includes(raw))
862
+ sink.push(valueCode(field), fieldPath);
863
+ else
864
+ normalized[field.key] = raw;
865
+ break;
866
+ }
867
+ case "boolean": {
868
+ if (typeof raw !== "boolean")
869
+ sink.push("invalid-type", fieldPath);
870
+ else
871
+ normalized[field.key] = raw;
872
+ break;
873
+ }
874
+ case "string": {
875
+ const checked = checkString(field, raw, fieldPath, sink);
876
+ if (checked !== undefined)
877
+ normalized[field.key] = checked;
878
+ break;
879
+ }
880
+ case "integer": {
881
+ const checked = checkInteger(field, raw, fieldPath, sink);
882
+ if (checked !== undefined)
883
+ normalized[field.key] = checked;
884
+ break;
885
+ }
886
+ case "stringArray": {
887
+ if (!Array.isArray(raw)) {
888
+ sink.push("invalid-type", fieldPath);
889
+ break;
890
+ }
891
+ // Cardinality first: the ceiling is expressible in Draft-07, so the
892
+ // projection and this validator must agree (AC10).
893
+ if (field.maxItems !== undefined && raw.length > field.maxItems) {
894
+ sink.push("limit-exceeded", fieldPath);
895
+ break;
896
+ }
897
+ const items = [];
898
+ for (let i = 0; i < raw.length; i++) {
899
+ const item = raw[i];
900
+ if (typeof item !== "string") {
901
+ sink.push("invalid-type", `${fieldPath}/${i}`);
902
+ continue;
903
+ }
904
+ if (field.itemNulFree && item.includes("\0")) {
905
+ sink.push("invalid-value", `${fieldPath}/${i}`);
906
+ continue;
907
+ }
908
+ if (field.itemMaxLength !== undefined && item.length > field.itemMaxLength) {
909
+ sink.push("limit-exceeded", `${fieldPath}/${i}`);
910
+ continue;
911
+ }
912
+ items.push(item);
913
+ }
914
+ normalized[field.key] = items;
915
+ break;
916
+ }
917
+ case "array": {
918
+ const nested = verificationObjectSpec(contract, field.specName ?? "");
919
+ if (!Array.isArray(raw)) {
920
+ sink.push("invalid-type", fieldPath);
921
+ break;
922
+ }
923
+ if (field.minItems !== undefined && raw.length < field.minItems) {
924
+ sink.push("limit-exceeded", fieldPath);
925
+ break;
926
+ }
927
+ if (field.maxItems !== undefined && raw.length > field.maxItems) {
928
+ sink.push("limit-exceeded", fieldPath);
929
+ break;
930
+ }
931
+ const children = [];
932
+ for (let i = 0; i < raw.length; i++) {
933
+ const child = validateStructure(contract, nested, raw[i], `${fieldPath}/${i}`, sink);
934
+ if (child)
935
+ children.push(child);
936
+ }
937
+ normalized[field.key] = children;
938
+ break;
939
+ }
940
+ case "nullable": {
941
+ if (raw === null) {
942
+ normalized[field.key] = null;
943
+ break;
944
+ }
945
+ if (field.nullableOf === "string") {
946
+ const checked = checkString(field, raw, fieldPath, sink);
947
+ if (checked !== undefined)
948
+ normalized[field.key] = checked;
949
+ break;
950
+ }
951
+ if (field.nullableOf === "integer") {
952
+ const checked = checkInteger(field, raw, fieldPath, sink);
953
+ if (checked !== undefined)
954
+ normalized[field.key] = checked;
955
+ break;
956
+ }
957
+ if (!isPlainRecord(raw)) {
958
+ sink.push("invalid-type", fieldPath);
959
+ break;
960
+ }
961
+ const nested = verificationObjectSpec(contract, field.specName ?? "");
962
+ const child = validateStructure(contract, nested, raw, fieldPath, sink);
963
+ if (child)
964
+ normalized[field.key] = child;
965
+ break;
966
+ }
967
+ }
968
+ }
969
+ for (const rule of spec.rules) {
970
+ applyCrossRule(spec, rule, value, path, sink);
971
+ }
972
+ return sink.count() === before ? normalized : undefined;
973
+ }
974
+ /** Fallback code per rule kind; a spec may name a narrower one with `code`. */
975
+ const CROSS_RULE_DEFAULT_CODE = Object.freeze({
976
+ "exactly-one-non-null": "invalid-exit-state",
977
+ "null-when": "invalid-value",
978
+ "non-null-when": "invalid-value",
979
+ unique: "duplicate-id",
980
+ "timestamp-order": "invalid-value",
981
+ "calendar-roundtrip": "invalid-value",
982
+ "maximum-when": "limit-exceeded",
983
+ "stage-aggregate-budget": "budget-exceeded",
984
+ });
985
+ function applyCrossRule(spec, rule, value, path, sink) {
986
+ const code = rule.code ?? CROSS_RULE_DEFAULT_CODE[rule.kind];
987
+ const at = (key) => `${path}/${key}`;
988
+ switch (rule.kind) {
989
+ case "unique": {
990
+ const collectionName = rule.collection ?? "";
991
+ const collection = Array.isArray(value[collectionName]) ? value[collectionName] : [];
992
+ const field = rule.fields?.[0] ?? "";
993
+ const seen = new Set();
994
+ for (let i = 0; i < collection.length; i++) {
995
+ const item = collection[i];
996
+ if (!isPlainRecord(item))
997
+ continue;
998
+ const key = item[field];
999
+ if (typeof key !== "string" || key.length === 0)
1000
+ continue;
1001
+ if (seen.has(key))
1002
+ sink.push(code, `${at(collectionName)}/${i}/${field}`);
1003
+ else
1004
+ seen.add(key);
1005
+ }
1006
+ break;
1007
+ }
1008
+ case "exactly-one-non-null": {
1009
+ if (!ruleApplies(spec, rule, value))
1010
+ break;
1011
+ const fields = rule.fields ?? [];
1012
+ const whenField = rule.when?.field ?? "";
1013
+ const present = fields.filter((key) => Object.prototype.hasOwnProperty.call(value, key) && value[key] !== null);
1014
+ // One row at the discriminator: the combination of its value with the
1015
+ // nullness of `fields` is the violation, and D16 forbids naming the values.
1016
+ if (present.length === fields.length || present.length === 0)
1017
+ sink.push(code, at(whenField));
1018
+ break;
1019
+ }
1020
+ case "null-when": {
1021
+ if (!ruleApplies(spec, rule, value))
1022
+ break;
1023
+ for (const key of rule.fields ?? []) {
1024
+ if (!Object.prototype.hasOwnProperty.call(value, key))
1025
+ continue;
1026
+ if (value[key] !== null)
1027
+ sink.push(code, at(key));
1028
+ }
1029
+ break;
1030
+ }
1031
+ case "non-null-when": {
1032
+ if (!ruleApplies(spec, rule, value))
1033
+ break;
1034
+ for (const key of rule.fields ?? []) {
1035
+ const present = Object.prototype.hasOwnProperty.call(value, key) && value[key] !== null;
1036
+ if (!present)
1037
+ sink.push(code, at(key));
1038
+ }
1039
+ break;
1040
+ }
1041
+ case "maximum-when": {
1042
+ if (!ruleApplies(spec, rule, value))
1043
+ break;
1044
+ for (const key of rule.fields ?? []) {
1045
+ const raw = value[key];
1046
+ if (typeof raw === "number" && rule.maximum !== undefined && raw > rule.maximum) {
1047
+ sink.push(code, at(key));
1048
+ }
1049
+ }
1050
+ break;
1051
+ }
1052
+ case "stage-aggregate-budget": {
1053
+ // Sum the stage's declared timeouts in declared order and report the ONE
1054
+ // command that crossed — the earliest pointer that explains the overflow.
1055
+ const collectionName = rule.collection ?? "";
1056
+ const collection = Array.isArray(value[collectionName]) ? value[collectionName] : [];
1057
+ const discriminator = rule.when?.field ?? "";
1058
+ const stage = rule.when?.equals ?? "";
1059
+ const field = rule.fields?.[0] ?? "";
1060
+ const ceiling = rule.maximum;
1061
+ if (ceiling === undefined || !discriminator || !stage || !field)
1062
+ break;
1063
+ let total = 0;
1064
+ for (let i = 0; i < collection.length; i++) {
1065
+ const item = collection[i];
1066
+ if (!isPlainRecord(item) || item[discriminator] !== stage)
1067
+ continue;
1068
+ const timeout = item[field];
1069
+ if (typeof timeout !== "number")
1070
+ continue;
1071
+ total += timeout;
1072
+ if (total > ceiling) {
1073
+ sink.push(code, `${at(collectionName)}/${i}/${field}`);
1074
+ break;
1075
+ }
1076
+ }
1077
+ break;
1078
+ }
1079
+ case "timestamp-order": {
1080
+ const [start, end] = rule.fields ?? [];
1081
+ if (!start || !end)
1082
+ break;
1083
+ const a = value[start];
1084
+ const b = value[end];
1085
+ if (typeof a === "string" && typeof b === "string" && new Date(b).getTime() < new Date(a).getTime()) {
1086
+ sink.push(code, at(end));
1087
+ }
1088
+ break;
1089
+ }
1090
+ case "calendar-roundtrip": {
1091
+ for (const key of rule.fields ?? []) {
1092
+ const raw = value[key];
1093
+ if (typeof raw !== "string" || !compiledPattern(ISO_8601_PATTERN).test(raw))
1094
+ continue;
1095
+ const date = new Date(raw);
1096
+ const parts = raw.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/);
1097
+ const ok = Number.isFinite(date.getTime()) &&
1098
+ parts !== null &&
1099
+ date.getUTCFullYear() === Number(parts[1]) &&
1100
+ date.getUTCMonth() + 1 === Number(parts[2]) &&
1101
+ date.getUTCDate() === Number(parts[3]) &&
1102
+ date.getUTCHours() === Number(parts[4]) &&
1103
+ date.getUTCMinutes() === Number(parts[5]) &&
1104
+ date.getUTCSeconds() === Number(parts[6]);
1105
+ if (!ok)
1106
+ sink.push(code, at(key));
1107
+ }
1108
+ break;
1109
+ }
1110
+ }
1111
+ }