@plasius/gpu-shader 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/testing.js CHANGED
@@ -15,63 +15,267 @@ Object.freeze(SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES);
15
15
  var SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES = Object.freeze([]);
16
16
 
17
17
  // src/canonical-json.ts
18
- function isPlainObject(value) {
19
- const prototype = Object.getPrototypeOf(value);
20
- return prototype === Object.prototype || prototype === null;
18
+ var GPU_CONTRACT_SNAPSHOT_LIMITS = Object.freeze({
19
+ maximumDepth: 64,
20
+ maximumNodes: 262144,
21
+ maximumProperties: 131072,
22
+ maximumElements: 131072,
23
+ maximumArrayLength: 1e5,
24
+ maximumStringBytes: 1024 * 1024,
25
+ maximumAggregateStringBytes: 8 * 1024 * 1024,
26
+ maximumAggregateBytes: 16 * 1024 * 1024,
27
+ maximumInputBytes: 16 * 1024 * 1024
28
+ });
29
+ var QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS = Object.freeze({
30
+ maximumDepth: 96,
31
+ maximumNodes: 4e6,
32
+ maximumProperties: 2e6,
33
+ maximumElements: 2e6,
34
+ maximumArrayLength: 25e4,
35
+ maximumStringBytes: 4 * 1024 * 1024,
36
+ maximumAggregateStringBytes: 128 * 1024 * 1024,
37
+ maximumAggregateBytes: 256 * 1024 * 1024,
38
+ maximumInputBytes: 256 * 1024 * 1024
39
+ });
40
+ var FAILURE_MESSAGES = Object.freeze({
41
+ "aggregate-bytes": "GPU contract snapshot exceeds the aggregate byte limit.",
42
+ "aggregate-string-bytes": "GPU contract snapshot exceeds the aggregate string byte limit.",
43
+ "array-length": "GPU contract snapshot exceeds the single-array element limit.",
44
+ cycle: "GPU contract snapshot contains a circular reference.",
45
+ depth: "GPU contract snapshot exceeds the nesting-depth limit.",
46
+ elements: "GPU contract snapshot exceeds the total element limit.",
47
+ inspection: "GPU contract snapshot rejected unsafe object inspection.",
48
+ nodes: "GPU contract snapshot exceeds the total node limit.",
49
+ "non-finite": "GPU contract snapshot contains a non-finite number.",
50
+ properties: "GPU contract snapshot exceeds the total property limit.",
51
+ shape: "GPU contract snapshot requires plain JSON objects with own enumerable data properties and dense arrays.",
52
+ "string-bytes": "GPU contract snapshot exceeds the individual string byte limit.",
53
+ unicode: "GPU contract snapshot contains an invalid Unicode scalar string or unpaired UTF-16 surrogate.",
54
+ value: "GPU contract snapshot contains undefined or another value that JSON cannot represent."
55
+ });
56
+ var GpuContractSnapshotError = class extends TypeError {
57
+ code;
58
+ constructor(code) {
59
+ super(FAILURE_MESSAGES[code]);
60
+ this.name = "GpuContractSnapshotError";
61
+ this.code = code;
62
+ }
63
+ };
64
+ var TYPED_ARRAY_PROTOTYPE = Reflect.getPrototypeOf(Uint8Array.prototype);
65
+ var TYPED_ARRAY_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(
66
+ TYPED_ARRAY_PROTOTYPE,
67
+ "byteLength"
68
+ )?.get;
69
+ var TYPED_ARRAY_TAG = Reflect.getOwnPropertyDescriptor(
70
+ TYPED_ARRAY_PROTOTYPE,
71
+ Symbol.toStringTag
72
+ )?.get;
73
+ var UINT8_ARRAY_SET = Uint8Array.prototype.set;
74
+ function snapshotUint8Array(value, maximumBytes) {
75
+ if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0) {
76
+ throw new TypeError("GPU contract byte limit must be a non-negative safe integer.");
77
+ }
78
+ let byteLength;
79
+ let tag;
80
+ try {
81
+ if (!TYPED_ARRAY_BYTE_LENGTH || !TYPED_ARRAY_TAG) throw new TypeError();
82
+ byteLength = Reflect.apply(TYPED_ARRAY_BYTE_LENGTH, value, []);
83
+ tag = Reflect.apply(TYPED_ARRAY_TAG, value, []);
84
+ } catch {
85
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
86
+ }
87
+ if (tag !== "Uint8Array" || !Number.isSafeInteger(byteLength) || byteLength > maximumBytes) {
88
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
89
+ }
90
+ const output = new Uint8Array(byteLength);
91
+ try {
92
+ Reflect.apply(UINT8_ARRAY_SET, output, [value]);
93
+ } catch {
94
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
95
+ }
96
+ return output;
97
+ }
98
+ function fail(reason) {
99
+ throw new GpuContractSnapshotError(reason);
100
+ }
101
+ function inspected(operation) {
102
+ try {
103
+ return operation();
104
+ } catch {
105
+ return fail("inspection");
106
+ }
21
107
  }
22
- function assertUnicodeScalarString(value, path2) {
108
+ function assertLimit(value, maximum, reason) {
109
+ if (!Number.isSafeInteger(value) || value > maximum) fail(reason);
110
+ }
111
+ function quotedJsonByteLength(value, maximum) {
112
+ let raw = 0;
113
+ let quoted = 2;
23
114
  for (let index = 0; index < value.length; index += 1) {
24
115
  const code = value.charCodeAt(index);
25
- if (code >= 55296 && code <= 56319) {
116
+ if (code <= 127) {
117
+ raw += 1;
118
+ if (code <= 31) quoted += code === 8 || code === 9 || code === 10 || code === 12 || code === 13 ? 2 : 6;
119
+ else quoted += code === 34 || code === 92 ? 2 : 1;
120
+ } else if (code <= 2047) {
121
+ raw += 2;
122
+ quoted += 2;
123
+ } else if (code >= 55296 && code <= 56319) {
26
124
  const next = value.charCodeAt(index + 1);
27
- if (!(next >= 56320 && next <= 57343)) throw new TypeError(`${path2} contains an unpaired UTF-16 surrogate.`);
125
+ if (!(next >= 56320 && next <= 57343)) fail("unicode");
126
+ raw += 4;
127
+ quoted += 4;
28
128
  index += 1;
29
- } else if (code >= 56320 && code <= 57343) throw new TypeError(`${path2} contains an unpaired UTF-16 surrogate.`);
129
+ } else if (code >= 56320 && code <= 57343) fail("unicode");
130
+ else {
131
+ raw += 3;
132
+ quoted += 3;
133
+ }
134
+ if (raw > maximum) fail("string-bytes");
30
135
  }
136
+ return { raw, quoted };
31
137
  }
32
- function canonicalizeGpuContract(value) {
138
+ function assertLimits(limits) {
139
+ for (const value of Object.values(limits)) {
140
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError("GPU contract snapshot limits must be positive safe integers.");
141
+ }
142
+ }
143
+ function snapshotGpuContract(value, limits = GPU_CONTRACT_SNAPSHOT_LIMITS) {
144
+ assertLimits(limits);
33
145
  const ancestors = /* @__PURE__ */ new Set();
34
- const visit = (current, path2) => {
35
- if (current === null) return "null";
36
- if (typeof current === "string" || typeof current === "boolean") {
37
- if (typeof current === "string") assertUnicodeScalarString(current, path2);
38
- return JSON.stringify(current);
146
+ let nodes = 0;
147
+ let properties = 0;
148
+ let elements = 0;
149
+ let aggregateStringBytes = 0;
150
+ let aggregateBytes = 0;
151
+ const addAggregate = (bytes) => {
152
+ aggregateBytes += bytes;
153
+ assertLimit(aggregateBytes, limits.maximumAggregateBytes, "aggregate-bytes");
154
+ };
155
+ const addString = (text2) => {
156
+ const measured = quotedJsonByteLength(text2, limits.maximumStringBytes);
157
+ aggregateStringBytes += measured.raw;
158
+ assertLimit(aggregateStringBytes, limits.maximumAggregateStringBytes, "aggregate-string-bytes");
159
+ return measured.quoted;
160
+ };
161
+ const visit = (current, depth) => {
162
+ if (depth > limits.maximumDepth) fail("depth");
163
+ nodes += 1;
164
+ assertLimit(nodes, limits.maximumNodes, "nodes");
165
+ if (current === null) {
166
+ addAggregate(4);
167
+ return null;
39
168
  }
40
- if (typeof current === "number") {
41
- if (!Number.isFinite(current)) {
42
- throw new TypeError(`${path2} contains a non-finite number.`);
43
- }
44
- return Object.is(current, -0) ? "0" : JSON.stringify(current);
169
+ if (typeof current === "string") {
170
+ addAggregate(addString(current));
171
+ return current;
45
172
  }
46
- if (typeof current !== "object") {
47
- throw new TypeError(`${path2} contains a value that JSON cannot represent.`);
173
+ if (typeof current === "boolean") {
174
+ addAggregate(current ? 4 : 5);
175
+ return current;
48
176
  }
49
- if (ancestors.has(current)) {
50
- throw new TypeError(`${path2} contains a circular reference.`);
177
+ if (typeof current === "number") {
178
+ if (!Number.isFinite(current)) fail("non-finite");
179
+ const normalized = Object.is(current, -0) ? 0 : current;
180
+ addAggregate(JSON.stringify(normalized).length);
181
+ return normalized;
51
182
  }
183
+ if (typeof current !== "object") fail("value");
184
+ if (ancestors.has(current)) fail("cycle");
185
+ const isArray = inspected(() => Array.isArray(current));
186
+ const prototype = inspected(() => Reflect.getPrototypeOf(current));
187
+ if (isArray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) fail("shape");
52
188
  ancestors.add(current);
53
189
  try {
54
- if (Array.isArray(current)) {
55
- return `[${current.map((item, index) => visit(item, `${path2}[${index}]`)).join(",")}]`;
190
+ if (isArray) {
191
+ const lengthDescriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, "length"));
192
+ if (!lengthDescriptor || !Object.hasOwn(lengthDescriptor, "value") || lengthDescriptor.enumerable || typeof lengthDescriptor.value !== "number" || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0) fail("shape");
193
+ const length = lengthDescriptor.value;
194
+ assertLimit(length, limits.maximumArrayLength, "array-length");
195
+ elements += length;
196
+ assertLimit(elements, limits.maximumElements, "elements");
197
+ const ownKeys2 = inspected(() => Reflect.ownKeys(current));
198
+ if (ownKeys2.some((key) => typeof key !== "string")) fail("shape");
199
+ if (ownKeys2.length !== length + 1) fail("shape");
200
+ const keySet = new Set(ownKeys2);
201
+ if (!keySet.delete("length")) fail("shape");
202
+ const output2 = new Array(length);
203
+ addAggregate(2 + Math.max(0, length - 1));
204
+ for (let index = 0; index < length; index += 1) {
205
+ const key = String(index);
206
+ if (!keySet.delete(key)) fail("shape");
207
+ const descriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, key));
208
+ if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) fail("shape");
209
+ Object.defineProperty(output2, key, {
210
+ configurable: true,
211
+ enumerable: true,
212
+ value: visit(descriptor.value, depth + 1),
213
+ writable: true
214
+ });
215
+ }
216
+ if (keySet.size !== 0) fail("shape");
217
+ return output2;
56
218
  }
57
- if (!isPlainObject(current)) {
58
- throw new TypeError(`${path2} must contain only plain JSON objects.`);
219
+ const ownKeys = inspected(() => Reflect.ownKeys(current));
220
+ if (ownKeys.some((key) => typeof key !== "string")) fail("shape");
221
+ properties += ownKeys.length;
222
+ assertLimit(properties, limits.maximumProperties, "properties");
223
+ addAggregate(2 + Math.max(0, ownKeys.length - 1) + ownKeys.length);
224
+ const output = {};
225
+ for (const key of ownKeys) {
226
+ addAggregate(addString(key));
227
+ const descriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, key));
228
+ if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) fail("shape");
229
+ Object.defineProperty(output, key, {
230
+ configurable: true,
231
+ enumerable: true,
232
+ value: visit(descriptor.value, depth + 1),
233
+ writable: true
234
+ });
59
235
  }
60
- const keys2 = Object.keys(current).sort();
61
- const properties = keys2.map((key) => {
62
- assertUnicodeScalarString(key, `${path2} key`);
63
- const member = current[key];
64
- if (member === void 0) {
65
- throw new TypeError(`${path2}.${key} is undefined.`);
66
- }
67
- return `${JSON.stringify(key)}:${visit(member, `${path2}.${key}`)}`;
68
- });
69
- return `{${properties.join(",")}}`;
236
+ return output;
70
237
  } finally {
71
238
  ancestors.delete(current);
72
239
  }
73
240
  };
74
- return visit(value, "$root");
241
+ return visit(value, 0);
242
+ }
243
+ function serializeSnapshot(value) {
244
+ if (value === null) return "null";
245
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
246
+ if (typeof value === "number") return JSON.stringify(value);
247
+ if (Array.isArray(value)) return `[${value.map(serializeSnapshot).join(",")}]`;
248
+ const input = value;
249
+ return `{${Object.keys(input).sort().map((key) => `${JSON.stringify(key)}:${serializeSnapshot(input[key])}`).join(",")}}`;
250
+ }
251
+ function canonicalizeGpuContract(value) {
252
+ return serializeSnapshot(snapshotGpuContract(value));
253
+ }
254
+ function canonicalizeQualificationGpuContract(value) {
255
+ return serializeSnapshot(snapshotGpuContract(value, QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS));
256
+ }
257
+
258
+ // src/asset-version.ts
259
+ var ASSET_VERSION_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$/u;
260
+ var MUTABLE_VERSION_ALIASES = /* @__PURE__ */ new Set([
261
+ "latest",
262
+ "current",
263
+ "stable",
264
+ "preview",
265
+ "default",
266
+ "production",
267
+ "canary",
268
+ "next",
269
+ "head",
270
+ "main"
271
+ ]);
272
+ var X_WILDCARD_SEGMENT_PATTERN = /^(?:[vV])?[xX](?:\.|-|$)|\.[xX](?:\.|-|$)/u;
273
+ var IMMUTABLE_VERSION_ERROR_MESSAGE = "Immutable asset version must be an exact token up to 128 characters; mutable aliases, ranges, wildcards, and URLs are not allowed.";
274
+ function assertImmutableAssetVersion(value) {
275
+ if (typeof value !== "string" || !ASSET_VERSION_PATTERN.test(value) || MUTABLE_VERSION_ALIASES.has(value.toLowerCase()) || X_WILDCARD_SEGMENT_PATTERN.test(value)) {
276
+ throw new TypeError(IMMUTABLE_VERSION_ERROR_MESSAGE);
277
+ }
278
+ return value;
75
279
  }
76
280
 
77
281
  // src/hash.ts
@@ -96,6 +300,14 @@ async function computeSha256(value) {
96
300
 
97
301
  // src/manifest-validation.ts
98
302
  var stages = ["vertex", "fragment", "compute"];
303
+ function detachedJson(value, path2) {
304
+ try {
305
+ return snapshotGpuContract(value);
306
+ } catch (cause) {
307
+ const detail = cause instanceof GpuContractSnapshotError ? ` ${cause.message}` : "";
308
+ throw new TypeError(`${path2} must contain bounded detached JSON contract data.${detail}`);
309
+ }
310
+ }
99
311
  function object(value, path2) {
100
312
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${path2} must be an object.`);
101
313
  return value;
@@ -103,7 +315,7 @@ function object(value, path2) {
103
315
  function exact(value, keys2, path2) {
104
316
  const allowed = new Set(keys2);
105
317
  for (const key of Object.keys(value)) if (!allowed.has(key)) throw new TypeError(`${path2}.${key} is not part of this contract version.`);
106
- for (const key of keys2) if (!(key in value)) throw new TypeError(`${path2}.${key} is required.`);
318
+ for (const key of keys2) if (!Object.hasOwn(value, key)) throw new TypeError(`${path2}.${key} is required.`);
107
319
  }
108
320
  function text(value, path2, maximum = 512) {
109
321
  if (typeof value !== "string" || value.length === 0 || value.length > maximum || [...value].some((character) => character.charCodeAt(0) <= 31)) {
@@ -308,7 +520,7 @@ function pipeline(value, path2, moduleIds) {
308
520
  return input;
309
521
  }
310
522
  function parseSerializableGpuPipelineDescriptors(value, moduleIds, path2 = "pipelines") {
311
- const parsed = array(value, path2).map((item, index) => pipeline(item, `${path2}[${index}]`, new Set(moduleIds)));
523
+ const parsed = array(detachedJson(value, path2), path2).map((item, index) => pipeline(item, `${path2}[${index}]`, new Set(moduleIds)));
312
524
  unique(parsed, (item) => item.pipelineId, path2);
313
525
  return freeze(parsed);
314
526
  }
@@ -326,13 +538,26 @@ function issue(code, message, path2) {
326
538
  function object2(value) {
327
539
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
328
540
  }
541
+ function freezeJson(value) {
542
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
543
+ for (const child of Object.values(value)) freezeJson(child);
544
+ return Object.freeze(value);
545
+ }
329
546
  function exactKeys(value, keys2) {
330
547
  const expected = new Set(keys2);
331
- return Object.keys(value).every((key) => expected.has(key)) && keys2.every((key) => key in value);
548
+ return Object.keys(value).every((key) => expected.has(key)) && keys2.every((key) => Object.hasOwn(value, key));
332
549
  }
333
550
  function safeToken(value) {
334
551
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$/u.test(value) && !value.includes("..");
335
552
  }
553
+ function immutableVersion(value) {
554
+ try {
555
+ assertImmutableAssetVersion(value);
556
+ return true;
557
+ } catch {
558
+ return false;
559
+ }
560
+ }
336
561
  function validSha(value) {
337
562
  try {
338
563
  asSha256Hex(String(value));
@@ -345,8 +570,20 @@ function defineShaderCompileUnit(unit) {
345
570
  return Object.freeze(unit);
346
571
  }
347
572
  function validateCompileUnitInventory(value) {
348
- const envelope = object2(value);
349
- const candidate = envelope && "inventory" in envelope ? object2(value.inventory) : envelope;
573
+ let snapshot;
574
+ try {
575
+ snapshot = snapshotGpuContract(value, QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS);
576
+ } catch {
577
+ return {
578
+ ok: false,
579
+ diagnostics: [issue(
580
+ "invalid-contract",
581
+ "Compile-unit inventory must contain bounded detached JSON contract data."
582
+ )]
583
+ };
584
+ }
585
+ const envelope = object2(snapshot);
586
+ const candidate = envelope && Object.hasOwn(envelope, "inventory") ? object2(snapshot.inventory) : envelope;
350
587
  const diagnostics = [];
351
588
  if (!candidate || !exactKeys(candidate, ["contractVersion", "fragments", "compileUnits"])) {
352
589
  return { ok: false, diagnostics: [issue("invalid-contract", "Compile-unit inventory has unknown or missing fields.")] };
@@ -477,7 +714,7 @@ function validateCompileUnitInventory(value) {
477
714
  diagnostics.push(issue("invalid-contract", cause instanceof Error ? cause.message : "Compile-unit pipelines are invalid.", `${path2}.pipelines`));
478
715
  }
479
716
  const interfaceRef = object2(unit.interfaceRef);
480
- if (!interfaceRef || !exactKeys(interfaceRef, ["interfaceId", "interfaceVersion", "manifestUri", "manifestSha256", "interfaceAbiHash", "modelAbiHash"]) || !safeToken(interfaceRef.interfaceId) || !safeToken(interfaceRef.interfaceVersion) || typeof interfaceRef.manifestUri !== "string" || !interfaceRef.manifestUri.startsWith("https://") || !validSha(interfaceRef.manifestSha256) || !validSha(interfaceRef.interfaceAbiHash) || !validSha(interfaceRef.modelAbiHash)) {
717
+ if (!interfaceRef || !exactKeys(interfaceRef, ["interfaceId", "interfaceVersion", "manifestUri", "manifestSha256", "interfaceAbiHash", "modelAbiHash"]) || !safeToken(interfaceRef.interfaceId) || !immutableVersion(interfaceRef.interfaceVersion) || typeof interfaceRef.manifestUri !== "string" || !interfaceRef.manifestUri.startsWith("https://") || !validSha(interfaceRef.manifestSha256) || !validSha(interfaceRef.interfaceAbiHash) || !validSha(interfaceRef.modelAbiHash)) {
481
718
  diagnostics.push(issue("invalid-contract", "Compile-unit interfaceRef is invalid.", `${path2}.interfaceRef`));
482
719
  }
483
720
  const fixture = object2(unit.qualificationFixture);
@@ -488,7 +725,7 @@ function validateCompileUnitInventory(value) {
488
725
  for (const fragmentId of fragmentIds) {
489
726
  if (!covered.has(fragmentId)) diagnostics.push(issue("uncovered-fragment", `WGSL fragment ${fragmentId} has no compile unit.`));
490
727
  }
491
- return diagnostics.length > 0 ? { ok: false, diagnostics } : { ok: true, value: candidate };
728
+ return diagnostics.length > 0 ? { ok: false, diagnostics } : { ok: true, value: freezeJson(candidate) };
492
729
  }
493
730
 
494
731
  // src/testing/matrix.ts
@@ -500,7 +737,12 @@ function object3(value) {
500
737
  }
501
738
  function keys(value, expected) {
502
739
  const set = new Set(expected);
503
- return Object.keys(value).every((key) => set.has(key)) && expected.every((key) => key in value);
740
+ return Object.keys(value).every((key) => set.has(key)) && expected.every((key) => Object.hasOwn(value, key));
741
+ }
742
+ function freezeJson2(value) {
743
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
744
+ for (const child of Object.values(value)) freezeJson2(child);
745
+ return Object.freeze(value);
504
746
  }
505
747
  function canonicalEqual(left, right) {
506
748
  try {
@@ -550,7 +792,13 @@ var BASELINE = /* @__PURE__ */ new Map([
550
792
  ["win11-nvidia-edge-d3d12", "edge|windows|x64|physical|nvidia|qualified-nvidia|d3d12|playwright|self-hosted,Windows,X64,shader-validation,physical-gpu,gpu-nvidia,d3d12"]
551
793
  ]);
552
794
  function validateStableWebGpuMatrix(value) {
553
- const matrix = object3(value);
795
+ let snapshot;
796
+ try {
797
+ snapshot = snapshotGpuContract(value);
798
+ } catch {
799
+ return { ok: false, diagnostics: [issue2("Matrix must contain bounded detached JSON contract data.")] };
800
+ }
801
+ const matrix = object3(snapshot);
554
802
  const diagnostics = [];
555
803
  if (!matrix || !keys(matrix, ["contractVersion", "matrixId", "version", "policy", "cells"])) {
556
804
  return { ok: false, diagnostics: [issue2("Matrix has unknown or missing top-level fields.")] };
@@ -623,7 +871,7 @@ function validateStableWebGpuMatrix(value) {
623
871
  }
624
872
  }
625
873
  if (physical !== 15 || blocking !== 16 || software !== 1 || ids.size !== BASELINE.size) diagnostics.push(issue2("Matrix must contain the exact 15 physical baseline cells plus one SwiftShader smoke cell."));
626
- return diagnostics.length > 0 ? { ok: false, diagnostics } : { ok: true, value: matrix };
874
+ return diagnostics.length > 0 ? { ok: false, diagnostics } : { ok: true, value: freezeJson2(matrix) };
627
875
  }
628
876
 
629
877
  // src/testing/qualification-bundle.ts
@@ -715,14 +963,33 @@ function object4(value, path2) {
715
963
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${path2} must be an object.`);
716
964
  return value;
717
965
  }
966
+ function detachedJson2(value, label) {
967
+ try {
968
+ return snapshotGpuContract(value, QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS);
969
+ } catch {
970
+ throw new TypeError(`${label} must contain bounded detached JSON contract data.`);
971
+ }
972
+ }
973
+ function freezeJson3(value) {
974
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
975
+ for (const child of Object.values(value)) freezeJson3(child);
976
+ return Object.freeze(value);
977
+ }
718
978
  function exact2(value, keys2, path2) {
719
979
  const expected = new Set(keys2);
720
- if (!Object.keys(value).every((key) => expected.has(key)) || !keys2.every((key) => key in value)) throw new TypeError(`${path2} has unknown or missing fields.`);
980
+ if (!Object.keys(value).every((key) => expected.has(key)) || !keys2.every((key) => Object.hasOwn(value, key))) throw new TypeError(`${path2} has unknown or missing fields.`);
721
981
  }
722
982
  function token2(value, path2) {
723
983
  if (typeof value !== "string" || !TOKEN.test(value) || value.includes("..")) throw new TypeError(`${path2} must be a safe token.`);
724
984
  return value;
725
985
  }
986
+ function immutableVersion2(value, path2) {
987
+ try {
988
+ return assertImmutableAssetVersion(value);
989
+ } catch {
990
+ throw new TypeError(`${path2} must be an immutable asset version: exact token required; mutable aliases, ranges, wildcards, and URLs are not allowed.`);
991
+ }
992
+ }
726
993
  function path(value, label, extensions) {
727
994
  if (typeof value !== "string" || !SAFE_PATH2.test(value) || !extensions.some((extension) => value.endsWith(extension))) {
728
995
  throw new TypeError(`${label} must be a safe data-only bundle path (${extensions.join(", ")}).`);
@@ -732,8 +999,8 @@ function path(value, label, extensions) {
732
999
  function sha(value, label) {
733
1000
  try {
734
1001
  return asSha256Hex(String(value));
735
- } catch (cause) {
736
- throw new TypeError(`${label} must be a lowercase SHA-256 digest.`, { cause });
1002
+ } catch {
1003
+ throw new TypeError(`${label} must be a lowercase SHA-256 digest.`);
737
1004
  }
738
1005
  }
739
1006
  function integer2(value, label, minimum = 0, maximum = 4294967295) {
@@ -857,7 +1124,8 @@ function jsonValue(value, label, depth = 0) {
857
1124
  }
858
1125
  function validateQualificationFixture(value, unit) {
859
1126
  try {
860
- const fixture = object4(value, "fixture");
1127
+ const compileUnit = unit === void 0 ? void 0 : detachedJson2(unit, "compile unit");
1128
+ const fixture = object4(detachedJson2(value, "fixture"), "fixture");
861
1129
  exact2(fixture, ["contractVersion", "fixtureId", "resources", "bindGroups", "commands", "layoutProbes", "readbacks", "bounds"], "fixture");
862
1130
  if (fixture.contractVersion !== SHADER_QUALIFICATION_FIXTURE_VERSION) throw new TypeError("Unsupported qualification fixture version.");
863
1131
  token2(fixture.fixtureId, "fixture.fixtureId");
@@ -987,14 +1255,14 @@ function validateQualificationFixture(value, unit) {
987
1255
  unique2(bindingIds, `${label}.entries`);
988
1256
  bindGroups.set(id, { group: groupIndex, entries: parsedEntries });
989
1257
  }
990
- const pipelines = new Map(unit?.pipelines.map((pipeline2) => [pipeline2.pipelineId, pipeline2]) ?? []);
1258
+ const pipelines = new Map(compileUnit?.pipelines.map((pipeline2) => [pipeline2.pipelineId, pipeline2]) ?? []);
991
1259
  const pipelineIds = new Set(pipelines.keys());
992
1260
  const commandBindGroups = (value2, pipelineId, label) => {
993
1261
  const ids = boundedArray(value2, label, 32).map((item, index) => token2(item, `${label}[${index}]`));
994
1262
  unique2(ids, label);
995
1263
  const pipeline2 = pipelines.get(pipelineId);
996
1264
  if (!pipeline2) {
997
- if (unit) throw new TypeError(`${label} pipeline is missing.`);
1265
+ if (compileUnit) throw new TypeError(`${label} pipeline is missing.`);
998
1266
  return;
999
1267
  }
1000
1268
  const expectedGroups = [...pipeline2.layout.bindGroups].sort((left, right) => left.group - right.group);
@@ -1019,7 +1287,7 @@ function validateQualificationFixture(value, unit) {
1019
1287
  executionCommands += 1;
1020
1288
  exact2(command, ["kind", "pipelineId", "bindGroupIds", "workgroups"], label);
1021
1289
  const id = token2(command.pipelineId, `${label}.pipelineId`);
1022
- if (unit && pipelines.get(id)?.kind !== "compute") throw new TypeError(`${label} references a missing or non-compute pipeline.`);
1290
+ if (compileUnit && pipelines.get(id)?.kind !== "compute") throw new TypeError(`${label} references a missing or non-compute pipeline.`);
1023
1291
  commandBindGroups(command.bindGroupIds, id, `${label}.bindGroupIds`);
1024
1292
  const workgroups = tuple(command.workgroups, `${label}.workgroups`, 3, 1);
1025
1293
  if (workgroups[0] * workgroups[1] * workgroups[2] > 1048576) throw new TypeError(`${label}.workgroups exceeds the hard dispatch bound.`);
@@ -1193,14 +1461,14 @@ function validateQualificationFixture(value, unit) {
1193
1461
  }
1194
1462
  unique2(probeIds, "fixture.layoutProbes probe IDs");
1195
1463
  unique2(probeSources, "fixture.layoutProbes model sources");
1196
- return { ok: true, value: fixture };
1464
+ return { ok: true, value: freezeJson3(fixture) };
1197
1465
  } catch (cause) {
1198
1466
  return { ok: false, diagnostics: [{ code: "invalid-contract", severity: "error", message: cause instanceof Error ? cause.message : "Invalid qualification fixture." }] };
1199
1467
  }
1200
1468
  }
1201
1469
  function validateQualificationBundleManifest(value) {
1202
1470
  try {
1203
- const bundle = object4(value, "qualification");
1471
+ const bundle = object4(detachedJson2(value, "qualification"), "qualification");
1204
1472
  exact2(bundle, ["contractVersion", "inventory", "subject", "shaderManifestCorePath", "gpuInterfaceManifest", "modelCompatibilityFixtures", "modules", "fixtures"], "qualification");
1205
1473
  if (bundle.contractVersion !== SHADER_QUALIFICATION_BUNDLE_VERSION) throw new TypeError("Unsupported qualification bundle version.");
1206
1474
  const inventory = validateCompileUnitInventory(bundle.inventory);
@@ -1210,7 +1478,7 @@ function validateQualificationBundleManifest(value) {
1210
1478
  const candidate = object4(subject.shaderManifestCore, "qualification.subject.shaderManifestCore");
1211
1479
  exact2(candidate, ["shaderId", "version", "sha256"], "qualification.subject.shaderManifestCore");
1212
1480
  token2(candidate.shaderId, "qualification.subject.shaderManifestCore.shaderId");
1213
- token2(candidate.version, "qualification.subject.shaderManifestCore.version");
1481
+ immutableVersion2(candidate.version, "qualification.subject.shaderManifestCore.version");
1214
1482
  sha(candidate.sha256, "qualification.subject.shaderManifestCore.sha256");
1215
1483
  path(bundle.shaderManifestCorePath, "qualification.shaderManifestCorePath", [".json"]);
1216
1484
  const interfaceManifest = object4(bundle.gpuInterfaceManifest, "qualification.gpuInterfaceManifest");
@@ -1270,7 +1538,7 @@ function validateQualificationBundleManifest(value) {
1270
1538
  const expectedUnits = [...inventory.value.compileUnits.map((unit) => unit.compileUnitId)].sort();
1271
1539
  if (unitIds.join("\n") !== expectedUnits.join("\n")) throw new TypeError("Subject compile-unit IDs differ from inventory.");
1272
1540
  orderedUniqueTokens(subject.requiredCellIds, "qualification.subject.requiredCellIds");
1273
- return { ok: true, value: bundle };
1541
+ return { ok: true, value: freezeJson3(bundle) };
1274
1542
  } catch (cause) {
1275
1543
  return { ok: false, diagnostics: [{ code: "invalid-contract", severity: "error", message: cause instanceof Error ? cause.message : "Invalid qualification bundle." }] };
1276
1544
  }
@@ -1283,7 +1551,37 @@ function object5(value, path2) {
1283
1551
  }
1284
1552
  function exact3(value, keys2, path2) {
1285
1553
  const expected = new Set(keys2);
1286
- if (!Object.keys(value).every((key) => expected.has(key)) || !keys2.every((key) => key in value)) throw new TypeError(`${path2} has unknown or missing fields.`);
1554
+ if (!Object.keys(value).every((key) => expected.has(key)) || !keys2.every((key) => Object.hasOwn(value, key))) throw new TypeError(`${path2} has unknown or missing fields.`);
1555
+ }
1556
+ function detachedQualificationContract(value) {
1557
+ try {
1558
+ return snapshotGpuContract(value, QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS);
1559
+ } catch {
1560
+ throw new TypeError("Qualification data must contain bounded detached JSON contract data.");
1561
+ }
1562
+ }
1563
+ function parseQualificationJsonBytes(bytes, label) {
1564
+ let snapshot;
1565
+ try {
1566
+ snapshot = snapshotUint8Array(
1567
+ bytes,
1568
+ QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
1569
+ );
1570
+ } catch {
1571
+ throw new TypeError(`${label} is not bounded UTF-8 JSON.`);
1572
+ }
1573
+ let parsed;
1574
+ try {
1575
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(snapshot));
1576
+ } catch {
1577
+ throw new TypeError(`${label} is not valid UTF-8 JSON.`);
1578
+ }
1579
+ return detachedQualificationContract(parsed);
1580
+ }
1581
+ function freezeJson4(value) {
1582
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
1583
+ for (const child of Object.values(value)) freezeJson4(child);
1584
+ return Object.freeze(value);
1287
1585
  }
1288
1586
  function token3(value, path2, maximum = 512) {
1289
1587
  if (typeof value !== "string" || value.length === 0 || value.length > maximum || [...value].some((character) => character.charCodeAt(0) <= 31)) throw new TypeError(`${path2} is not a bounded string.`);
@@ -1292,8 +1590,8 @@ function token3(value, path2, maximum = 512) {
1292
1590
  function sha2(value, path2) {
1293
1591
  try {
1294
1592
  return asSha256Hex(token3(value, path2, 64));
1295
- } catch (cause) {
1296
- throw new TypeError(`${path2} is not a SHA-256 digest.`, { cause });
1593
+ } catch {
1594
+ throw new TypeError(`${path2} is not a SHA-256 digest.`);
1297
1595
  }
1298
1596
  }
1299
1597
  function integer3(value, path2, minimum = 0) {
@@ -1326,7 +1624,7 @@ function trustedWorkflowRef(value, path2) {
1326
1624
  return result;
1327
1625
  }
1328
1626
  function parseTrustedWorkflowProvenance(value, path2 = "provenance") {
1329
- const input = object5(value, path2);
1627
+ const input = object5(detachedQualificationContract(value), path2);
1330
1628
  exact3(input, ["repository", "commit", "ref", "workflowRef", "workflowSha", "runId", "runAttempt", "job", "eventName", "oidcAttestation"], path2);
1331
1629
  const repository = token3(input.repository, `${path2}.repository`);
1332
1630
  if (!repository.startsWith("Plasius-LTD/")) throw new TypeError(`${path2}.repository is outside Plasius-LTD.`);
@@ -1345,10 +1643,10 @@ function parseTrustedWorkflowProvenance(value, path2 = "provenance") {
1345
1643
  token3(oidc.audience, `${path2}.oidcAttestation.audience`, 2048);
1346
1644
  sha2(oidc.verifiedClaimsSha256, `${path2}.oidcAttestation.verifiedClaimsSha256`);
1347
1645
  timestamp(oidc.verifiedAt, `${path2}.oidcAttestation.verifiedAt`);
1348
- return input;
1646
+ return freezeJson4(input);
1349
1647
  }
1350
1648
  function parseQualificationExecutionProducer(value, path2 = "producer") {
1351
- const input = object5(value, path2);
1649
+ const input = object5(detachedQualificationContract(value), path2);
1352
1650
  exact3(input, ["repository", "commit", "ref", "runId", "runAttempt", "job", "trustedWorkflowRepository", "trustedWorkflowRef", "trustedWorkflowSha", "runner"], path2);
1353
1651
  const repository = token3(input.repository, `${path2}.repository`);
1354
1652
  if (!repository.startsWith("Plasius-LTD/")) throw new TypeError(`${path2}.repository is outside Plasius-LTD.`);
@@ -1366,7 +1664,7 @@ function parseQualificationExecutionProducer(value, path2 = "producer") {
1366
1664
  if (!["github-hosted", "self-hosted", "device-farm"].includes(String(runner.environment))) throw new TypeError(`${path2}.runner.environment is invalid.`);
1367
1665
  token3(runner.os, `${path2}.runner.os`);
1368
1666
  token3(runner.architecture, `${path2}.runner.architecture`);
1369
- return input;
1667
+ return freezeJson4(input);
1370
1668
  }
1371
1669
  function assertProducerMatchesPreflight(producer, provenance, cell, path2, expectedJob) {
1372
1670
  if (producer.repository !== provenance.repository || !canonicalEqual2(producer.commit, provenance.commit) || producer.ref !== provenance.ref || producer.runId !== provenance.runId || producer.runAttempt !== provenance.runAttempt || producer.trustedWorkflowRepository !== "Plasius-LTD/gpu-shader" || producer.trustedWorkflowRef !== provenance.workflowRef || !canonicalEqual2(producer.trustedWorkflowSha, provenance.workflowSha) || producer.job !== expectedJob) throw new TypeError(`${path2} does not match the exact qualification workflow run or subject.`);
@@ -1375,26 +1673,32 @@ function assertProducerMatchesPreflight(producer, provenance, cell, path2, expec
1375
1673
  if (expectedJob === "physical-runner-preflight" && producer.runner.environment !== "github-hosted") throw new TypeError(`${path2} must identify its hosted orchestration job truthfully.`);
1376
1674
  }
1377
1675
  function canonicalEqual2(left, right) {
1378
- return canonicalizeGpuContract(left) === canonicalizeGpuContract(right);
1676
+ return canonicalizeQualificationGpuContract(left) === canonicalizeQualificationGpuContract(right);
1379
1677
  }
1380
1678
  function foldRunnerLabel(value) {
1381
1679
  return value.replace(/[A-Z]/gu, (character) => character.toLowerCase());
1382
1680
  }
1383
1681
  async function computeQualificationInventorySha256(bundle) {
1384
- return computeSha256(canonicalizeGpuContract(bundle.inventory));
1682
+ const snapshot = detachedQualificationContract(bundle);
1683
+ return computeSha256(canonicalizeQualificationGpuContract(snapshot.inventory));
1385
1684
  }
1386
1685
  async function computeQualificationSubjectBinding(input) {
1387
1686
  return computeSha256(`plasius.gpu.qualification-subject/v1
1388
- ${canonicalizeGpuContract(input)}`);
1687
+ ${canonicalizeQualificationGpuContract(input)}`);
1389
1688
  }
1390
1689
  async function computeValidationEvidenceId(value) {
1391
1690
  const input = object5(value, "evidence identity input");
1392
1691
  const projection = Object.fromEntries(Object.entries(input).filter(([key]) => key !== "evidenceId"));
1393
1692
  return `qualification-${(await computeSha256(`plasius.gpu.validation-evidence/v1
1394
- ${canonicalizeGpuContract(projection)}`)).slice(0, 24)}`;
1693
+ ${canonicalizeQualificationGpuContract(projection)}`)).slice(0, 24)}`;
1395
1694
  }
1396
1695
  function immutableBlobUri(value) {
1397
- const url = new URL(value);
1696
+ let url;
1697
+ try {
1698
+ url = new URL(value);
1699
+ } catch {
1700
+ throw new TypeError("Source URI must be a normalized immutable Azure Blob .tar URL.");
1701
+ }
1398
1702
  if (url.protocol !== "https:" || url.username || url.password || url.hash || url.port || !/^[a-z0-9]{3,24}\.blob\.core\.windows\.net$/u.test(url.hostname) || !/^[A-Za-z0-9][A-Za-z0-9._/-]*\.tar$/u.test(url.pathname.slice(1)) || url.pathname.split("/").some((segment, index) => index > 0 && (!segment || segment === "." || segment === ".."))) {
1399
1703
  throw new TypeError("Source URI must be a normalized immutable Azure Blob .tar URL.");
1400
1704
  }
@@ -1404,12 +1708,7 @@ function immutableBlobUri(value) {
1404
1708
  }
1405
1709
  async function createQualificationPreflight(input) {
1406
1710
  token3(input.qualificationId, "qualificationId");
1407
- let parsedMatrix;
1408
- try {
1409
- parsedMatrix = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(input.matrixBytes));
1410
- } catch (cause) {
1411
- throw new TypeError("Selected matrix artifact is not UTF-8 JSON.", { cause });
1412
- }
1711
+ const parsedMatrix = parseQualificationJsonBytes(input.matrixBytes, "Selected matrix artifact");
1413
1712
  if (!canonicalEqual2(parsedMatrix, input.matrix)) throw new TypeError("Selected matrix artifact bytes differ from the supplied matrix value.");
1414
1713
  const actualMatrixSha256 = await computeSha256(input.matrixBytes);
1415
1714
  if (actualMatrixSha256 !== input.matrixSha256) throw new TypeError("Selected matrix digest is not derived from the exact matrix manifest.");
@@ -1579,12 +1878,7 @@ function syntheticResult(unitId, cell, status, message, now) {
1579
1878
  async function aggregateShaderValidationEvidence(input) {
1580
1879
  const verifyArtifact = async (artifact, label) => {
1581
1880
  if (await computeSha256(artifact.bytes) !== artifact.sha256) throw new TypeError(`${label} artifact digest is not derived from its exact bytes.`);
1582
- let parsed;
1583
- try {
1584
- parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(artifact.bytes));
1585
- } catch (cause) {
1586
- throw new TypeError(`${label} bytes are not UTF-8 JSON.`, { cause });
1587
- }
1881
+ const parsed = parseQualificationJsonBytes(artifact.bytes, `${label} bytes`);
1588
1882
  if (!canonicalEqual2(parsed, artifact.value)) throw new TypeError(`${label} parsed value differs from its exact bytes.`);
1589
1883
  };
1590
1884
  await verifyArtifact(input.preflight, "Qualification preflight");
@@ -1606,12 +1900,7 @@ async function aggregateShaderValidationEvidence(input) {
1606
1900
  exact3(sourceBlob, ["host", "versionId", "uri"], "Qualification preflight.sourceBlob");
1607
1901
  const normalizedSource = immutableBlobUri(token3(sourceBlob.uri, "Qualification preflight.sourceBlob.uri", 2048));
1608
1902
  if (!canonicalEqual2(sourceBlob, normalizedSource)) throw new TypeError("Qualification preflight source Blob claims are stale.");
1609
- let parsedMatrix;
1610
- try {
1611
- parsedMatrix = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(input.matrixBytes));
1612
- } catch (cause) {
1613
- throw new TypeError("Matrix artifact is not UTF-8 JSON.", { cause });
1614
- }
1903
+ const parsedMatrix = parseQualificationJsonBytes(input.matrixBytes, "Matrix artifact");
1615
1904
  if (!canonicalEqual2(parsedMatrix, input.matrix)) throw new TypeError("Matrix artifact bytes differ from the supplied matrix value.");
1616
1905
  const actualMatrixSha256 = await computeSha256(input.matrixBytes);
1617
1906
  if (preflight.matrixSha256 !== actualMatrixSha256) throw new TypeError("Qualification preflight matrix artifact digest is stale.");
@@ -1685,7 +1974,7 @@ async function aggregateShaderValidationEvidence(input) {
1685
1974
  if (cellArtifact || diagnostic) throw new TypeError(`Unavailable cell ${cell.cellId} has conflicting evidence.`);
1686
1975
  for (const unit of units) results.push(syntheticResult(unit, cell, "runner-unavailable", "Required physical runner was unavailable.", now));
1687
1976
  const cellResults = results.slice(-units.size);
1688
- cellRuns.push({ cellId: cell.cellId, source: "runner-preflight", sourceArtifactSha256: runner.sha256, resultsSha256: await computeSha256(canonicalizeGpuContract(cellResults)), qualificationPreflightProvenance: preflight.provenance, producer: runner.value.producer, harness: input.harness, automation: null, resultCount: units.size, status: "runner-unavailable" });
1977
+ cellRuns.push({ cellId: cell.cellId, source: "runner-preflight", sourceArtifactSha256: runner.sha256, resultsSha256: await computeSha256(canonicalizeQualificationGpuContract(cellResults)), qualificationPreflightProvenance: preflight.provenance, producer: runner.value.producer, harness: input.harness, automation: null, resultCount: units.size, status: "runner-unavailable" });
1689
1978
  continue;
1690
1979
  }
1691
1980
  if (diagnostic) {
@@ -1700,7 +1989,7 @@ async function aggregateShaderValidationEvidence(input) {
1700
1989
  const status2 = value2.status === "timeout" ? "timeout" : "failed";
1701
1990
  for (const unit of units) results.push(syntheticResult(unit, cell, status2, value2.message, now));
1702
1991
  const cellResults = results.slice(-units.size);
1703
- cellRuns.push({ cellId: cell.cellId, source: "workflow-diagnostic", sourceArtifactSha256: diagnostic.sha256, resultsSha256: await computeSha256(canonicalizeGpuContract(cellResults)), qualificationPreflightProvenance: preflight.provenance, producer: value2.producer, harness: input.harness, automation: null, resultCount: units.size, status: status2 });
1992
+ cellRuns.push({ cellId: cell.cellId, source: "workflow-diagnostic", sourceArtifactSha256: diagnostic.sha256, resultsSha256: await computeSha256(canonicalizeQualificationGpuContract(cellResults)), qualificationPreflightProvenance: preflight.provenance, producer: value2.producer, harness: input.harness, automation: null, resultCount: units.size, status: status2 });
1704
1993
  continue;
1705
1994
  }
1706
1995
  if (!cellArtifact) throw new TypeError(`Cell ${cell.cellId} has no qualification evidence.`);
@@ -1708,7 +1997,7 @@ async function aggregateShaderValidationEvidence(input) {
1708
1997
  if (!matchedRunner) throw new TypeError(`Cell evidence ${cell.cellId} producer was not matched by runner preflight.`);
1709
1998
  const value = assertCellEvidence(cellArtifact.value, cell, input.matrix, preflight, input.harness, runner.value.adapterHarness, matchedRunner, units, now);
1710
1999
  results.push(...value.results);
1711
- cellRuns.push({ cellId: cell.cellId, source: "cell-evidence", sourceArtifactSha256: cellArtifact.sha256, resultsSha256: await computeSha256(canonicalizeGpuContract(value.results)), qualificationPreflightProvenance: value.qualificationPreflightProvenance, producer: value.producer, harness: value.harness, automation: value.automation, resultCount: value.results.length, status: "passed" });
2000
+ cellRuns.push({ cellId: cell.cellId, source: "cell-evidence", sourceArtifactSha256: cellArtifact.sha256, resultsSha256: await computeSha256(canonicalizeQualificationGpuContract(value.results)), qualificationPreflightProvenance: value.qualificationPreflightProvenance, producer: value.producer, harness: value.harness, automation: value.automation, resultCount: value.results.length, status: "passed" });
1712
2001
  }
1713
2002
  const expectedResults = units.size * cells.size;
1714
2003
  if (results.length !== expectedResults) throw new TypeError("Aggregate result product is incomplete.");
@@ -1731,34 +2020,31 @@ async function aggregateShaderValidationEvidence(input) {
1731
2020
  }
1732
2021
  async function validateShaderValidationEvidence(input) {
1733
2022
  try {
1734
- const evidence = object5(input.evidence, "evidence");
2023
+ const evidence = object5(detachedQualificationContract(input.evidence), "evidence");
2024
+ const bundle = detachedQualificationContract(input.bundle);
2025
+ const matrix = detachedQualificationContract(input.matrix);
1735
2026
  exact3(evidence, ["contractVersion", "evidenceId", "status", "generatedAt", "subjectBindingSha256", "subject", "matrixRef", "toolchain", "qualificationPreflightProvenance", "counts", "cellRuns", "results"], "evidence");
1736
2027
  if (evidence.contractVersion !== SHADER_VALIDATION_EVIDENCE_VERSION) throw new TypeError("Unsupported evidence contract version.");
1737
2028
  const evidenceId = token3(evidence.evidenceId, "evidence.evidenceId");
1738
2029
  const generatedAt = timestamp(evidence.generatedAt, "evidence.generatedAt");
1739
2030
  const subjectBindingSha256 = sha2(evidence.subjectBindingSha256, "evidence.subjectBindingSha256");
1740
2031
  if (evidence.status !== "passed" && evidence.status !== "failed") throw new TypeError("Evidence status is invalid.");
1741
- let parsedMatrix;
1742
- try {
1743
- parsedMatrix = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(input.matrixBytes));
1744
- } catch (cause) {
1745
- throw new TypeError("Matrix artifact is not UTF-8 JSON.", { cause });
1746
- }
1747
- if (!canonicalEqual2(parsedMatrix, input.matrix)) throw new TypeError("Matrix artifact bytes differ from the supplied matrix value.");
2032
+ const parsedMatrix = parseQualificationJsonBytes(input.matrixBytes, "Matrix artifact");
2033
+ if (!canonicalEqual2(parsedMatrix, matrix)) throw new TypeError("Matrix artifact bytes differ from the supplied matrix value.");
1748
2034
  const matrixSha256 = await computeSha256(input.matrixBytes);
1749
- const inventorySha256 = await computeQualificationInventorySha256(input.bundle);
1750
- if (inventorySha256 !== input.bundle.subject.compileUnitInventorySha256) throw new TypeError("Bundle subject inventory digest is stale.");
2035
+ const inventorySha256 = await computeQualificationInventorySha256(bundle);
2036
+ if (inventorySha256 !== bundle.subject.compileUnitInventorySha256) throw new TypeError("Bundle subject inventory digest is stale.");
1751
2037
  const subject = object5(evidence.subject, "evidence.subject");
1752
- const expectedSubjectKeys = [...Object.keys(input.bundle.subject), "dataBundleSha256"];
2038
+ const expectedSubjectKeys = [...Object.keys(bundle.subject), "dataBundleSha256"];
1753
2039
  exact3(subject, expectedSubjectKeys, "evidence.subject");
1754
2040
  const candidateSubject = Object.fromEntries(Object.entries(subject).filter(([key]) => key !== "dataBundleSha256"));
1755
- if (!canonicalEqual2(candidateSubject, input.bundle.subject)) throw new TypeError("Evidence candidate subject differs from bundle.");
2041
+ if (!canonicalEqual2(candidateSubject, bundle.subject)) throw new TypeError("Evidence candidate subject differs from bundle.");
1756
2042
  const dataBundleSha256 = sha2(subject.dataBundleSha256, "evidence.subject.dataBundleSha256");
1757
2043
  if (input.dataBundleSha256 && input.dataBundleSha256 !== dataBundleSha256) throw new TypeError("Evidence data bundle digest differs from the exact archive.");
1758
2044
  if (subject.compileUnitInventorySha256 !== inventorySha256) throw new TypeError("Evidence compile-unit inventory digest is stale.");
1759
2045
  const matrixRef = object5(evidence.matrixRef, "evidence.matrixRef");
1760
2046
  exact3(matrixRef, ["matrixId", "version", "sha256"], "evidence.matrixRef");
1761
- if (matrixRef.matrixId !== input.matrix.matrixId || matrixRef.version !== input.matrix.version || matrixRef.sha256 !== matrixSha256) throw new TypeError("Evidence matrix artifact identity differs.");
2047
+ if (matrixRef.matrixId !== matrix.matrixId || matrixRef.version !== matrix.version || matrixRef.sha256 !== matrixSha256) throw new TypeError("Evidence matrix artifact identity differs.");
1762
2048
  const toolchain = object5(evidence.toolchain, "evidence.toolchain");
1763
2049
  exact3(toolchain, ["packageVersion", "reflectorVersion", "harness"], "evidence.toolchain");
1764
2050
  token3(toolchain.packageVersion, "evidence.toolchain.packageVersion");
@@ -1770,11 +2056,11 @@ async function validateShaderValidationEvidence(input) {
1770
2056
  const harnessSha256 = sha2(harness.sha256, "evidence.toolchain.harness.sha256");
1771
2057
  const preflightProvenance = parseTrustedWorkflowProvenance(evidence.qualificationPreflightProvenance, "evidence.qualificationPreflightProvenance");
1772
2058
  if (Date.parse(generatedAt) < Date.parse(preflightProvenance.oidcAttestation.verifiedAt)) throw new TypeError("Evidence predates trusted preflight verification.");
1773
- const expectedBinding = await computeQualificationSubjectBinding({ subject: input.bundle.subject, dataBundleSha256, compileUnitInventorySha256: inventorySha256, matrixSha256, harnessSha256 });
2059
+ const expectedBinding = await computeQualificationSubjectBinding({ subject: bundle.subject, dataBundleSha256, compileUnitInventorySha256: inventorySha256, matrixSha256, harnessSha256 });
1774
2060
  if (subjectBindingSha256 !== expectedBinding) throw new TypeError("Evidence subject binding is stale.");
1775
2061
  if (evidenceId !== await computeValidationEvidenceId(evidence)) throw new TypeError("Evidence identity is stale.");
1776
- const units = new Set(input.bundle.inventory.compileUnits.map((unit) => unit.compileUnitId));
1777
- const cells = new Map(input.matrix.cells.map((cell) => [cell.cellId, cell]));
2062
+ const units = new Set(bundle.inventory.compileUnits.map((unit) => unit.compileUnitId));
2063
+ const cells = new Map(matrix.cells.map((cell) => [cell.cellId, cell]));
1778
2064
  const expected = units.size * cells.size;
1779
2065
  const results = array2(evidence.results, "evidence.results");
1780
2066
  if (results.length !== expected) throw new TypeError("Evidence result product is incomplete.");
@@ -1824,7 +2110,7 @@ async function validateShaderValidationEvidence(input) {
1824
2110
  sha2(automation2.sha256, `${path2}.automation.sha256`);
1825
2111
  } else if (run.automation !== null) throw new TypeError(`${path2}.automation must be null when no adapter completed a cell run.`);
1826
2112
  const cellResults = parsedResults.filter((result) => result.cellId === cellId);
1827
- if (run.resultCount !== units.size || cellResults.length !== units.size || await computeSha256(canonicalizeGpuContract(cellResults)) !== resultsSha256) throw new TypeError(`${path2} result count/digest is stale.`);
2113
+ if (run.resultCount !== units.size || cellResults.length !== units.size || await computeSha256(canonicalizeQualificationGpuContract(cellResults)) !== resultsSha256) throw new TypeError(`${path2} result count/digest is stale.`);
1828
2114
  const resultStatuses = new Set(cellResults.map((result) => result.status));
1829
2115
  if (resultStatuses.size !== 1 || !resultStatuses.has(String(run.status))) throw new TypeError(`${path2}.status differs from its results.`);
1830
2116
  if (run.source === "cell-evidence" && run.status !== "passed") throw new TypeError(`${path2} cell evidence must contain passing results.`);
@@ -1833,13 +2119,13 @@ async function validateShaderValidationEvidence(input) {
1833
2119
  if (run.source === "cell-evidence" && cellResults.some((result) => result.observed.runner.id !== producer.runner.name)) throw new TypeError(`${path2} producer runner differs from its results.`);
1834
2120
  }
1835
2121
  if (evidence.status === "passed" !== (passed === expected) || input.requirePassed !== false && evidence.status !== "passed") throw new TypeError("Evidence does not satisfy the required passed gate.");
1836
- return { ok: true, value: evidence };
2122
+ return { ok: true, value: freezeJson4(evidence) };
1837
2123
  } catch (cause) {
1838
2124
  return { ok: false, diagnostics: [{ code: "invalid-contract", severity: "error", message: cause instanceof Error ? cause.message : "Invalid shader validation evidence." }] };
1839
2125
  }
1840
2126
  }
1841
2127
  function parseShaderValidationEvidenceAttestationRef(value) {
1842
- const input = object5(value, "attestationRef");
2128
+ const input = object5(detachedQualificationContract(value), "attestationRef");
1843
2129
  exact3(input, ["contractVersion", "kind", "evidence", "attestation", "producer"], "attestationRef");
1844
2130
  if (input.contractVersion !== SHADER_VALIDATION_EVIDENCE_VERSION || input.kind !== "shader-validation-evidence-attestation-ref") throw new TypeError("Unsupported evidence attestation ref.");
1845
2131
  const producer = object5(input.producer, "attestationRef.producer");
@@ -1859,7 +2145,12 @@ function parseShaderValidationEvidenceAttestationRef(value) {
1859
2145
  const attestation = object5(input.attestation, "attestationRef.attestation");
1860
2146
  exact3(attestation, ["id", "url", "bundle"], "attestationRef.attestation");
1861
2147
  token3(attestation.id, "attestationRef.attestation.id");
1862
- const url = new URL(token3(attestation.url, "attestationRef.attestation.url", 2048));
2148
+ let url;
2149
+ try {
2150
+ url = new URL(token3(attestation.url, "attestationRef.attestation.url", 2048));
2151
+ } catch {
2152
+ throw new TypeError("Attestation URL must be an exact GitHub repository attestation URL.");
2153
+ }
1863
2154
  const expectedPrefix = `/${repository}/attestations/`;
1864
2155
  if (url.protocol !== "https:" || url.hostname !== "github.com" || url.port || url.username || url.password || url.search || url.hash || !url.pathname.startsWith(expectedPrefix) || url.pathname.length <= expectedPrefix.length) throw new TypeError("Attestation URL must be an exact GitHub repository attestation URL.");
1865
2156
  const bundle = object5(attestation.bundle, "attestationRef.attestation.bundle");
@@ -1867,13 +2158,43 @@ function parseShaderValidationEvidenceAttestationRef(value) {
1867
2158
  const bundleName = token3(bundle.name, "attestationRef.attestation.bundle.name");
1868
2159
  if (!/^[A-Za-z0-9._-]+\.json$/u.test(bundleName)) throw new TypeError("Attestation bundle name must be a JSON basename.");
1869
2160
  sha2(bundle.sha256, "attestationRef.attestation.bundle.sha256");
1870
- return input;
2161
+ return freezeJson4(input);
1871
2162
  }
1872
2163
  async function verifyShaderValidationEvidenceAttestation(input) {
1873
2164
  try {
1874
- const ref = parseShaderValidationEvidenceAttestationRef(input.ref);
1875
- if (await computeSha256(input.evidenceBytes) !== ref.evidence.sha256 || await computeSha256(input.bundleBytes) !== ref.attestation.bundle.sha256) throw new TypeError("Attested evidence or bundle digest differs.");
1876
- if (!await input.verifyCryptographicBundle({ ref, evidenceBytes: input.evidenceBytes, bundleBytes: input.bundleBytes })) throw new TypeError("External build-provenance cryptographic verification failed.");
2165
+ if (typeof input !== "object" || input === null) throw new TypeError("Evidence attestation verification input is invalid.");
2166
+ let values;
2167
+ try {
2168
+ const keys2 = Reflect.ownKeys(input);
2169
+ const expected = ["ref", "evidenceBytes", "bundleBytes", "verifyCryptographicBundle"];
2170
+ if (keys2.length !== expected.length || keys2.some((key) => typeof key !== "string" || !expected.includes(key))) throw new TypeError();
2171
+ values = expected.map((key) => {
2172
+ const descriptor = Reflect.getOwnPropertyDescriptor(input, key);
2173
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) throw new TypeError();
2174
+ return descriptor;
2175
+ });
2176
+ } catch {
2177
+ throw new TypeError("Evidence attestation verification input is invalid.");
2178
+ }
2179
+ const [refValue, evidenceValue, bundleValue, verifierValue] = values;
2180
+ if (typeof verifierValue?.value !== "function") throw new TypeError("Evidence attestation verification input is invalid.");
2181
+ const evidenceBytes = snapshotUint8Array(
2182
+ evidenceValue?.value,
2183
+ QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2184
+ );
2185
+ const bundleBytes = snapshotUint8Array(
2186
+ bundleValue?.value,
2187
+ QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2188
+ );
2189
+ const ref = parseShaderValidationEvidenceAttestationRef(refValue?.value);
2190
+ if (await computeSha256(evidenceBytes) !== ref.evidence.sha256 || await computeSha256(bundleBytes) !== ref.attestation.bundle.sha256) throw new TypeError("Attested evidence or bundle digest differs.");
2191
+ let verified;
2192
+ try {
2193
+ verified = await Reflect.apply(verifierValue.value, void 0, [{ ref, evidenceBytes, bundleBytes }]);
2194
+ } catch {
2195
+ throw new TypeError("External build-provenance cryptographic verification failed.");
2196
+ }
2197
+ if (verified !== true) throw new TypeError("External build-provenance cryptographic verification failed.");
1877
2198
  return { ok: true, value: ref };
1878
2199
  } catch (cause) {
1879
2200
  return { ok: false, diagnostics: [{ code: "invalid-contract", severity: "error", message: cause instanceof Error ? cause.message : "Evidence attestation verification failed." }] };