@quolu/lattice 0.52.3 → 0.53.0

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