@quolu/lattice 0.52.0 → 0.52.2

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 (182) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-mcp.mjs +0 -0
  5. package/bin/lattice-scripted-adapter.mjs +0 -0
  6. package/bin/lattice-scripted-worker.mjs +0 -0
  7. package/bin/lattice-work-order-adapter.mjs +0 -0
  8. package/bin/lattice.mjs +0 -0
  9. package/docs/bridge-setup.md +132 -132
  10. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  11. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  12. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  13. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  14. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  15. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  16. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  17. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  18. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  19. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  20. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  21. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  22. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  23. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  24. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  25. package/package.json +103 -103
  26. package/sensor/LICENSE +21 -21
  27. package/sensor/NOTICE +19 -19
  28. package/sensor/dist/bin/lattice-sensor.js +9 -9
  29. package/sensor/dist/db/index.js +24 -24
  30. package/sensor/dist/db/migrations.js +41 -41
  31. package/sensor/dist/db/queries.js +164 -164
  32. package/sensor/dist/db/schema.sql +205 -205
  33. package/sensor/dist/directory.js +5 -5
  34. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  35. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  36. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  49. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  50. package/sensor/dist/mcp/server-instructions.js +95 -95
  51. package/sensor/package.json +56 -56
  52. package/src/artifact-contracts-v2.mjs +325 -325
  53. package/src/artifact-contracts.mjs +895 -895
  54. package/src/boundary-compiler.mjs +712 -712
  55. package/src/boundary-observation-compiler-v2.mjs +344 -344
  56. package/src/bounded-seam.mjs +230 -230
  57. package/src/bridge-address.mjs +107 -107
  58. package/src/bridge-cli.mjs +297 -297
  59. package/src/bridge-config.mjs +346 -346
  60. package/src/bridge-daemon.mjs +378 -378
  61. package/src/bridge-launch-agent.mjs +323 -323
  62. package/src/bridge-registrar.mjs +102 -102
  63. package/src/bridge-server.mjs +376 -376
  64. package/src/cli-help.mjs +308 -308
  65. package/src/cli-stdio.mjs +40 -40
  66. package/src/control-compiler.mjs +532 -532
  67. package/src/dag-chain.mjs +261 -261
  68. package/src/factory-diagnostics.mjs +188 -188
  69. package/src/hash-chain.mjs +76 -76
  70. package/src/hooks-cli.mjs +1057 -1053
  71. package/src/isolation-runner.mjs +409 -409
  72. package/src/node-version-guard.mjs +44 -44
  73. package/src/project-cli.mjs +697 -697
  74. package/src/project-identity.mjs +130 -130
  75. package/src/rc1-black-box-oracle.mjs +906 -906
  76. package/src/rc1-comparison.mjs +154 -154
  77. package/src/rc1-evidence-bundle.mjs +456 -456
  78. package/src/rc1-v4-campaign.mjs +708 -708
  79. package/src/rc1-v4-transform.mjs +467 -467
  80. package/src/rc1-v5-artifact-set.mjs +855 -855
  81. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  82. package/src/rc1-v5-campaign.mjs +797 -797
  83. package/src/rc1-v5-transform.mjs +421 -421
  84. package/src/rc1-v6-artifact-set.mjs +807 -807
  85. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  86. package/src/rc1-v6-campaign.mjs +623 -623
  87. package/src/rc1-v6-causal-binding.mjs +473 -473
  88. package/src/rc1-v6-measurement.mjs +313 -313
  89. package/src/rc2-artifact-set.mjs +1584 -1584
  90. package/src/rc2-campaign.mjs +1506 -1502
  91. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  92. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  93. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  94. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  95. package/src/rc3-actual-dogfood.mjs +652 -652
  96. package/src/rc3-dogfood-scaffold.mjs +315 -315
  97. package/src/rc3-scripted-campaign.mjs +1383 -1383
  98. package/src/rc4-stage1-dogfood.mjs +673 -673
  99. package/src/runtime-adapter-registry.mjs +524 -520
  100. package/src/runtime-cli.mjs +4588 -4584
  101. package/src/runtime-contracts.mjs +824 -824
  102. package/src/runtime-control-store.mjs +604 -600
  103. package/src/runtime-controller-protocol.mjs +587 -587
  104. package/src/runtime-decision-verifier.mjs +701 -701
  105. package/src/runtime-diff-observer.mjs +361 -361
  106. package/src/runtime-direct-os-observer.mjs +301 -301
  107. package/src/runtime-driver-state.mjs +166 -162
  108. package/src/runtime-engine.mjs +779 -779
  109. package/src/runtime-errors.mjs +356 -356
  110. package/src/runtime-event-store.mjs +189 -189
  111. package/src/runtime-front-end.mjs +925 -925
  112. package/src/runtime-gate-store.mjs +481 -477
  113. package/src/runtime-hold-recompile.mjs +916 -916
  114. package/src/runtime-io-sentinel.mjs +391 -391
  115. package/src/runtime-lifecycle-lock.mjs +294 -290
  116. package/src/runtime-managed-supervisor.mjs +1490 -1490
  117. package/src/runtime-multi-epoch-store.mjs +838 -834
  118. package/src/runtime-projection.mjs +269 -269
  119. package/src/runtime-pull-intake.mjs +1192 -1188
  120. package/src/runtime-scripted-adapter-controller.mjs +1160 -1156
  121. package/src/runtime-scripted-executor.mjs +163 -163
  122. package/src/runtime-scripted-worktree.mjs +104 -104
  123. package/src/runtime-seam-resolve.mjs +428 -428
  124. package/src/runtime-seam-treatment.mjs +173 -173
  125. package/src/runtime-socket-owner.mjs +125 -125
  126. package/src/runtime-work-order-contracts.mjs +91 -91
  127. package/src/runtime-work-order-controller.mjs +1171 -1167
  128. package/src/runtime-worktree-executor.mjs +199 -199
  129. package/src/schedulability-compiler-v2.mjs +303 -303
  130. package/src/schedulability-verifier-v2.mjs +317 -317
  131. package/src/seam-apply.mjs +549 -549
  132. package/src/seam-commit-shared.mjs +22 -22
  133. package/src/seam-commit-transform.mjs +81 -81
  134. package/src/seam-commit.mjs +18 -18
  135. package/src/seam-cost.mjs +322 -322
  136. package/src/seam-derivation.mjs +188 -188
  137. package/src/seam-gate.mjs +146 -146
  138. package/src/seam-proposal-contracts.mjs +446 -446
  139. package/src/seam-proposal-queries.mjs +521 -521
  140. package/src/seam-proposal.mjs +2011 -2011
  141. package/src/seam-ref.mjs +33 -33
  142. package/src/seam-rewrite.mjs +286 -286
  143. package/src/seam-transform.mjs +554 -554
  144. package/src/seam-verification.mjs +260 -260
  145. package/src/sensor-adapter.mjs +432 -432
  146. package/src/sensor-cli.mjs +139 -139
  147. package/src/sensor-diff.mjs +661 -661
  148. package/src/sensor-node-runtime.mjs +53 -53
  149. package/src/sensor-runtime.mjs +52 -52
  150. package/src/timestamp-contract.mjs +8 -8
  151. package/src/todo-audit-pending.mjs +91 -91
  152. package/src/todo-chain.mjs +178 -178
  153. package/src/todo-cli.mjs +3141 -3126
  154. package/src/todo-contracts.mjs +728 -728
  155. package/src/todo-dashboard-registry.mjs +573 -573
  156. package/src/todo-dispatch-shape.mjs +190 -190
  157. package/src/todo-gantt-html-independence.mjs +239 -239
  158. package/src/todo-gantt-html-shared.mjs +226 -226
  159. package/src/todo-gantt-html-style.mjs +131 -131
  160. package/src/todo-gantt-html.mjs +248 -248
  161. package/src/todo-gantt-layout.mjs +974 -974
  162. package/src/todo-gantt-live.mjs +361 -361
  163. package/src/todo-gantt-nested.mjs +263 -263
  164. package/src/todo-gantt-presentation.mjs +217 -217
  165. package/src/todo-gantt-scope.mjs +123 -123
  166. package/src/todo-gantt-svg.mjs +353 -353
  167. package/src/todo-independence-contracts.mjs +595 -595
  168. package/src/todo-independence-guidance.mjs +322 -322
  169. package/src/todo-independence.mjs +640 -640
  170. package/src/todo-markdown-renderer.mjs +260 -260
  171. package/src/todo-migration.mjs +448 -448
  172. package/src/todo-narrative-anchor.mjs +130 -130
  173. package/src/todo-note-store.mjs +629 -625
  174. package/src/todo-parallel-candidates.mjs +114 -114
  175. package/src/todo-revision.mjs +995 -995
  176. package/src/todo-split.mjs +472 -472
  177. package/src/todo-status.mjs +690 -690
  178. package/src/todo-store-git-transaction.mjs +418 -418
  179. package/src/todo-store.mjs +4322 -4314
  180. package/src/treatment-compiler.mjs +728 -728
  181. package/src/treatment-runner.mjs +656 -656
  182. package/src/witness-scaffold.mjs +180 -180
@@ -1,797 +1,797 @@
1
- import { spawn } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import {
4
- lstat,
5
- mkdir,
6
- mkdtemp,
7
- readFile,
8
- rename,
9
- rm,
10
- writeFile,
11
- } from 'node:fs/promises';
12
- import path from 'node:path';
13
- import { performance } from 'node:perf_hooks';
14
-
15
- import {
16
- canonicalizeArtifact,
17
- digestArtifact,
18
- } from './artifact-contracts.mjs';
19
- import {
20
- compileBoundaryCondition,
21
- RC1_BOUNDARY_COMPILER_CONTRACT,
22
- } from './boundary-compiler.mjs';
23
- import { collectSensorEvidence } from './sensor-adapter.mjs';
24
- import { invokeSensorCli } from './sensor-runtime.mjs';
25
- import { runIsolatedTransform } from './isolation-runner.mjs';
26
- import {
27
- createRc1EvidenceBundle,
28
- recomputePortableAggregate,
29
- validateRc1EvidenceBundle,
30
- validateRc1EvidenceCampaign,
31
- } from './rc1-evidence-bundle.mjs';
32
- import {
33
- evaluateRc1V5Hypothesis,
34
- } from './rc1-v5-behavior-evidence.mjs';
35
- import { verifyRc1V5CampaignArtifactSet } from './rc1-v5-artifact-set.mjs';
36
- import {
37
- RC1_V5_TRANSFORM_PATHS,
38
- runRc1V5SeamTransform,
39
- } from './rc1-v5-transform.mjs';
40
-
41
- const ARTIFACT_ROOT = 'research/campaigns/rc1/artifacts/v5';
42
- const SHA256 = /^[0-9a-f]{64}$/;
43
- const GIT_SHA1 = /^[0-9a-f]{40}$/;
44
- const INPUT_KEYS = Object.freeze([
45
- 'planInput',
46
- 'candidateSpec',
47
- 'normalManualEvidence',
48
- 'negativeManualEvidence',
49
- 'querySet',
50
- 'oracle',
51
- ]);
52
- const INVALIDATED_CONTEXTS = Object.freeze([
53
- {
54
- kind: 'old_plan',
55
- ref: 'lattice-research-campaign-1-v4',
56
- reason: 'v4 machine support was rejected by ADR 0022 and cannot receive v5 topology updates',
57
- },
58
- {
59
- kind: 'agent_context',
60
- ref: 'lattice-research-campaign-1-v4-agent-context',
61
- reason: 'v4 agent context admits behavior evidence without full snapshot and patch identity',
62
- },
63
- {
64
- kind: 'partial_patch',
65
- ref: 'lattice-research-campaign-1-v4-partial-patch',
66
- reason: 'patches based on v4 behavior summaries cannot cross the v5 version barrier',
67
- },
68
- {
69
- kind: 'interface_assumption',
70
- ref: 'receipt-reuse-is-behavior-evidence',
71
- reason: 'pre and post receipts must be distinct and exact-snapshot-bound in v5',
72
- },
73
- ]);
74
-
75
- function isPlainObject(value) {
76
- return value !== null
77
- && typeof value === 'object'
78
- && !Array.isArray(value)
79
- && Object.getPrototypeOf(value) === Object.prototype;
80
- }
81
-
82
- function exactRecord(value, keys) {
83
- if (!isPlainObject(value)) return false;
84
- const actual = Object.keys(value).sort();
85
- const expected = [...keys].sort();
86
- return actual.length === expected.length
87
- && actual.every((key, index) => key === expected[index]);
88
- }
89
-
90
- function sha256(value) {
91
- return createHash('sha256').update(value).digest('hex');
92
- }
93
-
94
- function roundedMilliseconds(startedAt) {
95
- return Math.round((performance.now() - startedAt) * 1_000) / 1_000;
96
- }
97
-
98
- function run(command, args, { cwd, input } = {}) {
99
- return new Promise((resolve, reject) => {
100
- const child = spawn(command, args, {
101
- cwd,
102
- shell: false,
103
- stdio: ['pipe', 'pipe', 'pipe'],
104
- env: { ...process.env, NO_COLOR: '1' },
105
- });
106
- const stdout = [];
107
- const stderr = [];
108
- child.stdout.on('data', (chunk) => stdout.push(chunk));
109
- child.stderr.on('data', (chunk) => stderr.push(chunk));
110
- child.once('error', reject);
111
- child.once('close', (code, signal) => {
112
- const result = {
113
- code,
114
- signal,
115
- stdout: Buffer.concat(stdout),
116
- stderr: Buffer.concat(stderr),
117
- };
118
- if (code === 0 && signal === null) resolve(result);
119
- else reject(Object.assign(
120
- new Error(`${command} failed (${signal ?? code}): ${result.stderr.toString('utf8').trim()}`),
121
- result,
122
- ));
123
- });
124
- child.stdin.end(input);
125
- });
126
- }
127
-
128
- async function fixedSnapshot(repoRoot) {
129
- const files = [];
130
- for (const relativePath of RC1_V5_TRANSFORM_PATHS) {
131
- const absolutePath = path.join(repoRoot, relativePath);
132
- try {
133
- const stat = await lstat(absolutePath);
134
- if (!stat.isFile()) throw new TypeError(`RC1 v5 snapshot path is not a file: ${relativePath}`);
135
- files.push({
136
- path: relativePath,
137
- state: 'file',
138
- content_digest: sha256(await readFile(absolutePath)),
139
- });
140
- } catch (error) {
141
- if (error?.code !== 'ENOENT') throw error;
142
- files.push({ path: relativePath, state: 'missing', content_digest: null });
143
- }
144
- }
145
- const value = { schema: 'lattice.rc1.fixed_surface_snapshot.v5', files };
146
- return { ...value, digest: digestArtifact(value) };
147
- }
148
-
149
- async function applyAcceptedPatch(worktreePath, patch) {
150
- await run('git', ['apply', '--check', '--binary', '-'], { cwd: worktreePath, input: patch });
151
- await run('git', ['apply', '--binary', '-'], { cwd: worktreePath, input: patch });
152
- }
153
-
154
- async function captureLatticeSensorBootstrap(worktreePath) {
155
- try {
156
- return await readFile(path.join(worktreePath, '.lattice/sensor', '.gitignore'));
157
- } catch (error) {
158
- if (error?.code === 'ENOENT') return null;
159
- throw error;
160
- }
161
- }
162
-
163
- async function restoreLatticeSensorBootstrap(worktreePath, bootstrap) {
164
- const sensorPath = path.join(worktreePath, '.lattice/sensor');
165
- await rm(sensorPath, { recursive: true, force: true });
166
- if (bootstrap === null) return;
167
- await mkdir(sensorPath, { recursive: true });
168
- await writeFile(path.join(sensorPath, '.gitignore'), bootstrap);
169
- }
170
-
171
- async function observeFreshIndex({
172
- repoRoot,
173
- baseRef,
174
- condition,
175
- runId,
176
- querySet,
177
- patch,
178
- }) {
179
- let rawEvidence;
180
- let snapshot;
181
- let indexElapsedMs;
182
- let queryElapsedMs;
183
- const isolated = await runIsolatedTransform({
184
- repoRoot,
185
- baseRef,
186
- allowedPaths: condition === 'treatment' ? [...RC1_V5_TRANSFORM_PATHS] : [],
187
- transform: async ({ worktreePath }) => {
188
- if (condition === 'treatment') await applyAcceptedPatch(worktreePath, patch);
189
- snapshot = await fixedSnapshot(worktreePath);
190
- const sensorBootstrap = await captureLatticeSensorBootstrap(worktreePath);
191
- try {
192
- const indexStartedAt = performance.now();
193
- await invokeSensorCli(run, ['init', '.'], { cwd: worktreePath });
194
- indexElapsedMs = roundedMilliseconds(indexStartedAt);
195
- const queryStartedAt = performance.now();
196
- rawEvidence = await collectSensorEvidence({ cwd: worktreePath, querySet });
197
- queryElapsedMs = roundedMilliseconds(queryStartedAt);
198
- } finally {
199
- await restoreLatticeSensorBootstrap(worktreePath, sensorBootstrap);
200
- }
201
- },
202
- verifyCommands: [],
203
- });
204
- if (!rawEvidence || !snapshot || isolated.sourceInvariant?.outcome !== 'passed') {
205
- throw new TypeError(`RC1 v5 ${runId} fresh index did not produce complete evidence`);
206
- }
207
- if (condition === 'treatment'
208
- && (!Buffer.isBuffer(patch) || !isolated.patch.equals(patch))) {
209
- throw new TypeError(`RC1 v5 ${runId} did not replay the accepted patch bytes exactly`);
210
- }
211
- const bundle = createRc1EvidenceBundle({ condition, runId, querySet, rawEvidence });
212
- const patchDigest = condition === 'treatment' ? sha256(isolated.patch) : null;
213
- return {
214
- runId,
215
- condition,
216
- rawEvidence,
217
- bundle,
218
- codeSnapshotDigest: snapshot.digest,
219
- sourceInvariant: isolated.sourceInvariant,
220
- patchDigest,
221
- indexElapsedMs,
222
- queryElapsedMs,
223
- };
224
- }
225
-
226
- function compileOne({ inputs, observation, manualEvidence, planVersion }) {
227
- return compileBoundaryCondition({
228
- planInput: inputs.planInput,
229
- candidateSpec: inputs.candidateSpec,
230
- manualEvidence,
231
- querySet: inputs.querySet,
232
- sensorEvidence: observation.rawEvidence,
233
- codeSnapshotDigest: observation.codeSnapshotDigest,
234
- planVersion,
235
- });
236
- }
237
-
238
- function compileCondition(inputs, observations, condition) {
239
- const planVersion = `rc1-v5-${condition}`;
240
- const compiled = observations.map((observation) => ({
241
- normal: compileOne({
242
- inputs,
243
- observation,
244
- manualEvidence: inputs.normalManualEvidence,
245
- planVersion,
246
- }),
247
- negative: compileOne({
248
- inputs,
249
- observation,
250
- manualEvidence: inputs.negativeManualEvidence,
251
- planVersion: `${planVersion}-negative`,
252
- }),
253
- }));
254
- for (const key of ['normal', 'negative']) {
255
- if (digestArtifact(compiled[0][key]) !== digestArtifact(compiled[1][key])) {
256
- throw new TypeError(`RC1 v5 ${condition} ${key} compilation is not reproducible`);
257
- }
258
- }
259
- return compiled[0];
260
- }
261
-
262
- function sourceBindings(control, querySet) {
263
- return {
264
- boundary_manifest_digest: control.boundary_manifest_digest,
265
- boundary_verdict_digest: control.boundary_verdict_digest,
266
- control_plan_digest: control.plan_graph_digest,
267
- query_set_digest: digestArtifact(querySet),
268
- };
269
- }
270
-
271
- function compilationSummary(compiled) {
272
- const conflicts = compiled.boundary_manifest.conflicts;
273
- return {
274
- boundary_manifest_digest: compiled.boundary_manifest_digest,
275
- boundary_verdict_digest: compiled.boundary_verdict_digest,
276
- plan_graph_digest: compiled.plan_graph_digest,
277
- verdict: compiled.boundary_verdict.verdicts[0].verdict,
278
- write_conflicts: conflicts.filter(({ kind }) => kind === 'write_boundary').length,
279
- test_write_conflicts: conflicts.filter(({ kind, resource }) => (
280
- kind === 'write_boundary'
281
- && resource.kind === 'path'
282
- && resource.target.startsWith('test/')
283
- )).length,
284
- state_conflicts: conflicts.filter(({ kind }) => kind === 'state').length,
285
- hard_precedence: compiled.boundary_manifest.todos
286
- .reduce((count, todo) => count + todo.hard_needs.length, 0),
287
- unknowns: compiled.boundary_manifest.unknowns.length,
288
- minimum_feasible_waves: compiled.plan_graph.minimum_feasible_waves,
289
- };
290
- }
291
-
292
- function fixedInputIdentity(inputs) {
293
- return {
294
- plan_input: digestArtifact(inputs.planInput),
295
- candidate_spec: digestArtifact(inputs.candidateSpec),
296
- normal_manual_evidence: digestArtifact(inputs.normalManualEvidence),
297
- negative_manual_evidence: digestArtifact(inputs.negativeManualEvidence),
298
- query_set: digestArtifact(inputs.querySet),
299
- capacity_writers: inputs.planInput.capacity.writers,
300
- behavior_oracle: digestArtifact(inputs.oracle),
301
- };
302
- }
303
-
304
- function evidenceSummary(bundles, querySet) {
305
- return {
306
- portable_preimages_complete: bundles.length === 2 && bundles.every((bundle) => (
307
- validateRc1EvidenceBundle(bundle)
308
- && bundle.portable.outcomes.length === querySet.queries.length
309
- && bundle.portable.per_query.length === querySet.queries.length
310
- )),
311
- digests_recomputed: bundles.every((bundle) => (
312
- recomputePortableAggregate(bundle.portable) === bundle.portable.aggregate_digest
313
- )),
314
- diagnostics_sanitized: bundles.every((bundle) => (
315
- validateRc1EvidenceBundle(bundle)
316
- && bundle.diagnostic.payload.cwd === '<repo-root>'
317
- && bundle.diagnostic.sanitization_manifest.schema
318
- === 'lattice.sensor_sanitization_manifest.v1'
319
- )),
320
- };
321
- }
322
-
323
- function buildPlanDiff(control, treatment, transform) {
324
- const before = compilationSummary(control);
325
- const after = compilationSummary(treatment);
326
- return {
327
- schema: 'lattice.plan_diff.v2',
328
- old_plan: { version: control.plan_graph.plan_version, digest: control.plan_graph_digest },
329
- new_plan: { version: treatment.plan_graph.plan_version, digest: treatment.plan_graph_digest },
330
- causal_predecessor: {
331
- plan_version: 'lattice-research-campaign-1-v4',
332
- decision_ref: 'docs/adr/0022-rc1-v4-phase-gate-rejection.md',
333
- status: 'phase_rejected',
334
- },
335
- transform: {
336
- status: transform.artifact.status,
337
- artifact_digest: transform.artifact_digest,
338
- receipt_digest: transform.receipt_digest,
339
- patch_digest: transform.artifact.patch.digest,
340
- changed_paths: [...transform.artifact.scope.changed_paths],
341
- },
342
- nodes: {
343
- added: [],
344
- removed: [],
345
- changed: control.plan_graph.nodes.map(({ id }) => id),
346
- },
347
- edges: {
348
- added: treatment.plan_graph.edges.map(({ id }) => id),
349
- removed: control.plan_graph.edges.map(({ id }) => id),
350
- },
351
- invalidated_contexts: structuredClone(INVALIDATED_CONTEXTS),
352
- metrics: {
353
- write_conflicts_before: before.write_conflicts,
354
- write_conflicts_after: after.write_conflicts,
355
- test_write_conflicts_before: before.test_write_conflicts,
356
- test_write_conflicts_after: after.test_write_conflicts,
357
- hard_precedence_before: before.hard_precedence,
358
- hard_precedence_after: after.hard_precedence,
359
- minimum_feasible_waves_before: before.minimum_feasible_waves,
360
- minimum_feasible_waves_after: after.minimum_feasible_waves,
361
- },
362
- };
363
- }
364
-
365
- function transformReceiptValid(transform) {
366
- const receipt = transform?.receipt;
367
- if (!exactRecord(receipt, [
368
- 'schema',
369
- 'status',
370
- 'transform_artifact_digest',
371
- 'behavior_envelope_digest',
372
- 'fixed_inputs_digest',
373
- 'source_invariant',
374
- 'receipt_digest',
375
- ])
376
- || receipt.schema !== 'lattice.rc1.seam_transform_receipt.v5'
377
- || receipt.status !== 'accepted'
378
- || !SHA256.test(receipt.transform_artifact_digest)
379
- || !SHA256.test(receipt.behavior_envelope_digest)
380
- || !SHA256.test(receipt.fixed_inputs_digest)
381
- || receipt.source_invariant?.outcome !== 'passed'
382
- || !SHA256.test(receipt.receipt_digest)) {
383
- return false;
384
- }
385
- const { receipt_digest: ignored, ...preimage } = receipt;
386
- return receipt.receipt_digest === digestArtifact(preimage)
387
- && transform.receipt_digest === receipt.receipt_digest;
388
- }
389
-
390
- function fixedInputsBound(transform, bindings, baseSha) {
391
- const behavior = transform.behavior_evidence;
392
- return transform.artifact.status === 'accepted'
393
- && Object.entries(bindings).every(([key, digest]) => transform.artifact.source[key] === digest)
394
- && transform.artifact.source.base_sha === baseSha
395
- && transform.artifact.source.code_snapshot_digest === behavior?.pre_receipt?.surface_digest
396
- && transform.artifact_digest === digestArtifact(transform.artifact)
397
- && transform.receipt.transform_artifact_digest === transform.artifact_digest
398
- && transform.receipt.behavior_envelope_digest === behavior?.envelope?.envelope_digest
399
- && transform.artifact.patch.digest === behavior?.patch_digest
400
- && digestArtifact(behavior?.transform_artifact) === transform.artifact_digest
401
- && transformReceiptValid(transform);
402
- }
403
-
404
- function makeComparison({
405
- inputs,
406
- compilerSourceDigest,
407
- control,
408
- treatment,
409
- controlBundles,
410
- treatmentBundles,
411
- transform,
412
- baseSha,
413
- planDiff,
414
- sourceInvariant,
415
- }) {
416
- const fixed = fixedInputIdentity(inputs);
417
- const bindings = sourceBindings(control.normal, inputs.querySet);
418
- return {
419
- schema: 'lattice.rc1.control_treatment_comparison.v3',
420
- fixed_inputs: { control: fixed, treatment: structuredClone(fixed) },
421
- independent_variable: {
422
- kind: 'accepted_production_and_test_seam',
423
- transform_artifact_digest: transform.artifact_digest,
424
- transform_receipt_digest: transform.receipt_digest,
425
- patch_digest: transform.artifact.patch.digest,
426
- },
427
- compiler: {
428
- condition_selector: RC1_BOUNDARY_COMPILER_CONTRACT.condition_selector,
429
- control: {
430
- export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
431
- source_digest: compilerSourceDigest,
432
- },
433
- treatment: {
434
- export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
435
- source_digest: compilerSourceDigest,
436
- },
437
- },
438
- control: compilationSummary(control.normal),
439
- treatment: compilationSummary(treatment.normal),
440
- negative_control: compilationSummary(control.negative),
441
- negative_treatment: compilationSummary(treatment.negative),
442
- behavior: {
443
- evidence_envelope_digest: transform.behavior_evidence.envelope.envelope_digest,
444
- },
445
- evidence: {
446
- control: evidenceSummary(controlBundles, inputs.querySet),
447
- treatment: evidenceSummary(treatmentBundles, inputs.querySet),
448
- },
449
- predecessor: {
450
- transform_status: transform.artifact.status,
451
- same_base: transform.artifact.source.base_sha === baseSha,
452
- fixed_inputs_bound: fixedInputsBound(transform, bindings, baseSha),
453
- },
454
- version_barrier: {
455
- old_plan: planDiff.old_plan,
456
- new_plan: planDiff.new_plan,
457
- plan_diff_digest: digestArtifact(planDiff),
458
- invalidated_contexts: planDiff.invalidated_contexts.map(({ kind, ref }) => ({ kind, ref })),
459
- },
460
- source_invariant: {
461
- control: sourceInvariant.control ? 'passed' : 'failed',
462
- treatment: sourceInvariant.treatment ? 'passed' : 'failed',
463
- },
464
- };
465
- }
466
-
467
- function runRecord(observation) {
468
- return {
469
- run_id: observation.runId,
470
- condition: observation.condition,
471
- index_elapsed_ms: observation.indexElapsedMs,
472
- query_elapsed_ms: observation.queryElapsedMs,
473
- code_snapshot_digest: observation.codeSnapshotDigest,
474
- raw_digest: observation.bundle.raw.payload_digest,
475
- diagnostic_digest: observation.bundle.diagnostic.payload_digest,
476
- portable_digest: observation.bundle.portable.aggregate_digest,
477
- bundle_descriptor_digest: digestArtifact({
478
- schema: observation.bundle.schema,
479
- condition: observation.bundle.condition,
480
- run_id: observation.bundle.run_id,
481
- query_set_digest: observation.bundle.query_set_digest,
482
- component_digests: observation.bundle.component_digests,
483
- }),
484
- patch_digest: observation.patchDigest,
485
- source_invariant: observation.sourceInvariant,
486
- source_invariant_digest: digestArtifact(observation.sourceInvariant),
487
- };
488
- }
489
-
490
- function compilationDigests(condition) {
491
- return Object.fromEntries(['normal', 'negative'].map((key) => [key, {
492
- boundary_manifest: condition[key].boundary_manifest_digest,
493
- boundary_verdict: condition[key].boundary_verdict_digest,
494
- plan_graph: condition[key].plan_graph_digest,
495
- }]));
496
- }
497
-
498
- function assertInputs(inputs) {
499
- if (!exactRecord(inputs, INPUT_KEYS)) {
500
- throw new TypeError('RC1 v5 campaign inputs must have the fixed exact shape');
501
- }
502
- for (const value of Object.values(inputs)) canonicalizeArtifact(value);
503
- }
504
-
505
- /** fixed RC1 fixtureをfull behavior evidence付きcontrol→transform→treatment再compileで実行する。 */
506
- export async function runRc1V5Campaign(options = {}) {
507
- if (!exactRecord(options, ['repoRoot', 'baseRef', 'inputs'])) {
508
- throw new TypeError('RC1 v5 campaign options must have the fixed exact shape');
509
- }
510
- const { repoRoot, baseRef, inputs } = options;
511
- if (typeof repoRoot !== 'string' || repoRoot.length === 0
512
- || typeof baseRef !== 'string' || baseRef.length === 0) {
513
- throw new TypeError('RC1 v5 campaign repoRoot and baseRef are required');
514
- }
515
- assertInputs(inputs);
516
- const fixedInputs = structuredClone(inputs);
517
- const baseSha = (await run('git', ['rev-parse', '--verify', `${baseRef}^{commit}`], { cwd: repoRoot }))
518
- .stdout.toString('utf8').trim();
519
- if (!GIT_SHA1.test(baseSha)) throw new TypeError('RC1 v5 campaign base SHA is invalid');
520
- const compilerSourceDigest = sha256(await readFile(new URL('./boundary-compiler.mjs', import.meta.url)));
521
- const campaignSourceDigest = sha256(await readFile(new URL('./rc1-v5-campaign.mjs', import.meta.url)));
522
- const startedAt = performance.now();
523
-
524
- const controlObservations = [];
525
- for (const runId of ['control-1', 'control-2']) {
526
- controlObservations.push(await observeFreshIndex({
527
- repoRoot,
528
- baseRef: baseSha,
529
- condition: 'control',
530
- runId,
531
- querySet: fixedInputs.querySet,
532
- }));
533
- }
534
- const control = compileCondition(fixedInputs, controlObservations, 'control');
535
- const bindings = sourceBindings(control.normal, fixedInputs.querySet);
536
- const transformStartedAt = performance.now();
537
- const transform = await runRc1V5SeamTransform({
538
- repoRoot,
539
- baseRef: baseSha,
540
- oracle: fixedInputs.oracle,
541
- sourceBindings: bindings,
542
- });
543
- const transformElapsedMs = roundedMilliseconds(transformStartedAt);
544
- if (transform.artifact.status !== 'accepted'
545
- || transform.receipt.source_invariant?.outcome !== 'passed'
546
- || !Buffer.isBuffer(transform.patch)
547
- || transform.behavior_evidence === null) {
548
- const error = new Error('RC1 v5 accepted transform predecessor was not produced');
549
- error.transform = transform;
550
- throw error;
551
- }
552
-
553
- const treatmentObservations = [];
554
- for (const runId of ['treatment-1', 'treatment-2']) {
555
- const observation = await observeFreshIndex({
556
- repoRoot,
557
- baseRef: baseSha,
558
- condition: 'treatment',
559
- runId,
560
- querySet: fixedInputs.querySet,
561
- patch: transform.patch,
562
- });
563
- if (observation.patchDigest !== transform.artifact.patch.digest) {
564
- throw new TypeError(`${runId} did not apply the exact accepted patch`);
565
- }
566
- treatmentObservations.push(observation);
567
- }
568
- const treatment = compileCondition(fixedInputs, treatmentObservations, 'treatment');
569
- const evidenceBundles = [
570
- ...controlObservations.map(({ bundle }) => bundle),
571
- ...treatmentObservations.map(({ bundle }) => bundle),
572
- ];
573
- if (!validateRc1EvidenceCampaign(evidenceBundles)) {
574
- throw new TypeError('RC1 v5 2+2 evidence campaign is not reproducible');
575
- }
576
-
577
- const sourceInvariant = {
578
- control: controlObservations.every(({ sourceInvariant: receipt }) => receipt.outcome === 'passed'),
579
- treatment: transform.receipt.source_invariant.outcome === 'passed'
580
- && treatmentObservations.every(({ sourceInvariant: receipt }) => receipt.outcome === 'passed'),
581
- };
582
- const planDiff = buildPlanDiff(control.normal, treatment.normal, transform);
583
- const comparison = makeComparison({
584
- inputs: fixedInputs,
585
- compilerSourceDigest,
586
- control,
587
- treatment,
588
- controlBundles: evidenceBundles.filter(({ condition }) => condition === 'control'),
589
- treatmentBundles: evidenceBundles.filter(({ condition }) => condition === 'treatment'),
590
- transform,
591
- baseSha,
592
- planDiff,
593
- sourceInvariant,
594
- });
595
- const hypothesisEvaluation = evaluateRc1V5Hypothesis({
596
- comparison,
597
- behaviorEvidence: transform.behavior_evidence,
598
- });
599
- const conditionRuns = {
600
- control: controlObservations.map(runRecord),
601
- treatment: treatmentObservations.map(runRecord),
602
- };
603
- const behavior = transform.behavior_evidence;
604
- const executionEvidence = {
605
- schema: 'lattice.rc1.corrected_campaign_execution_evidence.v5',
606
- base_sha: baseSha,
607
- elapsed_ms: roundedMilliseconds(startedAt),
608
- compiler: {
609
- export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
610
- source_digest: compilerSourceDigest,
611
- campaign_runner_source_digest: campaignSourceDigest,
612
- },
613
- fixed_inputs: fixedInputIdentity(fixedInputs),
614
- runs: conditionRuns,
615
- transform: {
616
- elapsed_ms: transformElapsedMs,
617
- artifact_digest: transform.artifact_digest,
618
- receipt_digest: transform.receipt_digest,
619
- patch_digest: transform.artifact.patch.digest,
620
- source_invariant_digest: digestArtifact(transform.receipt.source_invariant),
621
- },
622
- behavior: {
623
- pre_receipt_digest: behavior.pre_receipt.receipt_digest,
624
- post_receipt_digest: behavior.post_receipt.receipt_digest,
625
- pre_surface_digest: behavior.pre_receipt.surface_digest,
626
- post_surface_digest: behavior.post_receipt.surface_digest,
627
- envelope_digest: behavior.envelope.envelope_digest,
628
- },
629
- compilations: {
630
- control: compilationDigests(control),
631
- treatment: compilationDigests(treatment),
632
- },
633
- plan_diff_digest: digestArtifact(planDiff),
634
- comparison_digest: digestArtifact(comparison),
635
- hypothesis_evaluation_digest: digestArtifact(hypothesisEvaluation),
636
- observed_facts: {
637
- evidence_campaign_valid: true,
638
- compiler_reused: true,
639
- exact_patch_replayed: true,
640
- full_behavior_evidence_bound: true,
641
- source_invariant_passed: sourceInvariant.control && sourceInvariant.treatment,
642
- hypothesis_supported: hypothesisEvaluation.supported,
643
- },
644
- };
645
- return {
646
- schema: 'lattice.rc1.corrected_campaign_result.v5',
647
- base_sha: baseSha,
648
- inputs: fixedInputs,
649
- evidence_bundles: evidenceBundles,
650
- condition_runs: conditionRuns,
651
- control,
652
- treatment,
653
- transform,
654
- plan_diff: planDiff,
655
- comparison,
656
- hypothesis_evaluation: hypothesisEvaluation,
657
- execution_evidence: executionEvidence,
658
- };
659
- }
660
-
661
- function jsonBytes(value) {
662
- return Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8');
663
- }
664
-
665
- function artifactFiles(result) {
666
- const files = new Map();
667
- for (const [key, relativePath] of [
668
- ['planInput', 'inputs/plan-input.json'],
669
- ['candidateSpec', 'inputs/candidate-spec-v2.json'],
670
- ['normalManualEvidence', 'inputs/manual-evidence.normal.json'],
671
- ['negativeManualEvidence', 'inputs/manual-evidence.shared-state-negative.json'],
672
- ['querySet', 'inputs/query-set-v2.json'],
673
- ['oracle', 'inputs/behavior-oracle-v2.json'],
674
- ]) {
675
- files.set(relativePath, jsonBytes(result.inputs[key]));
676
- }
677
- for (const bundle of result.evidence_bundles) {
678
- files.set(`evidence/${bundle.run_id}.json`, jsonBytes(bundle));
679
- }
680
- for (const [conditionName, condition] of [
681
- ['control', result.control],
682
- ['treatment', result.treatment],
683
- ]) {
684
- for (const [variantName, compiled] of [
685
- ['normal', condition.normal],
686
- ['negative', condition.negative],
687
- ]) {
688
- const root = `compiled/${conditionName}-${variantName}`;
689
- files.set(`${root}/boundary-manifest.json`, jsonBytes(compiled.boundary_manifest));
690
- files.set(`${root}/boundary-verdict.json`, jsonBytes(compiled.boundary_verdict));
691
- files.set(`${root}/plan.json`, jsonBytes(compiled.plan_graph));
692
- }
693
- }
694
- files.set('behavior/pre-receipt.json', jsonBytes(result.transform.behavior_evidence.pre_receipt));
695
- files.set('behavior/post-receipt.json', jsonBytes(result.transform.behavior_evidence.post_receipt));
696
- files.set('behavior/evidence-envelope.json', jsonBytes(result.transform.behavior_evidence.envelope));
697
- files.set('transform/transform-artifact.json', jsonBytes(result.transform.artifact));
698
- files.set('transform/transform-receipt.json', jsonBytes(result.transform.receipt));
699
- files.set('transform/seam.patch', Buffer.from(result.transform.patch));
700
- files.set('plan-diff.json', jsonBytes(result.plan_diff));
701
- files.set('comparison.json', jsonBytes(result.comparison));
702
- files.set('hypothesis-evaluation.json', jsonBytes(result.hypothesis_evaluation));
703
- files.set('execution-evidence.json', jsonBytes(result.execution_evidence));
704
- return files;
705
- }
706
-
707
- function assertWritableResult(result) {
708
- if (!exactRecord(result, [
709
- 'schema',
710
- 'base_sha',
711
- 'inputs',
712
- 'evidence_bundles',
713
- 'condition_runs',
714
- 'control',
715
- 'treatment',
716
- 'transform',
717
- 'plan_diff',
718
- 'comparison',
719
- 'hypothesis_evaluation',
720
- 'execution_evidence',
721
- ])
722
- || result.schema !== 'lattice.rc1.corrected_campaign_result.v5'
723
- || !GIT_SHA1.test(result.base_sha)
724
- || !validateRc1EvidenceCampaign(result.evidence_bundles)
725
- || !Buffer.isBuffer(result.transform?.patch)
726
- || result.transform?.artifact?.status !== 'accepted'
727
- || result.transform?.behavior_evidence === null
728
- || sha256(result.transform.patch) !== result.transform.artifact.patch?.digest
729
- || digestArtifact(result.transform.artifact) !== result.transform.artifact_digest
730
- || !transformReceiptValid(result.transform)
731
- || result.comparison?.schema !== 'lattice.rc1.control_treatment_comparison.v3'
732
- || result.comparison.behavior?.evidence_envelope_digest
733
- !== result.transform.behavior_evidence.envelope?.envelope_digest) {
734
- throw new TypeError('RC1 v5 artifact writer arguments are invalid');
735
- }
736
- const recomputed = evaluateRc1V5Hypothesis({
737
- comparison: result.comparison,
738
- behaviorEvidence: result.transform.behavior_evidence,
739
- });
740
- if (digestArtifact(recomputed) !== digestArtifact(result.hypothesis_evaluation)) {
741
- throw new TypeError('RC1 v5 hypothesis evaluation is not reproducible');
742
- }
743
- }
744
-
745
- /** RC1 v5 full causal artifactを既存treeへ上書きせずatomicに保存する。 */
746
- export async function writeRc1V5Artifacts(options = {}) {
747
- if (!exactRecord(options, ['repoRoot', 'result'])
748
- || typeof options.repoRoot !== 'string' || options.repoRoot.length === 0) {
749
- throw new TypeError('RC1 v5 artifact writer options must have the fixed exact shape');
750
- }
751
- const { repoRoot, result } = options;
752
- assertWritableResult(result);
753
- const artifactRoot = path.join(repoRoot, ARTIFACT_ROOT);
754
- try {
755
- await lstat(artifactRoot);
756
- throw new Error('RC1 v5 artifact root already exists; immutable evidence is not overwritten');
757
- } catch (error) {
758
- if (error?.code !== 'ENOENT') throw error;
759
- }
760
-
761
- const files = artifactFiles(result);
762
- const manifest = {
763
- schema: 'lattice.rc1.artifact_manifest.v5',
764
- base_sha: result.base_sha,
765
- result_digest: result.transform.behavior_evidence.envelope.envelope_digest,
766
- files: [...files].map(([relativePath, bytes]) => ({
767
- path: relativePath,
768
- media_type: relativePath.endsWith('.json') ? 'application/json' : 'text/x-diff',
769
- bytes: bytes.byteLength,
770
- sha256: sha256(bytes),
771
- })).sort((left, right) => left.path.localeCompare(right.path)),
772
- };
773
- const verification = verifyRc1V5CampaignArtifactSet({
774
- manifest,
775
- payloads: [...files].map(([relativePath, bytes]) => ({ path: relativePath, bytes })),
776
- });
777
- if (!verification.valid) {
778
- throw new TypeError(`RC1 v5 campaign artifact set is invalid: ${verification.failed_conditions.join(', ')}`);
779
- }
780
-
781
- const parent = path.dirname(artifactRoot);
782
- await mkdir(parent, { recursive: true });
783
- const temporaryRoot = await mkdtemp(path.join(parent, '.v5-write-'));
784
- try {
785
- for (const [relativePath, bytes] of files) {
786
- const target = path.join(temporaryRoot, relativePath);
787
- await mkdir(path.dirname(target), { recursive: true });
788
- await writeFile(target, bytes);
789
- }
790
- await writeFile(path.join(temporaryRoot, 'artifact-manifest.json'), jsonBytes(manifest));
791
- await rename(temporaryRoot, artifactRoot);
792
- } catch (error) {
793
- await rm(temporaryRoot, { recursive: true, force: true });
794
- throw error;
795
- }
796
- return manifest;
797
- }
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import {
4
+ lstat,
5
+ mkdir,
6
+ mkdtemp,
7
+ readFile,
8
+ rename,
9
+ rm,
10
+ writeFile,
11
+ } from 'node:fs/promises';
12
+ import path from 'node:path';
13
+ import { performance } from 'node:perf_hooks';
14
+
15
+ import {
16
+ canonicalizeArtifact,
17
+ digestArtifact,
18
+ } from './artifact-contracts.mjs';
19
+ import {
20
+ compileBoundaryCondition,
21
+ RC1_BOUNDARY_COMPILER_CONTRACT,
22
+ } from './boundary-compiler.mjs';
23
+ import { collectSensorEvidence } from './sensor-adapter.mjs';
24
+ import { invokeSensorCli } from './sensor-runtime.mjs';
25
+ import { runIsolatedTransform } from './isolation-runner.mjs';
26
+ import {
27
+ createRc1EvidenceBundle,
28
+ recomputePortableAggregate,
29
+ validateRc1EvidenceBundle,
30
+ validateRc1EvidenceCampaign,
31
+ } from './rc1-evidence-bundle.mjs';
32
+ import {
33
+ evaluateRc1V5Hypothesis,
34
+ } from './rc1-v5-behavior-evidence.mjs';
35
+ import { verifyRc1V5CampaignArtifactSet } from './rc1-v5-artifact-set.mjs';
36
+ import {
37
+ RC1_V5_TRANSFORM_PATHS,
38
+ runRc1V5SeamTransform,
39
+ } from './rc1-v5-transform.mjs';
40
+
41
+ const ARTIFACT_ROOT = 'research/campaigns/rc1/artifacts/v5';
42
+ const SHA256 = /^[0-9a-f]{64}$/;
43
+ const GIT_SHA1 = /^[0-9a-f]{40}$/;
44
+ const INPUT_KEYS = Object.freeze([
45
+ 'planInput',
46
+ 'candidateSpec',
47
+ 'normalManualEvidence',
48
+ 'negativeManualEvidence',
49
+ 'querySet',
50
+ 'oracle',
51
+ ]);
52
+ const INVALIDATED_CONTEXTS = Object.freeze([
53
+ {
54
+ kind: 'old_plan',
55
+ ref: 'lattice-research-campaign-1-v4',
56
+ reason: 'v4 machine support was rejected by ADR 0022 and cannot receive v5 topology updates',
57
+ },
58
+ {
59
+ kind: 'agent_context',
60
+ ref: 'lattice-research-campaign-1-v4-agent-context',
61
+ reason: 'v4 agent context admits behavior evidence without full snapshot and patch identity',
62
+ },
63
+ {
64
+ kind: 'partial_patch',
65
+ ref: 'lattice-research-campaign-1-v4-partial-patch',
66
+ reason: 'patches based on v4 behavior summaries cannot cross the v5 version barrier',
67
+ },
68
+ {
69
+ kind: 'interface_assumption',
70
+ ref: 'receipt-reuse-is-behavior-evidence',
71
+ reason: 'pre and post receipts must be distinct and exact-snapshot-bound in v5',
72
+ },
73
+ ]);
74
+
75
+ function isPlainObject(value) {
76
+ return value !== null
77
+ && typeof value === 'object'
78
+ && !Array.isArray(value)
79
+ && Object.getPrototypeOf(value) === Object.prototype;
80
+ }
81
+
82
+ function exactRecord(value, keys) {
83
+ if (!isPlainObject(value)) return false;
84
+ const actual = Object.keys(value).sort();
85
+ const expected = [...keys].sort();
86
+ return actual.length === expected.length
87
+ && actual.every((key, index) => key === expected[index]);
88
+ }
89
+
90
+ function sha256(value) {
91
+ return createHash('sha256').update(value).digest('hex');
92
+ }
93
+
94
+ function roundedMilliseconds(startedAt) {
95
+ return Math.round((performance.now() - startedAt) * 1_000) / 1_000;
96
+ }
97
+
98
+ function run(command, args, { cwd, input } = {}) {
99
+ return new Promise((resolve, reject) => {
100
+ const child = spawn(command, args, {
101
+ cwd,
102
+ shell: false,
103
+ stdio: ['pipe', 'pipe', 'pipe'],
104
+ env: { ...process.env, NO_COLOR: '1' },
105
+ });
106
+ const stdout = [];
107
+ const stderr = [];
108
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
109
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
110
+ child.once('error', reject);
111
+ child.once('close', (code, signal) => {
112
+ const result = {
113
+ code,
114
+ signal,
115
+ stdout: Buffer.concat(stdout),
116
+ stderr: Buffer.concat(stderr),
117
+ };
118
+ if (code === 0 && signal === null) resolve(result);
119
+ else reject(Object.assign(
120
+ new Error(`${command} failed (${signal ?? code}): ${result.stderr.toString('utf8').trim()}`),
121
+ result,
122
+ ));
123
+ });
124
+ child.stdin.end(input);
125
+ });
126
+ }
127
+
128
+ async function fixedSnapshot(repoRoot) {
129
+ const files = [];
130
+ for (const relativePath of RC1_V5_TRANSFORM_PATHS) {
131
+ const absolutePath = path.join(repoRoot, relativePath);
132
+ try {
133
+ const stat = await lstat(absolutePath);
134
+ if (!stat.isFile()) throw new TypeError(`RC1 v5 snapshot path is not a file: ${relativePath}`);
135
+ files.push({
136
+ path: relativePath,
137
+ state: 'file',
138
+ content_digest: sha256(await readFile(absolutePath)),
139
+ });
140
+ } catch (error) {
141
+ if (error?.code !== 'ENOENT') throw error;
142
+ files.push({ path: relativePath, state: 'missing', content_digest: null });
143
+ }
144
+ }
145
+ const value = { schema: 'lattice.rc1.fixed_surface_snapshot.v5', files };
146
+ return { ...value, digest: digestArtifact(value) };
147
+ }
148
+
149
+ async function applyAcceptedPatch(worktreePath, patch) {
150
+ await run('git', ['apply', '--check', '--binary', '-'], { cwd: worktreePath, input: patch });
151
+ await run('git', ['apply', '--binary', '-'], { cwd: worktreePath, input: patch });
152
+ }
153
+
154
+ async function captureLatticeSensorBootstrap(worktreePath) {
155
+ try {
156
+ return await readFile(path.join(worktreePath, '.lattice/sensor', '.gitignore'));
157
+ } catch (error) {
158
+ if (error?.code === 'ENOENT') return null;
159
+ throw error;
160
+ }
161
+ }
162
+
163
+ async function restoreLatticeSensorBootstrap(worktreePath, bootstrap) {
164
+ const sensorPath = path.join(worktreePath, '.lattice/sensor');
165
+ await rm(sensorPath, { recursive: true, force: true });
166
+ if (bootstrap === null) return;
167
+ await mkdir(sensorPath, { recursive: true });
168
+ await writeFile(path.join(sensorPath, '.gitignore'), bootstrap);
169
+ }
170
+
171
+ async function observeFreshIndex({
172
+ repoRoot,
173
+ baseRef,
174
+ condition,
175
+ runId,
176
+ querySet,
177
+ patch,
178
+ }) {
179
+ let rawEvidence;
180
+ let snapshot;
181
+ let indexElapsedMs;
182
+ let queryElapsedMs;
183
+ const isolated = await runIsolatedTransform({
184
+ repoRoot,
185
+ baseRef,
186
+ allowedPaths: condition === 'treatment' ? [...RC1_V5_TRANSFORM_PATHS] : [],
187
+ transform: async ({ worktreePath }) => {
188
+ if (condition === 'treatment') await applyAcceptedPatch(worktreePath, patch);
189
+ snapshot = await fixedSnapshot(worktreePath);
190
+ const sensorBootstrap = await captureLatticeSensorBootstrap(worktreePath);
191
+ try {
192
+ const indexStartedAt = performance.now();
193
+ await invokeSensorCli(run, ['init', '.'], { cwd: worktreePath });
194
+ indexElapsedMs = roundedMilliseconds(indexStartedAt);
195
+ const queryStartedAt = performance.now();
196
+ rawEvidence = await collectSensorEvidence({ cwd: worktreePath, querySet });
197
+ queryElapsedMs = roundedMilliseconds(queryStartedAt);
198
+ } finally {
199
+ await restoreLatticeSensorBootstrap(worktreePath, sensorBootstrap);
200
+ }
201
+ },
202
+ verifyCommands: [],
203
+ });
204
+ if (!rawEvidence || !snapshot || isolated.sourceInvariant?.outcome !== 'passed') {
205
+ throw new TypeError(`RC1 v5 ${runId} fresh index did not produce complete evidence`);
206
+ }
207
+ if (condition === 'treatment'
208
+ && (!Buffer.isBuffer(patch) || !isolated.patch.equals(patch))) {
209
+ throw new TypeError(`RC1 v5 ${runId} did not replay the accepted patch bytes exactly`);
210
+ }
211
+ const bundle = createRc1EvidenceBundle({ condition, runId, querySet, rawEvidence });
212
+ const patchDigest = condition === 'treatment' ? sha256(isolated.patch) : null;
213
+ return {
214
+ runId,
215
+ condition,
216
+ rawEvidence,
217
+ bundle,
218
+ codeSnapshotDigest: snapshot.digest,
219
+ sourceInvariant: isolated.sourceInvariant,
220
+ patchDigest,
221
+ indexElapsedMs,
222
+ queryElapsedMs,
223
+ };
224
+ }
225
+
226
+ function compileOne({ inputs, observation, manualEvidence, planVersion }) {
227
+ return compileBoundaryCondition({
228
+ planInput: inputs.planInput,
229
+ candidateSpec: inputs.candidateSpec,
230
+ manualEvidence,
231
+ querySet: inputs.querySet,
232
+ sensorEvidence: observation.rawEvidence,
233
+ codeSnapshotDigest: observation.codeSnapshotDigest,
234
+ planVersion,
235
+ });
236
+ }
237
+
238
+ function compileCondition(inputs, observations, condition) {
239
+ const planVersion = `rc1-v5-${condition}`;
240
+ const compiled = observations.map((observation) => ({
241
+ normal: compileOne({
242
+ inputs,
243
+ observation,
244
+ manualEvidence: inputs.normalManualEvidence,
245
+ planVersion,
246
+ }),
247
+ negative: compileOne({
248
+ inputs,
249
+ observation,
250
+ manualEvidence: inputs.negativeManualEvidence,
251
+ planVersion: `${planVersion}-negative`,
252
+ }),
253
+ }));
254
+ for (const key of ['normal', 'negative']) {
255
+ if (digestArtifact(compiled[0][key]) !== digestArtifact(compiled[1][key])) {
256
+ throw new TypeError(`RC1 v5 ${condition} ${key} compilation is not reproducible`);
257
+ }
258
+ }
259
+ return compiled[0];
260
+ }
261
+
262
+ function sourceBindings(control, querySet) {
263
+ return {
264
+ boundary_manifest_digest: control.boundary_manifest_digest,
265
+ boundary_verdict_digest: control.boundary_verdict_digest,
266
+ control_plan_digest: control.plan_graph_digest,
267
+ query_set_digest: digestArtifact(querySet),
268
+ };
269
+ }
270
+
271
+ function compilationSummary(compiled) {
272
+ const conflicts = compiled.boundary_manifest.conflicts;
273
+ return {
274
+ boundary_manifest_digest: compiled.boundary_manifest_digest,
275
+ boundary_verdict_digest: compiled.boundary_verdict_digest,
276
+ plan_graph_digest: compiled.plan_graph_digest,
277
+ verdict: compiled.boundary_verdict.verdicts[0].verdict,
278
+ write_conflicts: conflicts.filter(({ kind }) => kind === 'write_boundary').length,
279
+ test_write_conflicts: conflicts.filter(({ kind, resource }) => (
280
+ kind === 'write_boundary'
281
+ && resource.kind === 'path'
282
+ && resource.target.startsWith('test/')
283
+ )).length,
284
+ state_conflicts: conflicts.filter(({ kind }) => kind === 'state').length,
285
+ hard_precedence: compiled.boundary_manifest.todos
286
+ .reduce((count, todo) => count + todo.hard_needs.length, 0),
287
+ unknowns: compiled.boundary_manifest.unknowns.length,
288
+ minimum_feasible_waves: compiled.plan_graph.minimum_feasible_waves,
289
+ };
290
+ }
291
+
292
+ function fixedInputIdentity(inputs) {
293
+ return {
294
+ plan_input: digestArtifact(inputs.planInput),
295
+ candidate_spec: digestArtifact(inputs.candidateSpec),
296
+ normal_manual_evidence: digestArtifact(inputs.normalManualEvidence),
297
+ negative_manual_evidence: digestArtifact(inputs.negativeManualEvidence),
298
+ query_set: digestArtifact(inputs.querySet),
299
+ capacity_writers: inputs.planInput.capacity.writers,
300
+ behavior_oracle: digestArtifact(inputs.oracle),
301
+ };
302
+ }
303
+
304
+ function evidenceSummary(bundles, querySet) {
305
+ return {
306
+ portable_preimages_complete: bundles.length === 2 && bundles.every((bundle) => (
307
+ validateRc1EvidenceBundle(bundle)
308
+ && bundle.portable.outcomes.length === querySet.queries.length
309
+ && bundle.portable.per_query.length === querySet.queries.length
310
+ )),
311
+ digests_recomputed: bundles.every((bundle) => (
312
+ recomputePortableAggregate(bundle.portable) === bundle.portable.aggregate_digest
313
+ )),
314
+ diagnostics_sanitized: bundles.every((bundle) => (
315
+ validateRc1EvidenceBundle(bundle)
316
+ && bundle.diagnostic.payload.cwd === '<repo-root>'
317
+ && bundle.diagnostic.sanitization_manifest.schema
318
+ === 'lattice.sensor_sanitization_manifest.v1'
319
+ )),
320
+ };
321
+ }
322
+
323
+ function buildPlanDiff(control, treatment, transform) {
324
+ const before = compilationSummary(control);
325
+ const after = compilationSummary(treatment);
326
+ return {
327
+ schema: 'lattice.plan_diff.v2',
328
+ old_plan: { version: control.plan_graph.plan_version, digest: control.plan_graph_digest },
329
+ new_plan: { version: treatment.plan_graph.plan_version, digest: treatment.plan_graph_digest },
330
+ causal_predecessor: {
331
+ plan_version: 'lattice-research-campaign-1-v4',
332
+ decision_ref: 'docs/adr/0022-rc1-v4-phase-gate-rejection.md',
333
+ status: 'phase_rejected',
334
+ },
335
+ transform: {
336
+ status: transform.artifact.status,
337
+ artifact_digest: transform.artifact_digest,
338
+ receipt_digest: transform.receipt_digest,
339
+ patch_digest: transform.artifact.patch.digest,
340
+ changed_paths: [...transform.artifact.scope.changed_paths],
341
+ },
342
+ nodes: {
343
+ added: [],
344
+ removed: [],
345
+ changed: control.plan_graph.nodes.map(({ id }) => id),
346
+ },
347
+ edges: {
348
+ added: treatment.plan_graph.edges.map(({ id }) => id),
349
+ removed: control.plan_graph.edges.map(({ id }) => id),
350
+ },
351
+ invalidated_contexts: structuredClone(INVALIDATED_CONTEXTS),
352
+ metrics: {
353
+ write_conflicts_before: before.write_conflicts,
354
+ write_conflicts_after: after.write_conflicts,
355
+ test_write_conflicts_before: before.test_write_conflicts,
356
+ test_write_conflicts_after: after.test_write_conflicts,
357
+ hard_precedence_before: before.hard_precedence,
358
+ hard_precedence_after: after.hard_precedence,
359
+ minimum_feasible_waves_before: before.minimum_feasible_waves,
360
+ minimum_feasible_waves_after: after.minimum_feasible_waves,
361
+ },
362
+ };
363
+ }
364
+
365
+ function transformReceiptValid(transform) {
366
+ const receipt = transform?.receipt;
367
+ if (!exactRecord(receipt, [
368
+ 'schema',
369
+ 'status',
370
+ 'transform_artifact_digest',
371
+ 'behavior_envelope_digest',
372
+ 'fixed_inputs_digest',
373
+ 'source_invariant',
374
+ 'receipt_digest',
375
+ ])
376
+ || receipt.schema !== 'lattice.rc1.seam_transform_receipt.v5'
377
+ || receipt.status !== 'accepted'
378
+ || !SHA256.test(receipt.transform_artifact_digest)
379
+ || !SHA256.test(receipt.behavior_envelope_digest)
380
+ || !SHA256.test(receipt.fixed_inputs_digest)
381
+ || receipt.source_invariant?.outcome !== 'passed'
382
+ || !SHA256.test(receipt.receipt_digest)) {
383
+ return false;
384
+ }
385
+ const { receipt_digest: ignored, ...preimage } = receipt;
386
+ return receipt.receipt_digest === digestArtifact(preimage)
387
+ && transform.receipt_digest === receipt.receipt_digest;
388
+ }
389
+
390
+ function fixedInputsBound(transform, bindings, baseSha) {
391
+ const behavior = transform.behavior_evidence;
392
+ return transform.artifact.status === 'accepted'
393
+ && Object.entries(bindings).every(([key, digest]) => transform.artifact.source[key] === digest)
394
+ && transform.artifact.source.base_sha === baseSha
395
+ && transform.artifact.source.code_snapshot_digest === behavior?.pre_receipt?.surface_digest
396
+ && transform.artifact_digest === digestArtifact(transform.artifact)
397
+ && transform.receipt.transform_artifact_digest === transform.artifact_digest
398
+ && transform.receipt.behavior_envelope_digest === behavior?.envelope?.envelope_digest
399
+ && transform.artifact.patch.digest === behavior?.patch_digest
400
+ && digestArtifact(behavior?.transform_artifact) === transform.artifact_digest
401
+ && transformReceiptValid(transform);
402
+ }
403
+
404
+ function makeComparison({
405
+ inputs,
406
+ compilerSourceDigest,
407
+ control,
408
+ treatment,
409
+ controlBundles,
410
+ treatmentBundles,
411
+ transform,
412
+ baseSha,
413
+ planDiff,
414
+ sourceInvariant,
415
+ }) {
416
+ const fixed = fixedInputIdentity(inputs);
417
+ const bindings = sourceBindings(control.normal, inputs.querySet);
418
+ return {
419
+ schema: 'lattice.rc1.control_treatment_comparison.v3',
420
+ fixed_inputs: { control: fixed, treatment: structuredClone(fixed) },
421
+ independent_variable: {
422
+ kind: 'accepted_production_and_test_seam',
423
+ transform_artifact_digest: transform.artifact_digest,
424
+ transform_receipt_digest: transform.receipt_digest,
425
+ patch_digest: transform.artifact.patch.digest,
426
+ },
427
+ compiler: {
428
+ condition_selector: RC1_BOUNDARY_COMPILER_CONTRACT.condition_selector,
429
+ control: {
430
+ export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
431
+ source_digest: compilerSourceDigest,
432
+ },
433
+ treatment: {
434
+ export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
435
+ source_digest: compilerSourceDigest,
436
+ },
437
+ },
438
+ control: compilationSummary(control.normal),
439
+ treatment: compilationSummary(treatment.normal),
440
+ negative_control: compilationSummary(control.negative),
441
+ negative_treatment: compilationSummary(treatment.negative),
442
+ behavior: {
443
+ evidence_envelope_digest: transform.behavior_evidence.envelope.envelope_digest,
444
+ },
445
+ evidence: {
446
+ control: evidenceSummary(controlBundles, inputs.querySet),
447
+ treatment: evidenceSummary(treatmentBundles, inputs.querySet),
448
+ },
449
+ predecessor: {
450
+ transform_status: transform.artifact.status,
451
+ same_base: transform.artifact.source.base_sha === baseSha,
452
+ fixed_inputs_bound: fixedInputsBound(transform, bindings, baseSha),
453
+ },
454
+ version_barrier: {
455
+ old_plan: planDiff.old_plan,
456
+ new_plan: planDiff.new_plan,
457
+ plan_diff_digest: digestArtifact(planDiff),
458
+ invalidated_contexts: planDiff.invalidated_contexts.map(({ kind, ref }) => ({ kind, ref })),
459
+ },
460
+ source_invariant: {
461
+ control: sourceInvariant.control ? 'passed' : 'failed',
462
+ treatment: sourceInvariant.treatment ? 'passed' : 'failed',
463
+ },
464
+ };
465
+ }
466
+
467
+ function runRecord(observation) {
468
+ return {
469
+ run_id: observation.runId,
470
+ condition: observation.condition,
471
+ index_elapsed_ms: observation.indexElapsedMs,
472
+ query_elapsed_ms: observation.queryElapsedMs,
473
+ code_snapshot_digest: observation.codeSnapshotDigest,
474
+ raw_digest: observation.bundle.raw.payload_digest,
475
+ diagnostic_digest: observation.bundle.diagnostic.payload_digest,
476
+ portable_digest: observation.bundle.portable.aggregate_digest,
477
+ bundle_descriptor_digest: digestArtifact({
478
+ schema: observation.bundle.schema,
479
+ condition: observation.bundle.condition,
480
+ run_id: observation.bundle.run_id,
481
+ query_set_digest: observation.bundle.query_set_digest,
482
+ component_digests: observation.bundle.component_digests,
483
+ }),
484
+ patch_digest: observation.patchDigest,
485
+ source_invariant: observation.sourceInvariant,
486
+ source_invariant_digest: digestArtifact(observation.sourceInvariant),
487
+ };
488
+ }
489
+
490
+ function compilationDigests(condition) {
491
+ return Object.fromEntries(['normal', 'negative'].map((key) => [key, {
492
+ boundary_manifest: condition[key].boundary_manifest_digest,
493
+ boundary_verdict: condition[key].boundary_verdict_digest,
494
+ plan_graph: condition[key].plan_graph_digest,
495
+ }]));
496
+ }
497
+
498
+ function assertInputs(inputs) {
499
+ if (!exactRecord(inputs, INPUT_KEYS)) {
500
+ throw new TypeError('RC1 v5 campaign inputs must have the fixed exact shape');
501
+ }
502
+ for (const value of Object.values(inputs)) canonicalizeArtifact(value);
503
+ }
504
+
505
+ /** fixed RC1 fixtureをfull behavior evidence付きcontrol→transform→treatment再compileで実行する。 */
506
+ export async function runRc1V5Campaign(options = {}) {
507
+ if (!exactRecord(options, ['repoRoot', 'baseRef', 'inputs'])) {
508
+ throw new TypeError('RC1 v5 campaign options must have the fixed exact shape');
509
+ }
510
+ const { repoRoot, baseRef, inputs } = options;
511
+ if (typeof repoRoot !== 'string' || repoRoot.length === 0
512
+ || typeof baseRef !== 'string' || baseRef.length === 0) {
513
+ throw new TypeError('RC1 v5 campaign repoRoot and baseRef are required');
514
+ }
515
+ assertInputs(inputs);
516
+ const fixedInputs = structuredClone(inputs);
517
+ const baseSha = (await run('git', ['rev-parse', '--verify', `${baseRef}^{commit}`], { cwd: repoRoot }))
518
+ .stdout.toString('utf8').trim();
519
+ if (!GIT_SHA1.test(baseSha)) throw new TypeError('RC1 v5 campaign base SHA is invalid');
520
+ const compilerSourceDigest = sha256(await readFile(new URL('./boundary-compiler.mjs', import.meta.url)));
521
+ const campaignSourceDigest = sha256(await readFile(new URL('./rc1-v5-campaign.mjs', import.meta.url)));
522
+ const startedAt = performance.now();
523
+
524
+ const controlObservations = [];
525
+ for (const runId of ['control-1', 'control-2']) {
526
+ controlObservations.push(await observeFreshIndex({
527
+ repoRoot,
528
+ baseRef: baseSha,
529
+ condition: 'control',
530
+ runId,
531
+ querySet: fixedInputs.querySet,
532
+ }));
533
+ }
534
+ const control = compileCondition(fixedInputs, controlObservations, 'control');
535
+ const bindings = sourceBindings(control.normal, fixedInputs.querySet);
536
+ const transformStartedAt = performance.now();
537
+ const transform = await runRc1V5SeamTransform({
538
+ repoRoot,
539
+ baseRef: baseSha,
540
+ oracle: fixedInputs.oracle,
541
+ sourceBindings: bindings,
542
+ });
543
+ const transformElapsedMs = roundedMilliseconds(transformStartedAt);
544
+ if (transform.artifact.status !== 'accepted'
545
+ || transform.receipt.source_invariant?.outcome !== 'passed'
546
+ || !Buffer.isBuffer(transform.patch)
547
+ || transform.behavior_evidence === null) {
548
+ const error = new Error('RC1 v5 accepted transform predecessor was not produced');
549
+ error.transform = transform;
550
+ throw error;
551
+ }
552
+
553
+ const treatmentObservations = [];
554
+ for (const runId of ['treatment-1', 'treatment-2']) {
555
+ const observation = await observeFreshIndex({
556
+ repoRoot,
557
+ baseRef: baseSha,
558
+ condition: 'treatment',
559
+ runId,
560
+ querySet: fixedInputs.querySet,
561
+ patch: transform.patch,
562
+ });
563
+ if (observation.patchDigest !== transform.artifact.patch.digest) {
564
+ throw new TypeError(`${runId} did not apply the exact accepted patch`);
565
+ }
566
+ treatmentObservations.push(observation);
567
+ }
568
+ const treatment = compileCondition(fixedInputs, treatmentObservations, 'treatment');
569
+ const evidenceBundles = [
570
+ ...controlObservations.map(({ bundle }) => bundle),
571
+ ...treatmentObservations.map(({ bundle }) => bundle),
572
+ ];
573
+ if (!validateRc1EvidenceCampaign(evidenceBundles)) {
574
+ throw new TypeError('RC1 v5 2+2 evidence campaign is not reproducible');
575
+ }
576
+
577
+ const sourceInvariant = {
578
+ control: controlObservations.every(({ sourceInvariant: receipt }) => receipt.outcome === 'passed'),
579
+ treatment: transform.receipt.source_invariant.outcome === 'passed'
580
+ && treatmentObservations.every(({ sourceInvariant: receipt }) => receipt.outcome === 'passed'),
581
+ };
582
+ const planDiff = buildPlanDiff(control.normal, treatment.normal, transform);
583
+ const comparison = makeComparison({
584
+ inputs: fixedInputs,
585
+ compilerSourceDigest,
586
+ control,
587
+ treatment,
588
+ controlBundles: evidenceBundles.filter(({ condition }) => condition === 'control'),
589
+ treatmentBundles: evidenceBundles.filter(({ condition }) => condition === 'treatment'),
590
+ transform,
591
+ baseSha,
592
+ planDiff,
593
+ sourceInvariant,
594
+ });
595
+ const hypothesisEvaluation = evaluateRc1V5Hypothesis({
596
+ comparison,
597
+ behaviorEvidence: transform.behavior_evidence,
598
+ });
599
+ const conditionRuns = {
600
+ control: controlObservations.map(runRecord),
601
+ treatment: treatmentObservations.map(runRecord),
602
+ };
603
+ const behavior = transform.behavior_evidence;
604
+ const executionEvidence = {
605
+ schema: 'lattice.rc1.corrected_campaign_execution_evidence.v5',
606
+ base_sha: baseSha,
607
+ elapsed_ms: roundedMilliseconds(startedAt),
608
+ compiler: {
609
+ export_name: RC1_BOUNDARY_COMPILER_CONTRACT.export_name,
610
+ source_digest: compilerSourceDigest,
611
+ campaign_runner_source_digest: campaignSourceDigest,
612
+ },
613
+ fixed_inputs: fixedInputIdentity(fixedInputs),
614
+ runs: conditionRuns,
615
+ transform: {
616
+ elapsed_ms: transformElapsedMs,
617
+ artifact_digest: transform.artifact_digest,
618
+ receipt_digest: transform.receipt_digest,
619
+ patch_digest: transform.artifact.patch.digest,
620
+ source_invariant_digest: digestArtifact(transform.receipt.source_invariant),
621
+ },
622
+ behavior: {
623
+ pre_receipt_digest: behavior.pre_receipt.receipt_digest,
624
+ post_receipt_digest: behavior.post_receipt.receipt_digest,
625
+ pre_surface_digest: behavior.pre_receipt.surface_digest,
626
+ post_surface_digest: behavior.post_receipt.surface_digest,
627
+ envelope_digest: behavior.envelope.envelope_digest,
628
+ },
629
+ compilations: {
630
+ control: compilationDigests(control),
631
+ treatment: compilationDigests(treatment),
632
+ },
633
+ plan_diff_digest: digestArtifact(planDiff),
634
+ comparison_digest: digestArtifact(comparison),
635
+ hypothesis_evaluation_digest: digestArtifact(hypothesisEvaluation),
636
+ observed_facts: {
637
+ evidence_campaign_valid: true,
638
+ compiler_reused: true,
639
+ exact_patch_replayed: true,
640
+ full_behavior_evidence_bound: true,
641
+ source_invariant_passed: sourceInvariant.control && sourceInvariant.treatment,
642
+ hypothesis_supported: hypothesisEvaluation.supported,
643
+ },
644
+ };
645
+ return {
646
+ schema: 'lattice.rc1.corrected_campaign_result.v5',
647
+ base_sha: baseSha,
648
+ inputs: fixedInputs,
649
+ evidence_bundles: evidenceBundles,
650
+ condition_runs: conditionRuns,
651
+ control,
652
+ treatment,
653
+ transform,
654
+ plan_diff: planDiff,
655
+ comparison,
656
+ hypothesis_evaluation: hypothesisEvaluation,
657
+ execution_evidence: executionEvidence,
658
+ };
659
+ }
660
+
661
+ function jsonBytes(value) {
662
+ return Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8');
663
+ }
664
+
665
+ function artifactFiles(result) {
666
+ const files = new Map();
667
+ for (const [key, relativePath] of [
668
+ ['planInput', 'inputs/plan-input.json'],
669
+ ['candidateSpec', 'inputs/candidate-spec-v2.json'],
670
+ ['normalManualEvidence', 'inputs/manual-evidence.normal.json'],
671
+ ['negativeManualEvidence', 'inputs/manual-evidence.shared-state-negative.json'],
672
+ ['querySet', 'inputs/query-set-v2.json'],
673
+ ['oracle', 'inputs/behavior-oracle-v2.json'],
674
+ ]) {
675
+ files.set(relativePath, jsonBytes(result.inputs[key]));
676
+ }
677
+ for (const bundle of result.evidence_bundles) {
678
+ files.set(`evidence/${bundle.run_id}.json`, jsonBytes(bundle));
679
+ }
680
+ for (const [conditionName, condition] of [
681
+ ['control', result.control],
682
+ ['treatment', result.treatment],
683
+ ]) {
684
+ for (const [variantName, compiled] of [
685
+ ['normal', condition.normal],
686
+ ['negative', condition.negative],
687
+ ]) {
688
+ const root = `compiled/${conditionName}-${variantName}`;
689
+ files.set(`${root}/boundary-manifest.json`, jsonBytes(compiled.boundary_manifest));
690
+ files.set(`${root}/boundary-verdict.json`, jsonBytes(compiled.boundary_verdict));
691
+ files.set(`${root}/plan.json`, jsonBytes(compiled.plan_graph));
692
+ }
693
+ }
694
+ files.set('behavior/pre-receipt.json', jsonBytes(result.transform.behavior_evidence.pre_receipt));
695
+ files.set('behavior/post-receipt.json', jsonBytes(result.transform.behavior_evidence.post_receipt));
696
+ files.set('behavior/evidence-envelope.json', jsonBytes(result.transform.behavior_evidence.envelope));
697
+ files.set('transform/transform-artifact.json', jsonBytes(result.transform.artifact));
698
+ files.set('transform/transform-receipt.json', jsonBytes(result.transform.receipt));
699
+ files.set('transform/seam.patch', Buffer.from(result.transform.patch));
700
+ files.set('plan-diff.json', jsonBytes(result.plan_diff));
701
+ files.set('comparison.json', jsonBytes(result.comparison));
702
+ files.set('hypothesis-evaluation.json', jsonBytes(result.hypothesis_evaluation));
703
+ files.set('execution-evidence.json', jsonBytes(result.execution_evidence));
704
+ return files;
705
+ }
706
+
707
+ function assertWritableResult(result) {
708
+ if (!exactRecord(result, [
709
+ 'schema',
710
+ 'base_sha',
711
+ 'inputs',
712
+ 'evidence_bundles',
713
+ 'condition_runs',
714
+ 'control',
715
+ 'treatment',
716
+ 'transform',
717
+ 'plan_diff',
718
+ 'comparison',
719
+ 'hypothesis_evaluation',
720
+ 'execution_evidence',
721
+ ])
722
+ || result.schema !== 'lattice.rc1.corrected_campaign_result.v5'
723
+ || !GIT_SHA1.test(result.base_sha)
724
+ || !validateRc1EvidenceCampaign(result.evidence_bundles)
725
+ || !Buffer.isBuffer(result.transform?.patch)
726
+ || result.transform?.artifact?.status !== 'accepted'
727
+ || result.transform?.behavior_evidence === null
728
+ || sha256(result.transform.patch) !== result.transform.artifact.patch?.digest
729
+ || digestArtifact(result.transform.artifact) !== result.transform.artifact_digest
730
+ || !transformReceiptValid(result.transform)
731
+ || result.comparison?.schema !== 'lattice.rc1.control_treatment_comparison.v3'
732
+ || result.comparison.behavior?.evidence_envelope_digest
733
+ !== result.transform.behavior_evidence.envelope?.envelope_digest) {
734
+ throw new TypeError('RC1 v5 artifact writer arguments are invalid');
735
+ }
736
+ const recomputed = evaluateRc1V5Hypothesis({
737
+ comparison: result.comparison,
738
+ behaviorEvidence: result.transform.behavior_evidence,
739
+ });
740
+ if (digestArtifact(recomputed) !== digestArtifact(result.hypothesis_evaluation)) {
741
+ throw new TypeError('RC1 v5 hypothesis evaluation is not reproducible');
742
+ }
743
+ }
744
+
745
+ /** RC1 v5 full causal artifactを既存treeへ上書きせずatomicに保存する。 */
746
+ export async function writeRc1V5Artifacts(options = {}) {
747
+ if (!exactRecord(options, ['repoRoot', 'result'])
748
+ || typeof options.repoRoot !== 'string' || options.repoRoot.length === 0) {
749
+ throw new TypeError('RC1 v5 artifact writer options must have the fixed exact shape');
750
+ }
751
+ const { repoRoot, result } = options;
752
+ assertWritableResult(result);
753
+ const artifactRoot = path.join(repoRoot, ARTIFACT_ROOT);
754
+ try {
755
+ await lstat(artifactRoot);
756
+ throw new Error('RC1 v5 artifact root already exists; immutable evidence is not overwritten');
757
+ } catch (error) {
758
+ if (error?.code !== 'ENOENT') throw error;
759
+ }
760
+
761
+ const files = artifactFiles(result);
762
+ const manifest = {
763
+ schema: 'lattice.rc1.artifact_manifest.v5',
764
+ base_sha: result.base_sha,
765
+ result_digest: result.transform.behavior_evidence.envelope.envelope_digest,
766
+ files: [...files].map(([relativePath, bytes]) => ({
767
+ path: relativePath,
768
+ media_type: relativePath.endsWith('.json') ? 'application/json' : 'text/x-diff',
769
+ bytes: bytes.byteLength,
770
+ sha256: sha256(bytes),
771
+ })).sort((left, right) => left.path.localeCompare(right.path)),
772
+ };
773
+ const verification = verifyRc1V5CampaignArtifactSet({
774
+ manifest,
775
+ payloads: [...files].map(([relativePath, bytes]) => ({ path: relativePath, bytes })),
776
+ });
777
+ if (!verification.valid) {
778
+ throw new TypeError(`RC1 v5 campaign artifact set is invalid: ${verification.failed_conditions.join(', ')}`);
779
+ }
780
+
781
+ const parent = path.dirname(artifactRoot);
782
+ await mkdir(parent, { recursive: true });
783
+ const temporaryRoot = await mkdtemp(path.join(parent, '.v5-write-'));
784
+ try {
785
+ for (const [relativePath, bytes] of files) {
786
+ const target = path.join(temporaryRoot, relativePath);
787
+ await mkdir(path.dirname(target), { recursive: true });
788
+ await writeFile(target, bytes);
789
+ }
790
+ await writeFile(path.join(temporaryRoot, 'artifact-manifest.json'), jsonBytes(manifest));
791
+ await rename(temporaryRoot, artifactRoot);
792
+ } catch (error) {
793
+ await rm(temporaryRoot, { recursive: true, force: true });
794
+ throw error;
795
+ }
796
+ return manifest;
797
+ }