@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,623 +1,623 @@
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
- import { isDeepStrictEqual } from 'node:util';
15
-
16
- import {
17
- canonicalizeArtifact,
18
- digestArtifact,
19
- validateTransformArtifact,
20
- } from './artifact-contracts.mjs';
21
- import { RC1_BOUNDARY_COMPILER_CONTRACT } from './boundary-compiler.mjs';
22
- import { runIsolatedTransform } from './isolation-runner.mjs';
23
- import {
24
- createRc1V6OracleRuntimeIdentity,
25
- runRc1V6BlackBoxOracle,
26
- } from './rc1-black-box-oracle.mjs';
27
- import {
28
- buildRc1V6PlanDiff,
29
- compileRc1V6Comparison,
30
- evaluateRc1V6Hypothesis,
31
- RC1_V6_ARTIFACT_PATHS,
32
- RC1_V6_PHASE_DECISION_REF,
33
- RC1_V6_REJECTED_PLAN_REF,
34
- rc1V6ArtifactMediaType,
35
- verifyRc1V6CampaignArtifactSet,
36
- } from './rc1-v6-artifact-set.mjs';
37
- import { compileRc1V6BehaviorEvidence } from './rc1-v6-behavior-evidence.mjs';
38
- import { createRc1V6EvidenceBundleDescriptor } from './rc1-v6-causal-binding.mjs';
39
- import { runRc1V5Campaign } from './rc1-v5-campaign.mjs';
40
- import {
41
- bindRc1V6EvidenceBundle,
42
- captureRc1V6LatticeSensorExecutable,
43
- compileRc1V6BoundaryCondition,
44
- createRc1V6ConditionRun,
45
- sourceSnapshotFromRc1BehaviorSurface,
46
- sourceSnapshotFromRc1TransformOutput,
47
- } from './rc1-v6-measurement.mjs';
48
- import { RC1_V5_TRANSFORM_PATHS } from './rc1-v5-transform.mjs';
49
-
50
- const ARTIFACT_ROOT = 'research/campaigns/rc1/artifacts/v6';
51
- const GIT_SHA1 = /^[0-9a-f]{40}$/;
52
- const INPUT_KEYS = Object.freeze([
53
- 'planInput',
54
- 'candidateSpec',
55
- 'normalManualEvidence',
56
- 'negativeManualEvidence',
57
- 'querySet',
58
- 'oracle',
59
- ]);
60
-
61
- function exactRecord(value, keys) {
62
- if (value === null || typeof value !== 'object' || Array.isArray(value)
63
- || Object.getPrototypeOf(value) !== Object.prototype) {
64
- return false;
65
- }
66
- const actual = Object.keys(value).sort();
67
- const expected = [...keys].sort();
68
- return actual.length === expected.length
69
- && actual.every((key, index) => key === expected[index]);
70
- }
71
-
72
- function sha256(bytes) {
73
- return createHash('sha256').update(bytes).digest('hex');
74
- }
75
-
76
- function roundedMilliseconds(startedAt) {
77
- return Math.round((performance.now() - startedAt) * 1_000) / 1_000;
78
- }
79
-
80
- function jsonBytes(value) {
81
- return Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8');
82
- }
83
-
84
- function run(command, args, { cwd, input } = {}) {
85
- return new Promise((resolve, reject) => {
86
- const child = spawn(command, args, {
87
- cwd,
88
- shell: false,
89
- stdio: ['pipe', 'pipe', 'pipe'],
90
- env: { ...process.env, NO_COLOR: '1' },
91
- });
92
- const stdout = [];
93
- const stderr = [];
94
- child.stdout.on('data', (chunk) => stdout.push(chunk));
95
- child.stderr.on('data', (chunk) => stderr.push(chunk));
96
- child.once('error', reject);
97
- child.once('close', (code, signal) => {
98
- const result = {
99
- code,
100
- signal,
101
- stdout: Buffer.concat(stdout),
102
- stderr: Buffer.concat(stderr),
103
- };
104
- if (code === 0 && signal === null) resolve(result);
105
- else reject(Object.assign(
106
- new Error(`${command} failed (${signal ?? code}): ${result.stderr.toString('utf8').trim()}`),
107
- result,
108
- ));
109
- });
110
- child.stdin.end(input);
111
- });
112
- }
113
-
114
- function assertInputs(inputs) {
115
- if (!exactRecord(inputs, INPUT_KEYS)) {
116
- throw new TypeError('RC1 v6 campaign inputs must have the fixed exact shape');
117
- }
118
- for (const value of Object.values(inputs)) canonicalizeArtifact(value);
119
- }
120
-
121
- function legacySnapshotDigest(snapshot) {
122
- return digestArtifact({
123
- schema: 'lattice.rc1.fixed_surface_snapshot.v5',
124
- files: snapshot.files.map((file) => ({
125
- path: file.path,
126
- state: file.state === 'file' ? 'file' : 'missing',
127
- content_digest: file.content_digest,
128
- })),
129
- });
130
- }
131
-
132
- function compileCondition({ inputs, bundles, runs, expected, condition }) {
133
- const outputs = bundles.map((bundle, index) => {
134
- const common = {
135
- planInput: inputs.planInput,
136
- candidateSpec: inputs.candidateSpec,
137
- querySet: inputs.querySet,
138
- run: runs[index],
139
- bundle,
140
- expected,
141
- };
142
- return {
143
- normal: compileRc1V6BoundaryCondition({
144
- ...common,
145
- manualEvidence: inputs.normalManualEvidence,
146
- planVersion: `rc1-v6-${condition}`,
147
- }),
148
- negative: compileRc1V6BoundaryCondition({
149
- ...common,
150
- manualEvidence: inputs.negativeManualEvidence,
151
- planVersion: `rc1-v6-${condition}-negative`,
152
- }),
153
- };
154
- });
155
- if (outputs.length !== 2 || digestArtifact(outputs[0]) !== digestArtifact(outputs[1])) {
156
- throw new TypeError(`RC1 v6 ${condition} compilation is not reproducible`);
157
- }
158
- return outputs[0];
159
- }
160
-
161
- function updatedTransformArtifact(v5Artifact, control, controlSnapshot, querySet) {
162
- const artifact = structuredClone(v5Artifact);
163
- artifact.source = {
164
- base_sha: v5Artifact.source.base_sha,
165
- boundary_manifest_digest: control.normal.boundary_manifest_digest,
166
- boundary_verdict_digest: control.normal.boundary_verdict_digest,
167
- control_plan_digest: control.normal.plan_graph_digest,
168
- query_set_digest: digestArtifact(querySet),
169
- code_snapshot_digest: digestArtifact(controlSnapshot),
170
- };
171
- if (!validateTransformArtifact(artifact) || artifact.status !== 'accepted') {
172
- throw new TypeError('RC1 v6 updated transform artifact is invalid');
173
- }
174
- return artifact;
175
- }
176
-
177
- async function applyPatch(worktreePath, patch) {
178
- await run('git', ['apply', '--check', '--binary', '-'], { cwd: worktreePath, input: patch });
179
- await run('git', ['apply', '--binary', '-'], { cwd: worktreePath, input: patch });
180
- }
181
-
182
- async function bindV6Behavior({
183
- repoRoot,
184
- baseSha,
185
- oracle,
186
- runtimeIdentity,
187
- artifact,
188
- patch,
189
- }) {
190
- const surfacePaths = [...artifact.scope.allowed_paths];
191
- const preReceipt = await runRc1V6BlackBoxOracle({
192
- repoRoot,
193
- oracle,
194
- role: 'pre_transform',
195
- baseSha,
196
- surfacePaths,
197
- runtimeIdentity,
198
- });
199
- let postReceipt;
200
- const isolated = await runIsolatedTransform({
201
- repoRoot,
202
- baseRef: baseSha,
203
- allowedPaths: surfacePaths,
204
- transform: async ({ worktreePath }) => {
205
- await applyPatch(worktreePath, patch);
206
- postReceipt = await runRc1V6BlackBoxOracle({
207
- repoRoot: worktreePath,
208
- oracle,
209
- role: 'post_transform',
210
- baseSha,
211
- surfacePaths,
212
- runtimeIdentity,
213
- });
214
- },
215
- verifyCommands: [],
216
- });
217
- if (!Buffer.isBuffer(isolated.patch)
218
- || !isolated.patch.equals(patch)
219
- || isolated.sourceInvariant?.outcome !== 'passed'
220
- || postReceipt?.outcome !== 'passed') {
221
- throw new TypeError('RC1 v6 behavior observation did not preserve accepted patch identity');
222
- }
223
- const patchDigest = sha256(patch);
224
- const envelope = compileRc1V6BehaviorEvidence({
225
- oracle,
226
- runtimeIdentity,
227
- preReceipt,
228
- postReceipt,
229
- transformArtifact: artifact,
230
- patchDigest,
231
- });
232
- return {
233
- pre_receipt: preReceipt,
234
- post_receipt: postReceipt,
235
- envelope,
236
- transform_artifact: artifact,
237
- patch_digest: patchDigest,
238
- source_invariant: isolated.sourceInvariant,
239
- };
240
- }
241
-
242
- function v6Transform(v5Transform, artifact, behaviorEvidence, runtimeIdentity) {
243
- const artifactDigest = digestArtifact(artifact);
244
- const preimage = {
245
- schema: 'lattice.rc1.seam_transform_receipt.v6',
246
- status: 'accepted',
247
- transform_artifact_digest: artifactDigest,
248
- behavior_envelope_digest: behaviorEvidence.envelope.envelope_digest,
249
- fixed_inputs_digest: digestArtifact(artifact.source),
250
- runtime_identity_digest: digestArtifact(runtimeIdentity),
251
- source_invariant: behaviorEvidence.source_invariant,
252
- };
253
- const receipt = { ...preimage, receipt_digest: digestArtifact(preimage) };
254
- return {
255
- artifact,
256
- artifact_digest: artifactDigest,
257
- receipt,
258
- receipt_digest: receipt.receipt_digest,
259
- patch: Buffer.from(v5Transform.patch),
260
- behavior_evidence: {
261
- pre_receipt: behaviorEvidence.pre_receipt,
262
- post_receipt: behaviorEvidence.post_receipt,
263
- envelope: behaviorEvidence.envelope,
264
- transform_artifact: artifact,
265
- patch_digest: behaviorEvidence.patch_digest,
266
- },
267
- };
268
- }
269
-
270
- function conditionRunRecords(v5Runs, runs) {
271
- return v5Runs.map((record, index) => ({
272
- run: runs[index],
273
- patch_digest: record.patch_digest,
274
- index_elapsed_ms: record.index_elapsed_ms,
275
- query_elapsed_ms: record.query_elapsed_ms,
276
- source_invariant: record.source_invariant,
277
- source_invariant_digest: record.source_invariant_digest,
278
- }));
279
- }
280
-
281
- /** v5のfresh機構を観測器として再利用し、全結果をv6 causal chainへ再compileする。 */
282
- export async function runRc1V6Campaign(options = {}) {
283
- if (!exactRecord(options, ['repoRoot', 'baseRef', 'inputs'])) {
284
- throw new TypeError('RC1 v6 campaign options must have the fixed exact shape');
285
- }
286
- const { repoRoot, baseRef, inputs } = options;
287
- if (typeof repoRoot !== 'string' || repoRoot.length === 0
288
- || typeof baseRef !== 'string' || baseRef.length === 0) {
289
- throw new TypeError('RC1 v6 campaign repoRoot and baseRef are required');
290
- }
291
- assertInputs(inputs);
292
- const fixedInputs = structuredClone(inputs);
293
- const baseSha = (await run('git', ['rev-parse', '--verify', `${baseRef}^{commit}`], { cwd: repoRoot }))
294
- .stdout.toString('utf8').trim();
295
- if (!GIT_SHA1.test(baseSha)) throw new TypeError('RC1 v6 campaign base SHA is invalid');
296
- const startedAt = performance.now();
297
- const [sensorCapture, compilerSourceBytes, oracleExecutorBytes] = await Promise.all([
298
- captureRc1V6LatticeSensorExecutable(),
299
- readFile(new URL('./boundary-compiler.mjs', import.meta.url)),
300
- readFile(new URL('./rc1-black-box-oracle.mjs', import.meta.url)),
301
- ]);
302
- const sensorIdentity = sensorCapture.identity;
303
- const runtimeIdentity = await createRc1V6OracleRuntimeIdentity();
304
- if (runtimeIdentity.executor_source_digest !== sha256(oracleExecutorBytes)) {
305
- throw new TypeError('RC1 v6 oracle runtime identityが保存executor bytesと一致しない');
306
- }
307
- const v5 = await runRc1V5Campaign({ repoRoot, baseRef: baseSha, inputs: fixedInputs });
308
- const [finalLatticeSensorCapture, finalCompilerSourceBytes, finalOracleExecutorBytes] =
309
- await Promise.all([
310
- captureRc1V6LatticeSensorExecutable(),
311
- readFile(new URL('./boundary-compiler.mjs', import.meta.url)),
312
- readFile(new URL('./rc1-black-box-oracle.mjs', import.meta.url)),
313
- ]);
314
- if (!isDeepStrictEqual(sensorCapture, finalLatticeSensorCapture)
315
- || !compilerSourceBytes.equals(finalCompilerSourceBytes)
316
- || !oracleExecutorBytes.equals(finalOracleExecutorBytes)) {
317
- throw new TypeError('RC1 v6実行主体のidentityがcampaign中にdriftした');
318
- }
319
-
320
- const controlSnapshot = sourceSnapshotFromRc1BehaviorSurface(
321
- v5.transform.behavior_evidence.pre_receipt.surface,
322
- );
323
- const treatmentSnapshot = sourceSnapshotFromRc1TransformOutput(v5.transform.artifact);
324
- const postSnapshot = sourceSnapshotFromRc1BehaviorSurface(
325
- v5.transform.behavior_evidence.post_receipt.surface,
326
- );
327
- if (!isDeepStrictEqual(treatmentSnapshot, postSnapshot)) {
328
- throw new TypeError('RC1 v6 treatment snapshot does not equal accepted transform output');
329
- }
330
- for (const record of v5.condition_runs.control) {
331
- if (record.code_snapshot_digest !== legacySnapshotDigest(controlSnapshot)) {
332
- throw new TypeError(`${record.run_id} hidden v5 snapshot does not match typed control preimage`);
333
- }
334
- }
335
- for (const record of v5.condition_runs.treatment) {
336
- if (record.code_snapshot_digest !== legacySnapshotDigest(treatmentSnapshot)) {
337
- throw new TypeError(`${record.run_id} hidden v5 snapshot does not match typed treatment preimage`);
338
- }
339
- }
340
-
341
- const evidenceBundles = v5.evidence_bundles.map((bundle) => bindRc1V6EvidenceBundle({
342
- bundle,
343
- base_sha: baseSha,
344
- patch_digest: bundle.condition === 'treatment' ? v5.transform.artifact.patch.digest : null,
345
- snapshot: bundle.condition === 'treatment' ? treatmentSnapshot : controlSnapshot,
346
- sensor_identity: sensorIdentity,
347
- query_set_digest: digestArtifact(fixedInputs.querySet),
348
- }));
349
- const runs = evidenceBundles.map(createRc1V6ConditionRun);
350
- const controlBundles = evidenceBundles.filter(({ condition }) => condition === 'control');
351
- const treatmentBundles = evidenceBundles.filter(({ condition }) => condition === 'treatment');
352
- const controlRuns = runs.filter(({ condition }) => condition === 'control');
353
- const treatmentRuns = runs.filter(({ condition }) => condition === 'treatment');
354
- const controlExpected = {
355
- base_sha: baseSha,
356
- patch_digest: null,
357
- snapshot: controlSnapshot,
358
- sensor_identity: sensorIdentity,
359
- query_set_digest: digestArtifact(fixedInputs.querySet),
360
- };
361
- const treatmentExpected = {
362
- base_sha: baseSha,
363
- patch_digest: v5.transform.artifact.patch.digest,
364
- snapshot: treatmentSnapshot,
365
- sensor_identity: sensorIdentity,
366
- query_set_digest: digestArtifact(fixedInputs.querySet),
367
- };
368
- const control = compileCondition({
369
- inputs: fixedInputs,
370
- bundles: controlBundles,
371
- runs: controlRuns,
372
- expected: controlExpected,
373
- condition: 'control',
374
- });
375
- const treatment = compileCondition({
376
- inputs: fixedInputs,
377
- bundles: treatmentBundles,
378
- runs: treatmentRuns,
379
- expected: treatmentExpected,
380
- condition: 'treatment',
381
- });
382
-
383
- const artifact = updatedTransformArtifact(
384
- v5.transform.artifact,
385
- control,
386
- controlSnapshot,
387
- fixedInputs.querySet,
388
- );
389
- const behaviorEvidence = await bindV6Behavior({
390
- repoRoot,
391
- baseSha,
392
- oracle: fixedInputs.oracle,
393
- runtimeIdentity,
394
- artifact,
395
- patch: v5.transform.patch,
396
- });
397
- const transform = v6Transform(v5.transform, artifact, behaviorEvidence, runtimeIdentity);
398
- const rejectedPlanBytes = await readFile(path.join(repoRoot, RC1_V6_REJECTED_PLAN_REF));
399
- const phaseDecisionBytes = await readFile(path.join(repoRoot, RC1_V6_PHASE_DECISION_REF));
400
- const planDiff = buildRc1V6PlanDiff({
401
- control,
402
- treatment,
403
- transform,
404
- evidenceBundles,
405
- rejectedPlanBytes,
406
- phaseDecisionBytes,
407
- });
408
- const sourceInvariant = {
409
- control: v5.condition_runs.control.every(({ source_invariant: receipt }) => (
410
- receipt.outcome === 'passed'
411
- )),
412
- treatment: behaviorEvidence.source_invariant.outcome === 'passed'
413
- && v5.condition_runs.treatment.every(({ source_invariant: receipt }) => (
414
- receipt.outcome === 'passed'
415
- )),
416
- };
417
- const compilerSourceDigest = sha256(compilerSourceBytes);
418
- const comparison = compileRc1V6Comparison({
419
- baseSha,
420
- inputs: fixedInputs,
421
- runtimeIdentity,
422
- sensorIdentity,
423
- compilerSourceDigest,
424
- control,
425
- treatment,
426
- evidenceBundles,
427
- transform,
428
- planDiff,
429
- sourceInvariant,
430
- });
431
- const hypothesisEvaluation = evaluateRc1V6Hypothesis(comparison);
432
- if (!hypothesisEvaluation.supported) {
433
- throw new TypeError(
434
- `RC1 v6 hypothesis is not supported: ${hypothesisEvaluation.failed_conditions.join(', ')}`,
435
- );
436
- }
437
- const conditionRuns = {
438
- control: conditionRunRecords(v5.condition_runs.control, controlRuns),
439
- treatment: conditionRunRecords(v5.condition_runs.treatment, treatmentRuns),
440
- };
441
- const executionEvidence = {
442
- schema: 'lattice.rc1.corrected_campaign_execution_evidence.v6',
443
- base_sha: baseSha,
444
- elapsed_ms: roundedMilliseconds(startedAt),
445
- compiler_source_digest: compilerSourceDigest,
446
- sensor_identity_digest: digestArtifact(sensorIdentity),
447
- runtime_identity_digest: digestArtifact(runtimeIdentity),
448
- run_descriptor_digests: runs.map(({ evidence_bundle_descriptor_digest: digest }) => digest),
449
- transform_artifact_digest: transform.artifact_digest,
450
- behavior_envelope_digest: transform.behavior_evidence.envelope.envelope_digest,
451
- plan_diff_digest: digestArtifact(planDiff),
452
- comparison_digest: digestArtifact(comparison),
453
- hypothesis_evaluation_digest: digestArtifact(hypothesisEvaluation),
454
- source_invariant: sourceInvariant,
455
- };
456
- return {
457
- schema: 'lattice.rc1.corrected_campaign_result.v6',
458
- base_sha: baseSha,
459
- inputs: fixedInputs,
460
- runtime_identity: runtimeIdentity,
461
- sensor_identity: sensorIdentity,
462
- identity_sources: {
463
- compiler: compilerSourceBytes,
464
- oracle_executor: oracleExecutorBytes,
465
- sensor_executable: sensorCapture.executable_bytes,
466
- },
467
- evidence_bundles: evidenceBundles,
468
- runs,
469
- condition_runs: conditionRuns,
470
- control,
471
- treatment,
472
- transform,
473
- plan_diff: planDiff,
474
- comparison,
475
- hypothesis_evaluation: hypothesisEvaluation,
476
- execution_evidence: executionEvidence,
477
- };
478
- }
479
-
480
- function artifactFiles(result, rejectedPlanBytes, phaseDecisionBytes) {
481
- const files = new Map();
482
- for (const [key, relativePath] of [
483
- ['planInput', 'inputs/plan-input.json'],
484
- ['candidateSpec', 'inputs/candidate-spec-v2.json'],
485
- ['normalManualEvidence', 'inputs/manual-evidence.normal.json'],
486
- ['negativeManualEvidence', 'inputs/manual-evidence.shared-state-negative.json'],
487
- ['querySet', 'inputs/query-set-v2.json'],
488
- ['oracle', 'inputs/behavior-oracle-v2.json'],
489
- ]) {
490
- files.set(relativePath, jsonBytes(result.inputs[key]));
491
- }
492
- files.set('inputs/oracle-runtime-identity.json', jsonBytes(result.runtime_identity));
493
- files.set('inputs/lattice-sensor-identity.json', jsonBytes(result.sensor_identity));
494
- files.set('identity/boundary-compiler.mjs', Buffer.from(result.identity_sources.compiler));
495
- files.set('identity/black-box-oracle.mjs', Buffer.from(result.identity_sources.oracle_executor));
496
- files.set('identity/lattice-sensor-executable', Buffer.from(result.identity_sources.sensor_executable));
497
- for (const bundle of result.evidence_bundles) {
498
- files.set(`evidence/${bundle.run_id}.json`, jsonBytes(bundle));
499
- }
500
- for (const runValue of result.runs) {
501
- files.set(`runs/${runValue.run_id}.json`, jsonBytes(runValue));
502
- }
503
- for (const [conditionName, condition] of [
504
- ['control', result.control],
505
- ['treatment', result.treatment],
506
- ]) {
507
- for (const [variantName, compiled] of [
508
- ['normal', condition.normal],
509
- ['negative', condition.negative],
510
- ]) {
511
- const root = `compiled/${conditionName}-${variantName}`;
512
- files.set(`${root}/boundary-manifest.json`, jsonBytes(compiled.boundary_manifest));
513
- files.set(`${root}/boundary-verdict.json`, jsonBytes(compiled.boundary_verdict));
514
- files.set(`${root}/plan.json`, jsonBytes(compiled.plan_graph));
515
- }
516
- }
517
- files.set('behavior/pre-receipt.json', jsonBytes(result.transform.behavior_evidence.pre_receipt));
518
- files.set('behavior/post-receipt.json', jsonBytes(result.transform.behavior_evidence.post_receipt));
519
- files.set('behavior/evidence-envelope.json', jsonBytes(result.transform.behavior_evidence.envelope));
520
- files.set('transform/transform-artifact.json', jsonBytes(result.transform.artifact));
521
- files.set('transform/transform-receipt.json', jsonBytes(result.transform.receipt));
522
- files.set('transform/seam.patch', Buffer.from(result.transform.patch));
523
- files.set('plan-diff.json', jsonBytes(result.plan_diff));
524
- files.set('comparison.json', jsonBytes(result.comparison));
525
- files.set('hypothesis-evaluation.json', jsonBytes(result.hypothesis_evaluation));
526
- files.set('execution-evidence.json', jsonBytes(result.execution_evidence));
527
- files.set(`predecessor/${RC1_V6_REJECTED_PLAN_REF}`, Buffer.from(rejectedPlanBytes));
528
- files.set(`predecessor/${RC1_V6_PHASE_DECISION_REF}`, Buffer.from(phaseDecisionBytes));
529
- return files;
530
- }
531
-
532
- /** RC1 v6 causal artifactを既存treeへ上書きせずatomicに保存する。 */
533
- export async function writeRc1V6Artifacts(options = {}) {
534
- if (!exactRecord(options, ['repoRoot', 'result'])
535
- || typeof options.repoRoot !== 'string'
536
- || options.repoRoot.length === 0
537
- || options.result?.schema !== 'lattice.rc1.corrected_campaign_result.v6') {
538
- throw new TypeError('RC1 v6 artifact writer options are invalid');
539
- }
540
- const { repoRoot, result } = options;
541
- const artifactRoot = path.join(repoRoot, ARTIFACT_ROOT);
542
- try {
543
- await lstat(artifactRoot);
544
- throw new Error('RC1 v6 artifact root already exists; immutable evidence is not overwritten');
545
- } catch (error) {
546
- if (error?.code !== 'ENOENT') throw error;
547
- }
548
- const rejectedPlanBytes = await readFile(path.join(repoRoot, RC1_V6_REJECTED_PLAN_REF));
549
- const phaseDecisionBytes = await readFile(path.join(repoRoot, RC1_V6_PHASE_DECISION_REF));
550
- const files = artifactFiles(result, rejectedPlanBytes, phaseDecisionBytes);
551
- const manifest = {
552
- schema: 'lattice.rc1.artifact_manifest.v6',
553
- base_sha: result.base_sha,
554
- result_digest: digestArtifact(result.hypothesis_evaluation),
555
- files: [...files].map(([relativePath, bytes]) => ({
556
- path: relativePath,
557
- media_type: rc1V6ArtifactMediaType(relativePath),
558
- bytes: bytes.byteLength,
559
- sha256: sha256(bytes),
560
- })).sort((left, right) => left.path.localeCompare(right.path)),
561
- };
562
- const verification = verifyRc1V6CampaignArtifactSet({
563
- manifest,
564
- payloads: [...files].map(([relativePath, bytes]) => ({ path: relativePath, bytes })),
565
- });
566
- if (!verification.valid) {
567
- throw new TypeError(
568
- `RC1 v6 campaign artifact set is invalid: ${verification.failed_conditions.join(', ')}`,
569
- );
570
- }
571
-
572
- const parent = path.dirname(artifactRoot);
573
- await mkdir(parent, { recursive: true });
574
- const temporaryRoot = await mkdtemp(path.join(parent, '.v6-write-'));
575
- try {
576
- for (const [relativePath, bytes] of files) {
577
- const target = path.join(temporaryRoot, relativePath);
578
- await mkdir(path.dirname(target), { recursive: true });
579
- await writeFile(target, bytes);
580
- }
581
- await writeFile(path.join(temporaryRoot, 'artifact-manifest.json'), jsonBytes(manifest));
582
- await rename(temporaryRoot, artifactRoot);
583
- } catch (error) {
584
- await rm(temporaryRoot, { recursive: true, force: true });
585
- throw error;
586
- }
587
- return manifest;
588
- }
589
-
590
- /** immutable directoryをexact path setで再読込し、pure verifierへ渡す。 */
591
- export async function verifyRc1V6ArtifactsOnDisk(options = {}) {
592
- if (!exactRecord(options, ['repoRoot'])
593
- || typeof options.repoRoot !== 'string'
594
- || options.repoRoot.length === 0) {
595
- throw new TypeError('RC1 v6 disk verifier options are invalid');
596
- }
597
- const artifactRoot = path.join(options.repoRoot, ARTIFACT_ROOT);
598
- const manifestBytes = await readFile(path.join(artifactRoot, 'artifact-manifest.json'));
599
- let manifest;
600
- try {
601
- manifest = JSON.parse(manifestBytes.toString('utf8'));
602
- } catch {
603
- return {
604
- schema: 'lattice.rc1.artifact_set_verification.v6',
605
- valid: false,
606
- checks: [{ id: 'manifest_canonical', passed: false }],
607
- failed_conditions: ['manifest_canonical'],
608
- };
609
- }
610
- if (!jsonBytes(manifest).equals(manifestBytes)) {
611
- return {
612
- schema: 'lattice.rc1.artifact_set_verification.v6',
613
- valid: false,
614
- checks: [{ id: 'manifest_canonical', passed: false }],
615
- failed_conditions: ['manifest_canonical'],
616
- };
617
- }
618
- const payloads = await Promise.all(RC1_V6_ARTIFACT_PATHS.map(async (relativePath) => ({
619
- path: relativePath,
620
- bytes: await readFile(path.join(artifactRoot, relativePath)),
621
- })));
622
- return verifyRc1V6CampaignArtifactSet({ manifest, payloads });
623
- }
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
+ import { isDeepStrictEqual } from 'node:util';
15
+
16
+ import {
17
+ canonicalizeArtifact,
18
+ digestArtifact,
19
+ validateTransformArtifact,
20
+ } from './artifact-contracts.mjs';
21
+ import { RC1_BOUNDARY_COMPILER_CONTRACT } from './boundary-compiler.mjs';
22
+ import { runIsolatedTransform } from './isolation-runner.mjs';
23
+ import {
24
+ createRc1V6OracleRuntimeIdentity,
25
+ runRc1V6BlackBoxOracle,
26
+ } from './rc1-black-box-oracle.mjs';
27
+ import {
28
+ buildRc1V6PlanDiff,
29
+ compileRc1V6Comparison,
30
+ evaluateRc1V6Hypothesis,
31
+ RC1_V6_ARTIFACT_PATHS,
32
+ RC1_V6_PHASE_DECISION_REF,
33
+ RC1_V6_REJECTED_PLAN_REF,
34
+ rc1V6ArtifactMediaType,
35
+ verifyRc1V6CampaignArtifactSet,
36
+ } from './rc1-v6-artifact-set.mjs';
37
+ import { compileRc1V6BehaviorEvidence } from './rc1-v6-behavior-evidence.mjs';
38
+ import { createRc1V6EvidenceBundleDescriptor } from './rc1-v6-causal-binding.mjs';
39
+ import { runRc1V5Campaign } from './rc1-v5-campaign.mjs';
40
+ import {
41
+ bindRc1V6EvidenceBundle,
42
+ captureRc1V6LatticeSensorExecutable,
43
+ compileRc1V6BoundaryCondition,
44
+ createRc1V6ConditionRun,
45
+ sourceSnapshotFromRc1BehaviorSurface,
46
+ sourceSnapshotFromRc1TransformOutput,
47
+ } from './rc1-v6-measurement.mjs';
48
+ import { RC1_V5_TRANSFORM_PATHS } from './rc1-v5-transform.mjs';
49
+
50
+ const ARTIFACT_ROOT = 'research/campaigns/rc1/artifacts/v6';
51
+ const GIT_SHA1 = /^[0-9a-f]{40}$/;
52
+ const INPUT_KEYS = Object.freeze([
53
+ 'planInput',
54
+ 'candidateSpec',
55
+ 'normalManualEvidence',
56
+ 'negativeManualEvidence',
57
+ 'querySet',
58
+ 'oracle',
59
+ ]);
60
+
61
+ function exactRecord(value, keys) {
62
+ if (value === null || typeof value !== 'object' || Array.isArray(value)
63
+ || Object.getPrototypeOf(value) !== Object.prototype) {
64
+ return false;
65
+ }
66
+ const actual = Object.keys(value).sort();
67
+ const expected = [...keys].sort();
68
+ return actual.length === expected.length
69
+ && actual.every((key, index) => key === expected[index]);
70
+ }
71
+
72
+ function sha256(bytes) {
73
+ return createHash('sha256').update(bytes).digest('hex');
74
+ }
75
+
76
+ function roundedMilliseconds(startedAt) {
77
+ return Math.round((performance.now() - startedAt) * 1_000) / 1_000;
78
+ }
79
+
80
+ function jsonBytes(value) {
81
+ return Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8');
82
+ }
83
+
84
+ function run(command, args, { cwd, input } = {}) {
85
+ return new Promise((resolve, reject) => {
86
+ const child = spawn(command, args, {
87
+ cwd,
88
+ shell: false,
89
+ stdio: ['pipe', 'pipe', 'pipe'],
90
+ env: { ...process.env, NO_COLOR: '1' },
91
+ });
92
+ const stdout = [];
93
+ const stderr = [];
94
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
95
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
96
+ child.once('error', reject);
97
+ child.once('close', (code, signal) => {
98
+ const result = {
99
+ code,
100
+ signal,
101
+ stdout: Buffer.concat(stdout),
102
+ stderr: Buffer.concat(stderr),
103
+ };
104
+ if (code === 0 && signal === null) resolve(result);
105
+ else reject(Object.assign(
106
+ new Error(`${command} failed (${signal ?? code}): ${result.stderr.toString('utf8').trim()}`),
107
+ result,
108
+ ));
109
+ });
110
+ child.stdin.end(input);
111
+ });
112
+ }
113
+
114
+ function assertInputs(inputs) {
115
+ if (!exactRecord(inputs, INPUT_KEYS)) {
116
+ throw new TypeError('RC1 v6 campaign inputs must have the fixed exact shape');
117
+ }
118
+ for (const value of Object.values(inputs)) canonicalizeArtifact(value);
119
+ }
120
+
121
+ function legacySnapshotDigest(snapshot) {
122
+ return digestArtifact({
123
+ schema: 'lattice.rc1.fixed_surface_snapshot.v5',
124
+ files: snapshot.files.map((file) => ({
125
+ path: file.path,
126
+ state: file.state === 'file' ? 'file' : 'missing',
127
+ content_digest: file.content_digest,
128
+ })),
129
+ });
130
+ }
131
+
132
+ function compileCondition({ inputs, bundles, runs, expected, condition }) {
133
+ const outputs = bundles.map((bundle, index) => {
134
+ const common = {
135
+ planInput: inputs.planInput,
136
+ candidateSpec: inputs.candidateSpec,
137
+ querySet: inputs.querySet,
138
+ run: runs[index],
139
+ bundle,
140
+ expected,
141
+ };
142
+ return {
143
+ normal: compileRc1V6BoundaryCondition({
144
+ ...common,
145
+ manualEvidence: inputs.normalManualEvidence,
146
+ planVersion: `rc1-v6-${condition}`,
147
+ }),
148
+ negative: compileRc1V6BoundaryCondition({
149
+ ...common,
150
+ manualEvidence: inputs.negativeManualEvidence,
151
+ planVersion: `rc1-v6-${condition}-negative`,
152
+ }),
153
+ };
154
+ });
155
+ if (outputs.length !== 2 || digestArtifact(outputs[0]) !== digestArtifact(outputs[1])) {
156
+ throw new TypeError(`RC1 v6 ${condition} compilation is not reproducible`);
157
+ }
158
+ return outputs[0];
159
+ }
160
+
161
+ function updatedTransformArtifact(v5Artifact, control, controlSnapshot, querySet) {
162
+ const artifact = structuredClone(v5Artifact);
163
+ artifact.source = {
164
+ base_sha: v5Artifact.source.base_sha,
165
+ boundary_manifest_digest: control.normal.boundary_manifest_digest,
166
+ boundary_verdict_digest: control.normal.boundary_verdict_digest,
167
+ control_plan_digest: control.normal.plan_graph_digest,
168
+ query_set_digest: digestArtifact(querySet),
169
+ code_snapshot_digest: digestArtifact(controlSnapshot),
170
+ };
171
+ if (!validateTransformArtifact(artifact) || artifact.status !== 'accepted') {
172
+ throw new TypeError('RC1 v6 updated transform artifact is invalid');
173
+ }
174
+ return artifact;
175
+ }
176
+
177
+ async function applyPatch(worktreePath, patch) {
178
+ await run('git', ['apply', '--check', '--binary', '-'], { cwd: worktreePath, input: patch });
179
+ await run('git', ['apply', '--binary', '-'], { cwd: worktreePath, input: patch });
180
+ }
181
+
182
+ async function bindV6Behavior({
183
+ repoRoot,
184
+ baseSha,
185
+ oracle,
186
+ runtimeIdentity,
187
+ artifact,
188
+ patch,
189
+ }) {
190
+ const surfacePaths = [...artifact.scope.allowed_paths];
191
+ const preReceipt = await runRc1V6BlackBoxOracle({
192
+ repoRoot,
193
+ oracle,
194
+ role: 'pre_transform',
195
+ baseSha,
196
+ surfacePaths,
197
+ runtimeIdentity,
198
+ });
199
+ let postReceipt;
200
+ const isolated = await runIsolatedTransform({
201
+ repoRoot,
202
+ baseRef: baseSha,
203
+ allowedPaths: surfacePaths,
204
+ transform: async ({ worktreePath }) => {
205
+ await applyPatch(worktreePath, patch);
206
+ postReceipt = await runRc1V6BlackBoxOracle({
207
+ repoRoot: worktreePath,
208
+ oracle,
209
+ role: 'post_transform',
210
+ baseSha,
211
+ surfacePaths,
212
+ runtimeIdentity,
213
+ });
214
+ },
215
+ verifyCommands: [],
216
+ });
217
+ if (!Buffer.isBuffer(isolated.patch)
218
+ || !isolated.patch.equals(patch)
219
+ || isolated.sourceInvariant?.outcome !== 'passed'
220
+ || postReceipt?.outcome !== 'passed') {
221
+ throw new TypeError('RC1 v6 behavior observation did not preserve accepted patch identity');
222
+ }
223
+ const patchDigest = sha256(patch);
224
+ const envelope = compileRc1V6BehaviorEvidence({
225
+ oracle,
226
+ runtimeIdentity,
227
+ preReceipt,
228
+ postReceipt,
229
+ transformArtifact: artifact,
230
+ patchDigest,
231
+ });
232
+ return {
233
+ pre_receipt: preReceipt,
234
+ post_receipt: postReceipt,
235
+ envelope,
236
+ transform_artifact: artifact,
237
+ patch_digest: patchDigest,
238
+ source_invariant: isolated.sourceInvariant,
239
+ };
240
+ }
241
+
242
+ function v6Transform(v5Transform, artifact, behaviorEvidence, runtimeIdentity) {
243
+ const artifactDigest = digestArtifact(artifact);
244
+ const preimage = {
245
+ schema: 'lattice.rc1.seam_transform_receipt.v6',
246
+ status: 'accepted',
247
+ transform_artifact_digest: artifactDigest,
248
+ behavior_envelope_digest: behaviorEvidence.envelope.envelope_digest,
249
+ fixed_inputs_digest: digestArtifact(artifact.source),
250
+ runtime_identity_digest: digestArtifact(runtimeIdentity),
251
+ source_invariant: behaviorEvidence.source_invariant,
252
+ };
253
+ const receipt = { ...preimage, receipt_digest: digestArtifact(preimage) };
254
+ return {
255
+ artifact,
256
+ artifact_digest: artifactDigest,
257
+ receipt,
258
+ receipt_digest: receipt.receipt_digest,
259
+ patch: Buffer.from(v5Transform.patch),
260
+ behavior_evidence: {
261
+ pre_receipt: behaviorEvidence.pre_receipt,
262
+ post_receipt: behaviorEvidence.post_receipt,
263
+ envelope: behaviorEvidence.envelope,
264
+ transform_artifact: artifact,
265
+ patch_digest: behaviorEvidence.patch_digest,
266
+ },
267
+ };
268
+ }
269
+
270
+ function conditionRunRecords(v5Runs, runs) {
271
+ return v5Runs.map((record, index) => ({
272
+ run: runs[index],
273
+ patch_digest: record.patch_digest,
274
+ index_elapsed_ms: record.index_elapsed_ms,
275
+ query_elapsed_ms: record.query_elapsed_ms,
276
+ source_invariant: record.source_invariant,
277
+ source_invariant_digest: record.source_invariant_digest,
278
+ }));
279
+ }
280
+
281
+ /** v5のfresh機構を観測器として再利用し、全結果をv6 causal chainへ再compileする。 */
282
+ export async function runRc1V6Campaign(options = {}) {
283
+ if (!exactRecord(options, ['repoRoot', 'baseRef', 'inputs'])) {
284
+ throw new TypeError('RC1 v6 campaign options must have the fixed exact shape');
285
+ }
286
+ const { repoRoot, baseRef, inputs } = options;
287
+ if (typeof repoRoot !== 'string' || repoRoot.length === 0
288
+ || typeof baseRef !== 'string' || baseRef.length === 0) {
289
+ throw new TypeError('RC1 v6 campaign repoRoot and baseRef are required');
290
+ }
291
+ assertInputs(inputs);
292
+ const fixedInputs = structuredClone(inputs);
293
+ const baseSha = (await run('git', ['rev-parse', '--verify', `${baseRef}^{commit}`], { cwd: repoRoot }))
294
+ .stdout.toString('utf8').trim();
295
+ if (!GIT_SHA1.test(baseSha)) throw new TypeError('RC1 v6 campaign base SHA is invalid');
296
+ const startedAt = performance.now();
297
+ const [sensorCapture, compilerSourceBytes, oracleExecutorBytes] = await Promise.all([
298
+ captureRc1V6LatticeSensorExecutable(),
299
+ readFile(new URL('./boundary-compiler.mjs', import.meta.url)),
300
+ readFile(new URL('./rc1-black-box-oracle.mjs', import.meta.url)),
301
+ ]);
302
+ const sensorIdentity = sensorCapture.identity;
303
+ const runtimeIdentity = await createRc1V6OracleRuntimeIdentity();
304
+ if (runtimeIdentity.executor_source_digest !== sha256(oracleExecutorBytes)) {
305
+ throw new TypeError('RC1 v6 oracle runtime identityが保存executor bytesと一致しない');
306
+ }
307
+ const v5 = await runRc1V5Campaign({ repoRoot, baseRef: baseSha, inputs: fixedInputs });
308
+ const [finalLatticeSensorCapture, finalCompilerSourceBytes, finalOracleExecutorBytes] =
309
+ await Promise.all([
310
+ captureRc1V6LatticeSensorExecutable(),
311
+ readFile(new URL('./boundary-compiler.mjs', import.meta.url)),
312
+ readFile(new URL('./rc1-black-box-oracle.mjs', import.meta.url)),
313
+ ]);
314
+ if (!isDeepStrictEqual(sensorCapture, finalLatticeSensorCapture)
315
+ || !compilerSourceBytes.equals(finalCompilerSourceBytes)
316
+ || !oracleExecutorBytes.equals(finalOracleExecutorBytes)) {
317
+ throw new TypeError('RC1 v6実行主体のidentityがcampaign中にdriftした');
318
+ }
319
+
320
+ const controlSnapshot = sourceSnapshotFromRc1BehaviorSurface(
321
+ v5.transform.behavior_evidence.pre_receipt.surface,
322
+ );
323
+ const treatmentSnapshot = sourceSnapshotFromRc1TransformOutput(v5.transform.artifact);
324
+ const postSnapshot = sourceSnapshotFromRc1BehaviorSurface(
325
+ v5.transform.behavior_evidence.post_receipt.surface,
326
+ );
327
+ if (!isDeepStrictEqual(treatmentSnapshot, postSnapshot)) {
328
+ throw new TypeError('RC1 v6 treatment snapshot does not equal accepted transform output');
329
+ }
330
+ for (const record of v5.condition_runs.control) {
331
+ if (record.code_snapshot_digest !== legacySnapshotDigest(controlSnapshot)) {
332
+ throw new TypeError(`${record.run_id} hidden v5 snapshot does not match typed control preimage`);
333
+ }
334
+ }
335
+ for (const record of v5.condition_runs.treatment) {
336
+ if (record.code_snapshot_digest !== legacySnapshotDigest(treatmentSnapshot)) {
337
+ throw new TypeError(`${record.run_id} hidden v5 snapshot does not match typed treatment preimage`);
338
+ }
339
+ }
340
+
341
+ const evidenceBundles = v5.evidence_bundles.map((bundle) => bindRc1V6EvidenceBundle({
342
+ bundle,
343
+ base_sha: baseSha,
344
+ patch_digest: bundle.condition === 'treatment' ? v5.transform.artifact.patch.digest : null,
345
+ snapshot: bundle.condition === 'treatment' ? treatmentSnapshot : controlSnapshot,
346
+ sensor_identity: sensorIdentity,
347
+ query_set_digest: digestArtifact(fixedInputs.querySet),
348
+ }));
349
+ const runs = evidenceBundles.map(createRc1V6ConditionRun);
350
+ const controlBundles = evidenceBundles.filter(({ condition }) => condition === 'control');
351
+ const treatmentBundles = evidenceBundles.filter(({ condition }) => condition === 'treatment');
352
+ const controlRuns = runs.filter(({ condition }) => condition === 'control');
353
+ const treatmentRuns = runs.filter(({ condition }) => condition === 'treatment');
354
+ const controlExpected = {
355
+ base_sha: baseSha,
356
+ patch_digest: null,
357
+ snapshot: controlSnapshot,
358
+ sensor_identity: sensorIdentity,
359
+ query_set_digest: digestArtifact(fixedInputs.querySet),
360
+ };
361
+ const treatmentExpected = {
362
+ base_sha: baseSha,
363
+ patch_digest: v5.transform.artifact.patch.digest,
364
+ snapshot: treatmentSnapshot,
365
+ sensor_identity: sensorIdentity,
366
+ query_set_digest: digestArtifact(fixedInputs.querySet),
367
+ };
368
+ const control = compileCondition({
369
+ inputs: fixedInputs,
370
+ bundles: controlBundles,
371
+ runs: controlRuns,
372
+ expected: controlExpected,
373
+ condition: 'control',
374
+ });
375
+ const treatment = compileCondition({
376
+ inputs: fixedInputs,
377
+ bundles: treatmentBundles,
378
+ runs: treatmentRuns,
379
+ expected: treatmentExpected,
380
+ condition: 'treatment',
381
+ });
382
+
383
+ const artifact = updatedTransformArtifact(
384
+ v5.transform.artifact,
385
+ control,
386
+ controlSnapshot,
387
+ fixedInputs.querySet,
388
+ );
389
+ const behaviorEvidence = await bindV6Behavior({
390
+ repoRoot,
391
+ baseSha,
392
+ oracle: fixedInputs.oracle,
393
+ runtimeIdentity,
394
+ artifact,
395
+ patch: v5.transform.patch,
396
+ });
397
+ const transform = v6Transform(v5.transform, artifact, behaviorEvidence, runtimeIdentity);
398
+ const rejectedPlanBytes = await readFile(path.join(repoRoot, RC1_V6_REJECTED_PLAN_REF));
399
+ const phaseDecisionBytes = await readFile(path.join(repoRoot, RC1_V6_PHASE_DECISION_REF));
400
+ const planDiff = buildRc1V6PlanDiff({
401
+ control,
402
+ treatment,
403
+ transform,
404
+ evidenceBundles,
405
+ rejectedPlanBytes,
406
+ phaseDecisionBytes,
407
+ });
408
+ const sourceInvariant = {
409
+ control: v5.condition_runs.control.every(({ source_invariant: receipt }) => (
410
+ receipt.outcome === 'passed'
411
+ )),
412
+ treatment: behaviorEvidence.source_invariant.outcome === 'passed'
413
+ && v5.condition_runs.treatment.every(({ source_invariant: receipt }) => (
414
+ receipt.outcome === 'passed'
415
+ )),
416
+ };
417
+ const compilerSourceDigest = sha256(compilerSourceBytes);
418
+ const comparison = compileRc1V6Comparison({
419
+ baseSha,
420
+ inputs: fixedInputs,
421
+ runtimeIdentity,
422
+ sensorIdentity,
423
+ compilerSourceDigest,
424
+ control,
425
+ treatment,
426
+ evidenceBundles,
427
+ transform,
428
+ planDiff,
429
+ sourceInvariant,
430
+ });
431
+ const hypothesisEvaluation = evaluateRc1V6Hypothesis(comparison);
432
+ if (!hypothesisEvaluation.supported) {
433
+ throw new TypeError(
434
+ `RC1 v6 hypothesis is not supported: ${hypothesisEvaluation.failed_conditions.join(', ')}`,
435
+ );
436
+ }
437
+ const conditionRuns = {
438
+ control: conditionRunRecords(v5.condition_runs.control, controlRuns),
439
+ treatment: conditionRunRecords(v5.condition_runs.treatment, treatmentRuns),
440
+ };
441
+ const executionEvidence = {
442
+ schema: 'lattice.rc1.corrected_campaign_execution_evidence.v6',
443
+ base_sha: baseSha,
444
+ elapsed_ms: roundedMilliseconds(startedAt),
445
+ compiler_source_digest: compilerSourceDigest,
446
+ sensor_identity_digest: digestArtifact(sensorIdentity),
447
+ runtime_identity_digest: digestArtifact(runtimeIdentity),
448
+ run_descriptor_digests: runs.map(({ evidence_bundle_descriptor_digest: digest }) => digest),
449
+ transform_artifact_digest: transform.artifact_digest,
450
+ behavior_envelope_digest: transform.behavior_evidence.envelope.envelope_digest,
451
+ plan_diff_digest: digestArtifact(planDiff),
452
+ comparison_digest: digestArtifact(comparison),
453
+ hypothesis_evaluation_digest: digestArtifact(hypothesisEvaluation),
454
+ source_invariant: sourceInvariant,
455
+ };
456
+ return {
457
+ schema: 'lattice.rc1.corrected_campaign_result.v6',
458
+ base_sha: baseSha,
459
+ inputs: fixedInputs,
460
+ runtime_identity: runtimeIdentity,
461
+ sensor_identity: sensorIdentity,
462
+ identity_sources: {
463
+ compiler: compilerSourceBytes,
464
+ oracle_executor: oracleExecutorBytes,
465
+ sensor_executable: sensorCapture.executable_bytes,
466
+ },
467
+ evidence_bundles: evidenceBundles,
468
+ runs,
469
+ condition_runs: conditionRuns,
470
+ control,
471
+ treatment,
472
+ transform,
473
+ plan_diff: planDiff,
474
+ comparison,
475
+ hypothesis_evaluation: hypothesisEvaluation,
476
+ execution_evidence: executionEvidence,
477
+ };
478
+ }
479
+
480
+ function artifactFiles(result, rejectedPlanBytes, phaseDecisionBytes) {
481
+ const files = new Map();
482
+ for (const [key, relativePath] of [
483
+ ['planInput', 'inputs/plan-input.json'],
484
+ ['candidateSpec', 'inputs/candidate-spec-v2.json'],
485
+ ['normalManualEvidence', 'inputs/manual-evidence.normal.json'],
486
+ ['negativeManualEvidence', 'inputs/manual-evidence.shared-state-negative.json'],
487
+ ['querySet', 'inputs/query-set-v2.json'],
488
+ ['oracle', 'inputs/behavior-oracle-v2.json'],
489
+ ]) {
490
+ files.set(relativePath, jsonBytes(result.inputs[key]));
491
+ }
492
+ files.set('inputs/oracle-runtime-identity.json', jsonBytes(result.runtime_identity));
493
+ files.set('inputs/lattice-sensor-identity.json', jsonBytes(result.sensor_identity));
494
+ files.set('identity/boundary-compiler.mjs', Buffer.from(result.identity_sources.compiler));
495
+ files.set('identity/black-box-oracle.mjs', Buffer.from(result.identity_sources.oracle_executor));
496
+ files.set('identity/lattice-sensor-executable', Buffer.from(result.identity_sources.sensor_executable));
497
+ for (const bundle of result.evidence_bundles) {
498
+ files.set(`evidence/${bundle.run_id}.json`, jsonBytes(bundle));
499
+ }
500
+ for (const runValue of result.runs) {
501
+ files.set(`runs/${runValue.run_id}.json`, jsonBytes(runValue));
502
+ }
503
+ for (const [conditionName, condition] of [
504
+ ['control', result.control],
505
+ ['treatment', result.treatment],
506
+ ]) {
507
+ for (const [variantName, compiled] of [
508
+ ['normal', condition.normal],
509
+ ['negative', condition.negative],
510
+ ]) {
511
+ const root = `compiled/${conditionName}-${variantName}`;
512
+ files.set(`${root}/boundary-manifest.json`, jsonBytes(compiled.boundary_manifest));
513
+ files.set(`${root}/boundary-verdict.json`, jsonBytes(compiled.boundary_verdict));
514
+ files.set(`${root}/plan.json`, jsonBytes(compiled.plan_graph));
515
+ }
516
+ }
517
+ files.set('behavior/pre-receipt.json', jsonBytes(result.transform.behavior_evidence.pre_receipt));
518
+ files.set('behavior/post-receipt.json', jsonBytes(result.transform.behavior_evidence.post_receipt));
519
+ files.set('behavior/evidence-envelope.json', jsonBytes(result.transform.behavior_evidence.envelope));
520
+ files.set('transform/transform-artifact.json', jsonBytes(result.transform.artifact));
521
+ files.set('transform/transform-receipt.json', jsonBytes(result.transform.receipt));
522
+ files.set('transform/seam.patch', Buffer.from(result.transform.patch));
523
+ files.set('plan-diff.json', jsonBytes(result.plan_diff));
524
+ files.set('comparison.json', jsonBytes(result.comparison));
525
+ files.set('hypothesis-evaluation.json', jsonBytes(result.hypothesis_evaluation));
526
+ files.set('execution-evidence.json', jsonBytes(result.execution_evidence));
527
+ files.set(`predecessor/${RC1_V6_REJECTED_PLAN_REF}`, Buffer.from(rejectedPlanBytes));
528
+ files.set(`predecessor/${RC1_V6_PHASE_DECISION_REF}`, Buffer.from(phaseDecisionBytes));
529
+ return files;
530
+ }
531
+
532
+ /** RC1 v6 causal artifactを既存treeへ上書きせずatomicに保存する。 */
533
+ export async function writeRc1V6Artifacts(options = {}) {
534
+ if (!exactRecord(options, ['repoRoot', 'result'])
535
+ || typeof options.repoRoot !== 'string'
536
+ || options.repoRoot.length === 0
537
+ || options.result?.schema !== 'lattice.rc1.corrected_campaign_result.v6') {
538
+ throw new TypeError('RC1 v6 artifact writer options are invalid');
539
+ }
540
+ const { repoRoot, result } = options;
541
+ const artifactRoot = path.join(repoRoot, ARTIFACT_ROOT);
542
+ try {
543
+ await lstat(artifactRoot);
544
+ throw new Error('RC1 v6 artifact root already exists; immutable evidence is not overwritten');
545
+ } catch (error) {
546
+ if (error?.code !== 'ENOENT') throw error;
547
+ }
548
+ const rejectedPlanBytes = await readFile(path.join(repoRoot, RC1_V6_REJECTED_PLAN_REF));
549
+ const phaseDecisionBytes = await readFile(path.join(repoRoot, RC1_V6_PHASE_DECISION_REF));
550
+ const files = artifactFiles(result, rejectedPlanBytes, phaseDecisionBytes);
551
+ const manifest = {
552
+ schema: 'lattice.rc1.artifact_manifest.v6',
553
+ base_sha: result.base_sha,
554
+ result_digest: digestArtifact(result.hypothesis_evaluation),
555
+ files: [...files].map(([relativePath, bytes]) => ({
556
+ path: relativePath,
557
+ media_type: rc1V6ArtifactMediaType(relativePath),
558
+ bytes: bytes.byteLength,
559
+ sha256: sha256(bytes),
560
+ })).sort((left, right) => left.path.localeCompare(right.path)),
561
+ };
562
+ const verification = verifyRc1V6CampaignArtifactSet({
563
+ manifest,
564
+ payloads: [...files].map(([relativePath, bytes]) => ({ path: relativePath, bytes })),
565
+ });
566
+ if (!verification.valid) {
567
+ throw new TypeError(
568
+ `RC1 v6 campaign artifact set is invalid: ${verification.failed_conditions.join(', ')}`,
569
+ );
570
+ }
571
+
572
+ const parent = path.dirname(artifactRoot);
573
+ await mkdir(parent, { recursive: true });
574
+ const temporaryRoot = await mkdtemp(path.join(parent, '.v6-write-'));
575
+ try {
576
+ for (const [relativePath, bytes] of files) {
577
+ const target = path.join(temporaryRoot, relativePath);
578
+ await mkdir(path.dirname(target), { recursive: true });
579
+ await writeFile(target, bytes);
580
+ }
581
+ await writeFile(path.join(temporaryRoot, 'artifact-manifest.json'), jsonBytes(manifest));
582
+ await rename(temporaryRoot, artifactRoot);
583
+ } catch (error) {
584
+ await rm(temporaryRoot, { recursive: true, force: true });
585
+ throw error;
586
+ }
587
+ return manifest;
588
+ }
589
+
590
+ /** immutable directoryをexact path setで再読込し、pure verifierへ渡す。 */
591
+ export async function verifyRc1V6ArtifactsOnDisk(options = {}) {
592
+ if (!exactRecord(options, ['repoRoot'])
593
+ || typeof options.repoRoot !== 'string'
594
+ || options.repoRoot.length === 0) {
595
+ throw new TypeError('RC1 v6 disk verifier options are invalid');
596
+ }
597
+ const artifactRoot = path.join(options.repoRoot, ARTIFACT_ROOT);
598
+ const manifestBytes = await readFile(path.join(artifactRoot, 'artifact-manifest.json'));
599
+ let manifest;
600
+ try {
601
+ manifest = JSON.parse(manifestBytes.toString('utf8'));
602
+ } catch {
603
+ return {
604
+ schema: 'lattice.rc1.artifact_set_verification.v6',
605
+ valid: false,
606
+ checks: [{ id: 'manifest_canonical', passed: false }],
607
+ failed_conditions: ['manifest_canonical'],
608
+ };
609
+ }
610
+ if (!jsonBytes(manifest).equals(manifestBytes)) {
611
+ return {
612
+ schema: 'lattice.rc1.artifact_set_verification.v6',
613
+ valid: false,
614
+ checks: [{ id: 'manifest_canonical', passed: false }],
615
+ failed_conditions: ['manifest_canonical'],
616
+ };
617
+ }
618
+ const payloads = await Promise.all(RC1_V6_ARTIFACT_PATHS.map(async (relativePath) => ({
619
+ path: relativePath,
620
+ bytes: await readFile(path.join(artifactRoot, relativePath)),
621
+ })));
622
+ return verifyRc1V6CampaignArtifactSet({ manifest, payloads });
623
+ }