@quolu/lattice 0.52.2 → 0.52.4

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.
Files changed (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. package/src/witness-scaffold.mjs +180 -180
@@ -1,1584 +1,1584 @@
1
- import { createHash } from 'node:crypto';
2
- import { isDeepStrictEqual } from 'node:util';
3
-
4
- import {
5
- canonicalizeArtifact,
6
- digestArtifact,
7
- } from './artifact-contracts.mjs';
8
- import { compileBoundaryCondition } from './boundary-compiler.mjs';
9
- import { compileDeliveryPolicyBoundaryBundleV2 } from './rc2-delivery-policy-front-end.mjs';
10
- import { expectedRc2DeliveryPolicyOracleReceipt } from './rc2-delivery-policy-oracle.mjs';
11
- import { compileRc1TransferBundleV2 } from './rc2-rc1-transfer-front-end.mjs';
12
- import {
13
- validateRc1EvidenceBundle,
14
- } from './rc1-evidence-bundle.mjs';
15
- import { compileSchedulabilityGraphV2 } from './schedulability-compiler-v2.mjs';
16
- import { verifySchedulabilityPlanV2 } from './schedulability-verifier-v2.mjs';
17
-
18
- const SHA256 = /^[0-9a-f]{64}$/;
19
- const GIT_SHA1 = /^[0-9a-f]{40}$/;
20
- const RAW_EVIDENCE_CHUNK_BYTES = 12_000;
21
- const RC2_ORACLE_PATH = 'src/rc2-delivery-policy-oracle.mjs';
22
- const RC2_ORACLE_IDENTITY_REF = 'identity/rc2-delivery-policy-oracle.mjs';
23
- const RC2_TRANSFORM_PATH = 'src/rc2-delivery-policy-transform.mjs';
24
- const RC2_TRANSFORM_IDENTITY_REF = 'identity/rc2-delivery-policy-transform.mjs';
25
- const LEGACY_WITNESS = Object.freeze({
26
- epoch: 'delivery-policy-legacy-v1',
27
- candidateDigest: '30ee67852f7ab5fb0d9bf82f2a4c55b6569a76507b0df5b329290c84d29b49f5',
28
- oracleSourceDigest: 'c4012dfc00cc5b0194bd1a87be4a4e0b20d45e784d49a987768eea1b9932fafe',
29
- });
30
- const SEMANTIC_WITNESS = Object.freeze({
31
- epoch: 'delivery-policy-semantic-v2',
32
- candidateDigest: '4cc5d7bb428a8899353d18524c25105742fa90f89ee55d36064c4be3c52e2907',
33
- oracleSourceDigest: 'c68a7ff9a7c9c4a181ceda6396d5fcbf27084de18680018d244a27998041652c',
34
- });
35
- const WITNESS_BY_VERSION = Object.freeze({
36
- v1: LEGACY_WITNESS,
37
- v2: LEGACY_WITNESS,
38
- v3: SEMANTIC_WITNESS,
39
- v4: SEMANTIC_WITNESS,
40
- });
41
-
42
- const PRIMARY_INPUT_PATHS = Object.freeze({
43
- planInput: 'inputs/primary/plan-input.json',
44
- candidateSpec: 'inputs/primary/candidate-spec-v1.json',
45
- normalManualEvidence: 'inputs/primary/manual-evidence.normal.json',
46
- partialManualEvidence: 'inputs/primary/manual-evidence.partial-state-negative.json',
47
- unknownManualEvidence: 'inputs/primary/manual-evidence.third-only-unknown.json',
48
- querySet: 'inputs/primary/query-set-v2.json',
49
- });
50
-
51
- const RC1_INPUT_PATHS = Object.freeze({
52
- planInput: 'inputs/rc1/plan-input.json',
53
- candidateSpec: 'inputs/rc1/candidate-spec-v2.json',
54
- normalManualEvidence: 'inputs/rc1/manual-evidence.normal.json',
55
- negativeManualEvidence: 'inputs/rc1/manual-evidence.shared-state-negative.json',
56
- querySet: 'inputs/rc1/query-set-v2.json',
57
- oracle: 'inputs/rc1/behavior-oracle-v2.json',
58
- });
59
-
60
- const SENSOR_CONFIG_PATH = 'identity/lattice-sensor-config.json';
61
- // ratified config epochのallowlist。artifactのconfig bytesはこのいずれかと完全一致し、
62
- // かつidentity.jsonのproject_config_digestと自己整合でなければreject(第三のbytesはfail closed)。
63
- const SENSOR_CONFIG_EPOCHS = Object.freeze([
64
- // ADR 0040 epoch(RC2 v2〜v4 canonical artifactが保存する当時のratified config)
65
- Buffer.from('{"exclude":["research/campaigns/**/artifacts/**/identity/"]}\n', 'utf8'),
66
- // ADR 0044 Decision 10.3 epoch(research/runs/ event store除外、RC3-B以降のfresh実行)
67
- Buffer.from(
68
- '{"exclude":["research/campaigns/**/artifacts/**/identity/","research/runs/"]}\n',
69
- 'utf8',
70
- ),
71
- // ADR 0053 Decision 3 epoch(Lattice TODO state/generated artifact除外、G2以降のfresh実行)
72
- Buffer.from(
73
- '{"exclude":["research/campaigns/**/artifacts/**/identity/","research/runs/",".lattice/todo/",".lattice/generated/"]}\n',
74
- 'utf8',
75
- ),
76
- ]);
77
-
78
- const V1_IDENTITY_PATHS = Object.freeze([
79
- 'identity/lattice-sensor-adapter.mjs',
80
- 'identity/lattice-sensor-executable',
81
- 'identity/rc1-black-box-oracle.mjs',
82
- 'identity/rc1-boundary-compiler.mjs',
83
- 'identity/rc1-evidence-bundle.mjs',
84
- 'identity/rc2-artifact-set.mjs',
85
- 'identity/rc2-campaign.mjs',
86
- 'identity/rc2-delivery-policy-front-end.mjs',
87
- 'identity/rc2-delivery-policy-oracle.mjs',
88
- 'identity/rc2-delivery-policy-transform.mjs',
89
- 'identity/rc2-rc1-transfer-front-end.mjs',
90
- 'identity/schedulability-compiler-v2.mjs',
91
- 'identity/schedulability-verifier-v2.mjs',
92
- ]);
93
-
94
- const V2_IDENTITY_PATHS = Object.freeze([
95
- ...V1_IDENTITY_PATHS,
96
- SENSOR_CONFIG_PATH,
97
- ]);
98
-
99
- const V3_IDENTITY_PATHS = V2_IDENTITY_PATHS;
100
- const V4_IDENTITY_PATHS = V3_IDENTITY_PATHS;
101
-
102
- const V1_PREDECESSOR_PATHS = Object.freeze([
103
- 'predecessors/adr-0031.md',
104
- 'predecessors/adr-0032.md',
105
- 'predecessors/adr-0037.md',
106
- 'predecessors/adr-0038.md',
107
- 'predecessors/rc1-v6-artifact-manifest.json',
108
- 'predecessors/rc1-v6-plan.md',
109
- 'predecessors/rc1-v6-seam.patch',
110
- 'predecessors/rc1-v6-transform-artifact.json',
111
- 'predecessors/rc1-v6-transform-receipt.json',
112
- ]);
113
-
114
- const V2_PREDECESSOR_PATHS = Object.freeze([
115
- ...V1_PREDECESSOR_PATHS,
116
- 'predecessors/adr-0040.md',
117
- 'predecessors/rc2-v1-artifact-manifest.json',
118
- 'predecessors/rc2-v1-new-plan-version.json',
119
- ]);
120
-
121
- const V3_PREDECESSOR_PATHS = Object.freeze([
122
- ...V2_PREDECESSOR_PATHS,
123
- 'predecessors/adr-0041.md',
124
- 'predecessors/rc2-semantic-reseal-characterization.md',
125
- 'predecessors/rc2-v2-artifact-manifest.json',
126
- 'predecessors/rc2-v2-new-plan-version.json',
127
- ]);
128
-
129
- const V4_PREDECESSOR_PATHS = Object.freeze([
130
- ...V3_PREDECESSOR_PATHS,
131
- 'predecessors/adr-0042.md',
132
- 'predecessors/rc2-v3-version-downgrade-refutation.md',
133
- 'predecessors/rc2-v3-artifact-manifest.json',
134
- 'predecessors/rc2-v3-new-plan-version.json',
135
- ]);
136
-
137
- const BYTE_PRESERVING_JSON_PATHS = new Set([
138
- 'predecessors/rc1-v6-artifact-manifest.json',
139
- 'predecessors/rc1-v6-transform-artifact.json',
140
- 'predecessors/rc1-v6-transform-receipt.json',
141
- SENSOR_CONFIG_PATH,
142
- ]);
143
-
144
- const TRANSFORM_PATHS = Object.freeze([
145
- 'transform/accepted-artifact.json',
146
- 'transform/accepted-receipt.json',
147
- 'transform/behavior-evidence.json',
148
- 'transform/mutation-evidence.json',
149
- 'transform/rejected-incomplete-artifact.json',
150
- 'transform/rejected-incomplete-receipt.json',
151
- 'transform/rejected-scope-artifact.json',
152
- 'transform/rejected-scope-receipt.json',
153
- 'transform/seam.patch',
154
- ]);
155
-
156
- const RUN_IDS = Object.freeze([
157
- 'primary-control-1',
158
- 'primary-control-2',
159
- 'primary-treatment-1',
160
- 'primary-treatment-2',
161
- 'rc1-transfer-control-1',
162
- 'rc1-transfer-treatment-1',
163
- ]);
164
-
165
- const COMPILED_PATHS = Object.freeze([
166
- 'compiled/primary-control-1-normal.json',
167
- 'compiled/primary-control-2-normal.json',
168
- 'compiled/primary-treatment-1-normal.json',
169
- 'compiled/primary-treatment-2-normal.json',
170
- 'compiled/primary-treatment-capacity-2.json',
171
- 'compiled/primary-treatment-partial-state.json',
172
- 'compiled/primary-treatment-third-only-unknown.json',
173
- 'compiled/rc1-transfer-control-negative.json',
174
- 'compiled/rc1-transfer-control-normal.json',
175
- 'compiled/rc1-transfer-treatment-negative.json',
176
- 'compiled/rc1-transfer-treatment-normal.json',
177
- ]);
178
-
179
- const SUMMARY_PATHS = Object.freeze([
180
- 'comparison.json',
181
- 'cost.json',
182
- 'execution-evidence.json',
183
- 'hypothesis-evaluation.json',
184
- 'identity.json',
185
- 'new-plan-version.json',
186
- 'plan-diff.json',
187
- ]);
188
-
189
- const RC2_V1_ARTIFACT_PATHS = Object.freeze([
190
- ...Object.values(PRIMARY_INPUT_PATHS),
191
- ...Object.values(RC1_INPUT_PATHS),
192
- ...V1_IDENTITY_PATHS,
193
- ...V1_PREDECESSOR_PATHS,
194
- ...TRANSFORM_PATHS,
195
- ...RUN_IDS.map((runId) => `evidence/${runId}.json`),
196
- ...COMPILED_PATHS,
197
- ...SUMMARY_PATHS,
198
- ].sort());
199
-
200
- const RC2_V2_ARTIFACT_PATHS = Object.freeze([
201
- ...Object.values(PRIMARY_INPUT_PATHS),
202
- ...Object.values(RC1_INPUT_PATHS),
203
- ...V2_IDENTITY_PATHS,
204
- ...V2_PREDECESSOR_PATHS,
205
- ...TRANSFORM_PATHS,
206
- ...RUN_IDS.map((runId) => `evidence/${runId}.json`),
207
- ...COMPILED_PATHS,
208
- ...SUMMARY_PATHS,
209
- ].sort());
210
-
211
- const RC2_V3_ARTIFACT_PATHS = Object.freeze([
212
- ...Object.values(PRIMARY_INPUT_PATHS),
213
- ...Object.values(RC1_INPUT_PATHS),
214
- ...V3_IDENTITY_PATHS,
215
- ...V3_PREDECESSOR_PATHS,
216
- ...TRANSFORM_PATHS,
217
- ...RUN_IDS.map((runId) => `evidence/${runId}.json`),
218
- ...COMPILED_PATHS,
219
- ...SUMMARY_PATHS,
220
- ].sort());
221
-
222
- export const RC2_ARTIFACT_PATHS = Object.freeze([
223
- ...Object.values(PRIMARY_INPUT_PATHS),
224
- ...Object.values(RC1_INPUT_PATHS),
225
- ...V4_IDENTITY_PATHS,
226
- ...V4_PREDECESSOR_PATHS,
227
- ...TRANSFORM_PATHS,
228
- ...RUN_IDS.map((runId) => `evidence/${runId}.json`),
229
- ...COMPILED_PATHS,
230
- ...SUMMARY_PATHS,
231
- ].sort());
232
-
233
- function plainRecord(value) {
234
- return value !== null
235
- && typeof value === 'object'
236
- && !Array.isArray(value)
237
- && Object.getPrototypeOf(value) === Object.prototype;
238
- }
239
-
240
- function exactRecord(value, keys) {
241
- if (!plainRecord(value)) return false;
242
- const actual = Object.keys(value).sort();
243
- const expected = [...keys].sort();
244
- return actual.length === expected.length
245
- && actual.every((key, index) => key === expected[index]);
246
- }
247
-
248
- function sha256(bytes) {
249
- return createHash('sha256').update(bytes).digest('hex');
250
- }
251
-
252
- function jsonBytes(value) {
253
- return Buffer.from(canonicalizeArtifact(value), 'utf8');
254
- }
255
-
256
- function sameArtifact(left, right) {
257
- try {
258
- return digestArtifact(left) === digestArtifact(right);
259
- } catch {
260
- return false;
261
- }
262
- }
263
-
264
- function mediaType(relativePath) {
265
- if (relativePath.endsWith('.json')) return 'application/json';
266
- if (relativePath.endsWith('.mjs')) return 'application/javascript';
267
- if (relativePath.endsWith('.patch')) return 'text/x-diff';
268
- if (relativePath.endsWith('.md')) return 'text/markdown';
269
- return 'application/octet-stream';
270
- }
271
-
272
- function payloadMap(payloads) {
273
- if (!Array.isArray(payloads)) return null;
274
- const result = new Map();
275
- for (const payload of payloads) {
276
- if (!exactRecord(payload, ['path', 'bytes'])
277
- || typeof payload.path !== 'string'
278
- || !Buffer.isBuffer(payload.bytes)
279
- || result.has(payload.path)) {
280
- return null;
281
- }
282
- result.set(payload.path, payload.bytes);
283
- }
284
- return result;
285
- }
286
-
287
- function parseCanonicalJson(bytes) {
288
- try {
289
- const value = JSON.parse(bytes.toString('utf8'));
290
- return jsonBytes(value).equals(bytes) ? value : null;
291
- } catch {
292
- return null;
293
- }
294
- }
295
-
296
- function parseOpaqueJson(bytes) {
297
- try {
298
- return JSON.parse(bytes.toString('utf8'));
299
- } catch {
300
- return null;
301
- }
302
- }
303
-
304
- function artifactContract(manifest) {
305
- if (manifest?.schema === 'lattice.rc2.artifact_manifest.v1') {
306
- return {
307
- artifactVersion: 'v1',
308
- artifactPaths: RC2_V1_ARTIFACT_PATHS,
309
- identityPaths: V1_IDENTITY_PATHS,
310
- predecessorPaths: V1_PREDECESSOR_PATHS,
311
- witness: WITNESS_BY_VERSION.v1,
312
- };
313
- }
314
- if (manifest?.schema === 'lattice.rc2.artifact_manifest.v2') {
315
- return {
316
- artifactVersion: 'v2',
317
- artifactPaths: RC2_V2_ARTIFACT_PATHS,
318
- identityPaths: V2_IDENTITY_PATHS,
319
- predecessorPaths: V2_PREDECESSOR_PATHS,
320
- witness: WITNESS_BY_VERSION.v2,
321
- };
322
- }
323
- if (manifest?.schema === 'lattice.rc2.artifact_manifest.v3') {
324
- return {
325
- artifactVersion: 'v3',
326
- artifactPaths: RC2_V3_ARTIFACT_PATHS,
327
- identityPaths: V3_IDENTITY_PATHS,
328
- predecessorPaths: V3_PREDECESSOR_PATHS,
329
- witness: WITNESS_BY_VERSION.v3,
330
- };
331
- }
332
- if (manifest?.schema === 'lattice.rc2.artifact_manifest.v4') {
333
- return {
334
- artifactVersion: 'v4',
335
- artifactPaths: RC2_ARTIFACT_PATHS,
336
- identityPaths: V4_IDENTITY_PATHS,
337
- predecessorPaths: V4_PREDECESSOR_PATHS,
338
- witness: WITNESS_BY_VERSION.v4,
339
- };
340
- }
341
- return null;
342
- }
343
-
344
- function artifactContext(options) {
345
- if (!exactRecord(options, ['manifest', 'payloads'])) return null;
346
- const payloads = payloadMap(options.payloads);
347
- const manifest = options.manifest;
348
- const contract = artifactContract(manifest);
349
- if (!payloads
350
- || contract === null
351
- || !exactRecord(manifest, ['schema', 'base_sha', 'result_digest', 'files'])
352
- || !GIT_SHA1.test(manifest.base_sha)
353
- || !SHA256.test(manifest.result_digest)
354
- || !Array.isArray(manifest.files)) {
355
- return null;
356
- }
357
- const manifestPaths = manifest.files.map(({ path: relativePath }) => relativePath).sort();
358
- if (!sameArtifact(manifestPaths, contract.artifactPaths)
359
- || !sameArtifact([...payloads.keys()].sort(), contract.artifactPaths)) {
360
- return null;
361
- }
362
- for (const entry of manifest.files) {
363
- const bytes = payloads.get(entry.path);
364
- if (!exactRecord(entry, ['path', 'media_type', 'bytes', 'sha256'])
365
- || !Buffer.isBuffer(bytes)
366
- || entry.media_type !== mediaType(entry.path)
367
- || entry.bytes !== bytes.byteLength
368
- || entry.sha256 !== sha256(bytes)) {
369
- return null;
370
- }
371
- }
372
- const json = new Map();
373
- for (const relativePath of contract.artifactPaths.filter((entry) => entry.endsWith('.json'))) {
374
- const parsed = BYTE_PRESERVING_JSON_PATHS.has(relativePath)
375
- ? parseOpaqueJson(payloads.get(relativePath))
376
- : parseCanonicalJson(payloads.get(relativePath));
377
- if (parsed === null) return null;
378
- json.set(relativePath, parsed);
379
- }
380
- return { manifest, payloads, json, ...contract };
381
- }
382
-
383
- function objectFromPaths(context, paths) {
384
- return Object.fromEntries(Object.entries(paths).map(([key, relativePath]) => (
385
- [key, context.json.get(relativePath)]
386
- )));
387
- }
388
-
389
- function stripDigest(value, key) {
390
- if (!plainRecord(value) || !Object.hasOwn(value, key)) return null;
391
- const result = structuredClone(value);
392
- delete result[key];
393
- return result;
394
- }
395
-
396
- function verifyIdentity(context) {
397
- const identity = context.json.get('identity.json');
398
- const projectConfigBound = context.artifactVersion !== 'v1';
399
- const expectedIdentitySchema = `lattice.rc2.execution_identity.${context.artifactVersion}`;
400
- const expectedLatticeSensorSchema = projectConfigBound
401
- ? 'lattice.rc2.sensor_identity.v2'
402
- : 'lattice.rc2.sensor_identity.v1';
403
- const sensorKeys = projectConfigBound
404
- ? [
405
- 'schema',
406
- 'version',
407
- 'executable_ref',
408
- 'executable_digest',
409
- 'project_config_ref',
410
- 'project_config_digest',
411
- ]
412
- : ['schema', 'version', 'executable_ref', 'executable_digest'];
413
- if (!exactRecord(identity, [
414
- 'schema',
415
- 'sources',
416
- 'sensor_identity',
417
- 'sensor_identity_digest',
418
- 'before_digest',
419
- 'after_digest',
420
- ])
421
- || identity.schema !== expectedIdentitySchema
422
- || !Array.isArray(identity.sources)
423
- || identity.sources.length !== V1_IDENTITY_PATHS.length - 1
424
- || !exactRecord(identity.sensor_identity, sensorKeys)
425
- || identity.sensor_identity.schema !== expectedLatticeSensorSchema
426
- || !SHA256.test(identity.sensor_identity.executable_digest)
427
- || identity.sensor_identity.executable_digest
428
- !== sha256(context.payloads.get('identity/lattice-sensor-executable'))
429
- || (projectConfigBound && (
430
- identity.sensor_identity.project_config_ref !== SENSOR_CONFIG_PATH
431
- || !SHA256.test(identity.sensor_identity.project_config_digest)
432
- || identity.sensor_identity.project_config_digest
433
- !== sha256(context.payloads.get(SENSOR_CONFIG_PATH))
434
- ))
435
- || identity.sensor_identity_digest !== digestArtifact(identity.sensor_identity)) {
436
- return false;
437
- }
438
- const expectedSourceRefs = V1_IDENTITY_PATHS
439
- .filter((relativePath) => relativePath !== 'identity/lattice-sensor-executable');
440
- const actualRefs = identity.sources.map(({ artifact_ref: ref }) => ref).sort();
441
- if (!sameArtifact(actualRefs, expectedSourceRefs)) return false;
442
- for (const source of identity.sources) {
443
- if (!exactRecord(source, ['runtime_path', 'artifact_ref', 'digest'])
444
- || typeof source.runtime_path !== 'string'
445
- || !expectedSourceRefs.includes(source.artifact_ref)
446
- || source.digest !== sha256(context.payloads.get(source.artifact_ref))) {
447
- return false;
448
- }
449
- }
450
- const snapshot = {
451
- sources: identity.sources.map(({ runtime_path: runtimePath, artifact_ref: artifactRef, digest }) => ({
452
- runtime_path: runtimePath,
453
- artifact_ref: artifactRef,
454
- digest,
455
- })),
456
- sensor_identity: identity.sensor_identity,
457
- };
458
- const digest = digestArtifact(snapshot);
459
- return identity.before_digest === digest && identity.after_digest === digest;
460
- }
461
-
462
- function verifyLatticeSensorConfig(context) {
463
- if (context.artifactVersion === 'v1') return false;
464
- const bytes = context.payloads.get(SENSOR_CONFIG_PATH);
465
- const identity = context.json.get('identity.json');
466
- return Buffer.isBuffer(bytes)
467
- && SENSOR_CONFIG_EPOCHS.some((epochBytes) => bytes.equals(epochBytes))
468
- && identity?.sensor_identity?.project_config_ref === SENSOR_CONFIG_PATH
469
- && identity.sensor_identity.project_config_digest === sha256(bytes);
470
- }
471
-
472
- function verifySurfaceSnapshot(snapshot, expectedPaths, expectedPresentPaths) {
473
- if (!exactRecord(snapshot, ['schema', 'files', 'digest'])
474
- || snapshot.schema !== 'lattice.rc2.delivery_policy_surface_snapshot.v1'
475
- || !Array.isArray(snapshot.files)
476
- || !isDeepStrictEqual(snapshot.files.map(({ path: relativePath }) => relativePath), expectedPaths)
477
- || snapshot.files.some((file) => (
478
- !exactRecord(file, ['path', 'state', 'content_digest'])
479
- || (expectedPresentPaths.has(file.path)
480
- ? file.state !== 'present' || !SHA256.test(file.content_digest)
481
- : file.state !== 'absent' || file.content_digest !== null)
482
- ))) {
483
- return false;
484
- }
485
- return snapshot.digest === digestArtifact({ schema: snapshot.schema, files: snapshot.files });
486
- }
487
-
488
- function expectedMutationContract(candidate) {
489
- if (!plainRecord(candidate)
490
- || candidate.schema !== 'lattice.rc2.boundary_candidate_spec.v1'
491
- || typeof candidate.candidate_id !== 'string'
492
- || !plainRecord(candidate.fixed_oracle)
493
- || candidate.fixed_oracle.path !== RC2_ORACLE_PATH
494
- || !SHA256.test(candidate.fixed_oracle.source_digest)
495
- || !Array.isArray(candidate.fixed_oracle.case_ids)
496
- || !Array.isArray(candidate.todos)
497
- || candidate.todos.length !== 3
498
- || !Array.isArray(candidate.stable_surfaces)) {
499
- return null;
500
- }
501
- const compositionSurfaces = candidate.stable_surfaces.filter(({ role }) => (
502
- role === 'composition-test'
503
- ));
504
- if (compositionSurfaces.length !== 1) return null;
505
- const composition = compositionSurfaces[0];
506
- if (typeof composition.target !== 'string' || typeof composition.path !== 'string') return null;
507
-
508
- const contracts = [];
509
- const rows = [];
510
- const surfacePaths = new Set([candidate.fixed_oracle.path]);
511
- const controlPaths = new Set([candidate.fixed_oracle.path]);
512
- for (const todo of candidate.todos) {
513
- if (!plainRecord(todo)
514
- || typeof todo.todo_id !== 'string'
515
- || !Array.isArray(todo.case_ids)
516
- || todo.case_ids.length !== 2
517
- || !plainRecord(todo.current)
518
- || !plainRecord(todo.proposed)
519
- || !plainRecord(todo.current.production)
520
- || !plainRecord(todo.proposed.production)
521
- || !Array.isArray(todo.current.tests)
522
- || !Array.isArray(todo.proposed.tests)
523
- || todo.proposed.tests.length !== 1) {
524
- return null;
525
- }
526
- const production = todo.proposed.production;
527
- const test = todo.proposed.tests[0];
528
- if (typeof production.symbol !== 'string'
529
- || typeof production.path !== 'string'
530
- || typeof test.symbol !== 'string'
531
- || typeof test.path !== 'string'
532
- || todo.case_ids.some((caseId) => typeof caseId !== 'string')) {
533
- return null;
534
- }
535
- contracts.push({ testId: test.symbol, path: test.path });
536
- rows.push(...todo.case_ids.map((caseId) => ({
537
- caseId,
538
- todoId: todo.todo_id,
539
- resolver: production.symbol,
540
- productionPath: production.path,
541
- ownerTestId: test.symbol,
542
- })));
543
- for (const mode of [todo.current, todo.proposed]) {
544
- if (typeof mode.production?.path !== 'string'
545
- || mode.tests.some(({ path: testPath }) => typeof testPath !== 'string')) {
546
- return null;
547
- }
548
- surfacePaths.add(mode.production.path);
549
- mode.tests.forEach(({ path: testPath }) => surfacePaths.add(testPath));
550
- }
551
- controlPaths.add(todo.current.production.path);
552
- todo.current.tests.forEach(({ path: testPath }) => controlPaths.add(testPath));
553
- }
554
- contracts.push({ testId: composition.target, path: composition.path });
555
- if (new Set(contracts.map(({ testId }) => testId)).size !== contracts.length
556
- || new Set(contracts.map(({ path: testPath }) => testPath)).size !== contracts.length
557
- || !isDeepStrictEqual(rows.map(({ caseId }) => caseId), candidate.fixed_oracle.case_ids)
558
- || new Set(candidate.fixed_oracle.case_ids).size !== candidate.fixed_oracle.case_ids.length) {
559
- return null;
560
- }
561
- return {
562
- contracts,
563
- rows,
564
- surfacePaths: [...surfacePaths].sort(),
565
- controlPaths,
566
- };
567
- }
568
-
569
- function verifyMutationEvidence(mutation, expected, outputDigest, candidateDigest, caseSetDigest) {
570
- if (!exactRecord(mutation, [
571
- 'schema',
572
- 'candidate_digest',
573
- 'case_set_digest',
574
- 'rows',
575
- 'matrix_digest',
576
- 'evidence_digest',
577
- ])
578
- || mutation.schema !== 'lattice.rc2.delivery_policy_mutation_evidence.v1'
579
- || mutation.candidate_digest !== candidateDigest
580
- || mutation.case_set_digest !== caseSetDigest
581
- || !Array.isArray(mutation.rows)
582
- || mutation.rows.length !== expected.rows.length) {
583
- return false;
584
- }
585
- for (let rowIndex = 0; rowIndex < expected.rows.length; rowIndex += 1) {
586
- const row = mutation.rows[rowIndex];
587
- const expectedRow = expected.rows[rowIndex];
588
- if (!exactRecord(row, [
589
- 'case_id',
590
- 'owner_todo_id',
591
- 'resolver_symbol',
592
- 'mutated_path',
593
- 'oracle_mismatch_id',
594
- 'cells',
595
- 'restore_digest',
596
- ])
597
- || row.case_id !== expectedRow.caseId
598
- || row.owner_todo_id !== expectedRow.todoId
599
- || row.resolver_symbol !== expectedRow.resolver
600
- || row.mutated_path !== expectedRow.productionPath
601
- || row.oracle_mismatch_id !== expectedRow.caseId
602
- || row.restore_digest !== outputDigest
603
- || !Array.isArray(row.cells)
604
- || row.cells.length !== expected.contracts.length) {
605
- return false;
606
- }
607
- for (let cellIndex = 0; cellIndex < expected.contracts.length; cellIndex += 1) {
608
- const cell = row.cells[cellIndex];
609
- const contract = expected.contracts[cellIndex];
610
- const owner = contract.testId === expectedRow.ownerTestId;
611
- if (!exactRecord(cell, [
612
- 'test_id', 'path', 'outcome', 'exit_code', 'stdout_digest', 'stderr_digest',
613
- ])
614
- || cell.test_id !== contract.testId
615
- || cell.path !== contract.path
616
- || !Number.isSafeInteger(cell.exit_code)
617
- || cell.exit_code < 0
618
- || !SHA256.test(cell.stdout_digest)
619
- || !SHA256.test(cell.stderr_digest)
620
- || (owner
621
- ? cell.outcome !== 'failed' || cell.exit_code === 0
622
- : cell.outcome !== 'passed' || cell.exit_code !== 0)) {
623
- return false;
624
- }
625
- }
626
- }
627
- const mutationBase = stripDigest(mutation, 'evidence_digest');
628
- return mutation.matrix_digest === digestArtifact({ rows: mutation.rows })
629
- && mutationBase !== null
630
- && mutation.evidence_digest === digestArtifact(mutationBase);
631
- }
632
-
633
- function verifyTransformSemantics(context, accepted, behavior, mutation) {
634
- try {
635
- const candidate = context.json.get(PRIMARY_INPUT_PATHS.candidateSpec);
636
- const expected = expectedMutationContract(candidate);
637
- const oracleReceipt = expectedRc2DeliveryPolicyOracleReceipt();
638
- const candidateDigest = digestArtifact(candidate);
639
- const oracleIdentityBytes = context.payloads.get(RC2_ORACLE_IDENTITY_REF);
640
- const transformIdentityBytes = context.payloads.get(RC2_TRANSFORM_IDENTITY_REF);
641
- if (expected === null
642
- || !Buffer.isBuffer(oracleIdentityBytes)
643
- || !Buffer.isBuffer(transformIdentityBytes)
644
- || !exactRecord(behavior, [
645
- 'schema',
646
- 'candidate_digest',
647
- 'adapter_source_digest',
648
- 'control_snapshot',
649
- 'output_snapshot',
650
- 'fixed_oracle',
651
- 'pre_oracle',
652
- 'post_oracle',
653
- 'case_set_digest',
654
- 'equivalent',
655
- 'evidence_digest',
656
- ])
657
- || behavior.schema !== 'lattice.rc2.delivery_policy_behavior_evidence.v1'
658
- || !exactRecord(behavior.fixed_oracle, ['path', 'source_base64', 'source_digest'])
659
- || behavior.fixed_oracle.path !== RC2_ORACLE_PATH
660
- || typeof behavior.fixed_oracle.source_base64 !== 'string') {
661
- return false;
662
- }
663
- const oracleBytes = Buffer.from(behavior.fixed_oracle.source_base64, 'base64');
664
- if (oracleBytes.toString('base64') !== behavior.fixed_oracle.source_base64
665
- || !oracleBytes.equals(oracleIdentityBytes)
666
- || sha256(oracleBytes) !== behavior.fixed_oracle.source_digest
667
- || behavior.fixed_oracle.source_digest !== candidate.fixed_oracle.source_digest
668
- || behavior.fixed_oracle.source_digest !== accepted?.source?.fixed_oracle?.source_digest
669
- || accepted.source.fixed_oracle.path !== RC2_ORACLE_PATH
670
- || candidateDigest !== context.witness.candidateDigest
671
- || behavior.fixed_oracle.source_digest !== context.witness.oracleSourceDigest
672
- || behavior.candidate_digest !== candidateDigest
673
- || mutation?.candidate_digest !== candidateDigest
674
- || accepted?.candidate?.candidate_id !== candidate.candidate_id
675
- || accepted.candidate.digest !== candidateDigest
676
- || behavior.adapter_source_digest !== sha256(transformIdentityBytes)
677
- || accepted?.source?.adapter?.path !== RC2_TRANSFORM_PATH
678
- || accepted.source.adapter.digest !== behavior.adapter_source_digest
679
- || !isDeepStrictEqual(behavior.pre_oracle, oracleReceipt)
680
- || !isDeepStrictEqual(behavior.post_oracle, oracleReceipt)) {
681
- return false;
682
- }
683
- const expectedCaseSetDigest = digestArtifact({
684
- case_results: oracleReceipt.case_results.map(({ id, output_digest: outputDigest }) => ({
685
- id,
686
- output_digest: outputDigest,
687
- })),
688
- });
689
- const outputPaths = new Set(expected.surfacePaths);
690
- if (behavior.case_set_digest !== expectedCaseSetDigest
691
- || mutation.case_set_digest !== expectedCaseSetDigest
692
- || accepted.behavior?.case_set_digest !== expectedCaseSetDigest
693
- || accepted.behavior?.pre_oracle_digest !== digestArtifact(oracleReceipt)
694
- || accepted.behavior?.post_oracle_digest !== digestArtifact(oracleReceipt)
695
- || accepted.behavior?.equivalent !== true
696
- || behavior.equivalent !== true
697
- || !verifySurfaceSnapshot(behavior.control_snapshot, expected.surfacePaths, expected.controlPaths)
698
- || !verifySurfaceSnapshot(behavior.output_snapshot, expected.surfacePaths, outputPaths)
699
- || !isDeepStrictEqual(accepted.output?.files, behavior.output_snapshot.files)
700
- || accepted.output.snapshot_digest !== behavior.output_snapshot.digest
701
- || accepted.source.control_snapshot_digest !== behavior.control_snapshot.digest
702
- || behavior.control_snapshot.files.find(({ path: relativePath }) => (
703
- relativePath === RC2_ORACLE_PATH
704
- ))?.content_digest !== behavior.fixed_oracle.source_digest
705
- || behavior.output_snapshot.files.find(({ path: relativePath }) => (
706
- relativePath === RC2_ORACLE_PATH
707
- ))?.content_digest !== behavior.fixed_oracle.source_digest) {
708
- return false;
709
- }
710
- const behaviorBase = stripDigest(behavior, 'evidence_digest');
711
- if (behaviorBase === null
712
- || behavior.evidence_digest !== digestArtifact(behaviorBase)
713
- || accepted.behavior.evidence_digest !== behavior.evidence_digest
714
- || !verifyMutationEvidence(
715
- mutation,
716
- expected,
717
- behavior.output_snapshot.digest,
718
- candidateDigest,
719
- expectedCaseSetDigest,
720
- )) {
721
- return false;
722
- }
723
- return accepted.mutation?.evidence_digest === mutation.evidence_digest
724
- && accepted.mutation.matrix_digest === mutation.matrix_digest
725
- && accepted.mutation.row_count === expected.rows.length
726
- && accepted.mutation.cell_count === expected.rows.length * expected.contracts.length;
727
- } catch {
728
- return false;
729
- }
730
- }
731
-
732
- function verifyTransform(context) {
733
- const accepted = context.json.get('transform/accepted-artifact.json');
734
- const acceptedReceipt = context.json.get('transform/accepted-receipt.json');
735
- const behavior = context.json.get('transform/behavior-evidence.json');
736
- const mutation = context.json.get('transform/mutation-evidence.json');
737
- const incomplete = context.json.get('transform/rejected-incomplete-artifact.json');
738
- const incompleteReceipt = context.json.get('transform/rejected-incomplete-receipt.json');
739
- const scope = context.json.get('transform/rejected-scope-artifact.json');
740
- const scopeReceipt = context.json.get('transform/rejected-scope-receipt.json');
741
- const patch = context.payloads.get('transform/seam.patch');
742
- const behaviorBase = stripDigest(behavior, 'evidence_digest');
743
- const mutationBase = stripDigest(mutation, 'evidence_digest');
744
- const acceptedReceiptBase = stripDigest(acceptedReceipt, 'receipt_digest');
745
- const incompleteReceiptBase = stripDigest(incompleteReceipt, 'receipt_digest');
746
- const scopeReceiptBase = stripDigest(scopeReceipt, 'receipt_digest');
747
- return accepted?.schema === 'lattice.rc2.delivery_policy_transform_artifact.v1'
748
- && accepted.status === 'accepted'
749
- && exactRecord(accepted.candidate, ['candidate_id', 'digest'])
750
- && accepted.candidate.digest === context.witness.candidateDigest
751
- && exactRecord(accepted.source, [
752
- 'adapter',
753
- 'base_sha',
754
- 'control_snapshot_digest',
755
- 'fixed_oracle',
756
- ])
757
- && exactRecord(accepted.source.adapter, ['path', 'digest'])
758
- && exactRecord(accepted.source.fixed_oracle, ['path', 'source_digest'])
759
- && accepted.source.base_sha === context.manifest.base_sha
760
- && accepted.source.fixed_oracle.source_digest === context.witness.oracleSourceDigest
761
- && accepted.patch?.digest === sha256(patch)
762
- && accepted.patch?.bytes === patch.byteLength
763
- && accepted.output?.snapshot_digest === behavior?.output_snapshot?.digest
764
- && accepted.source?.control_snapshot_digest === behavior?.control_snapshot?.digest
765
- && accepted.source?.fixed_oracle?.source_digest === behavior?.fixed_oracle?.source_digest
766
- && accepted.behavior?.evidence_digest === behavior?.evidence_digest
767
- && behaviorBase !== null
768
- && behavior.evidence_digest === digestArtifact(behaviorBase)
769
- && accepted.mutation?.evidence_digest === mutation?.evidence_digest
770
- && mutationBase !== null
771
- && mutation.evidence_digest === digestArtifact(mutationBase)
772
- && acceptedReceipt?.status === 'accepted'
773
- && acceptedReceipt.transform_artifact_digest === digestArtifact(accepted)
774
- && acceptedReceipt.behavior_evidence_digest === behavior.evidence_digest
775
- && acceptedReceipt.mutation_evidence_digest === mutation.evidence_digest
776
- && acceptedReceiptBase !== null
777
- && acceptedReceipt.receipt_digest === digestArtifact(acceptedReceiptBase)
778
- && incomplete?.status === 'rejected'
779
- && incomplete?.rejection?.kind === 'incomplete_transform'
780
- && incomplete.output === null
781
- && sameArtifact(incomplete.candidate, accepted.candidate)
782
- && sameArtifact(incomplete.source, accepted.source)
783
- && incompleteReceipt?.status === 'rejected'
784
- && incompleteReceipt.transform_artifact_digest === digestArtifact(incomplete)
785
- && incompleteReceiptBase !== null
786
- && incompleteReceipt.receipt_digest === digestArtifact(incompleteReceiptBase)
787
- && scope?.status === 'rejected'
788
- && scope?.rejection?.kind === 'scope_violation'
789
- && scope.output === null
790
- && sameArtifact(scope.candidate, accepted.candidate)
791
- && sameArtifact(scope.source, accepted.source)
792
- && scopeReceipt?.status === 'rejected'
793
- && scopeReceipt.transform_artifact_digest === digestArtifact(scope)
794
- && scopeReceiptBase !== null
795
- && scopeReceipt.receipt_digest === digestArtifact(scopeReceiptBase)
796
- && verifyTransformSemantics(context, accepted, behavior, mutation);
797
- }
798
-
799
- function decodeRawEvidence(evidence) {
800
- try {
801
- return JSON.parse(Buffer.from(evidence.raw.payload_base64, 'base64').toString('utf8'));
802
- } catch {
803
- return null;
804
- }
805
- }
806
-
807
- function rehydrateStoredEvidence(evidence) {
808
- if (!plainRecord(evidence)) return null;
809
- const raw = evidence.raw;
810
- if (!exactRecord(raw, [
811
- 'schema',
812
- 'source_schema',
813
- 'media_type',
814
- 'source_encoding',
815
- 'storage_encoding',
816
- 'canonical_bytes',
817
- 'payload_digest',
818
- 'payload_base64_chunks',
819
- ])
820
- || raw.schema !== 'lattice.rc2.chunked_sensor_raw_receipt.v1'
821
- || raw.source_schema !== 'lattice.sensor_raw_opaque_receipt.v1'
822
- || raw.source_encoding !== 'canonical-json-base64'
823
- || raw.storage_encoding !== 'ordered-base64-chunks'
824
- || !Number.isSafeInteger(raw.canonical_bytes)
825
- || raw.canonical_bytes < 0
826
- || !SHA256.test(raw.payload_digest)
827
- || !Array.isArray(raw.payload_base64_chunks)
828
- || raw.payload_base64_chunks.length === 0
829
- || raw.payload_base64_chunks.some((chunk) => (
830
- typeof chunk !== 'string'
831
- || chunk.length === 0
832
- || Buffer.byteLength(chunk, 'utf8') > RAW_EVIDENCE_CHUNK_BYTES
833
- ))
834
- || raw.payload_base64_chunks.slice(0, -1).some((chunk) => (
835
- Buffer.byteLength(chunk, 'utf8') !== RAW_EVIDENCE_CHUNK_BYTES
836
- ))) {
837
- return null;
838
- }
839
- const payloadBase64 = raw.payload_base64_chunks.join('');
840
- const payload = Buffer.from(payloadBase64, 'base64');
841
- if (payload.toString('base64') !== payloadBase64
842
- || payload.byteLength !== raw.canonical_bytes
843
- || sha256(payload) !== raw.payload_digest) {
844
- return null;
845
- }
846
- const restored = {
847
- ...structuredClone(evidence),
848
- raw: {
849
- schema: raw.source_schema,
850
- media_type: raw.media_type,
851
- encoding: raw.source_encoding,
852
- canonical_bytes: raw.canonical_bytes,
853
- payload_digest: raw.payload_digest,
854
- payload_base64: payloadBase64,
855
- },
856
- };
857
- return validateRc1EvidenceBundle(restored) ? restored : null;
858
- }
859
-
860
- function rehydrateStoredRun(run) {
861
- if (!plainRecord(run)) return null;
862
- const evidence = rehydrateStoredEvidence(run.evidence);
863
- if (evidence === null) return null;
864
- return { ...structuredClone(run), evidence };
865
- }
866
-
867
- function runMap(context) {
868
- return new Map(RUN_IDS.map((runId) => [
869
- runId,
870
- rehydrateStoredRun(context.json.get(`evidence/${runId}.json`)),
871
- ]));
872
- }
873
-
874
- function expectedRunFamily(runId) {
875
- return runId.startsWith('primary-') ? 'primary' : 'rc1_transfer';
876
- }
877
-
878
- function expectedRunCondition(runId) {
879
- return runId.includes('-treatment-') ? 'treatment' : 'control';
880
- }
881
-
882
- function verifyRuns(context) {
883
- const runs = runMap(context);
884
- const primaryInputs = objectFromPaths(context, PRIMARY_INPUT_PATHS);
885
- const rc1Inputs = objectFromPaths(context, RC1_INPUT_PATHS);
886
- const identity = context.json.get('identity.json');
887
- const accepted = context.json.get('transform/accepted-artifact.json');
888
- const rc1Transform = context.json.get('predecessors/rc1-v6-transform-artifact.json');
889
- const isolationDigests = new Set();
890
- for (const [runId, run] of runs) {
891
- const family = expectedRunFamily(runId);
892
- const condition = expectedRunCondition(runId);
893
- const inputs = family === 'primary' ? primaryInputs : rc1Inputs;
894
- const expectedPatch = condition === 'control'
895
- ? null
896
- : (family === 'primary' ? accepted?.patch?.digest : rc1Transform?.patch?.digest);
897
- if (!plainRecord(run)
898
- || run.schema !== 'lattice.rc2.fresh_sensor_run.v1'
899
- || run.run_id !== runId
900
- || run.family !== family
901
- || run.condition !== condition
902
- || run.fresh_index !== true
903
- || !SHA256.test(run.isolation_instance_digest)
904
- || isolationDigests.has(run.isolation_instance_digest)
905
- || !validateRc1EvidenceBundle(run.evidence)
906
- || run.evidence.run_id !== runId
907
- || run.evidence.condition !== condition
908
- || run.evidence.query_set_digest !== digestArtifact(inputs.querySet)
909
- || run.measurement?.schema !== 'lattice.rc2.sensor_measurement.v1'
910
- || run.measurement.base_sha !== context.manifest.base_sha
911
- || run.measurement.patch_digest !== expectedPatch
912
- || run.measurement.snapshot_digest !== digestArtifact(run.measurement.snapshot)
913
- || run.measurement.sensor_identity_digest !== identity.sensor_identity_digest
914
- || !sameArtifact(run.measurement.sensor_identity, identity.sensor_identity)
915
- || run.measurement.query_set_digest !== digestArtifact(inputs.querySet)
916
- || run.measurement.raw_evidence_digest !== run.evidence.raw.payload_digest
917
- || run.source_invariant?.outcome !== 'passed'
918
- || run.cleanup?.outcome !== 'passed'
919
- || run.oracle_receipt?.outcome !== 'passed'
920
- || run.cost?.index?.state !== 'measured'
921
- || run.cost?.query?.state !== 'measured'
922
- || run.cost?.oracle?.state !== 'measured') {
923
- return false;
924
- }
925
- isolationDigests.add(run.isolation_instance_digest);
926
- }
927
- return isolationDigests.size === RUN_IDS.length;
928
- }
929
-
930
- function verdictFor(bundle, compiled) {
931
- return {
932
- schema_version: 'lattice.boundary_verdict.v2',
933
- normalized_graph_digest: bundle.graph_digest,
934
- verdicts: compiled.pairwise_verdicts,
935
- };
936
- }
937
-
938
- function compiledRecord({ condition, runId, bundle, compiled }) {
939
- if (compiled.outcome !== 'compiled') throw new TypeError(`${condition} did not compile`);
940
- const verdict = verdictFor(bundle, compiled);
941
- const verification = verifySchedulabilityPlanV2(bundle.graph, compiled.plan);
942
- const stable = { bundle, verdict, plan: compiled.plan, verification };
943
- return {
944
- schema: 'lattice.rc2.compiled_condition.v1',
945
- condition,
946
- run_id: runId,
947
- outcome: 'compiled',
948
- ...stable,
949
- artifact_digest: digestArtifact(stable),
950
- };
951
- }
952
-
953
- function compilePrimaryRecord({ run, inputs, manualEvidence, planInput, condition }) {
954
- const bundle = compileDeliveryPolicyBoundaryBundleV2({
955
- planInput,
956
- candidateSpec: inputs.candidateSpec,
957
- manualEvidence,
958
- querySet: inputs.querySet,
959
- sourceSnapshot: run.measurement.snapshot,
960
- sensorEvidence: run.evidence.portable,
961
- });
962
- return compiledRecord({
963
- condition,
964
- runId: run.run_id,
965
- bundle,
966
- compiled: compileSchedulabilityGraphV2(bundle.graph),
967
- });
968
- }
969
-
970
- function compileUnknownRecord({ run, inputs }) {
971
- const bundle = compileDeliveryPolicyBoundaryBundleV2({
972
- planInput: inputs.planInput,
973
- candidateSpec: inputs.candidateSpec,
974
- manualEvidence: inputs.unknownManualEvidence,
975
- querySet: inputs.querySet,
976
- sourceSnapshot: run.measurement.snapshot,
977
- sensorEvidence: run.evidence.portable,
978
- });
979
- const outcome = compileSchedulabilityGraphV2(bundle.graph);
980
- const verification = verifySchedulabilityPlanV2(bundle.graph, {
981
- schema_version: 'lattice.plan_graph.v2',
982
- waves: [],
983
- minimum_feasible_waves: 0,
984
- });
985
- return {
986
- schema: 'lattice.rc2.non_dispatchable_condition.v1',
987
- condition: 'primary-treatment-third-only-unknown',
988
- run_id: run.run_id,
989
- bundle,
990
- outcome,
991
- verification,
992
- };
993
- }
994
-
995
- function recompileLegacy(run, inputs, manualEvidence, label) {
996
- const rawEvidence = decodeRawEvidence(run.evidence);
997
- if (rawEvidence === null) throw new TypeError('RC1 raw evidence is not decodable');
998
- return compileBoundaryCondition({
999
- planInput: inputs.planInput,
1000
- candidateSpec: inputs.candidateSpec,
1001
- manualEvidence,
1002
- querySet: inputs.querySet,
1003
- sensorEvidence: rawEvidence,
1004
- codeSnapshotDigest: run.measurement.snapshot_digest,
1005
- planVersion: `rc2-${run.condition}-transfer-${label}`,
1006
- });
1007
- }
1008
-
1009
- function compileTransferRecord({ run, inputs, manualEvidence, label }) {
1010
- const legacy = recompileLegacy(run, inputs, manualEvidence, label);
1011
- if (!sameArtifact(legacy.boundary_manifest, run.legacy_boundary_manifests?.[label])) {
1012
- throw new TypeError(`RC1 ${run.condition} ${label} fresh manifest mismatch`);
1013
- }
1014
- const transferred = compileRc1TransferBundleV2({
1015
- planInput: inputs.planInput,
1016
- candidateSpec: inputs.candidateSpec,
1017
- manualEvidence,
1018
- querySet: inputs.querySet,
1019
- boundaryManifest: legacy.boundary_manifest,
1020
- });
1021
- const verification = verifySchedulabilityPlanV2(transferred.bundle.graph, transferred.plan);
1022
- const stable = {
1023
- bundle: transferred.bundle,
1024
- verdict: transferred.verdict,
1025
- plan: transferred.plan,
1026
- verification,
1027
- };
1028
- return {
1029
- schema: 'lattice.rc2.compiled_condition.v1',
1030
- condition: `rc1-transfer-${run.condition}-${label}`,
1031
- run_id: run.run_id,
1032
- outcome: 'compiled',
1033
- ...stable,
1034
- artifact_digest: digestArtifact(stable),
1035
- };
1036
- }
1037
-
1038
- function recomputeConditions(context) {
1039
- const runs = runMap(context);
1040
- const primaryInputs = objectFromPaths(context, PRIMARY_INPUT_PATHS);
1041
- const rc1Inputs = objectFromPaths(context, RC1_INPUT_PATHS);
1042
- const control = [1, 2].map((index) => compilePrimaryRecord({
1043
- run: runs.get(`primary-control-${index}`),
1044
- inputs: primaryInputs,
1045
- manualEvidence: primaryInputs.normalManualEvidence,
1046
- planInput: primaryInputs.planInput,
1047
- condition: 'primary-control-normal',
1048
- }));
1049
- const treatment = [1, 2].map((index) => compilePrimaryRecord({
1050
- run: runs.get(`primary-treatment-${index}`),
1051
- inputs: primaryInputs,
1052
- manualEvidence: primaryInputs.normalManualEvidence,
1053
- planInput: primaryInputs.planInput,
1054
- condition: 'primary-treatment-normal',
1055
- }));
1056
- const treatmentRun = runs.get('primary-treatment-1');
1057
- const capacityPlan = structuredClone(primaryInputs.planInput);
1058
- capacityPlan.capacity.writers = 2;
1059
- const partialState = compilePrimaryRecord({
1060
- run: treatmentRun,
1061
- inputs: primaryInputs,
1062
- manualEvidence: primaryInputs.partialManualEvidence,
1063
- planInput: primaryInputs.planInput,
1064
- condition: 'primary-treatment-partial-state',
1065
- });
1066
- const capacity2 = compilePrimaryRecord({
1067
- run: treatmentRun,
1068
- inputs: primaryInputs,
1069
- manualEvidence: primaryInputs.normalManualEvidence,
1070
- planInput: capacityPlan,
1071
- condition: 'primary-treatment-capacity-2',
1072
- });
1073
- const unknown = compileUnknownRecord({ run: treatmentRun, inputs: primaryInputs });
1074
- const transferControlRun = runs.get('rc1-transfer-control-1');
1075
- const transferTreatmentRun = runs.get('rc1-transfer-treatment-1');
1076
- const transfer = {
1077
- control: {
1078
- normal: compileTransferRecord({
1079
- run: transferControlRun,
1080
- inputs: rc1Inputs,
1081
- manualEvidence: rc1Inputs.normalManualEvidence,
1082
- label: 'normal',
1083
- }),
1084
- negative: compileTransferRecord({
1085
- run: transferControlRun,
1086
- inputs: rc1Inputs,
1087
- manualEvidence: rc1Inputs.negativeManualEvidence,
1088
- label: 'negative',
1089
- }),
1090
- },
1091
- treatment: {
1092
- normal: compileTransferRecord({
1093
- run: transferTreatmentRun,
1094
- inputs: rc1Inputs,
1095
- manualEvidence: rc1Inputs.normalManualEvidence,
1096
- label: 'normal',
1097
- }),
1098
- negative: compileTransferRecord({
1099
- run: transferTreatmentRun,
1100
- inputs: rc1Inputs,
1101
- manualEvidence: rc1Inputs.negativeManualEvidence,
1102
- label: 'negative',
1103
- }),
1104
- },
1105
- };
1106
- return {
1107
- primary: { control, treatment, partial_state: partialState, capacity_2: capacity2,
1108
- third_only_unknown: unknown },
1109
- rc1_transfer: transfer,
1110
- };
1111
- }
1112
-
1113
- const COMPILED_RECORD_PATHS = Object.freeze({
1114
- 'compiled/primary-control-1-normal.json': ['primary', 'control', 0],
1115
- 'compiled/primary-control-2-normal.json': ['primary', 'control', 1],
1116
- 'compiled/primary-treatment-1-normal.json': ['primary', 'treatment', 0],
1117
- 'compiled/primary-treatment-2-normal.json': ['primary', 'treatment', 1],
1118
- 'compiled/primary-treatment-partial-state.json': ['primary', 'partial_state'],
1119
- 'compiled/primary-treatment-capacity-2.json': ['primary', 'capacity_2'],
1120
- 'compiled/primary-treatment-third-only-unknown.json': ['primary', 'third_only_unknown'],
1121
- 'compiled/rc1-transfer-control-normal.json': ['rc1_transfer', 'control', 'normal'],
1122
- 'compiled/rc1-transfer-control-negative.json': ['rc1_transfer', 'control', 'negative'],
1123
- 'compiled/rc1-transfer-treatment-normal.json': ['rc1_transfer', 'treatment', 'normal'],
1124
- 'compiled/rc1-transfer-treatment-negative.json': ['rc1_transfer', 'treatment', 'negative'],
1125
- });
1126
-
1127
- function nestedValue(value, keys) {
1128
- return keys.reduce((current, key) => current?.[key], value);
1129
- }
1130
-
1131
- function verifyCompiledConditions(context, recomputed) {
1132
- return Object.entries(COMPILED_RECORD_PATHS).every(([relativePath, keys]) => (
1133
- sameArtifact(context.json.get(relativePath), nestedValue(recomputed, keys))
1134
- ));
1135
- }
1136
-
1137
- function distinctConflictPairs(record) {
1138
- return new Set(record.bundle.graph.conflicts.map(({ todo_ids: todoIds }) => (
1139
- [...todoIds].sort().join('\u0000')
1140
- ))).size;
1141
- }
1142
-
1143
- function conditionMetrics(record) {
1144
- return {
1145
- conflict_records: record.bundle.graph.conflicts.length,
1146
- distinct_conflict_pairs: distinctConflictPairs(record),
1147
- minimum_feasible_waves: record.plan.minimum_feasible_waves,
1148
- };
1149
- }
1150
-
1151
- function expectedComparison(context, recomputed) {
1152
- const identity = context.json.get('identity.json');
1153
- const transform = context.json.get('transform/accepted-artifact.json');
1154
- const newPlan = context.json.get('new-plan-version.json');
1155
- const planDiff = context.json.get('plan-diff.json');
1156
- return {
1157
- schema: 'lattice.rc2.control_treatment_comparison.v1',
1158
- base_sha: context.manifest.base_sha,
1159
- identity_digest: digestArtifact(identity),
1160
- independent_variable: {
1161
- kind: 'accepted_registry_shard_patch',
1162
- transform_artifact_digest: digestArtifact(transform),
1163
- patch_digest: transform.patch.digest,
1164
- },
1165
- condition_artifact_digests: {
1166
- primary_control: recomputed.primary.control.map(({ artifact_digest: digest }) => digest),
1167
- primary_treatment: recomputed.primary.treatment.map(({ artifact_digest: digest }) => digest),
1168
- primary_partial_state: recomputed.primary.partial_state.artifact_digest,
1169
- primary_capacity_2: recomputed.primary.capacity_2.artifact_digest,
1170
- primary_unknown: digestArtifact(recomputed.primary.third_only_unknown),
1171
- rc1_transfer_control_normal: recomputed.rc1_transfer.control.normal.artifact_digest,
1172
- rc1_transfer_control_negative: recomputed.rc1_transfer.control.negative.artifact_digest,
1173
- rc1_transfer_treatment_normal: recomputed.rc1_transfer.treatment.normal.artifact_digest,
1174
- rc1_transfer_treatment_negative: recomputed.rc1_transfer.treatment.negative.artifact_digest,
1175
- },
1176
- metrics: {
1177
- primary_control: conditionMetrics(recomputed.primary.control[0]),
1178
- primary_treatment: conditionMetrics(recomputed.primary.treatment[0]),
1179
- primary_partial_state: conditionMetrics(recomputed.primary.partial_state),
1180
- primary_capacity_2: conditionMetrics(recomputed.primary.capacity_2),
1181
- rc1_transfer_control_normal: conditionMetrics(recomputed.rc1_transfer.control.normal),
1182
- rc1_transfer_control_negative: conditionMetrics(recomputed.rc1_transfer.control.negative),
1183
- rc1_transfer_treatment_normal: conditionMetrics(recomputed.rc1_transfer.treatment.normal),
1184
- rc1_transfer_treatment_negative: conditionMetrics(recomputed.rc1_transfer.treatment.negative),
1185
- },
1186
- version_barrier: {
1187
- new_plan_version_digest: digestArtifact(newPlan),
1188
- plan_diff_digest: digestArtifact(planDiff),
1189
- causal_predecessors_digest: digestArtifact(planDiff.causal_predecessors),
1190
- },
1191
- };
1192
- }
1193
-
1194
- function expectedHypothesis(comparison, recomputed, transform) {
1195
- const checks = [
1196
- { id: 'accepted_transform_only', passed: transform.status === 'accepted' },
1197
- {
1198
- id: 'primary_repeat_reproducible',
1199
- passed: new Set(recomputed.primary.control.map(({ artifact_digest: digest }) => digest)).size === 1
1200
- && new Set(recomputed.primary.treatment.map(({ artifact_digest: digest }) => digest)).size === 1,
1201
- },
1202
- {
1203
- id: 'primary_conflicts_removed',
1204
- passed: comparison.metrics.primary_control.conflict_records === 12
1205
- && comparison.metrics.primary_control.distinct_conflict_pairs === 3
1206
- && comparison.metrics.primary_treatment.conflict_records === 0,
1207
- },
1208
- {
1209
- id: 'primary_waves_reduced',
1210
- passed: comparison.metrics.primary_control.minimum_feasible_waves === 3
1211
- && comparison.metrics.primary_treatment.minimum_feasible_waves === 1,
1212
- },
1213
- {
1214
- id: 'partial_state_preserved',
1215
- passed: comparison.metrics.primary_partial_state.conflict_records === 1
1216
- && comparison.metrics.primary_partial_state.minimum_feasible_waves === 2,
1217
- },
1218
- {
1219
- id: 'capacity_control_preserved',
1220
- passed: comparison.metrics.primary_capacity_2.conflict_records === 0
1221
- && comparison.metrics.primary_capacity_2.minimum_feasible_waves === 2,
1222
- },
1223
- {
1224
- id: 'third_only_unknown_closed',
1225
- passed: recomputed.primary.third_only_unknown.outcome.outcome === 'unknown'
1226
- && recomputed.primary.third_only_unknown.verification.outcome === 'unknown',
1227
- },
1228
- {
1229
- id: 'rc1_transfer_isomorphic',
1230
- passed: comparison.metrics.rc1_transfer_control_normal.conflict_records === 3
1231
- && comparison.metrics.rc1_transfer_control_normal.minimum_feasible_waves === 2
1232
- && comparison.metrics.rc1_transfer_treatment_normal.conflict_records === 0
1233
- && comparison.metrics.rc1_transfer_treatment_normal.minimum_feasible_waves === 1
1234
- && comparison.metrics.rc1_transfer_control_negative.minimum_feasible_waves === 2
1235
- && comparison.metrics.rc1_transfer_treatment_negative.minimum_feasible_waves === 2,
1236
- },
1237
- {
1238
- id: 'all_minimum_verified',
1239
- passed: Object.values(COMPILED_RECORD_PATHS).every((keys) => {
1240
- const record = nestedValue(recomputed, keys);
1241
- return record.outcome !== 'compiled' || record.verification.outcome === 'verified';
1242
- }),
1243
- },
1244
- ];
1245
- return {
1246
- schema: 'lattice.rc2.hypothesis_evaluation.v1',
1247
- checks,
1248
- supported: checks.every(({ passed }) => passed),
1249
- failed_conditions: checks.filter(({ passed }) => !passed).map(({ id }) => id),
1250
- };
1251
- }
1252
-
1253
- function expectedPredecessorKinds(context) {
1254
- const expected = new Map();
1255
- for (const ref of context.predecessorPaths) {
1256
- expected.set(
1257
- ref,
1258
- ref === 'predecessors/rc1-v6-plan.md'
1259
- ? 'rc1_v6_phase_archive'
1260
- : 'immutable_predecessor',
1261
- );
1262
- }
1263
- expected.set('transform/accepted-artifact.json', 'accepted_transform');
1264
- expected.set('transform/behavior-evidence.json', 'behavior_envelope');
1265
- expected.set('transform/mutation-evidence.json', 'mutation_evidence');
1266
- for (const runId of RUN_IDS) expected.set(`evidence/${runId}.json`, 'evidence_bundle');
1267
- for (const ref of Object.values(PRIMARY_INPUT_PATHS)) expected.set(ref, 'fixed_input');
1268
- expected.set('identity.json', 'execution_identity');
1269
- expected.set('identity/schedulability-compiler-v2.mjs', 'compiler_identity');
1270
- expected.set('identity/schedulability-verifier-v2.mjs', 'verifier_identity');
1271
- if (context.artifactVersion !== 'v1') {
1272
- expected.set(SENSOR_CONFIG_PATH, 'sensor_project_config');
1273
- }
1274
- return expected;
1275
- }
1276
-
1277
- function verifyV1PredecessorPair(context) {
1278
- if (context.artifactVersion === 'v1') return true;
1279
- const manifest = context.json.get('predecessors/rc2-v1-artifact-manifest.json');
1280
- const plan = context.json.get('predecessors/rc2-v1-new-plan-version.json');
1281
- if (!exactRecord(manifest, ['schema', 'base_sha', 'result_digest', 'files'])
1282
- || manifest.schema !== 'lattice.rc2.artifact_manifest.v1'
1283
- || !GIT_SHA1.test(manifest.base_sha)
1284
- || !SHA256.test(manifest.result_digest)
1285
- || !Array.isArray(manifest.files)
1286
- || !sameArtifact(
1287
- manifest.files.map(({ path: relativePath }) => relativePath).sort(),
1288
- RC2_V1_ARTIFACT_PATHS,
1289
- )
1290
- || new Set(manifest.files.map(({ path: relativePath }) => relativePath)).size
1291
- !== RC2_V1_ARTIFACT_PATHS.length
1292
- || plan?.schema !== 'lattice.rc2.plan_version.v1'
1293
- || plan.version !== 'rc2-delivery-policy-v2') {
1294
- return false;
1295
- }
1296
- const planBytes = context.payloads.get('predecessors/rc2-v1-new-plan-version.json');
1297
- const entry = manifest.files.find(({ path: relativePath }) => (
1298
- relativePath === 'new-plan-version.json'
1299
- ));
1300
- return exactRecord(entry, ['path', 'media_type', 'bytes', 'sha256'])
1301
- && entry.media_type === 'application/json'
1302
- && entry.bytes === planBytes.byteLength
1303
- && entry.sha256 === sha256(planBytes);
1304
- }
1305
-
1306
- function verifyV2PredecessorPair(context) {
1307
- if (!['v3', 'v4'].includes(context.artifactVersion)) return true;
1308
- const manifest = context.json.get('predecessors/rc2-v2-artifact-manifest.json');
1309
- const plan = context.json.get('predecessors/rc2-v2-new-plan-version.json');
1310
- if (!exactRecord(manifest, ['schema', 'base_sha', 'result_digest', 'files'])
1311
- || manifest.schema !== 'lattice.rc2.artifact_manifest.v2'
1312
- || !GIT_SHA1.test(manifest.base_sha)
1313
- || !SHA256.test(manifest.result_digest)
1314
- || !Array.isArray(manifest.files)
1315
- || !sameArtifact(
1316
- manifest.files.map(({ path: relativePath }) => relativePath).sort(),
1317
- RC2_V2_ARTIFACT_PATHS,
1318
- )
1319
- || new Set(manifest.files.map(({ path: relativePath }) => relativePath)).size
1320
- !== RC2_V2_ARTIFACT_PATHS.length
1321
- || plan?.schema !== 'lattice.rc2.plan_version.v1'
1322
- || plan.version !== 'rc2-delivery-policy-v3') {
1323
- return false;
1324
- }
1325
- const planBytes = context.payloads.get('predecessors/rc2-v2-new-plan-version.json');
1326
- const entry = manifest.files.find(({ path: relativePath }) => (
1327
- relativePath === 'new-plan-version.json'
1328
- ));
1329
- return exactRecord(entry, ['path', 'media_type', 'bytes', 'sha256'])
1330
- && entry.media_type === 'application/json'
1331
- && entry.bytes === planBytes.byteLength
1332
- && entry.sha256 === sha256(planBytes);
1333
- }
1334
-
1335
- function verifyV3PredecessorPair(context) {
1336
- if (context.artifactVersion !== 'v4') return true;
1337
- const manifest = context.json.get('predecessors/rc2-v3-artifact-manifest.json');
1338
- const plan = context.json.get('predecessors/rc2-v3-new-plan-version.json');
1339
- if (!exactRecord(manifest, ['schema', 'base_sha', 'result_digest', 'files'])
1340
- || manifest.schema !== 'lattice.rc2.artifact_manifest.v3'
1341
- || !GIT_SHA1.test(manifest.base_sha)
1342
- || !SHA256.test(manifest.result_digest)
1343
- || !Array.isArray(manifest.files)
1344
- || !sameArtifact(
1345
- manifest.files.map(({ path: relativePath }) => relativePath).sort(),
1346
- RC2_V3_ARTIFACT_PATHS,
1347
- )
1348
- || new Set(manifest.files.map(({ path: relativePath }) => relativePath)).size
1349
- !== RC2_V3_ARTIFACT_PATHS.length
1350
- || plan?.schema !== 'lattice.rc2.plan_version.v1'
1351
- || plan.version !== 'rc2-delivery-policy-v4') {
1352
- return false;
1353
- }
1354
- const planBytes = context.payloads.get('predecessors/rc2-v3-new-plan-version.json');
1355
- const entry = manifest.files.find(({ path: relativePath }) => (
1356
- relativePath === 'new-plan-version.json'
1357
- ));
1358
- return exactRecord(entry, ['path', 'media_type', 'bytes', 'sha256'])
1359
- && entry.media_type === 'application/json'
1360
- && entry.bytes === planBytes.byteLength
1361
- && entry.sha256 === sha256(planBytes);
1362
- }
1363
-
1364
- function verifyPredecessors(context) {
1365
- const planDiff = context.json.get('plan-diff.json');
1366
- const newPlan = context.json.get('new-plan-version.json');
1367
- const expected = expectedPredecessorKinds(context);
1368
- if (!Array.isArray(planDiff?.causal_predecessors)
1369
- || !sameArtifact(planDiff.causal_predecessors, newPlan?.causal_predecessors)
1370
- || planDiff.causal_predecessors.length !== expected.size) {
1371
- return false;
1372
- }
1373
- const refs = new Set();
1374
- for (const predecessor of planDiff.causal_predecessors) {
1375
- if (!exactRecord(predecessor, ['kind', 'ref', 'digest'])
1376
- || predecessor.kind !== expected.get(predecessor.ref)
1377
- || !context.artifactPaths.includes(predecessor.ref)
1378
- || refs.has(predecessor.ref)
1379
- || predecessor.digest !== sha256(context.payloads.get(predecessor.ref))) {
1380
- return false;
1381
- }
1382
- refs.add(predecessor.ref);
1383
- }
1384
- return refs.size === expected.size
1385
- && [...expected.keys()].every((relativePath) => refs.has(relativePath))
1386
- && verifyV1PredecessorPair(context)
1387
- && verifyV2PredecessorPair(context)
1388
- && verifyV3PredecessorPair(context);
1389
- }
1390
-
1391
- function verifyVersionBarrier(context, recomputed) {
1392
- const primaryInputs = objectFromPaths(context, PRIMARY_INPUT_PATHS);
1393
- const newPlan = context.json.get('new-plan-version.json');
1394
- const planDiff = context.json.get('plan-diff.json');
1395
- const control = recomputed.primary.control[0];
1396
- const treatment = recomputed.primary.treatment[0];
1397
- const expectedInvalidations = [
1398
- 'old_plan',
1399
- 'agent_context',
1400
- 'partial_patch',
1401
- 'interface_assumption',
1402
- 'boundary_evidence',
1403
- ];
1404
- const predecessorPath = {
1405
- v1: null,
1406
- v2: 'predecessors/rc2-v1-new-plan-version.json',
1407
- v3: 'predecessors/rc2-v2-new-plan-version.json',
1408
- v4: 'predecessors/rc2-v3-new-plan-version.json',
1409
- }[context.artifactVersion];
1410
- const predecessorPlan = predecessorPath === null ? null : context.json.get(predecessorPath);
1411
- const versionedPredecessor = predecessorPlan !== null;
1412
- const predecessorVersion = versionedPredecessor
1413
- ? predecessorPlan?.version
1414
- : primaryInputs.planInput.plan_version;
1415
- const expectedVersion = {
1416
- v1: 'rc2-delivery-policy-v2',
1417
- v2: 'rc2-delivery-policy-v3',
1418
- v3: 'rc2-delivery-policy-v4',
1419
- v4: 'rc2-delivery-policy-v5',
1420
- }[context.artifactVersion];
1421
- const expectedOldDigest = versionedPredecessor
1422
- ? digestArtifact(predecessorPlan)
1423
- : digestArtifact(control.plan);
1424
- return newPlan?.schema === 'lattice.rc2.plan_version.v1'
1425
- && newPlan.version === expectedVersion
1426
- && newPlan.predecessor_version === predecessorVersion
1427
- && sameArtifact(newPlan.plan, treatment.plan)
1428
- && newPlan.plan_digest === digestArtifact(treatment.plan)
1429
- && newPlan.bundle_digest === digestArtifact(treatment.bundle)
1430
- && newPlan.verdict_digest === digestArtifact(treatment.verdict)
1431
- && sameArtifact(
1432
- [...newPlan.affected_todos].sort(),
1433
- primaryInputs.planInput.todos.map(({ id }) => id).sort(),
1434
- )
1435
- && planDiff?.schema === 'lattice.rc2.plan_diff.v1'
1436
- && planDiff.old_plan?.version === predecessorVersion
1437
- && planDiff.old_plan?.digest === expectedOldDigest
1438
- && planDiff.new_plan?.version === newPlan.version
1439
- && planDiff.new_plan?.digest === digestArtifact(newPlan)
1440
- && sameArtifact(planDiff.affected_todos, newPlan.affected_todos)
1441
- && planDiff.invalidated_contexts?.map(({ kind }) => kind)
1442
- .every((kind, index) => kind === expectedInvalidations[index])
1443
- && planDiff.invalidated_contexts.length === expectedInvalidations.length
1444
- && (!versionedPredecessor || (
1445
- predecessorPlan?.plan_digest === digestArtifact(predecessorPlan.plan)
1446
- && sameArtifact(predecessorPlan.plan, treatment.plan)
1447
- && planDiff.invalidated_contexts.find(({ kind }) => kind === 'interface_assumption')?.ref
1448
- === `${predecessorVersion}-interface-assumption`
1449
- && planDiff.invalidated_contexts.find(({ kind }) => kind === 'boundary_evidence')?.ref
1450
- === `${predecessorVersion}-boundary-evidence`
1451
- ));
1452
- }
1453
-
1454
- function verifyCost(context) {
1455
- const cost = context.json.get('cost.json');
1456
- if (cost?.schema !== 'lattice.rc2.stage_cost.v1'
1457
- || !Array.isArray(cost.measurements)
1458
- || cost.measurements.length < 20
1459
- || cost.measurements.some((measurement) => (
1460
- !exactRecord(measurement, ['stage', 'state', 'elapsed_ms'])
1461
- || typeof measurement.stage !== 'string'
1462
- || measurement.state !== 'measured'
1463
- || typeof measurement.elapsed_ms !== 'number'
1464
- || !Number.isFinite(measurement.elapsed_ms)
1465
- || measurement.elapsed_ms < 0
1466
- ))
1467
- || cost.aggregate?.measured_count !== cost.measurements.length
1468
- || cost.aggregate?.not_measured_count !== 0) {
1469
- return false;
1470
- }
1471
- const elapsed = Math.round(cost.measurements
1472
- .reduce((sum, measurement) => sum + measurement.elapsed_ms, 0) * 1_000) / 1_000;
1473
- const transform = context.json.get('transform/accepted-artifact.json');
1474
- return cost.aggregate.elapsed_ms === elapsed
1475
- && cost.intervention?.patch_bytes === transform.patch.bytes
1476
- && cost.intervention?.files === transform.scope.changed_paths.length
1477
- && Number.isSafeInteger(cost.intervention?.review_lines)
1478
- && cost.intervention.review_lines > 0
1479
- && cost.rework?.rejected_attempts === 2
1480
- && cost.rework?.retries === 0
1481
- && cost.rework?.rollbacks === 0
1482
- && Array.isArray(cost.unverified)
1483
- && cost.unverified.length > 0;
1484
- }
1485
-
1486
- function expectedExecutionEvidence(context, recomputed, comparison, hypothesis) {
1487
- const identity = context.json.get('identity.json');
1488
- const transform = context.json.get('transform/accepted-artifact.json');
1489
- const newPlan = context.json.get('new-plan-version.json');
1490
- const planDiff = context.json.get('plan-diff.json');
1491
- const cost = context.json.get('cost.json');
1492
- return {
1493
- schema: 'lattice.rc2.campaign_execution_evidence.v1',
1494
- base_sha: context.manifest.base_sha,
1495
- identity_digest: digestArtifact(identity),
1496
- transform_artifact_digest: digestArtifact(transform),
1497
- run_digests: RUN_IDS.map((runId) => digestArtifact(
1498
- context.json.get(`evidence/${runId}.json`),
1499
- )),
1500
- compiled_condition_digests: Object.values(COMPILED_RECORD_PATHS).map((keys) => (
1501
- digestArtifact(nestedValue(recomputed, keys))
1502
- )),
1503
- new_plan_version_digest: digestArtifact(newPlan),
1504
- plan_diff_digest: digestArtifact(planDiff),
1505
- comparison_digest: digestArtifact(comparison),
1506
- hypothesis_evaluation_digest: digestArtifact(hypothesis),
1507
- cost_digest: digestArtifact(cost),
1508
- };
1509
- }
1510
-
1511
- /** 保存payloadだけからRC2のcausal relationとschedule minimumを再計算する。 */
1512
- export function verifyRc2CampaignArtifactSet(options = {}) {
1513
- const checks = [];
1514
- const check = (id, passed) => checks.push({ id, passed: passed === true });
1515
- const context = artifactContext(options);
1516
- check('exact_artifact_set', context !== null);
1517
- if (context === null) {
1518
- return {
1519
- schema: 'lattice.rc2.artifact_set_verification.v1',
1520
- valid: false,
1521
- checks,
1522
- failed_conditions: ['exact_artifact_set'],
1523
- };
1524
- }
1525
-
1526
- check('identity_binding', verifyIdentity(context));
1527
- if (context.artifactVersion !== 'v1') {
1528
- check('sensor_config_binding', verifyLatticeSensorConfig(context));
1529
- }
1530
- check('transform_binding', verifyTransform(context));
1531
- check('fresh_run_binding', verifyRuns(context));
1532
-
1533
- let recomputed;
1534
- try {
1535
- recomputed = recomputeConditions(context);
1536
- } catch {
1537
- recomputed = null;
1538
- }
1539
- check('compiled_conditions', recomputed !== null
1540
- && verifyCompiledConditions(context, recomputed));
1541
- check('minimum_verification', recomputed !== null
1542
- && Object.values(COMPILED_RECORD_PATHS).every((keys) => {
1543
- const record = nestedValue(recomputed, keys);
1544
- return record.outcome !== 'compiled' || record.verification.outcome === 'verified';
1545
- }));
1546
- check('repeat_reproducibility', recomputed !== null
1547
- && new Set(recomputed.primary.control.map(({ artifact_digest: digest }) => digest)).size === 1
1548
- && new Set(recomputed.primary.treatment.map(({ artifact_digest: digest }) => digest)).size === 1);
1549
- check('rc1_transfer_binding', recomputed !== null
1550
- && recomputed.rc1_transfer.control.normal.bundle.graph.conflicts.length === 3
1551
- && recomputed.rc1_transfer.treatment.normal.bundle.graph.conflicts.length === 0);
1552
- check('predecessor_binding', verifyPredecessors(context));
1553
- check('version_barrier', recomputed !== null && verifyVersionBarrier(context, recomputed));
1554
- check('cost_arithmetic', verifyCost(context));
1555
-
1556
- let comparison;
1557
- let hypothesis;
1558
- if (recomputed !== null) {
1559
- comparison = expectedComparison(context, recomputed);
1560
- hypothesis = expectedHypothesis(
1561
- comparison,
1562
- recomputed,
1563
- context.json.get('transform/accepted-artifact.json'),
1564
- );
1565
- }
1566
- check('comparison_recalculation', recomputed !== null
1567
- && sameArtifact(comparison, context.json.get('comparison.json')));
1568
- check('hypothesis_recalculation', recomputed !== null
1569
- && hypothesis.supported
1570
- && sameArtifact(hypothesis, context.json.get('hypothesis-evaluation.json'))
1571
- && context.manifest.result_digest === digestArtifact(hypothesis));
1572
- check('execution_binding', recomputed !== null
1573
- && sameArtifact(
1574
- expectedExecutionEvidence(context, recomputed, comparison, hypothesis),
1575
- context.json.get('execution-evidence.json'),
1576
- ));
1577
-
1578
- return {
1579
- schema: 'lattice.rc2.artifact_set_verification.v1',
1580
- valid: checks.every(({ passed }) => passed),
1581
- checks,
1582
- failed_conditions: checks.filter(({ passed }) => !passed).map(({ id }) => id),
1583
- };
1584
- }
1
+ import { createHash } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+
4
+ import {
5
+ canonicalizeArtifact,
6
+ digestArtifact,
7
+ } from './artifact-contracts.mjs';
8
+ import { compileBoundaryCondition } from './boundary-compiler.mjs';
9
+ import { compileDeliveryPolicyBoundaryBundleV2 } from './rc2-delivery-policy-front-end.mjs';
10
+ import { expectedRc2DeliveryPolicyOracleReceipt } from './rc2-delivery-policy-oracle.mjs';
11
+ import { compileRc1TransferBundleV2 } from './rc2-rc1-transfer-front-end.mjs';
12
+ import {
13
+ validateRc1EvidenceBundle,
14
+ } from './rc1-evidence-bundle.mjs';
15
+ import { compileSchedulabilityGraphV2 } from './schedulability-compiler-v2.mjs';
16
+ import { verifySchedulabilityPlanV2 } from './schedulability-verifier-v2.mjs';
17
+
18
+ const SHA256 = /^[0-9a-f]{64}$/;
19
+ const GIT_SHA1 = /^[0-9a-f]{40}$/;
20
+ const RAW_EVIDENCE_CHUNK_BYTES = 12_000;
21
+ const RC2_ORACLE_PATH = 'src/rc2-delivery-policy-oracle.mjs';
22
+ const RC2_ORACLE_IDENTITY_REF = 'identity/rc2-delivery-policy-oracle.mjs';
23
+ const RC2_TRANSFORM_PATH = 'src/rc2-delivery-policy-transform.mjs';
24
+ const RC2_TRANSFORM_IDENTITY_REF = 'identity/rc2-delivery-policy-transform.mjs';
25
+ const LEGACY_WITNESS = Object.freeze({
26
+ epoch: 'delivery-policy-legacy-v1',
27
+ candidateDigest: '30ee67852f7ab5fb0d9bf82f2a4c55b6569a76507b0df5b329290c84d29b49f5',
28
+ oracleSourceDigest: 'c4012dfc00cc5b0194bd1a87be4a4e0b20d45e784d49a987768eea1b9932fafe',
29
+ });
30
+ const SEMANTIC_WITNESS = Object.freeze({
31
+ epoch: 'delivery-policy-semantic-v2',
32
+ candidateDigest: '4cc5d7bb428a8899353d18524c25105742fa90f89ee55d36064c4be3c52e2907',
33
+ oracleSourceDigest: 'c68a7ff9a7c9c4a181ceda6396d5fcbf27084de18680018d244a27998041652c',
34
+ });
35
+ const WITNESS_BY_VERSION = Object.freeze({
36
+ v1: LEGACY_WITNESS,
37
+ v2: LEGACY_WITNESS,
38
+ v3: SEMANTIC_WITNESS,
39
+ v4: SEMANTIC_WITNESS,
40
+ });
41
+
42
+ const PRIMARY_INPUT_PATHS = Object.freeze({
43
+ planInput: 'inputs/primary/plan-input.json',
44
+ candidateSpec: 'inputs/primary/candidate-spec-v1.json',
45
+ normalManualEvidence: 'inputs/primary/manual-evidence.normal.json',
46
+ partialManualEvidence: 'inputs/primary/manual-evidence.partial-state-negative.json',
47
+ unknownManualEvidence: 'inputs/primary/manual-evidence.third-only-unknown.json',
48
+ querySet: 'inputs/primary/query-set-v2.json',
49
+ });
50
+
51
+ const RC1_INPUT_PATHS = Object.freeze({
52
+ planInput: 'inputs/rc1/plan-input.json',
53
+ candidateSpec: 'inputs/rc1/candidate-spec-v2.json',
54
+ normalManualEvidence: 'inputs/rc1/manual-evidence.normal.json',
55
+ negativeManualEvidence: 'inputs/rc1/manual-evidence.shared-state-negative.json',
56
+ querySet: 'inputs/rc1/query-set-v2.json',
57
+ oracle: 'inputs/rc1/behavior-oracle-v2.json',
58
+ });
59
+
60
+ const SENSOR_CONFIG_PATH = 'identity/lattice-sensor-config.json';
61
+ // ratified config epochのallowlist。artifactのconfig bytesはこのいずれかと完全一致し、
62
+ // かつidentity.jsonのproject_config_digestと自己整合でなければreject(第三のbytesはfail closed)。
63
+ const SENSOR_CONFIG_EPOCHS = Object.freeze([
64
+ // ADR 0040 epoch(RC2 v2〜v4 canonical artifactが保存する当時のratified config)
65
+ Buffer.from('{"exclude":["research/campaigns/**/artifacts/**/identity/"]}\n', 'utf8'),
66
+ // ADR 0044 Decision 10.3 epoch(research/runs/ event store除外、RC3-B以降のfresh実行)
67
+ Buffer.from(
68
+ '{"exclude":["research/campaigns/**/artifacts/**/identity/","research/runs/"]}\n',
69
+ 'utf8',
70
+ ),
71
+ // ADR 0053 Decision 3 epoch(Lattice TODO state/generated artifact除外、G2以降のfresh実行)
72
+ Buffer.from(
73
+ '{"exclude":["research/campaigns/**/artifacts/**/identity/","research/runs/",".lattice/todo/",".lattice/generated/"]}\n',
74
+ 'utf8',
75
+ ),
76
+ ]);
77
+
78
+ const V1_IDENTITY_PATHS = Object.freeze([
79
+ 'identity/lattice-sensor-adapter.mjs',
80
+ 'identity/lattice-sensor-executable',
81
+ 'identity/rc1-black-box-oracle.mjs',
82
+ 'identity/rc1-boundary-compiler.mjs',
83
+ 'identity/rc1-evidence-bundle.mjs',
84
+ 'identity/rc2-artifact-set.mjs',
85
+ 'identity/rc2-campaign.mjs',
86
+ 'identity/rc2-delivery-policy-front-end.mjs',
87
+ 'identity/rc2-delivery-policy-oracle.mjs',
88
+ 'identity/rc2-delivery-policy-transform.mjs',
89
+ 'identity/rc2-rc1-transfer-front-end.mjs',
90
+ 'identity/schedulability-compiler-v2.mjs',
91
+ 'identity/schedulability-verifier-v2.mjs',
92
+ ]);
93
+
94
+ const V2_IDENTITY_PATHS = Object.freeze([
95
+ ...V1_IDENTITY_PATHS,
96
+ SENSOR_CONFIG_PATH,
97
+ ]);
98
+
99
+ const V3_IDENTITY_PATHS = V2_IDENTITY_PATHS;
100
+ const V4_IDENTITY_PATHS = V3_IDENTITY_PATHS;
101
+
102
+ const V1_PREDECESSOR_PATHS = Object.freeze([
103
+ 'predecessors/adr-0031.md',
104
+ 'predecessors/adr-0032.md',
105
+ 'predecessors/adr-0037.md',
106
+ 'predecessors/adr-0038.md',
107
+ 'predecessors/rc1-v6-artifact-manifest.json',
108
+ 'predecessors/rc1-v6-plan.md',
109
+ 'predecessors/rc1-v6-seam.patch',
110
+ 'predecessors/rc1-v6-transform-artifact.json',
111
+ 'predecessors/rc1-v6-transform-receipt.json',
112
+ ]);
113
+
114
+ const V2_PREDECESSOR_PATHS = Object.freeze([
115
+ ...V1_PREDECESSOR_PATHS,
116
+ 'predecessors/adr-0040.md',
117
+ 'predecessors/rc2-v1-artifact-manifest.json',
118
+ 'predecessors/rc2-v1-new-plan-version.json',
119
+ ]);
120
+
121
+ const V3_PREDECESSOR_PATHS = Object.freeze([
122
+ ...V2_PREDECESSOR_PATHS,
123
+ 'predecessors/adr-0041.md',
124
+ 'predecessors/rc2-semantic-reseal-characterization.md',
125
+ 'predecessors/rc2-v2-artifact-manifest.json',
126
+ 'predecessors/rc2-v2-new-plan-version.json',
127
+ ]);
128
+
129
+ const V4_PREDECESSOR_PATHS = Object.freeze([
130
+ ...V3_PREDECESSOR_PATHS,
131
+ 'predecessors/adr-0042.md',
132
+ 'predecessors/rc2-v3-version-downgrade-refutation.md',
133
+ 'predecessors/rc2-v3-artifact-manifest.json',
134
+ 'predecessors/rc2-v3-new-plan-version.json',
135
+ ]);
136
+
137
+ const BYTE_PRESERVING_JSON_PATHS = new Set([
138
+ 'predecessors/rc1-v6-artifact-manifest.json',
139
+ 'predecessors/rc1-v6-transform-artifact.json',
140
+ 'predecessors/rc1-v6-transform-receipt.json',
141
+ SENSOR_CONFIG_PATH,
142
+ ]);
143
+
144
+ const TRANSFORM_PATHS = Object.freeze([
145
+ 'transform/accepted-artifact.json',
146
+ 'transform/accepted-receipt.json',
147
+ 'transform/behavior-evidence.json',
148
+ 'transform/mutation-evidence.json',
149
+ 'transform/rejected-incomplete-artifact.json',
150
+ 'transform/rejected-incomplete-receipt.json',
151
+ 'transform/rejected-scope-artifact.json',
152
+ 'transform/rejected-scope-receipt.json',
153
+ 'transform/seam.patch',
154
+ ]);
155
+
156
+ const RUN_IDS = Object.freeze([
157
+ 'primary-control-1',
158
+ 'primary-control-2',
159
+ 'primary-treatment-1',
160
+ 'primary-treatment-2',
161
+ 'rc1-transfer-control-1',
162
+ 'rc1-transfer-treatment-1',
163
+ ]);
164
+
165
+ const COMPILED_PATHS = Object.freeze([
166
+ 'compiled/primary-control-1-normal.json',
167
+ 'compiled/primary-control-2-normal.json',
168
+ 'compiled/primary-treatment-1-normal.json',
169
+ 'compiled/primary-treatment-2-normal.json',
170
+ 'compiled/primary-treatment-capacity-2.json',
171
+ 'compiled/primary-treatment-partial-state.json',
172
+ 'compiled/primary-treatment-third-only-unknown.json',
173
+ 'compiled/rc1-transfer-control-negative.json',
174
+ 'compiled/rc1-transfer-control-normal.json',
175
+ 'compiled/rc1-transfer-treatment-negative.json',
176
+ 'compiled/rc1-transfer-treatment-normal.json',
177
+ ]);
178
+
179
+ const SUMMARY_PATHS = Object.freeze([
180
+ 'comparison.json',
181
+ 'cost.json',
182
+ 'execution-evidence.json',
183
+ 'hypothesis-evaluation.json',
184
+ 'identity.json',
185
+ 'new-plan-version.json',
186
+ 'plan-diff.json',
187
+ ]);
188
+
189
+ const RC2_V1_ARTIFACT_PATHS = Object.freeze([
190
+ ...Object.values(PRIMARY_INPUT_PATHS),
191
+ ...Object.values(RC1_INPUT_PATHS),
192
+ ...V1_IDENTITY_PATHS,
193
+ ...V1_PREDECESSOR_PATHS,
194
+ ...TRANSFORM_PATHS,
195
+ ...RUN_IDS.map((runId) => `evidence/${runId}.json`),
196
+ ...COMPILED_PATHS,
197
+ ...SUMMARY_PATHS,
198
+ ].sort());
199
+
200
+ const RC2_V2_ARTIFACT_PATHS = Object.freeze([
201
+ ...Object.values(PRIMARY_INPUT_PATHS),
202
+ ...Object.values(RC1_INPUT_PATHS),
203
+ ...V2_IDENTITY_PATHS,
204
+ ...V2_PREDECESSOR_PATHS,
205
+ ...TRANSFORM_PATHS,
206
+ ...RUN_IDS.map((runId) => `evidence/${runId}.json`),
207
+ ...COMPILED_PATHS,
208
+ ...SUMMARY_PATHS,
209
+ ].sort());
210
+
211
+ const RC2_V3_ARTIFACT_PATHS = Object.freeze([
212
+ ...Object.values(PRIMARY_INPUT_PATHS),
213
+ ...Object.values(RC1_INPUT_PATHS),
214
+ ...V3_IDENTITY_PATHS,
215
+ ...V3_PREDECESSOR_PATHS,
216
+ ...TRANSFORM_PATHS,
217
+ ...RUN_IDS.map((runId) => `evidence/${runId}.json`),
218
+ ...COMPILED_PATHS,
219
+ ...SUMMARY_PATHS,
220
+ ].sort());
221
+
222
+ export const RC2_ARTIFACT_PATHS = Object.freeze([
223
+ ...Object.values(PRIMARY_INPUT_PATHS),
224
+ ...Object.values(RC1_INPUT_PATHS),
225
+ ...V4_IDENTITY_PATHS,
226
+ ...V4_PREDECESSOR_PATHS,
227
+ ...TRANSFORM_PATHS,
228
+ ...RUN_IDS.map((runId) => `evidence/${runId}.json`),
229
+ ...COMPILED_PATHS,
230
+ ...SUMMARY_PATHS,
231
+ ].sort());
232
+
233
+ function plainRecord(value) {
234
+ return value !== null
235
+ && typeof value === 'object'
236
+ && !Array.isArray(value)
237
+ && Object.getPrototypeOf(value) === Object.prototype;
238
+ }
239
+
240
+ function exactRecord(value, keys) {
241
+ if (!plainRecord(value)) return false;
242
+ const actual = Object.keys(value).sort();
243
+ const expected = [...keys].sort();
244
+ return actual.length === expected.length
245
+ && actual.every((key, index) => key === expected[index]);
246
+ }
247
+
248
+ function sha256(bytes) {
249
+ return createHash('sha256').update(bytes).digest('hex');
250
+ }
251
+
252
+ function jsonBytes(value) {
253
+ return Buffer.from(canonicalizeArtifact(value), 'utf8');
254
+ }
255
+
256
+ function sameArtifact(left, right) {
257
+ try {
258
+ return digestArtifact(left) === digestArtifact(right);
259
+ } catch {
260
+ return false;
261
+ }
262
+ }
263
+
264
+ function mediaType(relativePath) {
265
+ if (relativePath.endsWith('.json')) return 'application/json';
266
+ if (relativePath.endsWith('.mjs')) return 'application/javascript';
267
+ if (relativePath.endsWith('.patch')) return 'text/x-diff';
268
+ if (relativePath.endsWith('.md')) return 'text/markdown';
269
+ return 'application/octet-stream';
270
+ }
271
+
272
+ function payloadMap(payloads) {
273
+ if (!Array.isArray(payloads)) return null;
274
+ const result = new Map();
275
+ for (const payload of payloads) {
276
+ if (!exactRecord(payload, ['path', 'bytes'])
277
+ || typeof payload.path !== 'string'
278
+ || !Buffer.isBuffer(payload.bytes)
279
+ || result.has(payload.path)) {
280
+ return null;
281
+ }
282
+ result.set(payload.path, payload.bytes);
283
+ }
284
+ return result;
285
+ }
286
+
287
+ function parseCanonicalJson(bytes) {
288
+ try {
289
+ const value = JSON.parse(bytes.toString('utf8'));
290
+ return jsonBytes(value).equals(bytes) ? value : null;
291
+ } catch {
292
+ return null;
293
+ }
294
+ }
295
+
296
+ function parseOpaqueJson(bytes) {
297
+ try {
298
+ return JSON.parse(bytes.toString('utf8'));
299
+ } catch {
300
+ return null;
301
+ }
302
+ }
303
+
304
+ function artifactContract(manifest) {
305
+ if (manifest?.schema === 'lattice.rc2.artifact_manifest.v1') {
306
+ return {
307
+ artifactVersion: 'v1',
308
+ artifactPaths: RC2_V1_ARTIFACT_PATHS,
309
+ identityPaths: V1_IDENTITY_PATHS,
310
+ predecessorPaths: V1_PREDECESSOR_PATHS,
311
+ witness: WITNESS_BY_VERSION.v1,
312
+ };
313
+ }
314
+ if (manifest?.schema === 'lattice.rc2.artifact_manifest.v2') {
315
+ return {
316
+ artifactVersion: 'v2',
317
+ artifactPaths: RC2_V2_ARTIFACT_PATHS,
318
+ identityPaths: V2_IDENTITY_PATHS,
319
+ predecessorPaths: V2_PREDECESSOR_PATHS,
320
+ witness: WITNESS_BY_VERSION.v2,
321
+ };
322
+ }
323
+ if (manifest?.schema === 'lattice.rc2.artifact_manifest.v3') {
324
+ return {
325
+ artifactVersion: 'v3',
326
+ artifactPaths: RC2_V3_ARTIFACT_PATHS,
327
+ identityPaths: V3_IDENTITY_PATHS,
328
+ predecessorPaths: V3_PREDECESSOR_PATHS,
329
+ witness: WITNESS_BY_VERSION.v3,
330
+ };
331
+ }
332
+ if (manifest?.schema === 'lattice.rc2.artifact_manifest.v4') {
333
+ return {
334
+ artifactVersion: 'v4',
335
+ artifactPaths: RC2_ARTIFACT_PATHS,
336
+ identityPaths: V4_IDENTITY_PATHS,
337
+ predecessorPaths: V4_PREDECESSOR_PATHS,
338
+ witness: WITNESS_BY_VERSION.v4,
339
+ };
340
+ }
341
+ return null;
342
+ }
343
+
344
+ function artifactContext(options) {
345
+ if (!exactRecord(options, ['manifest', 'payloads'])) return null;
346
+ const payloads = payloadMap(options.payloads);
347
+ const manifest = options.manifest;
348
+ const contract = artifactContract(manifest);
349
+ if (!payloads
350
+ || contract === null
351
+ || !exactRecord(manifest, ['schema', 'base_sha', 'result_digest', 'files'])
352
+ || !GIT_SHA1.test(manifest.base_sha)
353
+ || !SHA256.test(manifest.result_digest)
354
+ || !Array.isArray(manifest.files)) {
355
+ return null;
356
+ }
357
+ const manifestPaths = manifest.files.map(({ path: relativePath }) => relativePath).sort();
358
+ if (!sameArtifact(manifestPaths, contract.artifactPaths)
359
+ || !sameArtifact([...payloads.keys()].sort(), contract.artifactPaths)) {
360
+ return null;
361
+ }
362
+ for (const entry of manifest.files) {
363
+ const bytes = payloads.get(entry.path);
364
+ if (!exactRecord(entry, ['path', 'media_type', 'bytes', 'sha256'])
365
+ || !Buffer.isBuffer(bytes)
366
+ || entry.media_type !== mediaType(entry.path)
367
+ || entry.bytes !== bytes.byteLength
368
+ || entry.sha256 !== sha256(bytes)) {
369
+ return null;
370
+ }
371
+ }
372
+ const json = new Map();
373
+ for (const relativePath of contract.artifactPaths.filter((entry) => entry.endsWith('.json'))) {
374
+ const parsed = BYTE_PRESERVING_JSON_PATHS.has(relativePath)
375
+ ? parseOpaqueJson(payloads.get(relativePath))
376
+ : parseCanonicalJson(payloads.get(relativePath));
377
+ if (parsed === null) return null;
378
+ json.set(relativePath, parsed);
379
+ }
380
+ return { manifest, payloads, json, ...contract };
381
+ }
382
+
383
+ function objectFromPaths(context, paths) {
384
+ return Object.fromEntries(Object.entries(paths).map(([key, relativePath]) => (
385
+ [key, context.json.get(relativePath)]
386
+ )));
387
+ }
388
+
389
+ function stripDigest(value, key) {
390
+ if (!plainRecord(value) || !Object.hasOwn(value, key)) return null;
391
+ const result = structuredClone(value);
392
+ delete result[key];
393
+ return result;
394
+ }
395
+
396
+ function verifyIdentity(context) {
397
+ const identity = context.json.get('identity.json');
398
+ const projectConfigBound = context.artifactVersion !== 'v1';
399
+ const expectedIdentitySchema = `lattice.rc2.execution_identity.${context.artifactVersion}`;
400
+ const expectedLatticeSensorSchema = projectConfigBound
401
+ ? 'lattice.rc2.sensor_identity.v2'
402
+ : 'lattice.rc2.sensor_identity.v1';
403
+ const sensorKeys = projectConfigBound
404
+ ? [
405
+ 'schema',
406
+ 'version',
407
+ 'executable_ref',
408
+ 'executable_digest',
409
+ 'project_config_ref',
410
+ 'project_config_digest',
411
+ ]
412
+ : ['schema', 'version', 'executable_ref', 'executable_digest'];
413
+ if (!exactRecord(identity, [
414
+ 'schema',
415
+ 'sources',
416
+ 'sensor_identity',
417
+ 'sensor_identity_digest',
418
+ 'before_digest',
419
+ 'after_digest',
420
+ ])
421
+ || identity.schema !== expectedIdentitySchema
422
+ || !Array.isArray(identity.sources)
423
+ || identity.sources.length !== V1_IDENTITY_PATHS.length - 1
424
+ || !exactRecord(identity.sensor_identity, sensorKeys)
425
+ || identity.sensor_identity.schema !== expectedLatticeSensorSchema
426
+ || !SHA256.test(identity.sensor_identity.executable_digest)
427
+ || identity.sensor_identity.executable_digest
428
+ !== sha256(context.payloads.get('identity/lattice-sensor-executable'))
429
+ || (projectConfigBound && (
430
+ identity.sensor_identity.project_config_ref !== SENSOR_CONFIG_PATH
431
+ || !SHA256.test(identity.sensor_identity.project_config_digest)
432
+ || identity.sensor_identity.project_config_digest
433
+ !== sha256(context.payloads.get(SENSOR_CONFIG_PATH))
434
+ ))
435
+ || identity.sensor_identity_digest !== digestArtifact(identity.sensor_identity)) {
436
+ return false;
437
+ }
438
+ const expectedSourceRefs = V1_IDENTITY_PATHS
439
+ .filter((relativePath) => relativePath !== 'identity/lattice-sensor-executable');
440
+ const actualRefs = identity.sources.map(({ artifact_ref: ref }) => ref).sort();
441
+ if (!sameArtifact(actualRefs, expectedSourceRefs)) return false;
442
+ for (const source of identity.sources) {
443
+ if (!exactRecord(source, ['runtime_path', 'artifact_ref', 'digest'])
444
+ || typeof source.runtime_path !== 'string'
445
+ || !expectedSourceRefs.includes(source.artifact_ref)
446
+ || source.digest !== sha256(context.payloads.get(source.artifact_ref))) {
447
+ return false;
448
+ }
449
+ }
450
+ const snapshot = {
451
+ sources: identity.sources.map(({ runtime_path: runtimePath, artifact_ref: artifactRef, digest }) => ({
452
+ runtime_path: runtimePath,
453
+ artifact_ref: artifactRef,
454
+ digest,
455
+ })),
456
+ sensor_identity: identity.sensor_identity,
457
+ };
458
+ const digest = digestArtifact(snapshot);
459
+ return identity.before_digest === digest && identity.after_digest === digest;
460
+ }
461
+
462
+ function verifyLatticeSensorConfig(context) {
463
+ if (context.artifactVersion === 'v1') return false;
464
+ const bytes = context.payloads.get(SENSOR_CONFIG_PATH);
465
+ const identity = context.json.get('identity.json');
466
+ return Buffer.isBuffer(bytes)
467
+ && SENSOR_CONFIG_EPOCHS.some((epochBytes) => bytes.equals(epochBytes))
468
+ && identity?.sensor_identity?.project_config_ref === SENSOR_CONFIG_PATH
469
+ && identity.sensor_identity.project_config_digest === sha256(bytes);
470
+ }
471
+
472
+ function verifySurfaceSnapshot(snapshot, expectedPaths, expectedPresentPaths) {
473
+ if (!exactRecord(snapshot, ['schema', 'files', 'digest'])
474
+ || snapshot.schema !== 'lattice.rc2.delivery_policy_surface_snapshot.v1'
475
+ || !Array.isArray(snapshot.files)
476
+ || !isDeepStrictEqual(snapshot.files.map(({ path: relativePath }) => relativePath), expectedPaths)
477
+ || snapshot.files.some((file) => (
478
+ !exactRecord(file, ['path', 'state', 'content_digest'])
479
+ || (expectedPresentPaths.has(file.path)
480
+ ? file.state !== 'present' || !SHA256.test(file.content_digest)
481
+ : file.state !== 'absent' || file.content_digest !== null)
482
+ ))) {
483
+ return false;
484
+ }
485
+ return snapshot.digest === digestArtifact({ schema: snapshot.schema, files: snapshot.files });
486
+ }
487
+
488
+ function expectedMutationContract(candidate) {
489
+ if (!plainRecord(candidate)
490
+ || candidate.schema !== 'lattice.rc2.boundary_candidate_spec.v1'
491
+ || typeof candidate.candidate_id !== 'string'
492
+ || !plainRecord(candidate.fixed_oracle)
493
+ || candidate.fixed_oracle.path !== RC2_ORACLE_PATH
494
+ || !SHA256.test(candidate.fixed_oracle.source_digest)
495
+ || !Array.isArray(candidate.fixed_oracle.case_ids)
496
+ || !Array.isArray(candidate.todos)
497
+ || candidate.todos.length !== 3
498
+ || !Array.isArray(candidate.stable_surfaces)) {
499
+ return null;
500
+ }
501
+ const compositionSurfaces = candidate.stable_surfaces.filter(({ role }) => (
502
+ role === 'composition-test'
503
+ ));
504
+ if (compositionSurfaces.length !== 1) return null;
505
+ const composition = compositionSurfaces[0];
506
+ if (typeof composition.target !== 'string' || typeof composition.path !== 'string') return null;
507
+
508
+ const contracts = [];
509
+ const rows = [];
510
+ const surfacePaths = new Set([candidate.fixed_oracle.path]);
511
+ const controlPaths = new Set([candidate.fixed_oracle.path]);
512
+ for (const todo of candidate.todos) {
513
+ if (!plainRecord(todo)
514
+ || typeof todo.todo_id !== 'string'
515
+ || !Array.isArray(todo.case_ids)
516
+ || todo.case_ids.length !== 2
517
+ || !plainRecord(todo.current)
518
+ || !plainRecord(todo.proposed)
519
+ || !plainRecord(todo.current.production)
520
+ || !plainRecord(todo.proposed.production)
521
+ || !Array.isArray(todo.current.tests)
522
+ || !Array.isArray(todo.proposed.tests)
523
+ || todo.proposed.tests.length !== 1) {
524
+ return null;
525
+ }
526
+ const production = todo.proposed.production;
527
+ const test = todo.proposed.tests[0];
528
+ if (typeof production.symbol !== 'string'
529
+ || typeof production.path !== 'string'
530
+ || typeof test.symbol !== 'string'
531
+ || typeof test.path !== 'string'
532
+ || todo.case_ids.some((caseId) => typeof caseId !== 'string')) {
533
+ return null;
534
+ }
535
+ contracts.push({ testId: test.symbol, path: test.path });
536
+ rows.push(...todo.case_ids.map((caseId) => ({
537
+ caseId,
538
+ todoId: todo.todo_id,
539
+ resolver: production.symbol,
540
+ productionPath: production.path,
541
+ ownerTestId: test.symbol,
542
+ })));
543
+ for (const mode of [todo.current, todo.proposed]) {
544
+ if (typeof mode.production?.path !== 'string'
545
+ || mode.tests.some(({ path: testPath }) => typeof testPath !== 'string')) {
546
+ return null;
547
+ }
548
+ surfacePaths.add(mode.production.path);
549
+ mode.tests.forEach(({ path: testPath }) => surfacePaths.add(testPath));
550
+ }
551
+ controlPaths.add(todo.current.production.path);
552
+ todo.current.tests.forEach(({ path: testPath }) => controlPaths.add(testPath));
553
+ }
554
+ contracts.push({ testId: composition.target, path: composition.path });
555
+ if (new Set(contracts.map(({ testId }) => testId)).size !== contracts.length
556
+ || new Set(contracts.map(({ path: testPath }) => testPath)).size !== contracts.length
557
+ || !isDeepStrictEqual(rows.map(({ caseId }) => caseId), candidate.fixed_oracle.case_ids)
558
+ || new Set(candidate.fixed_oracle.case_ids).size !== candidate.fixed_oracle.case_ids.length) {
559
+ return null;
560
+ }
561
+ return {
562
+ contracts,
563
+ rows,
564
+ surfacePaths: [...surfacePaths].sort(),
565
+ controlPaths,
566
+ };
567
+ }
568
+
569
+ function verifyMutationEvidence(mutation, expected, outputDigest, candidateDigest, caseSetDigest) {
570
+ if (!exactRecord(mutation, [
571
+ 'schema',
572
+ 'candidate_digest',
573
+ 'case_set_digest',
574
+ 'rows',
575
+ 'matrix_digest',
576
+ 'evidence_digest',
577
+ ])
578
+ || mutation.schema !== 'lattice.rc2.delivery_policy_mutation_evidence.v1'
579
+ || mutation.candidate_digest !== candidateDigest
580
+ || mutation.case_set_digest !== caseSetDigest
581
+ || !Array.isArray(mutation.rows)
582
+ || mutation.rows.length !== expected.rows.length) {
583
+ return false;
584
+ }
585
+ for (let rowIndex = 0; rowIndex < expected.rows.length; rowIndex += 1) {
586
+ const row = mutation.rows[rowIndex];
587
+ const expectedRow = expected.rows[rowIndex];
588
+ if (!exactRecord(row, [
589
+ 'case_id',
590
+ 'owner_todo_id',
591
+ 'resolver_symbol',
592
+ 'mutated_path',
593
+ 'oracle_mismatch_id',
594
+ 'cells',
595
+ 'restore_digest',
596
+ ])
597
+ || row.case_id !== expectedRow.caseId
598
+ || row.owner_todo_id !== expectedRow.todoId
599
+ || row.resolver_symbol !== expectedRow.resolver
600
+ || row.mutated_path !== expectedRow.productionPath
601
+ || row.oracle_mismatch_id !== expectedRow.caseId
602
+ || row.restore_digest !== outputDigest
603
+ || !Array.isArray(row.cells)
604
+ || row.cells.length !== expected.contracts.length) {
605
+ return false;
606
+ }
607
+ for (let cellIndex = 0; cellIndex < expected.contracts.length; cellIndex += 1) {
608
+ const cell = row.cells[cellIndex];
609
+ const contract = expected.contracts[cellIndex];
610
+ const owner = contract.testId === expectedRow.ownerTestId;
611
+ if (!exactRecord(cell, [
612
+ 'test_id', 'path', 'outcome', 'exit_code', 'stdout_digest', 'stderr_digest',
613
+ ])
614
+ || cell.test_id !== contract.testId
615
+ || cell.path !== contract.path
616
+ || !Number.isSafeInteger(cell.exit_code)
617
+ || cell.exit_code < 0
618
+ || !SHA256.test(cell.stdout_digest)
619
+ || !SHA256.test(cell.stderr_digest)
620
+ || (owner
621
+ ? cell.outcome !== 'failed' || cell.exit_code === 0
622
+ : cell.outcome !== 'passed' || cell.exit_code !== 0)) {
623
+ return false;
624
+ }
625
+ }
626
+ }
627
+ const mutationBase = stripDigest(mutation, 'evidence_digest');
628
+ return mutation.matrix_digest === digestArtifact({ rows: mutation.rows })
629
+ && mutationBase !== null
630
+ && mutation.evidence_digest === digestArtifact(mutationBase);
631
+ }
632
+
633
+ function verifyTransformSemantics(context, accepted, behavior, mutation) {
634
+ try {
635
+ const candidate = context.json.get(PRIMARY_INPUT_PATHS.candidateSpec);
636
+ const expected = expectedMutationContract(candidate);
637
+ const oracleReceipt = expectedRc2DeliveryPolicyOracleReceipt();
638
+ const candidateDigest = digestArtifact(candidate);
639
+ const oracleIdentityBytes = context.payloads.get(RC2_ORACLE_IDENTITY_REF);
640
+ const transformIdentityBytes = context.payloads.get(RC2_TRANSFORM_IDENTITY_REF);
641
+ if (expected === null
642
+ || !Buffer.isBuffer(oracleIdentityBytes)
643
+ || !Buffer.isBuffer(transformIdentityBytes)
644
+ || !exactRecord(behavior, [
645
+ 'schema',
646
+ 'candidate_digest',
647
+ 'adapter_source_digest',
648
+ 'control_snapshot',
649
+ 'output_snapshot',
650
+ 'fixed_oracle',
651
+ 'pre_oracle',
652
+ 'post_oracle',
653
+ 'case_set_digest',
654
+ 'equivalent',
655
+ 'evidence_digest',
656
+ ])
657
+ || behavior.schema !== 'lattice.rc2.delivery_policy_behavior_evidence.v1'
658
+ || !exactRecord(behavior.fixed_oracle, ['path', 'source_base64', 'source_digest'])
659
+ || behavior.fixed_oracle.path !== RC2_ORACLE_PATH
660
+ || typeof behavior.fixed_oracle.source_base64 !== 'string') {
661
+ return false;
662
+ }
663
+ const oracleBytes = Buffer.from(behavior.fixed_oracle.source_base64, 'base64');
664
+ if (oracleBytes.toString('base64') !== behavior.fixed_oracle.source_base64
665
+ || !oracleBytes.equals(oracleIdentityBytes)
666
+ || sha256(oracleBytes) !== behavior.fixed_oracle.source_digest
667
+ || behavior.fixed_oracle.source_digest !== candidate.fixed_oracle.source_digest
668
+ || behavior.fixed_oracle.source_digest !== accepted?.source?.fixed_oracle?.source_digest
669
+ || accepted.source.fixed_oracle.path !== RC2_ORACLE_PATH
670
+ || candidateDigest !== context.witness.candidateDigest
671
+ || behavior.fixed_oracle.source_digest !== context.witness.oracleSourceDigest
672
+ || behavior.candidate_digest !== candidateDigest
673
+ || mutation?.candidate_digest !== candidateDigest
674
+ || accepted?.candidate?.candidate_id !== candidate.candidate_id
675
+ || accepted.candidate.digest !== candidateDigest
676
+ || behavior.adapter_source_digest !== sha256(transformIdentityBytes)
677
+ || accepted?.source?.adapter?.path !== RC2_TRANSFORM_PATH
678
+ || accepted.source.adapter.digest !== behavior.adapter_source_digest
679
+ || !isDeepStrictEqual(behavior.pre_oracle, oracleReceipt)
680
+ || !isDeepStrictEqual(behavior.post_oracle, oracleReceipt)) {
681
+ return false;
682
+ }
683
+ const expectedCaseSetDigest = digestArtifact({
684
+ case_results: oracleReceipt.case_results.map(({ id, output_digest: outputDigest }) => ({
685
+ id,
686
+ output_digest: outputDigest,
687
+ })),
688
+ });
689
+ const outputPaths = new Set(expected.surfacePaths);
690
+ if (behavior.case_set_digest !== expectedCaseSetDigest
691
+ || mutation.case_set_digest !== expectedCaseSetDigest
692
+ || accepted.behavior?.case_set_digest !== expectedCaseSetDigest
693
+ || accepted.behavior?.pre_oracle_digest !== digestArtifact(oracleReceipt)
694
+ || accepted.behavior?.post_oracle_digest !== digestArtifact(oracleReceipt)
695
+ || accepted.behavior?.equivalent !== true
696
+ || behavior.equivalent !== true
697
+ || !verifySurfaceSnapshot(behavior.control_snapshot, expected.surfacePaths, expected.controlPaths)
698
+ || !verifySurfaceSnapshot(behavior.output_snapshot, expected.surfacePaths, outputPaths)
699
+ || !isDeepStrictEqual(accepted.output?.files, behavior.output_snapshot.files)
700
+ || accepted.output.snapshot_digest !== behavior.output_snapshot.digest
701
+ || accepted.source.control_snapshot_digest !== behavior.control_snapshot.digest
702
+ || behavior.control_snapshot.files.find(({ path: relativePath }) => (
703
+ relativePath === RC2_ORACLE_PATH
704
+ ))?.content_digest !== behavior.fixed_oracle.source_digest
705
+ || behavior.output_snapshot.files.find(({ path: relativePath }) => (
706
+ relativePath === RC2_ORACLE_PATH
707
+ ))?.content_digest !== behavior.fixed_oracle.source_digest) {
708
+ return false;
709
+ }
710
+ const behaviorBase = stripDigest(behavior, 'evidence_digest');
711
+ if (behaviorBase === null
712
+ || behavior.evidence_digest !== digestArtifact(behaviorBase)
713
+ || accepted.behavior.evidence_digest !== behavior.evidence_digest
714
+ || !verifyMutationEvidence(
715
+ mutation,
716
+ expected,
717
+ behavior.output_snapshot.digest,
718
+ candidateDigest,
719
+ expectedCaseSetDigest,
720
+ )) {
721
+ return false;
722
+ }
723
+ return accepted.mutation?.evidence_digest === mutation.evidence_digest
724
+ && accepted.mutation.matrix_digest === mutation.matrix_digest
725
+ && accepted.mutation.row_count === expected.rows.length
726
+ && accepted.mutation.cell_count === expected.rows.length * expected.contracts.length;
727
+ } catch {
728
+ return false;
729
+ }
730
+ }
731
+
732
+ function verifyTransform(context) {
733
+ const accepted = context.json.get('transform/accepted-artifact.json');
734
+ const acceptedReceipt = context.json.get('transform/accepted-receipt.json');
735
+ const behavior = context.json.get('transform/behavior-evidence.json');
736
+ const mutation = context.json.get('transform/mutation-evidence.json');
737
+ const incomplete = context.json.get('transform/rejected-incomplete-artifact.json');
738
+ const incompleteReceipt = context.json.get('transform/rejected-incomplete-receipt.json');
739
+ const scope = context.json.get('transform/rejected-scope-artifact.json');
740
+ const scopeReceipt = context.json.get('transform/rejected-scope-receipt.json');
741
+ const patch = context.payloads.get('transform/seam.patch');
742
+ const behaviorBase = stripDigest(behavior, 'evidence_digest');
743
+ const mutationBase = stripDigest(mutation, 'evidence_digest');
744
+ const acceptedReceiptBase = stripDigest(acceptedReceipt, 'receipt_digest');
745
+ const incompleteReceiptBase = stripDigest(incompleteReceipt, 'receipt_digest');
746
+ const scopeReceiptBase = stripDigest(scopeReceipt, 'receipt_digest');
747
+ return accepted?.schema === 'lattice.rc2.delivery_policy_transform_artifact.v1'
748
+ && accepted.status === 'accepted'
749
+ && exactRecord(accepted.candidate, ['candidate_id', 'digest'])
750
+ && accepted.candidate.digest === context.witness.candidateDigest
751
+ && exactRecord(accepted.source, [
752
+ 'adapter',
753
+ 'base_sha',
754
+ 'control_snapshot_digest',
755
+ 'fixed_oracle',
756
+ ])
757
+ && exactRecord(accepted.source.adapter, ['path', 'digest'])
758
+ && exactRecord(accepted.source.fixed_oracle, ['path', 'source_digest'])
759
+ && accepted.source.base_sha === context.manifest.base_sha
760
+ && accepted.source.fixed_oracle.source_digest === context.witness.oracleSourceDigest
761
+ && accepted.patch?.digest === sha256(patch)
762
+ && accepted.patch?.bytes === patch.byteLength
763
+ && accepted.output?.snapshot_digest === behavior?.output_snapshot?.digest
764
+ && accepted.source?.control_snapshot_digest === behavior?.control_snapshot?.digest
765
+ && accepted.source?.fixed_oracle?.source_digest === behavior?.fixed_oracle?.source_digest
766
+ && accepted.behavior?.evidence_digest === behavior?.evidence_digest
767
+ && behaviorBase !== null
768
+ && behavior.evidence_digest === digestArtifact(behaviorBase)
769
+ && accepted.mutation?.evidence_digest === mutation?.evidence_digest
770
+ && mutationBase !== null
771
+ && mutation.evidence_digest === digestArtifact(mutationBase)
772
+ && acceptedReceipt?.status === 'accepted'
773
+ && acceptedReceipt.transform_artifact_digest === digestArtifact(accepted)
774
+ && acceptedReceipt.behavior_evidence_digest === behavior.evidence_digest
775
+ && acceptedReceipt.mutation_evidence_digest === mutation.evidence_digest
776
+ && acceptedReceiptBase !== null
777
+ && acceptedReceipt.receipt_digest === digestArtifact(acceptedReceiptBase)
778
+ && incomplete?.status === 'rejected'
779
+ && incomplete?.rejection?.kind === 'incomplete_transform'
780
+ && incomplete.output === null
781
+ && sameArtifact(incomplete.candidate, accepted.candidate)
782
+ && sameArtifact(incomplete.source, accepted.source)
783
+ && incompleteReceipt?.status === 'rejected'
784
+ && incompleteReceipt.transform_artifact_digest === digestArtifact(incomplete)
785
+ && incompleteReceiptBase !== null
786
+ && incompleteReceipt.receipt_digest === digestArtifact(incompleteReceiptBase)
787
+ && scope?.status === 'rejected'
788
+ && scope?.rejection?.kind === 'scope_violation'
789
+ && scope.output === null
790
+ && sameArtifact(scope.candidate, accepted.candidate)
791
+ && sameArtifact(scope.source, accepted.source)
792
+ && scopeReceipt?.status === 'rejected'
793
+ && scopeReceipt.transform_artifact_digest === digestArtifact(scope)
794
+ && scopeReceiptBase !== null
795
+ && scopeReceipt.receipt_digest === digestArtifact(scopeReceiptBase)
796
+ && verifyTransformSemantics(context, accepted, behavior, mutation);
797
+ }
798
+
799
+ function decodeRawEvidence(evidence) {
800
+ try {
801
+ return JSON.parse(Buffer.from(evidence.raw.payload_base64, 'base64').toString('utf8'));
802
+ } catch {
803
+ return null;
804
+ }
805
+ }
806
+
807
+ function rehydrateStoredEvidence(evidence) {
808
+ if (!plainRecord(evidence)) return null;
809
+ const raw = evidence.raw;
810
+ if (!exactRecord(raw, [
811
+ 'schema',
812
+ 'source_schema',
813
+ 'media_type',
814
+ 'source_encoding',
815
+ 'storage_encoding',
816
+ 'canonical_bytes',
817
+ 'payload_digest',
818
+ 'payload_base64_chunks',
819
+ ])
820
+ || raw.schema !== 'lattice.rc2.chunked_sensor_raw_receipt.v1'
821
+ || raw.source_schema !== 'lattice.sensor_raw_opaque_receipt.v1'
822
+ || raw.source_encoding !== 'canonical-json-base64'
823
+ || raw.storage_encoding !== 'ordered-base64-chunks'
824
+ || !Number.isSafeInteger(raw.canonical_bytes)
825
+ || raw.canonical_bytes < 0
826
+ || !SHA256.test(raw.payload_digest)
827
+ || !Array.isArray(raw.payload_base64_chunks)
828
+ || raw.payload_base64_chunks.length === 0
829
+ || raw.payload_base64_chunks.some((chunk) => (
830
+ typeof chunk !== 'string'
831
+ || chunk.length === 0
832
+ || Buffer.byteLength(chunk, 'utf8') > RAW_EVIDENCE_CHUNK_BYTES
833
+ ))
834
+ || raw.payload_base64_chunks.slice(0, -1).some((chunk) => (
835
+ Buffer.byteLength(chunk, 'utf8') !== RAW_EVIDENCE_CHUNK_BYTES
836
+ ))) {
837
+ return null;
838
+ }
839
+ const payloadBase64 = raw.payload_base64_chunks.join('');
840
+ const payload = Buffer.from(payloadBase64, 'base64');
841
+ if (payload.toString('base64') !== payloadBase64
842
+ || payload.byteLength !== raw.canonical_bytes
843
+ || sha256(payload) !== raw.payload_digest) {
844
+ return null;
845
+ }
846
+ const restored = {
847
+ ...structuredClone(evidence),
848
+ raw: {
849
+ schema: raw.source_schema,
850
+ media_type: raw.media_type,
851
+ encoding: raw.source_encoding,
852
+ canonical_bytes: raw.canonical_bytes,
853
+ payload_digest: raw.payload_digest,
854
+ payload_base64: payloadBase64,
855
+ },
856
+ };
857
+ return validateRc1EvidenceBundle(restored) ? restored : null;
858
+ }
859
+
860
+ function rehydrateStoredRun(run) {
861
+ if (!plainRecord(run)) return null;
862
+ const evidence = rehydrateStoredEvidence(run.evidence);
863
+ if (evidence === null) return null;
864
+ return { ...structuredClone(run), evidence };
865
+ }
866
+
867
+ function runMap(context) {
868
+ return new Map(RUN_IDS.map((runId) => [
869
+ runId,
870
+ rehydrateStoredRun(context.json.get(`evidence/${runId}.json`)),
871
+ ]));
872
+ }
873
+
874
+ function expectedRunFamily(runId) {
875
+ return runId.startsWith('primary-') ? 'primary' : 'rc1_transfer';
876
+ }
877
+
878
+ function expectedRunCondition(runId) {
879
+ return runId.includes('-treatment-') ? 'treatment' : 'control';
880
+ }
881
+
882
+ function verifyRuns(context) {
883
+ const runs = runMap(context);
884
+ const primaryInputs = objectFromPaths(context, PRIMARY_INPUT_PATHS);
885
+ const rc1Inputs = objectFromPaths(context, RC1_INPUT_PATHS);
886
+ const identity = context.json.get('identity.json');
887
+ const accepted = context.json.get('transform/accepted-artifact.json');
888
+ const rc1Transform = context.json.get('predecessors/rc1-v6-transform-artifact.json');
889
+ const isolationDigests = new Set();
890
+ for (const [runId, run] of runs) {
891
+ const family = expectedRunFamily(runId);
892
+ const condition = expectedRunCondition(runId);
893
+ const inputs = family === 'primary' ? primaryInputs : rc1Inputs;
894
+ const expectedPatch = condition === 'control'
895
+ ? null
896
+ : (family === 'primary' ? accepted?.patch?.digest : rc1Transform?.patch?.digest);
897
+ if (!plainRecord(run)
898
+ || run.schema !== 'lattice.rc2.fresh_sensor_run.v1'
899
+ || run.run_id !== runId
900
+ || run.family !== family
901
+ || run.condition !== condition
902
+ || run.fresh_index !== true
903
+ || !SHA256.test(run.isolation_instance_digest)
904
+ || isolationDigests.has(run.isolation_instance_digest)
905
+ || !validateRc1EvidenceBundle(run.evidence)
906
+ || run.evidence.run_id !== runId
907
+ || run.evidence.condition !== condition
908
+ || run.evidence.query_set_digest !== digestArtifact(inputs.querySet)
909
+ || run.measurement?.schema !== 'lattice.rc2.sensor_measurement.v1'
910
+ || run.measurement.base_sha !== context.manifest.base_sha
911
+ || run.measurement.patch_digest !== expectedPatch
912
+ || run.measurement.snapshot_digest !== digestArtifact(run.measurement.snapshot)
913
+ || run.measurement.sensor_identity_digest !== identity.sensor_identity_digest
914
+ || !sameArtifact(run.measurement.sensor_identity, identity.sensor_identity)
915
+ || run.measurement.query_set_digest !== digestArtifact(inputs.querySet)
916
+ || run.measurement.raw_evidence_digest !== run.evidence.raw.payload_digest
917
+ || run.source_invariant?.outcome !== 'passed'
918
+ || run.cleanup?.outcome !== 'passed'
919
+ || run.oracle_receipt?.outcome !== 'passed'
920
+ || run.cost?.index?.state !== 'measured'
921
+ || run.cost?.query?.state !== 'measured'
922
+ || run.cost?.oracle?.state !== 'measured') {
923
+ return false;
924
+ }
925
+ isolationDigests.add(run.isolation_instance_digest);
926
+ }
927
+ return isolationDigests.size === RUN_IDS.length;
928
+ }
929
+
930
+ function verdictFor(bundle, compiled) {
931
+ return {
932
+ schema_version: 'lattice.boundary_verdict.v2',
933
+ normalized_graph_digest: bundle.graph_digest,
934
+ verdicts: compiled.pairwise_verdicts,
935
+ };
936
+ }
937
+
938
+ function compiledRecord({ condition, runId, bundle, compiled }) {
939
+ if (compiled.outcome !== 'compiled') throw new TypeError(`${condition} did not compile`);
940
+ const verdict = verdictFor(bundle, compiled);
941
+ const verification = verifySchedulabilityPlanV2(bundle.graph, compiled.plan);
942
+ const stable = { bundle, verdict, plan: compiled.plan, verification };
943
+ return {
944
+ schema: 'lattice.rc2.compiled_condition.v1',
945
+ condition,
946
+ run_id: runId,
947
+ outcome: 'compiled',
948
+ ...stable,
949
+ artifact_digest: digestArtifact(stable),
950
+ };
951
+ }
952
+
953
+ function compilePrimaryRecord({ run, inputs, manualEvidence, planInput, condition }) {
954
+ const bundle = compileDeliveryPolicyBoundaryBundleV2({
955
+ planInput,
956
+ candidateSpec: inputs.candidateSpec,
957
+ manualEvidence,
958
+ querySet: inputs.querySet,
959
+ sourceSnapshot: run.measurement.snapshot,
960
+ sensorEvidence: run.evidence.portable,
961
+ });
962
+ return compiledRecord({
963
+ condition,
964
+ runId: run.run_id,
965
+ bundle,
966
+ compiled: compileSchedulabilityGraphV2(bundle.graph),
967
+ });
968
+ }
969
+
970
+ function compileUnknownRecord({ run, inputs }) {
971
+ const bundle = compileDeliveryPolicyBoundaryBundleV2({
972
+ planInput: inputs.planInput,
973
+ candidateSpec: inputs.candidateSpec,
974
+ manualEvidence: inputs.unknownManualEvidence,
975
+ querySet: inputs.querySet,
976
+ sourceSnapshot: run.measurement.snapshot,
977
+ sensorEvidence: run.evidence.portable,
978
+ });
979
+ const outcome = compileSchedulabilityGraphV2(bundle.graph);
980
+ const verification = verifySchedulabilityPlanV2(bundle.graph, {
981
+ schema_version: 'lattice.plan_graph.v2',
982
+ waves: [],
983
+ minimum_feasible_waves: 0,
984
+ });
985
+ return {
986
+ schema: 'lattice.rc2.non_dispatchable_condition.v1',
987
+ condition: 'primary-treatment-third-only-unknown',
988
+ run_id: run.run_id,
989
+ bundle,
990
+ outcome,
991
+ verification,
992
+ };
993
+ }
994
+
995
+ function recompileLegacy(run, inputs, manualEvidence, label) {
996
+ const rawEvidence = decodeRawEvidence(run.evidence);
997
+ if (rawEvidence === null) throw new TypeError('RC1 raw evidence is not decodable');
998
+ return compileBoundaryCondition({
999
+ planInput: inputs.planInput,
1000
+ candidateSpec: inputs.candidateSpec,
1001
+ manualEvidence,
1002
+ querySet: inputs.querySet,
1003
+ sensorEvidence: rawEvidence,
1004
+ codeSnapshotDigest: run.measurement.snapshot_digest,
1005
+ planVersion: `rc2-${run.condition}-transfer-${label}`,
1006
+ });
1007
+ }
1008
+
1009
+ function compileTransferRecord({ run, inputs, manualEvidence, label }) {
1010
+ const legacy = recompileLegacy(run, inputs, manualEvidence, label);
1011
+ if (!sameArtifact(legacy.boundary_manifest, run.legacy_boundary_manifests?.[label])) {
1012
+ throw new TypeError(`RC1 ${run.condition} ${label} fresh manifest mismatch`);
1013
+ }
1014
+ const transferred = compileRc1TransferBundleV2({
1015
+ planInput: inputs.planInput,
1016
+ candidateSpec: inputs.candidateSpec,
1017
+ manualEvidence,
1018
+ querySet: inputs.querySet,
1019
+ boundaryManifest: legacy.boundary_manifest,
1020
+ });
1021
+ const verification = verifySchedulabilityPlanV2(transferred.bundle.graph, transferred.plan);
1022
+ const stable = {
1023
+ bundle: transferred.bundle,
1024
+ verdict: transferred.verdict,
1025
+ plan: transferred.plan,
1026
+ verification,
1027
+ };
1028
+ return {
1029
+ schema: 'lattice.rc2.compiled_condition.v1',
1030
+ condition: `rc1-transfer-${run.condition}-${label}`,
1031
+ run_id: run.run_id,
1032
+ outcome: 'compiled',
1033
+ ...stable,
1034
+ artifact_digest: digestArtifact(stable),
1035
+ };
1036
+ }
1037
+
1038
+ function recomputeConditions(context) {
1039
+ const runs = runMap(context);
1040
+ const primaryInputs = objectFromPaths(context, PRIMARY_INPUT_PATHS);
1041
+ const rc1Inputs = objectFromPaths(context, RC1_INPUT_PATHS);
1042
+ const control = [1, 2].map((index) => compilePrimaryRecord({
1043
+ run: runs.get(`primary-control-${index}`),
1044
+ inputs: primaryInputs,
1045
+ manualEvidence: primaryInputs.normalManualEvidence,
1046
+ planInput: primaryInputs.planInput,
1047
+ condition: 'primary-control-normal',
1048
+ }));
1049
+ const treatment = [1, 2].map((index) => compilePrimaryRecord({
1050
+ run: runs.get(`primary-treatment-${index}`),
1051
+ inputs: primaryInputs,
1052
+ manualEvidence: primaryInputs.normalManualEvidence,
1053
+ planInput: primaryInputs.planInput,
1054
+ condition: 'primary-treatment-normal',
1055
+ }));
1056
+ const treatmentRun = runs.get('primary-treatment-1');
1057
+ const capacityPlan = structuredClone(primaryInputs.planInput);
1058
+ capacityPlan.capacity.writers = 2;
1059
+ const partialState = compilePrimaryRecord({
1060
+ run: treatmentRun,
1061
+ inputs: primaryInputs,
1062
+ manualEvidence: primaryInputs.partialManualEvidence,
1063
+ planInput: primaryInputs.planInput,
1064
+ condition: 'primary-treatment-partial-state',
1065
+ });
1066
+ const capacity2 = compilePrimaryRecord({
1067
+ run: treatmentRun,
1068
+ inputs: primaryInputs,
1069
+ manualEvidence: primaryInputs.normalManualEvidence,
1070
+ planInput: capacityPlan,
1071
+ condition: 'primary-treatment-capacity-2',
1072
+ });
1073
+ const unknown = compileUnknownRecord({ run: treatmentRun, inputs: primaryInputs });
1074
+ const transferControlRun = runs.get('rc1-transfer-control-1');
1075
+ const transferTreatmentRun = runs.get('rc1-transfer-treatment-1');
1076
+ const transfer = {
1077
+ control: {
1078
+ normal: compileTransferRecord({
1079
+ run: transferControlRun,
1080
+ inputs: rc1Inputs,
1081
+ manualEvidence: rc1Inputs.normalManualEvidence,
1082
+ label: 'normal',
1083
+ }),
1084
+ negative: compileTransferRecord({
1085
+ run: transferControlRun,
1086
+ inputs: rc1Inputs,
1087
+ manualEvidence: rc1Inputs.negativeManualEvidence,
1088
+ label: 'negative',
1089
+ }),
1090
+ },
1091
+ treatment: {
1092
+ normal: compileTransferRecord({
1093
+ run: transferTreatmentRun,
1094
+ inputs: rc1Inputs,
1095
+ manualEvidence: rc1Inputs.normalManualEvidence,
1096
+ label: 'normal',
1097
+ }),
1098
+ negative: compileTransferRecord({
1099
+ run: transferTreatmentRun,
1100
+ inputs: rc1Inputs,
1101
+ manualEvidence: rc1Inputs.negativeManualEvidence,
1102
+ label: 'negative',
1103
+ }),
1104
+ },
1105
+ };
1106
+ return {
1107
+ primary: { control, treatment, partial_state: partialState, capacity_2: capacity2,
1108
+ third_only_unknown: unknown },
1109
+ rc1_transfer: transfer,
1110
+ };
1111
+ }
1112
+
1113
+ const COMPILED_RECORD_PATHS = Object.freeze({
1114
+ 'compiled/primary-control-1-normal.json': ['primary', 'control', 0],
1115
+ 'compiled/primary-control-2-normal.json': ['primary', 'control', 1],
1116
+ 'compiled/primary-treatment-1-normal.json': ['primary', 'treatment', 0],
1117
+ 'compiled/primary-treatment-2-normal.json': ['primary', 'treatment', 1],
1118
+ 'compiled/primary-treatment-partial-state.json': ['primary', 'partial_state'],
1119
+ 'compiled/primary-treatment-capacity-2.json': ['primary', 'capacity_2'],
1120
+ 'compiled/primary-treatment-third-only-unknown.json': ['primary', 'third_only_unknown'],
1121
+ 'compiled/rc1-transfer-control-normal.json': ['rc1_transfer', 'control', 'normal'],
1122
+ 'compiled/rc1-transfer-control-negative.json': ['rc1_transfer', 'control', 'negative'],
1123
+ 'compiled/rc1-transfer-treatment-normal.json': ['rc1_transfer', 'treatment', 'normal'],
1124
+ 'compiled/rc1-transfer-treatment-negative.json': ['rc1_transfer', 'treatment', 'negative'],
1125
+ });
1126
+
1127
+ function nestedValue(value, keys) {
1128
+ return keys.reduce((current, key) => current?.[key], value);
1129
+ }
1130
+
1131
+ function verifyCompiledConditions(context, recomputed) {
1132
+ return Object.entries(COMPILED_RECORD_PATHS).every(([relativePath, keys]) => (
1133
+ sameArtifact(context.json.get(relativePath), nestedValue(recomputed, keys))
1134
+ ));
1135
+ }
1136
+
1137
+ function distinctConflictPairs(record) {
1138
+ return new Set(record.bundle.graph.conflicts.map(({ todo_ids: todoIds }) => (
1139
+ [...todoIds].sort().join('\u0000')
1140
+ ))).size;
1141
+ }
1142
+
1143
+ function conditionMetrics(record) {
1144
+ return {
1145
+ conflict_records: record.bundle.graph.conflicts.length,
1146
+ distinct_conflict_pairs: distinctConflictPairs(record),
1147
+ minimum_feasible_waves: record.plan.minimum_feasible_waves,
1148
+ };
1149
+ }
1150
+
1151
+ function expectedComparison(context, recomputed) {
1152
+ const identity = context.json.get('identity.json');
1153
+ const transform = context.json.get('transform/accepted-artifact.json');
1154
+ const newPlan = context.json.get('new-plan-version.json');
1155
+ const planDiff = context.json.get('plan-diff.json');
1156
+ return {
1157
+ schema: 'lattice.rc2.control_treatment_comparison.v1',
1158
+ base_sha: context.manifest.base_sha,
1159
+ identity_digest: digestArtifact(identity),
1160
+ independent_variable: {
1161
+ kind: 'accepted_registry_shard_patch',
1162
+ transform_artifact_digest: digestArtifact(transform),
1163
+ patch_digest: transform.patch.digest,
1164
+ },
1165
+ condition_artifact_digests: {
1166
+ primary_control: recomputed.primary.control.map(({ artifact_digest: digest }) => digest),
1167
+ primary_treatment: recomputed.primary.treatment.map(({ artifact_digest: digest }) => digest),
1168
+ primary_partial_state: recomputed.primary.partial_state.artifact_digest,
1169
+ primary_capacity_2: recomputed.primary.capacity_2.artifact_digest,
1170
+ primary_unknown: digestArtifact(recomputed.primary.third_only_unknown),
1171
+ rc1_transfer_control_normal: recomputed.rc1_transfer.control.normal.artifact_digest,
1172
+ rc1_transfer_control_negative: recomputed.rc1_transfer.control.negative.artifact_digest,
1173
+ rc1_transfer_treatment_normal: recomputed.rc1_transfer.treatment.normal.artifact_digest,
1174
+ rc1_transfer_treatment_negative: recomputed.rc1_transfer.treatment.negative.artifact_digest,
1175
+ },
1176
+ metrics: {
1177
+ primary_control: conditionMetrics(recomputed.primary.control[0]),
1178
+ primary_treatment: conditionMetrics(recomputed.primary.treatment[0]),
1179
+ primary_partial_state: conditionMetrics(recomputed.primary.partial_state),
1180
+ primary_capacity_2: conditionMetrics(recomputed.primary.capacity_2),
1181
+ rc1_transfer_control_normal: conditionMetrics(recomputed.rc1_transfer.control.normal),
1182
+ rc1_transfer_control_negative: conditionMetrics(recomputed.rc1_transfer.control.negative),
1183
+ rc1_transfer_treatment_normal: conditionMetrics(recomputed.rc1_transfer.treatment.normal),
1184
+ rc1_transfer_treatment_negative: conditionMetrics(recomputed.rc1_transfer.treatment.negative),
1185
+ },
1186
+ version_barrier: {
1187
+ new_plan_version_digest: digestArtifact(newPlan),
1188
+ plan_diff_digest: digestArtifact(planDiff),
1189
+ causal_predecessors_digest: digestArtifact(planDiff.causal_predecessors),
1190
+ },
1191
+ };
1192
+ }
1193
+
1194
+ function expectedHypothesis(comparison, recomputed, transform) {
1195
+ const checks = [
1196
+ { id: 'accepted_transform_only', passed: transform.status === 'accepted' },
1197
+ {
1198
+ id: 'primary_repeat_reproducible',
1199
+ passed: new Set(recomputed.primary.control.map(({ artifact_digest: digest }) => digest)).size === 1
1200
+ && new Set(recomputed.primary.treatment.map(({ artifact_digest: digest }) => digest)).size === 1,
1201
+ },
1202
+ {
1203
+ id: 'primary_conflicts_removed',
1204
+ passed: comparison.metrics.primary_control.conflict_records === 12
1205
+ && comparison.metrics.primary_control.distinct_conflict_pairs === 3
1206
+ && comparison.metrics.primary_treatment.conflict_records === 0,
1207
+ },
1208
+ {
1209
+ id: 'primary_waves_reduced',
1210
+ passed: comparison.metrics.primary_control.minimum_feasible_waves === 3
1211
+ && comparison.metrics.primary_treatment.minimum_feasible_waves === 1,
1212
+ },
1213
+ {
1214
+ id: 'partial_state_preserved',
1215
+ passed: comparison.metrics.primary_partial_state.conflict_records === 1
1216
+ && comparison.metrics.primary_partial_state.minimum_feasible_waves === 2,
1217
+ },
1218
+ {
1219
+ id: 'capacity_control_preserved',
1220
+ passed: comparison.metrics.primary_capacity_2.conflict_records === 0
1221
+ && comparison.metrics.primary_capacity_2.minimum_feasible_waves === 2,
1222
+ },
1223
+ {
1224
+ id: 'third_only_unknown_closed',
1225
+ passed: recomputed.primary.third_only_unknown.outcome.outcome === 'unknown'
1226
+ && recomputed.primary.third_only_unknown.verification.outcome === 'unknown',
1227
+ },
1228
+ {
1229
+ id: 'rc1_transfer_isomorphic',
1230
+ passed: comparison.metrics.rc1_transfer_control_normal.conflict_records === 3
1231
+ && comparison.metrics.rc1_transfer_control_normal.minimum_feasible_waves === 2
1232
+ && comparison.metrics.rc1_transfer_treatment_normal.conflict_records === 0
1233
+ && comparison.metrics.rc1_transfer_treatment_normal.minimum_feasible_waves === 1
1234
+ && comparison.metrics.rc1_transfer_control_negative.minimum_feasible_waves === 2
1235
+ && comparison.metrics.rc1_transfer_treatment_negative.minimum_feasible_waves === 2,
1236
+ },
1237
+ {
1238
+ id: 'all_minimum_verified',
1239
+ passed: Object.values(COMPILED_RECORD_PATHS).every((keys) => {
1240
+ const record = nestedValue(recomputed, keys);
1241
+ return record.outcome !== 'compiled' || record.verification.outcome === 'verified';
1242
+ }),
1243
+ },
1244
+ ];
1245
+ return {
1246
+ schema: 'lattice.rc2.hypothesis_evaluation.v1',
1247
+ checks,
1248
+ supported: checks.every(({ passed }) => passed),
1249
+ failed_conditions: checks.filter(({ passed }) => !passed).map(({ id }) => id),
1250
+ };
1251
+ }
1252
+
1253
+ function expectedPredecessorKinds(context) {
1254
+ const expected = new Map();
1255
+ for (const ref of context.predecessorPaths) {
1256
+ expected.set(
1257
+ ref,
1258
+ ref === 'predecessors/rc1-v6-plan.md'
1259
+ ? 'rc1_v6_phase_archive'
1260
+ : 'immutable_predecessor',
1261
+ );
1262
+ }
1263
+ expected.set('transform/accepted-artifact.json', 'accepted_transform');
1264
+ expected.set('transform/behavior-evidence.json', 'behavior_envelope');
1265
+ expected.set('transform/mutation-evidence.json', 'mutation_evidence');
1266
+ for (const runId of RUN_IDS) expected.set(`evidence/${runId}.json`, 'evidence_bundle');
1267
+ for (const ref of Object.values(PRIMARY_INPUT_PATHS)) expected.set(ref, 'fixed_input');
1268
+ expected.set('identity.json', 'execution_identity');
1269
+ expected.set('identity/schedulability-compiler-v2.mjs', 'compiler_identity');
1270
+ expected.set('identity/schedulability-verifier-v2.mjs', 'verifier_identity');
1271
+ if (context.artifactVersion !== 'v1') {
1272
+ expected.set(SENSOR_CONFIG_PATH, 'sensor_project_config');
1273
+ }
1274
+ return expected;
1275
+ }
1276
+
1277
+ function verifyV1PredecessorPair(context) {
1278
+ if (context.artifactVersion === 'v1') return true;
1279
+ const manifest = context.json.get('predecessors/rc2-v1-artifact-manifest.json');
1280
+ const plan = context.json.get('predecessors/rc2-v1-new-plan-version.json');
1281
+ if (!exactRecord(manifest, ['schema', 'base_sha', 'result_digest', 'files'])
1282
+ || manifest.schema !== 'lattice.rc2.artifact_manifest.v1'
1283
+ || !GIT_SHA1.test(manifest.base_sha)
1284
+ || !SHA256.test(manifest.result_digest)
1285
+ || !Array.isArray(manifest.files)
1286
+ || !sameArtifact(
1287
+ manifest.files.map(({ path: relativePath }) => relativePath).sort(),
1288
+ RC2_V1_ARTIFACT_PATHS,
1289
+ )
1290
+ || new Set(manifest.files.map(({ path: relativePath }) => relativePath)).size
1291
+ !== RC2_V1_ARTIFACT_PATHS.length
1292
+ || plan?.schema !== 'lattice.rc2.plan_version.v1'
1293
+ || plan.version !== 'rc2-delivery-policy-v2') {
1294
+ return false;
1295
+ }
1296
+ const planBytes = context.payloads.get('predecessors/rc2-v1-new-plan-version.json');
1297
+ const entry = manifest.files.find(({ path: relativePath }) => (
1298
+ relativePath === 'new-plan-version.json'
1299
+ ));
1300
+ return exactRecord(entry, ['path', 'media_type', 'bytes', 'sha256'])
1301
+ && entry.media_type === 'application/json'
1302
+ && entry.bytes === planBytes.byteLength
1303
+ && entry.sha256 === sha256(planBytes);
1304
+ }
1305
+
1306
+ function verifyV2PredecessorPair(context) {
1307
+ if (!['v3', 'v4'].includes(context.artifactVersion)) return true;
1308
+ const manifest = context.json.get('predecessors/rc2-v2-artifact-manifest.json');
1309
+ const plan = context.json.get('predecessors/rc2-v2-new-plan-version.json');
1310
+ if (!exactRecord(manifest, ['schema', 'base_sha', 'result_digest', 'files'])
1311
+ || manifest.schema !== 'lattice.rc2.artifact_manifest.v2'
1312
+ || !GIT_SHA1.test(manifest.base_sha)
1313
+ || !SHA256.test(manifest.result_digest)
1314
+ || !Array.isArray(manifest.files)
1315
+ || !sameArtifact(
1316
+ manifest.files.map(({ path: relativePath }) => relativePath).sort(),
1317
+ RC2_V2_ARTIFACT_PATHS,
1318
+ )
1319
+ || new Set(manifest.files.map(({ path: relativePath }) => relativePath)).size
1320
+ !== RC2_V2_ARTIFACT_PATHS.length
1321
+ || plan?.schema !== 'lattice.rc2.plan_version.v1'
1322
+ || plan.version !== 'rc2-delivery-policy-v3') {
1323
+ return false;
1324
+ }
1325
+ const planBytes = context.payloads.get('predecessors/rc2-v2-new-plan-version.json');
1326
+ const entry = manifest.files.find(({ path: relativePath }) => (
1327
+ relativePath === 'new-plan-version.json'
1328
+ ));
1329
+ return exactRecord(entry, ['path', 'media_type', 'bytes', 'sha256'])
1330
+ && entry.media_type === 'application/json'
1331
+ && entry.bytes === planBytes.byteLength
1332
+ && entry.sha256 === sha256(planBytes);
1333
+ }
1334
+
1335
+ function verifyV3PredecessorPair(context) {
1336
+ if (context.artifactVersion !== 'v4') return true;
1337
+ const manifest = context.json.get('predecessors/rc2-v3-artifact-manifest.json');
1338
+ const plan = context.json.get('predecessors/rc2-v3-new-plan-version.json');
1339
+ if (!exactRecord(manifest, ['schema', 'base_sha', 'result_digest', 'files'])
1340
+ || manifest.schema !== 'lattice.rc2.artifact_manifest.v3'
1341
+ || !GIT_SHA1.test(manifest.base_sha)
1342
+ || !SHA256.test(manifest.result_digest)
1343
+ || !Array.isArray(manifest.files)
1344
+ || !sameArtifact(
1345
+ manifest.files.map(({ path: relativePath }) => relativePath).sort(),
1346
+ RC2_V3_ARTIFACT_PATHS,
1347
+ )
1348
+ || new Set(manifest.files.map(({ path: relativePath }) => relativePath)).size
1349
+ !== RC2_V3_ARTIFACT_PATHS.length
1350
+ || plan?.schema !== 'lattice.rc2.plan_version.v1'
1351
+ || plan.version !== 'rc2-delivery-policy-v4') {
1352
+ return false;
1353
+ }
1354
+ const planBytes = context.payloads.get('predecessors/rc2-v3-new-plan-version.json');
1355
+ const entry = manifest.files.find(({ path: relativePath }) => (
1356
+ relativePath === 'new-plan-version.json'
1357
+ ));
1358
+ return exactRecord(entry, ['path', 'media_type', 'bytes', 'sha256'])
1359
+ && entry.media_type === 'application/json'
1360
+ && entry.bytes === planBytes.byteLength
1361
+ && entry.sha256 === sha256(planBytes);
1362
+ }
1363
+
1364
+ function verifyPredecessors(context) {
1365
+ const planDiff = context.json.get('plan-diff.json');
1366
+ const newPlan = context.json.get('new-plan-version.json');
1367
+ const expected = expectedPredecessorKinds(context);
1368
+ if (!Array.isArray(planDiff?.causal_predecessors)
1369
+ || !sameArtifact(planDiff.causal_predecessors, newPlan?.causal_predecessors)
1370
+ || planDiff.causal_predecessors.length !== expected.size) {
1371
+ return false;
1372
+ }
1373
+ const refs = new Set();
1374
+ for (const predecessor of planDiff.causal_predecessors) {
1375
+ if (!exactRecord(predecessor, ['kind', 'ref', 'digest'])
1376
+ || predecessor.kind !== expected.get(predecessor.ref)
1377
+ || !context.artifactPaths.includes(predecessor.ref)
1378
+ || refs.has(predecessor.ref)
1379
+ || predecessor.digest !== sha256(context.payloads.get(predecessor.ref))) {
1380
+ return false;
1381
+ }
1382
+ refs.add(predecessor.ref);
1383
+ }
1384
+ return refs.size === expected.size
1385
+ && [...expected.keys()].every((relativePath) => refs.has(relativePath))
1386
+ && verifyV1PredecessorPair(context)
1387
+ && verifyV2PredecessorPair(context)
1388
+ && verifyV3PredecessorPair(context);
1389
+ }
1390
+
1391
+ function verifyVersionBarrier(context, recomputed) {
1392
+ const primaryInputs = objectFromPaths(context, PRIMARY_INPUT_PATHS);
1393
+ const newPlan = context.json.get('new-plan-version.json');
1394
+ const planDiff = context.json.get('plan-diff.json');
1395
+ const control = recomputed.primary.control[0];
1396
+ const treatment = recomputed.primary.treatment[0];
1397
+ const expectedInvalidations = [
1398
+ 'old_plan',
1399
+ 'agent_context',
1400
+ 'partial_patch',
1401
+ 'interface_assumption',
1402
+ 'boundary_evidence',
1403
+ ];
1404
+ const predecessorPath = {
1405
+ v1: null,
1406
+ v2: 'predecessors/rc2-v1-new-plan-version.json',
1407
+ v3: 'predecessors/rc2-v2-new-plan-version.json',
1408
+ v4: 'predecessors/rc2-v3-new-plan-version.json',
1409
+ }[context.artifactVersion];
1410
+ const predecessorPlan = predecessorPath === null ? null : context.json.get(predecessorPath);
1411
+ const versionedPredecessor = predecessorPlan !== null;
1412
+ const predecessorVersion = versionedPredecessor
1413
+ ? predecessorPlan?.version
1414
+ : primaryInputs.planInput.plan_version;
1415
+ const expectedVersion = {
1416
+ v1: 'rc2-delivery-policy-v2',
1417
+ v2: 'rc2-delivery-policy-v3',
1418
+ v3: 'rc2-delivery-policy-v4',
1419
+ v4: 'rc2-delivery-policy-v5',
1420
+ }[context.artifactVersion];
1421
+ const expectedOldDigest = versionedPredecessor
1422
+ ? digestArtifact(predecessorPlan)
1423
+ : digestArtifact(control.plan);
1424
+ return newPlan?.schema === 'lattice.rc2.plan_version.v1'
1425
+ && newPlan.version === expectedVersion
1426
+ && newPlan.predecessor_version === predecessorVersion
1427
+ && sameArtifact(newPlan.plan, treatment.plan)
1428
+ && newPlan.plan_digest === digestArtifact(treatment.plan)
1429
+ && newPlan.bundle_digest === digestArtifact(treatment.bundle)
1430
+ && newPlan.verdict_digest === digestArtifact(treatment.verdict)
1431
+ && sameArtifact(
1432
+ [...newPlan.affected_todos].sort(),
1433
+ primaryInputs.planInput.todos.map(({ id }) => id).sort(),
1434
+ )
1435
+ && planDiff?.schema === 'lattice.rc2.plan_diff.v1'
1436
+ && planDiff.old_plan?.version === predecessorVersion
1437
+ && planDiff.old_plan?.digest === expectedOldDigest
1438
+ && planDiff.new_plan?.version === newPlan.version
1439
+ && planDiff.new_plan?.digest === digestArtifact(newPlan)
1440
+ && sameArtifact(planDiff.affected_todos, newPlan.affected_todos)
1441
+ && planDiff.invalidated_contexts?.map(({ kind }) => kind)
1442
+ .every((kind, index) => kind === expectedInvalidations[index])
1443
+ && planDiff.invalidated_contexts.length === expectedInvalidations.length
1444
+ && (!versionedPredecessor || (
1445
+ predecessorPlan?.plan_digest === digestArtifact(predecessorPlan.plan)
1446
+ && sameArtifact(predecessorPlan.plan, treatment.plan)
1447
+ && planDiff.invalidated_contexts.find(({ kind }) => kind === 'interface_assumption')?.ref
1448
+ === `${predecessorVersion}-interface-assumption`
1449
+ && planDiff.invalidated_contexts.find(({ kind }) => kind === 'boundary_evidence')?.ref
1450
+ === `${predecessorVersion}-boundary-evidence`
1451
+ ));
1452
+ }
1453
+
1454
+ function verifyCost(context) {
1455
+ const cost = context.json.get('cost.json');
1456
+ if (cost?.schema !== 'lattice.rc2.stage_cost.v1'
1457
+ || !Array.isArray(cost.measurements)
1458
+ || cost.measurements.length < 20
1459
+ || cost.measurements.some((measurement) => (
1460
+ !exactRecord(measurement, ['stage', 'state', 'elapsed_ms'])
1461
+ || typeof measurement.stage !== 'string'
1462
+ || measurement.state !== 'measured'
1463
+ || typeof measurement.elapsed_ms !== 'number'
1464
+ || !Number.isFinite(measurement.elapsed_ms)
1465
+ || measurement.elapsed_ms < 0
1466
+ ))
1467
+ || cost.aggregate?.measured_count !== cost.measurements.length
1468
+ || cost.aggregate?.not_measured_count !== 0) {
1469
+ return false;
1470
+ }
1471
+ const elapsed = Math.round(cost.measurements
1472
+ .reduce((sum, measurement) => sum + measurement.elapsed_ms, 0) * 1_000) / 1_000;
1473
+ const transform = context.json.get('transform/accepted-artifact.json');
1474
+ return cost.aggregate.elapsed_ms === elapsed
1475
+ && cost.intervention?.patch_bytes === transform.patch.bytes
1476
+ && cost.intervention?.files === transform.scope.changed_paths.length
1477
+ && Number.isSafeInteger(cost.intervention?.review_lines)
1478
+ && cost.intervention.review_lines > 0
1479
+ && cost.rework?.rejected_attempts === 2
1480
+ && cost.rework?.retries === 0
1481
+ && cost.rework?.rollbacks === 0
1482
+ && Array.isArray(cost.unverified)
1483
+ && cost.unverified.length > 0;
1484
+ }
1485
+
1486
+ function expectedExecutionEvidence(context, recomputed, comparison, hypothesis) {
1487
+ const identity = context.json.get('identity.json');
1488
+ const transform = context.json.get('transform/accepted-artifact.json');
1489
+ const newPlan = context.json.get('new-plan-version.json');
1490
+ const planDiff = context.json.get('plan-diff.json');
1491
+ const cost = context.json.get('cost.json');
1492
+ return {
1493
+ schema: 'lattice.rc2.campaign_execution_evidence.v1',
1494
+ base_sha: context.manifest.base_sha,
1495
+ identity_digest: digestArtifact(identity),
1496
+ transform_artifact_digest: digestArtifact(transform),
1497
+ run_digests: RUN_IDS.map((runId) => digestArtifact(
1498
+ context.json.get(`evidence/${runId}.json`),
1499
+ )),
1500
+ compiled_condition_digests: Object.values(COMPILED_RECORD_PATHS).map((keys) => (
1501
+ digestArtifact(nestedValue(recomputed, keys))
1502
+ )),
1503
+ new_plan_version_digest: digestArtifact(newPlan),
1504
+ plan_diff_digest: digestArtifact(planDiff),
1505
+ comparison_digest: digestArtifact(comparison),
1506
+ hypothesis_evaluation_digest: digestArtifact(hypothesis),
1507
+ cost_digest: digestArtifact(cost),
1508
+ };
1509
+ }
1510
+
1511
+ /** 保存payloadだけからRC2のcausal relationとschedule minimumを再計算する。 */
1512
+ export function verifyRc2CampaignArtifactSet(options = {}) {
1513
+ const checks = [];
1514
+ const check = (id, passed) => checks.push({ id, passed: passed === true });
1515
+ const context = artifactContext(options);
1516
+ check('exact_artifact_set', context !== null);
1517
+ if (context === null) {
1518
+ return {
1519
+ schema: 'lattice.rc2.artifact_set_verification.v1',
1520
+ valid: false,
1521
+ checks,
1522
+ failed_conditions: ['exact_artifact_set'],
1523
+ };
1524
+ }
1525
+
1526
+ check('identity_binding', verifyIdentity(context));
1527
+ if (context.artifactVersion !== 'v1') {
1528
+ check('sensor_config_binding', verifyLatticeSensorConfig(context));
1529
+ }
1530
+ check('transform_binding', verifyTransform(context));
1531
+ check('fresh_run_binding', verifyRuns(context));
1532
+
1533
+ let recomputed;
1534
+ try {
1535
+ recomputed = recomputeConditions(context);
1536
+ } catch {
1537
+ recomputed = null;
1538
+ }
1539
+ check('compiled_conditions', recomputed !== null
1540
+ && verifyCompiledConditions(context, recomputed));
1541
+ check('minimum_verification', recomputed !== null
1542
+ && Object.values(COMPILED_RECORD_PATHS).every((keys) => {
1543
+ const record = nestedValue(recomputed, keys);
1544
+ return record.outcome !== 'compiled' || record.verification.outcome === 'verified';
1545
+ }));
1546
+ check('repeat_reproducibility', recomputed !== null
1547
+ && new Set(recomputed.primary.control.map(({ artifact_digest: digest }) => digest)).size === 1
1548
+ && new Set(recomputed.primary.treatment.map(({ artifact_digest: digest }) => digest)).size === 1);
1549
+ check('rc1_transfer_binding', recomputed !== null
1550
+ && recomputed.rc1_transfer.control.normal.bundle.graph.conflicts.length === 3
1551
+ && recomputed.rc1_transfer.treatment.normal.bundle.graph.conflicts.length === 0);
1552
+ check('predecessor_binding', verifyPredecessors(context));
1553
+ check('version_barrier', recomputed !== null && verifyVersionBarrier(context, recomputed));
1554
+ check('cost_arithmetic', verifyCost(context));
1555
+
1556
+ let comparison;
1557
+ let hypothesis;
1558
+ if (recomputed !== null) {
1559
+ comparison = expectedComparison(context, recomputed);
1560
+ hypothesis = expectedHypothesis(
1561
+ comparison,
1562
+ recomputed,
1563
+ context.json.get('transform/accepted-artifact.json'),
1564
+ );
1565
+ }
1566
+ check('comparison_recalculation', recomputed !== null
1567
+ && sameArtifact(comparison, context.json.get('comparison.json')));
1568
+ check('hypothesis_recalculation', recomputed !== null
1569
+ && hypothesis.supported
1570
+ && sameArtifact(hypothesis, context.json.get('hypothesis-evaluation.json'))
1571
+ && context.manifest.result_digest === digestArtifact(hypothesis));
1572
+ check('execution_binding', recomputed !== null
1573
+ && sameArtifact(
1574
+ expectedExecutionEvidence(context, recomputed, comparison, hypothesis),
1575
+ context.json.get('execution-evidence.json'),
1576
+ ));
1577
+
1578
+ return {
1579
+ schema: 'lattice.rc2.artifact_set_verification.v1',
1580
+ valid: checks.every(({ passed }) => passed),
1581
+ checks,
1582
+ failed_conditions: checks.filter(({ passed }) => !passed).map(({ id }) => id),
1583
+ };
1584
+ }