@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,855 +1,855 @@
1
- import { createHash } from 'node:crypto';
2
- import { readFileSync } from 'node:fs';
3
-
4
- import {
5
- canonicalizeArtifact,
6
- digestArtifact,
7
- validateBoundaryManifest,
8
- validateBoundaryVerdict,
9
- validatePlanGraph,
10
- validatePlanInput,
11
- validateTransformArtifact,
12
- } from './artifact-contracts.mjs';
13
- import {
14
- compileBoundaryCondition,
15
- RC1_BOUNDARY_COMPILER_CONTRACT,
16
- } from './boundary-compiler.mjs';
17
- import {
18
- recomputePortableAggregate,
19
- validateRc1EvidenceBundle,
20
- validateRc1EvidenceCampaign,
21
- } from './rc1-evidence-bundle.mjs';
22
- import { validateRc1BlackBoxOracle } from './rc1-black-box-oracle.mjs';
23
- import {
24
- evaluateRc1V5Hypothesis,
25
- verifyRc1V5BehaviorArtifactSet,
26
- } from './rc1-v5-behavior-evidence.mjs';
27
-
28
- const SHA256 = /^[0-9a-f]{64}$/;
29
- const GIT_SHA1 = /^[0-9a-f]{40}$/;
30
- const INPUT_PATHS = Object.freeze({
31
- planInput: 'inputs/plan-input.json',
32
- candidateSpec: 'inputs/candidate-spec-v2.json',
33
- normalManualEvidence: 'inputs/manual-evidence.normal.json',
34
- negativeManualEvidence: 'inputs/manual-evidence.shared-state-negative.json',
35
- querySet: 'inputs/query-set-v2.json',
36
- oracle: 'inputs/behavior-oracle-v2.json',
37
- });
38
- const EVIDENCE_PATHS = Object.freeze([
39
- ['control', 'control-1'],
40
- ['control', 'control-2'],
41
- ['treatment', 'treatment-1'],
42
- ['treatment', 'treatment-2'],
43
- ]);
44
- const INVALIDATED_CONTEXTS = Object.freeze([
45
- {
46
- kind: 'old_plan',
47
- ref: 'lattice-research-campaign-1-v4',
48
- reason: 'v4 machine support was rejected by ADR 0022 and cannot receive v5 topology updates',
49
- },
50
- {
51
- kind: 'agent_context',
52
- ref: 'lattice-research-campaign-1-v4-agent-context',
53
- reason: 'v4 agent context admits behavior evidence without full snapshot and patch identity',
54
- },
55
- {
56
- kind: 'partial_patch',
57
- ref: 'lattice-research-campaign-1-v4-partial-patch',
58
- reason: 'patches based on v4 behavior summaries cannot cross the v5 version barrier',
59
- },
60
- {
61
- kind: 'interface_assumption',
62
- ref: 'receipt-reuse-is-behavior-evidence',
63
- reason: 'pre and post receipts must be distinct and exact-snapshot-bound in v5',
64
- },
65
- ]);
66
- const CHECK_IDS = Object.freeze([
67
- 'behavior_artifact_set',
68
- 'exact_artifact_set',
69
- 'canonical_payloads',
70
- 'input_identity',
71
- 'evidence_campaign',
72
- 'compiler_replay',
73
- 'transform_binding',
74
- 'plan_diff_binding',
75
- 'comparison_binding',
76
- 'hypothesis_evaluation',
77
- 'execution_evidence',
78
- 'result_binding',
79
- ]);
80
-
81
- function compiledPaths() {
82
- const paths = [];
83
- for (const condition of ['control', 'treatment']) {
84
- for (const variant of ['normal', 'negative']) {
85
- const root = `compiled/${condition}-${variant}`;
86
- paths.push(
87
- `${root}/boundary-manifest.json`,
88
- `${root}/boundary-verdict.json`,
89
- `${root}/plan.json`,
90
- );
91
- }
92
- }
93
- return paths;
94
- }
95
-
96
- const EXPECTED_PATHS = Object.freeze([
97
- ...Object.values(INPUT_PATHS),
98
- ...EVIDENCE_PATHS.map(([, runId]) => `evidence/${runId}.json`),
99
- ...compiledPaths(),
100
- 'behavior/pre-receipt.json',
101
- 'behavior/post-receipt.json',
102
- 'behavior/evidence-envelope.json',
103
- 'transform/transform-artifact.json',
104
- 'transform/transform-receipt.json',
105
- 'transform/seam.patch',
106
- 'plan-diff.json',
107
- 'comparison.json',
108
- 'hypothesis-evaluation.json',
109
- 'execution-evidence.json',
110
- ].sort());
111
-
112
- function isPlainObject(value) {
113
- return value !== null
114
- && typeof value === 'object'
115
- && !Array.isArray(value)
116
- && Object.getPrototypeOf(value) === Object.prototype;
117
- }
118
-
119
- function exactRecord(value, keys) {
120
- if (!isPlainObject(value)) return false;
121
- const actual = Object.keys(value).sort();
122
- const expected = [...keys].sort();
123
- return actual.length === expected.length
124
- && actual.every((key, index) => key === expected[index]);
125
- }
126
-
127
- function sameArray(left, right) {
128
- return Array.isArray(left)
129
- && Array.isArray(right)
130
- && left.length === right.length
131
- && left.every((entry, index) => entry === right[index]);
132
- }
133
-
134
- function sameArtifact(left, right) {
135
- try {
136
- return digestArtifact(left) === digestArtifact(right);
137
- } catch {
138
- return false;
139
- }
140
- }
141
-
142
- function sha256(value) {
143
- return createHash('sha256').update(value).digest('hex');
144
- }
145
-
146
- function parseJson(bytes) {
147
- try {
148
- const value = JSON.parse(bytes.toString('utf8'));
149
- return Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8').equals(bytes)
150
- ? value
151
- : null;
152
- } catch {
153
- return null;
154
- }
155
- }
156
-
157
- function payloadMap(payloads) {
158
- if (!Array.isArray(payloads)) return null;
159
- const map = new Map();
160
- for (const payload of payloads) {
161
- if (!exactRecord(payload, ['path', 'bytes'])
162
- || typeof payload.path !== 'string'
163
- || !Buffer.isBuffer(payload.bytes)
164
- || map.has(payload.path)) {
165
- return null;
166
- }
167
- map.set(payload.path, payload.bytes);
168
- }
169
- return map;
170
- }
171
-
172
- function exactArtifactSet(options) {
173
- if (!exactRecord(options, ['manifest', 'payloads'])) return false;
174
- const payloads = payloadMap(options.payloads);
175
- const manifestPaths = Array.isArray(options.manifest?.files)
176
- ? options.manifest.files.map(({ path }) => path).sort()
177
- : [];
178
- const payloadPaths = payloads ? [...payloads.keys()].sort() : [];
179
- return sameArray(manifestPaths, EXPECTED_PATHS)
180
- && sameArray(payloadPaths, EXPECTED_PATHS);
181
- }
182
-
183
- function artifactContext(options) {
184
- if (!exactArtifactSet(options)) return null;
185
- const payloads = payloadMap(options.payloads);
186
- const json = new Map();
187
- for (const relativePath of EXPECTED_PATHS) {
188
- if (!relativePath.endsWith('.json')) continue;
189
- const parsed = parseJson(payloads.get(relativePath));
190
- if (parsed === null) return null;
191
- json.set(relativePath, parsed);
192
- }
193
- const patch = payloads.get('transform/seam.patch');
194
- if (!Buffer.isBuffer(patch) || patch.byteLength === 0) return null;
195
- return { manifest: options.manifest, payloads, json, patch };
196
- }
197
-
198
- function fixedInputs(context) {
199
- return Object.fromEntries(Object.entries(INPUT_PATHS).map(([key, relativePath]) => (
200
- [key, context.json.get(relativePath)]
201
- )));
202
- }
203
-
204
- function fixedInputIdentity(inputs) {
205
- return {
206
- plan_input: digestArtifact(inputs.planInput),
207
- candidate_spec: digestArtifact(inputs.candidateSpec),
208
- normal_manual_evidence: digestArtifact(inputs.normalManualEvidence),
209
- negative_manual_evidence: digestArtifact(inputs.negativeManualEvidence),
210
- query_set: digestArtifact(inputs.querySet),
211
- capacity_writers: inputs.planInput.capacity.writers,
212
- behavior_oracle: digestArtifact(inputs.oracle),
213
- };
214
- }
215
-
216
- function evidenceBundles(context) {
217
- return EVIDENCE_PATHS.map(([, runId]) => context.json.get(`evidence/${runId}.json`));
218
- }
219
-
220
- function decodeRawEvidence(bundle) {
221
- const receipt = bundle.raw;
222
- const bytes = Buffer.from(receipt.payload_base64, 'base64');
223
- if (bytes.toString('base64') !== receipt.payload_base64
224
- || bytes.byteLength !== receipt.canonical_bytes
225
- || sha256(bytes) !== receipt.payload_digest) {
226
- throw new TypeError('RC1 v5 raw evidence receipt bytes are invalid');
227
- }
228
- const value = JSON.parse(bytes.toString('utf8'));
229
- if (canonicalizeArtifact(value) !== bytes.toString('utf8')) {
230
- throw new TypeError('RC1 v5 raw evidence receipt is not canonical');
231
- }
232
- return value;
233
- }
234
-
235
- function inputIdentityValid(context) {
236
- const inputs = fixedInputs(context);
237
- for (const value of Object.values(inputs)) canonicalizeArtifact(value);
238
- if (!validatePlanInput(inputs.planInput)
239
- || !validateRc1BlackBoxOracle(inputs.oracle)) {
240
- return false;
241
- }
242
- const queryDigest = digestArtifact(inputs.querySet);
243
- const bundles = evidenceBundles(context);
244
- const execution = context.json.get('execution-evidence.json');
245
- return sameArtifact(execution.fixed_inputs, fixedInputIdentity(inputs))
246
- && bundles.every((bundle) => bundle.query_set_digest === queryDigest
247
- && sameArtifact(bundle.query_set, inputs.querySet));
248
- }
249
-
250
- function evidenceCampaignValid(context) {
251
- const inputs = fixedInputs(context);
252
- const bundles = evidenceBundles(context);
253
- return validateRc1EvidenceCampaign(bundles)
254
- && EVIDENCE_PATHS.every(([condition, runId], index) => {
255
- const bundle = bundles[index];
256
- return validateRc1EvidenceBundle(bundle)
257
- && bundle.condition === condition
258
- && bundle.run_id === runId
259
- && sameArtifact(bundle.query_set, inputs.querySet)
260
- && recomputePortableAggregate(bundle.portable) === bundle.portable.aggregate_digest;
261
- });
262
- }
263
-
264
- function storedCompilation(context, condition, variant) {
265
- const root = `compiled/${condition}-${variant}`;
266
- const boundaryManifest = context.json.get(`${root}/boundary-manifest.json`);
267
- const boundaryVerdict = context.json.get(`${root}/boundary-verdict.json`);
268
- const planGraph = context.json.get(`${root}/plan.json`);
269
- const manifestDigest = digestArtifact(boundaryManifest);
270
- const verdictDigest = digestArtifact(boundaryVerdict);
271
- const planDigest = digestArtifact(planGraph);
272
- if (!validateBoundaryManifest(boundaryManifest)
273
- || !validateBoundaryVerdict(boundaryVerdict)
274
- || !validatePlanGraph(planGraph)
275
- || boundaryVerdict.boundary_manifest_digest !== manifestDigest
276
- || planGraph.source_manifest_digest !== manifestDigest) {
277
- throw new TypeError(`RC1 v5 stored ${condition}/${variant} compilation is invalid`);
278
- }
279
- return {
280
- boundary_manifest: boundaryManifest,
281
- boundary_manifest_digest: manifestDigest,
282
- boundary_verdict: boundaryVerdict,
283
- boundary_verdict_digest: verdictDigest,
284
- plan_graph: planGraph,
285
- plan_graph_digest: planDigest,
286
- };
287
- }
288
-
289
- function storedCompilations(context) {
290
- return Object.fromEntries(['control', 'treatment'].map((condition) => [
291
- condition,
292
- Object.fromEntries(['normal', 'negative'].map((variant) => [
293
- variant,
294
- storedCompilation(context, condition, variant),
295
- ])),
296
- ]));
297
- }
298
-
299
- function compilerReplayValid(context) {
300
- const inputs = fixedInputs(context);
301
- const execution = context.json.get('execution-evidence.json');
302
- const stored = storedCompilations(context);
303
- for (const [condition, runId] of EVIDENCE_PATHS) {
304
- const bundle = context.json.get(`evidence/${runId}.json`);
305
- const run = execution.runs?.[condition]?.find(({ run_id: id }) => id === runId);
306
- if (!run || !SHA256.test(run.code_snapshot_digest)) return false;
307
- const rawEvidence = decodeRawEvidence(bundle);
308
- for (const variant of ['normal', 'negative']) {
309
- const replay = compileBoundaryCondition({
310
- planInput: inputs.planInput,
311
- candidateSpec: inputs.candidateSpec,
312
- manualEvidence: variant === 'normal'
313
- ? inputs.normalManualEvidence
314
- : inputs.negativeManualEvidence,
315
- querySet: inputs.querySet,
316
- sensorEvidence: rawEvidence,
317
- codeSnapshotDigest: run.code_snapshot_digest,
318
- planVersion: `rc1-v5-${condition}${variant === 'negative' ? '-negative' : ''}`,
319
- });
320
- const expected = stored[condition][variant];
321
- if (!sameArtifact(replay.boundary_manifest, expected.boundary_manifest)
322
- || !sameArtifact(replay.boundary_verdict, expected.boundary_verdict)
323
- || !sameArtifact(replay.plan_graph, expected.plan_graph)
324
- || replay.boundary_manifest_digest !== expected.boundary_manifest_digest
325
- || replay.boundary_verdict_digest !== expected.boundary_verdict_digest
326
- || replay.plan_graph_digest !== expected.plan_graph_digest
327
- || replay.candidate_spec_digest !== digestArtifact(inputs.candidateSpec)) {
328
- return false;
329
- }
330
- }
331
- }
332
- return true;
333
- }
334
-
335
- function behaviorEvidence(context) {
336
- return {
337
- pre_receipt: context.json.get('behavior/pre-receipt.json'),
338
- post_receipt: context.json.get('behavior/post-receipt.json'),
339
- envelope: context.json.get('behavior/evidence-envelope.json'),
340
- transform_artifact: context.json.get('transform/transform-artifact.json'),
341
- patch_digest: sha256(context.patch),
342
- };
343
- }
344
-
345
- function transformResult(context) {
346
- const artifact = context.json.get('transform/transform-artifact.json');
347
- const receipt = context.json.get('transform/transform-receipt.json');
348
- return {
349
- artifact,
350
- artifact_digest: digestArtifact(artifact),
351
- receipt,
352
- receipt_digest: receipt.receipt_digest,
353
- patch: context.patch,
354
- behavior_evidence: behaviorEvidence(context),
355
- };
356
- }
357
-
358
- function sourceBindings(compiled, querySet) {
359
- return {
360
- boundary_manifest_digest: compiled.boundary_manifest_digest,
361
- boundary_verdict_digest: compiled.boundary_verdict_digest,
362
- control_plan_digest: compiled.plan_graph_digest,
363
- query_set_digest: digestArtifact(querySet),
364
- };
365
- }
366
-
367
- function transformReceiptValid(transform, inputs) {
368
- const receipt = transform.receipt;
369
- if (!exactRecord(receipt, [
370
- 'schema',
371
- 'status',
372
- 'transform_artifact_digest',
373
- 'behavior_envelope_digest',
374
- 'fixed_inputs_digest',
375
- 'source_invariant',
376
- 'receipt_digest',
377
- ])
378
- || receipt.schema !== 'lattice.rc1.seam_transform_receipt.v5'
379
- || receipt.status !== 'accepted'
380
- || receipt.source_invariant?.outcome !== 'passed') {
381
- return false;
382
- }
383
- const { receipt_digest: ignored, ...preimage } = receipt;
384
- const artifact = transform.artifact;
385
- const bindings = {
386
- boundary_manifest_digest: artifact.source.boundary_manifest_digest,
387
- boundary_verdict_digest: artifact.source.boundary_verdict_digest,
388
- control_plan_digest: artifact.source.control_plan_digest,
389
- query_set_digest: artifact.source.query_set_digest,
390
- };
391
- const verifiers = artifact.verification.receipts.map(({ id, command, args }) => ({
392
- id,
393
- command,
394
- args,
395
- }));
396
- const fixedDigest = digestArtifact({
397
- candidate_id: artifact.candidate_id,
398
- allowed_paths: artifact.scope.allowed_paths,
399
- verifiers,
400
- oracle_digest: digestArtifact(inputs.oracle),
401
- source_bindings: bindings,
402
- });
403
- return SHA256.test(receipt.receipt_digest)
404
- && receipt.receipt_digest === digestArtifact(preimage)
405
- && receipt.transform_artifact_digest === transform.artifact_digest
406
- && receipt.behavior_envelope_digest === transform.behavior_evidence.envelope.envelope_digest
407
- && receipt.fixed_inputs_digest === fixedDigest;
408
- }
409
-
410
- function transformBindingValid(context) {
411
- const inputs = fixedInputs(context);
412
- const stored = storedCompilations(context);
413
- const transform = transformResult(context);
414
- const artifact = transform.artifact;
415
- const behavior = transform.behavior_evidence;
416
- const execution = context.json.get('execution-evidence.json');
417
- const expectedBindings = sourceBindings(stored.control.normal, inputs.querySet);
418
- return validateTransformArtifact(artifact)
419
- && artifact.status === 'accepted'
420
- && Object.entries(expectedBindings).every(([key, digest]) => artifact.source[key] === digest)
421
- && artifact.source.base_sha === context.manifest.base_sha
422
- && artifact.source.code_snapshot_digest === behavior.pre_receipt.surface_digest
423
- && artifact.patch.digest === sha256(context.patch)
424
- && artifact.patch.bytes === context.patch.byteLength
425
- && transform.artifact_digest === behavior.envelope.transform_artifact_digest
426
- && transform.artifact_digest === digestArtifact(behavior.transform_artifact)
427
- && transformReceiptValid(transform, inputs)
428
- && execution.transform?.artifact_digest === transform.artifact_digest
429
- && execution.transform?.receipt_digest === transform.receipt_digest
430
- && execution.transform?.patch_digest === artifact.patch.digest
431
- && execution.transform?.source_invariant_digest
432
- === digestArtifact(transform.receipt.source_invariant);
433
- }
434
-
435
- function compilationSummary(compiled) {
436
- const conflicts = compiled.boundary_manifest.conflicts;
437
- return {
438
- boundary_manifest_digest: compiled.boundary_manifest_digest,
439
- boundary_verdict_digest: compiled.boundary_verdict_digest,
440
- plan_graph_digest: compiled.plan_graph_digest,
441
- verdict: compiled.boundary_verdict.verdicts[0].verdict,
442
- write_conflicts: conflicts.filter(({ kind }) => kind === 'write_boundary').length,
443
- test_write_conflicts: conflicts.filter(({ kind, resource }) => (
444
- kind === 'write_boundary'
445
- && resource.kind === 'path'
446
- && resource.target.startsWith('test/')
447
- )).length,
448
- state_conflicts: conflicts.filter(({ kind }) => kind === 'state').length,
449
- hard_precedence: compiled.boundary_manifest.todos
450
- .reduce((count, todo) => count + todo.hard_needs.length, 0),
451
- unknowns: compiled.boundary_manifest.unknowns.length,
452
- minimum_feasible_waves: compiled.plan_graph.minimum_feasible_waves,
453
- };
454
- }
455
-
456
- function expectedPlanDiff(context) {
457
- const stored = storedCompilations(context);
458
- const transform = transformResult(context);
459
- const control = compilationSummary(stored.control.normal);
460
- const treatment = compilationSummary(stored.treatment.normal);
461
- return {
462
- schema: 'lattice.plan_diff.v2',
463
- old_plan: {
464
- version: stored.control.normal.plan_graph.plan_version,
465
- digest: stored.control.normal.plan_graph_digest,
466
- },
467
- new_plan: {
468
- version: stored.treatment.normal.plan_graph.plan_version,
469
- digest: stored.treatment.normal.plan_graph_digest,
470
- },
471
- causal_predecessor: {
472
- plan_version: 'lattice-research-campaign-1-v4',
473
- decision_ref: 'docs/adr/0022-rc1-v4-phase-gate-rejection.md',
474
- status: 'phase_rejected',
475
- },
476
- transform: {
477
- status: transform.artifact.status,
478
- artifact_digest: transform.artifact_digest,
479
- receipt_digest: transform.receipt_digest,
480
- patch_digest: transform.artifact.patch.digest,
481
- changed_paths: [...transform.artifact.scope.changed_paths],
482
- },
483
- nodes: {
484
- added: [],
485
- removed: [],
486
- changed: stored.control.normal.plan_graph.nodes.map(({ id }) => id),
487
- },
488
- edges: {
489
- added: stored.treatment.normal.plan_graph.edges.map(({ id }) => id),
490
- removed: stored.control.normal.plan_graph.edges.map(({ id }) => id),
491
- },
492
- invalidated_contexts: structuredClone(INVALIDATED_CONTEXTS),
493
- metrics: {
494
- write_conflicts_before: control.write_conflicts,
495
- write_conflicts_after: treatment.write_conflicts,
496
- test_write_conflicts_before: control.test_write_conflicts,
497
- test_write_conflicts_after: treatment.test_write_conflicts,
498
- hard_precedence_before: control.hard_precedence,
499
- hard_precedence_after: treatment.hard_precedence,
500
- minimum_feasible_waves_before: control.minimum_feasible_waves,
501
- minimum_feasible_waves_after: treatment.minimum_feasible_waves,
502
- },
503
- };
504
- }
505
-
506
- function planDiffBindingValid(context) {
507
- return sameArtifact(context.json.get('plan-diff.json'), expectedPlanDiff(context));
508
- }
509
-
510
- function evidenceSummary(bundles, querySet) {
511
- return {
512
- portable_preimages_complete: bundles.length === 2 && bundles.every((bundle) => (
513
- validateRc1EvidenceBundle(bundle)
514
- && bundle.portable.outcomes.length === querySet.queries.length
515
- && bundle.portable.per_query.length === querySet.queries.length
516
- )),
517
- digests_recomputed: bundles.every((bundle) => (
518
- recomputePortableAggregate(bundle.portable) === bundle.portable.aggregate_digest
519
- )),
520
- diagnostics_sanitized: bundles.every((bundle) => (
521
- validateRc1EvidenceBundle(bundle)
522
- && bundle.diagnostic.payload.cwd === '<repo-root>'
523
- && bundle.diagnostic.sanitization_manifest.schema
524
- === 'lattice.sensor_sanitization_manifest.v1'
525
- )),
526
- };
527
- }
528
-
529
- function transformReceiptSelfValid(transform) {
530
- const receipt = transform.receipt;
531
- if (!exactRecord(receipt, [
532
- 'schema',
533
- 'status',
534
- 'transform_artifact_digest',
535
- 'behavior_envelope_digest',
536
- 'fixed_inputs_digest',
537
- 'source_invariant',
538
- 'receipt_digest',
539
- ])) return false;
540
- const { receipt_digest: ignored, ...preimage } = receipt;
541
- return receipt.schema === 'lattice.rc1.seam_transform_receipt.v5'
542
- && receipt.status === 'accepted'
543
- && receipt.receipt_digest === digestArtifact(preimage)
544
- && transform.receipt_digest === receipt.receipt_digest;
545
- }
546
-
547
- function fixedInputsBound(transform, bindings, baseSha) {
548
- const behavior = transform.behavior_evidence;
549
- return transform.artifact.status === 'accepted'
550
- && Object.entries(bindings).every(([key, digest]) => transform.artifact.source[key] === digest)
551
- && transform.artifact.source.base_sha === baseSha
552
- && transform.artifact.source.code_snapshot_digest === behavior.pre_receipt.surface_digest
553
- && transform.artifact_digest === digestArtifact(transform.artifact)
554
- && transform.receipt.transform_artifact_digest === transform.artifact_digest
555
- && transform.receipt.behavior_envelope_digest === behavior.envelope.envelope_digest
556
- && transform.artifact.patch.digest === behavior.patch_digest
557
- && digestArtifact(behavior.transform_artifact) === transform.artifact_digest
558
- && transformReceiptSelfValid(transform);
559
- }
560
-
561
- function sourceInvariantState(context) {
562
- const execution = context.json.get('execution-evidence.json');
563
- return {
564
- control: execution.runs.control.every(({ source_invariant: receipt }) => (
565
- receipt?.outcome === 'passed'
566
- )),
567
- treatment: context.json.get('transform/transform-receipt.json').source_invariant?.outcome
568
- === 'passed'
569
- && execution.runs.treatment.every(({ source_invariant: receipt }) => (
570
- receipt?.outcome === 'passed'
571
- )),
572
- };
573
- }
574
-
575
- function expectedComparison(context) {
576
- const inputs = fixedInputs(context);
577
- const stored = storedCompilations(context);
578
- const bundles = evidenceBundles(context);
579
- const transform = transformResult(context);
580
- const planDiff = expectedPlanDiff(context);
581
- const sourceInvariant = sourceInvariantState(context);
582
- const fixed = fixedInputIdentity(inputs);
583
- const bindings = sourceBindings(stored.control.normal, inputs.querySet);
584
- return {
585
- schema: 'lattice.rc1.control_treatment_comparison.v3',
586
- fixed_inputs: { control: fixed, treatment: structuredClone(fixed) },
587
- independent_variable: {
588
- kind: 'accepted_production_and_test_seam',
589
- transform_artifact_digest: transform.artifact_digest,
590
- transform_receipt_digest: transform.receipt_digest,
591
- patch_digest: transform.artifact.patch.digest,
592
- },
593
- compiler: {
594
- condition_selector: RC1_BOUNDARY_COMPILER_CONTRACT.condition_selector,
595
- control: {
596
- export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
597
- source_digest: CURRENT_COMPILER_SOURCE_DIGEST,
598
- },
599
- treatment: {
600
- export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
601
- source_digest: CURRENT_COMPILER_SOURCE_DIGEST,
602
- },
603
- },
604
- control: compilationSummary(stored.control.normal),
605
- treatment: compilationSummary(stored.treatment.normal),
606
- negative_control: compilationSummary(stored.control.negative),
607
- negative_treatment: compilationSummary(stored.treatment.negative),
608
- behavior: {
609
- evidence_envelope_digest: transform.behavior_evidence.envelope.envelope_digest,
610
- },
611
- evidence: {
612
- control: evidenceSummary(bundles.filter(({ condition }) => condition === 'control'), inputs.querySet),
613
- treatment: evidenceSummary(
614
- bundles.filter(({ condition }) => condition === 'treatment'),
615
- inputs.querySet,
616
- ),
617
- },
618
- predecessor: {
619
- transform_status: transform.artifact.status,
620
- same_base: transform.artifact.source.base_sha === context.manifest.base_sha,
621
- fixed_inputs_bound: fixedInputsBound(transform, bindings, context.manifest.base_sha),
622
- },
623
- version_barrier: {
624
- old_plan: planDiff.old_plan,
625
- new_plan: planDiff.new_plan,
626
- plan_diff_digest: digestArtifact(planDiff),
627
- invalidated_contexts: planDiff.invalidated_contexts.map(({ kind, ref }) => ({ kind, ref })),
628
- },
629
- source_invariant: {
630
- control: sourceInvariant.control ? 'passed' : 'failed',
631
- treatment: sourceInvariant.treatment ? 'passed' : 'failed',
632
- },
633
- };
634
- }
635
-
636
- function comparisonBindingValid(context) {
637
- return sameArtifact(context.json.get('comparison.json'), expectedComparison(context));
638
- }
639
-
640
- function hypothesisEvaluationValid(context) {
641
- const actual = context.json.get('hypothesis-evaluation.json');
642
- const expected = evaluateRc1V5Hypothesis({
643
- comparison: context.json.get('comparison.json'),
644
- behaviorEvidence: behaviorEvidence(context),
645
- });
646
- return sameArtifact(actual, expected);
647
- }
648
-
649
- function compilationDigests(condition) {
650
- return Object.fromEntries(['normal', 'negative'].map((variant) => [variant, {
651
- boundary_manifest: condition[variant].boundary_manifest_digest,
652
- boundary_verdict: condition[variant].boundary_verdict_digest,
653
- plan_graph: condition[variant].plan_graph_digest,
654
- }]));
655
- }
656
-
657
- function bundleDescriptorDigest(bundle) {
658
- return digestArtifact({
659
- schema: bundle.schema,
660
- condition: bundle.condition,
661
- run_id: bundle.run_id,
662
- query_set_digest: bundle.query_set_digest,
663
- component_digests: bundle.component_digests,
664
- });
665
- }
666
-
667
- function nonNegativeMilliseconds(value) {
668
- return Number.isFinite(value) && value >= 0;
669
- }
670
-
671
- function runEvidenceValid(context, condition, run, bundle, transformPatchDigest) {
672
- return exactRecord(run, [
673
- 'run_id',
674
- 'condition',
675
- 'index_elapsed_ms',
676
- 'query_elapsed_ms',
677
- 'code_snapshot_digest',
678
- 'raw_digest',
679
- 'diagnostic_digest',
680
- 'portable_digest',
681
- 'bundle_descriptor_digest',
682
- 'patch_digest',
683
- 'source_invariant',
684
- 'source_invariant_digest',
685
- ])
686
- && run.run_id === bundle.run_id
687
- && run.condition === condition
688
- && nonNegativeMilliseconds(run.index_elapsed_ms)
689
- && nonNegativeMilliseconds(run.query_elapsed_ms)
690
- && SHA256.test(run.code_snapshot_digest)
691
- && run.raw_digest === bundle.raw.payload_digest
692
- && run.diagnostic_digest === bundle.diagnostic.payload_digest
693
- && run.portable_digest === bundle.portable.aggregate_digest
694
- && run.bundle_descriptor_digest === bundleDescriptorDigest(bundle)
695
- && run.patch_digest === (condition === 'treatment' ? transformPatchDigest : null)
696
- && run.source_invariant?.outcome === 'passed'
697
- && run.source_invariant_digest === digestArtifact(run.source_invariant);
698
- }
699
-
700
- function executionEvidenceValid(context) {
701
- const execution = context.json.get('execution-evidence.json');
702
- const inputs = fixedInputs(context);
703
- const bundles = evidenceBundles(context);
704
- const stored = storedCompilations(context);
705
- const transform = transformResult(context);
706
- const planDiff = context.json.get('plan-diff.json');
707
- const comparison = context.json.get('comparison.json');
708
- const evaluation = context.json.get('hypothesis-evaluation.json');
709
- if (!exactRecord(execution, [
710
- 'schema',
711
- 'base_sha',
712
- 'elapsed_ms',
713
- 'compiler',
714
- 'fixed_inputs',
715
- 'runs',
716
- 'transform',
717
- 'behavior',
718
- 'compilations',
719
- 'plan_diff_digest',
720
- 'comparison_digest',
721
- 'hypothesis_evaluation_digest',
722
- 'observed_facts',
723
- ])
724
- || execution.schema !== 'lattice.rc1.corrected_campaign_execution_evidence.v5'
725
- || execution.base_sha !== context.manifest.base_sha
726
- || !nonNegativeMilliseconds(execution.elapsed_ms)
727
- || !exactRecord(execution.compiler, [
728
- 'export_name',
729
- 'source_digest',
730
- 'campaign_runner_source_digest',
731
- ])
732
- || execution.compiler.export_name !== RC1_BOUNDARY_COMPILER_CONTRACT.export_name
733
- || execution.compiler.source_digest !== CURRENT_COMPILER_SOURCE_DIGEST
734
- || execution.compiler.campaign_runner_source_digest !== CURRENT_CAMPAIGN_SOURCE_DIGEST
735
- || !sameArtifact(execution.fixed_inputs, fixedInputIdentity(inputs))
736
- || !exactRecord(execution.runs, ['control', 'treatment'])) {
737
- return false;
738
- }
739
- for (const condition of ['control', 'treatment']) {
740
- const conditionBundles = bundles.filter((bundle) => bundle.condition === condition);
741
- if (!Array.isArray(execution.runs[condition])
742
- || execution.runs[condition].length !== 2
743
- || !execution.runs[condition].every((run, index) => runEvidenceValid(
744
- context,
745
- condition,
746
- run,
747
- conditionBundles[index],
748
- transform.artifact.patch.digest,
749
- ))) {
750
- return false;
751
- }
752
- }
753
- const behavior = transform.behavior_evidence;
754
- const expectedFacts = {
755
- evidence_campaign_valid: true,
756
- compiler_reused: true,
757
- exact_patch_replayed: true,
758
- full_behavior_evidence_bound: true,
759
- source_invariant_passed: true,
760
- hypothesis_supported: evaluation.supported,
761
- };
762
- return exactRecord(execution.transform, [
763
- 'elapsed_ms',
764
- 'artifact_digest',
765
- 'receipt_digest',
766
- 'patch_digest',
767
- 'source_invariant_digest',
768
- ])
769
- && nonNegativeMilliseconds(execution.transform.elapsed_ms)
770
- && sameArtifact({
771
- artifact_digest: execution.transform.artifact_digest,
772
- receipt_digest: execution.transform.receipt_digest,
773
- patch_digest: execution.transform.patch_digest,
774
- source_invariant_digest: execution.transform.source_invariant_digest,
775
- }, {
776
- artifact_digest: transform.artifact_digest,
777
- receipt_digest: transform.receipt_digest,
778
- patch_digest: transform.artifact.patch.digest,
779
- source_invariant_digest: digestArtifact(transform.receipt.source_invariant),
780
- })
781
- && sameArtifact(execution.behavior, {
782
- pre_receipt_digest: behavior.pre_receipt.receipt_digest,
783
- post_receipt_digest: behavior.post_receipt.receipt_digest,
784
- pre_surface_digest: behavior.pre_receipt.surface_digest,
785
- post_surface_digest: behavior.post_receipt.surface_digest,
786
- envelope_digest: behavior.envelope.envelope_digest,
787
- })
788
- && sameArtifact(execution.compilations, {
789
- control: compilationDigests(stored.control),
790
- treatment: compilationDigests(stored.treatment),
791
- })
792
- && execution.plan_diff_digest === digestArtifact(planDiff)
793
- && execution.comparison_digest === digestArtifact(comparison)
794
- && execution.hypothesis_evaluation_digest === digestArtifact(evaluation)
795
- && sameArtifact(execution.observed_facts, expectedFacts);
796
- }
797
-
798
- function resultBindingValid(context) {
799
- const execution = context.json.get('execution-evidence.json');
800
- const transform = context.json.get('transform/transform-artifact.json');
801
- const pre = context.json.get('behavior/pre-receipt.json');
802
- const post = context.json.get('behavior/post-receipt.json');
803
- const envelope = context.json.get('behavior/evidence-envelope.json');
804
- return GIT_SHA1.test(context.manifest.base_sha)
805
- && context.manifest.base_sha === execution.base_sha
806
- && context.manifest.base_sha === transform.source.base_sha
807
- && context.manifest.base_sha === pre.base_sha
808
- && context.manifest.base_sha === post.base_sha
809
- && context.manifest.base_sha === envelope.base_sha
810
- && context.manifest.result_digest === envelope.envelope_digest;
811
- }
812
-
813
- function safeCheck(callback) {
814
- try {
815
- return callback() === true;
816
- } catch {
817
- return false;
818
- }
819
- }
820
-
821
- const CURRENT_COMPILER_SOURCE_DIGEST = sha256(
822
- readFileSync(new URL('./boundary-compiler.mjs', import.meta.url)),
823
- );
824
- const CURRENT_CAMPAIGN_SOURCE_DIGEST = sha256(
825
- readFileSync(new URL('./rc1-v5-campaign.mjs', import.meta.url)),
826
- );
827
-
828
- /** 保存済みv5 payloadだけからclosed-loopの全因果cross-bindingを再検証する。 */
829
- export function verifyRc1V5CampaignArtifactSet(options = {}) {
830
- const behaviorVerification = verifyRc1V5BehaviorArtifactSet(options);
831
- const exactSet = safeCheck(() => exactArtifactSet(options));
832
- const context = exactSet ? artifactContext(options) : null;
833
- const values = [
834
- behaviorVerification.valid,
835
- exactSet,
836
- context !== null,
837
- context !== null && safeCheck(() => inputIdentityValid(context)),
838
- context !== null && safeCheck(() => evidenceCampaignValid(context)),
839
- context !== null && safeCheck(() => compilerReplayValid(context)),
840
- context !== null && safeCheck(() => transformBindingValid(context)),
841
- context !== null && safeCheck(() => planDiffBindingValid(context)),
842
- context !== null && safeCheck(() => comparisonBindingValid(context)),
843
- context !== null && safeCheck(() => hypothesisEvaluationValid(context)),
844
- context !== null && safeCheck(() => executionEvidenceValid(context)),
845
- context !== null && safeCheck(() => resultBindingValid(context)),
846
- ];
847
- const checks = CHECK_IDS.map((id, index) => ({ id, passed: values[index] }));
848
- const failedConditions = checks.filter(({ passed }) => !passed).map(({ id }) => id);
849
- return {
850
- schema: 'lattice.rc1.campaign_artifact_verification.v1',
851
- valid: failedConditions.length === 0,
852
- checks,
853
- failed_conditions: failedConditions,
854
- };
855
- }
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+
4
+ import {
5
+ canonicalizeArtifact,
6
+ digestArtifact,
7
+ validateBoundaryManifest,
8
+ validateBoundaryVerdict,
9
+ validatePlanGraph,
10
+ validatePlanInput,
11
+ validateTransformArtifact,
12
+ } from './artifact-contracts.mjs';
13
+ import {
14
+ compileBoundaryCondition,
15
+ RC1_BOUNDARY_COMPILER_CONTRACT,
16
+ } from './boundary-compiler.mjs';
17
+ import {
18
+ recomputePortableAggregate,
19
+ validateRc1EvidenceBundle,
20
+ validateRc1EvidenceCampaign,
21
+ } from './rc1-evidence-bundle.mjs';
22
+ import { validateRc1BlackBoxOracle } from './rc1-black-box-oracle.mjs';
23
+ import {
24
+ evaluateRc1V5Hypothesis,
25
+ verifyRc1V5BehaviorArtifactSet,
26
+ } from './rc1-v5-behavior-evidence.mjs';
27
+
28
+ const SHA256 = /^[0-9a-f]{64}$/;
29
+ const GIT_SHA1 = /^[0-9a-f]{40}$/;
30
+ const INPUT_PATHS = Object.freeze({
31
+ planInput: 'inputs/plan-input.json',
32
+ candidateSpec: 'inputs/candidate-spec-v2.json',
33
+ normalManualEvidence: 'inputs/manual-evidence.normal.json',
34
+ negativeManualEvidence: 'inputs/manual-evidence.shared-state-negative.json',
35
+ querySet: 'inputs/query-set-v2.json',
36
+ oracle: 'inputs/behavior-oracle-v2.json',
37
+ });
38
+ const EVIDENCE_PATHS = Object.freeze([
39
+ ['control', 'control-1'],
40
+ ['control', 'control-2'],
41
+ ['treatment', 'treatment-1'],
42
+ ['treatment', 'treatment-2'],
43
+ ]);
44
+ const INVALIDATED_CONTEXTS = Object.freeze([
45
+ {
46
+ kind: 'old_plan',
47
+ ref: 'lattice-research-campaign-1-v4',
48
+ reason: 'v4 machine support was rejected by ADR 0022 and cannot receive v5 topology updates',
49
+ },
50
+ {
51
+ kind: 'agent_context',
52
+ ref: 'lattice-research-campaign-1-v4-agent-context',
53
+ reason: 'v4 agent context admits behavior evidence without full snapshot and patch identity',
54
+ },
55
+ {
56
+ kind: 'partial_patch',
57
+ ref: 'lattice-research-campaign-1-v4-partial-patch',
58
+ reason: 'patches based on v4 behavior summaries cannot cross the v5 version barrier',
59
+ },
60
+ {
61
+ kind: 'interface_assumption',
62
+ ref: 'receipt-reuse-is-behavior-evidence',
63
+ reason: 'pre and post receipts must be distinct and exact-snapshot-bound in v5',
64
+ },
65
+ ]);
66
+ const CHECK_IDS = Object.freeze([
67
+ 'behavior_artifact_set',
68
+ 'exact_artifact_set',
69
+ 'canonical_payloads',
70
+ 'input_identity',
71
+ 'evidence_campaign',
72
+ 'compiler_replay',
73
+ 'transform_binding',
74
+ 'plan_diff_binding',
75
+ 'comparison_binding',
76
+ 'hypothesis_evaluation',
77
+ 'execution_evidence',
78
+ 'result_binding',
79
+ ]);
80
+
81
+ function compiledPaths() {
82
+ const paths = [];
83
+ for (const condition of ['control', 'treatment']) {
84
+ for (const variant of ['normal', 'negative']) {
85
+ const root = `compiled/${condition}-${variant}`;
86
+ paths.push(
87
+ `${root}/boundary-manifest.json`,
88
+ `${root}/boundary-verdict.json`,
89
+ `${root}/plan.json`,
90
+ );
91
+ }
92
+ }
93
+ return paths;
94
+ }
95
+
96
+ const EXPECTED_PATHS = Object.freeze([
97
+ ...Object.values(INPUT_PATHS),
98
+ ...EVIDENCE_PATHS.map(([, runId]) => `evidence/${runId}.json`),
99
+ ...compiledPaths(),
100
+ 'behavior/pre-receipt.json',
101
+ 'behavior/post-receipt.json',
102
+ 'behavior/evidence-envelope.json',
103
+ 'transform/transform-artifact.json',
104
+ 'transform/transform-receipt.json',
105
+ 'transform/seam.patch',
106
+ 'plan-diff.json',
107
+ 'comparison.json',
108
+ 'hypothesis-evaluation.json',
109
+ 'execution-evidence.json',
110
+ ].sort());
111
+
112
+ function isPlainObject(value) {
113
+ return value !== null
114
+ && typeof value === 'object'
115
+ && !Array.isArray(value)
116
+ && Object.getPrototypeOf(value) === Object.prototype;
117
+ }
118
+
119
+ function exactRecord(value, keys) {
120
+ if (!isPlainObject(value)) return false;
121
+ const actual = Object.keys(value).sort();
122
+ const expected = [...keys].sort();
123
+ return actual.length === expected.length
124
+ && actual.every((key, index) => key === expected[index]);
125
+ }
126
+
127
+ function sameArray(left, right) {
128
+ return Array.isArray(left)
129
+ && Array.isArray(right)
130
+ && left.length === right.length
131
+ && left.every((entry, index) => entry === right[index]);
132
+ }
133
+
134
+ function sameArtifact(left, right) {
135
+ try {
136
+ return digestArtifact(left) === digestArtifact(right);
137
+ } catch {
138
+ return false;
139
+ }
140
+ }
141
+
142
+ function sha256(value) {
143
+ return createHash('sha256').update(value).digest('hex');
144
+ }
145
+
146
+ function parseJson(bytes) {
147
+ try {
148
+ const value = JSON.parse(bytes.toString('utf8'));
149
+ return Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8').equals(bytes)
150
+ ? value
151
+ : null;
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
156
+
157
+ function payloadMap(payloads) {
158
+ if (!Array.isArray(payloads)) return null;
159
+ const map = new Map();
160
+ for (const payload of payloads) {
161
+ if (!exactRecord(payload, ['path', 'bytes'])
162
+ || typeof payload.path !== 'string'
163
+ || !Buffer.isBuffer(payload.bytes)
164
+ || map.has(payload.path)) {
165
+ return null;
166
+ }
167
+ map.set(payload.path, payload.bytes);
168
+ }
169
+ return map;
170
+ }
171
+
172
+ function exactArtifactSet(options) {
173
+ if (!exactRecord(options, ['manifest', 'payloads'])) return false;
174
+ const payloads = payloadMap(options.payloads);
175
+ const manifestPaths = Array.isArray(options.manifest?.files)
176
+ ? options.manifest.files.map(({ path }) => path).sort()
177
+ : [];
178
+ const payloadPaths = payloads ? [...payloads.keys()].sort() : [];
179
+ return sameArray(manifestPaths, EXPECTED_PATHS)
180
+ && sameArray(payloadPaths, EXPECTED_PATHS);
181
+ }
182
+
183
+ function artifactContext(options) {
184
+ if (!exactArtifactSet(options)) return null;
185
+ const payloads = payloadMap(options.payloads);
186
+ const json = new Map();
187
+ for (const relativePath of EXPECTED_PATHS) {
188
+ if (!relativePath.endsWith('.json')) continue;
189
+ const parsed = parseJson(payloads.get(relativePath));
190
+ if (parsed === null) return null;
191
+ json.set(relativePath, parsed);
192
+ }
193
+ const patch = payloads.get('transform/seam.patch');
194
+ if (!Buffer.isBuffer(patch) || patch.byteLength === 0) return null;
195
+ return { manifest: options.manifest, payloads, json, patch };
196
+ }
197
+
198
+ function fixedInputs(context) {
199
+ return Object.fromEntries(Object.entries(INPUT_PATHS).map(([key, relativePath]) => (
200
+ [key, context.json.get(relativePath)]
201
+ )));
202
+ }
203
+
204
+ function fixedInputIdentity(inputs) {
205
+ return {
206
+ plan_input: digestArtifact(inputs.planInput),
207
+ candidate_spec: digestArtifact(inputs.candidateSpec),
208
+ normal_manual_evidence: digestArtifact(inputs.normalManualEvidence),
209
+ negative_manual_evidence: digestArtifact(inputs.negativeManualEvidence),
210
+ query_set: digestArtifact(inputs.querySet),
211
+ capacity_writers: inputs.planInput.capacity.writers,
212
+ behavior_oracle: digestArtifact(inputs.oracle),
213
+ };
214
+ }
215
+
216
+ function evidenceBundles(context) {
217
+ return EVIDENCE_PATHS.map(([, runId]) => context.json.get(`evidence/${runId}.json`));
218
+ }
219
+
220
+ function decodeRawEvidence(bundle) {
221
+ const receipt = bundle.raw;
222
+ const bytes = Buffer.from(receipt.payload_base64, 'base64');
223
+ if (bytes.toString('base64') !== receipt.payload_base64
224
+ || bytes.byteLength !== receipt.canonical_bytes
225
+ || sha256(bytes) !== receipt.payload_digest) {
226
+ throw new TypeError('RC1 v5 raw evidence receipt bytes are invalid');
227
+ }
228
+ const value = JSON.parse(bytes.toString('utf8'));
229
+ if (canonicalizeArtifact(value) !== bytes.toString('utf8')) {
230
+ throw new TypeError('RC1 v5 raw evidence receipt is not canonical');
231
+ }
232
+ return value;
233
+ }
234
+
235
+ function inputIdentityValid(context) {
236
+ const inputs = fixedInputs(context);
237
+ for (const value of Object.values(inputs)) canonicalizeArtifact(value);
238
+ if (!validatePlanInput(inputs.planInput)
239
+ || !validateRc1BlackBoxOracle(inputs.oracle)) {
240
+ return false;
241
+ }
242
+ const queryDigest = digestArtifact(inputs.querySet);
243
+ const bundles = evidenceBundles(context);
244
+ const execution = context.json.get('execution-evidence.json');
245
+ return sameArtifact(execution.fixed_inputs, fixedInputIdentity(inputs))
246
+ && bundles.every((bundle) => bundle.query_set_digest === queryDigest
247
+ && sameArtifact(bundle.query_set, inputs.querySet));
248
+ }
249
+
250
+ function evidenceCampaignValid(context) {
251
+ const inputs = fixedInputs(context);
252
+ const bundles = evidenceBundles(context);
253
+ return validateRc1EvidenceCampaign(bundles)
254
+ && EVIDENCE_PATHS.every(([condition, runId], index) => {
255
+ const bundle = bundles[index];
256
+ return validateRc1EvidenceBundle(bundle)
257
+ && bundle.condition === condition
258
+ && bundle.run_id === runId
259
+ && sameArtifact(bundle.query_set, inputs.querySet)
260
+ && recomputePortableAggregate(bundle.portable) === bundle.portable.aggregate_digest;
261
+ });
262
+ }
263
+
264
+ function storedCompilation(context, condition, variant) {
265
+ const root = `compiled/${condition}-${variant}`;
266
+ const boundaryManifest = context.json.get(`${root}/boundary-manifest.json`);
267
+ const boundaryVerdict = context.json.get(`${root}/boundary-verdict.json`);
268
+ const planGraph = context.json.get(`${root}/plan.json`);
269
+ const manifestDigest = digestArtifact(boundaryManifest);
270
+ const verdictDigest = digestArtifact(boundaryVerdict);
271
+ const planDigest = digestArtifact(planGraph);
272
+ if (!validateBoundaryManifest(boundaryManifest)
273
+ || !validateBoundaryVerdict(boundaryVerdict)
274
+ || !validatePlanGraph(planGraph)
275
+ || boundaryVerdict.boundary_manifest_digest !== manifestDigest
276
+ || planGraph.source_manifest_digest !== manifestDigest) {
277
+ throw new TypeError(`RC1 v5 stored ${condition}/${variant} compilation is invalid`);
278
+ }
279
+ return {
280
+ boundary_manifest: boundaryManifest,
281
+ boundary_manifest_digest: manifestDigest,
282
+ boundary_verdict: boundaryVerdict,
283
+ boundary_verdict_digest: verdictDigest,
284
+ plan_graph: planGraph,
285
+ plan_graph_digest: planDigest,
286
+ };
287
+ }
288
+
289
+ function storedCompilations(context) {
290
+ return Object.fromEntries(['control', 'treatment'].map((condition) => [
291
+ condition,
292
+ Object.fromEntries(['normal', 'negative'].map((variant) => [
293
+ variant,
294
+ storedCompilation(context, condition, variant),
295
+ ])),
296
+ ]));
297
+ }
298
+
299
+ function compilerReplayValid(context) {
300
+ const inputs = fixedInputs(context);
301
+ const execution = context.json.get('execution-evidence.json');
302
+ const stored = storedCompilations(context);
303
+ for (const [condition, runId] of EVIDENCE_PATHS) {
304
+ const bundle = context.json.get(`evidence/${runId}.json`);
305
+ const run = execution.runs?.[condition]?.find(({ run_id: id }) => id === runId);
306
+ if (!run || !SHA256.test(run.code_snapshot_digest)) return false;
307
+ const rawEvidence = decodeRawEvidence(bundle);
308
+ for (const variant of ['normal', 'negative']) {
309
+ const replay = compileBoundaryCondition({
310
+ planInput: inputs.planInput,
311
+ candidateSpec: inputs.candidateSpec,
312
+ manualEvidence: variant === 'normal'
313
+ ? inputs.normalManualEvidence
314
+ : inputs.negativeManualEvidence,
315
+ querySet: inputs.querySet,
316
+ sensorEvidence: rawEvidence,
317
+ codeSnapshotDigest: run.code_snapshot_digest,
318
+ planVersion: `rc1-v5-${condition}${variant === 'negative' ? '-negative' : ''}`,
319
+ });
320
+ const expected = stored[condition][variant];
321
+ if (!sameArtifact(replay.boundary_manifest, expected.boundary_manifest)
322
+ || !sameArtifact(replay.boundary_verdict, expected.boundary_verdict)
323
+ || !sameArtifact(replay.plan_graph, expected.plan_graph)
324
+ || replay.boundary_manifest_digest !== expected.boundary_manifest_digest
325
+ || replay.boundary_verdict_digest !== expected.boundary_verdict_digest
326
+ || replay.plan_graph_digest !== expected.plan_graph_digest
327
+ || replay.candidate_spec_digest !== digestArtifact(inputs.candidateSpec)) {
328
+ return false;
329
+ }
330
+ }
331
+ }
332
+ return true;
333
+ }
334
+
335
+ function behaviorEvidence(context) {
336
+ return {
337
+ pre_receipt: context.json.get('behavior/pre-receipt.json'),
338
+ post_receipt: context.json.get('behavior/post-receipt.json'),
339
+ envelope: context.json.get('behavior/evidence-envelope.json'),
340
+ transform_artifact: context.json.get('transform/transform-artifact.json'),
341
+ patch_digest: sha256(context.patch),
342
+ };
343
+ }
344
+
345
+ function transformResult(context) {
346
+ const artifact = context.json.get('transform/transform-artifact.json');
347
+ const receipt = context.json.get('transform/transform-receipt.json');
348
+ return {
349
+ artifact,
350
+ artifact_digest: digestArtifact(artifact),
351
+ receipt,
352
+ receipt_digest: receipt.receipt_digest,
353
+ patch: context.patch,
354
+ behavior_evidence: behaviorEvidence(context),
355
+ };
356
+ }
357
+
358
+ function sourceBindings(compiled, querySet) {
359
+ return {
360
+ boundary_manifest_digest: compiled.boundary_manifest_digest,
361
+ boundary_verdict_digest: compiled.boundary_verdict_digest,
362
+ control_plan_digest: compiled.plan_graph_digest,
363
+ query_set_digest: digestArtifact(querySet),
364
+ };
365
+ }
366
+
367
+ function transformReceiptValid(transform, inputs) {
368
+ const receipt = transform.receipt;
369
+ if (!exactRecord(receipt, [
370
+ 'schema',
371
+ 'status',
372
+ 'transform_artifact_digest',
373
+ 'behavior_envelope_digest',
374
+ 'fixed_inputs_digest',
375
+ 'source_invariant',
376
+ 'receipt_digest',
377
+ ])
378
+ || receipt.schema !== 'lattice.rc1.seam_transform_receipt.v5'
379
+ || receipt.status !== 'accepted'
380
+ || receipt.source_invariant?.outcome !== 'passed') {
381
+ return false;
382
+ }
383
+ const { receipt_digest: ignored, ...preimage } = receipt;
384
+ const artifact = transform.artifact;
385
+ const bindings = {
386
+ boundary_manifest_digest: artifact.source.boundary_manifest_digest,
387
+ boundary_verdict_digest: artifact.source.boundary_verdict_digest,
388
+ control_plan_digest: artifact.source.control_plan_digest,
389
+ query_set_digest: artifact.source.query_set_digest,
390
+ };
391
+ const verifiers = artifact.verification.receipts.map(({ id, command, args }) => ({
392
+ id,
393
+ command,
394
+ args,
395
+ }));
396
+ const fixedDigest = digestArtifact({
397
+ candidate_id: artifact.candidate_id,
398
+ allowed_paths: artifact.scope.allowed_paths,
399
+ verifiers,
400
+ oracle_digest: digestArtifact(inputs.oracle),
401
+ source_bindings: bindings,
402
+ });
403
+ return SHA256.test(receipt.receipt_digest)
404
+ && receipt.receipt_digest === digestArtifact(preimage)
405
+ && receipt.transform_artifact_digest === transform.artifact_digest
406
+ && receipt.behavior_envelope_digest === transform.behavior_evidence.envelope.envelope_digest
407
+ && receipt.fixed_inputs_digest === fixedDigest;
408
+ }
409
+
410
+ function transformBindingValid(context) {
411
+ const inputs = fixedInputs(context);
412
+ const stored = storedCompilations(context);
413
+ const transform = transformResult(context);
414
+ const artifact = transform.artifact;
415
+ const behavior = transform.behavior_evidence;
416
+ const execution = context.json.get('execution-evidence.json');
417
+ const expectedBindings = sourceBindings(stored.control.normal, inputs.querySet);
418
+ return validateTransformArtifact(artifact)
419
+ && artifact.status === 'accepted'
420
+ && Object.entries(expectedBindings).every(([key, digest]) => artifact.source[key] === digest)
421
+ && artifact.source.base_sha === context.manifest.base_sha
422
+ && artifact.source.code_snapshot_digest === behavior.pre_receipt.surface_digest
423
+ && artifact.patch.digest === sha256(context.patch)
424
+ && artifact.patch.bytes === context.patch.byteLength
425
+ && transform.artifact_digest === behavior.envelope.transform_artifact_digest
426
+ && transform.artifact_digest === digestArtifact(behavior.transform_artifact)
427
+ && transformReceiptValid(transform, inputs)
428
+ && execution.transform?.artifact_digest === transform.artifact_digest
429
+ && execution.transform?.receipt_digest === transform.receipt_digest
430
+ && execution.transform?.patch_digest === artifact.patch.digest
431
+ && execution.transform?.source_invariant_digest
432
+ === digestArtifact(transform.receipt.source_invariant);
433
+ }
434
+
435
+ function compilationSummary(compiled) {
436
+ const conflicts = compiled.boundary_manifest.conflicts;
437
+ return {
438
+ boundary_manifest_digest: compiled.boundary_manifest_digest,
439
+ boundary_verdict_digest: compiled.boundary_verdict_digest,
440
+ plan_graph_digest: compiled.plan_graph_digest,
441
+ verdict: compiled.boundary_verdict.verdicts[0].verdict,
442
+ write_conflicts: conflicts.filter(({ kind }) => kind === 'write_boundary').length,
443
+ test_write_conflicts: conflicts.filter(({ kind, resource }) => (
444
+ kind === 'write_boundary'
445
+ && resource.kind === 'path'
446
+ && resource.target.startsWith('test/')
447
+ )).length,
448
+ state_conflicts: conflicts.filter(({ kind }) => kind === 'state').length,
449
+ hard_precedence: compiled.boundary_manifest.todos
450
+ .reduce((count, todo) => count + todo.hard_needs.length, 0),
451
+ unknowns: compiled.boundary_manifest.unknowns.length,
452
+ minimum_feasible_waves: compiled.plan_graph.minimum_feasible_waves,
453
+ };
454
+ }
455
+
456
+ function expectedPlanDiff(context) {
457
+ const stored = storedCompilations(context);
458
+ const transform = transformResult(context);
459
+ const control = compilationSummary(stored.control.normal);
460
+ const treatment = compilationSummary(stored.treatment.normal);
461
+ return {
462
+ schema: 'lattice.plan_diff.v2',
463
+ old_plan: {
464
+ version: stored.control.normal.plan_graph.plan_version,
465
+ digest: stored.control.normal.plan_graph_digest,
466
+ },
467
+ new_plan: {
468
+ version: stored.treatment.normal.plan_graph.plan_version,
469
+ digest: stored.treatment.normal.plan_graph_digest,
470
+ },
471
+ causal_predecessor: {
472
+ plan_version: 'lattice-research-campaign-1-v4',
473
+ decision_ref: 'docs/adr/0022-rc1-v4-phase-gate-rejection.md',
474
+ status: 'phase_rejected',
475
+ },
476
+ transform: {
477
+ status: transform.artifact.status,
478
+ artifact_digest: transform.artifact_digest,
479
+ receipt_digest: transform.receipt_digest,
480
+ patch_digest: transform.artifact.patch.digest,
481
+ changed_paths: [...transform.artifact.scope.changed_paths],
482
+ },
483
+ nodes: {
484
+ added: [],
485
+ removed: [],
486
+ changed: stored.control.normal.plan_graph.nodes.map(({ id }) => id),
487
+ },
488
+ edges: {
489
+ added: stored.treatment.normal.plan_graph.edges.map(({ id }) => id),
490
+ removed: stored.control.normal.plan_graph.edges.map(({ id }) => id),
491
+ },
492
+ invalidated_contexts: structuredClone(INVALIDATED_CONTEXTS),
493
+ metrics: {
494
+ write_conflicts_before: control.write_conflicts,
495
+ write_conflicts_after: treatment.write_conflicts,
496
+ test_write_conflicts_before: control.test_write_conflicts,
497
+ test_write_conflicts_after: treatment.test_write_conflicts,
498
+ hard_precedence_before: control.hard_precedence,
499
+ hard_precedence_after: treatment.hard_precedence,
500
+ minimum_feasible_waves_before: control.minimum_feasible_waves,
501
+ minimum_feasible_waves_after: treatment.minimum_feasible_waves,
502
+ },
503
+ };
504
+ }
505
+
506
+ function planDiffBindingValid(context) {
507
+ return sameArtifact(context.json.get('plan-diff.json'), expectedPlanDiff(context));
508
+ }
509
+
510
+ function evidenceSummary(bundles, querySet) {
511
+ return {
512
+ portable_preimages_complete: bundles.length === 2 && bundles.every((bundle) => (
513
+ validateRc1EvidenceBundle(bundle)
514
+ && bundle.portable.outcomes.length === querySet.queries.length
515
+ && bundle.portable.per_query.length === querySet.queries.length
516
+ )),
517
+ digests_recomputed: bundles.every((bundle) => (
518
+ recomputePortableAggregate(bundle.portable) === bundle.portable.aggregate_digest
519
+ )),
520
+ diagnostics_sanitized: bundles.every((bundle) => (
521
+ validateRc1EvidenceBundle(bundle)
522
+ && bundle.diagnostic.payload.cwd === '<repo-root>'
523
+ && bundle.diagnostic.sanitization_manifest.schema
524
+ === 'lattice.sensor_sanitization_manifest.v1'
525
+ )),
526
+ };
527
+ }
528
+
529
+ function transformReceiptSelfValid(transform) {
530
+ const receipt = transform.receipt;
531
+ if (!exactRecord(receipt, [
532
+ 'schema',
533
+ 'status',
534
+ 'transform_artifact_digest',
535
+ 'behavior_envelope_digest',
536
+ 'fixed_inputs_digest',
537
+ 'source_invariant',
538
+ 'receipt_digest',
539
+ ])) return false;
540
+ const { receipt_digest: ignored, ...preimage } = receipt;
541
+ return receipt.schema === 'lattice.rc1.seam_transform_receipt.v5'
542
+ && receipt.status === 'accepted'
543
+ && receipt.receipt_digest === digestArtifact(preimage)
544
+ && transform.receipt_digest === receipt.receipt_digest;
545
+ }
546
+
547
+ function fixedInputsBound(transform, bindings, baseSha) {
548
+ const behavior = transform.behavior_evidence;
549
+ return transform.artifact.status === 'accepted'
550
+ && Object.entries(bindings).every(([key, digest]) => transform.artifact.source[key] === digest)
551
+ && transform.artifact.source.base_sha === baseSha
552
+ && transform.artifact.source.code_snapshot_digest === behavior.pre_receipt.surface_digest
553
+ && transform.artifact_digest === digestArtifact(transform.artifact)
554
+ && transform.receipt.transform_artifact_digest === transform.artifact_digest
555
+ && transform.receipt.behavior_envelope_digest === behavior.envelope.envelope_digest
556
+ && transform.artifact.patch.digest === behavior.patch_digest
557
+ && digestArtifact(behavior.transform_artifact) === transform.artifact_digest
558
+ && transformReceiptSelfValid(transform);
559
+ }
560
+
561
+ function sourceInvariantState(context) {
562
+ const execution = context.json.get('execution-evidence.json');
563
+ return {
564
+ control: execution.runs.control.every(({ source_invariant: receipt }) => (
565
+ receipt?.outcome === 'passed'
566
+ )),
567
+ treatment: context.json.get('transform/transform-receipt.json').source_invariant?.outcome
568
+ === 'passed'
569
+ && execution.runs.treatment.every(({ source_invariant: receipt }) => (
570
+ receipt?.outcome === 'passed'
571
+ )),
572
+ };
573
+ }
574
+
575
+ function expectedComparison(context) {
576
+ const inputs = fixedInputs(context);
577
+ const stored = storedCompilations(context);
578
+ const bundles = evidenceBundles(context);
579
+ const transform = transformResult(context);
580
+ const planDiff = expectedPlanDiff(context);
581
+ const sourceInvariant = sourceInvariantState(context);
582
+ const fixed = fixedInputIdentity(inputs);
583
+ const bindings = sourceBindings(stored.control.normal, inputs.querySet);
584
+ return {
585
+ schema: 'lattice.rc1.control_treatment_comparison.v3',
586
+ fixed_inputs: { control: fixed, treatment: structuredClone(fixed) },
587
+ independent_variable: {
588
+ kind: 'accepted_production_and_test_seam',
589
+ transform_artifact_digest: transform.artifact_digest,
590
+ transform_receipt_digest: transform.receipt_digest,
591
+ patch_digest: transform.artifact.patch.digest,
592
+ },
593
+ compiler: {
594
+ condition_selector: RC1_BOUNDARY_COMPILER_CONTRACT.condition_selector,
595
+ control: {
596
+ export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
597
+ source_digest: CURRENT_COMPILER_SOURCE_DIGEST,
598
+ },
599
+ treatment: {
600
+ export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
601
+ source_digest: CURRENT_COMPILER_SOURCE_DIGEST,
602
+ },
603
+ },
604
+ control: compilationSummary(stored.control.normal),
605
+ treatment: compilationSummary(stored.treatment.normal),
606
+ negative_control: compilationSummary(stored.control.negative),
607
+ negative_treatment: compilationSummary(stored.treatment.negative),
608
+ behavior: {
609
+ evidence_envelope_digest: transform.behavior_evidence.envelope.envelope_digest,
610
+ },
611
+ evidence: {
612
+ control: evidenceSummary(bundles.filter(({ condition }) => condition === 'control'), inputs.querySet),
613
+ treatment: evidenceSummary(
614
+ bundles.filter(({ condition }) => condition === 'treatment'),
615
+ inputs.querySet,
616
+ ),
617
+ },
618
+ predecessor: {
619
+ transform_status: transform.artifact.status,
620
+ same_base: transform.artifact.source.base_sha === context.manifest.base_sha,
621
+ fixed_inputs_bound: fixedInputsBound(transform, bindings, context.manifest.base_sha),
622
+ },
623
+ version_barrier: {
624
+ old_plan: planDiff.old_plan,
625
+ new_plan: planDiff.new_plan,
626
+ plan_diff_digest: digestArtifact(planDiff),
627
+ invalidated_contexts: planDiff.invalidated_contexts.map(({ kind, ref }) => ({ kind, ref })),
628
+ },
629
+ source_invariant: {
630
+ control: sourceInvariant.control ? 'passed' : 'failed',
631
+ treatment: sourceInvariant.treatment ? 'passed' : 'failed',
632
+ },
633
+ };
634
+ }
635
+
636
+ function comparisonBindingValid(context) {
637
+ return sameArtifact(context.json.get('comparison.json'), expectedComparison(context));
638
+ }
639
+
640
+ function hypothesisEvaluationValid(context) {
641
+ const actual = context.json.get('hypothesis-evaluation.json');
642
+ const expected = evaluateRc1V5Hypothesis({
643
+ comparison: context.json.get('comparison.json'),
644
+ behaviorEvidence: behaviorEvidence(context),
645
+ });
646
+ return sameArtifact(actual, expected);
647
+ }
648
+
649
+ function compilationDigests(condition) {
650
+ return Object.fromEntries(['normal', 'negative'].map((variant) => [variant, {
651
+ boundary_manifest: condition[variant].boundary_manifest_digest,
652
+ boundary_verdict: condition[variant].boundary_verdict_digest,
653
+ plan_graph: condition[variant].plan_graph_digest,
654
+ }]));
655
+ }
656
+
657
+ function bundleDescriptorDigest(bundle) {
658
+ return digestArtifact({
659
+ schema: bundle.schema,
660
+ condition: bundle.condition,
661
+ run_id: bundle.run_id,
662
+ query_set_digest: bundle.query_set_digest,
663
+ component_digests: bundle.component_digests,
664
+ });
665
+ }
666
+
667
+ function nonNegativeMilliseconds(value) {
668
+ return Number.isFinite(value) && value >= 0;
669
+ }
670
+
671
+ function runEvidenceValid(context, condition, run, bundle, transformPatchDigest) {
672
+ return exactRecord(run, [
673
+ 'run_id',
674
+ 'condition',
675
+ 'index_elapsed_ms',
676
+ 'query_elapsed_ms',
677
+ 'code_snapshot_digest',
678
+ 'raw_digest',
679
+ 'diagnostic_digest',
680
+ 'portable_digest',
681
+ 'bundle_descriptor_digest',
682
+ 'patch_digest',
683
+ 'source_invariant',
684
+ 'source_invariant_digest',
685
+ ])
686
+ && run.run_id === bundle.run_id
687
+ && run.condition === condition
688
+ && nonNegativeMilliseconds(run.index_elapsed_ms)
689
+ && nonNegativeMilliseconds(run.query_elapsed_ms)
690
+ && SHA256.test(run.code_snapshot_digest)
691
+ && run.raw_digest === bundle.raw.payload_digest
692
+ && run.diagnostic_digest === bundle.diagnostic.payload_digest
693
+ && run.portable_digest === bundle.portable.aggregate_digest
694
+ && run.bundle_descriptor_digest === bundleDescriptorDigest(bundle)
695
+ && run.patch_digest === (condition === 'treatment' ? transformPatchDigest : null)
696
+ && run.source_invariant?.outcome === 'passed'
697
+ && run.source_invariant_digest === digestArtifact(run.source_invariant);
698
+ }
699
+
700
+ function executionEvidenceValid(context) {
701
+ const execution = context.json.get('execution-evidence.json');
702
+ const inputs = fixedInputs(context);
703
+ const bundles = evidenceBundles(context);
704
+ const stored = storedCompilations(context);
705
+ const transform = transformResult(context);
706
+ const planDiff = context.json.get('plan-diff.json');
707
+ const comparison = context.json.get('comparison.json');
708
+ const evaluation = context.json.get('hypothesis-evaluation.json');
709
+ if (!exactRecord(execution, [
710
+ 'schema',
711
+ 'base_sha',
712
+ 'elapsed_ms',
713
+ 'compiler',
714
+ 'fixed_inputs',
715
+ 'runs',
716
+ 'transform',
717
+ 'behavior',
718
+ 'compilations',
719
+ 'plan_diff_digest',
720
+ 'comparison_digest',
721
+ 'hypothesis_evaluation_digest',
722
+ 'observed_facts',
723
+ ])
724
+ || execution.schema !== 'lattice.rc1.corrected_campaign_execution_evidence.v5'
725
+ || execution.base_sha !== context.manifest.base_sha
726
+ || !nonNegativeMilliseconds(execution.elapsed_ms)
727
+ || !exactRecord(execution.compiler, [
728
+ 'export_name',
729
+ 'source_digest',
730
+ 'campaign_runner_source_digest',
731
+ ])
732
+ || execution.compiler.export_name !== RC1_BOUNDARY_COMPILER_CONTRACT.export_name
733
+ || execution.compiler.source_digest !== CURRENT_COMPILER_SOURCE_DIGEST
734
+ || execution.compiler.campaign_runner_source_digest !== CURRENT_CAMPAIGN_SOURCE_DIGEST
735
+ || !sameArtifact(execution.fixed_inputs, fixedInputIdentity(inputs))
736
+ || !exactRecord(execution.runs, ['control', 'treatment'])) {
737
+ return false;
738
+ }
739
+ for (const condition of ['control', 'treatment']) {
740
+ const conditionBundles = bundles.filter((bundle) => bundle.condition === condition);
741
+ if (!Array.isArray(execution.runs[condition])
742
+ || execution.runs[condition].length !== 2
743
+ || !execution.runs[condition].every((run, index) => runEvidenceValid(
744
+ context,
745
+ condition,
746
+ run,
747
+ conditionBundles[index],
748
+ transform.artifact.patch.digest,
749
+ ))) {
750
+ return false;
751
+ }
752
+ }
753
+ const behavior = transform.behavior_evidence;
754
+ const expectedFacts = {
755
+ evidence_campaign_valid: true,
756
+ compiler_reused: true,
757
+ exact_patch_replayed: true,
758
+ full_behavior_evidence_bound: true,
759
+ source_invariant_passed: true,
760
+ hypothesis_supported: evaluation.supported,
761
+ };
762
+ return exactRecord(execution.transform, [
763
+ 'elapsed_ms',
764
+ 'artifact_digest',
765
+ 'receipt_digest',
766
+ 'patch_digest',
767
+ 'source_invariant_digest',
768
+ ])
769
+ && nonNegativeMilliseconds(execution.transform.elapsed_ms)
770
+ && sameArtifact({
771
+ artifact_digest: execution.transform.artifact_digest,
772
+ receipt_digest: execution.transform.receipt_digest,
773
+ patch_digest: execution.transform.patch_digest,
774
+ source_invariant_digest: execution.transform.source_invariant_digest,
775
+ }, {
776
+ artifact_digest: transform.artifact_digest,
777
+ receipt_digest: transform.receipt_digest,
778
+ patch_digest: transform.artifact.patch.digest,
779
+ source_invariant_digest: digestArtifact(transform.receipt.source_invariant),
780
+ })
781
+ && sameArtifact(execution.behavior, {
782
+ pre_receipt_digest: behavior.pre_receipt.receipt_digest,
783
+ post_receipt_digest: behavior.post_receipt.receipt_digest,
784
+ pre_surface_digest: behavior.pre_receipt.surface_digest,
785
+ post_surface_digest: behavior.post_receipt.surface_digest,
786
+ envelope_digest: behavior.envelope.envelope_digest,
787
+ })
788
+ && sameArtifact(execution.compilations, {
789
+ control: compilationDigests(stored.control),
790
+ treatment: compilationDigests(stored.treatment),
791
+ })
792
+ && execution.plan_diff_digest === digestArtifact(planDiff)
793
+ && execution.comparison_digest === digestArtifact(comparison)
794
+ && execution.hypothesis_evaluation_digest === digestArtifact(evaluation)
795
+ && sameArtifact(execution.observed_facts, expectedFacts);
796
+ }
797
+
798
+ function resultBindingValid(context) {
799
+ const execution = context.json.get('execution-evidence.json');
800
+ const transform = context.json.get('transform/transform-artifact.json');
801
+ const pre = context.json.get('behavior/pre-receipt.json');
802
+ const post = context.json.get('behavior/post-receipt.json');
803
+ const envelope = context.json.get('behavior/evidence-envelope.json');
804
+ return GIT_SHA1.test(context.manifest.base_sha)
805
+ && context.manifest.base_sha === execution.base_sha
806
+ && context.manifest.base_sha === transform.source.base_sha
807
+ && context.manifest.base_sha === pre.base_sha
808
+ && context.manifest.base_sha === post.base_sha
809
+ && context.manifest.base_sha === envelope.base_sha
810
+ && context.manifest.result_digest === envelope.envelope_digest;
811
+ }
812
+
813
+ function safeCheck(callback) {
814
+ try {
815
+ return callback() === true;
816
+ } catch {
817
+ return false;
818
+ }
819
+ }
820
+
821
+ const CURRENT_COMPILER_SOURCE_DIGEST = sha256(
822
+ readFileSync(new URL('./boundary-compiler.mjs', import.meta.url)),
823
+ );
824
+ const CURRENT_CAMPAIGN_SOURCE_DIGEST = sha256(
825
+ readFileSync(new URL('./rc1-v5-campaign.mjs', import.meta.url)),
826
+ );
827
+
828
+ /** 保存済みv5 payloadだけからclosed-loopの全因果cross-bindingを再検証する。 */
829
+ export function verifyRc1V5CampaignArtifactSet(options = {}) {
830
+ const behaviorVerification = verifyRc1V5BehaviorArtifactSet(options);
831
+ const exactSet = safeCheck(() => exactArtifactSet(options));
832
+ const context = exactSet ? artifactContext(options) : null;
833
+ const values = [
834
+ behaviorVerification.valid,
835
+ exactSet,
836
+ context !== null,
837
+ context !== null && safeCheck(() => inputIdentityValid(context)),
838
+ context !== null && safeCheck(() => evidenceCampaignValid(context)),
839
+ context !== null && safeCheck(() => compilerReplayValid(context)),
840
+ context !== null && safeCheck(() => transformBindingValid(context)),
841
+ context !== null && safeCheck(() => planDiffBindingValid(context)),
842
+ context !== null && safeCheck(() => comparisonBindingValid(context)),
843
+ context !== null && safeCheck(() => hypothesisEvaluationValid(context)),
844
+ context !== null && safeCheck(() => executionEvidenceValid(context)),
845
+ context !== null && safeCheck(() => resultBindingValid(context)),
846
+ ];
847
+ const checks = CHECK_IDS.map((id, index) => ({ id, passed: values[index] }));
848
+ const failedConditions = checks.filter(({ passed }) => !passed).map(({ id }) => id);
849
+ return {
850
+ schema: 'lattice.rc1.campaign_artifact_verification.v1',
851
+ valid: failedConditions.length === 0,
852
+ checks,
853
+ failed_conditions: failedConditions,
854
+ };
855
+ }