pi-spine 2.21.0 → 2.23.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.
@@ -1,4 +1,3 @@
1
- // @ts-nocheck
2
1
  /**
3
2
  * Shared review poll-loop mechanics for the engine lane review phases
4
3
  * (SP-727 / #262). Extracted from review.mjs so the plan, code, and final
@@ -38,12 +37,12 @@ export function removeDoneFile(taskFolder) {
38
37
  * @param {object} params
39
38
  * @param {string} params.projectRoot
40
39
  * @param {string} params.batchId
41
- * @param {object} params.task
42
- * @param {object} params.lane
40
+ * @param {Record<string, any>} params.task
41
+ * @param {Record<string, any>} params.lane
43
42
  * @param {string} params.laneCorrelationId
44
43
  * @param {"plan"|"code"|"final"} params.reviewType
45
44
  * @param {number} params.reviewAttempt
46
- * @param {object} params.honored
45
+ * @param {Record<string, any>} params.honored
47
46
  * @param {"review.crash_recovered"|"review.skipped_fresh_artifact"|null} params.honorJournalEvent
48
47
  */
49
48
  export function appendReviewHonorJournalEvents({
@@ -105,6 +104,15 @@ export function appendReviewHonorJournalEvents({
105
104
  * @param {string} params.attemptField Task state field, e.g. "codeReviewAttempts".
106
105
  * @param {string} params.attemptKey Journal payload key, e.g. "codeReviewAttempt".
107
106
  * @param {Function} params.findCompletedReview ({ taskFolder, journalEvents, taskId }) => honored|null
107
+ * @param {string} params.projectRoot
108
+ * @param {Record<string, any>} params.state
109
+ * @param {string} params.batchId
110
+ * @param {Record<string, any>} params.task
111
+ * @param {Record<string, any>} params.lane
112
+ * @param {string} params.laneCorrelationId
113
+ * @param {string} params.taskFolder
114
+ * @param {Array<Record<string, any>>} params.journalEvents
115
+ * @returns {{ ok: boolean, [key: string]: any } | null}
108
116
  */
109
117
  export function honorCompletedReview({
110
118
  reviewType,
@@ -130,7 +138,9 @@ export function honorCompletedReview({
130
138
  const honorJournalEvent = resolveReviewHonorJournalEvent({
131
139
  journalEvents,
132
140
  taskId,
133
- reviewType,
141
+ // review-artifacts.mjs predates the plan phase and still narrows the
142
+ // JSDoc to "code"|"final"; its body treats all three types alike.
143
+ reviewType: /** @type {"code"|"final"} */ (reviewType),
134
144
  honorSource: honored.source,
135
145
  reviewAttempt,
136
146
  });
@@ -178,12 +188,25 @@ export function honorCompletedReview({
178
188
  * @param {string} params.attemptField Task state field, e.g. "codeReviewAttempts".
179
189
  * @param {string} params.attemptKey Journal payload key, e.g. "codeReviewAttempt".
180
190
  * @param {number} params.maxAttempts
181
- * @param {Function} params.runEngineReview Async engine review fn (e.g. runEngineCodeReview).
191
+ * @param {(reviewParams: Record<string, any>) => any} params.runEngineReview Async engine review fn (e.g. runEngineCodeReview).
182
192
  * @param {Function} params.recordReviewTaskFailure Phase-specific failure recorder.
183
193
  * @param {string} params.invalidVerdictOutput Output message for the invalid-verdict failure.
184
194
  * @param {boolean} [params.allowReplan] Final phase only: handle REPLAN as needs_replan.
185
- * @param {Function} [params.beforeReview] Async hook per iteration; returns
195
+ * @param {((hookParams: { attempt: number }) => Promise<{ abort?: any, extraReviewParams?: Record<string, any> } | undefined>) | null} [params.beforeReview] Async hook per iteration; returns
186
196
  * { abort: result } to stop the loop or { extraReviewParams: object } to continue.
197
+ * @param {Array<Record<string, any>>} params.journalEvents
198
+ * @param {string} params.projectRoot
199
+ * @param {Record<string, any>} params.state
200
+ * @param {string} params.batchId
201
+ * @param {Record<string, any>} params.config
202
+ * @param {Record<string, any>} params.task
203
+ * @param {Record<string, any>} params.lane
204
+ * @param {string} params.taskFolderInWorktree
205
+ * @param {string} params.wt
206
+ * @param {string} params.taskBranch
207
+ * @param {string} params.laneCorrelationId
208
+ * @param {string[]} params.fileScopePaths
209
+ * @returns {Promise<{ ok: boolean, [key: string]: any }>}
187
210
  */
188
211
  export async function runReviewPollLoop({
189
212
  reviewType,
@@ -355,7 +378,7 @@ export async function runReviewPollLoop({
355
378
  }
356
379
 
357
380
  removeDoneFile(taskFolderInWorktree);
358
- const reworkResult = await runWorker({
381
+ const reworkResult = /** @type {any} */ (await runWorker({
359
382
  worktreePath: wt,
360
383
  taskFolder: taskFolderInWorktree,
361
384
  projectRoot,
@@ -376,7 +399,7 @@ export async function runReviewPollLoop({
376
399
  saveSpineBatchState(projectRoot, state);
377
400
  }
378
401
  },
379
- });
402
+ }));
380
403
  if (!reworkResult.ok) {
381
404
  const aborted = reworkResult.classification === "aborted";
382
405
  task.status = aborted ? "aborted" : "failed";
@@ -1,4 +1,3 @@
1
- // @ts-nocheck
2
1
  /**
3
2
  * Engine lane review stub verdict queues (SP-728 / #262).
4
3
  *
@@ -69,7 +68,7 @@ export function createStubVerdictQueue({ queueValue, singleValue, normalize, def
69
68
  * @param {string} params.singleEnv Env var holding the single-verdict fallback.
70
69
  * @param {(raw: string) => string|null} params.normalize Verdict normalizer.
71
70
  * @param {string} params.defaultVerdict Fallback when nothing else resolves.
72
- * @param {NodeJS.ProcessEnv} [env]
71
+ * @param {NodeJS.ProcessEnv} [params.env]
73
72
  */
74
73
  export function createStubVerdictQueueFromEnv({
75
74
  queueEnv,
@@ -1,4 +1,3 @@
1
- // @ts-nocheck
2
1
  /**
3
2
  * Engine lane review-phase coordinator — re-exports phase modules (SP-729/730 / #262).
4
3
  */
@@ -1,4 +1,3 @@
1
- // @ts-nocheck
2
1
  /**
3
2
  * Lane task execution facade — re-exports split modules and phase transitions.
4
3
  *
@@ -90,6 +89,22 @@ export { runMatrixTaskOnLane, runMatrixSubLane } from "./engine-lanes/matrix-run
90
89
 
91
90
  export { transitionPhase } from "./engine-lanes/phase.mjs";
92
91
 
92
+ /**
93
+ * Run one task on its lane: file-scope load, matrix fan-out, or the single
94
+ * worker path (SP-770 typing).
95
+ *
96
+ * @param {object} params
97
+ * @param {string} params.projectRoot
98
+ * @param {Record<string, any>} params.state
99
+ * @param {string} params.batchId
100
+ * @param {string} [params.baseBranch]
101
+ * @param {Record<string, any>} params.config
102
+ * @param {Record<string, any>} params.task
103
+ * @param {Record<string, any>} params.lane
104
+ * @param {string} params.taskFolderRel
105
+ * @param {string} params.laneCorrelationId
106
+ * @returns {Promise<{ ok: boolean, [key: string]: any }>}
107
+ */
93
108
  export async function runTaskOnLane({
94
109
  projectRoot,
95
110
  state,
@@ -125,7 +140,8 @@ export async function runTaskOnLane({
125
140
  // global in-flight workers never exceed `lanes.maxParallel`.
126
141
  const matrixRows = loadMatrixTaskRows(path.join(projectRoot, taskFolderRel));
127
142
  if (matrixRows) {
128
- return runMatrixTaskOnLane({
143
+ /** @type {{ maxParallel: number } & Record<string, any>} */
144
+ const matrixParams = {
129
145
  projectRoot,
130
146
  state,
131
147
  batchId,
@@ -138,7 +154,8 @@ export async function runTaskOnLane({
138
154
  fileScopePaths,
139
155
  matrix: matrixRows,
140
156
  maxParallel: config?.lanes?.maxParallel ?? 1,
141
- });
157
+ };
158
+ return runMatrixTaskOnLane(matrixParams);
142
159
  }
143
160
 
144
161
  const laneSlot = await acquireLaneSlot(state, config?.lanes?.maxParallel ?? 1);
@@ -165,6 +182,17 @@ export async function runTaskOnLane({
165
182
  * for the duration of this call.
166
183
  *
167
184
  * @param {object} params
185
+ * @param {string} params.projectRoot
186
+ * @param {Record<string, any>} params.state
187
+ * @param {string} params.batchId
188
+ * @param {string} [params.baseBranch]
189
+ * @param {Record<string, any>} params.config
190
+ * @param {Record<string, any>} params.task
191
+ * @param {Record<string, any>} params.lane
192
+ * @param {string} params.taskFolderRel
193
+ * @param {string} params.laneCorrelationId
194
+ * @param {string[]} params.fileScopePaths
195
+ * @returns {Promise<{ ok: boolean, [key: string]: any }>}
168
196
  */
169
197
  async function runNonMatrixTaskOnLane({
170
198
  projectRoot,
@@ -256,7 +284,7 @@ async function runNonMatrixTaskOnLane({
256
284
  correlationId: laneCorrelationId,
257
285
  });
258
286
 
259
- const workerResult = await runWorker({
287
+ const workerResult = /** @type {any} */ (await runWorker({
260
288
  worktreePath: wt,
261
289
  taskFolder: taskFolderInWorktree,
262
290
  projectRoot,
@@ -277,7 +305,7 @@ async function runNonMatrixTaskOnLane({
277
305
  saveEngineBatchState(projectRoot, state);
278
306
  }
279
307
  },
280
- });
308
+ }));
281
309
 
282
310
  if (!workerResult.ok) {
283
311
  const doneOnDisk = fs.existsSync(path.join(taskFolderInWorktree, ".DONE"));
@@ -30,12 +30,15 @@ export const ALLOWED_EVIDENCE_EXECUTABLES = new Set([
30
30
  "npx",
31
31
  "cargo",
32
32
  "task",
33
+ "python3",
33
34
  ]);
34
35
 
35
36
  /**
36
- * Interpreter basenames allowed only as project-local relative paths under
37
+ * Interpreter basenames allowed as project-local relative paths under
37
38
  * `.venv/` or `venv/` (see {@link isAllowedProjectLocalInterpreter}).
38
- * Bare names (PATH lookup) and absolute/outside-project paths stay rejected.
39
+ * Within that venv rule, bare names (PATH lookup) and absolute/outside-project
40
+ * paths stay rejected. Bare `python3` PATH lookup is separately allowed for
41
+ * evidence via {@link ALLOWED_EVIDENCE_EXECUTABLES}; bare `python` is not.
39
42
  * @type {Set<string>}
40
43
  */
41
44
  export const ALLOWED_PROJECT_LOCAL_INTERPRETERS = new Set(["python", "python3"]);
@@ -60,9 +60,19 @@ function taskIdsOf(value) {
60
60
  return value.map((entry) => String(entry ?? "").trim()).filter(Boolean);
61
61
  }
62
62
 
63
+ /** Finite positive laneNumber, or null when the value is missing/garbage (#287). */
64
+ function finiteLaneNumber(value) {
65
+ const n = Number(value);
66
+ return Number.isFinite(n) && n > 0 ? n : null;
67
+ }
68
+
63
69
  function taskStub(map, taskId, hints = {}) {
64
70
  const row = map.get(taskId) ?? { taskId };
65
- if (hints.laneNumber != null) row.laneNumber = Number(hints.laneNumber) || row.laneNumber || 1;
71
+ // Only an explicit finite laneNumber from an event may assign a lane. Garbage
72
+ // hints (NaN/0) must not default the row to lane 1 — that defaulted value
73
+ // would shadow the seed's correct lane in finalizeTasks (#287).
74
+ const hintedLane = finiteLaneNumber(hints.laneNumber);
75
+ if (hintedLane != null) row.laneNumber = hintedLane;
66
76
  if (typeof hints.taskFolder === "string" && hints.taskFolder) row.taskFolder = hints.taskFolder;
67
77
  map.set(taskId, row);
68
78
  return row;
@@ -85,7 +95,8 @@ function finalizeTasks(tasksById, seedTasks) {
85
95
  const seed = seedById.get(taskId);
86
96
  return {
87
97
  taskId,
88
- laneNumber: Number(derived.laneNumber ?? seed?.laneNumber ?? 1) || 1,
98
+ // Journal-provided lane wins; seed fills the gap; 1 is the last resort (#287).
99
+ laneNumber: finiteLaneNumber(derived.laneNumber) ?? finiteLaneNumber(seed?.laneNumber) ?? 1,
89
100
  status: "pending",
90
101
  taskFolder: derived.taskFolder ?? seed?.taskFolder ?? null,
91
102
  sessionName: seed?.sessionName,
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Diagnosis enrichment helpers for reconcile.
3
+ * Extracted from reconcile-diagnosis.mjs to stay under the Phase 23 500 LOC cap.
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import { inferLaunchFailureFromWorkerOutputTail } from "./diagnosis.mjs";
8
+ import { workerOutputLogPath, workerOutputLogRef } from "./worker-output.mjs";
9
+
10
+ const WORKER_OUTPUT_TAIL_LINES = 20;
11
+
12
+ /**
13
+ * @typedef {{
14
+ * taskId: string,
15
+ * laneNumber?: number|null,
16
+ * classification?: string,
17
+ * }} DiagnosisTaskRow
18
+ */
19
+
20
+ /**
21
+ * @typedef {{
22
+ * workerOutputLogRef?: string|null,
23
+ * workerOutputLogPath?: string|null,
24
+ * output?: string|null,
25
+ * changedFileCount?: number|null,
26
+ * }} DoneMissingHint
27
+ */
28
+
29
+ /**
30
+ * @typedef {{
31
+ * type?: string,
32
+ * taskId?: string,
33
+ * payload?: {
34
+ * taskId?: string,
35
+ * gitignoredPaths?: unknown,
36
+ * },
37
+ * }} JournalEventLike
38
+ */
39
+
40
+ /**
41
+ * @param {string} filePath
42
+ * @param {number} [lineCount]
43
+ * @returns {string|null}
44
+ */
45
+ function readWorkerOutputLogTail(filePath, lineCount = WORKER_OUTPUT_TAIL_LINES) {
46
+ if (!fs.existsSync(filePath)) return null;
47
+ const content = fs.readFileSync(filePath, "utf-8");
48
+ const lines = content.split("\n");
49
+ if (lines.at(-1) === "") lines.pop();
50
+ if (lines.length === 0) return null;
51
+ return lines.slice(-lineCount).join("\n");
52
+ }
53
+
54
+ /**
55
+ * @param {string} projectRoot
56
+ * @param {string} batchId
57
+ * @param {string|null} failedTaskId
58
+ * @param {DiagnosisTaskRow[]} tasks
59
+ * @param {string|null} launchFailureKind
60
+ * @returns {string|null}
61
+ */
62
+ export function enrichLaunchFailureFromWorkerOutput(projectRoot, batchId, failedTaskId, tasks, launchFailureKind) {
63
+ if (launchFailureKind || !failedTaskId || !batchId) return launchFailureKind;
64
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
65
+ if (!task || task.laneNumber == null) return launchFailureKind;
66
+ const logPath = workerOutputLogPath(projectRoot, batchId, task.laneNumber, failedTaskId);
67
+ const tail = readWorkerOutputLogTail(logPath);
68
+ return inferLaunchFailureFromWorkerOutputTail(tail) ?? launchFailureKind;
69
+ }
70
+
71
+ /**
72
+ * @param {string} projectRoot
73
+ * @param {string} batchId
74
+ * @param {string|null} failedTaskId
75
+ * @param {DiagnosisTaskRow[]} tasks
76
+ * @param {DoneMissingHint|null|undefined} doneMissingHint
77
+ * @returns {{ workerOutputLogRef: string|null, workerOutputLogPath: string|null, workerOutputTail: string|null, workerOutputSnippet: string|null, changedFileCount: number|null }}
78
+ */
79
+ export function enrichWorkerDoneMissingContext(
80
+ projectRoot,
81
+ batchId,
82
+ failedTaskId,
83
+ tasks,
84
+ doneMissingHint,
85
+ ) {
86
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
87
+ const laneNumber = task?.laneNumber;
88
+ const logRef =
89
+ doneMissingHint?.workerOutputLogRef ??
90
+ (failedTaskId && laneNumber != null
91
+ ? workerOutputLogRef(batchId, laneNumber, failedTaskId)
92
+ : null);
93
+ const logPath =
94
+ doneMissingHint?.workerOutputLogPath ??
95
+ (failedTaskId && laneNumber != null
96
+ ? workerOutputLogPath(projectRoot, batchId, laneNumber, failedTaskId)
97
+ : null);
98
+ const tailFromDisk = logPath ? readWorkerOutputLogTail(logPath) : null;
99
+ const outputText = [doneMissingHint?.output, tailFromDisk].filter(Boolean).join("\n");
100
+ const snippet = outputText
101
+ ? outputText
102
+ .split("\n")
103
+ .filter(Boolean)
104
+ .slice(-3)
105
+ .join(" | ")
106
+ : null;
107
+
108
+ return {
109
+ workerOutputLogRef: logRef,
110
+ workerOutputLogPath: logPath,
111
+ workerOutputTail: tailFromDisk,
112
+ workerOutputSnippet: snippet,
113
+ changedFileCount:
114
+ doneMissingHint?.changedFileCount != null ? doneMissingHint.changedFileCount : null,
115
+ };
116
+ }
117
+
118
+ /**
119
+ * @param {DiagnosisTaskRow[]} tasks
120
+ * @param {string|null} failedTaskId
121
+ * @returns {boolean}
122
+ */
123
+ export function hasGhostRunningCluster(tasks, failedTaskId) {
124
+ if (!failedTaskId) return false;
125
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
126
+ if (!task || task.laneNumber == null) return false;
127
+ const laneNumber = Number(task.laneNumber);
128
+ return (
129
+ tasks.filter(
130
+ (entry) =>
131
+ entry.classification === "running" && Number(entry.laneNumber) === laneNumber,
132
+ ).length > 1
133
+ );
134
+ }
135
+
136
+ /**
137
+ * @param {JournalEventLike[]} journalEvents
138
+ * @param {string|null} failedTaskId
139
+ * @returns {string[]}
140
+ */
141
+ export function extractGitignoredPathsFromJournal(journalEvents, failedTaskId) {
142
+ if (!Array.isArray(journalEvents)) return [];
143
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
144
+ const event = journalEvents[index];
145
+ if (event.type !== "task.failed") continue;
146
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
147
+ if (failedTaskId && eventTaskId && eventTaskId !== failedTaskId) continue;
148
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
149
+ if (Array.isArray(payload.gitignoredPaths)) {
150
+ return payload.gitignoredPaths.filter((entry) => typeof entry === "string");
151
+ }
152
+ }
153
+ return [];
154
+ }
155
+
156
+ /**
157
+ * @param {Record<string, unknown>|null|undefined} raw
158
+ * @param {string} batchId
159
+ * @param {string} taskId
160
+ * @returns {string|null}
161
+ */
162
+ export function laneTaskBranchForDiagnosis(raw, batchId, taskId) {
163
+ const tasks = raw?.tasks;
164
+ if (!Array.isArray(tasks)) return null;
165
+ const task = /** @type {DiagnosisTaskRow|undefined} */ (
166
+ tasks.find((entry) => {
167
+ if (!entry || typeof entry !== "object") return false;
168
+ return /** @type {{ taskId?: unknown }} */ (entry).taskId === taskId;
169
+ })
170
+ );
171
+ if (!task || task.laneNumber == null) return null;
172
+ return `task/spine-lane-${task.laneNumber}-${batchId}`;
173
+ }
@@ -1,21 +1,26 @@
1
1
  // @ts-nocheck
2
2
  /** Diagnosis derivation (SP-596/SP-606 / #192). */
3
3
 
4
- import fs from "node:fs";
5
- import { inferLaunchFailureFromWorkerOutputTail, inferLaunchFailureKind } from "./diagnosis.mjs";
4
+ import { inferLaunchFailureKind } from "./diagnosis.mjs";
6
5
  import {
7
6
  findPendingLaneLandTasks,
8
7
  shouldDiagnosePendingLaneLand,
9
8
  } from "./diagnosis-pending-lane.mjs";
10
9
  import { inferWorkerDoneMissingFailure } from "./diagnosis-worker-done-missing.mjs";
11
10
  import { inferStubExitReasonForTask } from "./diagnosis-stub.mjs";
12
- import { workerOutputLogPath, workerOutputLogRef } from "./worker-output.mjs";
13
11
  import { isPostMergeLimbo } from "./limbo-detect.mjs";
14
12
  import {
15
13
  LIMBO_PHASES,
16
14
  RUNNING_PHASES,
17
15
  } from "./reconcile-light-cache.mjs";
18
16
  export { buildReconcileDiagnosisContext } from "./reconcile-diagnosis-context.mjs";
17
+ export {
18
+ enrichLaunchFailureFromWorkerOutput,
19
+ enrichWorkerDoneMissingContext,
20
+ extractGitignoredPathsFromJournal,
21
+ hasGhostRunningCluster,
22
+ laneTaskBranchForDiagnosis,
23
+ } from "./reconcile-diagnosis-enrich.mjs";
19
24
 
20
25
  /**
21
26
  * @param {unknown} rawTasks
@@ -92,138 +97,6 @@ function deriveFailureContext(failedTaskId, exitReason, signals) {
92
97
  return { exitReason: resolvedExitReason, launchFailureKind };
93
98
  }
94
99
 
95
- const WORKER_OUTPUT_TAIL_LINES = 20;
96
-
97
- /**
98
- * @param {string} filePath
99
- * @param {number} [lineCount]
100
- * @returns {string|null}
101
- */
102
- function readWorkerOutputLogTail(filePath, lineCount = WORKER_OUTPUT_TAIL_LINES) {
103
- if (!fs.existsSync(filePath)) return null;
104
- const content = fs.readFileSync(filePath, "utf-8");
105
- const lines = content.split("\n");
106
- if (lines.at(-1) === "") lines.pop();
107
- if (lines.length === 0) return null;
108
- return lines.slice(-lineCount).join("\n");
109
- }
110
-
111
- /**
112
- * @param {string} projectRoot
113
- * @param {string} batchId
114
- * @param {string|null} failedTaskId
115
- * @param {Array<{ taskId: string, laneNumber?: number|null }>} tasks
116
- * @param {string|null} launchFailureKind
117
- * @returns {string|null}
118
- */
119
- export function enrichLaunchFailureFromWorkerOutput(projectRoot, batchId, failedTaskId, tasks, launchFailureKind) {
120
- if (launchFailureKind || !failedTaskId || !batchId) return launchFailureKind;
121
- const task = tasks.find((entry) => entry.taskId === failedTaskId);
122
- if (!task || task.laneNumber == null) return launchFailureKind;
123
- const logPath = workerOutputLogPath(projectRoot, batchId, task.laneNumber, failedTaskId);
124
- const tail = readWorkerOutputLogTail(logPath);
125
- return inferLaunchFailureFromWorkerOutputTail(tail) ?? launchFailureKind;
126
- }
127
-
128
- /**
129
- * @param {string} projectRoot
130
- * @param {string} batchId
131
- * @param {string|null} failedTaskId
132
- * @param {Array<{ taskId: string, laneNumber?: number|null }>} tasks
133
- * @param {object|null} doneMissingHint
134
- * @returns {{ workerOutputLogRef: string|null, workerOutputLogPath: string|null, workerOutputTail: string|null, workerOutputSnippet: string|null, changedFileCount: number|null }}
135
- */
136
- export function enrichWorkerDoneMissingContext(
137
- projectRoot,
138
- batchId,
139
- failedTaskId,
140
- tasks,
141
- doneMissingHint,
142
- ) {
143
- const task = tasks.find((entry) => entry.taskId === failedTaskId);
144
- const laneNumber = task?.laneNumber;
145
- const logRef =
146
- doneMissingHint?.workerOutputLogRef ??
147
- (failedTaskId && laneNumber != null
148
- ? workerOutputLogRef(batchId, laneNumber, failedTaskId)
149
- : null);
150
- const logPath =
151
- doneMissingHint?.workerOutputLogPath ??
152
- (failedTaskId && laneNumber != null
153
- ? workerOutputLogPath(projectRoot, batchId, laneNumber, failedTaskId)
154
- : null);
155
- const tailFromDisk = logPath ? readWorkerOutputLogTail(logPath) : null;
156
- const outputText = [doneMissingHint?.output, tailFromDisk].filter(Boolean).join("\n");
157
- const snippet = outputText
158
- ? outputText
159
- .split("\n")
160
- .filter(Boolean)
161
- .slice(-3)
162
- .join(" | ")
163
- : null;
164
-
165
- return {
166
- workerOutputLogRef: logRef,
167
- workerOutputLogPath: logPath,
168
- workerOutputTail: tailFromDisk,
169
- workerOutputSnippet: snippet,
170
- changedFileCount:
171
- doneMissingHint?.changedFileCount != null ? doneMissingHint.changedFileCount : null,
172
- };
173
- }
174
-
175
- /**
176
- * @param {Array<{ taskId: string, classification: string, laneNumber?: number|null }>} tasks
177
- * @param {string|null} failedTaskId
178
- * @returns {boolean}
179
- */
180
- export function hasGhostRunningCluster(tasks, failedTaskId) {
181
- if (!failedTaskId) return false;
182
- const task = tasks.find((entry) => entry.taskId === failedTaskId);
183
- if (!task || task.laneNumber == null) return false;
184
- const laneNumber = Number(task.laneNumber);
185
- return (
186
- tasks.filter(
187
- (entry) =>
188
- entry.classification === "running" && Number(entry.laneNumber) === laneNumber,
189
- ).length > 1
190
- );
191
- }
192
-
193
- /**
194
- * @param {object[]} journalEvents
195
- * @param {string|null} failedTaskId
196
- * @returns {string[]}
197
- */
198
- export function extractGitignoredPathsFromJournal(journalEvents, failedTaskId) {
199
- if (!Array.isArray(journalEvents)) return [];
200
- for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
201
- const event = journalEvents[index];
202
- if (event.type !== "task.failed") continue;
203
- const eventTaskId = event.taskId ?? event.payload?.taskId;
204
- if (failedTaskId && eventTaskId && eventTaskId !== failedTaskId) continue;
205
- const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
206
- if (Array.isArray(payload.gitignoredPaths)) {
207
- return payload.gitignoredPaths.filter((entry) => typeof entry === "string");
208
- }
209
- }
210
- return [];
211
- }
212
-
213
- /**
214
- * @param {Record<string, unknown>|null|undefined} raw
215
- * @param {string} batchId
216
- * @param {string} taskId
217
- * @returns {string|null}
218
- */
219
- export function laneTaskBranchForDiagnosis(raw, batchId, taskId) {
220
- const tasks = raw?.tasks;
221
- if (!Array.isArray(tasks)) return null;
222
- const task = tasks.find((entry) => entry?.taskId === taskId);
223
- if (!task || task.laneNumber == null) return null;
224
- return `task/spine-lane-${task.laneNumber}-${batchId}`;
225
- }
226
-
227
100
  /**
228
101
  * @param {string} diagnosis
229
102
  * @param {string|null} failedTaskId
@@ -262,6 +135,50 @@ function hasNeedsReplanBlocker(signals) {
262
135
  return tasks.some((task) => task?.exitReason === "needs_replan");
263
136
  }
264
137
 
138
+ /**
139
+ * Plan-review exit reasons where reviewer infrastructure failed after the
140
+ * worker had already completed its lane work (#291 / SP-762). Mirrors the
141
+ * SP-718 final-review distinction: spawn failure / timeout mean no verdict
142
+ * was produced — the implementation itself is not the failure.
143
+ */
144
+ const POST_DONE_PLAN_REVIEW_EXIT_REASONS = new Set([
145
+ "plan_review_spawn_failed",
146
+ "plan_review_timeout",
147
+ ]);
148
+
149
+ /**
150
+ * Failed task whose lane work already completed (done evidence / `.DONE` in
151
+ * the lane worktree) but whose engine plan review failed to spawn or timed
152
+ * out. Such tasks are salvageable land-loop candidates — a full worker retry
153
+ * would re-run expensive work that is already on disk (#291 / SP-762).
154
+ *
155
+ * Parsed batch-state tasks drop `exitReason` (normalizeTasks), so the exit
156
+ * reason is resolved the same way deriveFailureContext resolves it: from the
157
+ * task entry when present, else raw state / journal `task.failed` events.
158
+ * The salvage command itself hard-gates on commits-ahead, so pointing at it
159
+ * without lane commits is safe (dry-run reports none salvageable).
160
+ *
161
+ * @param {object} signals
162
+ * @returns {object|null}
163
+ */
164
+ function findPostDonePlanReviewSpawnFailedTask(signals) {
165
+ const tasks = Array.isArray(signals.tasks) ? signals.tasks : [];
166
+ for (const task of tasks) {
167
+ if (String(task?.status ?? "").toLowerCase() !== "failed") continue;
168
+ const hasDoneEvidence =
169
+ task?.doneInLane === true ||
170
+ task?.doneOnMain === true ||
171
+ task?.doneFileFound === true ||
172
+ String(task?.classification ?? "").toLowerCase() === "terminal-success";
173
+ if (!hasDoneEvidence) continue;
174
+ const taskId = String(task?.taskId ?? "");
175
+ const exitReason = task?.exitReason ?? resolvePrimaryFailureExitReason(taskId, signals);
176
+ if (!POST_DONE_PLAN_REVIEW_EXIT_REASONS.has(String(exitReason ?? ""))) continue;
177
+ return task;
178
+ }
179
+ return null;
180
+ }
181
+
265
182
  /**
266
183
  * @param {object} signals
267
184
  */
@@ -362,6 +279,17 @@ export function deriveDiagnosis(signals) {
362
279
  if (doneMissing) {
363
280
  return withFailureContext("worker_done_missing", failedTaskId, signals);
364
281
  }
282
+ // Post-DONE plan-review spawn failure: lane work is complete, so map to
283
+ // pending_lane_land (salvage / land-loop guidance) instead of needs_retry,
284
+ // whose retry language would force an expensive worker re-run (#291 / SP-762).
285
+ const postDonePlanReviewTask = findPostDonePlanReviewSpawnFailedTask(signals);
286
+ if (postDonePlanReviewTask) {
287
+ return withFailureContext(
288
+ "pending_lane_land",
289
+ postDonePlanReviewTask.taskId ?? failedTaskId,
290
+ signals,
291
+ );
292
+ }
365
293
  return withFailureContext("needs_retry", failedTaskId, signals);
366
294
  }
367
295