@quolu/lattice 0.52.2 → 0.52.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. package/src/witness-scaffold.mjs +180 -180
@@ -1,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
+ }