pi-spine 2.21.0 → 2.22.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.
package/README.md CHANGED
@@ -49,7 +49,7 @@ Primary monitor surfaces: **`spine status --diagnose`**, **`spine dashboard`** /
49
49
  | [pi](https://pi.dev) coding agent | ≥ 0.80.0 (`pi.minPiVersion`) | Yes |
50
50
  | Git (worktree support) | — | Yes |
51
51
 
52
- These are the Wave A floors ([#285](https://github.com/beettlle/pi-spine/issues/285)). `spine doctor` **warns** when the installed pi is below `pi.minPiVersion` ("pi version supported"). The optional peer `@earendil-works/pi-coding-agent` is developed and tested against `^0.85.1` (pinned in `devDependencies`; the `peerDependencies` range stays `*`).
52
+ These are the Wave A floors ([#285](https://github.com/beettlle/pi-spine/issues/285)). `spine doctor` **warns** when the installed pi is below `pi.minPiVersion` ("pi version supported"). The optional peer `@earendil-works/pi-coding-agent` is developed and tested against `^0.87.0` (pinned in `devDependencies`; the `peerDependencies` range stays `*`).
53
53
 
54
54
  ## Install
55
55
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.21.0",
3
+ "version": "2.22.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -72,7 +72,7 @@
72
72
  }
73
73
  },
74
74
  "devDependencies": {
75
- "@earendil-works/pi-coding-agent": "^0.85.1",
75
+ "@earendil-works/pi-coding-agent": "^0.87.0",
76
76
  "@types/node": "^22.19.18",
77
77
  "eslint": "^10.10.0",
78
78
  "globals": "^17.12.0",
@@ -57,6 +57,39 @@ export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
57
57
  return null;
58
58
  }
59
59
 
60
+ // Keep the hint readable; the gitignored merge repair command uses the same cap (#288).
61
+ const DIRTY_WORKTREE_PATH_HINT_LIMIT = 5;
62
+
63
+ /**
64
+ * DirtyWorktree remediation hint built from the actual dirty set (#288).
65
+ * Prefers concrete dirty paths from the failure payload / lane dirty-check;
66
+ * falls back to a generic status inspection plus retry when paths are unknown.
67
+ * Never hardcodes coverage paths — they appear only when present in the dirty set.
68
+ *
69
+ * @param {object} ctx
70
+ * @param {string|null} [ctx.failedTaskId]
71
+ * @param {string[]|null} [ctx.dirtyPaths]
72
+ * @param {string|null} [ctx.laneWorktree]
73
+ * @returns {string}
74
+ */
75
+ export function buildDirtyWorktreeSuggestedCommand(ctx = {}) {
76
+ const dirtyPaths = (Array.isArray(ctx.dirtyPaths) ? ctx.dirtyPaths : []).filter(
77
+ (entry) => typeof entry === "string" && entry.trim().length > 0,
78
+ );
79
+ const retryHint = ctx.failedTaskId
80
+ ? `spine batch retry ${ctx.failedTaskId}`
81
+ : "spine batch retry";
82
+ if (dirtyPaths.length > 0) {
83
+ const pathHint = dirtyPaths.slice(0, DIRTY_WORKTREE_PATH_HINT_LIMIT).join(" ");
84
+ return `git checkout -- ${pathHint} && ${retryHint}`;
85
+ }
86
+ const worktreeHint =
87
+ typeof ctx.laneWorktree === "string" && ctx.laneWorktree.trim().length > 0
88
+ ? ctx.laneWorktree
89
+ : "<laneWorktree>";
90
+ return `git -C ${worktreeHint} status --porcelain && ${retryHint}`;
91
+ }
92
+
60
93
  /**
61
94
  * @param {object} ctx
62
95
  * @param {string|null} [ctx.exitReason]
@@ -66,9 +99,7 @@ export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
66
99
  export function buildPrimaryFailureSuggestedCommand(ctx = {}) {
67
100
  if (LANE_COMMIT_EXIT_REASONS.has(ctx.exitReason ?? "")) {
68
101
  if (ctx.exitReason === "DirtyWorktree") {
69
- return ctx.failedTaskId
70
- ? `git checkout -- extension/coverage && spine batch retry ${ctx.failedTaskId}`
71
- : "git checkout -- extension/coverage && spine batch retry";
102
+ return buildDirtyWorktreeSuggestedCommand(ctx);
72
103
  }
73
104
  return ctx.failedTaskId
74
105
  ? `spine batch retry ${ctx.failedTaskId}`
@@ -32,6 +32,8 @@ import { buildPendingLaneLandSuggestedCommand } from "./diagnosis-pending-lane.m
32
32
  * @param {boolean} [ctx.mergeFailed]
33
33
  * @param {string|null} [ctx.taskBranch]
34
34
  * @param {string[]|null} [ctx.gitignoredPaths]
35
+ * @param {string[]|null} [ctx.dirtyPaths]
36
+ * @param {string|null} [ctx.laneWorktree]
35
37
  * @param {object[]} [ctx.pendingLaneLandTasks]
36
38
  */
37
39
  export function buildSuggestedCommand(diagnosis, ctx = {}) {
@@ -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
 
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Heal failed-task gates after a successful salvage integrate (#292 / SP-763).
3
+ *
4
+ * When `spine batch salvage --lane N --integrate` lands lane work on the base
5
+ * branch, the active batch state still records the salvaged tasks as failed
6
+ * (status "failed", failed segment, failedTasks counter), so
7
+ * `spine batch complete` keeps refusing (`needs_retry` / `pending_lane_land`)
8
+ * and operators are forced to `dismiss --force`. Once the land succeeded there
9
+ * is no unresolved failure left for those tasks, so the failed-task gate is
10
+ * healed here: each salvageable task is promoted with `recordTaskSucceeded`
11
+ * (task status, segments, and succeeded/failed counters in one step) and a
12
+ * reconciled `task.completed` journal event keeps journal-derived rebuilds in
13
+ * agreement — the same promotion `reconcileBatchStateDrift` applies on
14
+ * done-in-lane terminal evidence.
15
+ *
16
+ * Tasks outside the salvage set are never touched: non-salvageable failures
17
+ * (contract/review failures) and evidence-less worker deaths remain failed and
18
+ * keep blocking complete (SP-763 completion criteria).
19
+ */
20
+
21
+ import { loadBatchStateFile } from "./batch-state-io.mjs";
22
+ import { appendJournalEvent } from "./journal.mjs";
23
+ import { recordTaskSucceeded, saveSpineBatchState } from "./state.mjs";
24
+
25
+ /**
26
+ * Heal the failed-task gate for a lane a salvage integrate just landed, and
27
+ * journal `batch.salvage_heal_failed` when the heal itself fails without
28
+ * failing the integrate — the merge has already landed (#292 / SP-763).
29
+ *
30
+ * @param {string} projectRoot
31
+ * @param {string} batchId
32
+ * @param {object} lane
33
+ * @param {string|null} mergeCommit
34
+ * @returns {{ ok: boolean, healedTaskIds: string[], healError: string|null }}
35
+ */
36
+ export function healAfterSalvageLand(projectRoot, batchId, lane, mergeCommit) {
37
+ const heal = healSalvagedTasksAfterIntegrate(projectRoot, batchId, {
38
+ salvageableTasks: lane.salvageableTasks ?? [],
39
+ mergeCommit,
40
+ });
41
+ if (!heal.ok) {
42
+ appendJournalEvent(projectRoot, batchId, "batch.salvage_heal_failed", {
43
+ laneNumber: lane.laneNumber ?? null,
44
+ salvageableTasks: lane.salvageableTasks ?? [],
45
+ reason: heal.reason,
46
+ error: heal.error,
47
+ });
48
+ }
49
+ return { ok: heal.ok, healedTaskIds: heal.healedTaskIds, healError: heal.ok ? null : heal.error };
50
+ }
51
+
52
+ /**
53
+ * Heal the failed-task gate for tasks whose lane work a salvage integrate just
54
+ * landed on the base branch. Never throws into the salvage path: the merge has
55
+ * already landed, so a heal problem is reported as a result, not a command
56
+ * failure.
57
+ *
58
+ * @param {string} projectRoot
59
+ * @param {string} batchId
60
+ * @param {object} [options]
61
+ * @param {string[]} [options.salvageableTasks] Task ids the salvage landed.
62
+ * @param {string|null} [options.mergeCommit] Salvage merge commit, when known.
63
+ * @returns {{ ok: boolean, healedTaskIds: string[], reason: string|null, error: string|null }}
64
+ */
65
+ export function healSalvagedTasksAfterIntegrate(projectRoot, batchId, options = {}) {
66
+ const salvageableTasks = (options.salvageableTasks ?? []).map((taskId) => String(taskId ?? "")).filter(Boolean);
67
+ const mergeCommit = options.mergeCommit ?? null;
68
+ if (salvageableTasks.length === 0) {
69
+ return { ok: true, healedTaskIds: [], reason: "no_salvageable_tasks", error: null };
70
+ }
71
+
72
+ try {
73
+ const loaded = loadBatchStateFile(projectRoot);
74
+ // Salvage also runs against archived batches; without an active state
75
+ // there is no gate to heal and `complete` is not applicable anyway.
76
+ if (!loaded.path || !loaded.raw) {
77
+ return { ok: true, healedTaskIds: [], reason: "no_active_batch_state", error: null };
78
+ }
79
+ if (loaded.parseError) {
80
+ return { ok: false, healedTaskIds: [], reason: "batch_state_unreadable", error: loaded.parseError };
81
+ }
82
+ const stateBatchId = String(loaded.raw.batchId ?? loaded.raw.id ?? "");
83
+ if (stateBatchId !== batchId) {
84
+ return { ok: true, healedTaskIds: [], reason: "batch_id_mismatch", error: null };
85
+ }
86
+
87
+ const healedTaskIds = [];
88
+ for (const taskId of salvageableTasks) {
89
+ const task = (loaded.raw.tasks ?? []).find(
90
+ (entry) => entry && typeof entry === "object" && entry.taskId === taskId,
91
+ );
92
+ if (!task) continue;
93
+ const status = String(task.status ?? "").toLowerCase();
94
+ if (status === "succeeded" || status === "skipped") continue;
95
+ if (!recordTaskSucceeded(loaded.raw, taskId, { exitReason: "done", doneFileFound: true })) continue;
96
+ healedTaskIds.push(taskId);
97
+ appendJournalEvent(projectRoot, batchId, "task.completed", {
98
+ taskId,
99
+ laneNumber: task.laneNumber ?? null,
100
+ reconciled: true,
101
+ reconcileReason: "salvage_integrated",
102
+ mergeCommit,
103
+ });
104
+ }
105
+
106
+ if (healedTaskIds.length === 0) {
107
+ return { ok: true, healedTaskIds, reason: "nothing_to_heal", error: null };
108
+ }
109
+
110
+ saveSpineBatchState(projectRoot, loaded.raw);
111
+ return { ok: true, healedTaskIds, reason: null, error: null };
112
+ } catch (err) {
113
+ const message = err instanceof Error ? err.message : String(err);
114
+ return { ok: false, healedTaskIds: [], reason: "heal_threw", error: message };
115
+ }
116
+ }
@@ -16,6 +16,7 @@ import {
16
16
  gateBlockedOnMissingGate,
17
17
  openGateFromSalvageEvidence,
18
18
  } from "./salvage-batch-integrate-gate.mjs";
19
+ import { healAfterSalvageLand } from "./salvage-batch-integrate-heal.mjs";
19
20
  import { laneTaskBranch } from "./worktree.mjs";
20
21
  import { listSalvageableLanes } from "./salvage-batch-list.mjs";
21
22
 
@@ -141,10 +142,15 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
141
142
  }
142
143
 
143
144
  if (commitsAhead <= 0) {
145
+ // Lane work is already fully merged (manual land or re-run) — heal the
146
+ // failed-task gate on the same landed-work evidence (#292 / SP-763).
147
+ const heal = healAfterSalvageLand(projectRoot, resolvedBatchId, lane, null);
144
148
  return {
145
149
  ok: true,
146
150
  exitCode: 0,
147
151
  alreadyMerged: true,
152
+ healedTaskIds: heal.healedTaskIds,
153
+ healError: heal.healError,
148
154
  batchId: resolvedBatchId,
149
155
  laneNumber: laneNum,
150
156
  baseBranch,
@@ -385,6 +391,9 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
385
391
  };
386
392
  }
387
393
 
394
+ // Landed lane work clears the salvaged tasks' failure gate (#292 / SP-763).
395
+ const heal = healAfterSalvageLand(projectRoot, resolvedBatchId, lane, mergeCommit);
396
+
388
397
  appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrated", {
389
398
  laneNumber: laneNum,
390
399
  taskBranch,
@@ -393,6 +402,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
393
402
  commitsAhead,
394
403
  salvageableTasks: lane.salvageableTasks,
395
404
  excludedTasks: lane.excludedTasks,
405
+ healedTaskIds: heal.healedTaskIds,
396
406
  });
397
407
 
398
408
  return {
@@ -406,6 +416,8 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
406
416
  commitsAhead,
407
417
  salvageableTasks: lane.salvageableTasks,
408
418
  excludedTasks: lane.excludedTasks,
419
+ healedTaskIds: heal.healedTaskIds,
420
+ healError: heal.healError,
409
421
  gateOpenedBySalvage,
410
422
  headline: `Salvaged lane ${laneNum} (${taskBranch}) into ${baseBranch}`,
411
423
  suggestedCommand: "spine status --diagnose",
@@ -455,6 +467,12 @@ export function formatSalvageIntegrateOutput(result, options = {}) {
455
467
  if (result.mergeCommit) {
456
468
  lines.push(` Merge commit: ${result.mergeCommit}`);
457
469
  }
470
+ if (result.healedTaskIds?.length) {
471
+ lines.push(` Healed tasks: ${result.healedTaskIds.join(", ")}`);
472
+ }
473
+ if (result.healError) {
474
+ lines.push(` Heal failed: ${result.healError} — failed-task gate not cleared (see journal)`);
475
+ }
458
476
 
459
477
  if (result.suggestedCommand) {
460
478
  lines.push("", ` → ${result.suggestedCommand}`);
@@ -0,0 +1,178 @@
1
+ import { execFileSync } from "node:child_process";
2
+
3
+ const TRACKED_GITIGNORED_CHECK_ID = "tracked-gitignored";
4
+ const TRACKED_GITIGNORED_LABEL = "tracked gitignored paths";
5
+ const PREVIEW_LIMIT = 3;
6
+
7
+ /**
8
+ * @typedef {object} TrackedGitignoredPathsResult
9
+ * @property {string[]} paths Tracked paths that also match ignore patterns.
10
+ * @property {string | null} error Non-null when the git query itself failed.
11
+ */
12
+
13
+ /**
14
+ * @typedef {object} TrackedGitignoredPreflightCheck
15
+ * @property {"tracked-gitignored"} id
16
+ * @property {true} ok Always advisory — this check never blocks preflight (#289).
17
+ * @property {string} message
18
+ * @property {true} [warning]
19
+ * @property {{ paths: string[] }} [details]
20
+ * @property {string} [suggestedCommand]
21
+ */
22
+
23
+ /**
24
+ * @typedef {object} TrackedGitignoredDoctorCheck
25
+ * @property {"tracked gitignored paths"} label
26
+ * @property {true} ok Always advisory — this check never increments issueCount (#289).
27
+ * @property {true} [warning]
28
+ * @property {string} detail
29
+ * @property {string} [suggestedCommand]
30
+ */
31
+
32
+ /**
33
+ * @param {"tracked-gitignored"} id
34
+ * @param {true} ok
35
+ * @param {string} message
36
+ * @param {Partial<Omit<TrackedGitignoredPreflightCheck, "id" | "ok" | "message">>} [extra]
37
+ * @returns {TrackedGitignoredPreflightCheck}
38
+ */
39
+ function makeCheck(id, ok, message, extra = {}) {
40
+ return { id, ok, message, ...extra };
41
+ }
42
+
43
+ /**
44
+ * List tracked files that also match .gitignore / exclude patterns (issue #289).
45
+ *
46
+ * Bare `git ls-files -i` is fatal on supported git versions ("ls-files -i must
47
+ * be used with either -o or -c"), so `-c` is passed explicitly: the signal we
48
+ * want is exactly "tracked AND ignore-matched". Files that were committed
49
+ * before being ignored keep mutating in lane worktrees and can fail
50
+ * DirtyWorktree after a PASS.
51
+ *
52
+ * @param {string} projectRoot
53
+ * @returns {TrackedGitignoredPathsResult}
54
+ */
55
+ export function listTrackedGitignoredPaths(projectRoot) {
56
+ try {
57
+ const output = execFileSync(
58
+ "git",
59
+ ["ls-files", "-i", "-c", "--exclude-standard"],
60
+ {
61
+ cwd: projectRoot,
62
+ encoding: "utf-8",
63
+ stdio: ["ignore", "pipe", "pipe"],
64
+ timeout: 5000,
65
+ },
66
+ ).trim();
67
+ const paths = output
68
+ .split(/\r?\n/)
69
+ .map((line) => line.trim())
70
+ .filter(Boolean);
71
+ return { paths, error: null };
72
+ } catch (err) {
73
+ return {
74
+ paths: [],
75
+ error: err instanceof Error ? err.message : String(err),
76
+ };
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Bounded remediation command: untrack while keeping the working copy, letting
82
+ * .gitignore keep it out of future commits (#289).
83
+ *
84
+ * @param {string[]} paths
85
+ * @returns {string}
86
+ */
87
+ export function trackedGitignoredRemediation(paths) {
88
+ return `git rm -r --cached -- ${paths.slice(0, PREVIEW_LIMIT).join(" ")}`;
89
+ }
90
+
91
+ /**
92
+ * @param {string[]} paths
93
+ * @returns {string}
94
+ */
95
+ function previewWithSuffix(paths) {
96
+ const preview = paths.slice(0, PREVIEW_LIMIT).join(", ");
97
+ const suffix =
98
+ paths.length > PREVIEW_LIMIT ? ` +${paths.length - PREVIEW_LIMIT} more` : "";
99
+ return `${preview}${suffix}`;
100
+ }
101
+
102
+ /**
103
+ * Advisory preflight check (#289): warn when tracked paths also match
104
+ * .gitignore. Non-blocking by default — operators may track such paths on
105
+ * purpose, so the check never fails; it only suggests the untrack remediation.
106
+ *
107
+ * @param {object} ctx
108
+ * @param {string} ctx.projectRoot
109
+ * @returns {TrackedGitignoredPreflightCheck}
110
+ */
111
+ export function checkTrackedGitignoredWarn(ctx) {
112
+ const { projectRoot } = ctx;
113
+ const { paths, error } = listTrackedGitignoredPaths(projectRoot);
114
+
115
+ if (error) {
116
+ return makeCheck(
117
+ TRACKED_GITIGNORED_CHECK_ID,
118
+ true,
119
+ `tracked gitignored check skipped: ${error}`,
120
+ );
121
+ }
122
+ if (paths.length === 0) {
123
+ return makeCheck(
124
+ TRACKED_GITIGNORED_CHECK_ID,
125
+ true,
126
+ "no tracked files match .gitignore",
127
+ );
128
+ }
129
+
130
+ return makeCheck(
131
+ TRACKED_GITIGNORED_CHECK_ID,
132
+ true,
133
+ `${paths.length} tracked file(s) also match .gitignore (${previewWithSuffix(paths)}) — they mutate outside version control and can fail DirtyWorktree after PASS; untrack but keep working copies, relying on .gitignore`,
134
+ {
135
+ warning: true,
136
+ details: { paths },
137
+ suggestedCommand: trackedGitignoredRemediation(paths),
138
+ },
139
+ );
140
+ }
141
+
142
+ /**
143
+ * Doctor advisory (#289) — same signal as checkTrackedGitignoredWarn, shaped
144
+ * for doctor output ({label, ok, warning, detail, suggestedCommand}).
145
+ *
146
+ * @param {object} ctx
147
+ * @param {string} ctx.projectRoot
148
+ * @returns {TrackedGitignoredDoctorCheck}
149
+ */
150
+ export function buildTrackedGitignoredDoctorCheck(ctx) {
151
+ const { projectRoot } = ctx;
152
+ const { paths, error } = listTrackedGitignoredPaths(projectRoot);
153
+
154
+ if (error) {
155
+ return {
156
+ label: TRACKED_GITIGNORED_LABEL,
157
+ ok: true,
158
+ detail: `skipped: ${error}`,
159
+ };
160
+ }
161
+ if (paths.length === 0) {
162
+ return {
163
+ label: TRACKED_GITIGNORED_LABEL,
164
+ ok: true,
165
+ detail: "none",
166
+ };
167
+ }
168
+
169
+ return {
170
+ label: TRACKED_GITIGNORED_LABEL,
171
+ ok: true,
172
+ warning: true,
173
+ detail:
174
+ `${paths.length} tracked file(s) also match .gitignore (${previewWithSuffix(paths)}) — ` +
175
+ "untrack but keep working copies, relying on .gitignore",
176
+ suggestedCommand: trackedGitignoredRemediation(paths),
177
+ };
178
+ }
@@ -29,6 +29,7 @@ import {
29
29
  runPreflightPlanCheck,
30
30
  } from "./preflight/integrate-plan.mjs";
31
31
  import { checkLocCapstoneReadiness } from "./preflight/loc-capstone.mjs";
32
+ import { checkTrackedGitignoredWarn } from "./preflight/tracked-gitignored.mjs";
32
33
  import { INTEGRATE_DEFAULTS } from "./defaults.mjs";
33
34
  import { parseContract } from "../tasks/packet/parse-prompt.mjs";
34
35
  import { hasReleaseCriticalContract, isStubWorkerMode } from "../batch/contract-verify.mjs";
@@ -78,6 +79,13 @@ export {
78
79
  listPendingLocCapstoneTasks,
79
80
  } from "./preflight/loc-capstone.mjs";
80
81
 
82
+ export {
83
+ buildTrackedGitignoredDoctorCheck,
84
+ checkTrackedGitignoredWarn,
85
+ listTrackedGitignoredPaths,
86
+ trackedGitignoredRemediation,
87
+ } from "./preflight/tracked-gitignored.mjs";
88
+
81
89
  const CONCURRENT_DEV_LABEL = "concurrent development on base branch";
82
90
 
83
91
  /**
@@ -355,6 +363,7 @@ export function runBatchPreflight(options) {
355
363
  checks.push(checkStalePathSpine(ctx));
356
364
 
357
365
  checks.push(checkGitClean(ctx));
366
+ checks.push(checkTrackedGitignoredWarn(ctx));
358
367
  checks.push(
359
368
  buildCoexistencePreflightCheck({
360
369
  projectRoot,
@@ -17,6 +17,7 @@ import {
17
17
  import { buildStalePathDoctorCheck } from "./stale-path.mjs";
18
18
  import { buildCoexistenceDoctorCheck } from "./coexistence.mjs";
19
19
  import { buildConcurrentDevDoctorCheck } from "../config/spine-preflight-lib.mjs";
20
+ import { buildTrackedGitignoredDoctorCheck } from "../config/preflight/tracked-gitignored.mjs";
20
21
  import { buildTaskPacketSizeDoctorCheck } from "./task-packet-size.mjs";
21
22
  import {
22
23
  buildPiWorkerTimeoutDoctorCheck,
@@ -576,6 +577,10 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
576
577
  } catch {
577
578
  // Git ls-files unavailable; skip tracked-metrics advisory.
578
579
  }
580
+
581
+ // Advisory only (#289): tracked files that also match .gitignore mutate in
582
+ // lane worktrees and fail DirtyWorktree after PASS; warn with remediation.
583
+ checks.push(buildTrackedGitignoredDoctorCheck({ projectRoot }));
579
584
  }
580
585
 
581
586
  const rulesRootPath = path.join(projectRoot, CURSOR_RULES_ROOT_REL);