@quolu/lattice 0.52.0 → 0.52.2

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 (182) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-mcp.mjs +0 -0
  5. package/bin/lattice-scripted-adapter.mjs +0 -0
  6. package/bin/lattice-scripted-worker.mjs +0 -0
  7. package/bin/lattice-work-order-adapter.mjs +0 -0
  8. package/bin/lattice.mjs +0 -0
  9. package/docs/bridge-setup.md +132 -132
  10. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  11. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  12. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  13. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  14. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  15. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  16. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  17. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  18. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  19. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  20. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  21. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  22. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  23. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  24. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  25. package/package.json +103 -103
  26. package/sensor/LICENSE +21 -21
  27. package/sensor/NOTICE +19 -19
  28. package/sensor/dist/bin/lattice-sensor.js +9 -9
  29. package/sensor/dist/db/index.js +24 -24
  30. package/sensor/dist/db/migrations.js +41 -41
  31. package/sensor/dist/db/queries.js +164 -164
  32. package/sensor/dist/db/schema.sql +205 -205
  33. package/sensor/dist/directory.js +5 -5
  34. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  35. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  36. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  49. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  50. package/sensor/dist/mcp/server-instructions.js +95 -95
  51. package/sensor/package.json +56 -56
  52. package/src/artifact-contracts-v2.mjs +325 -325
  53. package/src/artifact-contracts.mjs +895 -895
  54. package/src/boundary-compiler.mjs +712 -712
  55. package/src/boundary-observation-compiler-v2.mjs +344 -344
  56. package/src/bounded-seam.mjs +230 -230
  57. package/src/bridge-address.mjs +107 -107
  58. package/src/bridge-cli.mjs +297 -297
  59. package/src/bridge-config.mjs +346 -346
  60. package/src/bridge-daemon.mjs +378 -378
  61. package/src/bridge-launch-agent.mjs +323 -323
  62. package/src/bridge-registrar.mjs +102 -102
  63. package/src/bridge-server.mjs +376 -376
  64. package/src/cli-help.mjs +308 -308
  65. package/src/cli-stdio.mjs +40 -40
  66. package/src/control-compiler.mjs +532 -532
  67. package/src/dag-chain.mjs +261 -261
  68. package/src/factory-diagnostics.mjs +188 -188
  69. package/src/hash-chain.mjs +76 -76
  70. package/src/hooks-cli.mjs +1057 -1053
  71. package/src/isolation-runner.mjs +409 -409
  72. package/src/node-version-guard.mjs +44 -44
  73. package/src/project-cli.mjs +697 -697
  74. package/src/project-identity.mjs +130 -130
  75. package/src/rc1-black-box-oracle.mjs +906 -906
  76. package/src/rc1-comparison.mjs +154 -154
  77. package/src/rc1-evidence-bundle.mjs +456 -456
  78. package/src/rc1-v4-campaign.mjs +708 -708
  79. package/src/rc1-v4-transform.mjs +467 -467
  80. package/src/rc1-v5-artifact-set.mjs +855 -855
  81. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  82. package/src/rc1-v5-campaign.mjs +797 -797
  83. package/src/rc1-v5-transform.mjs +421 -421
  84. package/src/rc1-v6-artifact-set.mjs +807 -807
  85. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  86. package/src/rc1-v6-campaign.mjs +623 -623
  87. package/src/rc1-v6-causal-binding.mjs +473 -473
  88. package/src/rc1-v6-measurement.mjs +313 -313
  89. package/src/rc2-artifact-set.mjs +1584 -1584
  90. package/src/rc2-campaign.mjs +1506 -1502
  91. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  92. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  93. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  94. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  95. package/src/rc3-actual-dogfood.mjs +652 -652
  96. package/src/rc3-dogfood-scaffold.mjs +315 -315
  97. package/src/rc3-scripted-campaign.mjs +1383 -1383
  98. package/src/rc4-stage1-dogfood.mjs +673 -673
  99. package/src/runtime-adapter-registry.mjs +524 -520
  100. package/src/runtime-cli.mjs +4588 -4584
  101. package/src/runtime-contracts.mjs +824 -824
  102. package/src/runtime-control-store.mjs +604 -600
  103. package/src/runtime-controller-protocol.mjs +587 -587
  104. package/src/runtime-decision-verifier.mjs +701 -701
  105. package/src/runtime-diff-observer.mjs +361 -361
  106. package/src/runtime-direct-os-observer.mjs +301 -301
  107. package/src/runtime-driver-state.mjs +166 -162
  108. package/src/runtime-engine.mjs +779 -779
  109. package/src/runtime-errors.mjs +356 -356
  110. package/src/runtime-event-store.mjs +189 -189
  111. package/src/runtime-front-end.mjs +925 -925
  112. package/src/runtime-gate-store.mjs +481 -477
  113. package/src/runtime-hold-recompile.mjs +916 -916
  114. package/src/runtime-io-sentinel.mjs +391 -391
  115. package/src/runtime-lifecycle-lock.mjs +294 -290
  116. package/src/runtime-managed-supervisor.mjs +1490 -1490
  117. package/src/runtime-multi-epoch-store.mjs +838 -834
  118. package/src/runtime-projection.mjs +269 -269
  119. package/src/runtime-pull-intake.mjs +1192 -1188
  120. package/src/runtime-scripted-adapter-controller.mjs +1160 -1156
  121. package/src/runtime-scripted-executor.mjs +163 -163
  122. package/src/runtime-scripted-worktree.mjs +104 -104
  123. package/src/runtime-seam-resolve.mjs +428 -428
  124. package/src/runtime-seam-treatment.mjs +173 -173
  125. package/src/runtime-socket-owner.mjs +125 -125
  126. package/src/runtime-work-order-contracts.mjs +91 -91
  127. package/src/runtime-work-order-controller.mjs +1171 -1167
  128. package/src/runtime-worktree-executor.mjs +199 -199
  129. package/src/schedulability-compiler-v2.mjs +303 -303
  130. package/src/schedulability-verifier-v2.mjs +317 -317
  131. package/src/seam-apply.mjs +549 -549
  132. package/src/seam-commit-shared.mjs +22 -22
  133. package/src/seam-commit-transform.mjs +81 -81
  134. package/src/seam-commit.mjs +18 -18
  135. package/src/seam-cost.mjs +322 -322
  136. package/src/seam-derivation.mjs +188 -188
  137. package/src/seam-gate.mjs +146 -146
  138. package/src/seam-proposal-contracts.mjs +446 -446
  139. package/src/seam-proposal-queries.mjs +521 -521
  140. package/src/seam-proposal.mjs +2011 -2011
  141. package/src/seam-ref.mjs +33 -33
  142. package/src/seam-rewrite.mjs +286 -286
  143. package/src/seam-transform.mjs +554 -554
  144. package/src/seam-verification.mjs +260 -260
  145. package/src/sensor-adapter.mjs +432 -432
  146. package/src/sensor-cli.mjs +139 -139
  147. package/src/sensor-diff.mjs +661 -661
  148. package/src/sensor-node-runtime.mjs +53 -53
  149. package/src/sensor-runtime.mjs +52 -52
  150. package/src/timestamp-contract.mjs +8 -8
  151. package/src/todo-audit-pending.mjs +91 -91
  152. package/src/todo-chain.mjs +178 -178
  153. package/src/todo-cli.mjs +3141 -3126
  154. package/src/todo-contracts.mjs +728 -728
  155. package/src/todo-dashboard-registry.mjs +573 -573
  156. package/src/todo-dispatch-shape.mjs +190 -190
  157. package/src/todo-gantt-html-independence.mjs +239 -239
  158. package/src/todo-gantt-html-shared.mjs +226 -226
  159. package/src/todo-gantt-html-style.mjs +131 -131
  160. package/src/todo-gantt-html.mjs +248 -248
  161. package/src/todo-gantt-layout.mjs +974 -974
  162. package/src/todo-gantt-live.mjs +361 -361
  163. package/src/todo-gantt-nested.mjs +263 -263
  164. package/src/todo-gantt-presentation.mjs +217 -217
  165. package/src/todo-gantt-scope.mjs +123 -123
  166. package/src/todo-gantt-svg.mjs +353 -353
  167. package/src/todo-independence-contracts.mjs +595 -595
  168. package/src/todo-independence-guidance.mjs +322 -322
  169. package/src/todo-independence.mjs +640 -640
  170. package/src/todo-markdown-renderer.mjs +260 -260
  171. package/src/todo-migration.mjs +448 -448
  172. package/src/todo-narrative-anchor.mjs +130 -130
  173. package/src/todo-note-store.mjs +629 -625
  174. package/src/todo-parallel-candidates.mjs +114 -114
  175. package/src/todo-revision.mjs +995 -995
  176. package/src/todo-split.mjs +472 -472
  177. package/src/todo-status.mjs +690 -690
  178. package/src/todo-store-git-transaction.mjs +418 -418
  179. package/src/todo-store.mjs +4322 -4314
  180. package/src/treatment-compiler.mjs +728 -728
  181. package/src/treatment-runner.mjs +656 -656
  182. package/src/witness-scaffold.mjs +180 -180
@@ -1,652 +1,652 @@
1
- import { spawn } from 'node:child_process';
2
- import { mkdir, mkdtemp, readFile, rename, writeFile } from 'node:fs/promises';
3
- import { tmpdir } from 'node:os';
4
- import path from 'node:path';
5
-
6
- import { digestArtifact } from './artifact-contracts.mjs';
7
- import { collectSensorEvidence } from './sensor-adapter.mjs';
8
- import { scaffoldRc3DogfoodRepo, verifyRc3DogfoodScaffold } from './rc3-dogfood-scaffold.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 } from './runtime-contracts.mjs';
33
-
34
- /**
35
- * RC3-I actual multi-agent dogfood driver(plan RC3-I、ADR 0044 Decision 9.5)。
36
- *
37
- * 親orchestrator(Claude session)が実external executor(Claude implementer
38
- * subagent等)を隔離worktreeへdispatchするための、状態fileベースのstep driver。
39
- * 各stepは別processで実行できる純関数で、runtime stateはstate JSONのevent列
40
- * だけから再構成する(in-memory adapter stateを持たない)。
41
- *
42
- * - core event chainはscripted campaignと同一契約。provider固有の観測
43
- * (agent handle、実wall-clock、途中状態、回収、retry)は`provider_runs`として
44
- * 分離保存し、core成功へ丸めない(plan「provider runtime observationとして分離」)。
45
- * - 実executorはworktreeのfile変更だけを行う協調前提。commit・branch等の
46
- * 禁止操作はdiff observerのHEAD drift検査でfail loudする。
47
- * - 重複dispatch拒否・同一handle回収はstate上のactive attempt記録で強制する。
48
- */
49
-
50
- const RUN_TIMESTAMP = '2026-07-17T00:00:00.000Z';
51
- const RUN_ID = 'rc3i-actual-01';
52
- const ENTRY = 'research/fixtures/delivery-policy-registry/src/delivery-policy-registry.mjs';
53
- const ORACLE = 'src/rc2-delivery-policy-oracle.mjs';
54
- const SHARED_TEST = 'test/rc2-delivery-policy-fixture.test.mjs';
55
-
56
- function fail(reason) {
57
- throw new TypeError(`rc3 actual dogfood契約違反: ${reason}`);
58
- }
59
-
60
- function run(command, args, cwd) {
61
- return new Promise((resolve, reject) => {
62
- const child = spawn(command, args, { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
63
- const stdout = [];
64
- const stderr = [];
65
- child.stdout.on('data', (chunk) => stdout.push(chunk));
66
- child.stderr.on('data', (chunk) => stderr.push(chunk));
67
- child.once('error', reject);
68
- child.once('close', (code, signal) => {
69
- if (code === 0 && signal === null) resolve(Buffer.concat(stdout).toString('utf8'));
70
- else {
71
- reject(new TypeError(
72
- `${command} ${args[0]} failed (${signal ?? code}): ${Buffer.concat(stderr).toString('utf8').trim()}`,
73
- ));
74
- }
75
- });
76
- });
77
- }
78
-
79
- function statePath(stateDir) {
80
- return path.join(stateDir, 'rc3i-state.json');
81
- }
82
-
83
- async function loadState(stateDir) {
84
- return JSON.parse(await readFile(statePath(stateDir), 'utf8'));
85
- }
86
-
87
- async function saveState(stateDir, state) {
88
- await writeFile(statePath(stateDir), `${JSON.stringify(state, null, 1)}\n`);
89
- }
90
-
91
- function witness(todoId, target, affectedTests) {
92
- return {
93
- owns: [{ kind: 'path', target }],
94
- reads: [],
95
- writes: [target],
96
- resources: [],
97
- state_effects: [],
98
- sensor_provenance: {
99
- queries: [{ query_id: `q-aff-${todoId}`, expect: { kind: 'affected', path: target } }],
100
- },
101
- affected_tests: affectedTests,
102
- unknowns: [],
103
- };
104
- }
105
-
106
- async function provisionWorktree(state, todoId, attempt) {
107
- const worktreeRoot = await mkdtemp(path.join(tmpdir(), `lattice-rc3i-${todoId}-`));
108
- const worktreePath = path.join(worktreeRoot, 'tree');
109
- await run('git', ['worktree', 'add', '--detach', worktreePath, state.scaffold.target.base_sha], state.scaffold.repoRoot);
110
- return {
111
- handle: `actual-${todoId}-h${attempt}`,
112
- worktree_id: `wt-${todoId}-a${attempt}`,
113
- worktree_root: worktreeRoot,
114
- worktree_path: worktreePath,
115
- attempt,
116
- active: true,
117
- };
118
- }
119
-
120
- /** state駆動のexecutor adapter(dispatch=worktree provision、重複はstateで拒否)。 */
121
- function stateAdapter(state) {
122
- return {
123
- kind: 'actual-agent',
124
- async dispatch({ packet } = {}) {
125
- const existing = state.worktrees[packet.todo_id];
126
- if (existing !== undefined && existing.active) {
127
- fail(`同一TODOの重複dispatchを拒否する: ${packet.todo_id}`);
128
- }
129
- const attempt = existing === undefined ? 1 : existing.attempt + 1;
130
- const provisioned = await provisionWorktree(state, packet.todo_id, attempt);
131
- state.worktrees[packet.todo_id] = provisioned;
132
- return { executor_handle: provisioned.handle, worktree_id: provisioned.worktree_id };
133
- },
134
- };
135
- }
136
-
137
- /**
138
- * step 1: scaffold・compile・全TODO dispatch(worktree provision)まで。
139
- * 返り値のworktree pathsへ、親が実agentをdispatchする。
140
- */
141
- export async function initActualDogfoodRun({ latticeRoot, stateDir }) {
142
- await mkdir(stateDir, { recursive: true });
143
- const workRoot = await mkdtemp(path.join(tmpdir(), 'lattice-rc3i-scaffold-'));
144
- const scaffold = await scaffoldRc3DogfoodRepo({ latticeRoot, workRoot });
145
- const scaffoldVerified = await verifyRc3DogfoodScaffold({
146
- latticeRoot, repoRoot: scaffold.repoRoot, expected: scaffold,
147
- });
148
- if (scaffoldVerified.outcome !== 'verified') fail('scaffold検証が失敗');
149
-
150
- const probeQuerySet = {
151
- queries: [ENTRY, ORACLE, SHARED_TEST].map((target, index) => (
152
- { id: `probe-${index}`, operation: 'affected', target }
153
- )),
154
- };
155
- const probed = await collectSensorEvidence({ cwd: scaffold.repoRoot, querySet: probeQuerySet });
156
- const affectedByTarget = {};
157
- probed.outcomes.forEach((outcome, index) => {
158
- const entry = Array.isArray(outcome.targets) ? outcome.targets[0] : null;
159
- affectedByTarget[probeQuerySet.queries[index].target] = Array.isArray(entry?.data?.affectedTests)
160
- ? [...entry.data.affectedTests].sort()
161
- : [];
162
- });
163
-
164
- const request = {
165
- schema: 'lattice.run_request.v1',
166
- request_id: 'rc3i-actual',
167
- repo: { base_sha: scaffold.target.base_sha, root_kind: 'git-worktree' },
168
- capacity: { executors: 3 },
169
- todos: [{ todo_id: 'TA' }, { todo_id: 'TB' }, { todo_id: 'TC' }],
170
- manual_witness: {
171
- TA: witness('TA', ENTRY, affectedByTarget[ENTRY]),
172
- TB: witness('TB', ORACLE, affectedByTarget[ORACLE]),
173
- TC: witness('TC', SHARED_TEST, affectedByTarget[SHARED_TEST]),
174
- },
175
- sensor_query_set: {
176
- queries: [
177
- { id: 'q-status', operation: 'status' },
178
- { id: 'q-aff-TA', operation: 'affected', target: ENTRY },
179
- { id: 'q-aff-TB', operation: 'affected', target: ORACLE },
180
- { id: 'q-aff-TC', operation: 'affected', target: SHARED_TEST },
181
- ],
182
- },
183
- executor_capability: { adapters: ['actual-agent'] },
184
- claim_mode: 'exact_minimum',
185
- };
186
- request.request_digest = selfDigest(request, 'request_digest');
187
-
188
- const collected = await collectSensorEvidence({ cwd: scaffold.repoRoot, querySet: request.sensor_query_set });
189
- const compiled = compileRuntimePlanV1({
190
- request,
191
- sensorEvidence: evidenceFromCollectedOutcomes({ querySet: request.sensor_query_set, collected }),
192
- planRef: 'plan-rc3i-actual-e1',
193
- planEpoch: 1,
194
- predecessorRefs: [],
195
- });
196
- if (compiled.outcome !== 'dispatchable') fail(`compileがdispatchableにならない: ${compiled.code}`);
197
- const packets = buildExecutorPackets({ plan: compiled.plan, manifests: compiled.manifests });
198
-
199
- const state = {
200
- schema: 'lattice.rc3.actual_dogfood_state.v1',
201
- scaffold,
202
- request,
203
- plan: compiled.plan,
204
- manifests: compiled.manifests,
205
- packets,
206
- newPlan: null,
207
- rebindPackets: null,
208
- redispatchPackets: null,
209
- holdDecision: null,
210
- planDiff: null,
211
- events: initializeRunEvents({
212
- runId: RUN_ID, request, plan: compiled.plan, manifests: compiled.manifests, recordedAt: RUN_TIMESTAMP,
213
- }),
214
- worktrees: {},
215
- provider_runs: [],
216
- probes: {},
217
- };
218
- const adapter = stateAdapter(state);
219
- const dispatched = await dispatchReadyFrontier({
220
- runId: RUN_ID, plan: state.plan, events: state.events,
221
- packets, manifests: state.manifests, adapter, recordedAt: RUN_TIMESTAMP,
222
- });
223
- if (dispatched.failure) fail(`dispatch失敗: ${dispatched.failure.message}`);
224
- state.events = dispatched.events;
225
- await saveState(stateDir, state);
226
- return {
227
- dispatched: dispatched.dispatched,
228
- worktrees: Object.fromEntries(Object.entries(state.worktrees).map(([todoId, entry]) => (
229
- [todoId, { path: entry.worktree_path, handle: entry.handle, packet: packets[todoId] }]
230
- ))),
231
- };
232
- }
233
-
234
- /** provider観測(agent handle・時刻・状態遷移)をledgerへ追記する。core eventsへは入れない。 */
235
- export async function recordProviderObservation({ stateDir, observation }) {
236
- const state = await loadState(stateDir);
237
- state.provider_runs.push(observation);
238
- await saveState(stateDir, state);
239
- return { count: state.provider_runs.length };
240
- }
241
-
242
- /** 指定TODOのworktree実diffをcheckpoint観測し、findingがあればconflict+freezeまで進める。 */
243
- export async function observeActualCheckpoint({ stateDir, todoId, planKey = 'plan' }) {
244
- const state = await loadState(stateDir);
245
- const worktree = state.worktrees[todoId];
246
- if (worktree === undefined || !worktree.active) fail(`active worktreeがない: ${todoId}`);
247
- const plan = state[planKey];
248
- const checkpoint = await captureWorktreeDiff({
249
- worktreePath: worktree.worktree_path,
250
- baseSha: state.scaffold.target.base_sha,
251
- });
252
- let events = [...state.events];
253
- events.push(buildNextRunEvent({
254
- events,
255
- runId: RUN_ID,
256
- kind: 'checkpoint_observed',
257
- planEpoch: plan.plan_epoch,
258
- subject: { kind: 'todo', ref: todoId },
259
- payload: structuredClone(checkpoint),
260
- recordedAt: RUN_TIMESTAMP,
261
- }));
262
- const packets = plan.plan_epoch === 1 ? state.packets : state.redispatchPackets ?? state.packets;
263
- const classifyPackets = { ...state.packets, ...(state.redispatchPackets ?? {}) };
264
- void packets;
265
- const classified = classifyCheckpointObservation({
266
- runId: RUN_ID, plan, events, packets: classifyPackets, manifests: state.manifests, todoId,
267
- detect: detectCheckpointFindings, recordedAt: RUN_TIMESTAMP,
268
- });
269
- state.events = classified.events;
270
- await saveState(stateDir, state);
271
- return {
272
- findings: classified.findings,
273
- scope_expanded: classified.scope_expanded,
274
- checkpoint_digest: checkpoint.checkpoint_digest,
275
- };
276
- }
277
-
278
- /** hold裁定→recompile→(carried TODOの)rebind packet発行までを一括で行う。 */
279
- export async function holdAndRecompile({ stateDir, additionalConflicts }) {
280
- const state = await loadState(stateDir);
281
- const held = decideHoldAndCarryOver({
282
- runId: RUN_ID,
283
- request: state.request,
284
- plan: state.plan,
285
- manifests: state.manifests,
286
- packets: state.packets,
287
- events: state.events,
288
- recordedAt: RUN_TIMESTAMP,
289
- });
290
- const lane = routeConflictTreatment({
291
- finding: held.holdDecision.finding,
292
- predeclaredTreatments: [],
293
- });
294
- const recompiled = recompileNextEpochPlan({
295
- runId: RUN_ID,
296
- request: state.request,
297
- plan: state.plan,
298
- manifests: state.manifests,
299
- packets: state.packets,
300
- events: held.events,
301
- holdDecision: held.holdDecision,
302
- additionalConflicts,
303
- recordedAt: RUN_TIMESTAMP,
304
- });
305
- state.events = recompiled.events;
306
- state.holdDecision = held.holdDecision;
307
- state.newPlan = recompiled.newPlan;
308
- state.planDiff = recompiled.planDiff;
309
- state.rebindPackets = recompiled.rebindPackets;
310
- state.redispatchPackets = recompiled.redispatchPackets;
311
- // rebind: carried TODOのpacket epochを更新(同一handle・content不変)。
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
- // hold集合のworktreeは失効(active解除。掃除はcleanupWorktreesで記録付き実施)。
319
- for (const todoId of held.holdDecision.hold_set) {
320
- if (state.worktrees[todoId] !== undefined) state.worktrees[todoId].active = false;
321
- }
322
- await saveState(stateDir, state);
323
- return {
324
- hold: held.holdDecision.hold_set,
325
- continue: held.holdDecision.continue_set,
326
- lane: lane.lane,
327
- new_epoch: recompiled.newPlan.plan_epoch,
328
- };
329
- }
330
-
331
- /** terminal receipt(現attemptの最終checkpointへbind)を記録し、受理裁定まで行う。 */
332
- export async function terminalActualReceipt({ stateDir, todoId, planKey }) {
333
- const state = await loadState(stateDir);
334
- const plan = state[planKey];
335
- const worktree = state.worktrees[todoId];
336
- if (worktree === undefined || !worktree.active) fail(`active worktreeがない: ${todoId}`);
337
- const packet = planKey === 'newPlan' && state.redispatchPackets?.[todoId] !== undefined
338
- ? state.redispatchPackets[todoId]
339
- : state.packets[todoId];
340
- const stateProjection = projectRuntimeState({ events: state.events });
341
- const dispatchRecord = stateProjection.dispatches[todoId];
342
- const attemptCheckpoints = stateProjection.checkpoints.filter((entry) => (
343
- entry.todo_id === todoId && entry.sequence > dispatchRecord.sequence
344
- ));
345
- if (attemptCheckpoints.length === 0) fail(`checkpoint未観測でterminalにできない: ${todoId}`);
346
- const lastCheckpoint = attemptCheckpoints[attemptCheckpoints.length - 1].payload;
347
- const receipt = {
348
- schema: 'lattice.executor_receipt.v1',
349
- receipt_id: `${todoId}-a${worktree.attempt}-r1`,
350
- executor_handle: worktree.handle,
351
- worktree_id: worktree.worktree_id,
352
- base_sha: packet.base_sha,
353
- plan_epoch: packet.plan_epoch,
354
- packet_digest: dispatchRecord.payload.packet_digest,
355
- todo_id: todoId,
356
- checkpoint_digest: lastCheckpoint.checkpoint_digest,
357
- observed_diff: lastCheckpoint.diff.entries.map(({ path: p, change }) => ({ path: p, change })),
358
- };
359
- receipt.receipt_digest = selfDigest(receipt, 'receipt_digest');
360
- let events = [...state.events];
361
- events.push(buildNextRunEvent({
362
- events,
363
- runId: RUN_ID,
364
- kind: 'receipt_recorded',
365
- planEpoch: receipt.plan_epoch,
366
- subject: { kind: 'todo', ref: todoId },
367
- payload: receipt,
368
- recordedAt: RUN_TIMESTAMP,
369
- }));
370
- // worktree cleanup(失敗は成功へ丸めずterminal payloadへ記録)。
371
- let cleanup = { cleanup_ok: true, residual_paths: [] };
372
- try {
373
- await run('git', ['worktree', 'remove', '--force', worktree.worktree_path], state.scaffold.repoRoot);
374
- } catch (error) {
375
- cleanup = {
376
- cleanup_ok: false,
377
- residual_paths: [worktree.worktree_root],
378
- message: String(error?.message ?? error),
379
- };
380
- }
381
- events.push(buildNextRunEvent({
382
- events,
383
- runId: RUN_ID,
384
- kind: 'executor_terminal',
385
- planEpoch: plan.plan_epoch,
386
- subject: { kind: 'todo', ref: todoId },
387
- payload: { executor_handle: worktree.handle, terminal_state: 'reported', cleanup },
388
- recordedAt: RUN_TIMESTAMP,
389
- }));
390
- const adjudicated = adjudicatePendingReceipts({
391
- runId: RUN_ID, plan, events, recordedAt: RUN_TIMESTAMP,
392
- });
393
- state.events = adjudicated.events;
394
- state.worktrees[todoId].active = false;
395
- await saveState(stateDir, state);
396
- return { decisions: adjudicated.decisions, receipt_id: receipt.receipt_id };
397
- }
398
-
399
- /** 重複dispatch拒否のprobe(typed拒否をprovider観測として記録)。 */
400
- export async function probeDuplicateDispatch({ stateDir, todoId }) {
401
- const state = await loadState(stateDir);
402
- const adapter = stateAdapter(state);
403
- let refused = null;
404
- try {
405
- await adapter.dispatch({ packet: state.packets[todoId] });
406
- } catch (error) {
407
- refused = String(error?.message ?? error);
408
- }
409
- state.probes.duplicate_dispatch = { todo_id: todoId, refused };
410
- await saveState(stateDir, state);
411
- if (refused === null) fail('重複dispatchが拒否されなかった');
412
- return { refused };
413
- }
414
-
415
- /** 旧epoch stale receiptのprobe(typed rejectを記録)。 */
416
- export async function probeStaleReceipt({ stateDir, todoId }) {
417
- const state = await loadState(stateDir);
418
- const stateProjection = projectRuntimeState({ events: state.events });
419
- const dispatchRecord = stateProjection.dispatches[todoId];
420
- const staleReceipt = {
421
- schema: 'lattice.executor_receipt.v1',
422
- receipt_id: `${todoId}-stale-r1`,
423
- executor_handle: dispatchRecord.payload.executor_handle,
424
- worktree_id: dispatchRecord.payload.worktree_id,
425
- base_sha: state.plan.base_sha,
426
- plan_epoch: state.plan.plan_epoch,
427
- packet_digest: dispatchRecord.payload.packet_digest,
428
- todo_id: todoId,
429
- checkpoint_digest: '2'.repeat(64),
430
- observed_diff: [],
431
- };
432
- staleReceipt.receipt_digest = selfDigest(staleReceipt, 'receipt_digest');
433
- let events = [...state.events];
434
- events.push(buildNextRunEvent({
435
- events,
436
- runId: RUN_ID,
437
- kind: 'receipt_recorded',
438
- planEpoch: staleReceipt.plan_epoch,
439
- subject: { kind: 'todo', ref: todoId },
440
- payload: staleReceipt,
441
- recordedAt: RUN_TIMESTAMP,
442
- }));
443
- const adjudicated = adjudicatePendingReceipts({
444
- runId: RUN_ID, plan: state.newPlan, events, recordedAt: RUN_TIMESTAMP,
445
- });
446
- const decision = adjudicated.decisions.find(({ receipt_id: id }) => id === staleReceipt.receipt_id);
447
- if (decision?.decision !== 'rejected') fail('stale receiptがrejectされなかった');
448
- state.events = adjudicated.events;
449
- state.probes.stale_receipt = { todo_id: todoId, decision };
450
- await saveState(stateDir, state);
451
- return { decision };
452
- }
453
-
454
- /** epoch 2のredispatch(1件ずつ。frontier/conflict規則はengineに従う)。 */
455
- export async function redispatchNext({ stateDir }) {
456
- const state = await loadState(stateDir);
457
- const adapter = stateAdapter(state);
458
- const dispatched = await dispatchReadyFrontier({
459
- runId: RUN_ID,
460
- plan: state.newPlan,
461
- events: state.events,
462
- packets: state.redispatchPackets,
463
- manifests: state.manifests,
464
- adapter,
465
- recordedAt: RUN_TIMESTAMP,
466
- });
467
- if (dispatched.failure) fail(`redispatch失敗: ${dispatched.failure.message}`);
468
- state.events = dispatched.events;
469
- await saveState(stateDir, state);
470
- return {
471
- dispatched: dispatched.dispatched,
472
- worktrees: Object.fromEntries(dispatched.dispatched.map((todoId) => (
473
- [todoId, {
474
- path: state.worktrees[todoId].worktree_path,
475
- handle: state.worktrees[todoId].handle,
476
- packet: state.redispatchPackets[todoId],
477
- }]
478
- ))),
479
- };
480
- }
481
-
482
- /** run close+残worktree掃除(残存は記録)。 */
483
- export async function closeActualRun({ stateDir }) {
484
- const state = await loadState(stateDir);
485
- const closed = closeRunIfComplete({
486
- runId: RUN_ID, plan: state.newPlan ?? state.plan, events: state.events, recordedAt: RUN_TIMESTAMP,
487
- });
488
- state.events = closed.events;
489
- const residual = [];
490
- for (const [todoId, worktree] of Object.entries(state.worktrees)) {
491
- if (!worktree.active) continue;
492
- try {
493
- await run('git', ['worktree', 'remove', '--force', worktree.worktree_path], state.scaffold.repoRoot);
494
- worktree.active = false;
495
- } catch (error) {
496
- residual.push({ todo_id: todoId, path: worktree.worktree_root, message: String(error?.message ?? error) });
497
- }
498
- }
499
- state.probes.residual_worktrees = residual;
500
- await saveState(stateDir, state);
501
- return { closed: closed.closed, residual };
502
- }
503
-
504
- /** artifact v2をatomic no-overwriteで発行する。 */
505
- export async function publishActualArtifact({ stateDir, artifactRoot }) {
506
- const state = await loadState(stateDir);
507
- await mkdir(path.dirname(artifactRoot), { recursive: true });
508
- const staging = `${artifactRoot}.staging`;
509
- try {
510
- await mkdir(staging);
511
- } catch (error) {
512
- fail(`stagingを排他作成できない: ${String(error?.message ?? error)}`);
513
- }
514
- const documents = {
515
- 'request.json': state.request,
516
- 'plan.json': state.plan,
517
- 'new-plan.json': state.newPlan,
518
- 'manifests.json': state.manifests,
519
- 'hold-decision.json': state.holdDecision,
520
- 'plan-diff.json': state.planDiff,
521
- 'events.json': state.events,
522
- 'provider-runs.json': state.provider_runs,
523
- 'probes.json': state.probes,
524
- };
525
- const manifestEntries = {};
526
- for (const [name, document] of Object.entries(documents)) {
527
- await writeFile(path.join(staging, name), `${JSON.stringify(document, null, 1)}\n`);
528
- manifestEntries[name] = digestArtifact(document);
529
- }
530
- const manifest = {
531
- schema: 'lattice.rc3.actual_dogfood_manifest.v1',
532
- run_id: RUN_ID,
533
- scaffold: {
534
- lattice_source_base_sha: state.scaffold.lattice_source.base_sha,
535
- target_base_sha: state.scaffold.target.base_sha,
536
- path_digests: state.scaffold.target.path_digests,
537
- },
538
- document_digests: manifestEntries,
539
- };
540
- await writeFile(path.join(staging, 'dogfood-manifest.json'), `${JSON.stringify(manifest, null, 1)}\n`);
541
- try {
542
- let exists = true;
543
- try {
544
- await readFile(path.join(artifactRoot, 'dogfood-manifest.json'));
545
- } catch (error) {
546
- exists = error?.code !== 'ENOENT';
547
- }
548
- if (exists) throw new TypeError('既存artifact rootが存在する');
549
- await rename(staging, artifactRoot);
550
- } catch (error) {
551
- const { rm } = await import('node:fs/promises');
552
- await rm(staging, { recursive: true, force: true });
553
- fail(`artifact発行に失敗(上書き禁止): ${String(error?.message ?? error)}`);
554
- }
555
- return { manifest };
556
- }
557
-
558
- /** artifact v2を保存bytesだけから再検証する。 */
559
- export async function verifyActualArtifactOnDisk({ artifactRoot }) {
560
- const manifest = JSON.parse(await readFile(path.join(artifactRoot, 'dogfood-manifest.json'), 'utf8'));
561
- const checks = [];
562
- const documents = {};
563
- for (const [name, digest] of Object.entries(manifest.document_digests)) {
564
- const document = JSON.parse(await readFile(path.join(artifactRoot, name), 'utf8'));
565
- documents[name] = document;
566
- checks.push({ id: `digest:${name}`, passed: digestArtifact(document) === digest });
567
- }
568
- const events = documents['events.json'];
569
- const plan = documents['plan.json'];
570
- const newPlan = documents['new-plan.json'];
571
- const chain = verifyRunEventChain({ events });
572
- checks.push({ id: 'event_chain', passed: chain.valid });
573
- for (const [label, targetPlan] of [['e1', plan], ['e2', newPlan]]) {
574
- events.forEach((event, index) => {
575
- if (event.kind !== 'dispatch_decided' || event.plan_epoch !== targetPlan.plan_epoch) return;
576
- const recomputed = computeReadyFrontier({ plan: targetPlan, events: events.slice(0, index) });
577
- checks.push({
578
- id: `dispatch_replay:${label}:seq${event.sequence}`,
579
- passed: JSON.stringify(event.payload.dispatchable) === JSON.stringify(recomputed.dispatchable),
580
- });
581
- });
582
- }
583
- const holdDecision = documents['hold-decision.json'];
584
- const holdIndex = events.findIndex((event) => event.kind === 'hold_decided');
585
- const recomputedHold = recomputeHoldDecision({
586
- plan, events: events.slice(0, holdIndex), manifests: documents['manifests.json'],
587
- });
588
- checks.push({
589
- id: 'hold_replay',
590
- passed: JSON.stringify(recomputedHold.hold_set) === JSON.stringify(holdDecision.hold_set)
591
- && JSON.stringify(recomputedHold.continue_set) === JSON.stringify(holdDecision.continue_set),
592
- });
593
- // receipt裁定の再計算: 記録済みoutcome event(accepted/rejected+detail)と
594
- // replay結果の双方向・reason粒度の一致を要求する(片側包含にしない。RC3-J P1採用)。
595
- // 各receiptの裁定は「outcome eventのepoch=裁定時のactive plan」で再計算する
596
- //(receiptが名乗るepochではない。staleは新planの下でepoch_mismatchになる)。
597
- const recordedOutcomes = new Map();
598
- for (const event of events) {
599
- if (event.kind !== 'receipt_accepted' && event.kind !== 'receipt_rejected') continue;
600
- const receiptId = event.payload?.receipt_id;
601
- if (typeof receiptId !== 'string') continue;
602
- recordedOutcomes.set(receiptId, {
603
- decision: event.kind === 'receipt_accepted' ? 'accepted' : 'rejected',
604
- detail: event.payload?.detail ?? null,
605
- adjudication_epoch: event.plan_epoch,
606
- });
607
- }
608
- const planByEpoch = new Map([plan, newPlan]
609
- .filter((entry) => entry !== null)
610
- .map((entry) => [entry.plan_epoch, entry]));
611
- let receiptReplayOk = recordedOutcomes.size > 0;
612
- const acceptedInReplay = new Set();
613
- for (const [receiptId, recorded] of recordedOutcomes) {
614
- const adjudicationPlan = planByEpoch.get(recorded.adjudication_epoch);
615
- if (adjudicationPlan === undefined) {
616
- receiptReplayOk = false;
617
- continue;
618
- }
619
- // 裁定「前」のprefix(outcome event以前)に対するreplayと比較する。
620
- const outcomeIndex = events.findIndex((event) => (
621
- (event.kind === 'receipt_accepted' || event.kind === 'receipt_rejected')
622
- && event.payload?.receipt_id === receiptId
623
- ));
624
- const replayed = recomputeReceiptDecisions({
625
- plan: adjudicationPlan,
626
- events: events.slice(0, outcomeIndex),
627
- }).decisions.find(({ receipt_id: id }) => id === receiptId);
628
- if (replayed === undefined
629
- || replayed.decision !== recorded.decision
630
- || (recorded.decision === 'rejected' && replayed.detail !== recorded.detail)) {
631
- receiptReplayOk = false;
632
- }
633
- if (replayed?.decision === 'accepted') acceptedInReplay.add(receiptId);
634
- }
635
- // 最終planでのfull replayに現れる受理が、記録済みoutcomeへ全て対応することも要求。
636
- if (newPlan !== null) {
637
- for (const decision of recomputeReceiptDecisions({ plan: newPlan, events }).decisions) {
638
- if (decision.decision === 'accepted' && !recordedOutcomes.has(decision.receipt_id)) {
639
- receiptReplayOk = false;
640
- }
641
- }
642
- }
643
- checks.push({ id: 'receipt_replay_bidirectional', passed: receiptReplayOk });
644
- checks.push({
645
- id: 'provider_separation',
646
- passed: events.every((event) => (
647
- JSON.stringify(event.payload).includes('provider_handle') === false
648
- )),
649
- });
650
- const failed = checks.filter(({ passed }) => !passed).map(({ id }) => id);
651
- return { valid: failed.length === 0, checks, failed_conditions: failed };
652
- }
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdir, mkdtemp, readFile, rename, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ import { digestArtifact } from './artifact-contracts.mjs';
7
+ import { collectSensorEvidence } from './sensor-adapter.mjs';
8
+ import { scaffoldRc3DogfoodRepo, verifyRc3DogfoodScaffold } from './rc3-dogfood-scaffold.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 } from './runtime-contracts.mjs';
33
+
34
+ /**
35
+ * RC3-I actual multi-agent dogfood driver(plan RC3-I、ADR 0044 Decision 9.5)。
36
+ *
37
+ * 親orchestrator(Claude session)が実external executor(Claude implementer
38
+ * subagent等)を隔離worktreeへdispatchするための、状態fileベースのstep driver。
39
+ * 各stepは別processで実行できる純関数で、runtime stateはstate JSONのevent列
40
+ * だけから再構成する(in-memory adapter stateを持たない)。
41
+ *
42
+ * - core event chainはscripted campaignと同一契約。provider固有の観測
43
+ * (agent handle、実wall-clock、途中状態、回収、retry)は`provider_runs`として
44
+ * 分離保存し、core成功へ丸めない(plan「provider runtime observationとして分離」)。
45
+ * - 実executorはworktreeのfile変更だけを行う協調前提。commit・branch等の
46
+ * 禁止操作はdiff observerのHEAD drift検査でfail loudする。
47
+ * - 重複dispatch拒否・同一handle回収はstate上のactive attempt記録で強制する。
48
+ */
49
+
50
+ const RUN_TIMESTAMP = '2026-07-17T00:00:00.000Z';
51
+ const RUN_ID = 'rc3i-actual-01';
52
+ const ENTRY = 'research/fixtures/delivery-policy-registry/src/delivery-policy-registry.mjs';
53
+ const ORACLE = 'src/rc2-delivery-policy-oracle.mjs';
54
+ const SHARED_TEST = 'test/rc2-delivery-policy-fixture.test.mjs';
55
+
56
+ function fail(reason) {
57
+ throw new TypeError(`rc3 actual dogfood契約違反: ${reason}`);
58
+ }
59
+
60
+ function run(command, args, cwd) {
61
+ return new Promise((resolve, reject) => {
62
+ const child = spawn(command, args, { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
63
+ const stdout = [];
64
+ const stderr = [];
65
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
66
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
67
+ child.once('error', reject);
68
+ child.once('close', (code, signal) => {
69
+ if (code === 0 && signal === null) resolve(Buffer.concat(stdout).toString('utf8'));
70
+ else {
71
+ reject(new TypeError(
72
+ `${command} ${args[0]} failed (${signal ?? code}): ${Buffer.concat(stderr).toString('utf8').trim()}`,
73
+ ));
74
+ }
75
+ });
76
+ });
77
+ }
78
+
79
+ function statePath(stateDir) {
80
+ return path.join(stateDir, 'rc3i-state.json');
81
+ }
82
+
83
+ async function loadState(stateDir) {
84
+ return JSON.parse(await readFile(statePath(stateDir), 'utf8'));
85
+ }
86
+
87
+ async function saveState(stateDir, state) {
88
+ await writeFile(statePath(stateDir), `${JSON.stringify(state, null, 1)}\n`);
89
+ }
90
+
91
+ function witness(todoId, target, affectedTests) {
92
+ return {
93
+ owns: [{ kind: 'path', target }],
94
+ reads: [],
95
+ writes: [target],
96
+ resources: [],
97
+ state_effects: [],
98
+ sensor_provenance: {
99
+ queries: [{ query_id: `q-aff-${todoId}`, expect: { kind: 'affected', path: target } }],
100
+ },
101
+ affected_tests: affectedTests,
102
+ unknowns: [],
103
+ };
104
+ }
105
+
106
+ async function provisionWorktree(state, todoId, attempt) {
107
+ const worktreeRoot = await mkdtemp(path.join(tmpdir(), `lattice-rc3i-${todoId}-`));
108
+ const worktreePath = path.join(worktreeRoot, 'tree');
109
+ await run('git', ['worktree', 'add', '--detach', worktreePath, state.scaffold.target.base_sha], state.scaffold.repoRoot);
110
+ return {
111
+ handle: `actual-${todoId}-h${attempt}`,
112
+ worktree_id: `wt-${todoId}-a${attempt}`,
113
+ worktree_root: worktreeRoot,
114
+ worktree_path: worktreePath,
115
+ attempt,
116
+ active: true,
117
+ };
118
+ }
119
+
120
+ /** state駆動のexecutor adapter(dispatch=worktree provision、重複はstateで拒否)。 */
121
+ function stateAdapter(state) {
122
+ return {
123
+ kind: 'actual-agent',
124
+ async dispatch({ packet } = {}) {
125
+ const existing = state.worktrees[packet.todo_id];
126
+ if (existing !== undefined && existing.active) {
127
+ fail(`同一TODOの重複dispatchを拒否する: ${packet.todo_id}`);
128
+ }
129
+ const attempt = existing === undefined ? 1 : existing.attempt + 1;
130
+ const provisioned = await provisionWorktree(state, packet.todo_id, attempt);
131
+ state.worktrees[packet.todo_id] = provisioned;
132
+ return { executor_handle: provisioned.handle, worktree_id: provisioned.worktree_id };
133
+ },
134
+ };
135
+ }
136
+
137
+ /**
138
+ * step 1: scaffold・compile・全TODO dispatch(worktree provision)まで。
139
+ * 返り値のworktree pathsへ、親が実agentをdispatchする。
140
+ */
141
+ export async function initActualDogfoodRun({ latticeRoot, stateDir }) {
142
+ await mkdir(stateDir, { recursive: true });
143
+ const workRoot = await mkdtemp(path.join(tmpdir(), 'lattice-rc3i-scaffold-'));
144
+ const scaffold = await scaffoldRc3DogfoodRepo({ latticeRoot, workRoot });
145
+ const scaffoldVerified = await verifyRc3DogfoodScaffold({
146
+ latticeRoot, repoRoot: scaffold.repoRoot, expected: scaffold,
147
+ });
148
+ if (scaffoldVerified.outcome !== 'verified') fail('scaffold検証が失敗');
149
+
150
+ const probeQuerySet = {
151
+ queries: [ENTRY, ORACLE, SHARED_TEST].map((target, index) => (
152
+ { id: `probe-${index}`, operation: 'affected', target }
153
+ )),
154
+ };
155
+ const probed = await collectSensorEvidence({ cwd: scaffold.repoRoot, querySet: probeQuerySet });
156
+ const affectedByTarget = {};
157
+ probed.outcomes.forEach((outcome, index) => {
158
+ const entry = Array.isArray(outcome.targets) ? outcome.targets[0] : null;
159
+ affectedByTarget[probeQuerySet.queries[index].target] = Array.isArray(entry?.data?.affectedTests)
160
+ ? [...entry.data.affectedTests].sort()
161
+ : [];
162
+ });
163
+
164
+ const request = {
165
+ schema: 'lattice.run_request.v1',
166
+ request_id: 'rc3i-actual',
167
+ repo: { base_sha: scaffold.target.base_sha, root_kind: 'git-worktree' },
168
+ capacity: { executors: 3 },
169
+ todos: [{ todo_id: 'TA' }, { todo_id: 'TB' }, { todo_id: 'TC' }],
170
+ manual_witness: {
171
+ TA: witness('TA', ENTRY, affectedByTarget[ENTRY]),
172
+ TB: witness('TB', ORACLE, affectedByTarget[ORACLE]),
173
+ TC: witness('TC', SHARED_TEST, affectedByTarget[SHARED_TEST]),
174
+ },
175
+ sensor_query_set: {
176
+ queries: [
177
+ { id: 'q-status', operation: 'status' },
178
+ { id: 'q-aff-TA', operation: 'affected', target: ENTRY },
179
+ { id: 'q-aff-TB', operation: 'affected', target: ORACLE },
180
+ { id: 'q-aff-TC', operation: 'affected', target: SHARED_TEST },
181
+ ],
182
+ },
183
+ executor_capability: { adapters: ['actual-agent'] },
184
+ claim_mode: 'exact_minimum',
185
+ };
186
+ request.request_digest = selfDigest(request, 'request_digest');
187
+
188
+ const collected = await collectSensorEvidence({ cwd: scaffold.repoRoot, querySet: request.sensor_query_set });
189
+ const compiled = compileRuntimePlanV1({
190
+ request,
191
+ sensorEvidence: evidenceFromCollectedOutcomes({ querySet: request.sensor_query_set, collected }),
192
+ planRef: 'plan-rc3i-actual-e1',
193
+ planEpoch: 1,
194
+ predecessorRefs: [],
195
+ });
196
+ if (compiled.outcome !== 'dispatchable') fail(`compileがdispatchableにならない: ${compiled.code}`);
197
+ const packets = buildExecutorPackets({ plan: compiled.plan, manifests: compiled.manifests });
198
+
199
+ const state = {
200
+ schema: 'lattice.rc3.actual_dogfood_state.v1',
201
+ scaffold,
202
+ request,
203
+ plan: compiled.plan,
204
+ manifests: compiled.manifests,
205
+ packets,
206
+ newPlan: null,
207
+ rebindPackets: null,
208
+ redispatchPackets: null,
209
+ holdDecision: null,
210
+ planDiff: null,
211
+ events: initializeRunEvents({
212
+ runId: RUN_ID, request, plan: compiled.plan, manifests: compiled.manifests, recordedAt: RUN_TIMESTAMP,
213
+ }),
214
+ worktrees: {},
215
+ provider_runs: [],
216
+ probes: {},
217
+ };
218
+ const adapter = stateAdapter(state);
219
+ const dispatched = await dispatchReadyFrontier({
220
+ runId: RUN_ID, plan: state.plan, events: state.events,
221
+ packets, manifests: state.manifests, adapter, recordedAt: RUN_TIMESTAMP,
222
+ });
223
+ if (dispatched.failure) fail(`dispatch失敗: ${dispatched.failure.message}`);
224
+ state.events = dispatched.events;
225
+ await saveState(stateDir, state);
226
+ return {
227
+ dispatched: dispatched.dispatched,
228
+ worktrees: Object.fromEntries(Object.entries(state.worktrees).map(([todoId, entry]) => (
229
+ [todoId, { path: entry.worktree_path, handle: entry.handle, packet: packets[todoId] }]
230
+ ))),
231
+ };
232
+ }
233
+
234
+ /** provider観測(agent handle・時刻・状態遷移)をledgerへ追記する。core eventsへは入れない。 */
235
+ export async function recordProviderObservation({ stateDir, observation }) {
236
+ const state = await loadState(stateDir);
237
+ state.provider_runs.push(observation);
238
+ await saveState(stateDir, state);
239
+ return { count: state.provider_runs.length };
240
+ }
241
+
242
+ /** 指定TODOのworktree実diffをcheckpoint観測し、findingがあればconflict+freezeまで進める。 */
243
+ export async function observeActualCheckpoint({ stateDir, todoId, planKey = 'plan' }) {
244
+ const state = await loadState(stateDir);
245
+ const worktree = state.worktrees[todoId];
246
+ if (worktree === undefined || !worktree.active) fail(`active worktreeがない: ${todoId}`);
247
+ const plan = state[planKey];
248
+ const checkpoint = await captureWorktreeDiff({
249
+ worktreePath: worktree.worktree_path,
250
+ baseSha: state.scaffold.target.base_sha,
251
+ });
252
+ let events = [...state.events];
253
+ events.push(buildNextRunEvent({
254
+ events,
255
+ runId: RUN_ID,
256
+ kind: 'checkpoint_observed',
257
+ planEpoch: plan.plan_epoch,
258
+ subject: { kind: 'todo', ref: todoId },
259
+ payload: structuredClone(checkpoint),
260
+ recordedAt: RUN_TIMESTAMP,
261
+ }));
262
+ const packets = plan.plan_epoch === 1 ? state.packets : state.redispatchPackets ?? state.packets;
263
+ const classifyPackets = { ...state.packets, ...(state.redispatchPackets ?? {}) };
264
+ void packets;
265
+ const classified = classifyCheckpointObservation({
266
+ runId: RUN_ID, plan, events, packets: classifyPackets, manifests: state.manifests, todoId,
267
+ detect: detectCheckpointFindings, recordedAt: RUN_TIMESTAMP,
268
+ });
269
+ state.events = classified.events;
270
+ await saveState(stateDir, state);
271
+ return {
272
+ findings: classified.findings,
273
+ scope_expanded: classified.scope_expanded,
274
+ checkpoint_digest: checkpoint.checkpoint_digest,
275
+ };
276
+ }
277
+
278
+ /** hold裁定→recompile→(carried TODOの)rebind packet発行までを一括で行う。 */
279
+ export async function holdAndRecompile({ stateDir, additionalConflicts }) {
280
+ const state = await loadState(stateDir);
281
+ const held = decideHoldAndCarryOver({
282
+ runId: RUN_ID,
283
+ request: state.request,
284
+ plan: state.plan,
285
+ manifests: state.manifests,
286
+ packets: state.packets,
287
+ events: state.events,
288
+ recordedAt: RUN_TIMESTAMP,
289
+ });
290
+ const lane = routeConflictTreatment({
291
+ finding: held.holdDecision.finding,
292
+ predeclaredTreatments: [],
293
+ });
294
+ const recompiled = recompileNextEpochPlan({
295
+ runId: RUN_ID,
296
+ request: state.request,
297
+ plan: state.plan,
298
+ manifests: state.manifests,
299
+ packets: state.packets,
300
+ events: held.events,
301
+ holdDecision: held.holdDecision,
302
+ additionalConflicts,
303
+ recordedAt: RUN_TIMESTAMP,
304
+ });
305
+ state.events = recompiled.events;
306
+ state.holdDecision = held.holdDecision;
307
+ state.newPlan = recompiled.newPlan;
308
+ state.planDiff = recompiled.planDiff;
309
+ state.rebindPackets = recompiled.rebindPackets;
310
+ state.redispatchPackets = recompiled.redispatchPackets;
311
+ // rebind: carried TODOのpacket epochを更新(同一handle・content不変)。
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
+ // hold集合のworktreeは失効(active解除。掃除はcleanupWorktreesで記録付き実施)。
319
+ for (const todoId of held.holdDecision.hold_set) {
320
+ if (state.worktrees[todoId] !== undefined) state.worktrees[todoId].active = false;
321
+ }
322
+ await saveState(stateDir, state);
323
+ return {
324
+ hold: held.holdDecision.hold_set,
325
+ continue: held.holdDecision.continue_set,
326
+ lane: lane.lane,
327
+ new_epoch: recompiled.newPlan.plan_epoch,
328
+ };
329
+ }
330
+
331
+ /** terminal receipt(現attemptの最終checkpointへbind)を記録し、受理裁定まで行う。 */
332
+ export async function terminalActualReceipt({ stateDir, todoId, planKey }) {
333
+ const state = await loadState(stateDir);
334
+ const plan = state[planKey];
335
+ const worktree = state.worktrees[todoId];
336
+ if (worktree === undefined || !worktree.active) fail(`active worktreeがない: ${todoId}`);
337
+ const packet = planKey === 'newPlan' && state.redispatchPackets?.[todoId] !== undefined
338
+ ? state.redispatchPackets[todoId]
339
+ : state.packets[todoId];
340
+ const stateProjection = projectRuntimeState({ events: state.events });
341
+ const dispatchRecord = stateProjection.dispatches[todoId];
342
+ const attemptCheckpoints = stateProjection.checkpoints.filter((entry) => (
343
+ entry.todo_id === todoId && entry.sequence > dispatchRecord.sequence
344
+ ));
345
+ if (attemptCheckpoints.length === 0) fail(`checkpoint未観測でterminalにできない: ${todoId}`);
346
+ const lastCheckpoint = attemptCheckpoints[attemptCheckpoints.length - 1].payload;
347
+ const receipt = {
348
+ schema: 'lattice.executor_receipt.v1',
349
+ receipt_id: `${todoId}-a${worktree.attempt}-r1`,
350
+ executor_handle: worktree.handle,
351
+ worktree_id: worktree.worktree_id,
352
+ base_sha: packet.base_sha,
353
+ plan_epoch: packet.plan_epoch,
354
+ packet_digest: dispatchRecord.payload.packet_digest,
355
+ todo_id: todoId,
356
+ checkpoint_digest: lastCheckpoint.checkpoint_digest,
357
+ observed_diff: lastCheckpoint.diff.entries.map(({ path: p, change }) => ({ path: p, change })),
358
+ };
359
+ receipt.receipt_digest = selfDigest(receipt, 'receipt_digest');
360
+ let events = [...state.events];
361
+ events.push(buildNextRunEvent({
362
+ events,
363
+ runId: RUN_ID,
364
+ kind: 'receipt_recorded',
365
+ planEpoch: receipt.plan_epoch,
366
+ subject: { kind: 'todo', ref: todoId },
367
+ payload: receipt,
368
+ recordedAt: RUN_TIMESTAMP,
369
+ }));
370
+ // worktree cleanup(失敗は成功へ丸めずterminal payloadへ記録)。
371
+ let cleanup = { cleanup_ok: true, residual_paths: [] };
372
+ try {
373
+ await run('git', ['worktree', 'remove', '--force', worktree.worktree_path], state.scaffold.repoRoot);
374
+ } catch (error) {
375
+ cleanup = {
376
+ cleanup_ok: false,
377
+ residual_paths: [worktree.worktree_root],
378
+ message: String(error?.message ?? error),
379
+ };
380
+ }
381
+ events.push(buildNextRunEvent({
382
+ events,
383
+ runId: RUN_ID,
384
+ kind: 'executor_terminal',
385
+ planEpoch: plan.plan_epoch,
386
+ subject: { kind: 'todo', ref: todoId },
387
+ payload: { executor_handle: worktree.handle, terminal_state: 'reported', cleanup },
388
+ recordedAt: RUN_TIMESTAMP,
389
+ }));
390
+ const adjudicated = adjudicatePendingReceipts({
391
+ runId: RUN_ID, plan, events, recordedAt: RUN_TIMESTAMP,
392
+ });
393
+ state.events = adjudicated.events;
394
+ state.worktrees[todoId].active = false;
395
+ await saveState(stateDir, state);
396
+ return { decisions: adjudicated.decisions, receipt_id: receipt.receipt_id };
397
+ }
398
+
399
+ /** 重複dispatch拒否のprobe(typed拒否をprovider観測として記録)。 */
400
+ export async function probeDuplicateDispatch({ stateDir, todoId }) {
401
+ const state = await loadState(stateDir);
402
+ const adapter = stateAdapter(state);
403
+ let refused = null;
404
+ try {
405
+ await adapter.dispatch({ packet: state.packets[todoId] });
406
+ } catch (error) {
407
+ refused = String(error?.message ?? error);
408
+ }
409
+ state.probes.duplicate_dispatch = { todo_id: todoId, refused };
410
+ await saveState(stateDir, state);
411
+ if (refused === null) fail('重複dispatchが拒否されなかった');
412
+ return { refused };
413
+ }
414
+
415
+ /** 旧epoch stale receiptのprobe(typed rejectを記録)。 */
416
+ export async function probeStaleReceipt({ stateDir, todoId }) {
417
+ const state = await loadState(stateDir);
418
+ const stateProjection = projectRuntimeState({ events: state.events });
419
+ const dispatchRecord = stateProjection.dispatches[todoId];
420
+ const staleReceipt = {
421
+ schema: 'lattice.executor_receipt.v1',
422
+ receipt_id: `${todoId}-stale-r1`,
423
+ executor_handle: dispatchRecord.payload.executor_handle,
424
+ worktree_id: dispatchRecord.payload.worktree_id,
425
+ base_sha: state.plan.base_sha,
426
+ plan_epoch: state.plan.plan_epoch,
427
+ packet_digest: dispatchRecord.payload.packet_digest,
428
+ todo_id: todoId,
429
+ checkpoint_digest: '2'.repeat(64),
430
+ observed_diff: [],
431
+ };
432
+ staleReceipt.receipt_digest = selfDigest(staleReceipt, 'receipt_digest');
433
+ let events = [...state.events];
434
+ events.push(buildNextRunEvent({
435
+ events,
436
+ runId: RUN_ID,
437
+ kind: 'receipt_recorded',
438
+ planEpoch: staleReceipt.plan_epoch,
439
+ subject: { kind: 'todo', ref: todoId },
440
+ payload: staleReceipt,
441
+ recordedAt: RUN_TIMESTAMP,
442
+ }));
443
+ const adjudicated = adjudicatePendingReceipts({
444
+ runId: RUN_ID, plan: state.newPlan, events, recordedAt: RUN_TIMESTAMP,
445
+ });
446
+ const decision = adjudicated.decisions.find(({ receipt_id: id }) => id === staleReceipt.receipt_id);
447
+ if (decision?.decision !== 'rejected') fail('stale receiptがrejectされなかった');
448
+ state.events = adjudicated.events;
449
+ state.probes.stale_receipt = { todo_id: todoId, decision };
450
+ await saveState(stateDir, state);
451
+ return { decision };
452
+ }
453
+
454
+ /** epoch 2のredispatch(1件ずつ。frontier/conflict規則はengineに従う)。 */
455
+ export async function redispatchNext({ stateDir }) {
456
+ const state = await loadState(stateDir);
457
+ const adapter = stateAdapter(state);
458
+ const dispatched = await dispatchReadyFrontier({
459
+ runId: RUN_ID,
460
+ plan: state.newPlan,
461
+ events: state.events,
462
+ packets: state.redispatchPackets,
463
+ manifests: state.manifests,
464
+ adapter,
465
+ recordedAt: RUN_TIMESTAMP,
466
+ });
467
+ if (dispatched.failure) fail(`redispatch失敗: ${dispatched.failure.message}`);
468
+ state.events = dispatched.events;
469
+ await saveState(stateDir, state);
470
+ return {
471
+ dispatched: dispatched.dispatched,
472
+ worktrees: Object.fromEntries(dispatched.dispatched.map((todoId) => (
473
+ [todoId, {
474
+ path: state.worktrees[todoId].worktree_path,
475
+ handle: state.worktrees[todoId].handle,
476
+ packet: state.redispatchPackets[todoId],
477
+ }]
478
+ ))),
479
+ };
480
+ }
481
+
482
+ /** run close+残worktree掃除(残存は記録)。 */
483
+ export async function closeActualRun({ stateDir }) {
484
+ const state = await loadState(stateDir);
485
+ const closed = closeRunIfComplete({
486
+ runId: RUN_ID, plan: state.newPlan ?? state.plan, events: state.events, recordedAt: RUN_TIMESTAMP,
487
+ });
488
+ state.events = closed.events;
489
+ const residual = [];
490
+ for (const [todoId, worktree] of Object.entries(state.worktrees)) {
491
+ if (!worktree.active) continue;
492
+ try {
493
+ await run('git', ['worktree', 'remove', '--force', worktree.worktree_path], state.scaffold.repoRoot);
494
+ worktree.active = false;
495
+ } catch (error) {
496
+ residual.push({ todo_id: todoId, path: worktree.worktree_root, message: String(error?.message ?? error) });
497
+ }
498
+ }
499
+ state.probes.residual_worktrees = residual;
500
+ await saveState(stateDir, state);
501
+ return { closed: closed.closed, residual };
502
+ }
503
+
504
+ /** artifact v2をatomic no-overwriteで発行する。 */
505
+ export async function publishActualArtifact({ stateDir, artifactRoot }) {
506
+ const state = await loadState(stateDir);
507
+ await mkdir(path.dirname(artifactRoot), { recursive: true });
508
+ const staging = `${artifactRoot}.staging`;
509
+ try {
510
+ await mkdir(staging);
511
+ } catch (error) {
512
+ fail(`stagingを排他作成できない: ${String(error?.message ?? error)}`);
513
+ }
514
+ const documents = {
515
+ 'request.json': state.request,
516
+ 'plan.json': state.plan,
517
+ 'new-plan.json': state.newPlan,
518
+ 'manifests.json': state.manifests,
519
+ 'hold-decision.json': state.holdDecision,
520
+ 'plan-diff.json': state.planDiff,
521
+ 'events.json': state.events,
522
+ 'provider-runs.json': state.provider_runs,
523
+ 'probes.json': state.probes,
524
+ };
525
+ const manifestEntries = {};
526
+ for (const [name, document] of Object.entries(documents)) {
527
+ await writeFile(path.join(staging, name), `${JSON.stringify(document, null, 1)}\n`);
528
+ manifestEntries[name] = digestArtifact(document);
529
+ }
530
+ const manifest = {
531
+ schema: 'lattice.rc3.actual_dogfood_manifest.v1',
532
+ run_id: RUN_ID,
533
+ scaffold: {
534
+ lattice_source_base_sha: state.scaffold.lattice_source.base_sha,
535
+ target_base_sha: state.scaffold.target.base_sha,
536
+ path_digests: state.scaffold.target.path_digests,
537
+ },
538
+ document_digests: manifestEntries,
539
+ };
540
+ await writeFile(path.join(staging, 'dogfood-manifest.json'), `${JSON.stringify(manifest, null, 1)}\n`);
541
+ try {
542
+ let exists = true;
543
+ try {
544
+ await readFile(path.join(artifactRoot, 'dogfood-manifest.json'));
545
+ } catch (error) {
546
+ exists = error?.code !== 'ENOENT';
547
+ }
548
+ if (exists) throw new TypeError('既存artifact rootが存在する');
549
+ await rename(staging, artifactRoot);
550
+ } catch (error) {
551
+ const { rm } = await import('node:fs/promises');
552
+ await rm(staging, { recursive: true, force: true });
553
+ fail(`artifact発行に失敗(上書き禁止): ${String(error?.message ?? error)}`);
554
+ }
555
+ return { manifest };
556
+ }
557
+
558
+ /** artifact v2を保存bytesだけから再検証する。 */
559
+ export async function verifyActualArtifactOnDisk({ artifactRoot }) {
560
+ const manifest = JSON.parse(await readFile(path.join(artifactRoot, 'dogfood-manifest.json'), 'utf8'));
561
+ const checks = [];
562
+ const documents = {};
563
+ for (const [name, digest] of Object.entries(manifest.document_digests)) {
564
+ const document = JSON.parse(await readFile(path.join(artifactRoot, name), 'utf8'));
565
+ documents[name] = document;
566
+ checks.push({ id: `digest:${name}`, passed: digestArtifact(document) === digest });
567
+ }
568
+ const events = documents['events.json'];
569
+ const plan = documents['plan.json'];
570
+ const newPlan = documents['new-plan.json'];
571
+ const chain = verifyRunEventChain({ events });
572
+ checks.push({ id: 'event_chain', passed: chain.valid });
573
+ for (const [label, targetPlan] of [['e1', plan], ['e2', newPlan]]) {
574
+ events.forEach((event, index) => {
575
+ if (event.kind !== 'dispatch_decided' || event.plan_epoch !== targetPlan.plan_epoch) return;
576
+ const recomputed = computeReadyFrontier({ plan: targetPlan, events: events.slice(0, index) });
577
+ checks.push({
578
+ id: `dispatch_replay:${label}:seq${event.sequence}`,
579
+ passed: JSON.stringify(event.payload.dispatchable) === JSON.stringify(recomputed.dispatchable),
580
+ });
581
+ });
582
+ }
583
+ const holdDecision = documents['hold-decision.json'];
584
+ const holdIndex = events.findIndex((event) => event.kind === 'hold_decided');
585
+ const recomputedHold = recomputeHoldDecision({
586
+ plan, events: events.slice(0, holdIndex), manifests: documents['manifests.json'],
587
+ });
588
+ checks.push({
589
+ id: 'hold_replay',
590
+ passed: JSON.stringify(recomputedHold.hold_set) === JSON.stringify(holdDecision.hold_set)
591
+ && JSON.stringify(recomputedHold.continue_set) === JSON.stringify(holdDecision.continue_set),
592
+ });
593
+ // receipt裁定の再計算: 記録済みoutcome event(accepted/rejected+detail)と
594
+ // replay結果の双方向・reason粒度の一致を要求する(片側包含にしない。RC3-J P1採用)。
595
+ // 各receiptの裁定は「outcome eventのepoch=裁定時のactive plan」で再計算する
596
+ //(receiptが名乗るepochではない。staleは新planの下でepoch_mismatchになる)。
597
+ const recordedOutcomes = new Map();
598
+ for (const event of events) {
599
+ if (event.kind !== 'receipt_accepted' && event.kind !== 'receipt_rejected') continue;
600
+ const receiptId = event.payload?.receipt_id;
601
+ if (typeof receiptId !== 'string') continue;
602
+ recordedOutcomes.set(receiptId, {
603
+ decision: event.kind === 'receipt_accepted' ? 'accepted' : 'rejected',
604
+ detail: event.payload?.detail ?? null,
605
+ adjudication_epoch: event.plan_epoch,
606
+ });
607
+ }
608
+ const planByEpoch = new Map([plan, newPlan]
609
+ .filter((entry) => entry !== null)
610
+ .map((entry) => [entry.plan_epoch, entry]));
611
+ let receiptReplayOk = recordedOutcomes.size > 0;
612
+ const acceptedInReplay = new Set();
613
+ for (const [receiptId, recorded] of recordedOutcomes) {
614
+ const adjudicationPlan = planByEpoch.get(recorded.adjudication_epoch);
615
+ if (adjudicationPlan === undefined) {
616
+ receiptReplayOk = false;
617
+ continue;
618
+ }
619
+ // 裁定「前」のprefix(outcome event以前)に対するreplayと比較する。
620
+ const outcomeIndex = events.findIndex((event) => (
621
+ (event.kind === 'receipt_accepted' || event.kind === 'receipt_rejected')
622
+ && event.payload?.receipt_id === receiptId
623
+ ));
624
+ const replayed = recomputeReceiptDecisions({
625
+ plan: adjudicationPlan,
626
+ events: events.slice(0, outcomeIndex),
627
+ }).decisions.find(({ receipt_id: id }) => id === receiptId);
628
+ if (replayed === undefined
629
+ || replayed.decision !== recorded.decision
630
+ || (recorded.decision === 'rejected' && replayed.detail !== recorded.detail)) {
631
+ receiptReplayOk = false;
632
+ }
633
+ if (replayed?.decision === 'accepted') acceptedInReplay.add(receiptId);
634
+ }
635
+ // 最終planでのfull replayに現れる受理が、記録済みoutcomeへ全て対応することも要求。
636
+ if (newPlan !== null) {
637
+ for (const decision of recomputeReceiptDecisions({ plan: newPlan, events }).decisions) {
638
+ if (decision.decision === 'accepted' && !recordedOutcomes.has(decision.receipt_id)) {
639
+ receiptReplayOk = false;
640
+ }
641
+ }
642
+ }
643
+ checks.push({ id: 'receipt_replay_bidirectional', passed: receiptReplayOk });
644
+ checks.push({
645
+ id: 'provider_separation',
646
+ passed: events.every((event) => (
647
+ JSON.stringify(event.payload).includes('provider_handle') === false
648
+ )),
649
+ });
650
+ const failed = checks.filter(({ passed }) => !passed).map(({ id }) => id);
651
+ return { valid: failed.length === 0, checks, failed_conditions: failed };
652
+ }