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