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