@quolu/lattice 0.52.3 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-bridge.mjs +25 -0
  5. package/bin/lattice-hub.mjs +67 -0
  6. package/bin/lattice-mcp.mjs +0 -0
  7. package/bin/lattice-scripted-adapter.mjs +0 -0
  8. package/bin/lattice-scripted-worker.mjs +0 -0
  9. package/bin/lattice-work-order-adapter.mjs +0 -0
  10. package/bin/lattice.mjs +0 -0
  11. package/docs/bridge-setup.md +132 -132
  12. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  13. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  14. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  15. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  16. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  17. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  18. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  19. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  20. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  21. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  22. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  23. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  24. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  25. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  26. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  27. package/package.json +103 -103
  28. package/sensor/LICENSE +21 -21
  29. package/sensor/NOTICE +19 -19
  30. package/sensor/dist/bin/lattice-sensor.js +9 -9
  31. package/sensor/dist/db/index.js +24 -24
  32. package/sensor/dist/db/migrations.js +41 -41
  33. package/sensor/dist/db/queries.js +164 -164
  34. package/sensor/dist/db/schema.sql +205 -205
  35. package/sensor/dist/directory.js +5 -5
  36. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  49. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  50. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  51. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  52. package/sensor/dist/mcp/server-instructions.js +95 -95
  53. package/sensor/package.json +56 -56
  54. package/src/artifact-contracts-v2.mjs +325 -325
  55. package/src/artifact-contracts.mjs +895 -895
  56. package/src/boundary-compiler.mjs +712 -712
  57. package/src/boundary-observation-compiler-v2.mjs +344 -344
  58. package/src/bounded-seam.mjs +230 -230
  59. package/src/bridge-address.mjs +107 -107
  60. package/src/bridge-cli.mjs +303 -297
  61. package/src/bridge-config.mjs +382 -346
  62. package/src/bridge-daemon.mjs +378 -378
  63. package/src/bridge-hub-heartbeat.mjs +170 -0
  64. package/src/bridge-hub-protocol.mjs +198 -0
  65. package/src/bridge-hub-server.mjs +544 -0
  66. package/src/bridge-launch-agent.mjs +323 -323
  67. package/src/bridge-registrar.mjs +102 -102
  68. package/src/bridge-server.mjs +376 -376
  69. package/src/cli-help.mjs +308 -308
  70. package/src/cli-stdio.mjs +40 -40
  71. package/src/control-compiler.mjs +532 -532
  72. package/src/dag-chain.mjs +261 -261
  73. package/src/factory-diagnostics.mjs +188 -188
  74. package/src/git-process.mjs +72 -0
  75. package/src/hash-chain.mjs +76 -76
  76. package/src/hooks-cli.mjs +1057 -1057
  77. package/src/isolation-runner.mjs +409 -409
  78. package/src/node-version-guard.mjs +44 -44
  79. package/src/project-cli.mjs +3 -3
  80. package/src/project-identity.mjs +130 -130
  81. package/src/rc1-black-box-oracle.mjs +906 -906
  82. package/src/rc1-comparison.mjs +154 -154
  83. package/src/rc1-evidence-bundle.mjs +456 -456
  84. package/src/rc1-v4-campaign.mjs +708 -708
  85. package/src/rc1-v4-transform.mjs +467 -467
  86. package/src/rc1-v5-artifact-set.mjs +855 -855
  87. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  88. package/src/rc1-v5-campaign.mjs +797 -797
  89. package/src/rc1-v5-transform.mjs +421 -421
  90. package/src/rc1-v6-artifact-set.mjs +807 -807
  91. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  92. package/src/rc1-v6-campaign.mjs +623 -623
  93. package/src/rc1-v6-causal-binding.mjs +473 -473
  94. package/src/rc1-v6-measurement.mjs +313 -313
  95. package/src/rc2-artifact-set.mjs +1584 -1584
  96. package/src/rc2-campaign.mjs +1506 -1506
  97. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  98. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  99. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  100. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  101. package/src/rc3-actual-dogfood.mjs +652 -652
  102. package/src/rc3-dogfood-scaffold.mjs +315 -315
  103. package/src/rc3-scripted-campaign.mjs +1383 -1383
  104. package/src/rc4-stage1-dogfood.mjs +673 -673
  105. package/src/runtime-adapter-registry.mjs +524 -524
  106. package/src/runtime-cli.mjs +4588 -4588
  107. package/src/runtime-contracts.mjs +824 -824
  108. package/src/runtime-control-store.mjs +604 -604
  109. package/src/runtime-controller-protocol.mjs +587 -587
  110. package/src/runtime-decision-verifier.mjs +701 -701
  111. package/src/runtime-diff-observer.mjs +361 -361
  112. package/src/runtime-direct-os-observer.mjs +301 -301
  113. package/src/runtime-driver-state.mjs +166 -166
  114. package/src/runtime-engine.mjs +779 -779
  115. package/src/runtime-errors.mjs +356 -356
  116. package/src/runtime-event-store.mjs +189 -189
  117. package/src/runtime-front-end.mjs +925 -925
  118. package/src/runtime-gate-store.mjs +481 -481
  119. package/src/runtime-hold-recompile.mjs +916 -916
  120. package/src/runtime-io-sentinel.mjs +391 -391
  121. package/src/runtime-lifecycle-lock.mjs +294 -294
  122. package/src/runtime-managed-supervisor.mjs +1490 -1490
  123. package/src/runtime-multi-epoch-store.mjs +838 -838
  124. package/src/runtime-projection.mjs +269 -269
  125. package/src/runtime-pull-intake.mjs +1192 -1192
  126. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  127. package/src/runtime-scripted-executor.mjs +163 -163
  128. package/src/runtime-scripted-worktree.mjs +104 -104
  129. package/src/runtime-seam-resolve.mjs +428 -428
  130. package/src/runtime-seam-treatment.mjs +173 -173
  131. package/src/runtime-socket-owner.mjs +125 -125
  132. package/src/runtime-work-order-contracts.mjs +91 -91
  133. package/src/runtime-work-order-controller.mjs +1171 -1171
  134. package/src/runtime-worktree-executor.mjs +199 -199
  135. package/src/schedulability-compiler-v2.mjs +303 -303
  136. package/src/schedulability-verifier-v2.mjs +317 -317
  137. package/src/seam-apply.mjs +549 -549
  138. package/src/seam-commit-shared.mjs +22 -22
  139. package/src/seam-commit-transform.mjs +81 -81
  140. package/src/seam-commit.mjs +18 -18
  141. package/src/seam-cost.mjs +322 -322
  142. package/src/seam-derivation.mjs +188 -188
  143. package/src/seam-gate.mjs +146 -146
  144. package/src/seam-proposal-contracts.mjs +446 -446
  145. package/src/seam-proposal-queries.mjs +521 -521
  146. package/src/seam-proposal.mjs +2011 -2011
  147. package/src/seam-ref.mjs +33 -33
  148. package/src/seam-rewrite.mjs +286 -286
  149. package/src/seam-transform.mjs +554 -554
  150. package/src/seam-verification.mjs +260 -260
  151. package/src/sensor-adapter.mjs +432 -432
  152. package/src/sensor-cli.mjs +139 -139
  153. package/src/sensor-diff.mjs +661 -661
  154. package/src/sensor-node-runtime.mjs +53 -53
  155. package/src/sensor-runtime.mjs +52 -52
  156. package/src/timestamp-contract.mjs +8 -8
  157. package/src/todo-audit-pending.mjs +91 -91
  158. package/src/todo-chain.mjs +178 -178
  159. package/src/todo-cli.mjs +8 -8
  160. package/src/todo-contracts.mjs +728 -728
  161. package/src/todo-dashboard-registry.mjs +573 -573
  162. package/src/todo-dispatch-shape.mjs +190 -190
  163. package/src/todo-gantt-html-independence.mjs +239 -239
  164. package/src/todo-gantt-html-shared.mjs +226 -226
  165. package/src/todo-gantt-html-style.mjs +131 -131
  166. package/src/todo-gantt-html.mjs +248 -248
  167. package/src/todo-gantt-layout.mjs +974 -974
  168. package/src/todo-gantt-live.mjs +361 -361
  169. package/src/todo-gantt-nested.mjs +263 -263
  170. package/src/todo-gantt-presentation.mjs +217 -217
  171. package/src/todo-gantt-scope.mjs +123 -123
  172. package/src/todo-gantt-svg.mjs +353 -353
  173. package/src/todo-independence-contracts.mjs +595 -595
  174. package/src/todo-independence-guidance.mjs +322 -322
  175. package/src/todo-independence.mjs +640 -640
  176. package/src/todo-markdown-renderer.mjs +260 -260
  177. package/src/todo-migration.mjs +448 -448
  178. package/src/todo-narrative-anchor.mjs +130 -130
  179. package/src/todo-note-store.mjs +629 -629
  180. package/src/todo-parallel-candidates.mjs +114 -114
  181. package/src/todo-revision.mjs +995 -995
  182. package/src/todo-split.mjs +472 -472
  183. package/src/todo-status.mjs +690 -690
  184. package/src/todo-store-git-transaction.mjs +418 -418
  185. package/src/todo-store.mjs +42 -21
  186. package/src/treatment-compiler.mjs +728 -728
  187. package/src/treatment-runner.mjs +656 -656
  188. package/src/witness-scaffold.mjs +180 -180
@@ -1,673 +1,673 @@
1
- import { spawn } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import { mkdir, mkdtemp, readFile, rename, writeFile } from 'node:fs/promises';
4
- import { tmpdir } from 'node:os';
5
- import path from 'node:path';
6
-
7
- import { digestArtifact } from './artifact-contracts.mjs';
8
- import { collectSensorEvidence } from './sensor-adapter.mjs';
9
- import { compileRuntimePlanV1, evidenceFromCollectedOutcomes } from './runtime-front-end.mjs';
10
- import {
11
- adjudicatePendingReceipts,
12
- buildExecutorPackets,
13
- buildNextRunEvent,
14
- classifyCheckpointObservation,
15
- closeRunIfComplete,
16
- dispatchReadyFrontier,
17
- initializeRunEvents,
18
- } from './runtime-engine.mjs';
19
- import {
20
- decideHoldAndCarryOver,
21
- recompileNextEpochPlan,
22
- routeConflictTreatment,
23
- } from './runtime-hold-recompile.mjs';
24
- import { captureWorktreeDiff, detectCheckpointFindings } from './runtime-diff-observer.mjs';
25
- import {
26
- computeReadyFrontier,
27
- recomputeHoldDecision,
28
- recomputeReceiptDecisions,
29
- } from './runtime-decision-verifier.mjs';
30
- import { verifyRunEventChain } from './runtime-event-store.mjs';
31
- import { projectRuntimeState } from './runtime-projection.mjs';
32
- import { selfDigest, validateRunRequest } from './runtime-contracts.mjs';
33
-
34
- /**
35
- * RC4 Stage 1 dotagents dogfood driver(plan
36
- * `docs/plan_lattice_rc4_dotagents_dogfood.md`「Stage 1」節、契約は
37
- * ADR 0046)。
38
- *
39
- * RC3-I(`rc3-actual-dogfood.mjs`)と同型のstate fileベースstep driver。
40
- * 相違点はscaffoldを使わず、親が用意したdotagents disposable clone
41
- * (tmpdir配下、正規repoへ不着地)を直接writer targetにする点と、
42
- * ADR 0046 Decision 2のexecutor隔離契約(`isolation_contract`)を各
43
- * executor packetへ焼き込む点にある。TODO集合・witnessは呼び出し側が
44
- * 用意する`lattice.run_request.v1`ファイル(requestPath)が正であり、
45
- * 本driverへハードコードしない。
46
- *
47
- * known conflict注入(rogue write)は行わない。conflictは(あれば)
48
- * request内のTODO write intersectionからplan compile時に自然導出される
49
- * plan.conflictsとしてのみ現れる。hold/recompile step(rc3の
50
- * `holdAndRecompile`相当)は受け皿として残すが、conflictがdispatch内
51
- * serializationで解決するrunでは未使用のままでよい。
52
- */
53
-
54
- const RUN_TIMESTAMP = '2026-07-17T00:00:00.000Z';
55
- const RUN_ID = 'rc4s1-actual-01';
56
-
57
- /** ADR 0046 Decision 2のexecutor隔離契約(packetへ焼き込む固定内容)。 */
58
- const ISOLATION_CONTRACT = Object.freeze({
59
- isolated_home: true,
60
- forbidden_commands: Object.freeze([
61
- 'install.sh',
62
- 'spotter install',
63
- 'apply-codex-config',
64
- 'claude mcp add',
65
- 'codex mcp add',
66
- ]),
67
- write_scope: 'assigned worktree only',
68
- no_git_mutations: true,
69
- note: 'clone搬送正典がhost変更手順を含んでもpacket契約が優先する',
70
- });
71
-
72
- function fail(reason) {
73
- throw new TypeError(`rc4 stage1 dogfood契約違反: ${reason}`);
74
- }
75
-
76
- function run(command, args, cwd) {
77
- return new Promise((resolve, reject) => {
78
- const child = spawn(command, args, { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
79
- const stdout = [];
80
- const stderr = [];
81
- child.stdout.on('data', (chunk) => stdout.push(chunk));
82
- child.stderr.on('data', (chunk) => stderr.push(chunk));
83
- child.once('error', reject);
84
- child.once('close', (code, signal) => {
85
- if (code === 0 && signal === null) resolve(Buffer.concat(stdout).toString('utf8'));
86
- else {
87
- reject(new TypeError(
88
- `${command} ${args[0]} failed (${signal ?? code}): ${Buffer.concat(stderr).toString('utf8').trim()}`,
89
- ));
90
- }
91
- });
92
- });
93
- }
94
-
95
- function statePath(stateDir) {
96
- return path.join(stateDir, 'rc4s1-state.json');
97
- }
98
-
99
- async function loadState(stateDir) {
100
- return JSON.parse(await readFile(statePath(stateDir), 'utf8'));
101
- }
102
-
103
- async function saveState(stateDir, state) {
104
- await writeFile(statePath(stateDir), `${JSON.stringify(state, null, 1)}\n`);
105
- }
106
-
107
- /** 純粋なengine packet(exact-shape契約)へ、isolation_contractを外挿したview。 */
108
- function withIsolationContract(packets) {
109
- return Object.fromEntries(Object.entries(packets).map(([todoId, packet]) => (
110
- [todoId, { ...packet, isolation_contract: ISOLATION_CONTRACT }]
111
- )));
112
- }
113
-
114
- async function provisionWorktree(state, todoId, attempt) {
115
- const worktreeRoot = await mkdtemp(path.join(tmpdir(), `lattice-rc4s1-${todoId}-`));
116
- const worktreePath = path.join(worktreeRoot, 'tree');
117
- await run('git', ['worktree', 'add', '--detach', worktreePath, state.baseSha], state.cloneRoot);
118
- return {
119
- handle: `stage1-${todoId}-h${attempt}`,
120
- worktree_id: `wt-${todoId}-a${attempt}`,
121
- worktree_root: worktreeRoot,
122
- worktree_path: worktreePath,
123
- attempt,
124
- active: true,
125
- };
126
- }
127
-
128
- /** state駆動のexecutor adapter(dispatch=worktree provision、重複はstateで拒否)。 */
129
- function stateAdapter(state) {
130
- return {
131
- kind: 'actual-agent',
132
- async dispatch({ packet } = {}) {
133
- const existing = state.worktrees[packet.todo_id];
134
- if (existing !== undefined && existing.active) {
135
- fail(`同一TODOの重複dispatchを拒否する: ${packet.todo_id}`);
136
- }
137
- const attempt = existing === undefined ? 1 : existing.attempt + 1;
138
- const provisioned = await provisionWorktree(state, packet.todo_id, attempt);
139
- state.worktrees[packet.todo_id] = provisioned;
140
- return { executor_handle: provisioned.handle, worktree_id: provisioned.worktree_id };
141
- },
142
- };
143
- }
144
-
145
- /**
146
- * step 1: request読込・sensor evidence収集・compile・全TODO dispatch
147
- * (worktree provision)まで。返り値のworktree pathsへ、親が実agentを
148
- * dispatchする。packetにはisolation_contractが含まれる。
149
- */
150
- export async function initStage1Run({ latticeRoot, cloneRoot, requestPath, stateDir }) {
151
- await mkdir(stateDir, { recursive: true });
152
- const request = JSON.parse(await readFile(requestPath, 'utf8'));
153
- if (!validateRunRequest(request)) fail('run_requestがlattice.run_request.v1 contractを満たさない');
154
-
155
- const collected = await collectSensorEvidence({ cwd: cloneRoot, querySet: request.sensor_query_set });
156
- const sensorEvidence = evidenceFromCollectedOutcomes({ querySet: request.sensor_query_set, collected });
157
- const compiled = compileRuntimePlanV1({
158
- request,
159
- sensorEvidence,
160
- planRef: `plan-${request.request_id}-e1`,
161
- planEpoch: 1,
162
- predecessorRefs: [],
163
- });
164
- if (compiled.outcome !== 'dispatchable') {
165
- fail(`compileがdispatchableにならない: ${compiled.outcome}${compiled.code ? ` ${compiled.code}` : ''}`);
166
- }
167
- const packets = buildExecutorPackets({ plan: compiled.plan, manifests: compiled.manifests });
168
-
169
- const state = {
170
- schema: 'lattice.rc4.stage1_dogfood_state.v1',
171
- latticeRoot,
172
- cloneRoot,
173
- requestPath,
174
- baseSha: request.repo.base_sha,
175
- request,
176
- plan: compiled.plan,
177
- manifests: compiled.manifests,
178
- packets,
179
- newPlan: null,
180
- rebindPackets: null,
181
- redispatchPackets: null,
182
- holdDecision: null,
183
- planDiff: null,
184
- events: initializeRunEvents({
185
- runId: RUN_ID, request, plan: compiled.plan, manifests: compiled.manifests, recordedAt: RUN_TIMESTAMP,
186
- }),
187
- worktrees: {},
188
- provider_runs: [],
189
- diagnostics: { residual_worktrees: [] },
190
- };
191
- const adapter = stateAdapter(state);
192
- const dispatched = await dispatchReadyFrontier({
193
- runId: RUN_ID, plan: state.plan, events: state.events,
194
- packets, manifests: state.manifests, adapter, recordedAt: RUN_TIMESTAMP,
195
- });
196
- if (dispatched.failure) fail(`dispatch失敗: ${dispatched.failure.message}`);
197
- state.events = dispatched.events;
198
- await saveState(stateDir, state);
199
- const packetsWithIsolation = withIsolationContract(packets);
200
- return {
201
- dispatched: dispatched.dispatched,
202
- worktrees: Object.fromEntries(Object.entries(state.worktrees).map(([todoId, entry]) => (
203
- [todoId, { path: entry.worktree_path, handle: entry.handle, packet: packetsWithIsolation[todoId] }]
204
- ))),
205
- };
206
- }
207
-
208
- /**
209
- * epoch内の後続wave dispatch(conflict pairの片方が受理され次第、残り分を
210
- * dispatchする)。redispatchStage1Next(epoch2専用)とは別に、hold/recompileを
211
- * 経由せずconflict pairが自然にserializeするrunで必要になる同一plan/packets上の
212
- * 追加dispatch呼び出し。dispatchReadyFrontier自体はrc3と同一primitive。
213
- */
214
- export async function dispatchStage1NextWave({ stateDir }) {
215
- const state = await loadState(stateDir);
216
- const adapter = stateAdapter(state);
217
- const dispatched = await dispatchReadyFrontier({
218
- runId: RUN_ID, plan: state.plan, events: state.events,
219
- packets: state.packets, manifests: state.manifests, adapter, recordedAt: RUN_TIMESTAMP,
220
- });
221
- if (dispatched.failure) fail(`dispatch失敗: ${dispatched.failure.message}`);
222
- state.events = dispatched.events;
223
- await saveState(stateDir, state);
224
- const packetsWithIsolation = withIsolationContract(state.packets);
225
- return {
226
- dispatched: dispatched.dispatched,
227
- worktrees: Object.fromEntries(dispatched.dispatched.map((todoId) => (
228
- [todoId, {
229
- path: state.worktrees[todoId].worktree_path,
230
- handle: state.worktrees[todoId].handle,
231
- packet: packetsWithIsolation[todoId],
232
- }]
233
- ))),
234
- };
235
- }
236
-
237
- /** provider観測(agent handle・時刻・状態遷移)をledgerへ追記する。core eventsへは入れない。 */
238
- export async function recordProviderObservation({ stateDir, observation }) {
239
- const state = await loadState(stateDir);
240
- state.provider_runs.push(observation);
241
- await saveState(stateDir, state);
242
- return { count: state.provider_runs.length };
243
- }
244
-
245
- /** 指定TODOのworktree実diffをcheckpoint観測し、findingがあればconflict+freezeまで進める。 */
246
- export async function observeStage1Checkpoint({ stateDir, todoId, planKey = 'plan' }) {
247
- const state = await loadState(stateDir);
248
- const worktree = state.worktrees[todoId];
249
- if (worktree === undefined || !worktree.active) fail(`active worktreeがない: ${todoId}`);
250
- const plan = state[planKey];
251
- const checkpoint = await captureWorktreeDiff({
252
- worktreePath: worktree.worktree_path,
253
- baseSha: state.baseSha,
254
- });
255
- let events = [...state.events];
256
- events.push(buildNextRunEvent({
257
- events,
258
- runId: RUN_ID,
259
- kind: 'checkpoint_observed',
260
- planEpoch: plan.plan_epoch,
261
- subject: { kind: 'todo', ref: todoId },
262
- payload: structuredClone(checkpoint),
263
- recordedAt: RUN_TIMESTAMP,
264
- }));
265
- const classifyPackets = { ...state.packets, ...(state.redispatchPackets ?? {}) };
266
- const classified = classifyCheckpointObservation({
267
- runId: RUN_ID, plan, events, packets: classifyPackets, manifests: state.manifests, todoId,
268
- detect: detectCheckpointFindings, recordedAt: RUN_TIMESTAMP,
269
- });
270
- state.events = classified.events;
271
- await saveState(stateDir, state);
272
- return {
273
- findings: classified.findings,
274
- scope_expanded: classified.scope_expanded,
275
- checkpoint_digest: checkpoint.checkpoint_digest,
276
- };
277
- }
278
-
279
- /** hold裁定→recompile→(carried TODOの)rebind packet発行までを一括で行う受け皿。 */
280
- export async function holdAndRecompileStage1({ stateDir, additionalConflicts }) {
281
- const state = await loadState(stateDir);
282
- const held = decideHoldAndCarryOver({
283
- runId: RUN_ID,
284
- request: state.request,
285
- plan: state.plan,
286
- manifests: state.manifests,
287
- packets: state.packets,
288
- events: state.events,
289
- recordedAt: RUN_TIMESTAMP,
290
- });
291
- const lane = routeConflictTreatment({
292
- finding: held.holdDecision.finding,
293
- predeclaredTreatments: [],
294
- });
295
- const recompiled = recompileNextEpochPlan({
296
- runId: RUN_ID,
297
- request: state.request,
298
- plan: state.plan,
299
- manifests: state.manifests,
300
- packets: state.packets,
301
- events: held.events,
302
- holdDecision: held.holdDecision,
303
- additionalConflicts,
304
- recordedAt: RUN_TIMESTAMP,
305
- });
306
- state.events = recompiled.events;
307
- state.holdDecision = held.holdDecision;
308
- state.newPlan = recompiled.newPlan;
309
- state.planDiff = recompiled.planDiff;
310
- state.rebindPackets = recompiled.rebindPackets;
311
- state.redispatchPackets = recompiled.redispatchPackets;
312
- for (const todoId of held.holdDecision.continue_set) {
313
- state.packets[todoId] = {
314
- ...state.packets[todoId],
315
- plan_epoch: recompiled.newPlan.plan_epoch,
316
- };
317
- }
318
- for (const todoId of held.holdDecision.hold_set) {
319
- if (state.worktrees[todoId] !== undefined) state.worktrees[todoId].active = false;
320
- }
321
- await saveState(stateDir, state);
322
- return {
323
- hold: held.holdDecision.hold_set,
324
- continue: held.holdDecision.continue_set,
325
- lane: lane.lane,
326
- new_epoch: recompiled.newPlan.plan_epoch,
327
- };
328
- }
329
-
330
- /** terminal receipt(現attemptの最終checkpointへbind)を記録し、受理裁定まで行う。 */
331
- export async function terminalStage1Receipt({ stateDir, todoId, planKey }) {
332
- const state = await loadState(stateDir);
333
- const plan = state[planKey];
334
- const worktree = state.worktrees[todoId];
335
- if (worktree === undefined || !worktree.active) fail(`active worktreeがない: ${todoId}`);
336
- const packet = planKey === 'newPlan' && state.redispatchPackets?.[todoId] !== undefined
337
- ? state.redispatchPackets[todoId]
338
- : state.packets[todoId];
339
- const stateProjection = projectRuntimeState({ events: state.events });
340
- const dispatchRecord = stateProjection.dispatches[todoId];
341
- const attemptCheckpoints = stateProjection.checkpoints.filter((entry) => (
342
- entry.todo_id === todoId && entry.sequence > dispatchRecord.sequence
343
- ));
344
- if (attemptCheckpoints.length === 0) fail(`checkpoint未観測でterminalにできない: ${todoId}`);
345
- const lastCheckpoint = attemptCheckpoints[attemptCheckpoints.length - 1].payload;
346
- const receipt = {
347
- schema: 'lattice.executor_receipt.v1',
348
- receipt_id: `${todoId}-a${worktree.attempt}-r1`,
349
- executor_handle: worktree.handle,
350
- worktree_id: worktree.worktree_id,
351
- base_sha: packet.base_sha,
352
- plan_epoch: packet.plan_epoch,
353
- packet_digest: dispatchRecord.payload.packet_digest,
354
- todo_id: todoId,
355
- checkpoint_digest: lastCheckpoint.checkpoint_digest,
356
- observed_diff: lastCheckpoint.diff.entries.map(({ path: p, change }) => ({ path: p, change })),
357
- };
358
- receipt.receipt_digest = selfDigest(receipt, 'receipt_digest');
359
- let events = [...state.events];
360
- events.push(buildNextRunEvent({
361
- events,
362
- runId: RUN_ID,
363
- kind: 'receipt_recorded',
364
- planEpoch: receipt.plan_epoch,
365
- subject: { kind: 'todo', ref: todoId },
366
- payload: receipt,
367
- recordedAt: RUN_TIMESTAMP,
368
- }));
369
- // Stage 2着地素材: worktree破棄前にpatch本文を捕獲する。receipt schemaは不変のまま
370
- // (replay契約を壊さない)、patchはstate/artifactの別文書として保存し、
371
- // receipt_idとcheckpoint_digestでreceiptへbindする。捕獲失敗はfail loud
372
- // (Stage 1受理はできたのに着地素材が無い、という無言の欠損を作らない)。
373
- await run('git', ['add', '-A'], worktree.worktree_path);
374
- const patchBytes = await run(
375
- 'git',
376
- ['-c', 'core.quotepath=false', 'diff', '--cached', '--binary'],
377
- worktree.worktree_path,
378
- );
379
- if (patchBytes.length === 0) fail(`patch捕獲が空: ${todoId}(observed_diffと矛盾)`);
380
- if (state.patches === undefined) state.patches = {};
381
- state.patches[receipt.receipt_id] = {
382
- receipt_id: receipt.receipt_id,
383
- todo_id: todoId,
384
- checkpoint_digest: lastCheckpoint.checkpoint_digest,
385
- paths: receipt.observed_diff.map(({ path: p }) => p),
386
- patch: patchBytes,
387
- // ADR 0051 Decision 4: path一致だけではpatch本文の取り違え・破損を検出できない。
388
- // 捕獲bytesのdigestを併記し、verifierが保存bytesから再計算して束縛を検査する。
389
- patch_sha256: createHash('sha256').update(patchBytes).digest('hex'),
390
- };
391
- let cleanup = { cleanup_ok: true, residual_paths: [] };
392
- try {
393
- await run('git', ['worktree', 'remove', '--force', worktree.worktree_path], state.cloneRoot);
394
- } catch (error) {
395
- cleanup = {
396
- cleanup_ok: false,
397
- residual_paths: [worktree.worktree_root],
398
- message: String(error?.message ?? error),
399
- };
400
- }
401
- events.push(buildNextRunEvent({
402
- events,
403
- runId: RUN_ID,
404
- kind: 'executor_terminal',
405
- planEpoch: plan.plan_epoch,
406
- subject: { kind: 'todo', ref: todoId },
407
- payload: { executor_handle: worktree.handle, terminal_state: 'reported', cleanup },
408
- recordedAt: RUN_TIMESTAMP,
409
- }));
410
- const adjudicated = adjudicatePendingReceipts({
411
- runId: RUN_ID, plan, events, recordedAt: RUN_TIMESTAMP,
412
- });
413
- state.events = adjudicated.events;
414
- state.worktrees[todoId].active = false;
415
- await saveState(stateDir, state);
416
- return { decisions: adjudicated.decisions, receipt_id: receipt.receipt_id };
417
- }
418
-
419
- /** epoch 2のredispatch(1件ずつ。frontier/conflict規則はengineに従う)。hold未発火なら未使用。 */
420
- export async function redispatchStage1Next({ stateDir }) {
421
- const state = await loadState(stateDir);
422
- const adapter = stateAdapter(state);
423
- const dispatched = await dispatchReadyFrontier({
424
- runId: RUN_ID,
425
- plan: state.newPlan,
426
- events: state.events,
427
- packets: state.redispatchPackets,
428
- manifests: state.manifests,
429
- adapter,
430
- recordedAt: RUN_TIMESTAMP,
431
- });
432
- if (dispatched.failure) fail(`redispatch失敗: ${dispatched.failure.message}`);
433
- state.events = dispatched.events;
434
- await saveState(stateDir, state);
435
- const redispatchPacketsWithIsolation = withIsolationContract(state.redispatchPackets);
436
- return {
437
- dispatched: dispatched.dispatched,
438
- worktrees: Object.fromEntries(dispatched.dispatched.map((todoId) => (
439
- [todoId, {
440
- path: state.worktrees[todoId].worktree_path,
441
- handle: state.worktrees[todoId].handle,
442
- packet: redispatchPacketsWithIsolation[todoId],
443
- }]
444
- ))),
445
- };
446
- }
447
-
448
- /** run close+残worktree掃除(残存は記録)。 */
449
- export async function closeStage1Run({ stateDir }) {
450
- const state = await loadState(stateDir);
451
- const closed = closeRunIfComplete({
452
- runId: RUN_ID, plan: state.newPlan ?? state.plan, events: state.events, recordedAt: RUN_TIMESTAMP,
453
- });
454
- state.events = closed.events;
455
- const residual = [];
456
- for (const [todoId, worktree] of Object.entries(state.worktrees)) {
457
- if (!worktree.active) continue;
458
- try {
459
- await run('git', ['worktree', 'remove', '--force', worktree.worktree_path], state.cloneRoot);
460
- worktree.active = false;
461
- } catch (error) {
462
- residual.push({ todo_id: todoId, path: worktree.worktree_root, message: String(error?.message ?? error) });
463
- }
464
- }
465
- state.diagnostics.residual_worktrees = residual;
466
- await saveState(stateDir, state);
467
- return { closed: closed.closed, residual };
468
- }
469
-
470
- /** artifact v3(RC4 Stage 1 dotagents dogfood)をatomic no-overwriteで発行する。 */
471
- export async function publishStage1Artifact({ stateDir, artifactRoot }) {
472
- const state = await loadState(stateDir);
473
- await mkdir(path.dirname(artifactRoot), { recursive: true });
474
- const staging = `${artifactRoot}.staging`;
475
- try {
476
- await mkdir(staging);
477
- } catch (error) {
478
- fail(`stagingを排他作成できない: ${String(error?.message ?? error)}`);
479
- }
480
- const packetsDocument = {
481
- epoch1: withIsolationContract(state.packets),
482
- redispatch: state.redispatchPackets === null ? null : withIsolationContract(state.redispatchPackets),
483
- };
484
- const documents = {
485
- 'request.json': state.request,
486
- 'plan.json': state.plan,
487
- 'new-plan.json': state.newPlan,
488
- 'manifests.json': state.manifests,
489
- 'packets.json': packetsDocument,
490
- 'hold-decision.json': state.holdDecision,
491
- 'plan-diff.json': state.planDiff,
492
- 'events.json': state.events,
493
- 'provider-runs.json': state.provider_runs,
494
- 'diagnostics.json': state.diagnostics,
495
- 'patches.json': state.patches ?? {},
496
- };
497
- const manifestEntries = {};
498
- for (const [name, document] of Object.entries(documents)) {
499
- await writeFile(path.join(staging, name), `${JSON.stringify(document, null, 1)}\n`);
500
- manifestEntries[name] = digestArtifact(document);
501
- }
502
- const manifest = {
503
- schema: 'lattice.rc4.stage1_dogfood_manifest.v1',
504
- run_id: RUN_ID,
505
- clone: {
506
- lattice_root: state.latticeRoot,
507
- clone_base_sha: state.baseSha,
508
- },
509
- document_digests: manifestEntries,
510
- };
511
- await writeFile(path.join(staging, 'dogfood-manifest.json'), `${JSON.stringify(manifest, null, 1)}\n`);
512
- try {
513
- let exists = true;
514
- try {
515
- await readFile(path.join(artifactRoot, 'dogfood-manifest.json'));
516
- } catch (error) {
517
- exists = error?.code !== 'ENOENT';
518
- }
519
- if (exists) throw new TypeError('既存artifact rootが存在する');
520
- await rename(staging, artifactRoot);
521
- } catch (error) {
522
- const { rm } = await import('node:fs/promises');
523
- await rm(staging, { recursive: true, force: true });
524
- fail(`artifact発行に失敗(上書き禁止): ${String(error?.message ?? error)}`);
525
- }
526
- return { manifest };
527
- }
528
-
529
- function isolationContractComplete(contract) {
530
- if (contract === null || typeof contract !== 'object') return false;
531
- return contract.isolated_home === true
532
- && Array.isArray(contract.forbidden_commands)
533
- && ['install.sh', 'spotter install', 'apply-codex-config', 'claude mcp add', 'codex mcp add']
534
- .every((command) => contract.forbidden_commands.includes(command))
535
- && contract.write_scope === 'assigned worktree only'
536
- && contract.no_git_mutations === true
537
- && typeof contract.note === 'string' && contract.note.length > 0;
538
- }
539
-
540
- /** artifact v3を保存bytesだけから再検証する。 */
541
- export async function verifyStage1ArtifactOnDisk({ artifactRoot }) {
542
- const manifest = JSON.parse(await readFile(path.join(artifactRoot, 'dogfood-manifest.json'), 'utf8'));
543
- const checks = [];
544
- const documents = {};
545
- for (const [name, digest] of Object.entries(manifest.document_digests)) {
546
- const document = JSON.parse(await readFile(path.join(artifactRoot, name), 'utf8'));
547
- documents[name] = document;
548
- checks.push({ id: `digest:${name}`, passed: digestArtifact(document) === digest });
549
- }
550
- const events = documents['events.json'];
551
- const plan = documents['plan.json'];
552
- const newPlan = documents['new-plan.json'];
553
- const chain = verifyRunEventChain({ events });
554
- checks.push({ id: 'event_chain', passed: chain.valid });
555
- for (const [label, targetPlan] of [['e1', plan], ['e2', newPlan]]) {
556
- if (targetPlan === null) continue;
557
- events.forEach((event, index) => {
558
- if (event.kind !== 'dispatch_decided' || event.plan_epoch !== targetPlan.plan_epoch) return;
559
- const recomputed = computeReadyFrontier({ plan: targetPlan, events: events.slice(0, index) });
560
- checks.push({
561
- id: `dispatch_replay:${label}:seq${event.sequence}`,
562
- passed: JSON.stringify(event.payload.dispatchable) === JSON.stringify(recomputed.dispatchable),
563
- });
564
- });
565
- }
566
- const holdDecision = documents['hold-decision.json'];
567
- const holdIndex = events.findIndex((event) => event.kind === 'hold_decided');
568
- if (holdDecision !== null && holdIndex !== -1) {
569
- const recomputedHold = recomputeHoldDecision({
570
- plan, events: events.slice(0, holdIndex), manifests: documents['manifests.json'],
571
- });
572
- checks.push({
573
- id: 'hold_replay',
574
- passed: JSON.stringify(recomputedHold.hold_set) === JSON.stringify(holdDecision.hold_set)
575
- && JSON.stringify(recomputedHold.continue_set) === JSON.stringify(holdDecision.continue_set),
576
- });
577
- }
578
- // receipt裁定の再計算: 記録済みoutcome event(accepted/rejected+detail)と
579
- // replay結果の双方向・reason粒度の一致を要求する(RC3-J P1採用の踏襲)。
580
- const recordedOutcomes = new Map();
581
- for (const event of events) {
582
- if (event.kind !== 'receipt_accepted' && event.kind !== 'receipt_rejected') continue;
583
- const receiptId = event.payload?.receipt_id;
584
- if (typeof receiptId !== 'string') continue;
585
- recordedOutcomes.set(receiptId, {
586
- decision: event.kind === 'receipt_accepted' ? 'accepted' : 'rejected',
587
- detail: event.payload?.detail ?? null,
588
- adjudication_epoch: event.plan_epoch,
589
- });
590
- }
591
- const planByEpoch = new Map([plan, newPlan]
592
- .filter((entry) => entry !== null)
593
- .map((entry) => [entry.plan_epoch, entry]));
594
- let receiptReplayOk = recordedOutcomes.size > 0;
595
- for (const [receiptId, recorded] of recordedOutcomes) {
596
- const adjudicationPlan = planByEpoch.get(recorded.adjudication_epoch);
597
- if (adjudicationPlan === undefined) {
598
- receiptReplayOk = false;
599
- continue;
600
- }
601
- const outcomeIndex = events.findIndex((event) => (
602
- (event.kind === 'receipt_accepted' || event.kind === 'receipt_rejected')
603
- && event.payload?.receipt_id === receiptId
604
- ));
605
- const replayed = recomputeReceiptDecisions({
606
- plan: adjudicationPlan,
607
- events: events.slice(0, outcomeIndex),
608
- }).decisions.find(({ receipt_id: id }) => id === receiptId);
609
- if (replayed === undefined
610
- || replayed.decision !== recorded.decision
611
- || (recorded.decision === 'rejected' && replayed.detail !== recorded.detail)) {
612
- receiptReplayOk = false;
613
- }
614
- }
615
- if (newPlan !== null) {
616
- for (const decision of recomputeReceiptDecisions({ plan: newPlan, events }).decisions) {
617
- if (decision.decision === 'accepted' && !recordedOutcomes.has(decision.receipt_id)) {
618
- receiptReplayOk = false;
619
- }
620
- }
621
- }
622
- checks.push({ id: 'receipt_replay_bidirectional', passed: receiptReplayOk });
623
- checks.push({
624
- id: 'provider_separation',
625
- passed: events.every((event) => (
626
- JSON.stringify(event.payload).includes('provider_handle') === false
627
- )),
628
- });
629
- // Stage 2着地素材: patches.jsonがある場合(patch捕獲実装後のartifact)、
630
- // accepted receiptごとにpatch entryが存在し、receipt observed_diffのpathと
631
- // 一致することを要求する。旧artifact(v3/v3-hold・patches.json不在)は
632
- // manifest記載文書のみ検査する既存規則のまま。
633
- if (Object.hasOwn(manifest.document_digests, 'patches.json')) {
634
- const patches = documents['patches.json'];
635
- const receiptByld = new Map();
636
- for (const event of events) {
637
- if (event.kind !== 'receipt_accepted') continue;
638
- receiptByld.set(event.payload.receipt_id, event);
639
- }
640
- const receiptEvents = events.filter((event) => event.kind === 'receipt_recorded');
641
- // ADR 0051 Decision 4の強化: path照合に加え、(a) checkpoint_digest/todo_idを
642
- // receipt_recorded payloadと照合し、(b) patch bytesのsha256を再計算して保存digestと
643
- // 突合する。(b)は世代判定=1 entryでもpatch_sha256を持つartifactは全entryへ必須
644
- // (旧v4-landing世代=全entry不在は(a)までで検査し、per-entryのfail-openを作らない)。
645
- const patchEntries = Object.values(patches);
646
- const shaGeneration = patchEntries.some((entry) => entry.patch_sha256 !== undefined);
647
- const patchesOk = patchEntries.length > 0 && [...receiptByld.keys()].every((receiptId) => {
648
- const patch = patches[receiptId];
649
- if (patch === undefined || typeof patch.patch !== 'string' || patch.patch.length === 0) return false;
650
- const recorded = receiptEvents.find((event) => event.payload.receipt_id === receiptId);
651
- if (recorded === undefined) return false;
652
- if (patch.checkpoint_digest !== recorded.payload.checkpoint_digest) return false;
653
- if (patch.todo_id !== recorded.payload.todo_id) return false;
654
- const receiptPaths = [...recorded.payload.observed_diff.map(({ path: p }) => p)].sort();
655
- if (JSON.stringify([...patch.paths].sort()) !== JSON.stringify(receiptPaths)) return false;
656
- if (shaGeneration) {
657
- if (typeof patch.patch_sha256 !== 'string') return false;
658
- return createHash('sha256').update(patch.patch).digest('hex') === patch.patch_sha256;
659
- }
660
- return true;
661
- });
662
- checks.push({ id: 'patches_bound_to_accepted_receipts', passed: patchesOk });
663
- }
664
- // ADR 0046 Decision 2: 全executor packetがisolation_contractを完備していること。
665
- const packetsDocument = documents['packets.json'];
666
- const allPacketGroups = [packetsDocument.epoch1, packetsDocument.redispatch].filter((group) => group !== null);
667
- const allPacketsIsolated = allPacketGroups.every((group) => (
668
- Object.values(group).every((packet) => isolationContractComplete(packet.isolation_contract))
669
- ));
670
- checks.push({ id: 'isolation_contract_complete', passed: allPacketsIsolated });
671
- const failed = checks.filter(({ passed }) => !passed).map(({ id }) => id);
672
- return { valid: failed.length === 0, checks, failed_conditions: failed };
673
- }
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdir, mkdtemp, readFile, rename, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ import { digestArtifact } from './artifact-contracts.mjs';
8
+ import { collectSensorEvidence } from './sensor-adapter.mjs';
9
+ import { compileRuntimePlanV1, evidenceFromCollectedOutcomes } from './runtime-front-end.mjs';
10
+ import {
11
+ adjudicatePendingReceipts,
12
+ buildExecutorPackets,
13
+ buildNextRunEvent,
14
+ classifyCheckpointObservation,
15
+ closeRunIfComplete,
16
+ dispatchReadyFrontier,
17
+ initializeRunEvents,
18
+ } from './runtime-engine.mjs';
19
+ import {
20
+ decideHoldAndCarryOver,
21
+ recompileNextEpochPlan,
22
+ routeConflictTreatment,
23
+ } from './runtime-hold-recompile.mjs';
24
+ import { captureWorktreeDiff, detectCheckpointFindings } from './runtime-diff-observer.mjs';
25
+ import {
26
+ computeReadyFrontier,
27
+ recomputeHoldDecision,
28
+ recomputeReceiptDecisions,
29
+ } from './runtime-decision-verifier.mjs';
30
+ import { verifyRunEventChain } from './runtime-event-store.mjs';
31
+ import { projectRuntimeState } from './runtime-projection.mjs';
32
+ import { selfDigest, validateRunRequest } from './runtime-contracts.mjs';
33
+
34
+ /**
35
+ * RC4 Stage 1 dotagents dogfood driver(plan
36
+ * `docs/plan_lattice_rc4_dotagents_dogfood.md`「Stage 1」節、契約は
37
+ * ADR 0046)。
38
+ *
39
+ * RC3-I(`rc3-actual-dogfood.mjs`)と同型のstate fileベースstep driver。
40
+ * 相違点はscaffoldを使わず、親が用意したdotagents disposable clone
41
+ * (tmpdir配下、正規repoへ不着地)を直接writer targetにする点と、
42
+ * ADR 0046 Decision 2のexecutor隔離契約(`isolation_contract`)を各
43
+ * executor packetへ焼き込む点にある。TODO集合・witnessは呼び出し側が
44
+ * 用意する`lattice.run_request.v1`ファイル(requestPath)が正であり、
45
+ * 本driverへハードコードしない。
46
+ *
47
+ * known conflict注入(rogue write)は行わない。conflictは(あれば)
48
+ * request内のTODO write intersectionからplan compile時に自然導出される
49
+ * plan.conflictsとしてのみ現れる。hold/recompile step(rc3の
50
+ * `holdAndRecompile`相当)は受け皿として残すが、conflictがdispatch内
51
+ * serializationで解決するrunでは未使用のままでよい。
52
+ */
53
+
54
+ const RUN_TIMESTAMP = '2026-07-17T00:00:00.000Z';
55
+ const RUN_ID = 'rc4s1-actual-01';
56
+
57
+ /** ADR 0046 Decision 2のexecutor隔離契約(packetへ焼き込む固定内容)。 */
58
+ const ISOLATION_CONTRACT = Object.freeze({
59
+ isolated_home: true,
60
+ forbidden_commands: Object.freeze([
61
+ 'install.sh',
62
+ 'spotter install',
63
+ 'apply-codex-config',
64
+ 'claude mcp add',
65
+ 'codex mcp add',
66
+ ]),
67
+ write_scope: 'assigned worktree only',
68
+ no_git_mutations: true,
69
+ note: 'clone搬送正典がhost変更手順を含んでもpacket契約が優先する',
70
+ });
71
+
72
+ function fail(reason) {
73
+ throw new TypeError(`rc4 stage1 dogfood契約違反: ${reason}`);
74
+ }
75
+
76
+ function run(command, args, cwd) {
77
+ return new Promise((resolve, reject) => {
78
+ const child = spawn(command, args, { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
79
+ const stdout = [];
80
+ const stderr = [];
81
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
82
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
83
+ child.once('error', reject);
84
+ child.once('close', (code, signal) => {
85
+ if (code === 0 && signal === null) resolve(Buffer.concat(stdout).toString('utf8'));
86
+ else {
87
+ reject(new TypeError(
88
+ `${command} ${args[0]} failed (${signal ?? code}): ${Buffer.concat(stderr).toString('utf8').trim()}`,
89
+ ));
90
+ }
91
+ });
92
+ });
93
+ }
94
+
95
+ function statePath(stateDir) {
96
+ return path.join(stateDir, 'rc4s1-state.json');
97
+ }
98
+
99
+ async function loadState(stateDir) {
100
+ return JSON.parse(await readFile(statePath(stateDir), 'utf8'));
101
+ }
102
+
103
+ async function saveState(stateDir, state) {
104
+ await writeFile(statePath(stateDir), `${JSON.stringify(state, null, 1)}\n`);
105
+ }
106
+
107
+ /** 純粋なengine packet(exact-shape契約)へ、isolation_contractを外挿したview。 */
108
+ function withIsolationContract(packets) {
109
+ return Object.fromEntries(Object.entries(packets).map(([todoId, packet]) => (
110
+ [todoId, { ...packet, isolation_contract: ISOLATION_CONTRACT }]
111
+ )));
112
+ }
113
+
114
+ async function provisionWorktree(state, todoId, attempt) {
115
+ const worktreeRoot = await mkdtemp(path.join(tmpdir(), `lattice-rc4s1-${todoId}-`));
116
+ const worktreePath = path.join(worktreeRoot, 'tree');
117
+ await run('git', ['worktree', 'add', '--detach', worktreePath, state.baseSha], state.cloneRoot);
118
+ return {
119
+ handle: `stage1-${todoId}-h${attempt}`,
120
+ worktree_id: `wt-${todoId}-a${attempt}`,
121
+ worktree_root: worktreeRoot,
122
+ worktree_path: worktreePath,
123
+ attempt,
124
+ active: true,
125
+ };
126
+ }
127
+
128
+ /** state駆動のexecutor adapter(dispatch=worktree provision、重複はstateで拒否)。 */
129
+ function stateAdapter(state) {
130
+ return {
131
+ kind: 'actual-agent',
132
+ async dispatch({ packet } = {}) {
133
+ const existing = state.worktrees[packet.todo_id];
134
+ if (existing !== undefined && existing.active) {
135
+ fail(`同一TODOの重複dispatchを拒否する: ${packet.todo_id}`);
136
+ }
137
+ const attempt = existing === undefined ? 1 : existing.attempt + 1;
138
+ const provisioned = await provisionWorktree(state, packet.todo_id, attempt);
139
+ state.worktrees[packet.todo_id] = provisioned;
140
+ return { executor_handle: provisioned.handle, worktree_id: provisioned.worktree_id };
141
+ },
142
+ };
143
+ }
144
+
145
+ /**
146
+ * step 1: request読込・sensor evidence収集・compile・全TODO dispatch
147
+ * (worktree provision)まで。返り値のworktree pathsへ、親が実agentを
148
+ * dispatchする。packetにはisolation_contractが含まれる。
149
+ */
150
+ export async function initStage1Run({ latticeRoot, cloneRoot, requestPath, stateDir }) {
151
+ await mkdir(stateDir, { recursive: true });
152
+ const request = JSON.parse(await readFile(requestPath, 'utf8'));
153
+ if (!validateRunRequest(request)) fail('run_requestがlattice.run_request.v1 contractを満たさない');
154
+
155
+ const collected = await collectSensorEvidence({ cwd: cloneRoot, querySet: request.sensor_query_set });
156
+ const sensorEvidence = evidenceFromCollectedOutcomes({ querySet: request.sensor_query_set, collected });
157
+ const compiled = compileRuntimePlanV1({
158
+ request,
159
+ sensorEvidence,
160
+ planRef: `plan-${request.request_id}-e1`,
161
+ planEpoch: 1,
162
+ predecessorRefs: [],
163
+ });
164
+ if (compiled.outcome !== 'dispatchable') {
165
+ fail(`compileがdispatchableにならない: ${compiled.outcome}${compiled.code ? ` ${compiled.code}` : ''}`);
166
+ }
167
+ const packets = buildExecutorPackets({ plan: compiled.plan, manifests: compiled.manifests });
168
+
169
+ const state = {
170
+ schema: 'lattice.rc4.stage1_dogfood_state.v1',
171
+ latticeRoot,
172
+ cloneRoot,
173
+ requestPath,
174
+ baseSha: request.repo.base_sha,
175
+ request,
176
+ plan: compiled.plan,
177
+ manifests: compiled.manifests,
178
+ packets,
179
+ newPlan: null,
180
+ rebindPackets: null,
181
+ redispatchPackets: null,
182
+ holdDecision: null,
183
+ planDiff: null,
184
+ events: initializeRunEvents({
185
+ runId: RUN_ID, request, plan: compiled.plan, manifests: compiled.manifests, recordedAt: RUN_TIMESTAMP,
186
+ }),
187
+ worktrees: {},
188
+ provider_runs: [],
189
+ diagnostics: { residual_worktrees: [] },
190
+ };
191
+ const adapter = stateAdapter(state);
192
+ const dispatched = await dispatchReadyFrontier({
193
+ runId: RUN_ID, plan: state.plan, events: state.events,
194
+ packets, manifests: state.manifests, adapter, recordedAt: RUN_TIMESTAMP,
195
+ });
196
+ if (dispatched.failure) fail(`dispatch失敗: ${dispatched.failure.message}`);
197
+ state.events = dispatched.events;
198
+ await saveState(stateDir, state);
199
+ const packetsWithIsolation = withIsolationContract(packets);
200
+ return {
201
+ dispatched: dispatched.dispatched,
202
+ worktrees: Object.fromEntries(Object.entries(state.worktrees).map(([todoId, entry]) => (
203
+ [todoId, { path: entry.worktree_path, handle: entry.handle, packet: packetsWithIsolation[todoId] }]
204
+ ))),
205
+ };
206
+ }
207
+
208
+ /**
209
+ * epoch内の後続wave dispatch(conflict pairの片方が受理され次第、残り分を
210
+ * dispatchする)。redispatchStage1Next(epoch2専用)とは別に、hold/recompileを
211
+ * 経由せずconflict pairが自然にserializeするrunで必要になる同一plan/packets上の
212
+ * 追加dispatch呼び出し。dispatchReadyFrontier自体はrc3と同一primitive。
213
+ */
214
+ export async function dispatchStage1NextWave({ stateDir }) {
215
+ const state = await loadState(stateDir);
216
+ const adapter = stateAdapter(state);
217
+ const dispatched = await dispatchReadyFrontier({
218
+ runId: RUN_ID, plan: state.plan, events: state.events,
219
+ packets: state.packets, manifests: state.manifests, adapter, recordedAt: RUN_TIMESTAMP,
220
+ });
221
+ if (dispatched.failure) fail(`dispatch失敗: ${dispatched.failure.message}`);
222
+ state.events = dispatched.events;
223
+ await saveState(stateDir, state);
224
+ const packetsWithIsolation = withIsolationContract(state.packets);
225
+ return {
226
+ dispatched: dispatched.dispatched,
227
+ worktrees: Object.fromEntries(dispatched.dispatched.map((todoId) => (
228
+ [todoId, {
229
+ path: state.worktrees[todoId].worktree_path,
230
+ handle: state.worktrees[todoId].handle,
231
+ packet: packetsWithIsolation[todoId],
232
+ }]
233
+ ))),
234
+ };
235
+ }
236
+
237
+ /** provider観測(agent handle・時刻・状態遷移)をledgerへ追記する。core eventsへは入れない。 */
238
+ export async function recordProviderObservation({ stateDir, observation }) {
239
+ const state = await loadState(stateDir);
240
+ state.provider_runs.push(observation);
241
+ await saveState(stateDir, state);
242
+ return { count: state.provider_runs.length };
243
+ }
244
+
245
+ /** 指定TODOのworktree実diffをcheckpoint観測し、findingがあればconflict+freezeまで進める。 */
246
+ export async function observeStage1Checkpoint({ stateDir, todoId, planKey = 'plan' }) {
247
+ const state = await loadState(stateDir);
248
+ const worktree = state.worktrees[todoId];
249
+ if (worktree === undefined || !worktree.active) fail(`active worktreeがない: ${todoId}`);
250
+ const plan = state[planKey];
251
+ const checkpoint = await captureWorktreeDiff({
252
+ worktreePath: worktree.worktree_path,
253
+ baseSha: state.baseSha,
254
+ });
255
+ let events = [...state.events];
256
+ events.push(buildNextRunEvent({
257
+ events,
258
+ runId: RUN_ID,
259
+ kind: 'checkpoint_observed',
260
+ planEpoch: plan.plan_epoch,
261
+ subject: { kind: 'todo', ref: todoId },
262
+ payload: structuredClone(checkpoint),
263
+ recordedAt: RUN_TIMESTAMP,
264
+ }));
265
+ const classifyPackets = { ...state.packets, ...(state.redispatchPackets ?? {}) };
266
+ const classified = classifyCheckpointObservation({
267
+ runId: RUN_ID, plan, events, packets: classifyPackets, manifests: state.manifests, todoId,
268
+ detect: detectCheckpointFindings, recordedAt: RUN_TIMESTAMP,
269
+ });
270
+ state.events = classified.events;
271
+ await saveState(stateDir, state);
272
+ return {
273
+ findings: classified.findings,
274
+ scope_expanded: classified.scope_expanded,
275
+ checkpoint_digest: checkpoint.checkpoint_digest,
276
+ };
277
+ }
278
+
279
+ /** hold裁定→recompile→(carried TODOの)rebind packet発行までを一括で行う受け皿。 */
280
+ export async function holdAndRecompileStage1({ stateDir, additionalConflicts }) {
281
+ const state = await loadState(stateDir);
282
+ const held = decideHoldAndCarryOver({
283
+ runId: RUN_ID,
284
+ request: state.request,
285
+ plan: state.plan,
286
+ manifests: state.manifests,
287
+ packets: state.packets,
288
+ events: state.events,
289
+ recordedAt: RUN_TIMESTAMP,
290
+ });
291
+ const lane = routeConflictTreatment({
292
+ finding: held.holdDecision.finding,
293
+ predeclaredTreatments: [],
294
+ });
295
+ const recompiled = recompileNextEpochPlan({
296
+ runId: RUN_ID,
297
+ request: state.request,
298
+ plan: state.plan,
299
+ manifests: state.manifests,
300
+ packets: state.packets,
301
+ events: held.events,
302
+ holdDecision: held.holdDecision,
303
+ additionalConflicts,
304
+ recordedAt: RUN_TIMESTAMP,
305
+ });
306
+ state.events = recompiled.events;
307
+ state.holdDecision = held.holdDecision;
308
+ state.newPlan = recompiled.newPlan;
309
+ state.planDiff = recompiled.planDiff;
310
+ state.rebindPackets = recompiled.rebindPackets;
311
+ state.redispatchPackets = recompiled.redispatchPackets;
312
+ for (const todoId of held.holdDecision.continue_set) {
313
+ state.packets[todoId] = {
314
+ ...state.packets[todoId],
315
+ plan_epoch: recompiled.newPlan.plan_epoch,
316
+ };
317
+ }
318
+ for (const todoId of held.holdDecision.hold_set) {
319
+ if (state.worktrees[todoId] !== undefined) state.worktrees[todoId].active = false;
320
+ }
321
+ await saveState(stateDir, state);
322
+ return {
323
+ hold: held.holdDecision.hold_set,
324
+ continue: held.holdDecision.continue_set,
325
+ lane: lane.lane,
326
+ new_epoch: recompiled.newPlan.plan_epoch,
327
+ };
328
+ }
329
+
330
+ /** terminal receipt(現attemptの最終checkpointへbind)を記録し、受理裁定まで行う。 */
331
+ export async function terminalStage1Receipt({ stateDir, todoId, planKey }) {
332
+ const state = await loadState(stateDir);
333
+ const plan = state[planKey];
334
+ const worktree = state.worktrees[todoId];
335
+ if (worktree === undefined || !worktree.active) fail(`active worktreeがない: ${todoId}`);
336
+ const packet = planKey === 'newPlan' && state.redispatchPackets?.[todoId] !== undefined
337
+ ? state.redispatchPackets[todoId]
338
+ : state.packets[todoId];
339
+ const stateProjection = projectRuntimeState({ events: state.events });
340
+ const dispatchRecord = stateProjection.dispatches[todoId];
341
+ const attemptCheckpoints = stateProjection.checkpoints.filter((entry) => (
342
+ entry.todo_id === todoId && entry.sequence > dispatchRecord.sequence
343
+ ));
344
+ if (attemptCheckpoints.length === 0) fail(`checkpoint未観測でterminalにできない: ${todoId}`);
345
+ const lastCheckpoint = attemptCheckpoints[attemptCheckpoints.length - 1].payload;
346
+ const receipt = {
347
+ schema: 'lattice.executor_receipt.v1',
348
+ receipt_id: `${todoId}-a${worktree.attempt}-r1`,
349
+ executor_handle: worktree.handle,
350
+ worktree_id: worktree.worktree_id,
351
+ base_sha: packet.base_sha,
352
+ plan_epoch: packet.plan_epoch,
353
+ packet_digest: dispatchRecord.payload.packet_digest,
354
+ todo_id: todoId,
355
+ checkpoint_digest: lastCheckpoint.checkpoint_digest,
356
+ observed_diff: lastCheckpoint.diff.entries.map(({ path: p, change }) => ({ path: p, change })),
357
+ };
358
+ receipt.receipt_digest = selfDigest(receipt, 'receipt_digest');
359
+ let events = [...state.events];
360
+ events.push(buildNextRunEvent({
361
+ events,
362
+ runId: RUN_ID,
363
+ kind: 'receipt_recorded',
364
+ planEpoch: receipt.plan_epoch,
365
+ subject: { kind: 'todo', ref: todoId },
366
+ payload: receipt,
367
+ recordedAt: RUN_TIMESTAMP,
368
+ }));
369
+ // Stage 2着地素材: worktree破棄前にpatch本文を捕獲する。receipt schemaは不変のまま
370
+ // (replay契約を壊さない)、patchはstate/artifactの別文書として保存し、
371
+ // receipt_idとcheckpoint_digestでreceiptへbindする。捕獲失敗はfail loud
372
+ // (Stage 1受理はできたのに着地素材が無い、という無言の欠損を作らない)。
373
+ await run('git', ['add', '-A'], worktree.worktree_path);
374
+ const patchBytes = await run(
375
+ 'git',
376
+ ['-c', 'core.quotepath=false', 'diff', '--cached', '--binary'],
377
+ worktree.worktree_path,
378
+ );
379
+ if (patchBytes.length === 0) fail(`patch捕獲が空: ${todoId}(observed_diffと矛盾)`);
380
+ if (state.patches === undefined) state.patches = {};
381
+ state.patches[receipt.receipt_id] = {
382
+ receipt_id: receipt.receipt_id,
383
+ todo_id: todoId,
384
+ checkpoint_digest: lastCheckpoint.checkpoint_digest,
385
+ paths: receipt.observed_diff.map(({ path: p }) => p),
386
+ patch: patchBytes,
387
+ // ADR 0051 Decision 4: path一致だけではpatch本文の取り違え・破損を検出できない。
388
+ // 捕獲bytesのdigestを併記し、verifierが保存bytesから再計算して束縛を検査する。
389
+ patch_sha256: createHash('sha256').update(patchBytes).digest('hex'),
390
+ };
391
+ let cleanup = { cleanup_ok: true, residual_paths: [] };
392
+ try {
393
+ await run('git', ['worktree', 'remove', '--force', worktree.worktree_path], state.cloneRoot);
394
+ } catch (error) {
395
+ cleanup = {
396
+ cleanup_ok: false,
397
+ residual_paths: [worktree.worktree_root],
398
+ message: String(error?.message ?? error),
399
+ };
400
+ }
401
+ events.push(buildNextRunEvent({
402
+ events,
403
+ runId: RUN_ID,
404
+ kind: 'executor_terminal',
405
+ planEpoch: plan.plan_epoch,
406
+ subject: { kind: 'todo', ref: todoId },
407
+ payload: { executor_handle: worktree.handle, terminal_state: 'reported', cleanup },
408
+ recordedAt: RUN_TIMESTAMP,
409
+ }));
410
+ const adjudicated = adjudicatePendingReceipts({
411
+ runId: RUN_ID, plan, events, recordedAt: RUN_TIMESTAMP,
412
+ });
413
+ state.events = adjudicated.events;
414
+ state.worktrees[todoId].active = false;
415
+ await saveState(stateDir, state);
416
+ return { decisions: adjudicated.decisions, receipt_id: receipt.receipt_id };
417
+ }
418
+
419
+ /** epoch 2のredispatch(1件ずつ。frontier/conflict規則はengineに従う)。hold未発火なら未使用。 */
420
+ export async function redispatchStage1Next({ stateDir }) {
421
+ const state = await loadState(stateDir);
422
+ const adapter = stateAdapter(state);
423
+ const dispatched = await dispatchReadyFrontier({
424
+ runId: RUN_ID,
425
+ plan: state.newPlan,
426
+ events: state.events,
427
+ packets: state.redispatchPackets,
428
+ manifests: state.manifests,
429
+ adapter,
430
+ recordedAt: RUN_TIMESTAMP,
431
+ });
432
+ if (dispatched.failure) fail(`redispatch失敗: ${dispatched.failure.message}`);
433
+ state.events = dispatched.events;
434
+ await saveState(stateDir, state);
435
+ const redispatchPacketsWithIsolation = withIsolationContract(state.redispatchPackets);
436
+ return {
437
+ dispatched: dispatched.dispatched,
438
+ worktrees: Object.fromEntries(dispatched.dispatched.map((todoId) => (
439
+ [todoId, {
440
+ path: state.worktrees[todoId].worktree_path,
441
+ handle: state.worktrees[todoId].handle,
442
+ packet: redispatchPacketsWithIsolation[todoId],
443
+ }]
444
+ ))),
445
+ };
446
+ }
447
+
448
+ /** run close+残worktree掃除(残存は記録)。 */
449
+ export async function closeStage1Run({ stateDir }) {
450
+ const state = await loadState(stateDir);
451
+ const closed = closeRunIfComplete({
452
+ runId: RUN_ID, plan: state.newPlan ?? state.plan, events: state.events, recordedAt: RUN_TIMESTAMP,
453
+ });
454
+ state.events = closed.events;
455
+ const residual = [];
456
+ for (const [todoId, worktree] of Object.entries(state.worktrees)) {
457
+ if (!worktree.active) continue;
458
+ try {
459
+ await run('git', ['worktree', 'remove', '--force', worktree.worktree_path], state.cloneRoot);
460
+ worktree.active = false;
461
+ } catch (error) {
462
+ residual.push({ todo_id: todoId, path: worktree.worktree_root, message: String(error?.message ?? error) });
463
+ }
464
+ }
465
+ state.diagnostics.residual_worktrees = residual;
466
+ await saveState(stateDir, state);
467
+ return { closed: closed.closed, residual };
468
+ }
469
+
470
+ /** artifact v3(RC4 Stage 1 dotagents dogfood)をatomic no-overwriteで発行する。 */
471
+ export async function publishStage1Artifact({ stateDir, artifactRoot }) {
472
+ const state = await loadState(stateDir);
473
+ await mkdir(path.dirname(artifactRoot), { recursive: true });
474
+ const staging = `${artifactRoot}.staging`;
475
+ try {
476
+ await mkdir(staging);
477
+ } catch (error) {
478
+ fail(`stagingを排他作成できない: ${String(error?.message ?? error)}`);
479
+ }
480
+ const packetsDocument = {
481
+ epoch1: withIsolationContract(state.packets),
482
+ redispatch: state.redispatchPackets === null ? null : withIsolationContract(state.redispatchPackets),
483
+ };
484
+ const documents = {
485
+ 'request.json': state.request,
486
+ 'plan.json': state.plan,
487
+ 'new-plan.json': state.newPlan,
488
+ 'manifests.json': state.manifests,
489
+ 'packets.json': packetsDocument,
490
+ 'hold-decision.json': state.holdDecision,
491
+ 'plan-diff.json': state.planDiff,
492
+ 'events.json': state.events,
493
+ 'provider-runs.json': state.provider_runs,
494
+ 'diagnostics.json': state.diagnostics,
495
+ 'patches.json': state.patches ?? {},
496
+ };
497
+ const manifestEntries = {};
498
+ for (const [name, document] of Object.entries(documents)) {
499
+ await writeFile(path.join(staging, name), `${JSON.stringify(document, null, 1)}\n`);
500
+ manifestEntries[name] = digestArtifact(document);
501
+ }
502
+ const manifest = {
503
+ schema: 'lattice.rc4.stage1_dogfood_manifest.v1',
504
+ run_id: RUN_ID,
505
+ clone: {
506
+ lattice_root: state.latticeRoot,
507
+ clone_base_sha: state.baseSha,
508
+ },
509
+ document_digests: manifestEntries,
510
+ };
511
+ await writeFile(path.join(staging, 'dogfood-manifest.json'), `${JSON.stringify(manifest, null, 1)}\n`);
512
+ try {
513
+ let exists = true;
514
+ try {
515
+ await readFile(path.join(artifactRoot, 'dogfood-manifest.json'));
516
+ } catch (error) {
517
+ exists = error?.code !== 'ENOENT';
518
+ }
519
+ if (exists) throw new TypeError('既存artifact rootが存在する');
520
+ await rename(staging, artifactRoot);
521
+ } catch (error) {
522
+ const { rm } = await import('node:fs/promises');
523
+ await rm(staging, { recursive: true, force: true });
524
+ fail(`artifact発行に失敗(上書き禁止): ${String(error?.message ?? error)}`);
525
+ }
526
+ return { manifest };
527
+ }
528
+
529
+ function isolationContractComplete(contract) {
530
+ if (contract === null || typeof contract !== 'object') return false;
531
+ return contract.isolated_home === true
532
+ && Array.isArray(contract.forbidden_commands)
533
+ && ['install.sh', 'spotter install', 'apply-codex-config', 'claude mcp add', 'codex mcp add']
534
+ .every((command) => contract.forbidden_commands.includes(command))
535
+ && contract.write_scope === 'assigned worktree only'
536
+ && contract.no_git_mutations === true
537
+ && typeof contract.note === 'string' && contract.note.length > 0;
538
+ }
539
+
540
+ /** artifact v3を保存bytesだけから再検証する。 */
541
+ export async function verifyStage1ArtifactOnDisk({ artifactRoot }) {
542
+ const manifest = JSON.parse(await readFile(path.join(artifactRoot, 'dogfood-manifest.json'), 'utf8'));
543
+ const checks = [];
544
+ const documents = {};
545
+ for (const [name, digest] of Object.entries(manifest.document_digests)) {
546
+ const document = JSON.parse(await readFile(path.join(artifactRoot, name), 'utf8'));
547
+ documents[name] = document;
548
+ checks.push({ id: `digest:${name}`, passed: digestArtifact(document) === digest });
549
+ }
550
+ const events = documents['events.json'];
551
+ const plan = documents['plan.json'];
552
+ const newPlan = documents['new-plan.json'];
553
+ const chain = verifyRunEventChain({ events });
554
+ checks.push({ id: 'event_chain', passed: chain.valid });
555
+ for (const [label, targetPlan] of [['e1', plan], ['e2', newPlan]]) {
556
+ if (targetPlan === null) continue;
557
+ events.forEach((event, index) => {
558
+ if (event.kind !== 'dispatch_decided' || event.plan_epoch !== targetPlan.plan_epoch) return;
559
+ const recomputed = computeReadyFrontier({ plan: targetPlan, events: events.slice(0, index) });
560
+ checks.push({
561
+ id: `dispatch_replay:${label}:seq${event.sequence}`,
562
+ passed: JSON.stringify(event.payload.dispatchable) === JSON.stringify(recomputed.dispatchable),
563
+ });
564
+ });
565
+ }
566
+ const holdDecision = documents['hold-decision.json'];
567
+ const holdIndex = events.findIndex((event) => event.kind === 'hold_decided');
568
+ if (holdDecision !== null && holdIndex !== -1) {
569
+ const recomputedHold = recomputeHoldDecision({
570
+ plan, events: events.slice(0, holdIndex), manifests: documents['manifests.json'],
571
+ });
572
+ checks.push({
573
+ id: 'hold_replay',
574
+ passed: JSON.stringify(recomputedHold.hold_set) === JSON.stringify(holdDecision.hold_set)
575
+ && JSON.stringify(recomputedHold.continue_set) === JSON.stringify(holdDecision.continue_set),
576
+ });
577
+ }
578
+ // receipt裁定の再計算: 記録済みoutcome event(accepted/rejected+detail)と
579
+ // replay結果の双方向・reason粒度の一致を要求する(RC3-J P1採用の踏襲)。
580
+ const recordedOutcomes = new Map();
581
+ for (const event of events) {
582
+ if (event.kind !== 'receipt_accepted' && event.kind !== 'receipt_rejected') continue;
583
+ const receiptId = event.payload?.receipt_id;
584
+ if (typeof receiptId !== 'string') continue;
585
+ recordedOutcomes.set(receiptId, {
586
+ decision: event.kind === 'receipt_accepted' ? 'accepted' : 'rejected',
587
+ detail: event.payload?.detail ?? null,
588
+ adjudication_epoch: event.plan_epoch,
589
+ });
590
+ }
591
+ const planByEpoch = new Map([plan, newPlan]
592
+ .filter((entry) => entry !== null)
593
+ .map((entry) => [entry.plan_epoch, entry]));
594
+ let receiptReplayOk = recordedOutcomes.size > 0;
595
+ for (const [receiptId, recorded] of recordedOutcomes) {
596
+ const adjudicationPlan = planByEpoch.get(recorded.adjudication_epoch);
597
+ if (adjudicationPlan === undefined) {
598
+ receiptReplayOk = false;
599
+ continue;
600
+ }
601
+ const outcomeIndex = events.findIndex((event) => (
602
+ (event.kind === 'receipt_accepted' || event.kind === 'receipt_rejected')
603
+ && event.payload?.receipt_id === receiptId
604
+ ));
605
+ const replayed = recomputeReceiptDecisions({
606
+ plan: adjudicationPlan,
607
+ events: events.slice(0, outcomeIndex),
608
+ }).decisions.find(({ receipt_id: id }) => id === receiptId);
609
+ if (replayed === undefined
610
+ || replayed.decision !== recorded.decision
611
+ || (recorded.decision === 'rejected' && replayed.detail !== recorded.detail)) {
612
+ receiptReplayOk = false;
613
+ }
614
+ }
615
+ if (newPlan !== null) {
616
+ for (const decision of recomputeReceiptDecisions({ plan: newPlan, events }).decisions) {
617
+ if (decision.decision === 'accepted' && !recordedOutcomes.has(decision.receipt_id)) {
618
+ receiptReplayOk = false;
619
+ }
620
+ }
621
+ }
622
+ checks.push({ id: 'receipt_replay_bidirectional', passed: receiptReplayOk });
623
+ checks.push({
624
+ id: 'provider_separation',
625
+ passed: events.every((event) => (
626
+ JSON.stringify(event.payload).includes('provider_handle') === false
627
+ )),
628
+ });
629
+ // Stage 2着地素材: patches.jsonがある場合(patch捕獲実装後のartifact)、
630
+ // accepted receiptごとにpatch entryが存在し、receipt observed_diffのpathと
631
+ // 一致することを要求する。旧artifact(v3/v3-hold・patches.json不在)は
632
+ // manifest記載文書のみ検査する既存規則のまま。
633
+ if (Object.hasOwn(manifest.document_digests, 'patches.json')) {
634
+ const patches = documents['patches.json'];
635
+ const receiptByld = new Map();
636
+ for (const event of events) {
637
+ if (event.kind !== 'receipt_accepted') continue;
638
+ receiptByld.set(event.payload.receipt_id, event);
639
+ }
640
+ const receiptEvents = events.filter((event) => event.kind === 'receipt_recorded');
641
+ // ADR 0051 Decision 4の強化: path照合に加え、(a) checkpoint_digest/todo_idを
642
+ // receipt_recorded payloadと照合し、(b) patch bytesのsha256を再計算して保存digestと
643
+ // 突合する。(b)は世代判定=1 entryでもpatch_sha256を持つartifactは全entryへ必須
644
+ // (旧v4-landing世代=全entry不在は(a)までで検査し、per-entryのfail-openを作らない)。
645
+ const patchEntries = Object.values(patches);
646
+ const shaGeneration = patchEntries.some((entry) => entry.patch_sha256 !== undefined);
647
+ const patchesOk = patchEntries.length > 0 && [...receiptByld.keys()].every((receiptId) => {
648
+ const patch = patches[receiptId];
649
+ if (patch === undefined || typeof patch.patch !== 'string' || patch.patch.length === 0) return false;
650
+ const recorded = receiptEvents.find((event) => event.payload.receipt_id === receiptId);
651
+ if (recorded === undefined) return false;
652
+ if (patch.checkpoint_digest !== recorded.payload.checkpoint_digest) return false;
653
+ if (patch.todo_id !== recorded.payload.todo_id) return false;
654
+ const receiptPaths = [...recorded.payload.observed_diff.map(({ path: p }) => p)].sort();
655
+ if (JSON.stringify([...patch.paths].sort()) !== JSON.stringify(receiptPaths)) return false;
656
+ if (shaGeneration) {
657
+ if (typeof patch.patch_sha256 !== 'string') return false;
658
+ return createHash('sha256').update(patch.patch).digest('hex') === patch.patch_sha256;
659
+ }
660
+ return true;
661
+ });
662
+ checks.push({ id: 'patches_bound_to_accepted_receipts', passed: patchesOk });
663
+ }
664
+ // ADR 0046 Decision 2: 全executor packetがisolation_contractを完備していること。
665
+ const packetsDocument = documents['packets.json'];
666
+ const allPacketGroups = [packetsDocument.epoch1, packetsDocument.redispatch].filter((group) => group !== null);
667
+ const allPacketsIsolated = allPacketGroups.every((group) => (
668
+ Object.values(group).every((packet) => isolationContractComplete(packet.isolation_contract))
669
+ ));
670
+ checks.push({ id: 'isolation_contract_complete', passed: allPacketsIsolated });
671
+ const failed = checks.filter(({ passed }) => !passed).map(({ id }) => id);
672
+ return { valid: failed.length === 0, checks, failed_conditions: failed };
673
+ }