pi-spine 2.17.0 → 2.18.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,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * Integrate gate inspection and resolution (PRD §12, FR-GATE).
4
- * Usage: spine gate [approve|reject|status] [--batch ID] [--reason text] [--json]
4
+ * Usage: spine gate [approve|reject|status|reopen] [--batch ID] [--reason text] [--json]
5
5
  */
6
6
 
7
7
  import { isCliEntrypoint } from "./spine-cli/shared.mjs";
@@ -10,6 +10,7 @@ import {
10
10
  approveIntegrateGate,
11
11
  getIntegrateGateStatus,
12
12
  rejectIntegrateGate,
13
+ reopenIntegrateGateForCompletedBatch,
13
14
  } from "../src/batch/gate.mjs";
14
15
 
15
16
  /**
@@ -113,13 +114,18 @@ export function runSpineGate(options) {
113
114
  case "status":
114
115
  result = getIntegrateGateStatus({ projectRoot, batchId });
115
116
  break;
117
+ case "reopen":
118
+ // SP-740 / #275: re-open + re-approve path for completed batches after
119
+ // stale_revision or a removed gate record.
120
+ result = reopenIntegrateGateForCompletedBatch({ projectRoot, batchId });
121
+ break;
116
122
  default:
117
123
  result = {
118
124
  ok: false,
119
125
  exitCode: 1,
120
126
  headline: `Unknown gate action: ${action}`,
121
127
  suggestedCommand: "spine gate status",
122
- error: "Use approve, reject, or status",
128
+ error: "Use approve, reject, status, or reopen",
123
129
  };
124
130
  }
125
131
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.17.0",
3
+ "version": "2.18.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -3,6 +3,11 @@
3
3
  * Worker exited without `.DONE` diagnosis helpers (SP-313 / issue #18).
4
4
  */
5
5
 
6
+ import {
7
+ BACKGROUND_VERIFICATION_HINT,
8
+ detectBackgroundedVerification,
9
+ } from "./worker-output.mjs";
10
+
6
11
  /** Worker exited cleanly but never wrote `.DONE`. */
7
12
  export const WORKER_DONE_MISSING_OUTPUT_MARKERS = [
8
13
  "pi exited but .DONE was not created",
@@ -81,7 +86,13 @@ export function buildWorkerDoneMissingHeadline(batchLabel, ctx = {}) {
81
86
  : ctx.workerOutputSnippet
82
87
  ? `: ${ctx.workerOutputSnippet}`
83
88
  : "";
84
- return `${batchLabel} ${taskLabel} exited without .DONE${fileHint}${logHint}${tailHint}`;
89
+ // SP-741 (#276): point operators at the backgrounded-verification cause when
90
+ // the captured output shows the worker exited mid-verification.
91
+ const hintInput = [tail, ctx.workerOutputSnippet, ctx.output].filter(Boolean).join("\n");
92
+ const backgroundHint = detectBackgroundedVerification(hintInput)
93
+ ? ` — ${BACKGROUND_VERIFICATION_HINT}`
94
+ : "";
95
+ return `${batchLabel} ${taskLabel} exited without .DONE${fileHint}${logHint}${tailHint}${backgroundHint}`;
85
96
  }
86
97
 
87
98
  /** @param {object} ctx */
@@ -7,6 +7,7 @@
7
7
 
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
10
+ import { createHash } from "node:crypto";
10
11
  import {
11
12
  acquireLaneSlot,
12
13
  aggregateMatrixOutcomes,
@@ -19,6 +20,7 @@ import {
19
20
  runShellInDir,
20
21
  substituteRowCommand,
21
22
  } from "./matrix.mjs";
23
+ import { applyMatrixRowToPrompt } from "../../planner/matrix.mjs";
22
24
  import { commitLaneAndValidateWorktree } from "./commit.mjs";
23
25
  import { recordLaneTaskMetric } from "./queue.mjs";
24
26
  import { appendJournalEvent } from "../journal.mjs";
@@ -47,13 +49,63 @@ export function readParentContract(parentTaskFolderAbs) {
47
49
  return parseContract(fs.readFileSync(promptPath, "utf-8"));
48
50
  }
49
51
 
52
+ /**
53
+ * Serve a matrix LLM row its row-substituted PROMPT.md (#232). Reads the parent
54
+ * PROMPT.md (same source convention as `readParentContract`), substitutes
55
+ * `{matrix.<column>}` placeholders across the whole document — steps, contract
56
+ * fields, and File Scope paths — and writes the result to the row worktree's
57
+ * PROMPT.md so `runWorker` and the spawned worker both read row-specific
58
+ * content instead of raw `{matrix.*}` refs.
59
+ *
60
+ * @param {object} params
61
+ * @param {string} params.parentTaskFolderAbs Parent task folder in the main checkout.
62
+ * @param {string} params.worktreePath Row worktree root.
63
+ * @param {string} params.taskFolderRel Task folder path relative to the worktree root.
64
+ * @param {Record<string, string>} params.row Matrix row values keyed by column.
65
+ * @returns {{ servedPrompt: string, sha256: string }} Exact bytes served plus their digest.
66
+ * @throws When the parent PROMPT.md is missing, or on unknown `{matrix.X}`
67
+ * references (fail-loud via `substituteMatrixVariables`).
68
+ */
69
+ function serveMatrixRowPrompt({ parentTaskFolderAbs, worktreePath, taskFolderRel, row }) {
70
+ const promptPath = path.join(parentTaskFolderAbs, "PROMPT.md");
71
+ if (!fs.existsSync(promptPath)) {
72
+ throw new Error(`parent PROMPT.md not found: ${promptPath}`);
73
+ }
74
+ const substituted = applyMatrixRowToPrompt(fs.readFileSync(promptPath, "utf-8"), row);
75
+ const rowPromptPath = path.join(worktreePath, taskFolderRel, "PROMPT.md");
76
+ fs.mkdirSync(path.dirname(rowPromptPath), { recursive: true });
77
+ fs.writeFileSync(rowPromptPath, substituted, "utf-8");
78
+ const sha256 = createHash("sha256").update(substituted, "utf-8").digest("hex");
79
+ return { servedPrompt: substituted, sha256 };
80
+ }
81
+
82
+ /**
83
+ * Restore the authored PROMPT.md and drop the row's `.DONE` after a successful
84
+ * LLM row so the per-row commit carries only real row output. Row branches are
85
+ * merged into the lane (SP-697), and per-row PROMPT/.DONE content always
86
+ * differs (row values, completion timestamps) — committing either would
87
+ * add/add-conflict every multi-row LLM matrix merge. The parent writes the
88
+ * lane-level `.DONE` after all rows merge, mirroring the execute path.
89
+ *
90
+ * @param {object} params
91
+ * @param {string} params.worktreePath Row worktree root.
92
+ * @param {string} params.taskFolderRel Task folder path relative to the worktree root.
93
+ * @param {string} [params.projectRoot] Main repo root for git identity.
94
+ */
95
+ function restoreMatrixRowPrompt({ worktreePath, taskFolderRel, projectRoot }) {
96
+ const promptRel = `${taskFolderRel.replace(/\\/g, "/")}/PROMPT.md`;
97
+ gitExec(worktreePath, ["checkout", "--", promptRel], { projectRoot });
98
+ fs.rmSync(path.join(worktreePath, taskFolderRel, ".DONE"), { force: true });
99
+ }
100
+
50
101
  /**
51
102
  * Execute a single matrix row in its own worktree. Substitutes `{matrix.X}`
52
- * placeholders for execution-only rows; LLM rows delegate to `runWorker`.
53
- * Commits successful row output to the row branch.
103
+ * placeholders for execution-only rows; LLM rows delegate to `runWorker` with a
104
+ * row-substituted PROMPT.md served into the row worktree (#232). Commits
105
+ * successful row output to the row branch.
54
106
  *
55
107
  * @param {object} params
56
- * @returns {Promise<{ rowId: string, ok: boolean, exitCode: number, output: string, worktreePath?: string, branch?: string, commitSha?: string }>}
108
+ * @returns {Promise<{ rowId: string, ok: boolean, exitCode: number, output: string, worktreePath?: string, branch?: string, commitSha?: string, servedPrompt?: string }>}
57
109
  */
58
110
  export async function runMatrixSubLane({
59
111
  projectRoot,
@@ -231,29 +283,73 @@ export async function runMatrixSubLane({
231
283
  }
232
284
  }
233
285
  } else {
234
- // LLM rows delegate to the worker in the row worktree. Per-row agent-prompt
235
- // substitution is handled by SP-670 helpers at the worker boundary; full
236
- // worker-side substitution wiring is tracked for SP-673.
237
- const workerResult = await runWorker({
238
- worktreePath,
239
- taskFolder: path.join(worktreePath, taskFolderRel),
240
- projectRoot,
241
- batchId,
242
- laneNumber,
243
- taskId,
244
- laneBranch: branch,
245
- laneCorrelationId: `${laneCorrelationId}-matrix-${rowId}`,
246
- fileScopePaths: [],
247
- config,
248
- });
249
- result = {
250
- rowId,
251
- ok: Boolean(workerResult.ok),
252
- exitCode: workerResult.exitCode ?? 0,
253
- output: workerResult.output ?? "",
254
- worktreePath,
255
- branch,
256
- };
286
+ // LLM rows delegate to the worker in the row worktree. Serve the row its
287
+ // row-substituted PROMPT.md first (#232): steps, contract fields, and File
288
+ // Scope all carry this row's values, so the worker never sees raw
289
+ // `{matrix.*}` refs. Substitution is fail-loud (SP-670 engine): an unknown
290
+ // reference fails the row instead of reaching the worker.
291
+ try {
292
+ const { servedPrompt, sha256 } = serveMatrixRowPrompt({
293
+ parentTaskFolderAbs,
294
+ worktreePath,
295
+ taskFolderRel,
296
+ row: values,
297
+ });
298
+ recordMatrixEvent(projectRoot, batchId, "matrix.sub_lane.prompt_served", {
299
+ taskId,
300
+ laneNumber,
301
+ rowId,
302
+ correlationId: laneCorrelationId,
303
+ sha256,
304
+ chars: servedPrompt.length,
305
+ });
306
+ const workerResult = await runWorker({
307
+ worktreePath,
308
+ taskFolder: path.join(worktreePath, taskFolderRel),
309
+ projectRoot,
310
+ batchId,
311
+ laneNumber,
312
+ taskId,
313
+ laneBranch: branch,
314
+ laneCorrelationId: `${laneCorrelationId}-matrix-${rowId}`,
315
+ fileScopePaths: [],
316
+ config,
317
+ });
318
+ result = {
319
+ rowId,
320
+ ok: Boolean(workerResult.ok),
321
+ exitCode: workerResult.exitCode ?? 0,
322
+ output: workerResult.output ?? "",
323
+ worktreePath,
324
+ branch,
325
+ };
326
+ if (result.ok) {
327
+ // Drop the substitution scaffolding before the per-row commit so
328
+ // row→lane merges stay conflict-free (see restoreMatrixRowPrompt).
329
+ try {
330
+ restoreMatrixRowPrompt({ worktreePath, taskFolderRel, projectRoot });
331
+ } catch (restoreErr) {
332
+ const restoreMessage = restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
333
+ result = {
334
+ ...result,
335
+ ok: false,
336
+ exitCode: 1,
337
+ output: `${result.output}\nmatrix row prompt restore failed: ${restoreMessage}`,
338
+ };
339
+ }
340
+ }
341
+ result.servedPrompt = servedPrompt;
342
+ } catch (err) {
343
+ const message = err instanceof Error ? err.message : String(err);
344
+ result = {
345
+ rowId,
346
+ ok: false,
347
+ exitCode: 1,
348
+ output: `matrix row prompt substitution failed: ${message}`,
349
+ worktreePath,
350
+ branch,
351
+ };
352
+ }
257
353
  }
258
354
 
259
355
  if (result.ok) {
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import crypto from "node:crypto";
7
+ import fs from "node:fs";
7
8
  import { resolveGatePostureConfig } from "../config/gate-posture-config.mjs";
8
9
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
10
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
@@ -200,6 +201,133 @@ export function openIntegrateGateAfterBatchComplete(ctx) {
200
201
  };
201
202
  }
202
203
 
204
+ /**
205
+ * Remove a gate record so a fresh gate can be opened (SP-740 / #275).
206
+ * Supported counterpart to hand-deleting `gate.json` (runbook §5.2 pre-v2.18).
207
+ *
208
+ * @param {string} projectRoot
209
+ * @param {string} batchId
210
+ * @returns {boolean} true when an existing record was removed
211
+ */
212
+ export function removeGateRecord(projectRoot, batchId) {
213
+ const filePath = gateRecordPath(projectRoot, batchId);
214
+ if (!fs.existsSync(filePath)) return false;
215
+ fs.rmSync(filePath, { force: true });
216
+ return true;
217
+ }
218
+
219
+ /**
220
+ * Re-open the integrate gate for a completed batch (SP-740 / #275).
221
+ *
222
+ * After `stale_revision` (orch tip drift past the approved pin) or a removed gate
223
+ * record, completed-phase batches had no working re-open path: `spine batch resume
224
+ * --force` refuses phase=completed. Reopening removes the stale/decided record and
225
+ * routes through `openIntegrateGateAfterBatchComplete`, re-pinning `targetRevision`
226
+ * to the current orch tip and re-collecting evidence for a fresh approval.
227
+ *
228
+ * Fail-closed guarantees preserved: a gate that is approved or pending AND still
229
+ * pinned to the current orch tip is never invalidated here — approve/integrate
230
+ * instead. Only missing, stale-pin, or rejected records are replaced.
231
+ *
232
+ * @param {object} ctx
233
+ * @param {string} ctx.projectRoot
234
+ * @param {string} ctx.batchId
235
+ * @param {object|null} [ctx.batchState]
236
+ * @returns {{ ok: boolean, exitCode: number, reopened: boolean, reason: string, gate: object|null, headline: string, suggestedCommand: string, alternatives: string[], error?: string, extendedError?: string|null }}
237
+ */
238
+ export function reopenIntegrateGateForCompletedBatch(ctx) {
239
+ const { projectRoot, batchId, batchState = null } = ctx;
240
+ const state = batchState ?? loadBatchStateFile(projectRoot).raw ?? null;
241
+
242
+ if (String(state?.phase ?? "") !== "completed") {
243
+ return {
244
+ ok: false,
245
+ exitCode: 1,
246
+ reopened: false,
247
+ reason: "batch_not_completed",
248
+ gate: null,
249
+ headline: "Gate reopen requires a completed batch",
250
+ suggestedCommand: "spine status --diagnose",
251
+ alternatives: [],
252
+ error: `Batch ${batchId} is in phase ${String(state?.phase ?? "unknown")} — gate reopen only applies to completed batches`,
253
+ };
254
+ }
255
+
256
+ if (!state?.orchBranch) {
257
+ return {
258
+ ok: false,
259
+ exitCode: 1,
260
+ reopened: false,
261
+ reason: "no_orch_branch",
262
+ gate: null,
263
+ headline: "Gate reopen blocked — batch state has no orch branch",
264
+ suggestedCommand: "spine status --diagnose",
265
+ alternatives: [],
266
+ error: "batchState.orchBranch missing; cannot pin a fresh targetRevision",
267
+ };
268
+ }
269
+
270
+ const existing = loadGateRecord(projectRoot, batchId);
271
+ if (existing && (existing.status === "approved" || existing.status === "pending")) {
272
+ const pinCheck = validateGateTargetRevision(projectRoot, existing, state);
273
+ if (pinCheck.ok) {
274
+ const approved = String(existing.status) === "approved";
275
+ return {
276
+ ok: true,
277
+ exitCode: 0,
278
+ reopened: false,
279
+ reason: approved ? "gate_current" : "gate_pending",
280
+ gate: existing,
281
+ headline: approved
282
+ ? "Gate already approved and pinned to the current orch tip — nothing to reopen"
283
+ : "Gate already pending with a current pin — approve the existing record",
284
+ suggestedCommand: approved ? "spine integrate" : "spine gate approve",
285
+ alternatives: ["spine gate status"],
286
+ };
287
+ }
288
+ }
289
+
290
+ // Missing, stale-pin, or rejected record: clear the way and re-open with a fresh pin.
291
+ removeGateRecord(projectRoot, batchId);
292
+ appendJournalEvent(projectRoot, batchId, "gate.reopened", {
293
+ previousStatus: existing?.status ?? null,
294
+ previousTargetRevision: existing?.targetRevision ?? null,
295
+ source: "spine gate reopen",
296
+ });
297
+
298
+ const gateResult = openIntegrateGateAfterBatchComplete({
299
+ projectRoot,
300
+ batchId,
301
+ batchState: { ...state, phase: "completed" },
302
+ });
303
+
304
+ if (gateResult.skipped) {
305
+ return {
306
+ ok: false,
307
+ exitCode: 1,
308
+ reopened: false,
309
+ reason: gateResult.reason ?? "gate_open_skipped",
310
+ gate: null,
311
+ headline: "Gate reopen failed — integrate gate could not be opened",
312
+ suggestedCommand: "spine status --diagnose",
313
+ alternatives: [],
314
+ error: gateResult.reason ?? "openIntegrateGateAfterBatchComplete skipped",
315
+ };
316
+ }
317
+
318
+ return {
319
+ ok: true,
320
+ exitCode: 0,
321
+ reopened: true,
322
+ reason: "reopened",
323
+ gate: gateResult.gate,
324
+ extendedError: gateResult.extendedError ?? null,
325
+ headline: `Integrate gate re-opened — ${formatGateSummary(gateResult.gate)}; targetRevision re-pinned to current orch tip`,
326
+ suggestedCommand: "spine gate approve",
327
+ alternatives: ["spine gate status", "/spine-gate approve"],
328
+ };
329
+ }
330
+
203
331
  /**
204
332
  * @param {object} ctx
205
333
  * @param {string} ctx.projectRoot
@@ -210,12 +338,22 @@ export function getIntegrateGateStatus(ctx) {
210
338
  const gate = loadGateRecord(projectRoot, batchId);
211
339
 
212
340
  if (!gate) {
341
+ // SP-740 / #275: agree with `spine integrate` — a completed batch without a
342
+ // gate record has a working re-open path; non-completed batches keep the
343
+ // diagnose suggestion.
344
+ const completed =
345
+ String(loadBatchStateFile(projectRoot).raw?.phase ?? "") === "completed";
213
346
  return {
214
347
  ok: true,
215
348
  exitCode: 0,
216
349
  gate: null,
217
- headline: "No integrate gate on record",
218
- suggestedCommand: "spine status --diagnose",
350
+ headline: completed
351
+ ? "No integrate gate on record — batch completed; re-open and re-approve"
352
+ : "No integrate gate on record",
353
+ suggestedCommand: completed ? "spine gate reopen" : "spine status --diagnose",
354
+ alternatives: completed
355
+ ? ["spine batch resume --force", "spine status --diagnose"]
356
+ : [],
219
357
  };
220
358
  }
221
359
 
@@ -282,16 +420,25 @@ export function checkIntegrateGate(ctx) {
282
420
 
283
421
  const gate = loadGateRecord(projectRoot, batchId);
284
422
  if (!gate) {
285
- const error = "Integrate gate not opened — approve evidence before merging";
423
+ // SP-740 / #275: for completed batches point at the working re-open path so
424
+ // integrate and `spine gate status` agree. Blocker code / exitCode unchanged —
425
+ // automation switches on `missing_gate`, not display text.
426
+ const completed =
427
+ String((ctx.batchState ?? loadBatchStateFile(projectRoot).raw)?.phase ?? "") === "completed";
428
+ const error = completed
429
+ ? "Integrate gate not opened — re-open and re-approve the completed batch before merging"
430
+ : "Integrate gate not opened — approve evidence before merging";
286
431
  return {
287
432
  ok: false,
288
433
  required: true,
289
434
  exitCode: 2,
290
435
  failureClass: "GateBlocked",
291
436
  error,
292
- headline: "Integrate blocked — no gate record (run batch to completion or spine gate status)",
293
- suggestedCommand: "spine gate status",
294
- alternatives: ["/spine-gate"],
437
+ headline: completed
438
+ ? "Integrate blocked — no gate record (batch completed: spine gate reopen to re-open and re-approve)"
439
+ : "Integrate blocked — no gate record (run batch to completion or spine gate status)",
440
+ suggestedCommand: completed ? "spine gate reopen" : "spine gate status",
441
+ alternatives: completed ? ["spine gate status", "/spine-gate"] : ["/spine-gate"],
295
442
  blockers: [makeBlocker("missing_gate", error)],
296
443
  };
297
444
  }
@@ -279,6 +279,24 @@ export function activitySignalsChanged(prev, next) {
279
279
  return false;
280
280
  }
281
281
 
282
+ /**
283
+ * Static-null progress snapshot (issue #272): every progress signal is absent, so
284
+ * the snapshot carries no evidence of forward movement. Heartbeat emission or
285
+ * child-process liveness alone must not refresh the stall anchor while snapshots
286
+ * stay static-null, otherwise a hung worker slides the stall budget forever.
287
+ * @param {object | null | undefined} signals
288
+ * @returns {boolean}
289
+ */
290
+ export function isStaticNullProgressSnapshot(signals) {
291
+ if (!signals) return true;
292
+ return (
293
+ signals.statusMtimeMs == null &&
294
+ signals.lastCommitAtMs == null &&
295
+ signals.fileScopeMtimeMs == null &&
296
+ (signals.dirtyPaths?.length ?? 0) === 0
297
+ );
298
+ }
299
+
282
300
  /**
283
301
  * @param {object | null} prev
284
302
  * @param {object} next
@@ -0,0 +1,50 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Force-resume gate reopen for completed batches (SP-740 / #275).
4
+ * Extracted from resume.mjs to keep that module under the 500 LOC cap.
5
+ */
6
+
7
+ import { reopenIntegrateGateForCompletedBatch } from "./gate.mjs";
8
+ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
9
+
10
+ /**
11
+ * When `resumeCheck.gateReopen` is set, re-open the integrate gate and return
12
+ * a resumeBatch-shaped result. Caller must release the resume lock via the
13
+ * returned path (this helper releases it).
14
+ *
15
+ * @param {{
16
+ * projectRoot: string,
17
+ * resumeCheck: { batchId: string, gateReopen?: boolean },
18
+ * releaseResumeLock?: (() => void) | null,
19
+ * }} params
20
+ * @returns {object | null} resumeBatch result when handled; null when not a reopen path
21
+ */
22
+ export function tryResumeCompletedGateReopen({ projectRoot, resumeCheck, releaseResumeLock }) {
23
+ if (!resumeCheck?.gateReopen) {
24
+ return null;
25
+ }
26
+
27
+ const reopenState = loadSpineBatchState(projectRoot).raw;
28
+ const reopenResult = reopenIntegrateGateForCompletedBatch({
29
+ projectRoot,
30
+ batchId: resumeCheck.batchId,
31
+ batchState: reopenState,
32
+ });
33
+ if (reopenState) {
34
+ saveSpineBatchState(projectRoot, reopenState, { bypassWriteGuard: true });
35
+ }
36
+ releaseResumeLock?.();
37
+ const output = reopenResult.reopened
38
+ ? `Batch ${resumeCheck.batchId} gate re-opened: evidence re-collected, targetRevision re-pinned.\n → spine gate approve\n → spine integrate\n`
39
+ : `${reopenResult.headline}\n → ${reopenResult.suggestedCommand}\n`;
40
+ return {
41
+ ok: reopenResult.ok,
42
+ exitCode: reopenResult.exitCode,
43
+ batchId: resumeCheck.batchId,
44
+ reopened: reopenResult.reopened,
45
+ reopenReason: reopenResult.reason,
46
+ gate: reopenResult.gate,
47
+ error: reopenResult.error,
48
+ output,
49
+ };
50
+ }
@@ -194,6 +194,49 @@ export function validateMultiTaskResume({ projectRoot, force = false }) {
194
194
  const failedTasksCount = Number(state.failedTasks ?? 0);
195
195
  const failedPhaseRetryLimbo =
196
196
  phase === "failed" && failedTasksCount === 0 && pendingTasksForResume.length > 0;
197
+
198
+ // SP-740 / #275: completed batches are never worker-resumable, but after a
199
+ // `stale_revision` blocker or a removed gate record they still need a working
200
+ // re-open + re-approve path. Force resume on a completed batch routes through
201
+ // the gate re-open (no worker re-run) instead of dead-ending on cannot_resume.
202
+ if (phase === "completed") {
203
+ if (!force) {
204
+ return {
205
+ ok: false,
206
+ exitCode: 1,
207
+ error: "cannot_resume",
208
+ output: `Batch ${state.batchId} completed. Use spine gate reopen (or spine batch resume --force) to re-open the integrate gate.\n`,
209
+ batchId: state.batchId,
210
+ phase,
211
+ };
212
+ }
213
+ if (pendingTasksForResume.length > 0) {
214
+ return {
215
+ ok: false,
216
+ exitCode: 1,
217
+ error: "cannot_resume",
218
+ output: `Batch ${state.batchId} is completed but has pending tasks — use spine batch retry <taskId> instead.\n`,
219
+ batchId: state.batchId,
220
+ phase,
221
+ };
222
+ }
223
+ // Lane worktrees may already be cleaned up after completion; skip worker-oriented
224
+ // validation. The caller must route this through reopenIntegrateGateForCompletedBatch.
225
+ return {
226
+ ok: true,
227
+ batchId: state.batchId,
228
+ phase,
229
+ updatedAt: Number(state.updatedAt ?? 0),
230
+ pendingTasks: [],
231
+ lanes: [],
232
+ resumableWave: null,
233
+ postMergeLimbo: false,
234
+ orphanResume: false,
235
+ engineConfirmedDead: false,
236
+ gateReopen: true,
237
+ };
238
+ }
239
+
197
240
  const postMergeLimbo = detectPostMergeLimboForResume({ projectRoot, state });
198
241
  const orphanEligibility =
199
242
  phase === "running"
@@ -0,0 +1,75 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Single-lane resume prompt-parse failure path.
4
+ * Extracted from resume.mjs to keep that module under the 500 LOC cap.
5
+ */
6
+
7
+ import { appendJournalEvent } from "./journal.mjs";
8
+ import { saveSpineBatchState, updateSegmentForTask } from "./state.mjs";
9
+
10
+ /**
11
+ * Persist prompt-parse failure for a resumed single-lane task and return the
12
+ * resumeBatch-shaped error result.
13
+ *
14
+ * @param {{
15
+ * projectRoot: string,
16
+ * state: object,
17
+ * batchId: string,
18
+ * task: object,
19
+ * taskId: string,
20
+ * scopeResult: { error?: string, errors?: unknown, promptPath?: string },
21
+ * releaseResumeLock?: (() => void) | null,
22
+ * laneCorrelationId: string,
23
+ * }} params
24
+ */
25
+ export function failResumePromptParse({
26
+ projectRoot,
27
+ state,
28
+ batchId,
29
+ task,
30
+ taskId,
31
+ scopeResult,
32
+ releaseResumeLock,
33
+ laneCorrelationId,
34
+ }) {
35
+ task.status = "failed";
36
+ task.endedAt = Date.now();
37
+ task.exitReason = "prompt_parse_failed";
38
+ if (!task.startedAt) task.startedAt = Date.now();
39
+ updateSegmentForTask(state, taskId, "failed");
40
+ state.failedTasks = 1;
41
+ state.succeededTasks = 0;
42
+ state.endedAt = Date.now();
43
+ state.lastError = scopeResult.error?.slice(0, 500) ?? "prompt parse failed";
44
+ state.phase = "failed";
45
+ saveSpineBatchState(projectRoot, state);
46
+ appendJournalEvent(projectRoot, batchId, "task.prompt_parse_failed", {
47
+ taskId,
48
+ laneNumber: 1,
49
+ laneId: "lane-1",
50
+ correlationId: laneCorrelationId,
51
+ error: scopeResult.error,
52
+ errors: scopeResult.errors,
53
+ promptPath: scopeResult.promptPath,
54
+ resumed: true,
55
+ });
56
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
57
+ taskId,
58
+ laneNumber: 1,
59
+ laneId: "lane-1",
60
+ correlationId: laneCorrelationId,
61
+ classification: "prompt_parse_failed",
62
+ exitCode: 1,
63
+ output: scopeResult.error,
64
+ resumed: true,
65
+ });
66
+ releaseResumeLock?.();
67
+ return {
68
+ ok: false,
69
+ exitCode: 1,
70
+ batchId,
71
+ taskId,
72
+ error: "prompt_parse_failed",
73
+ output: scopeResult.error,
74
+ };
75
+ }
@@ -24,6 +24,8 @@ import {
24
24
  resolveTaskFolderRel,
25
25
  taskAlreadyComplete,
26
26
  } from "./resume-common.mjs";
27
+ import { tryResumeCompletedGateReopen } from "./resume-gate-reopen.mjs";
28
+ import { failResumePromptParse } from "./resume-prompt-parse-fail.mjs";
27
29
  import {
28
30
  countPendingSegments,
29
31
  loadSpineBatchState,
@@ -66,6 +68,16 @@ export async function resumeBatch({ projectRoot, force = false }) {
66
68
  return resumeCheck;
67
69
  }
68
70
 
71
+ // SP-740 / #275: completed + force re-opens the integrate gate (no worker re-run).
72
+ const gateReopenResult = tryResumeCompletedGateReopen({
73
+ projectRoot,
74
+ resumeCheck,
75
+ releaseResumeLock,
76
+ });
77
+ if (gateReopenResult) {
78
+ return gateReopenResult;
79
+ }
80
+
69
81
  installAttachedEngineShutdownHandlers({ projectRoot });
70
82
 
71
83
  const loaded = loadSpineBatchState(projectRoot);
@@ -102,47 +114,16 @@ export async function resumeBatch({ projectRoot, force = false }) {
102
114
  const taskFolderOnHost = resolveTaskFolderOnHost(projectRoot, taskFolderRel, tasksRootRel, taskId);
103
115
  const scopeResult = loadResumeFileScopePaths(taskFolderOnHost);
104
116
  if (!scopeResult.ok) {
105
- const laneCorrelationId = crypto.randomUUID();
106
- task.status = "failed";
107
- task.endedAt = Date.now();
108
- task.exitReason = "prompt_parse_failed";
109
- if (!task.startedAt) task.startedAt = Date.now();
110
- updateSegmentForTask(state, taskId, "failed");
111
- state.failedTasks = 1;
112
- state.succeededTasks = 0;
113
- state.endedAt = Date.now();
114
- state.lastError = scopeResult.error?.slice(0, 500) ?? "prompt parse failed";
115
- state.phase = "failed";
116
- saveSpineBatchState(projectRoot, state);
117
- appendJournalEvent(projectRoot, batchId, "task.prompt_parse_failed", {
118
- taskId,
119
- laneNumber: 1,
120
- laneId: "lane-1",
121
- correlationId: laneCorrelationId,
122
- error: scopeResult.error,
123
- errors: scopeResult.errors,
124
- promptPath: scopeResult.promptPath,
125
- resumed: true,
126
- });
127
- appendJournalEvent(projectRoot, batchId, "task.failed", {
128
- taskId,
129
- laneNumber: 1,
130
- laneId: "lane-1",
131
- correlationId: laneCorrelationId,
132
- classification: "prompt_parse_failed",
133
- exitCode: 1,
134
- output: scopeResult.error,
135
- resumed: true,
136
- });
137
- releaseResumeLock?.();
138
- return {
139
- ok: false,
140
- exitCode: 1,
117
+ return failResumePromptParse({
118
+ projectRoot,
119
+ state,
141
120
  batchId,
121
+ task,
142
122
  taskId,
143
- error: "prompt_parse_failed",
144
- output: scopeResult.error,
145
- };
123
+ scopeResult,
124
+ releaseResumeLock,
125
+ laneCorrelationId: crypto.randomUUID(),
126
+ });
146
127
  }
147
128
  const fileScopePaths = scopeResult.fileScopePaths;
148
129
 
@@ -0,0 +1,180 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Salvage --integrate gate open path (#274).
4
+ * Extracted from salvage-batch-integrate.mjs to keep that module under the 500 LOC cap.
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
10
+ import {
11
+ evidenceDir,
12
+ loadGateRecord,
13
+ maybeAutoApproveIntegrateGate,
14
+ openIntegrateGate,
15
+ } from "./gate.mjs";
16
+ import { gitExec } from "./git-exec.mjs";
17
+ import { archiveBatchStatePath } from "./lifecycle.mjs";
18
+ import { appendJournalEvent } from "./journal.mjs";
19
+ import { loadBatchStateFile } from "./reconcile.mjs";
20
+
21
+ /**
22
+ * Load archived seed state (or matching live state) for a finished batch.
23
+ * Mirrors the seed resolution used by salvage-batch-list.mjs.
24
+ *
25
+ * @param {string} projectRoot
26
+ * @param {string} batchId
27
+ * @returns {object|null}
28
+ */
29
+ function loadSalvageBatchSeed(projectRoot, batchId) {
30
+ const archivePath = archiveBatchStatePath(projectRoot, batchId);
31
+ if (fs.existsSync(archivePath)) {
32
+ try {
33
+ return JSON.parse(fs.readFileSync(archivePath, "utf-8"));
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ const loaded = loadBatchStateFile(projectRoot);
40
+ if (loaded.raw && String(loaded.raw.batchId ?? loaded.raw.id ?? "") === batchId) {
41
+ return loaded.raw;
42
+ }
43
+
44
+ return null;
45
+ }
46
+
47
+ /**
48
+ * True only when the gate check failed solely on a missing gate record (#274).
49
+ * Pending / rejected / stale-revision gates keep their existing blocked paths.
50
+ *
51
+ * @param {{ ok?: boolean, gate?: object|null, blockers?: Array<{ code?: string }> }} gateCheck
52
+ */
53
+ export function gateBlockedOnMissingGate(gateCheck) {
54
+ return (
55
+ gateCheck.gate == null &&
56
+ Array.isArray(gateCheck.blockers) &&
57
+ gateCheck.blockers.some((blocker) => blocker?.code === "missing_gate")
58
+ );
59
+ }
60
+
61
+ /**
62
+ * Best-effort rev-parse of a branch tip SHA for salvage evidence.
63
+ *
64
+ * @param {string} projectRoot
65
+ * @param {string} ref
66
+ * @returns {string|null}
67
+ */
68
+ function resolveTipSha(projectRoot, ref) {
69
+ try {
70
+ return gitExec(projectRoot, ["rev-parse", "--verify", `${ref}^{commit}`], { projectRoot }) || null;
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Write salvage inspection evidence into the gate evidence dir.
78
+ * `collectCoreEvidenceBundle` picks up `salvage-*.json` files as gate evidence refs.
79
+ *
80
+ * @param {string} projectRoot
81
+ * @param {string} batchId
82
+ * @param {object} snapshot
83
+ * @returns {string} evidence ref
84
+ */
85
+ function writeSalvageGateEvidence(projectRoot, batchId, snapshot) {
86
+ const dir = evidenceDir(projectRoot, batchId);
87
+ fs.mkdirSync(dir, { recursive: true });
88
+ writeJsonAtomic(path.join(dir, "salvage-inspect.json"), {
89
+ ...snapshot,
90
+ inspectedAt: new Date().toISOString(),
91
+ source: "batch salvage --integrate",
92
+ });
93
+ return "evidence/salvage-inspect.json";
94
+ }
95
+
96
+ /**
97
+ * Open a fresh integrate gate from salvage inspection evidence (#274).
98
+ *
99
+ * A batch that failed before the merge phase never journaled `gate.opened`, so
100
+ * salvage --integrate used to dead-end on "no gate record". When the lane is
101
+ * verified salvageable (terminal-success tasks, commits ahead — established by
102
+ * `listSalvageableLanes` before this runs), open the gate here with salvage
103
+ * evidence plus the current orch tip pin. Approval posture still applies: the
104
+ * fresh gate stays pending unless config explicitly opts in to auto-approve.
105
+ *
106
+ * @param {string} projectRoot
107
+ * @param {string} batchId
108
+ * @param {object} ctx
109
+ * @param {object} ctx.lane
110
+ * @param {string} ctx.baseBranch
111
+ * @param {string} ctx.taskBranch
112
+ * @param {number} ctx.commitsAhead
113
+ * @param {object|null} ctx.config
114
+ * @returns {{ ok: true, opened: boolean, gate: object, evidenceRefs: string[] } | { ok: false, error: string }}
115
+ */
116
+ export function openGateFromSalvageEvidence(projectRoot, batchId, ctx) {
117
+ const { lane, baseBranch, taskBranch, commitsAhead, config } = ctx;
118
+
119
+ // Fail closed when salvage evidence is insufficient to justify a gate.
120
+ if (!lane || !Array.isArray(lane.salvageableTasks) || lane.salvageableTasks.length === 0) {
121
+ return { ok: false, error: "salvage_evidence_insufficient" };
122
+ }
123
+ if (!Number.isFinite(commitsAhead) || commitsAhead <= 0) {
124
+ return { ok: false, error: "salvage_commits_ahead_required" };
125
+ }
126
+
127
+ /** @type {string[]} */
128
+ const salvageEvidenceRefs = [];
129
+ try {
130
+ salvageEvidenceRefs.push(
131
+ writeSalvageGateEvidence(projectRoot, batchId, {
132
+ batchId,
133
+ laneNumber: lane.laneNumber,
134
+ taskBranch,
135
+ baseBranch,
136
+ commitsAhead,
137
+ salvageableTasks: lane.salvageableTasks,
138
+ excludedTasks: lane.excludedTasks ?? [],
139
+ diffStat: lane.diffStat ?? null,
140
+ baseTip: resolveTipSha(projectRoot, baseBranch),
141
+ laneTip: resolveTipSha(projectRoot, taskBranch),
142
+ }),
143
+ );
144
+ } catch (err) {
145
+ const message = err instanceof Error ? err.message : String(err);
146
+ return { ok: false, error: `salvage_evidence_write_failed: ${message}` };
147
+ }
148
+
149
+ const batchState = loadSalvageBatchSeed(projectRoot, batchId);
150
+ try {
151
+ const opened = openIntegrateGate({ projectRoot, batchId, batchState, config });
152
+ const gate = loadGateRecord(projectRoot, batchId);
153
+ if (!gate || !Array.isArray(gate.evidenceRefs) || gate.evidenceRefs.length === 0) {
154
+ return { ok: false, error: "gate_open_verification_failed" };
155
+ }
156
+
157
+ // Respect approval posture — auto-approves only when config opts in.
158
+ maybeAutoApproveIntegrateGate({ projectRoot, batchId, config });
159
+
160
+ appendJournalEvent(projectRoot, batchId, "batch.salvage_gate_opened", {
161
+ laneNumber: lane.laneNumber,
162
+ taskBranch,
163
+ baseBranch,
164
+ commitsAhead,
165
+ gateId: gate.gateId,
166
+ gateAlreadyOpen: opened.opened !== true,
167
+ salvageEvidenceRefs,
168
+ });
169
+
170
+ return {
171
+ ok: true,
172
+ opened: opened.opened === true,
173
+ gate: loadGateRecord(projectRoot, batchId) ?? gate,
174
+ evidenceRefs: gate.evidenceRefs,
175
+ };
176
+ } catch (err) {
177
+ const message = err instanceof Error ? err.message : String(err);
178
+ return { ok: false, error: `gate_open_failed: ${message}` };
179
+ }
180
+ }
@@ -12,6 +12,10 @@ import { gitExec } from "./git-exec.mjs";
12
12
  import { mergeOrchIntoBaseIsolated, syncPlumbingMergePathsToWorktree } from "./integrate-worktree.mjs";
13
13
  import { appendJournalEvent } from "./journal.mjs";
14
14
  import { resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
15
+ import {
16
+ gateBlockedOnMissingGate,
17
+ openGateFromSalvageEvidence,
18
+ } from "./salvage-batch-integrate-gate.mjs";
15
19
  import { laneTaskBranch } from "./worktree.mjs";
16
20
  import { listSalvageableLanes } from "./salvage-batch-list.mjs";
17
21
 
@@ -153,13 +157,54 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
153
157
  }
154
158
 
155
159
  const configResult = loadSpineConfig(projectRoot);
156
- const gateCheck = checkIntegrateGate({
160
+ const config = configResult.config ?? null;
161
+ let gateCheck = checkIntegrateGate({
157
162
  projectRoot,
158
163
  batchId: resolvedBatchId,
159
- config: configResult.config ?? null,
164
+ config,
160
165
  forceIntegrate,
161
166
  });
162
167
 
168
+ // #274 — a batch that failed before merge never opened the integrate gate,
169
+ // so the old path dead-ended on "no gate record". When the lane is salvageable,
170
+ // open a fresh gate from salvage evidence instead of failing.
171
+ let gateOpenedBySalvage = false;
172
+ if (!gateCheck.ok && gateBlockedOnMissingGate(gateCheck)) {
173
+ const openResult = openGateFromSalvageEvidence(projectRoot, resolvedBatchId, {
174
+ lane,
175
+ baseBranch,
176
+ taskBranch,
177
+ commitsAhead,
178
+ config,
179
+ });
180
+
181
+ if (!openResult.ok) {
182
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
183
+ laneNumber: laneNum,
184
+ taskBranch,
185
+ baseBranch,
186
+ gateBlocked: true,
187
+ gateStatus: "missing",
188
+ error: openResult.error,
189
+ });
190
+
191
+ return {
192
+ ok: false,
193
+ exitCode: 2,
194
+ failureClass: "GateBlocked",
195
+ error: openResult.error,
196
+ headline: "Salvage integrate blocked — could not open integrate gate from salvage evidence",
197
+ suggestedCommand: "spine status --diagnose",
198
+ alternatives: ["spine gate status"],
199
+ batchId: resolvedBatchId,
200
+ laneNumber: laneNum,
201
+ };
202
+ }
203
+
204
+ gateOpenedBySalvage = true;
205
+ gateCheck = checkIntegrateGate({ projectRoot, batchId: resolvedBatchId, config, forceIntegrate });
206
+ }
207
+
163
208
  if (!gateCheck.ok) {
164
209
  appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
165
210
  laneNumber: laneNum,
@@ -167,6 +212,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
167
212
  baseBranch,
168
213
  gateBlocked: true,
169
214
  gateStatus: gateCheck.gate?.status ?? "missing",
215
+ gateOpenedBySalvage,
170
216
  error: gateCheck.error ?? gateCheck.headline,
171
217
  });
172
218
 
@@ -175,12 +221,20 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
175
221
  exitCode: gateCheck.exitCode ?? 2,
176
222
  failureClass: gateCheck.failureClass ?? "GateBlocked",
177
223
  error: gateCheck.error,
178
- headline: gateCheck.headline ?? "Salvage integrate blocked by gate",
224
+ headline: gateOpenedBySalvage
225
+ ? "Salvage opened a fresh integrate gate — approve it, then re-run salvage integrate"
226
+ : gateCheck.headline ?? "Salvage integrate blocked by gate",
179
227
  suggestedCommand: gateCheck.suggestedCommand ?? "spine gate approve",
180
- alternatives: gateCheck.alternatives ?? ["/spine-gate approve"],
228
+ alternatives: gateOpenedBySalvage
229
+ ? [
230
+ "/spine-gate approve",
231
+ `spine batch salvage --batch ${resolvedBatchId} --lane ${laneNum} --integrate --yes`,
232
+ ]
233
+ : gateCheck.alternatives ?? ["/spine-gate approve"],
181
234
  batchId: resolvedBatchId,
182
235
  laneNumber: laneNum,
183
236
  gate: gateCheck.gate ?? null,
237
+ gateOpenedBySalvage,
184
238
  };
185
239
  }
186
240
 
@@ -261,6 +315,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
261
315
  excludedTasks: lane.excludedTasks,
262
316
  gateRequired: gateCheck.required ?? false,
263
317
  gateForced: gateCheck.forced ?? false,
318
+ gateOpenedBySalvage,
264
319
  });
265
320
 
266
321
  const mergeResult = mergeOrchIntoBaseIsolated({
@@ -351,6 +406,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
351
406
  commitsAhead,
352
407
  salvageableTasks: lane.salvageableTasks,
353
408
  excludedTasks: lane.excludedTasks,
409
+ gateOpenedBySalvage,
354
410
  headline: `Salvaged lane ${laneNum} (${taskBranch}) into ${baseBranch}`,
355
411
  suggestedCommand: "spine status --diagnose",
356
412
  };
@@ -375,6 +431,12 @@ export function formatSalvageIntegrateOutput(result, options = {}) {
375
431
  if (result.error) {
376
432
  lines.push("", ` Error: ${result.error}`);
377
433
  }
434
+ if (result.gateOpenedBySalvage) {
435
+ lines.push(
436
+ "",
437
+ " Gate: opened by salvage from inspection evidence (evidence/salvage-inspect.json)",
438
+ );
439
+ }
378
440
  if (result.batchId) {
379
441
  lines.push("", ` Batch: ${result.batchId}`);
380
442
  }
@@ -10,6 +10,7 @@ import {
10
10
  checkpointSignalsChanged,
11
11
  collectProgressSignals,
12
12
  computeStallDeadline,
13
+ isStaticNullProgressSnapshot,
13
14
  recordCheckpointWarning,
14
15
  recordLaneHeartbeat,
15
16
  recordLaneProgressSnapshot,
@@ -326,12 +327,21 @@ export async function pollWorkerUntilSettled({
326
327
  heartbeatKind,
327
328
  }),
328
329
  );
329
- stallAnchorAt = nextStallAnchorAt({
330
- stallAnchorAt,
331
- now,
332
- workerPhase,
333
- heartbeatKind,
334
- });
330
+ // Issue #272: a worker_alive heartbeat whose progress snapshot is static-null
331
+ // (statusMtimeMs / lastCommitAtMs / fileScopeMtimeMs null, dirtyPathCount 0, all
332
+ // unchanged) carries no progress evidence. The engine emits heartbeats itself
333
+ // while the child merely has not exited, so child liveness alone must not
334
+ // refresh the stall anchor — a SIGSTOP-style hung worker would otherwise slide
335
+ // the stall deadline forward forever and never journal stall events.
336
+ const staticNullProgress = isStaticNullProgressSnapshot(signals);
337
+ if (!(heartbeatKind === "worker_alive" && staticNullProgress)) {
338
+ stallAnchorAt = nextStallAnchorAt({
339
+ stallAnchorAt,
340
+ now,
341
+ workerPhase,
342
+ heartbeatKind,
343
+ });
344
+ }
335
345
  onHeartbeat?.(now);
336
346
  lastHeartbeatAt = now;
337
347
  }
@@ -344,6 +354,21 @@ export async function pollWorkerUntilSettled({
344
354
  });
345
355
 
346
356
  if (now >= stallDeadline) {
357
+ // SP-738 (#273): .DONE can be written between the loop-top check and this
358
+ // deadline check. A worker that has completed its contract is not a stall —
359
+ // hand it back to the done branch, which honors the post-done grace before
360
+ // any termination. Workers without .DONE keep the strict stall path (#272).
361
+ if (fs.existsSync(donePath)) {
362
+ if (projectRoot && batchId) {
363
+ appendJournalEvent(projectRoot, batchId, "worker.done_honored_at_stall", {
364
+ laneNumber,
365
+ taskId,
366
+ correlationId: laneCorrelationId,
367
+ stallDeadline,
368
+ });
369
+ }
370
+ continue;
371
+ }
347
372
  if (!stallWarningSent && projectRoot && batchId) {
348
373
  recordStallWarning({
349
374
  projectRoot,
@@ -36,6 +36,15 @@ export { buildWorkerChildEnv } from "./worker-spawn.mjs";
36
36
 
37
37
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
38
38
 
39
+ /**
40
+ * Exit code the worker runner uses when the `pi` spawn hits its wall-clock
41
+ * budget (ETIMEDOUT). Must stay in sync with bin/spine-worker-runner.mjs.
42
+ * Engine-initiated kills surface as exit code 1 (signal → `code ?? 1` in
43
+ * collectChildOutput), so 124 only ever originates from the runner's own
44
+ * timeout — never from post-done or stall termination.
45
+ */
46
+ const WORKER_TIMEOUT_EXIT_CODE = 124;
47
+
39
48
  /**
40
49
  * Force-terminate lane worker process trees tracked in batch state.
41
50
  * Reaps nested `pi` grandchildren, not only the tracked runner PID (SP-609 / #194).
@@ -326,7 +335,24 @@ export async function runWorker({
326
335
  config,
327
336
  });
328
337
  }
329
- const ok = doneFound && (exitCode === 0 || postDoneTerminated);
338
+ // SP-738 (#273): the runner exits 124 when the `pi` spawn hit its wall-clock
339
+ // budget (ETIMEDOUT). If the agent had already written .DONE, the task is done —
340
+ // do not classify a completed worker as timeout-failed. Post-done termination
341
+ // already resolves via postDoneTerminated, and true stalls never reach this
342
+ // boundary with .DONE absent (#272 keeps them failing).
343
+ const timedOutAfterDone =
344
+ doneFound && !postDoneTerminated && exitCode === WORKER_TIMEOUT_EXIT_CODE;
345
+ if (timedOutAfterDone && projectRoot && batchId) {
346
+ appendJournalEvent(projectRoot, batchId, "worker.done_after_timeout", {
347
+ laneNumber,
348
+ taskId,
349
+ correlationId: laneCorrelationId,
350
+ exitCode,
351
+ mode: workerMode,
352
+ });
353
+ }
354
+ const ok =
355
+ doneFound && (exitCode === 0 || postDoneTerminated || timedOutAfterDone);
330
356
  let classification = ok ? "succeeded" : "failed";
331
357
  if (!ok && useLaunchScript && !childPastPreflight) {
332
358
  classification = "launch_failed";
@@ -360,6 +360,62 @@ export function finalizeWorkerOutput({
360
360
  };
361
361
  }
362
362
 
363
+ /**
364
+ * Targeted `worker_done_missing` hint for backgrounded verifications (SP-741, #276).
365
+ * A worker that exits while a long verification is still running (waiting on a
366
+ * completion wake) cannot be resumed — the session dies with the turn.
367
+ */
368
+ export const BACKGROUND_VERIFICATION_HINT =
369
+ "backgrounded verification detected — long verifications must run in the foreground and finish in-session before .DONE";
370
+
371
+ /** Output phrases that on their own indicate background-and-exit behavior. */
372
+ const BACKGROUND_VERIFICATION_STRONG_MARKERS = [
373
+ "completion wake",
374
+ "running in the background",
375
+ "background monitor",
376
+ "backgrounded",
377
+ "monitorcreate",
378
+ ];
379
+
380
+ /** Output phrases indicating a verification has not finished yet. */
381
+ const BACKGROUND_VERIFICATION_PENDING_MARKERS = [
382
+ "still running",
383
+ "still in progress",
384
+ "not finished",
385
+ "hasn't finished",
386
+ "has not finished",
387
+ ];
388
+
389
+ /** Phrases that pair with pending work to indicate it was detached/backgrounded. */
390
+ const BACKGROUND_VERIFICATION_CONTEXT_MARKERS = [
391
+ "background",
392
+ "wake",
393
+ "monitor",
394
+ "redirected",
395
+ "detached",
396
+ ];
397
+
398
+ /**
399
+ * Detect worker output suggesting a long verification was backgrounded instead
400
+ * of run in the foreground (#276). Matched against the captured output tail
401
+ * at `worker_done_missing` diagnosis time; advisory only.
402
+ *
403
+ * @param {string|null|undefined} outputText
404
+ * @returns {boolean}
405
+ */
406
+ export function detectBackgroundedVerification(outputText) {
407
+ if (!outputText || !String(outputText).trim()) return false;
408
+ const normalized = String(outputText).toLowerCase();
409
+ if (BACKGROUND_VERIFICATION_STRONG_MARKERS.some((marker) => normalized.includes(marker))) {
410
+ return true;
411
+ }
412
+ const hasPending = BACKGROUND_VERIFICATION_PENDING_MARKERS.some((marker) =>
413
+ normalized.includes(marker),
414
+ );
415
+ if (!hasPending) return false;
416
+ return BACKGROUND_VERIFICATION_CONTEXT_MARKERS.some((marker) => normalized.includes(marker));
417
+ }
418
+
363
419
  /**
364
420
  * Parse a `.DONE` marker body. Legacy empty/text markers remain valid (SP-321).
365
421
  *
@@ -120,3 +120,27 @@ export function applyMatrixRowToSteps(steps, row) {
120
120
  body: substituteMatrixVariables(step.body, row),
121
121
  }));
122
122
  }
123
+
124
+ /**
125
+ * Substitute `{matrix.<column>}` placeholders across an entire raw PROMPT.md
126
+ * document for one matrix row. This is the LLM-row serving vehicle (#232):
127
+ * workers consume the raw markdown, so whole-document substitution is the
128
+ * composition of `applyMatrixRowToSteps` (step titles/bodies),
129
+ * `applyMatrixRowToContract` (contract table fields), and the File Scope paths
130
+ * in a single pass, with the same fail-loud semantics via
131
+ * `substituteMatrixVariables` — an unknown `{matrix.X}` reference throws.
132
+ *
133
+ * The input is returned unchanged when no row is supplied or the row is empty
134
+ * (non-matrix tasks keep their PROMPT verbatim), mirroring the guards on the
135
+ * structured helpers.
136
+ *
137
+ * @param {string} promptText Raw PROMPT.md content.
138
+ * @param {Record<string, string> | null | undefined} row Matrix row values keyed by column.
139
+ * @returns {string}
140
+ */
141
+ export function applyMatrixRowToPrompt(promptText, row) {
142
+ if (typeof promptText !== "string" || !row || Object.keys(row).length === 0) {
143
+ return promptText;
144
+ }
145
+ return substituteMatrixVariables(promptText, row);
146
+ }