diff --git a/docs/schema-zod-non-equivalence.md b/docs/schema-zod-non-equivalence.md new file mode 100644 index 0000000..97e5265 --- /dev/null +++ b/docs/schema-zod-non-equivalence.md @@ -0,0 +1,165 @@ +# JSON Schema and Zod: measured non-equivalence + +The 211-case corpus for [E3, issue #118](https://github.com/hoklims/assertledger/issues/118) +disproves equal acceptance by the published JSON Schemas and Zod 4.6.7. There are **19 refinement +witnesses** accepted by JSON Schema and rejected by Zod. Another **16 witnesses** pass both schemas +but fail a public parser's semantic checks. Two digest mutations pass parsing and fail replay. +These are different validation layers, not failures to repair by weakening the current contracts. + +[Accepted ADR 0002](decisions/0002-complete-rust-migration.md) keeps Zod canonical until a separately +decided transition. This corpus neither decides D3 nor qualifies a Rust validator. It measures 16 +of the 56 published schema types, not every input or every semantic rule. + +## Frozen inputs and observations + +[The corpus](../tests/schema-zod-corpus/corpus.json.gz) contains all 211 concrete JSON inputs, +case IDs, families, schema filenames and origins. It reuses the historical manifests v1–v5, +qualification receipts, requests and plans from the [replay corpus](../tests/replay-corpus/corpus.json). +The three synthetic controls cover allocation, trust-policy shape and replay-result consistency; +the synthetic public keys do not establish cryptographic trust. + +[Raw observations](../tests/schema-zod-corpus/results.json.gz) retain the original acceptances, +parser errors, validator diagnostics, replay flags and environment metadata. +[The schema inventory](../tests/schema-zod-corpus/schema-inventory.json) records the 56 schema hashes +and export/parser mapping used in that measurement; it is provenance, not a new schema lock. +These fixtures are gzip-compressed JSON, without changes to their decompressed bytes. + +The source measurement used commit `66bd40468fe6cff671b686d7a5529bda457a4832`, Darwin arm64, +Node 24.22.1, Zod 4.6.7 and Ajv 8.17.1. The original investigation also observed identical per-case +results and diagnostics on Node 22.22.0 on that host. The following hashes identify the decompressed +source artifacts, not a claim about an unexecuted platform: + +| Artifact | SHA-256 | +| --- | --- | +| `corpus.json` | `d3951c300a33b80e9797fcfeef5cf6e8f5b13a3d50e8194aa0ca627b49b20193` | +| `results.json` | `c8606bc7788eafb340d55183a5de196804729ed68d750dc7963aae60fdfb9ccc` | +| `schema-inventory.json` | `9ab76d5dde61688329a0a783037fa154ced34f1bab4564859dfdd3152973f395` | + +## Native reproduction + +After `pnpm install --frozen-lockfile`, run from the repository root: + +```sh +pnpm exec tsx --test tests/schema-zod.test.ts +``` + +This test runs in the existing `pnpm check` CI path on Node 22/24 and Linux, Windows and macOS. +It compiles all 56 on-disk draft 2020-12 schemas with Ajv 8.17.1, then exercises the 211 inputs +against their schema, Zod export, public parser where one exists, and replay where recorded. +It asserts each layer's frozen acceptance separately. The expected result is the observed +divergence, not equality between validators. Parser refusals require the recorded error class +and business code, or the specific semantic error message for qualification plans; an unrelated +exception fails the test. Schema compilation, fixture loading and unexpected replay errors fail +the run. Input immutability is checked after each layer. No commands from fixtures are executed. + +Ajv is a pinned development dependency, explicitly approved for this corpus and CI. Its options +are `strict`, `allowUnionTypes`, `allErrors`, `unicodeRegExp` and `validateFormats` enabled, with +`coerceTypes`, `useDefaults` and `removeAdditional` disabled. No custom business formats, +remote schema loading, coercion, default insertion or property stripping are configured. + +To emit the inputs and full raw measurements again, choose an output directory outside the checkout: + +```sh +E3_OUTPUT="$(mktemp -d)" +pnpm exec tsx tests/schema-zod-corpus/reproduce.mjs "$PWD" "$E3_OUTPUT" +``` + +[The reproducer](../tests/schema-zod-corpus/reproduce.mjs) reuses the investigation's deterministic +generator, with style adjustments, an explicit output-directory argument and project dependency resolution. +It verifies the historical document hashes before constructing mutations. It emits `corpus.json`, +`results.json` and `schema-inventory.json`; it does not update the compressed expectations. The +new results record the current commit/runtime, so their metadata and file hash may differ from +the source measurement. Compare per-case results separately from that metadata. Do not replace +expectations merely to make a changed acceptance pass: contract changes require their own review. + +## Observed acceptance + +Numbers are accepted / exercised. A dash means that layer has no associated function in this +measurement, not that acceptance was inferred. + +| Family | Cases | JSON Schema | Zod | Parser | Replay valid | +| --- | ---: | ---: | ---: | ---: | ---: | +| Historical documents | 22 | 22/22 | 22/22 | 18/18 | 22/22 | +| Historical requests | 10 | 10/10 | 10/10 | 6/6 | — | +| Historical plans | 4 | 4/4 | 4/4 | 4/4 | — | +| Synthetic controls | 3 | 3/3 | 3/3 | 3/3 | — | +| Structural rejects | 120 | 0/120 | 0/120 | 0/96 | — | +| Post-parse checks | 15 | 15/15 | 15/15 | 0/15 | — | +| Unicode length | 8 | 5/8 | 5/8 | 5/8 | — | +| Numeric bounds/budget | 7 | 2/7 | 2/7 | 1/7 | — | +| Structural acceptance | 1 | 1/1 | 1/1 | 1/1 | — | +| Relative-path refinement | 11 | 11/11 | 0/11 | 0/11 | — | +| Tool-identity refinement | 2 | 2/2 | 0/2 | 0/2 | — | +| Environment refinement | 3 | 3/3 | 0/3 | 0/3 | — | +| Runtime-identity refinement | 1 | 1/1 | 0/1 | — | — | +| Nested refinements | 2 | 2/2 | 0/2 | — | — | +| Replay-only mutations | 2 | 2/2 | 2/2 | 2/2 | 0/2 | + +There are 32 JSON Schema/parser differences where a parser exists: 16 refinement witnesses and +16 post-parse witnesses. Three refinement witnesses exercise exports without standalone parsers. +No inverse divergence was observed in this corpus. + +## The 19 refinement witnesses + +The refinements live in [qualification contracts](../src/contracts/qualification.ts). JSON Schema +exports retain the structural string constraints, not these predicates. + +| Field / family | Witness values or mutation | Count | +| --- | --- | ---: | +| Plan `allowedCandidatePaths` | `../escape`, `/absolute`, `a\b`, `C:/a`, `a//b`, `./a`, `a/../b`, `a.`, `NUL.txt`, `con/a`, `a` + NUL + `b` | 11 | +| Tool `identityPath` | `identity`, `/tmp/e3` + newline + `identity` | 2 | +| Action environment key | `HOME`, `NODE_OPTIONS`, `ASSERTLEDGER_E3` | 3 | +| Receipt runtime executable | `relative` | 1 | +| Execution request candidate file | `../escape` | 1 | +| Receipt's nested plan path | `../escape` | 1 | + +The environment values and paths are parsed as data only. In particular, no reserved environment +key is applied to a process and no path-traversal file is written. + +## The 16 post-parse witnesses + +These cases pass both JSON Schema and Zod. Their additional checks remain necessary in the +[contract parsers](../src/contracts/index.ts) and `parseQualificationPlan`. +IDs below are the suffixes of the corresponding base ID in the frozen corpus. + +| Base | Case suffix | Refusal | +| --- | --- | --- | +| `evidence-v1-request` | `duplicate-world` | `DUPLICATE_WORLD_ID` | +| `evidence-v1-request` | `duplicate-candidate` | `DUPLICATE_CANDIDATE_ID` | +| `evidence-v1-request` | `target-weight-zero` | `TARGET_WEIGHT_REQUIRED` | +| `evidence-v1-request` | `missing-neutral` | `NEUTRAL_WORLD_REQUIRED` | +| `evidence-v1-request` | `execution-budget` | `EXECUTION_BUDGET_EXCEEDED` | +| `evidence-v1-request` | `utf8-byte-budget` | `WORLD_OVERLAY_BYTES_EXCEEDED` | +| `evidence-v1-request` | `short-executions` | `EXECUTION_BUDGET_EXCEEDED` | +| `qualification-2.1.0-node-test-plan` | `unknown-action` | `Unknown obligation reference` | +| `qualification-2.1.0-node-test-plan` | `case-insensitive-tool` | `Duplicate tool` | +| `allocation-request` | `case-collision` | `AGENTIC_CORPUS_ALLOCATION_REQUEST_INVALID` | +| `allocation-request` | `empty-holdout` | `AGENTIC_CORPUS_ALLOCATION_REQUEST_INVALID` | +| `trust-policy` | `duplicate-role` | `AGENTIC_CORPUS_TRUST_POLICY_INVALID` | +| `trust-policy` | `duplicate-key` | `AGENTIC_CORPUS_TRUST_POLICY_INVALID` | +| `trust-policy` | `duplicate-author` | `AGENTIC_CORPUS_TRUST_POLICY_INVALID` | +| `replay-result` | `inconsistent` | `REPLAY_RESULT_INCONSISTENT` | +| `evidence-v1` | `unknown-world-reference` | `EVIDENCE_MANIFEST_INCONSISTENT` | + +The UTF-8 witness contains only one nonempty overlay: `é` occupies two bytes and exceeds a +one-byte budget. The numeric `short-executions` case permits 17 executions while 18 are required; +18 is also exercised as an accepted control. Tool and allocation collisions compare business +identities case-insensitively; uniqueness of whole JSON objects would not express those checks. + +## Historical replay and limits + +All 22 historical documents replay successfully through the existing pure replay functions, with +the complete frozen flag objects asserted. The `wrong-decision-digest` and `wrong-artifact-digest` +mutations on `evidence-v1` remain parseable but fail the integrity/semantic flags recorded in the +raw observations. Parsing alone does not establish digest binding. These tests replay stored +evidence; they do not rerun campaigns or authenticate producers. + +The Unicode cases agree on the tested code-point boundaries, including astral and combining +characters; see the [Zod 4.6 migration note](migration-zod-4.6.md). They do not establish grapheme +semantics or another validator's behavior. Large integers here are rejected by the chosen field's +business bound; no claim is made about a future Rust numeric parser. + +E3's equality hypothesis is false on this corpus. The reproducible witnesses answer the question +without a contract migration. D3's representation/admission decision and a replay against an +actually approved Rust validator remain separate work; other `partial` families in the +[SDK surface map](sdk-surface-map.md) are not covered by these 16 exercised schema types. diff --git a/docs/sdk-surface-map.md b/docs/sdk-surface-map.md index 0e5410b..8add719 100644 --- a/docs/sdk-surface-map.md +++ b/docs/sdk-surface-map.md @@ -145,6 +145,10 @@ reach a CLI or MCP user only through the command that parses the document. 57 published schemas: 2 equivalent, 55 partial. +The [211-case JSON Schema/Zod corpus](schema-zod-non-equivalence.md) records concrete refinement, +post-parse and replay witnesses for 16 of these schema types; it tests the measured divergences, +not an assumption of equal acceptance. + Versioned parsers dispatch on `schemaVersion` to the parsers above: | Export | Published schemas | Status | diff --git a/package.json b/package.json index f56463a..ad994c6 100644 --- a/package.json +++ b/package.json @@ -81,6 +81,7 @@ "@biomejs/biome": "2.6.4", "@modelcontextprotocol/client": "2.4.0", "@types/node": "22.20.5", + "ajv": "8.17.1", "tsx": "4.23.15" }, "directories": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fea3539..c2eaf94 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -27,6 +27,9 @@ importers: '@types/node': specifier: 22.20.5 version: 22.20.5 + ajv: + specifier: 8.17.1 + version: 8.17.1 tsx: specifier: 4.23.15 version: 4.23.15 @@ -393,6 +396,9 @@ packages: cpu: [x64] os: [win32] + ajv@8.17.1: + resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==} + cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -410,6 +416,12 @@ packages: resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} engines: {node: '>=18.0.0'} + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-uri@3.1.9: + resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -421,6 +433,9 @@ packages: jose@6.2.14: resolution: {integrity: sha512-3JasLuki1NRLQvY4wCoC37KZk4qxoBx2k2aFqLxT84IezqW0bkJKnNtxnZj/Fu1xsQivoc/lytxaRHJoGLjJ1A==} + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + path-key@3.1.1: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} @@ -429,6 +444,10 @@ packages: resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} engines: {node: '>=16.20.0'} + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -664,6 +683,13 @@ snapshots: '@typescript/typescript-win32-x64@7.0.2': optional: true + ajv@8.17.1: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.9 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -705,6 +731,10 @@ snapshots: dependencies: eventsource-parser: 3.1.1 + fast-deep-equal@3.1.3: {} + + fast-uri@3.1.9: {} + fsevents@2.3.3: optional: true @@ -712,10 +742,14 @@ snapshots: jose@6.2.14: {} + json-schema-traverse@1.0.0: {} + path-key@3.1.1: {} pkce-challenge@5.0.1: {} + require-from-string@2.0.2: {} + shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 diff --git a/tests/schema-zod-corpus/corpus.json.gz b/tests/schema-zod-corpus/corpus.json.gz new file mode 100644 index 0000000..ffcf53f Binary files /dev/null and b/tests/schema-zod-corpus/corpus.json.gz differ diff --git a/tests/schema-zod-corpus/reproduce.mjs b/tests/schema-zod-corpus/reproduce.mjs new file mode 100644 index 0000000..b614c43 --- /dev/null +++ b/tests/schema-zod-corpus/reproduce.mjs @@ -0,0 +1,407 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { createHash } from "node:crypto"; +import { gunzipSync } from "node:zlib"; +import { execFileSync } from "node:child_process"; +import Ajv2020 from "ajv/dist/2020.js"; + +assert.ok( + process.argv[2] && process.argv[3], + "Usage: reproduce.mjs ", +); +const root = path.resolve(process.argv[2]); +const lab = path.resolve(process.argv[3]); +assert.notEqual(lab, root); +fs.mkdirSync(lab, { recursive: true }); +const load = (p) => JSON.parse(fs.readFileSync(path.join(root, p), "utf8")); +const sha = (x) => createHash("sha256").update(x).digest("hex"); +const contracts = { + ...(await import(pathToFileURL(path.join(root, "src/contracts/index.ts")))), + ...(await import(pathToFileURL(path.join(root, "src/contracts/qualification.ts")))), +}; +const core = await import(pathToFileURL(path.join(root, "src/core/index.ts"))); +const qualification = await import(pathToFileURL(path.join(root, "src/core/qualification.ts"))); +const sourceMap = fs.readFileSync(path.join(root, "docs/sdk-surface-map.md"), "utf8"); +const registry = new Map(); +for (const line of sourceMap.split("\n")) { + const columns = line.split("|").map((x) => x.trim()); + if (!/^`[^`]+\.json`$/.test(columns[1] ?? "")) continue; + const filename = columns[1].slice(1, -1); + const names = [...columns[2].matchAll(/`([^`]+)`/g)].map((x) => x[1]); + const schemaName = names.find((x) => x.endsWith("Schema")); + const parserName = names.find((x) => x.startsWith("parse")); + assert.equal(typeof contracts[schemaName]?.safeParse, "function", filename); + if (parserName) assert.equal(typeof contracts[parserName], "function", filename); + registry.set(filename, { schemaName, parserName }); +} +const options = { + strict: true, + allowUnionTypes: true, + allErrors: true, + unicodeRegExp: true, + coerceTypes: false, + useDefaults: false, + removeAdditional: false, + validateFormats: true, +}; +const validators = new Map(); +const schemaInventory = []; +for (const filename of fs + .readdirSync(path.join(root, "schemas")) + .filter((x) => x.endsWith(".json")) + .sort()) { + assert.ok(registry.has(filename), filename); + const bytes = fs.readFileSync(path.join(root, "schemas", filename)); + const schema = JSON.parse(bytes); + const validator = new Ajv2020(options).compile(schema); + validators.set(filename, validator); + schemaInventory.push({ filename, sha256: sha(bytes), ...registry.get(filename) }); +} +const corpus = []; +const add = (id, family, filename, input, origin) => { + assert.ok(validators.has(filename), filename); + corpus.push({ id, family, filename, origin, input: JSON.parse(JSON.stringify(input)) }); +}; +const historical = load("tests/replay-corpus/corpus.json"); +for (const entry of historical.entries) { + let bytes = fs.readFileSync(path.join(root, entry.document)); + if (entry.document.endsWith(".gz")) bytes = gunzipSync(bytes); + assert.equal(`sha256:${sha(bytes)}`, entry.sha256, entry.id); + const document = JSON.parse(bytes); + const filename = + entry.kind === "evidence" + ? `evidence-manifest.v${document.schemaVersion[0]}.json` + : "qualification-receipt.v1.json"; + add(entry.id, "historical-document", filename, document, entry.document); + if (entry.kind === "qualification") + add( + `${entry.id}-plan`, + "historical-plan", + "qualification-plan.v1.json", + document.plan, + `${entry.document}#/plan`, + ); + const request = entry.input && path.join(entry.input, "request.json"); + if (request && fs.existsSync(path.join(root, request))) { + const input = load(request); + const schema = + entry.kind === "evidence" + ? `verification-request.v${input.schemaVersion[0]}.json` + : "qualification-execution-request.v1.json"; + add(`${entry.id}-request`, "historical-request", schema, input, request); + } +} +const digest = (c) => `sha256:${c.repeat(64)}`; +add( + "trust-policy", + "synthetic-control", + "agentic-corpus-trust-policy.v1.json", + { + schemaVersion: "1.0.0", + policyId: "e3", + policyDigest: digest("a"), + keys: ["b", "c"].map((c, i) => ({ + keyId: digest(c), + subjectId: i ? "reviewer" : "author", + roles: [i ? "REVIEWER" : "AUTHOR"], + publicKey: { algorithm: "Ed25519", format: "SPKI_DER_BASE64URL", data: "AA" }, + })), + sources: [ + { + sourceId: "source", + sourceIdentityDigest: digest("d"), + authorizedAuthorSubjectIds: ["author"], + authorizedReviewerSubjectIds: ["reviewer"], + }, + ], + }, + "synthetic:shape-only; not a cryptographically valid trust root", +); +add( + "replay-result", + "synthetic-control", + "replay-result.v1.json", + { + valid: true, + schemaValid: true, + decisionDigestValid: true, + artifactDigestValid: true, + decisionSemanticsValid: true, + }, + "synthetic", +); +add( + "allocation-request", + "synthetic-control", + "agentic-corpus-allocation-request.v1.json", + { + schemaVersion: "1.0.0", + allocationId: "e3", + seedDigest: digest("a"), + strata: [ + { + sourceId: "source", + sourceIdentityDigest: digest("b"), + calibrationCount: 1, + caseIds: ["case-a", "case-b"], + }, + ], + }, + "synthetic; based on tests/corpus-allocation.test.ts:37", +); +const bases = [...corpus]; +const mutate = (baseId, suffix, family, change) => { + const base = bases.find((x) => x.id === baseId); + assert.ok(base, baseId); + const value = structuredClone(base.input); + change(value); + add(`${baseId}/${suffix}`, family, base.filename, value, base.id); +}; +for (const base of bases) { + add(`${base.id}/null`, "structural-reject", base.filename, null, base.id); + mutate(base.id, "unknown-field", "structural-reject", (v) => { + v.e3Unknown = true; + }); + mutate(base.id, "missing-field", "structural-reject", (v) => { + delete v[Object.keys(v)[0]]; + }); +} +const requestId = "evidence-v1-request"; +mutate(requestId, "duplicate-world", "post-parse", (v) => { + v.worlds[1].id = v.worlds[0].id; +}); +mutate(requestId, "duplicate-candidate", "post-parse", (v) => { + v.candidates[1].id = v.candidates[0].id; +}); +mutate(requestId, "target-weight-zero", "post-parse", (v) => { + v.worlds.find((x) => x.kind === "TARGET").weight = 0; +}); +mutate(requestId, "missing-neutral", "post-parse", (v) => { + v.worlds = v.worlds.filter((x) => x.kind !== "NEUTRAL"); +}); +mutate(requestId, "execution-budget", "post-parse", (v) => { + v.budgets.maximumExecutions = 1; +}); +mutate(requestId, "utf8-byte-budget", "post-parse", (v) => { + for (const world of v.worlds) for (const file of world.files) file.content = ""; + v.worlds[1].files[0].content = "é"; + v.budgets.maximumWorldOverlayBytes = 1; +}); +mutate(requestId, "unsafe-outcome", "structural-reject", (v) => { + v.policy.acceptedTargetOutcomes = ["TIMEOUT"]; +}); +mutate(requestId, "reserved-env", "structural-reject", (v) => { + v.isolation.environmentAllowlist = ["NODE_OPTIONS"]; +}); +for (const [name, value] of [ + ["ascii-512", "a".repeat(512)], + ["ascii-513", "a".repeat(513)], + ["astral-256", "😀".repeat(256)], + ["astral-257", "😀".repeat(257)], + ["astral-512", "😀".repeat(512)], + ["astral-513", "😀".repeat(513)], + ["combining-256", "e\u0301".repeat(256)], + ["combining-257", "e\u0301".repeat(257)], +]) { + mutate(requestId, name, "unicode-length", (v) => { + v.candidates[0].files[0].path = value; + }); +} +for (const [name, value] of [ + ["int-string", "1"], + ["fraction", 1.5], + ["zero", 0], + ["max-safe", Number.MAX_SAFE_INTEGER], + ["unsafe-int", Number.MAX_SAFE_INTEGER + 1], + ["enough-executions", 18], + ["short-executions", 17], +]) { + mutate(requestId, name, "numeric", (v) => { + v.budgets.maximumExecutions = value; + }); +} +mutate(requestId, "null-optional", "structural-reject", (v) => { + v.adapter.extraArguments = null; +}); +mutate(requestId, "empty-optional-array", "structural-accept", (v) => { + v.adapter.extraArguments = []; +}); +const planId = "qualification-2.1.0-node-test-plan"; +for (const value of [ + "../escape", + "/absolute", + "a\\b", + "C:/a", + "a//b", + "./a", + "a/../b", + "a.", + "NUL.txt", + "con/a", + "a\u0000b", +]) { + mutate(planId, `relative-path-${Buffer.from(value).toString("hex")}`, "refinement-path", (v) => { + v.allowedCandidatePaths = [value]; + }); +} +for (const value of ["identity", "/tmp/e3\nidentity"]) { + mutate(planId, `identity-${Buffer.from(value).toString("hex")}`, "refinement-identity", (v) => { + v.tools[0].identityPath = value; + }); +} +for (const value of ["HOME", "NODE_OPTIONS", "ASSERTLEDGER_E3"]) { + mutate(planId, `env-${value}`, "refinement-env", (v) => { + v.actions[0].environment = { [value]: "x" }; + }); +} +mutate(planId, "unknown-action", "post-parse", (v) => { + v.obligations[0].checks[0].actionId = "unknown"; +}); +mutate(planId, "case-insensitive-tool", "post-parse", (v) => { + v.tools.push({ ...v.tools[0], id: v.tools[0].id.toUpperCase() }); +}); +mutate("qualification-2.1.0-node-test", "runtime-relative", "refinement-runtime", (v) => { + Object.values(v.provenance.runtime.tools)[0].executable = "relative"; +}); +mutate( + "qualification-2.1.0-node-test-request", + "candidate-relative-path", + "refinement-nested", + (v) => { + v.candidate.files = [{ path: "../escape", content: "" }]; + }, +); +mutate("qualification-2.1.0-node-test", "plan-relative-path", "refinement-nested", (v) => { + v.plan.allowedCandidatePaths = ["../escape"]; +}); +mutate("allocation-request", "case-collision", "post-parse", (v) => { + v.strata[0].caseIds = ["case-a", "CASE-A"]; +}); +mutate("allocation-request", "empty-holdout", "post-parse", (v) => { + v.strata[0].calibrationCount = 2; +}); +mutate("trust-policy", "duplicate-role", "post-parse", (v) => { + v.keys[0].roles = ["AUTHOR", "AUTHOR"]; +}); +mutate("trust-policy", "duplicate-key", "post-parse", (v) => { + v.keys[1].keyId = v.keys[0].keyId; +}); +mutate("trust-policy", "duplicate-author", "post-parse", (v) => { + v.sources[0].authorizedAuthorSubjectIds.push("author"); +}); +mutate("replay-result", "inconsistent", "post-parse", (v) => { + v.valid = false; +}); +mutate("evidence-v1", "unknown-world-reference", "post-parse", (v) => { + v.observations[0].worldId = "unknown"; +}); +mutate("evidence-v1", "wrong-decision-digest", "replay-only", (v) => { + v.decisionDigest = digest("0"); +}); +mutate("evidence-v1", "wrong-artifact-digest", "replay-only", (v) => { + v.artifactDigest = digest("0"); +}); +const results = []; +for (const item of corpus) { + const { schemaName, parserName } = registry.get(item.filename); + const before = JSON.stringify(item.input); + const jsonSchema = validators.get(item.filename)(item.input); + const jsonErrors = structuredClone(validators.get(item.filename).errors); + const zod = contracts[schemaName].safeParse(item.input); + let parser = null; + if (parserName) { + try { + contracts[parserName](item.input); + parser = { accepted: true }; + } catch (error) { + const expected = + ["ContractError", "ZodError"].includes(error.constructor.name) || + (parserName === "parseQualificationPlan" && + error.constructor.name === "Error" && + /^(Duplicate |Unknown |Test obligation |Test suite |Reference and neutral worlds required|Only target |Target world |Target discriminant )/.test( + error.message, + )); + if (!expected) throw error; + parser = { + accepted: false, + type: error.constructor.name, + code: error.code ?? null, + message: error.message, + }; + } + } + let replay = null; + if (item.family === "historical-document" || item.family === "replay-only") { + replay = item.filename.startsWith("evidence-manifest.") + ? core.replayEvidenceManifest(item.input) + : qualification.replayQualificationReceipt(item.input); + } + assert.equal(JSON.stringify(item.input), before, `${item.id}: mutated by a validator`); + results.push({ + id: item.id, + family: item.family, + filename: item.filename, + jsonSchema, + zod: zod.success, + parser, + replay, + jsonErrors, + zodErrors: zod.success ? null : zod.error.issues, + }); +} +for (const base of bases) { + const r = results.find((x) => x.id === base.id); + assert.equal(r.jsonSchema, true, base.id); + assert.equal(r.zod, true, base.id); + if (r.parser) assert.equal(r.parser.accepted, true, base.id); + if (r.replay) assert.equal(r.replay.valid, true, base.id); +} +const families = {}; +for (const r of results) { + families[r.family] ??= { + n: 0, + jsonSchemaAccepted: 0, + zodAccepted: 0, + parserTested: 0, + parserAccepted: 0, + replayTested: 0, + replayValid: 0, + schemaVsZodDifferences: 0, + schemaVsParserDifferences: 0, + }; + const s = families[r.family]; + s.n++; + s.jsonSchemaAccepted += +r.jsonSchema; + s.zodAccepted += +r.zod; + s.parserTested += +(r.parser !== null); + s.parserAccepted += +(r.parser?.accepted === true); + s.replayTested += +(r.replay !== null); + s.replayValid += +(r.replay?.valid === true); + s.schemaVsZodDifferences += +(r.jsonSchema !== r.zod); + s.schemaVsParserDifferences += +(r.parser !== null && r.jsonSchema !== r.parser.accepted); +} +const metadata = { + sha: execFileSync("git", ["-C", root, "rev-parse", "HEAD"], { encoding: "utf8" }).trim(), + node: process.version, + platform: process.platform, + arch: process.arch, + zod: load("node_modules/zod/package.json").version, + ajv: load("node_modules/ajv/package.json").version, + options, + compiledSchemas: schemaInventory.length, + exercisedSchemas: new Set(corpus.map((x) => x.filename)).size, + cases: corpus.length, + families, +}; +for (const [filename, value] of [ + ["corpus.json", corpus], + ["results.json", { metadata, results }], + ["schema-inventory.json", schemaInventory], +]) { + fs.writeFileSync(path.join(lab, filename), `${JSON.stringify(value, null, 2)}\n`); +} +console.log(JSON.stringify(metadata, null, 2)); +console.log("sha256 corpus.json", sha(fs.readFileSync(path.join(lab, "corpus.json")))); +console.log("sha256 results.json", sha(fs.readFileSync(path.join(lab, "results.json")))); diff --git a/tests/schema-zod-corpus/results.json.gz b/tests/schema-zod-corpus/results.json.gz new file mode 100644 index 0000000..a323020 Binary files /dev/null and b/tests/schema-zod-corpus/results.json.gz differ diff --git a/tests/schema-zod-corpus/schema-inventory.json b/tests/schema-zod-corpus/schema-inventory.json new file mode 100644 index 0000000..9976be9 --- /dev/null +++ b/tests/schema-zod-corpus/schema-inventory.json @@ -0,0 +1,335 @@ +[ + { + "filename": "agentic-benchmark-acquisition-replay-result.v1.json", + "sha256": "eb006b18365198a1bcef90de4879121280d6d9b7366661a8157c5eda0e1b548e", + "schemaName": "AgenticBenchmarkAcquisitionReplayResultSchema", + "parserName": "parseAgenticBenchmarkAcquisitionReplayResult" + }, + { + "filename": "agentic-benchmark-acquisition-request.v1.json", + "sha256": "60d52ec51276905c0aa8a7786c38d0ad925de3151bdface73a6938cb72c98ba8", + "schemaName": "AgenticBenchmarkAcquisitionRequestSchema", + "parserName": "parseAgenticBenchmarkAcquisitionRequest" + }, + { + "filename": "agentic-benchmark-acquisition-result.v1.json", + "sha256": "361ce73f5536e92a9f88bd0ec761602ce1d8eeed9665b618f6bd48d57919a511", + "schemaName": "AgenticBenchmarkAcquisitionResultSchema", + "parserName": "parseAgenticBenchmarkAcquisitionResult" + }, + { + "filename": "agentic-benchmark-artifact.v1.json", + "sha256": "d7e282c97e697c8256bd69ecf7f7e0eff2e66b15ef7790c0004712f4c98dafda", + "schemaName": "AgenticBenchmarkArtifactSchema", + "parserName": "parseAgenticBenchmarkArtifact" + }, + { + "filename": "agentic-benchmark-replay-result.v1.json", + "sha256": "ab6814cb377432958e55791d4ab1941f920d552f34616dfabdef2b35cec077c9", + "schemaName": "AgenticBenchmarkReplayResultSchema", + "parserName": "parseAgenticBenchmarkReplayResult" + }, + { + "filename": "agentic-benchmark-request.v1.json", + "sha256": "18805afa19cdd5a3d4bc5b7794e3020b25047267ba713af46922aacdd690f49e", + "schemaName": "AgenticBenchmarkRequestSchema", + "parserName": "parseAgenticBenchmarkRequest" + }, + { + "filename": "agentic-corpus-allocation-commitment-replay-result.v1.json", + "sha256": "aea2b1e6310c028ad43fd1b3699f63a4473934acc2dbd690834a75370850e4e2", + "schemaName": "AgenticCorpusAllocationCommitmentReplayResultSchema", + "parserName": "parseAgenticCorpusAllocationCommitmentReplayResult" + }, + { + "filename": "agentic-corpus-allocation-commitment.v1.json", + "sha256": "29b83d2299fc8de4476fb49b30d221c1d20c50cd7ba82dcaf27c3f1597d83919", + "schemaName": "AgenticCorpusAllocationCommitmentSchema", + "parserName": "parseAgenticCorpusAllocationCommitment" + }, + { + "filename": "agentic-corpus-allocation-replay-result.v1.json", + "sha256": "9f660ac3425d67c94742fbfef64be0ea4e1938bb88ea49fc097355c935b257d4", + "schemaName": "AgenticCorpusAllocationReplayResultSchema", + "parserName": "parseAgenticCorpusAllocationReplayResult" + }, + { + "filename": "agentic-corpus-allocation-request.v1.json", + "sha256": "a44b3f2bdacc28029588d07c78e09f44ea512342ca1cbeacc62ea71b7d1c5074", + "schemaName": "AgenticCorpusAllocationRequestSchema", + "parserName": "parseAgenticCorpusAllocationRequest" + }, + { + "filename": "agentic-corpus-allocation-reveal.v1.json", + "sha256": "aaafebd9564300861f947656c35e73cf02d9531655bc59d4cbba6458c743fed8", + "schemaName": "AgenticCorpusAllocationRevealSchema", + "parserName": "parseAgenticCorpusAllocationReveal" + }, + { + "filename": "agentic-corpus-allocation.v1.json", + "sha256": "248de6e66dc51aae9785785597ac66432855269f78f821e259c2627d7af0c9f8", + "schemaName": "AgenticCorpusAllocationSchema", + "parserName": "parseAgenticCorpusAllocation" + }, + { + "filename": "agentic-corpus-experiment-artifact.v1.json", + "sha256": "57f649fd4dd6e3387132443ed7714a37578fcba128f1be2d9004cfa36276a5ca", + "schemaName": "AgenticCorpusExperimentArtifactSchema", + "parserName": "parseAgenticCorpusExperimentArtifact" + }, + { + "filename": "agentic-corpus-experiment-plan-replay-result.v1.json", + "sha256": "8dc2133a84cb00e64ac28929baf085593eea9384cc0cf6a69beb8d908c222284", + "schemaName": "AgenticCorpusExperimentPlanReplayResultSchema", + "parserName": "parseAgenticCorpusExperimentPlanReplayResult" + }, + { + "filename": "agentic-corpus-experiment-plan.v1.json", + "sha256": "0cf6eb5314b4eb11b1ea6237f7ced841a7757af743f0783325d6c38d5e8ce619", + "schemaName": "AgenticCorpusExperimentPlanSchema", + "parserName": "parseAgenticCorpusExperimentPlan" + }, + { + "filename": "agentic-corpus-experiment-replay-request.v1.json", + "sha256": "e834f9c179883e050f87582a83dad2f22a40379aa0b47fff79c82742f1724841", + "schemaName": "AgenticCorpusExperimentReplayRequestSchema", + "parserName": "parseAgenticCorpusExperimentReplayRequest" + }, + { + "filename": "agentic-corpus-experiment-replay-result.v1.json", + "sha256": "2411a221c98c799c668e767b5a6dc3b8b1a7f4b168a60b8065898491b1cef14b", + "schemaName": "AgenticCorpusExperimentReplayResultSchema", + "parserName": "parseAgenticCorpusExperimentReplayResult" + }, + { + "filename": "agentic-corpus-experiment-request.v1.json", + "sha256": "b2edfd64843a7ad5cc5bea9e2a63b80258387a271694428c20e5c0de7ce31075", + "schemaName": "AgenticCorpusExperimentRequestSchema", + "parserName": "parseAgenticCorpusExperimentRequest" + }, + { + "filename": "agentic-corpus-provenance.v1.json", + "sha256": "2ded32d34b79784425de6578d0cc6d33043f51b14da1e8111e7cfdf2233f4324", + "schemaName": "AgenticCorpusProvenanceSchema", + "parserName": "parseAgenticCorpusProvenance" + }, + { + "filename": "agentic-corpus-trust-policy.v1.json", + "sha256": "b6694e06556f3fac9ed349b1a725dc73d8ef40ce1bae417bbe39acac59f4fda8", + "schemaName": "AgenticCorpusTrustPolicySchema", + "parserName": "parseAgenticCorpusTrustPolicy" + }, + { + "filename": "agentic-profile-replay-result.v1.json", + "sha256": "bb552aee20dd2abe7ad6b72743e510f856f02410ce744ec269f7053a0058e302", + "schemaName": "AgenticProfileReplayResultSchema", + "parserName": "parseAgenticProfileReplayResult" + }, + { + "filename": "agentic-profile-replay-result.v2.json", + "sha256": "d6eed66747b1f05753cfd17c8791f789c78749211747164599364a3c52b03cc7", + "schemaName": "AgenticProfileReplayResultV2Schema", + "parserName": "parseAgenticProfileReplayResultV2" + }, + { + "filename": "agentic-profile-report.v1.json", + "sha256": "13934855623f40c28db251cfb7a3acec048652e1bfd97f3f8b8161a2c2f51aa5", + "schemaName": "AgenticProfileReportSchema", + "parserName": "parseAgenticProfileReport" + }, + { + "filename": "agentic-profile-report.v2.json", + "sha256": "49d74357dba6a43c25664a84d31a24ac9391cb0251e228018560a267c01b1e49", + "schemaName": "AgenticProfileReportV2Schema", + "parserName": "parseAgenticProfileReportV2" + }, + { + "filename": "agentic-profile-request.v1.json", + "sha256": "e195f1db1e24dcca01fd72ed24478af36f8e69e20bd9db2e7c6ae0ef43ff9b7f", + "schemaName": "AgenticProfileRequestSchema", + "parserName": "parseAgenticProfileRequest" + }, + { + "filename": "agentic-profile-request.v2.json", + "sha256": "a00a3ceffc0b92a63df0d5c28f2e837ffd70e8a34ef565d7be058e3b25b6bf06", + "schemaName": "AgenticProfileRequestV2Schema", + "parserName": "parseAgenticProfileRequestV2" + }, + { + "filename": "evidence-export-replay-result.v1.json", + "sha256": "3b52decc4b977391a37e20f0a21a74a295f33a7c47739ff882dde38e86a9dab7", + "schemaName": "EvidenceExportReplayResultSchema", + "parserName": "parseEvidenceExportReplayResult" + }, + { + "filename": "evidence-export-request.v1.json", + "sha256": "4e960f1cfadc759189a1c62e76ec384cf0b82ae1e6d44cb18d000d30fc6247bc", + "schemaName": "EvidenceExportRequestSchema", + "parserName": "parseEvidenceExportRequest" + }, + { + "filename": "evidence-export.v1.json", + "sha256": "fc5bca67694200bc2c588d1e12c7aaed884619f53cfe11e21a8e02261363fb7d", + "schemaName": "EvidenceExportSchema", + "parserName": "parseEvidenceExport" + }, + { + "filename": "evidence-manifest.v1.json", + "sha256": "06dfd4241ef7d356141dae5e2b2b9808b18cd50dcdcf71a132ef5720ef16c4a1", + "schemaName": "EvidenceManifestSchema", + "parserName": "parseEvidenceManifest" + }, + { + "filename": "evidence-manifest.v2.json", + "sha256": "5c8a34f83bd7fef3a1accb957378956313607ed54b6c07ad8565a809e0ccf68e", + "schemaName": "EvidenceManifestV2Schema", + "parserName": "parseEvidenceManifestV2" + }, + { + "filename": "evidence-manifest.v3.json", + "sha256": "a1ff17f9c610ad6fee4583716a434d7ca13f2777794116153b0b44d4f4e3aa7c", + "schemaName": "EvidenceManifestV3Schema", + "parserName": "parseEvidenceManifestV3" + }, + { + "filename": "evidence-manifest.v4.json", + "sha256": "6707fcf8d3f68cb3d8ac5730c3474d58d5e64537ceea0b67d2c405320207a16c", + "schemaName": "EvidenceManifestV4Schema", + "parserName": "parseEvidenceManifestV4" + }, + { + "filename": "evidence-manifest.v5.json", + "sha256": "ad6fc0753c6182767b83516743eca6cf1ef8324ae4674cda52182e4c1d095fc5", + "schemaName": "EvidenceManifestV5Schema", + "parserName": "parseEvidenceManifestV5" + }, + { + "filename": "evidence-provider-manifest.v1.json", + "sha256": "7574f6e2bd8312f591343d059ee4a1008ad80058ecf6b990c0b50811015c5830", + "schemaName": "EvidenceProviderManifestSchema", + "parserName": "parseEvidenceProviderManifest" + }, + { + "filename": "qualification-execution-request.v1.json", + "sha256": "55660a7cc1324f28d5e3f2f6c3a46babea53388a5fbc120b84512116edfbee79", + "schemaName": "QualificationExecutionRequestSchema" + }, + { + "filename": "qualification-plan.v1.json", + "sha256": "9031c5a1cfa7a7b6a6c8928f8b3acb8d464b2b110f47f647374da2ae5360c9ca", + "schemaName": "QualificationPlanSchema", + "parserName": "parseQualificationPlan" + }, + { + "filename": "qualification-receipt.v1.json", + "sha256": "9c04acd147b66bc1cf6776eab98613e3ff4a67ab87ef7175a749e44fa42b0848", + "schemaName": "QualificationReceiptSchema" + }, + { + "filename": "qualification-replay-result.v1.json", + "sha256": "dcba32bdd1d9e5dcc435b29963debba9a715bed12afffd307c7443649c92fb35", + "schemaName": "QualificationReplayResultSchema" + }, + { + "filename": "replay-result.v1.json", + "sha256": "3607ffbf5474c2e118e11f3d14f73b3e3a35c11c9d555f46dabf0b01081a503f", + "schemaName": "ReplayResultSchema", + "parserName": "parseReplayResult" + }, + { + "filename": "repository-analysis.v1.json", + "sha256": "a5dd7d0e225acf74f4d6758d88fa125cbb241f1c7fd28402fd4c3761a65e6af2", + "schemaName": "RepositoryAnalysisSchema", + "parserName": "parseRepositoryAnalysis" + }, + { + "filename": "repository-audit.v1.json", + "sha256": "660638fd5c4f636da3bf107fdec9bde52e2261b91a65ca3bfa3353ed947200f3", + "schemaName": "RepositoryAuditSchema", + "parserName": "parseRepositoryAudit" + }, + { + "filename": "repository-audit.v2.json", + "sha256": "c65998d453aa2cc9e5ebb96ab1dc2a20123477b8d6fffde74a280911aa323600", + "schemaName": "RepositoryAuditV2Schema", + "parserName": "parseRepositoryAuditV2" + }, + { + "filename": "repository-init-config.v1.json", + "sha256": "cd577fe27e1e613548dc4a7e382aadf8e5e0f5b3ede46c659e843c2a7cb2ab25", + "schemaName": "RepositoryInitConfigSchema", + "parserName": "parseRepositoryInitConfig" + }, + { + "filename": "repository-init-config.v2.json", + "sha256": "51d5c3c7f994f0474eff0f2fb900214c9f07569b0730a733abeea0ade8a63832", + "schemaName": "RepositoryInitConfigV2Schema", + "parserName": "parseRepositoryInitConfigV2" + }, + { + "filename": "repository-init-lock.v1.json", + "sha256": "cf82e7c24bd4e019d9ccade4dab965d363e9e6448fdc894fdba5eb307ef4030a", + "schemaName": "RepositoryInitLockSchema", + "parserName": "parseRepositoryInitLock" + }, + { + "filename": "repository-init-lock.v2.json", + "sha256": "1db8d97b7b3560ef7a9fb095c35ea50337a35a49a58115a52a15b70ccb8f5f84", + "schemaName": "RepositoryInitLockV2Schema", + "parserName": "parseRepositoryInitLockV2" + }, + { + "filename": "repository-init-result.v1.json", + "sha256": "40035bb5c8d4072d0f7ba522e3b8d1dbf574eb9d9780c9c64aa731b5589cecce", + "schemaName": "RepositoryInitResultSchema", + "parserName": "parseRepositoryInitResult" + }, + { + "filename": "repository-init-result.v2.json", + "sha256": "6e7f2a437319e216c268b8d7dc8e7fd32df60408c0e87bf2e3b1f6b08f202e83", + "schemaName": "RepositoryInitResultV2Schema", + "parserName": "parseRepositoryInitResultV2" + }, + { + "filename": "verification-request.v1.json", + "sha256": "279a601cc872576581b19004244b7aba6ec894261a9ef0df15ff99eab08d4b1c", + "schemaName": "VerificationRequestSchema", + "parserName": "parseVerificationRequest" + }, + { + "filename": "verification-request.v2.json", + "sha256": "3e6da760006795dc07fbd17f0ce3666577d8de5c94879c449f40b5dc93ee9204", + "schemaName": "VerificationRequestV2Schema", + "parserName": "parseVerificationRequestV2" + }, + { + "filename": "verification-request.v3.json", + "sha256": "d38e70f10d56cbfb155fed89ed0b62cae9ab1305d8328e15f1024b2108059117", + "schemaName": "VerificationRequestV3Schema", + "parserName": "parseVerificationRequestV3" + }, + { + "filename": "verification-request.v4.json", + "sha256": "530c90708977561c591d631e3b39055f2be5412c151222517c058d7bad1b9f8a", + "schemaName": "VerificationRequestV4Schema", + "parserName": "parseVerificationRequestV4" + }, + { + "filename": "verification-request.v5.json", + "sha256": "4c53bf897ad22a1ef8de9e42e8dd6f0cba37575682b03b150450314fc887a9f2", + "schemaName": "VerificationRequestV5Schema", + "parserName": "parseVerificationRequestV5" + }, + { + "filename": "witness-import-request.v1.json", + "sha256": "80cddb677d6dcae47a119bf4e773018a95191e7262d263c881cd3bb55d0b542b", + "schemaName": "WitnessImportRequestSchema", + "parserName": "parseWitnessImportRequest" + }, + { + "filename": "witness-import-request.v2.json", + "sha256": "b0ae349265fc1645e29bc705afedbca379cb98d634fe21a7cbe44feb7ed945d4", + "schemaName": "WitnessImportRequestV2Schema", + "parserName": "parseWitnessImportRequestV2" + } +] diff --git a/tests/schema-zod.test.ts b/tests/schema-zod.test.ts new file mode 100644 index 0000000..ad9c0cd --- /dev/null +++ b/tests/schema-zod.test.ts @@ -0,0 +1,180 @@ +import assert from "node:assert/strict"; +import { readFile, readdir } from "node:fs/promises"; +import { describe, it } from "node:test"; +import { gunzipSync } from "node:zlib"; +import { Ajv2020 } from "ajv/dist/2020.js"; +import { ZodError, type ZodType } from "zod"; +import * as contracts from "../src/contracts/index.js"; +import * as qualification from "../src/contracts/qualification.js"; +import { replayEvidenceManifest } from "../src/core/index.js"; +import { replayQualificationReceipt } from "../src/core/qualification.js"; + +interface CorpusCase { + id: string; + family: string; + filename: string; + input: unknown; +} + +interface Observation { + id: string; + family: string; + filename: string; + jsonSchema: boolean; + zod: boolean; + parser: { accepted: boolean; type?: string; code?: string | null; message?: string } | null; + replay: Record | null; +} + +const boundaries: Record unknown) | null }> = + { + "agentic-corpus-allocation-request.v1.json": { + schema: contracts.AgenticCorpusAllocationRequestSchema, + parse: contracts.parseAgenticCorpusAllocationRequest, + }, + "agentic-corpus-trust-policy.v1.json": { + schema: contracts.AgenticCorpusTrustPolicySchema, + parse: contracts.parseAgenticCorpusTrustPolicy, + }, + "evidence-manifest.v1.json": { + schema: contracts.EvidenceManifestSchema, + parse: contracts.parseEvidenceManifest, + }, + "evidence-manifest.v2.json": { + schema: contracts.EvidenceManifestV2Schema, + parse: contracts.parseEvidenceManifestV2, + }, + "evidence-manifest.v3.json": { + schema: contracts.EvidenceManifestV3Schema, + parse: contracts.parseEvidenceManifestV3, + }, + "evidence-manifest.v4.json": { + schema: contracts.EvidenceManifestV4Schema, + parse: contracts.parseEvidenceManifestV4, + }, + "evidence-manifest.v5.json": { + schema: contracts.EvidenceManifestV5Schema, + parse: contracts.parseEvidenceManifestV5, + }, + "qualification-execution-request.v1.json": { + schema: qualification.QualificationExecutionRequestSchema, + parse: null, + }, + "qualification-plan.v1.json": { + schema: qualification.QualificationPlanSchema, + parse: qualification.parseQualificationPlan, + }, + "qualification-receipt.v1.json": { + schema: qualification.QualificationReceiptSchema, + parse: null, + }, + "replay-result.v1.json": { + schema: contracts.ReplayResultSchema, + parse: contracts.parseReplayResult, + }, + "verification-request.v1.json": { + schema: contracts.VerificationRequestSchema, + parse: contracts.parseVerificationRequest, + }, + "verification-request.v2.json": { + schema: contracts.VerificationRequestV2Schema, + parse: contracts.parseVerificationRequestV2, + }, + "verification-request.v3.json": { + schema: contracts.VerificationRequestV3Schema, + parse: contracts.parseVerificationRequestV3, + }, + "verification-request.v4.json": { + schema: contracts.VerificationRequestV4Schema, + parse: contracts.parseVerificationRequestV4, + }, + "verification-request.v5.json": { + schema: contracts.VerificationRequestV5Schema, + parse: contracts.parseVerificationRequestV5, + }, + }; + +const fixtureRoot = new URL("./schema-zod-corpus/", import.meta.url); +const corpus: CorpusCase[] = JSON.parse( + gunzipSync(await readFile(new URL("corpus.json.gz", fixtureRoot))).toString("utf8"), +); +const observations: Observation[] = JSON.parse( + gunzipSync(await readFile(new URL("results.json.gz", fixtureRoot))).toString("utf8"), +).results; +const expectedById = new Map(observations.map((item) => [item.id, item])); +const schemaRoot = new URL("../schemas/", import.meta.url); +const validators = new Map(); +for (const filename of (await readdir(schemaRoot)).filter((name) => name.endsWith(".json"))) { + const schema = JSON.parse(await readFile(new URL(filename, schemaRoot), "utf8")); + const ajv = new Ajv2020({ + strict: true, + allowUnionTypes: true, + allErrors: true, + unicodeRegExp: true, + coerceTypes: false, + useDefaults: false, + removeAdditional: false, + validateFormats: true, + }); + validators.set(filename, ajv.compile(schema)); +} + +assert.equal(corpus.length, 211); +assert.equal(new Set(corpus.map((item) => item.id)).size, corpus.length); +assert.deepEqual( + observations.map((item) => item.id), + corpus.map((item) => item.id), +); + +describe("JSON Schema/Zod measured non-equivalence", () => { + for (const item of corpus) { + it(`${item.family}: ${item.id}`, () => { + const expected = expectedById.get(item.id); + const boundary = boundaries[item.filename]; + const validate = validators.get(item.filename); + assert.ok(expected && boundary && validate, item.id); + assert.equal(expected.filename, item.filename); + assert.equal(expected.family, item.family); + const before = structuredClone(item.input); + assert.equal(validate(item.input), expected.jsonSchema, "JSON Schema acceptance"); + assert.deepEqual(item.input, before, "JSON Schema must not mutate input"); + assert.equal(boundary.schema.safeParse(item.input).success, expected.zod, "Zod acceptance"); + assert.deepEqual(item.input, before, "Zod must not mutate input"); + + const parse = boundary.parse; + const parser = expected.parser; + if (parse === null) { + assert.equal(parser, null, "no standalone parser for this export"); + } else { + assert.ok(parser); + if (parser.accepted) { + parse(item.input); + } else { + assert.throws( + () => parse(item.input), + (error: unknown) => { + if (parser.type === "ContractError") { + return error instanceof contracts.ContractError && error.code === parser.code; + } + if (parser.type === "ZodError") return error instanceof ZodError; + return ( + error instanceof Error && + error.constructor === Error && + error.message === parser.message + ); + }, + ); + } + assert.deepEqual(item.input, before, "parser must not mutate input"); + } + + if (expected.replay !== null) { + const replay = item.filename.startsWith("evidence-manifest.") + ? replayEvidenceManifest(item.input) + : replayQualificationReceipt(item.input); + assert.deepEqual(replay, expected.replay, "replay integrity and semantic flags"); + assert.deepEqual(item.input, before, "replay must not mutate input"); + } + }); + } +});