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.
@@ -4,18 +4,15 @@
4
4
  */
5
5
  import {
6
6
  buildWorkerDoneMissingHeadline,
7
- buildWorkerDoneMissingSuggestedCommand,
8
7
  } from "./diagnosis-worker-done-missing.mjs";
9
8
  import {
10
9
  buildFailedPhasePendingOnlyHeadline,
11
- buildFailedPhasePendingOnlySuggestedCommand,
12
10
  isFailedPhasePendingOnlyLimbo,
13
11
  } from "./diagnosis-retry-limbo.mjs";
14
12
  import { buildAlternatives } from "./diagnosis-alternatives.mjs";
15
13
  export { buildAlternatives } from "./diagnosis-alternatives.mjs";
16
14
  import {
17
15
  buildMergeFailureHeadline,
18
- buildGitignoredMergeRepairCommand,
19
16
  shouldPreferPrimaryOverGitignoredHeadline,
20
17
  } from "./diagnosis-merge-failure.mjs";
21
18
  export {
@@ -36,7 +33,6 @@ export {
36
33
  export { buildReviewHonorHeadlineSuffix, findLatestReviewHonorSignal } from "./review.mjs";
37
34
  import {
38
35
  buildStubFailureHeadline,
39
- buildStubFailureSuggestedCommand,
40
36
  STUB_EXIT_REASONS,
41
37
  } from "./diagnosis-stub.mjs";
42
38
  /** @typedef {import("./reconcile.mjs").ReconciliationResult} ReconciliationResult */
@@ -48,11 +44,9 @@ export {
48
44
  } from "./diagnosis-task-done.mjs";
49
45
  import {
50
46
  buildPrimaryFailureHeadline,
51
- buildPrimaryFailureSuggestedCommand,
52
47
  } from "./diagnosis-primary-failure.mjs";
53
48
  import {
54
49
  buildEngineOrphanParentExitHeadline,
55
- buildEngineOrphanParentExitSuggestedCommand,
56
50
  } from "./diagnosis-parent-exit.mjs";
57
51
  export {
58
52
  inferEngineOrphanCause,
@@ -63,11 +57,9 @@ import { buildReviewHonorHeadlineSuffix } from "./review.mjs";
63
57
  export { inferLaunchFailureFromWorkerOutputTail, inferLaunchFailureKind } from "./diagnosis-launch-failure.mjs";
64
58
  import { isGateReadyHeadlineContext } from "./diagnosis-gate-ready.mjs";
65
59
  export { isGateReadyHeadlineContext };
66
- import { sanitizeRetrySuggestedCommand } from "./diagnosis-retry-command.mjs";
67
- export { sanitizeRetrySuggestedCommand };
60
+ export { sanitizeRetrySuggestedCommand } from "./diagnosis-retry-command.mjs";
68
61
  import {
69
62
  buildPendingLaneLandHeadline,
70
- buildPendingLaneLandSuggestedCommand,
71
63
  } from "./diagnosis-pending-lane.mjs";
72
64
  export {
73
65
  buildPendingLaneLandHeadline,
@@ -75,6 +67,10 @@ export {
75
67
  findPendingLaneLandTasks,
76
68
  shouldDiagnosePendingLaneLand,
77
69
  } from "./diagnosis-pending-lane.mjs";
70
+ export { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
71
+ import { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
72
+ export { buildBackground, buildAssessmentReason } from "./diagnosis-handoff-packet.mjs";
73
+ import { buildBackground, buildAssessmentReason } from "./diagnosis-handoff-packet.mjs";
78
74
 
79
75
  export const DIAGNOSIS_TAXONOMY = [
80
76
  "running",
@@ -113,162 +109,6 @@ const REVIEW_SPAWN_FAILURE_EXIT_REASONS = new Set([
113
109
  "final_review_timeout",
114
110
  ]);
115
111
 
116
- /**
117
- * @param {string} diagnosis
118
- * @param {object} [ctx]
119
- * @param {string|null} [ctx.failedTaskId]
120
- * @param {string|null} [ctx.batchId]
121
- * @param {string|null} [ctx.salvageRetryCommand]
122
- * @param {string|null} [ctx.exitReason]
123
- * @param {string|null} [ctx.launchFailureKind]
124
- * @param {boolean} [ctx.mergeGitignoredFailure]
125
- * @param {boolean} [ctx.mergeFailed]
126
- * @param {string|null} [ctx.taskBranch]
127
- * @param {string[]|null} [ctx.gitignoredPaths]
128
- * @param {object[]} [ctx.pendingLaneLandTasks]
129
- */
130
- export function buildSuggestedCommand(diagnosis, ctx = {}) {
131
- const preferPrimaryOverGitignored = shouldPreferPrimaryOverGitignoredHeadline(diagnosis, ctx);
132
- // Prefer gate-approve / orphan primary over recovered merge/gitignored repair (#195 / #205).
133
- if (ctx.mergeGitignoredFailure && !preferPrimaryOverGitignored) {
134
- return buildGitignoredMergeRepairCommand(ctx.taskBranch, ctx.gitignoredPaths);
135
- }
136
- if (
137
- ctx.mergeFailed &&
138
- !preferPrimaryOverGitignored &&
139
- (diagnosis === "failed" || diagnosis === "needs_retry")
140
- ) {
141
- return "spine batch resume --force";
142
- }
143
- if (ctx.phase === "merge_blocked") {
144
- return "spine batch resume --force";
145
- }
146
-
147
- switch (diagnosis) {
148
- case "engine_still_running":
149
- return "spine wait --until completed,failed,needs_integrate --timeout 2h";
150
- case "limbo_stale":
151
- case "completed_manual":
152
- return "spine batch dismiss";
153
- case "state_drift":
154
- // Agent-safe detached recovery (#196 / SP-613) — never suggest --attached.
155
- if (
156
- ctx.phase === "running" ||
157
- ctx.staleEnginePid === true ||
158
- ctx.engineDead === true ||
159
- ctx.allTasksTerminalSuccess === true
160
- ) {
161
- return "spine batch resume --force";
162
- }
163
- if (ctx.failedTaskId) {
164
- const driftStatus = String(ctx.driftTaskStatus ?? "").toLowerCase();
165
- if (driftStatus === "running") {
166
- return "spine batch resume --force";
167
- }
168
- return `spine batch retry ${ctx.failedTaskId}`;
169
- }
170
- return "spine status --diagnose";
171
- case "needs_retry":
172
- if (STUB_EXIT_REASONS.has(ctx.exitReason ?? "")) {
173
- return buildStubFailureSuggestedCommand(ctx);
174
- }
175
- const primaryCommand = buildPrimaryFailureSuggestedCommand(ctx);
176
- if (primaryCommand) return primaryCommand;
177
- if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
178
- return "spine doctor";
179
- }
180
- if (ctx.launchFailureKind === "worktree_unhealthy") {
181
- return "spine doctor";
182
- }
183
- if (ctx.salvageRetryCommand) {
184
- return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
185
- }
186
- if (isFailedPhasePendingOnlyLimbo(ctx)) {
187
- return buildFailedPhasePendingOnlySuggestedCommand(ctx);
188
- }
189
- return ctx.failedTaskId
190
- ? `spine batch retry ${ctx.failedTaskId}`
191
- : "spine status --diagnose";
192
- case "worker_orphaned":
193
- if (ctx.planReviewNestedSpawnBlocked) {
194
- if (ctx.stalePathSpine) {
195
- return ctx.failedTaskId
196
- ? `node bin/spine.mjs batch retry ${ctx.failedTaskId}`
197
- : "npm link && spine batch resume --attached";
198
- }
199
- if (ctx.failedTaskId) {
200
- return `spine batch retry ${ctx.failedTaskId}`;
201
- }
202
- }
203
- if (ctx.engineDead) {
204
- return "spine batch resume --attached --force";
205
- }
206
- if (ctx.ghostRunningCluster) return "spine batch abort";
207
- if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
208
- return "spine doctor";
209
- }
210
- if (ctx.launchFailureKind === "worktree_unhealthy") {
211
- return "spine doctor";
212
- }
213
- if (ctx.salvageRetryCommand) {
214
- return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
215
- }
216
- return ctx.failedTaskId
217
- ? `spine batch retry ${ctx.failedTaskId}`
218
- : "spine batch abort";
219
- case "worker_done_missing":
220
- return buildWorkerDoneMissingSuggestedCommand(ctx);
221
- case "engine_orphaned": {
222
- const parentExitCommand = buildEngineOrphanParentExitSuggestedCommand(ctx);
223
- if (parentExitCommand) return parentExitCommand;
224
- // Terminal-success / doneInLane heal with dead engine — detached resume (#196 / #163).
225
- if (ctx.allTasksTerminalSuccess === true) {
226
- return "spine batch resume --force";
227
- }
228
- return ctx.failedTaskId
229
- ? `spine batch retry ${ctx.failedTaskId}`
230
- : "spine batch resume --attached";
231
- }
232
- case "needs_merge":
233
- return "spine batch resume --force";
234
- case "needs_integrate":
235
- if (ctx.integrateGateOpen) {
236
- return "spine gate approve";
237
- }
238
- if (ctx.postMergeLimbo && ctx.phase === "running") {
239
- if (ctx.stalePathSpine) {
240
- return "node bin/spine.mjs batch resume --attached";
241
- }
242
- return "spine batch resume --force";
243
- }
244
- return "spine integrate";
245
- case "needs_replan": {
246
- const tasksRoot = ctx.tasksRoot ?? "spine-tasks";
247
- return ctx.failedTaskId
248
- ? `edit ${tasksRoot}/${ctx.failedTaskId}/PROMPT.md then spine batch retry ${ctx.failedTaskId}`
249
- : "spine status --diagnose";
250
- }
251
- case "running":
252
- return "/spine-status --diagnose";
253
- case "paused":
254
- return "spine batch resume";
255
- case "failed":
256
- return "spine status --diagnose";
257
- case "aborted":
258
- return "spine batch dismiss";
259
- case "completed":
260
- return "spine preflight";
261
- case "human_base_diverged":
262
- return "spine sync-base";
263
- case "integrate_isolated_ok":
264
- return "spine sync-base";
265
- case "pending_lane_land":
266
- return buildPendingLaneLandSuggestedCommand(ctx.batchId, ctx.pendingLaneLandTasks ?? []);
267
- default:
268
- return "spine status --diagnose";
269
- }
270
- }
271
-
272
112
  /**
273
113
  * @param {string} diagnosis
274
114
  * @param {object} ctx
@@ -340,13 +180,13 @@ export function buildHeadline(diagnosis, ctx = {}) {
340
180
  const isFinal = ctx.exitReason.startsWith("final_review");
341
181
  const isTimeout = ctx.exitReason.endsWith("_timeout");
342
182
  const reviewKind = isFinal ? "final review" : "code review";
343
-
183
+
344
184
  if (isTimeout) {
345
185
  return ctx.failedTaskId
346
186
  ? `${batchLabel} ${reviewKind} timed out for task ${ctx.failedTaskId} — retry or increase SPINE_REVIEW_TIMEOUT_MS`
347
187
  : `${batchLabel} reviewer spawn timed out — retry`;
348
188
  }
349
-
189
+
350
190
  return ctx.failedTaskId
351
191
  ? `${batchLabel} ${reviewKind} spawn failed for task ${ctx.failedTaskId} — retry`
352
192
  : `${batchLabel} reviewer spawn failed — retry`;
@@ -482,7 +322,7 @@ export function resolveEffectiveDiagnosis(diagnosis, ctx = {}) {
482
322
  /**
483
323
  * @param {string} diagnosis
484
324
  * @param {object} ctx
485
- * @returns {Pick<ReconciliationResult, "diagnosis" | "headline" | "suggestedCommand" | "alternatives">}
325
+ * @returns {Pick<ReconciliationResult, "diagnosis" | "headline" | "suggestedCommand" | "alternatives"> & { background: string[], assessmentReason: string }}
486
326
  */
487
327
  export function buildDiagnosisOutput(diagnosis, ctx = {}) {
488
328
  const effectiveDiagnosis = resolveEffectiveDiagnosis(diagnosis, ctx);
@@ -491,5 +331,9 @@ export function buildDiagnosisOutput(diagnosis, ctx = {}) {
491
331
  headline: buildHeadline(effectiveDiagnosis, ctx),
492
332
  suggestedCommand: buildSuggestedCommand(effectiveDiagnosis, ctx),
493
333
  alternatives: buildAlternatives(effectiveDiagnosis, ctx),
334
+ // Additive SBAR fields (#278 / SP-745) — appended after legacy keys so
335
+ // consumers reading positional or partial fields are unaffected.
336
+ background: buildBackground(effectiveDiagnosis, ctx),
337
+ assessmentReason: buildAssessmentReason(effectiveDiagnosis, ctx),
494
338
  };
495
339
  }
@@ -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