pi-spine 2.1.0 → 2.3.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 (49) hide show
  1. package/bin/spine-batch.mjs +74 -5
  2. package/bin/spine-cli/verify.mjs +2 -18
  3. package/package.json +1 -1
  4. package/src/batch/attached-runner-promote.mjs +370 -0
  5. package/src/batch/attached-runner-reconcile.mjs +291 -0
  6. package/src/batch/attached-runner.mjs +24 -634
  7. package/src/batch/batch-guards.mjs +69 -0
  8. package/src/batch/contract-exec.mjs +483 -0
  9. package/src/batch/contract-parse.mjs +243 -0
  10. package/src/batch/contract-verify.mjs +32 -707
  11. package/src/batch/detached-diagnostics.mjs +255 -0
  12. package/src/batch/detached-run.mjs +326 -0
  13. package/src/batch/detached-start.mjs +18 -894
  14. package/src/batch/detached-wait.mjs +346 -0
  15. package/src/batch/engine-lanes/merge.mjs +25 -0
  16. package/src/batch/engine.mjs +8 -67
  17. package/src/batch/integrate-git.mjs +21 -0
  18. package/src/batch/integrate.mjs +5 -15
  19. package/src/batch/journal-rebuild-structural.mjs +352 -0
  20. package/src/batch/journal-rebuild.mjs +94 -347
  21. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  22. package/src/batch/lane-dirty-check-git.mjs +298 -0
  23. package/src/batch/lane-dirty-check.mjs +31 -297
  24. package/src/batch/reconcile-batch.mjs +483 -0
  25. package/src/batch/reconcile-classify.mjs +433 -0
  26. package/src/batch/reconcile-diagnosis.mjs +459 -0
  27. package/src/batch/reconcile-light-cache.mjs +61 -0
  28. package/src/batch/reconcile-orphan.mjs +198 -0
  29. package/src/batch/reconcile.mjs +19 -1693
  30. package/src/batch/resume-multi-lanes.mjs +44 -149
  31. package/src/batch/resume-multi-queue.mjs +159 -0
  32. package/src/batch/resume-single-validate.mjs +25 -0
  33. package/src/batch/resume.mjs +3 -20
  34. package/src/batch/review-artifacts.mjs +419 -0
  35. package/src/batch/review-step-run.mjs +383 -0
  36. package/src/batch/review-step.mjs +451 -0
  37. package/src/batch/review.mjs +32 -1199
  38. package/src/batch/salvage-batch-list.mjs +291 -0
  39. package/src/batch/salvage-batch.mjs +417 -0
  40. package/src/batch/sequence-plan.mjs +234 -0
  41. package/src/batch/sequence-run.mjs +418 -0
  42. package/src/batch/sequence-wait.mjs +167 -0
  43. package/src/batch/sequence.mjs +22 -783
  44. package/src/batch/state-guards.mjs +284 -0
  45. package/src/batch/state-io.mjs +135 -0
  46. package/src/batch/state.mjs +27 -396
  47. package/src/batch/worker-heartbeat.mjs +375 -0
  48. package/src/batch/worker-host.mjs +50 -541
  49. package/src/batch/worker-spawn.mjs +315 -0
@@ -1,359 +1,30 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Rebuild batch task/segment status from append-only journal (FR-REL-01/02, PRD §11.4).
4
+ * Structural derivation → journal-rebuild-structural.mjs (SP-584).
5
+ * Drift reconcile remains here until SP-602.
4
6
  */
5
7
 
6
8
  import fs from "node:fs";
7
- import { appendJournalEvent, readJournalEvents, STRUCTURAL_JOURNAL_EVENT_TYPES } from "./journal.mjs";
9
+ import path from "node:path";
10
+ import { execFileSync } from "node:child_process";
11
+ import { appendJournalEvent } from "./journal.mjs";
12
+ import { laneTaskBranch } from "./worktree.mjs";
8
13
  import { parseReviewVerdict } from "./review-shared.mjs";
9
14
  import { journalHasTaskCompleted } from "./resume-common.mjs";
10
- import {
11
- clearTaskFailureMetadata,
12
- createInitialBatchState,
13
- recordTaskSucceeded,
14
- recomputeTaskCounters,
15
- saveSpineBatchState,
16
- updateSegmentForTask,
17
- } from "./state.mjs";
18
-
19
- /** @type {ReadonlySet<string>} */
20
- export const TASK_LIFECYCLE_EVENT_TYPES = new Set([
21
- "task.started",
22
- "task.completed",
23
- "task.failed",
24
- "task.skipped",
25
- "task.skipped_done_on_disk",
26
- "task.retry_requested",
27
- "task.prompt_parse_failed",
28
- ]);
29
-
30
- /** @type {ReadonlySet<string>} */
31
- export const BATCH_PHASE_EVENT_TYPES = new Set([
32
- "batch.started",
33
- "batch.resumed",
34
- "batch.paused",
35
- "batch.completed",
36
- "batch.failed",
37
- "batch.aborted",
38
- "batch.dismissed",
39
- ]);
40
-
41
- export function readJournalTimeline(events) {
42
- return events.filter(
43
- (event) =>
44
- TASK_LIFECYCLE_EVENT_TYPES.has(String(event?.type ?? "")) ||
45
- BATCH_PHASE_EVENT_TYPES.has(String(event?.type ?? "")),
46
- );
47
- }
48
-
49
- export function readJournalTimelineFromDisk(projectRoot, batchId) {
50
- return readJournalTimeline(readJournalEvents(projectRoot, batchId));
51
- }
52
-
53
- function payloadOf(event) {
54
- return event.payload && typeof event.payload === "object" ? event.payload : {};
55
- }
56
-
57
- function tsOf(event) {
58
- return Date.parse(String(event.timestamp ?? "")) || Date.now();
59
- }
60
-
61
- function taskIdsOf(value) {
62
- if (typeof value === "string") return value.split(/\s+/).map((s) => s.trim()).filter(Boolean);
63
- if (!Array.isArray(value)) return [];
64
- return value.map((entry) => String(entry ?? "").trim()).filter(Boolean);
65
- }
66
-
67
- function taskStub(map, taskId, hints = {}) {
68
- const row = map.get(taskId) ?? { taskId };
69
- if (hints.laneNumber != null) row.laneNumber = Number(hints.laneNumber) || row.laneNumber || 1;
70
- if (typeof hints.taskFolder === "string" && hints.taskFolder) row.taskFolder = hints.taskFolder;
71
- map.set(taskId, row);
72
- return row;
73
- }
74
-
75
- function laneStub(map, laneNumber, hints = {}) {
76
- const row = map.get(laneNumber) ?? { laneNumber, laneId: hints.laneId ?? `lane-${laneNumber}`, taskIds: [] };
77
- row.laneId = hints.laneId ?? row.laneId;
78
- if (typeof hints.worktreePath === "string") row.worktreePath = hints.worktreePath;
79
- if (typeof hints.taskBranch === "string") row.branch = hints.taskBranch;
80
- if (!Array.isArray(row.taskIds)) row.taskIds = [];
81
- map.set(laneNumber, row);
82
- return row;
83
- }
84
-
85
- function finalizeTasks(tasksById, seedTasks) {
86
- const seedById = new Map((seedTasks ?? []).filter((t) => t?.taskId).map((t) => [String(t.taskId), t]));
87
- return [...new Set([...tasksById.keys(), ...seedById.keys()])].map((taskId) => {
88
- const derived = tasksById.get(taskId) ?? { taskId };
89
- const seed = seedById.get(taskId);
90
- return {
91
- taskId,
92
- laneNumber: Number(derived.laneNumber ?? seed?.laneNumber ?? 1) || 1,
93
- status: "pending",
94
- taskFolder: derived.taskFolder ?? seed?.taskFolder ?? null,
95
- sessionName: seed?.sessionName,
96
- startedAt: null,
97
- endedAt: null,
98
- doneFileFound: false,
99
- exitReason: null,
100
- };
101
- });
102
- }
103
-
104
- function finalizeLanes(lanesByNumber, seedLanes, tasks) {
105
- const seedByNumber = new Map((seedLanes ?? []).filter((l) => l?.laneNumber != null).map((l) => [Number(l.laneNumber), l]));
106
- const laneNumbers = new Set([...lanesByNumber.keys(), ...seedByNumber.keys()]);
107
- for (const task of tasks) if (task?.laneNumber != null) laneNumbers.add(Number(task.laneNumber));
108
- if (laneNumbers.size === 0) laneNumbers.add(1);
109
- return [...laneNumbers].sort((a, b) => a - b).map((laneNumber) => {
110
- const derived = lanesByNumber.get(laneNumber) ?? { laneNumber, laneId: `lane-${laneNumber}` };
111
- const seed = seedByNumber.get(laneNumber);
112
- const taskIds = [...new Set([
113
- ...(derived.taskIds ?? []),
114
- ...(seed?.taskIds ?? []),
115
- ...tasks.filter((t) => Number(t.laneNumber) === laneNumber).map((t) => t.taskId),
116
- ])];
117
- return {
118
- laneNumber,
119
- laneId: derived.laneId ?? seed?.laneId ?? `lane-${laneNumber}`,
120
- laneSessionId: seed?.laneSessionId,
121
- worktreePath: derived.worktreePath ?? seed?.worktreePath ?? null,
122
- branch: derived.branch ?? seed?.branch ?? null,
123
- taskIds,
124
- lastHeartbeatAt: seed?.lastHeartbeatAt ?? null,
125
- status: seed?.status ?? "pending",
126
- };
127
- });
128
- }
129
-
130
- /** Derive structural batch-state fields from journal; cache seed fills gaps only (FR-SHIP-10). */
131
- export function deriveStructuralBatchStateFromJournal(events, seedState = null) {
132
- const lanesByNumber = new Map();
133
- const tasksById = new Map();
134
- const wavePlanRows = [];
135
- const mergeResults = [];
136
- let batchId = String(seedState?.batchId ?? "").trim();
137
- let baseBranch = null;
138
- let orchBranch = null;
139
- let startedAt = null;
140
-
141
- for (const event of events) {
142
- const type = String(event?.type ?? "");
143
- if (!STRUCTURAL_JOURNAL_EVENT_TYPES.has(type)) continue;
144
- if (!batchId && typeof event.batchId === "string") batchId = event.batchId;
145
- const payload = payloadOf(event);
146
- const timestamp = tsOf(event);
147
- const taskId = typeof event.taskId === "string" ? event.taskId : typeof payload.taskId === "string" ? payload.taskId : null;
148
-
149
- if (type === "batch.started" || type === "batch.resumed") {
150
- if (startedAt == null) startedAt = timestamp;
151
- if (typeof payload.baseBranch === "string" && payload.baseBranch) baseBranch = payload.baseBranch;
152
- if (typeof payload.orchBranch === "string" && payload.orchBranch) orchBranch = payload.orchBranch;
153
- if (Array.isArray(payload.wavePlan)) {
154
- for (const wave of payload.wavePlan) if (Array.isArray(wave)) wavePlanRows.push([...wave]);
155
- }
156
- for (const scopedTaskId of taskIdsOf(payload.scope ?? payload.taskIds)) taskStub(tasksById, scopedTaskId, payload);
157
- }
158
-
159
- if (type === "lane.provisioned") {
160
- const laneNumber = Number(payload.laneNumber);
161
- if (Number.isFinite(laneNumber)) laneStub(lanesByNumber, laneNumber, payload);
162
- }
163
-
164
- if (type === "lane.tasks_serialized") {
165
- const laneNumber = Number(payload.laneNumber);
166
- const waveIndex = Number(payload.waveIndex ?? wavePlanRows.length);
167
- const serializedTaskIds = taskIdsOf(payload.taskIds);
168
- if (serializedTaskIds.length > 0) {
169
- while (wavePlanRows.length <= waveIndex) wavePlanRows.push([]);
170
- wavePlanRows[waveIndex] = [...new Set([...wavePlanRows[waveIndex], ...serializedTaskIds])];
171
- }
172
- if (Number.isFinite(laneNumber)) {
173
- const lane = laneStub(lanesByNumber, laneNumber, payload);
174
- for (const id of serializedTaskIds) {
175
- if (!lane.taskIds.includes(id)) lane.taskIds.push(id);
176
- taskStub(tasksById, id, { laneNumber, laneId: lane.laneId });
177
- }
178
- }
179
- }
180
-
181
- if (type === "task.started" && taskId) {
182
- const laneNumber = Number(payload.laneNumber ?? event.laneNumber);
183
- taskStub(tasksById, taskId, { laneNumber, laneId: payload.laneId ?? event.laneId });
184
- if (Number.isFinite(laneNumber)) {
185
- const lane = laneStub(lanesByNumber, laneNumber, { laneId: payload.laneId ?? event.laneId });
186
- if (!lane.taskIds.includes(taskId)) lane.taskIds.push(taskId);
187
- }
188
- }
189
-
190
- if (type === "task.skipped_done_on_disk" && taskId) taskStub(tasksById, taskId, payload);
191
-
192
- if (type === "batch.merge_started") {
193
- if (typeof payload.baseBranch === "string" && payload.baseBranch) baseBranch = payload.baseBranch;
194
- if (typeof payload.orchBranch === "string" && payload.orchBranch) orchBranch = payload.orchBranch;
195
- }
196
-
197
- if (type === "batch.merge_completed" || type === "lane.committed") {
198
- const mergeCommit = payload.mergeCommit ?? payload.commitSha;
199
- if (mergeCommit) {
200
- mergeResults.push({ mergeCommit, taskId: taskId ?? payload.taskId ?? null, laneNumber: payload.laneNumber ?? null });
201
- }
202
- }
203
- }
204
-
205
- const resolvedBatchId = batchId || String(seedState?.batchId ?? "").trim();
206
- const tasks = finalizeTasks(tasksById, seedState?.tasks);
207
- let wavePlan = wavePlanRows.filter((wave) => wave.length > 0);
208
- if (wavePlan.length === 0 && Array.isArray(seedState?.wavePlan) && seedState.wavePlan.length > 0) {
209
- wavePlan = seedState.wavePlan;
210
- } else if (wavePlan.length === 0 && tasks.length > 0) {
211
- wavePlan = [tasks.map((task) => task.taskId)];
212
- } else if (wavePlan.length === 0) {
213
- wavePlan = [[]];
214
- }
215
-
216
- const structural = createInitialBatchState({
217
- batchId: resolvedBatchId,
218
- baseBranch: baseBranch ?? seedState?.baseBranch ?? "main",
219
- orchBranch: orchBranch ?? seedState?.orchBranch ?? (resolvedBatchId ? `orch/spine-${resolvedBatchId}` : "main"),
220
- wavePlan,
221
- tasks,
222
- lanes: finalizeLanes(lanesByNumber, seedState?.lanes, tasks),
223
- });
224
-
225
- structural.startedAt = startedAt ?? seedState?.startedAt ?? Date.now();
226
- structural.mergeResults = mergeResults.length > 0 ? mergeResults : Array.isArray(seedState?.mergeResults) ? seedState.mergeResults : [];
227
- structural.currentWaveIndex = Number(seedState?.currentWaveIndex ?? 0) || 0;
228
- structural.blockedTasks = Number(seedState?.blockedTasks ?? 0) || 0;
229
- structural.blockedTaskIds = Array.isArray(seedState?.blockedTaskIds) ? [...seedState.blockedTaskIds] : [];
230
- structural.resilience = seedState?.resilience && typeof seedState.resilience === "object" ? structuredClone(seedState.resilience) : structural.resilience;
231
- structural.lastError = seedState?.lastError ?? null;
232
- return structural;
233
- }
234
-
235
- function mergeSeedOnlyFields(rebuilt, seedState) {
236
- if (!seedState || typeof seedState !== "object") return;
237
- rebuilt.currentWaveIndex = Number(seedState.currentWaveIndex ?? rebuilt.currentWaveIndex ?? 0) || 0;
238
- rebuilt.blockedTasks = Number(seedState.blockedTasks ?? rebuilt.blockedTasks ?? 0) || 0;
239
- rebuilt.blockedTaskIds = Array.isArray(seedState.blockedTaskIds) ? [...seedState.blockedTaskIds] : rebuilt.blockedTaskIds;
240
- if (seedState.resilience && typeof seedState.resilience === "object") rebuilt.resilience = structuredClone(seedState.resilience);
241
- if (rebuilt.mergeResults.length === 0 && Array.isArray(seedState.mergeResults)) rebuilt.mergeResults = structuredClone(seedState.mergeResults);
242
-
243
- const seedTasks = new Map((seedState.tasks ?? []).filter((t) => t?.taskId).map((t) => [String(t.taskId), t]));
244
- for (const task of rebuilt.tasks ?? []) {
245
- const seedTask = seedTasks.get(String(task.taskId));
246
- if (!seedTask) continue;
247
- if (!task.taskFolder && seedTask.taskFolder) task.taskFolder = seedTask.taskFolder;
248
- if (!task.sessionName && seedTask.sessionName) task.sessionName = seedTask.sessionName;
249
- }
250
-
251
- const seedLanes = new Map((seedState.lanes ?? []).filter((l) => l?.laneNumber != null).map((l) => [Number(l.laneNumber), l]));
252
- for (const lane of rebuilt.lanes ?? []) {
253
- const seedLane = seedLanes.get(Number(lane.laneNumber));
254
- if (!seedLane) continue;
255
- if (!lane.worktreePath && seedLane.worktreePath) lane.worktreePath = seedLane.worktreePath;
256
- if (!lane.branch && seedLane.branch) lane.branch = seedLane.branch;
257
- if (!lane.laneSessionId && seedLane.laneSessionId) lane.laneSessionId = seedLane.laneSessionId;
258
- }
259
- if (!rebuilt.segments?.length && Array.isArray(seedState.segments) && seedState.segments.length > 0) {
260
- rebuilt.segments = structuredClone(seedState.segments);
261
- }
262
- }
15
+ import { recordTaskSucceeded, saveSpineBatchState } from "./state.mjs";
263
16
 
264
- function applyJournalEvent(state, event) {
265
- const type = String(event?.type ?? "");
266
- const taskId = typeof event.taskId === "string" ? event.taskId : null;
267
- const payload = payloadOf(event);
268
- const timestamp = tsOf(event);
269
- if (!taskId && !BATCH_PHASE_EVENT_TYPES.has(type)) return;
270
- const task = taskId ? (state.tasks ?? []).find((entry) => entry?.taskId === taskId) : null;
271
-
272
- switch (type) {
273
- case "batch.started":
274
- case "batch.resumed":
275
- state.phase = "running";
276
- if (state.startedAt == null) state.startedAt = Number(payload.startedAt) || timestamp;
277
- break;
278
- case "task.started":
279
- if (!task) return;
280
- task.status = "running";
281
- task.startedAt = Number(payload.startedAt) || timestamp;
282
- task.endedAt = null;
283
- clearTaskFailureMetadata(task);
284
- updateSegmentForTask(state, taskId, "running");
285
- break;
286
- case "task.completed":
287
- if (!task) return;
288
- task.status = "succeeded";
289
- task.endedAt = Number(payload.endedAt) || timestamp;
290
- task.doneFileFound = payload.doneFileFound !== false;
291
- task.exitReason = String(payload.exitReason ?? "done");
292
- if ("classification" in task) delete task.classification;
293
- updateSegmentForTask(state, taskId, "succeeded");
294
- break;
295
- case "task.failed":
296
- case "task.prompt_parse_failed":
297
- if (!task) return;
298
- task.status = "failed";
299
- task.endedAt = Number(payload.endedAt) || timestamp;
300
- task.doneFileFound = false;
301
- task.exitReason = String(payload.exitReason ?? payload.reason ?? type);
302
- if (payload.classification) task.classification = String(payload.classification);
303
- updateSegmentForTask(state, taskId, "failed");
304
- break;
305
- case "task.skipped":
306
- case "task.skipped_done_on_disk":
307
- if (!task) return;
308
- task.status = "skipped";
309
- task.endedAt = Number(payload.endedAt) || timestamp;
310
- task.doneFileFound = type === "task.skipped_done_on_disk";
311
- task.exitReason = String(payload.exitReason ?? "skipped");
312
- updateSegmentForTask(state, taskId, "skipped");
313
- break;
314
- case "task.retry_requested":
315
- if (!task) return;
316
- clearTaskFailureMetadata(task);
317
- task.status = "pending";
318
- task.startedAt = null;
319
- task.endedAt = null;
320
- task.doneFileFound = false;
321
- updateSegmentForTask(state, taskId, "pending");
322
- break;
323
- case "batch.paused":
324
- state.phase = "paused";
325
- break;
326
- case "batch.completed":
327
- state.phase = "completed";
328
- state.endedAt = Number(payload.endedAt) || timestamp;
329
- break;
330
- case "batch.failed":
331
- state.phase = "failed";
332
- state.endedAt = Number(payload.endedAt) || timestamp;
333
- break;
334
- case "batch.aborted":
335
- case "batch.dismissed":
336
- state.phase = "aborted";
337
- state.endedAt = Number(payload.endedAt) || timestamp;
338
- break;
339
- default:
340
- break;
341
- }
342
- }
343
-
344
- /** Apply journal timeline to journal-derived structural state; cache seed fills non-journal fields only. */
345
- export function rebuildBatchStateFromJournal(seedState, events) {
346
- const timeline = readJournalTimeline(events);
347
- const rebuilt = deriveStructuralBatchStateFromJournal(events, seedState ?? null);
348
- mergeSeedOnlyFields(rebuilt, seedState ?? null);
349
- for (const event of timeline) applyJournalEvent(rebuilt, event);
350
- recomputeTaskCounters(rebuilt);
351
- return rebuilt;
352
- }
17
+ export {
18
+ BATCH_PHASE_EVENT_TYPES,
19
+ deriveStructuralBatchStateFromJournal,
20
+ readJournalTimeline,
21
+ readJournalTimelineFromDisk,
22
+ rebuildBatchStateFromDisk,
23
+ rebuildBatchStateFromJournal,
24
+ TASK_LIFECYCLE_EVENT_TYPES,
25
+ } from "./journal-rebuild-structural.mjs";
353
26
 
354
- export function rebuildBatchStateFromDisk(projectRoot, batchId, seedState) {
355
- return rebuildBatchStateFromJournal(seedState, readJournalEvents(projectRoot, batchId));
356
- }
27
+ import { TASK_LIFECYCLE_EVENT_TYPES } from "./journal-rebuild-structural.mjs";
357
28
 
358
29
  /** @typedef {{ taskId: string, field: string, cached: unknown, rebuilt: unknown }} DriftEntry */
359
30
 
@@ -390,6 +61,72 @@ function classifiedShowsDoneInLaneDrift(classified) {
390
61
  );
391
62
  }
392
63
 
64
+ export function normalizeTaskFolderRel(projectRoot, taskFolder) {
65
+ if (!taskFolder) return null;
66
+ if (path.isAbsolute(taskFolder)) {
67
+ return path.relative(projectRoot, taskFolder).replace(/\\/g, "/");
68
+ }
69
+ return String(taskFolder).replace(/\\/g, "/");
70
+ }
71
+
72
+ /**
73
+ * True when `.DONE` is committed on the lane task branch (fail-closed / #190).
74
+ *
75
+ * @param {string} projectRoot
76
+ * @param {string} taskBranch
77
+ * @param {string} taskFolderRel
78
+ */
79
+ export function laneDoneMarkerCommittedOnBranch(projectRoot, taskBranch, taskFolderRel) {
80
+ const folderRel = normalizeTaskFolderRel(projectRoot, taskFolderRel);
81
+ if (!projectRoot || !taskBranch || !folderRel) return false;
82
+ const donePath = `${folderRel.replace(/\/+$/, "")}/.DONE`;
83
+ try {
84
+ execFileSync("git", ["cat-file", "-e", `${taskBranch}:${donePath}`], {
85
+ cwd: projectRoot,
86
+ stdio: ["ignore", "pipe", "pipe"],
87
+ timeout: 5000,
88
+ });
89
+ return true;
90
+ } catch {
91
+ return false;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * @param {object} task
97
+ * @param {string} batchId
98
+ * @param {unknown[]} lanes
99
+ * @param {string} projectRoot
100
+ */
101
+ function laneTaskBranchForTask(task, batchId, lanes) {
102
+ const laneNumber = Number(task.laneNumber ?? 1);
103
+ const lane = Array.isArray(lanes)
104
+ ? lanes.find((entry) => Number(entry?.laneNumber) === laneNumber)
105
+ : null;
106
+ if (lane && typeof lane.branch === "string" && lane.branch) {
107
+ return lane.branch;
108
+ }
109
+ return laneTaskBranch(batchId, laneNumber);
110
+ }
111
+
112
+ /**
113
+ * Fail-closed gate: filesystem `.DONE` in lane worktree and committed on lane branch.
114
+ *
115
+ * @param {object} params
116
+ * @param {string} params.projectRoot
117
+ * @param {string} params.batchId
118
+ * @param {object} params.task
119
+ * @param {unknown[]} [params.lanes]
120
+ * @param {object|null|undefined} params.classified
121
+ */
122
+ export function laneDoneMarkerReadyForPromote({ projectRoot, batchId, task, lanes = [], classified }) {
123
+ if (classified?.doneInLane !== true) return false;
124
+ const taskFolder = normalizeTaskFolderRel(projectRoot, task?.taskFolder);
125
+ if (!taskFolder) return false;
126
+ const taskBranch = laneTaskBranchForTask(task, batchId, lanes);
127
+ return laneDoneMarkerCommittedOnBranch(projectRoot, taskBranch, taskFolder);
128
+ }
129
+
393
130
  /**
394
131
  * Detect review.started events that have no matching review.completed for the same
395
132
  * taskId + reviewType. These represent engine crashes mid-review where the artifact
@@ -634,7 +371,17 @@ export function reconcileBatchStateDrift({
634
371
 
635
372
  const classified = classifiedById.get(taskId);
636
373
  if (!classifiedShowsDoneInLaneDrift(classified)) continue;
637
- if (classified?.doneInLane !== true) continue;
374
+ if (
375
+ !laneDoneMarkerReadyForPromote({
376
+ projectRoot,
377
+ batchId,
378
+ task,
379
+ lanes: state.lanes ?? [],
380
+ classified,
381
+ })
382
+ ) {
383
+ continue;
384
+ }
638
385
  if (journalHasTaskCompleted(journalEvents, taskId)) continue;
639
386
  if (!journalShowsDoneInLaneTerminalArtifacts(journalEvents, taskId)) continue;
640
387
  if (String(task.status ?? "") === "succeeded") continue;