pi-spine 2.4.0 → 2.6.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.
Files changed (38) hide show
  1. package/bin/spine.mjs +22 -0
  2. package/package.json +1 -1
  3. package/src/batch/attached-runner-promote.mjs +95 -11
  4. package/src/batch/blocker-codes.mjs +63 -0
  5. package/src/batch/diagnosis-alternatives.mjs +18 -0
  6. package/src/batch/diagnosis-gate-ready.mjs +23 -0
  7. package/src/batch/diagnosis-pending-lane.mjs +63 -0
  8. package/src/batch/diagnosis-retry-command.mjs +23 -0
  9. package/src/batch/diagnosis-tail-state.mjs +68 -0
  10. package/src/batch/diagnosis.mjs +69 -52
  11. package/src/batch/engine-lanes/commit.mjs +2 -0
  12. package/src/batch/engine-lanes.mjs +2 -3
  13. package/src/batch/evidence-command.mjs +125 -4
  14. package/src/batch/gate-posture-approve.mjs +345 -0
  15. package/src/batch/gate-posture-defaults.mjs +64 -0
  16. package/src/batch/gate-posture-evaluate.mjs +133 -0
  17. package/src/batch/gate-posture-streak.mjs +290 -0
  18. package/src/batch/gate-revision.mjs +95 -0
  19. package/src/batch/gate.mjs +89 -117
  20. package/src/batch/integrate.mjs +1 -0
  21. package/src/batch/lane-commit.mjs +77 -8
  22. package/src/batch/lifecycle-archive.mjs +71 -0
  23. package/src/batch/lifecycle.mjs +27 -67
  24. package/src/batch/orphan-detect.mjs +68 -5
  25. package/src/batch/post-merge-limbo.mjs +137 -22
  26. package/src/batch/reconcile-batch.mjs +40 -43
  27. package/src/batch/reconcile-diagnosis-context.mjs +88 -0
  28. package/src/batch/reconcile-diagnosis.mjs +14 -32
  29. package/src/batch/resume-multi-validate.mjs +51 -9
  30. package/src/batch/retry.mjs +18 -2
  31. package/src/batch/sequence-wait.mjs +20 -6
  32. package/src/config/gate-posture-config.mjs +190 -0
  33. package/src/config/pi-spine-root.mjs +22 -0
  34. package/src/config/spine-config-load.mjs +33 -0
  35. package/src/doctor/duplicate-install.mjs +100 -0
  36. package/src/doctor/run-doctor-checks.mjs +10 -1
  37. package/src/doctor/worktree-health.mjs +4 -0
  38. package/templates/spine-config.json +3 -2
@@ -15,6 +15,7 @@ import {
15
15
  shouldEnforceStubContractAtLaneCommit,
16
16
  verifyStubFileScopeMustChange,
17
17
  } from "./contract-verify.mjs";
18
+ import { DEFAULT_WORKTREE_SETUP_IGNORE_PATHS } from "../config/spine-config-load.mjs";
18
19
 
19
20
  /**
20
21
  * @param {string} worktreePath
@@ -72,13 +73,50 @@ function pathMatchesIgnorePattern(filePath, pattern) {
72
73
  return path.posix.basename(normalizedPath) === normalizedPattern;
73
74
  }
74
75
 
76
+ /**
77
+ * Local fileScope check (avoid importing lane-dirty-check-git — circular via filterPorcelain).
78
+ *
79
+ * @param {string} filePath
80
+ * @param {string[]} [fileScopePaths]
81
+ */
82
+ function isPathInFileScope(filePath, fileScopePaths) {
83
+ if (!filePath || !Array.isArray(fileScopePaths) || fileScopePaths.length === 0) {
84
+ return false;
85
+ }
86
+ const normalizedPath = filePath.replace(/\\/g, "/");
87
+ for (const rel of fileScopePaths) {
88
+ if (!rel || typeof rel !== "string") continue;
89
+ const normalized = rel.replace(/\\/g, "/");
90
+ const prefix = normalized.endsWith("/") ? normalized : `${normalized}/`;
91
+ if (normalizedPath === normalized || normalizedPath.startsWith(prefix)) {
92
+ return true;
93
+ }
94
+ }
95
+ return false;
96
+ }
97
+
98
+ /**
99
+ * Hook ignore path unless task fileScope explicitly lists it (SP-640 / #200).
100
+ *
101
+ * @param {string} filePath
102
+ * @param {string[]} ignorePatterns
103
+ * @param {string[]} [fileScopePaths]
104
+ */
105
+ function shouldSkipHookIgnorePath(filePath, ignorePatterns, fileScopePaths) {
106
+ if (!Array.isArray(ignorePatterns) || ignorePatterns.length === 0) return false;
107
+ if (isPathInFileScope(filePath, fileScopePaths)) return false;
108
+ return ignorePatterns.some((pattern) => pathMatchesIgnorePattern(filePath, pattern));
109
+ }
110
+
75
111
  /**
76
112
  * Drop porcelain lines whose path matches any ignore pattern (basename or full path).
113
+ * Paths listed in `fileScopePaths` are kept even when they match ignore patterns.
77
114
  *
78
115
  * @param {string} porcelain
79
116
  * @param {string[]} ignorePatterns
117
+ * @param {string[]} [fileScopePaths]
80
118
  */
81
- export function filterPorcelain(porcelain, ignorePatterns) {
119
+ export function filterPorcelain(porcelain, ignorePatterns, fileScopePaths = []) {
82
120
  if (!porcelain?.trim()) return "";
83
121
  if (!Array.isArray(ignorePatterns) || ignorePatterns.length === 0) {
84
122
  return porcelain;
@@ -92,8 +130,8 @@ export function filterPorcelain(porcelain, ignorePatterns) {
92
130
  kept.push(line);
93
131
  continue;
94
132
  }
95
- const ignored = ignorePatterns.some((pattern) => pathMatchesIgnorePattern(filePath, pattern));
96
- if (!ignored) kept.push(line);
133
+ if (shouldSkipHookIgnorePath(filePath, ignorePatterns, fileScopePaths)) continue;
134
+ kept.push(line);
97
135
  }
98
136
  return kept.length === 0 ? "" : kept.join("\n");
99
137
  }
@@ -152,7 +190,9 @@ function listPorcelainPaths(porcelain) {
152
190
  * @param {string} params.taskFolder Absolute path to task folder (for `.DONE` check)
153
191
  * @param {string} [params.projectRoot] Main repo root for git identity resolution
154
192
  * @param {string} [params.baseBranch] Base branch for stub contract diff (default main)
155
- * @returns {{ ok: true, committed: boolean, commitSha?: string, skippedGitignoredPaths?: string[] } | { ok: false, error: string, failureClass: string, gitignoredPaths?: string[] }}
193
+ * @param {string[]} [params.ignorePatterns] Hook paths to skip (default includes `.venv`)
194
+ * @param {string[]} [params.fileScopePaths] Task fileScope — paths here are never skipped
195
+ * @returns {{ ok: true, committed: boolean, commitSha?: string, skippedGitignoredPaths?: string[], skippedIgnorePaths?: string[] } | { ok: false, error: string, failureClass: string, gitignoredPaths?: string[] }}
156
196
  */
157
197
  export function commitLaneWorktree({
158
198
  worktreePath,
@@ -162,14 +202,30 @@ export function commitLaneWorktree({
162
202
  taskFolder,
163
203
  projectRoot,
164
204
  baseBranch = "main",
205
+ ignorePatterns,
206
+ fileScopePaths = [],
165
207
  }) {
166
208
  const identityRoot = projectRoot ?? worktreePath;
209
+ const effectiveIgnorePatterns = Array.isArray(ignorePatterns)
210
+ ? ignorePatterns
211
+ : [...DEFAULT_WORKTREE_SETUP_IGNORE_PATHS];
167
212
  try {
168
213
  const porcelain = gitPorcelain(worktreePath);
169
214
  const dirtyPaths = listPorcelainPaths(porcelain);
215
+ const skippedIgnorePaths = dirtyPaths.filter((filePath) =>
216
+ shouldSkipHookIgnorePath(filePath, effectiveIgnorePatterns, fileScopePaths),
217
+ );
218
+ const stageCandidatePaths = dirtyPaths.filter(
219
+ (filePath) => !shouldSkipHookIgnorePath(filePath, effectiveIgnorePatterns, fileScopePaths),
220
+ );
170
221
  const ignoredUntrackedPaths = listIgnoredUntrackedPaths(worktreePath);
171
- if (dirtyPaths.length === 0 && ignoredUntrackedPaths.length === 0) {
172
- return { ok: true, committed: false };
222
+ // Only-hook-noise dirty (e.g. untracked `.venv` symlink) is not a DirtyWorktree failure.
223
+ if (stageCandidatePaths.length === 0 && ignoredUntrackedPaths.length === 0) {
224
+ return {
225
+ ok: true,
226
+ committed: false,
227
+ skippedIgnorePaths,
228
+ };
173
229
  }
174
230
 
175
231
  const donePath = path.join(taskFolder, ".DONE");
@@ -191,7 +247,7 @@ export function commitLaneWorktree({
191
247
  worktreePath,
192
248
  parsedContract,
193
249
  baseBranch,
194
- dirtyPaths,
250
+ stageCandidatePaths,
195
251
  );
196
252
  if (!scopeCheck.ok) {
197
253
  return {
@@ -203,7 +259,10 @@ export function commitLaneWorktree({
203
259
  }
204
260
  }
205
261
 
206
- const { stageable, skipped: gitignoredDirtyPaths } = filterGitignoredPaths(worktreePath, dirtyPaths);
262
+ const { stageable, skipped: gitignoredDirtyPaths } = filterGitignoredPaths(
263
+ worktreePath,
264
+ stageCandidatePaths,
265
+ );
207
266
  const gitignoredPaths = [...new Set([...gitignoredDirtyPaths, ...ignoredUntrackedPaths])];
208
267
  if (stageable.length === 0 && gitignoredPaths.length > 0) {
209
268
  const { indexTracked, worktreeOnly } = classifyGitignoredPaths(worktreePath, gitignoredPaths);
@@ -215,6 +274,15 @@ export function commitLaneWorktree({
215
274
  };
216
275
  }
217
276
 
277
+ if (stageable.length === 0) {
278
+ return {
279
+ ok: true,
280
+ committed: false,
281
+ skippedIgnorePaths,
282
+ skippedGitignoredPaths: gitignoredPaths,
283
+ };
284
+ }
285
+
218
286
  const currentBranch = git(worktreePath, ["rev-parse", "--abbrev-ref", "HEAD"], identityRoot);
219
287
  if (currentBranch !== taskBranch) {
220
288
  git(worktreePath, ["checkout", taskBranch], identityRoot);
@@ -228,6 +296,7 @@ export function commitLaneWorktree({
228
296
  committed: true,
229
297
  commitSha,
230
298
  skippedGitignoredPaths: [...addResult.skipped, ...gitignoredPaths],
299
+ skippedIgnorePaths,
231
300
  };
232
301
  } catch (err) {
233
302
  const message = err instanceof Error ? err.message : String(err);
@@ -0,0 +1,71 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Batch lifecycle archive and worktree cleanup helpers (FR-BATCH-15/16).
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { appendJournalEvent } from "./journal.mjs";
9
+ import { clearActiveBatchStateIfMatches } from "./batch-state-io.mjs";
10
+ import { removeLaneWorktrees, maxLaneNumberFromBatchState } from "./worktree.mjs";
11
+
12
+ /**
13
+ * @param {string} projectRoot
14
+ * @param {string} batchId
15
+ */
16
+ export function archiveBatchStatePath(projectRoot, batchId) {
17
+ return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
18
+ }
19
+
20
+ /**
21
+ * @param {string} projectRoot
22
+ * @param {string} batchId
23
+ * @param {unknown} raw
24
+ */
25
+ export function archiveBatchState(projectRoot, batchId, raw) {
26
+ const archivePath = archiveBatchStatePath(projectRoot, batchId);
27
+ fs.mkdirSync(path.dirname(archivePath), { recursive: true });
28
+ fs.writeFileSync(archivePath, `${JSON.stringify(raw, null, 2)}\n`, "utf-8");
29
+
30
+ const fd = fs.openSync(archivePath, "r");
31
+ try {
32
+ fs.fsyncSync(fd);
33
+ } finally {
34
+ fs.closeSync(fd);
35
+ }
36
+
37
+ return archivePath;
38
+ }
39
+
40
+ /**
41
+ * @param {string|null} batchStatePath
42
+ * @param {string} batchId
43
+ */
44
+ export function clearCompletedBatchState(batchStatePath, batchId) {
45
+ clearActiveBatchStateIfMatches(batchStatePath, batchId);
46
+ }
47
+
48
+ /**
49
+ * @param {object|null|undefined} config
50
+ */
51
+ function shouldCleanupWorktreesOnComplete(config) {
52
+ if (config?.lanes?.cleanupWorktreesOnComplete === false) return false;
53
+ return true;
54
+ }
55
+
56
+ /**
57
+ * @param {object} params
58
+ * @param {string} params.projectRoot
59
+ * @param {string} params.batchId
60
+ * @param {unknown} params.batchState
61
+ * @param {object} params.config
62
+ */
63
+ export function cleanupBatchLaneWorktrees({ projectRoot, batchId, batchState, config }) {
64
+ if (!shouldCleanupWorktreesOnComplete(config)) return;
65
+ const laneCount = maxLaneNumberFromBatchState(batchState);
66
+ removeLaneWorktrees(projectRoot, batchId, laneCount);
67
+ appendJournalEvent(projectRoot, batchId, "batch.worktrees_cleaned", {
68
+ batchId,
69
+ laneCount,
70
+ });
71
+ }
@@ -3,9 +3,18 @@
3
3
  * Batch lifecycle: dismiss, complete, archive-first (FR-BATCH-15/16, §18.6).
4
4
  */
5
5
 
6
- import fs from "node:fs";
7
6
  import path from "node:path";
8
7
  import { buildDiagnosisOutput } from "./diagnosis.mjs";
8
+ import {
9
+ buildPendingLaneLandSuggestedCommand,
10
+ findPendingLaneLandTasks,
11
+ } from "./diagnosis-pending-lane.mjs";
12
+ import {
13
+ archiveBatchState,
14
+ cleanupBatchLaneWorktrees,
15
+ clearCompletedBatchState,
16
+ } from "./lifecycle-archive.mjs";
17
+ export { archiveBatchStatePath } from "./lifecycle-archive.mjs";
9
18
  import { assertOrchIntegratable } from "./integrate.mjs";
10
19
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
11
20
  import { appendJournalEvent } from "./journal.mjs";
@@ -13,12 +22,8 @@ import { recordBatchTerminalMetric } from "./metrics.mjs";
13
22
  import { writeBatchPostMortem } from "./postmortem.mjs";
14
23
  import { appendBatchHistoryEntry, clearBatchEnginePid, saveSpineBatchState } from "./state.mjs";
15
24
  import { loadBatchStateFile, parseBatchState, reconcileBatch } from "./reconcile.mjs";
16
- import {
17
- clearActiveBatchStateIfMatches,
18
- readAliveBatchEnginePid,
19
- } from "./batch-state-io.mjs";
25
+ import { readAliveBatchEnginePid } from "./batch-state-io.mjs";
20
26
  import { terminateLaneWorkers } from "./worker-host.mjs";
21
- import { removeLaneWorktrees, maxLaneNumberFromBatchState } from "./worktree.mjs";
22
27
  import { terminateSupervisorIfRunning } from "./supervisor-spawn.mjs";
23
28
  import { bumpDashboardInvalidateSignal } from "../dashboard/cache-invalidate.mjs";
24
29
 
@@ -81,67 +86,6 @@ export function recordMergeBlocked({
81
86
  };
82
87
  }
83
88
 
84
- /**
85
- * @param {string} projectRoot
86
- * @param {string} batchId
87
- */
88
- export function archiveBatchStatePath(projectRoot, batchId) {
89
- return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
90
- }
91
-
92
- /**
93
- * @param {string} projectRoot
94
- * @param {string} batchId
95
- * @param {unknown} raw
96
- */
97
- function archiveBatchState(projectRoot, batchId, raw) {
98
- const archivePath = archiveBatchStatePath(projectRoot, batchId);
99
- fs.mkdirSync(path.dirname(archivePath), { recursive: true });
100
- fs.writeFileSync(archivePath, `${JSON.stringify(raw, null, 2)}\n`, "utf-8");
101
-
102
- const fd = fs.openSync(archivePath, "r");
103
- try {
104
- fs.fsyncSync(fd);
105
- } finally {
106
- fs.closeSync(fd);
107
- }
108
-
109
- return archivePath;
110
- }
111
-
112
- /**
113
- * @param {string|null} batchStatePath
114
- * @param {string} batchId
115
- */
116
- function clearCompletedBatchState(batchStatePath, batchId) {
117
- clearActiveBatchStateIfMatches(batchStatePath, batchId);
118
- }
119
-
120
- /**
121
- * @param {object|null|undefined} config
122
- */
123
- function shouldCleanupWorktreesOnComplete(config) {
124
- if (config?.lanes?.cleanupWorktreesOnComplete === false) return false;
125
- return true;
126
- }
127
-
128
- /**
129
- * @param {object} params
130
- * @param {string} params.projectRoot
131
- * @param {string} params.batchId
132
- * @param {unknown} params.batchState
133
- * @param {object} params.config
134
- */
135
- function cleanupBatchLaneWorktrees({ projectRoot, batchId, batchState, config }) {
136
- if (!shouldCleanupWorktreesOnComplete(config)) return;
137
- const laneCount = maxLaneNumberFromBatchState(batchState);
138
- removeLaneWorktrees(projectRoot, batchId, laneCount);
139
- appendJournalEvent(projectRoot, batchId, "batch.worktrees_cleaned", {
140
- batchId,
141
- laneCount,
142
- });
143
- }
144
-
145
89
  /**
146
90
  * @param {object} signals
147
91
  */
@@ -445,6 +389,22 @@ export function completeBatch(ctx) {
445
389
  };
446
390
  }
447
391
 
392
+ const pendingLaneLandTasks = findPendingLaneLandTasks(signals.tasks);
393
+ if (pendingLaneLandTasks.length > 0 && Boolean(signals.git?.orchMergedToBase)) {
394
+ const pendingTaskIds = pendingLaneLandTasks.map((task) => String(task.taskId ?? "")).filter(Boolean);
395
+ return {
396
+ ok: false,
397
+ exitCode: 1,
398
+ error: "pending_lane_land",
399
+ diagnosis: "pending_lane_land",
400
+ batchId,
401
+ pendingTaskIds,
402
+ headline: `Batch ${batchId} has lane work not on ${signals.git?.baseBranch ?? "main"} (${pendingTaskIds.join(", ")}) — complete refused`,
403
+ suggestedCommand: buildPendingLaneLandSuggestedCommand(batchId, pendingLaneLandTasks),
404
+ alternatives: ["spine status --diagnose", "spine batch salvage --batch <batchId> --dry-run"],
405
+ };
406
+ }
407
+
448
408
  terminateSupervisorIfRunning(projectRoot, batchId, "batch_complete");
449
409
 
450
410
  const archivePath = archiveBatchState(projectRoot, batchId, loaded.raw);
@@ -281,6 +281,43 @@ function hasFiniteWorkerPidForRunningTasks(lanes, runningTasks) {
281
281
  return false;
282
282
  }
283
283
 
284
+ /**
285
+ * No running task lane has a live worker PID (#203 multi-lane).
286
+ * Missing / non-finite workerPid counts as absent (not live).
287
+ *
288
+ * @param {unknown[]} lanes
289
+ * @param {Array<{ taskId?: string, laneNumber?: number|null }>} runningTasks
290
+ */
291
+ function noLiveWorkerPidForRunningTasks(lanes, runningTasks) {
292
+ if (runningTasks.length === 0) return false;
293
+ for (const task of runningTasks) {
294
+ const lane = findLane(lanes, task.laneNumber);
295
+ const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane)?.workerPid);
296
+ if (Number.isFinite(workerPid) && workerPid > 0 && isProcessAlive(workerPid)) {
297
+ return false;
298
+ }
299
+ }
300
+ return true;
301
+ }
302
+
303
+ /**
304
+ * Prefer the first running task whose lane worker PID is stale (dead-engine orphan #203).
305
+ *
306
+ * @param {Array<{ taskId: string, laneNumber?: number|null }>} runningTasks
307
+ * @param {unknown[]} lanes
308
+ * @returns {string|null}
309
+ */
310
+ function pickDeadEngineOrphanTaskId(runningTasks, lanes) {
311
+ for (const task of runningTasks) {
312
+ const lane = findLane(lanes, task.laneNumber);
313
+ const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane)?.workerPid);
314
+ if (Number.isFinite(workerPid) && workerPid > 0 && !isProcessAlive(workerPid)) {
315
+ return task.taskId;
316
+ }
317
+ }
318
+ return runningTasks[0]?.taskId ?? null;
319
+ }
320
+
284
321
  /**
285
322
  * @param {unknown[]} lanes
286
323
  * @param {number|null|undefined} laneNumber
@@ -318,6 +355,37 @@ export function detectOrphanRunning(ctx) {
318
355
  }
319
356
 
320
357
  const scopedJournalEvents = journalEventsSinceResume(ctx.journalEvents ?? [], ctx.raw);
358
+ const enginePid = readBatchEnginePid(ctx.raw);
359
+ const suppressPausedResumeEngineOrphan = shouldSuppressPausedResumeEngineOrphan(
360
+ ctx,
361
+ scopedJournalEvents,
362
+ );
363
+
364
+ // Dead or cleared engine + no live workers across multiple lanes → engine orphan (#203).
365
+ // Covers cleared enginePid and missing workerPid; single-lane stays lane/worker_orphaned.
366
+ // Only while phase is running — paused multi-lane must stay paused for resume DX.
367
+ const distinctRunningLanes = new Set(
368
+ runningTasks
369
+ .map((task) => (task.laneNumber == null ? null : Number(task.laneNumber)))
370
+ .filter((laneNumber) => Number.isFinite(laneNumber)),
371
+ );
372
+ const multiLaneRunning = distinctRunningLanes.size > 1;
373
+ const engineDeadOrCleared = enginePid == null || !isProcessAlive(enginePid);
374
+ if (
375
+ ctx.phase === "running" &&
376
+ multiLaneRunning &&
377
+ engineDeadOrCleared &&
378
+ !journalHasTerminalBatchEvent(scopedJournalEvents) &&
379
+ !suppressPausedResumeEngineOrphan &&
380
+ noLiveWorkerPidForRunningTasks(ctx.lanes, runningTasks)
381
+ ) {
382
+ /** @type {OrphanRunningSignal} */
383
+ return {
384
+ kind: "engine",
385
+ taskId: pickDeadEngineOrphanTaskId(runningTasks, ctx.lanes),
386
+ enginePid: enginePid ?? null,
387
+ };
388
+ }
321
389
 
322
390
  for (const task of runningTasks) {
323
391
  const lane = findLane(ctx.lanes, task.laneNumber);
@@ -347,11 +415,6 @@ export function detectOrphanRunning(ctx) {
347
415
  }
348
416
  }
349
417
 
350
- const enginePid = readBatchEnginePid(ctx.raw);
351
- const suppressPausedResumeEngineOrphan = shouldSuppressPausedResumeEngineOrphan(
352
- ctx,
353
- scopedJournalEvents,
354
- );
355
418
  if (
356
419
  enginePid &&
357
420
  !isProcessAlive(enginePid) &&
@@ -121,6 +121,105 @@ export function finalizeAttachedPostMergeLimbo({ projectRoot, state, batchId, or
121
121
  });
122
122
  }
123
123
 
124
+ /**
125
+ * @param {string} projectRoot
126
+ * @param {string} batchId
127
+ * @param {string} type
128
+ */
129
+ function journalHasEventType(projectRoot, batchId, type) {
130
+ if (!batchId) return false;
131
+ return readJournalEvents(projectRoot, batchId).some((event) => event.type === type);
132
+ }
133
+
134
+ /**
135
+ * Idempotent land-loop close after gate open or host integrate (#198 / SP-636).
136
+ * Clears engine PID and emits `batch.land_loop_finalized` so `spine batch complete`
137
+ * is not blocked while a resume engine is still mid-evidence or lingering.
138
+ *
139
+ * @param {object} params
140
+ * @param {string} params.projectRoot
141
+ * @param {object} params.state
142
+ * @param {string} params.batchId
143
+ * @param {boolean} [params.resumed]
144
+ * @param {boolean} [params.resumeForced]
145
+ * @param {string} [params.source]
146
+ * @returns {{ ok: true, changed: boolean, batchId: string, exitCode: 0, shouldExit: boolean } | null}
147
+ */
148
+ export function ensureLandLoopFinalizedAfterGateOrIntegrate({
149
+ projectRoot,
150
+ state,
151
+ batchId,
152
+ resumed = false,
153
+ resumeForced = false,
154
+ source = "ensure_after_gate_or_integrate",
155
+ }) {
156
+ if (!state || typeof state !== "object" || !batchId) {
157
+ return null;
158
+ }
159
+
160
+ const gateRecord = loadGateRecord(projectRoot, batchId);
161
+ const integrateCompleted = journalHasEventType(projectRoot, batchId, "integrate.completed");
162
+ const gateApproved = gateRecord != null && String(gateRecord.status ?? "") === "approved";
163
+ const phaseCompleted = String(state.phase ?? "") === "completed";
164
+
165
+ if (!gateRecord && !integrateCompleted && !phaseCompleted) {
166
+ return null;
167
+ }
168
+
169
+ let changed = false;
170
+ const taskIds = (state.tasks ?? []).map((task) => task.taskId);
171
+
172
+ if (!phaseCompleted) {
173
+ state.endedAt = state.endedAt ?? Date.now();
174
+ state.phase = "completed";
175
+ changed = true;
176
+ }
177
+
178
+ if (!journalHasEventType(projectRoot, batchId, "batch.completed")) {
179
+ appendJournalEvent(projectRoot, batchId, "batch.completed", {
180
+ taskIds,
181
+ mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
182
+ resumed,
183
+ postMergeLimbo: !resumed,
184
+ resumeForced,
185
+ source,
186
+ });
187
+ changed = true;
188
+ }
189
+
190
+ if (state.resilience?.enginePid != null) {
191
+ clearBatchEnginePid(state);
192
+ changed = true;
193
+ }
194
+
195
+ if (!journalHasEventType(projectRoot, batchId, "batch.land_loop_finalized")) {
196
+ const finalizeSource = integrateCompleted
197
+ ? "host_integrate"
198
+ : gateApproved
199
+ ? "host_gate_approved"
200
+ : source;
201
+ appendJournalEvent(projectRoot, batchId, "batch.land_loop_finalized", {
202
+ resumed,
203
+ resumeForced,
204
+ gateId: gateRecord?.gateId ?? null,
205
+ source: finalizeSource,
206
+ });
207
+ changed = true;
208
+ }
209
+
210
+ if (changed) {
211
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
212
+ }
213
+
214
+ return {
215
+ ok: true,
216
+ changed,
217
+ batchId,
218
+ exitCode: 0,
219
+ shouldExit: integrateCompleted || gateApproved,
220
+ };
221
+ }
222
+
124
223
  /**
125
224
  * Open integrate gate or spawn detached resume before attached engine exit (SP-378, GitHub #59).
126
225
  *
@@ -148,10 +247,24 @@ export function finalizeAttachedLandLoopBeforeExit({
148
247
  const state = loaded.raw;
149
248
  const batchId = String(state.batchId ?? "");
150
249
  const orchBranch = String(state.orchBranch ?? "");
250
+ const gateExists = loadGateRecord(projectRoot, batchId) != null;
251
+ const integrateCompleted = journalHasEventType(projectRoot, batchId, "integrate.completed");
151
252
 
152
- if (String(state.phase ?? "") === "completed" || loadGateRecord(projectRoot, batchId)) {
253
+ if (String(state.phase ?? "") === "completed" || gateExists || integrateCompleted) {
254
+ const ensured = ensureLandLoopFinalizedAfterGateOrIntegrate({
255
+ projectRoot,
256
+ state,
257
+ batchId,
258
+ resumed: true,
259
+ source: integrateCompleted ? "host_integrate" : "attached_exit_after_gate",
260
+ });
153
261
  attachedExitFinalizeInFlight = false;
154
- return { handled: true, action: "already_finalized", batchId };
262
+ return {
263
+ handled: true,
264
+ action: ensured?.changed ? "finalized_after_gate_or_integrate" : "already_finalized",
265
+ batchId,
266
+ result: ensured,
267
+ };
155
268
  }
156
269
 
157
270
  hydrateMergeResultsFromJournal({ projectRoot, state, batchId });
@@ -307,6 +420,10 @@ export function tryFinalizePostMergeLimbo({
307
420
  * Open integrate gate and mark batch completed (idempotent gate open).
308
421
  * Shared by engine completion and resume post-merge limbo fast path (SP-204, SP-280).
309
422
  *
423
+ * Clear engine PID before gate open so extended evidence (often `npm test`) cannot
424
+ * leave a live PID blocking `batch complete` while the gate record already exists (#198).
425
+ * Journal order keeps `gate.opened` before `batch.completed`.
426
+ *
310
427
  * @param {object} params
311
428
  */
312
429
  export function finalizeBatchForIntegrate({
@@ -321,40 +438,37 @@ export function finalizeBatchForIntegrate({
321
438
  const summaryTask =
322
439
  taskIds.length === 1 ? taskIds[0] : `${taskIds.length} tasks (${taskIds.join(", ")})`;
323
440
  const alreadyCompleted = String(state.phase ?? "") === "completed";
441
+ const landLoopSource = resumed ? "resume_fast_path" : "engine_land_loop";
324
442
 
325
443
  if (!alreadyCompleted) {
326
444
  state.endedAt = Date.now();
327
445
  }
328
446
 
447
+ // Persist PID clear before evidence collection can hang (#198 / SP-636).
448
+ clearBatchEnginePid(state);
449
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
450
+
329
451
  const gateResult = openIntegrateGateAfterBatchComplete({
330
452
  projectRoot,
331
453
  batchId,
332
454
  batchState: { ...state, phase: "completed" },
333
455
  });
334
456
 
457
+ // Always mark completed in memory before ensure so a prior land-loop journal
458
+ // (e.g. start then pause/resume) still persists phase: completed on disk.
335
459
  if (!alreadyCompleted) {
336
460
  state.phase = "completed";
337
- appendJournalEvent(projectRoot, batchId, "batch.completed", {
338
- taskIds,
339
- mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
340
- resumed,
341
- postMergeLimbo: !resumed,
342
- resumeForced,
343
- });
344
- }
345
-
346
- clearBatchEnginePid(state);
347
-
348
- const gateRecord = loadGateRecord(projectRoot, batchId);
349
- if (gateRecord) {
350
- appendJournalEvent(projectRoot, batchId, "batch.land_loop_finalized", {
351
- resumed,
352
- resumeForced,
353
- gateId: gateRecord.gateId ?? gateResult?.gate?.gateId ?? null,
354
- source: resumed ? "resume_fast_path" : "engine_land_loop",
355
- });
461
+ state.endedAt = state.endedAt ?? Date.now();
356
462
  }
357
-
463
+ ensureLandLoopFinalizedAfterGateOrIntegrate({
464
+ projectRoot,
465
+ state,
466
+ batchId,
467
+ resumed,
468
+ resumeForced,
469
+ source: landLoopSource,
470
+ });
471
+ // Ensure may no-op when journal events already exist; always persist phase/PID.
358
472
  saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
359
473
 
360
474
  const completionLabel = resumed ? "resumed and completed" : "completed";
@@ -370,6 +484,7 @@ export function finalizeBatchForIntegrate({
370
484
  taskId: taskIds.length === 1 ? taskIds[0] : undefined,
371
485
  orchBranch,
372
486
  mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
487
+ gateResult,
373
488
  output:
374
489
  `Batch ${batchId} ${completionLabel}: ${summaryTask} succeeded; merged to ${orchBranch}.\n` +
375
490
  nextSteps,