pi-spine 2.17.0 → 2.19.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.
@@ -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";