pi-spine 1.0.2 → 1.1.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 (63) hide show
  1. package/README.md +61 -489
  2. package/bin/get-version.mjs +1 -13
  3. package/bin/spine-batch.mjs +5 -1
  4. package/bin/spine-config.mjs +1 -212
  5. package/bin/spine-doctor.mjs +2 -418
  6. package/bin/spine-init.mjs +1 -398
  7. package/bin/spine-preflight.mjs +1 -700
  8. package/bin/spine-review-step.mjs +6 -4
  9. package/bin/spine-tasks.mjs +96 -11
  10. package/bin/spine-worker-runner.mjs +14 -4
  11. package/bin/spine.mjs +3 -1
  12. package/extensions/spine/worker-tools.ts +14 -12
  13. package/package.json +5 -2
  14. package/skills/create-spine-tasks/SKILL.md +135 -6
  15. package/skills/create-spine-tasks/references/clarify-template.md +73 -0
  16. package/skills/create-spine-tasks/references/prompt-template.md +2 -0
  17. package/skills/create-spine-tasks/references/requirements-checklist-template.md +94 -0
  18. package/src/batch/abort.mjs +1 -1
  19. package/src/batch/detached-start.mjs +41 -7
  20. package/src/batch/diagnosis.mjs +51 -6
  21. package/src/batch/engine-lanes/merge.mjs +70 -7
  22. package/src/batch/engine-lanes/review.mjs +32 -74
  23. package/src/batch/engine-scope.mjs +31 -4
  24. package/src/batch/engine.mjs +40 -48
  25. package/src/batch/evidence.mjs +3 -2
  26. package/src/batch/gate.mjs +3 -3
  27. package/src/batch/integrate.mjs +1 -1
  28. package/src/batch/journal.mjs +22 -0
  29. package/src/batch/lifecycle.mjs +1 -1
  30. package/src/batch/merge/adoption-doc-merge.mjs +160 -0
  31. package/src/batch/merge/wave-merge-state.mjs +105 -0
  32. package/src/batch/post-merge-limbo.mjs +87 -15
  33. package/src/batch/reconcile.mjs +50 -2
  34. package/src/batch/resume-common.mjs +1 -1
  35. package/src/batch/resume-engine.mjs +58 -1
  36. package/src/batch/resume-multi-validate.mjs +82 -3
  37. package/src/batch/resume-multi.mjs +36 -40
  38. package/src/batch/resume.mjs +20 -10
  39. package/src/batch/review-shared.mjs +196 -0
  40. package/src/batch/review-spawn.mjs +320 -0
  41. package/src/batch/review.mjs +178 -212
  42. package/src/batch/task-stall-budget.mjs +72 -0
  43. package/src/batch/worker-host.mjs +94 -34
  44. package/src/batch/worktree.mjs +10 -0
  45. package/src/cli/handoff.mjs +1 -1
  46. package/src/cli/rules.mjs +1 -1
  47. package/src/cli/settings-set.mjs +1 -1
  48. package/src/cli/settings-slash.mjs +27 -5
  49. package/src/config/spine-config-load.mjs +221 -0
  50. package/src/config/spine-init-constants.mjs +423 -0
  51. package/src/config/spine-preflight-lib.mjs +725 -0
  52. package/src/dashboard/public/dashboard.js +4 -25
  53. package/src/dashboard/public/index.html +1 -7
  54. package/src/dashboard/snapshot.mjs +172 -5
  55. package/src/dashboard/view.mjs +2 -0
  56. package/src/doctor/run-doctor-checks.mjs +458 -0
  57. package/src/doctor/stale-path.mjs +22 -0
  58. package/src/migrate/taskplane-config.mjs +1 -1
  59. package/src/planner/pending.mjs +92 -1
  60. package/src/tasks/analyze/index.mjs +453 -0
  61. package/src/util/command-exists.mjs +19 -0
  62. package/templates/docs/constitution.md +61 -0
  63. package/templates/spine-config.json +1 -1
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Safe auto-merge for additive conflicts in docs/adoption/* during lane→orch wave merge.
3
+ * @see GitHub #14 — serial README wave tasks overlapping operator-runbook.md
4
+ */
5
+
6
+ import { execFileSync } from "node:child_process";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { gitExec } from "../git-exec.mjs";
11
+
12
+ export const ADOPTION_DOC_PREFIX = "docs/adoption/";
13
+
14
+ /**
15
+ * @param {string} filePath
16
+ */
17
+ export function isAdoptionDocPath(filePath) {
18
+ const normalized = String(filePath ?? "").replace(/\\/g, "/");
19
+ return normalized.startsWith(ADOPTION_DOC_PREFIX);
20
+ }
21
+
22
+ /**
23
+ * @param {string} projectRoot
24
+ * @param {string} filePath
25
+ * @param {1 | 2 | 3} stage
26
+ */
27
+ function readMergeStageContent(projectRoot, filePath, stage) {
28
+ const output = gitExec(
29
+ projectRoot,
30
+ ["show", `:${stage}:${filePath}`],
31
+ { throwOnError: false, projectRoot },
32
+ );
33
+ if (output == null) {
34
+ return null;
35
+ }
36
+ return output;
37
+ }
38
+
39
+ /**
40
+ * @param {string} ours
41
+ * @param {string} base
42
+ * @param {string} theirs
43
+ */
44
+ function runGitMergeFile(ours, base, theirs) {
45
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "spine-adoption-merge-"));
46
+ const oursPath = path.join(tempDir, "ours");
47
+ const basePath = path.join(tempDir, "base");
48
+ const theirsPath = path.join(tempDir, "theirs");
49
+ try {
50
+ fs.writeFileSync(oursPath, ours, "utf-8");
51
+ fs.writeFileSync(basePath, base, "utf-8");
52
+ fs.writeFileSync(theirsPath, theirs, "utf-8");
53
+ let merged = "";
54
+ let exitCode = 0;
55
+ try {
56
+ merged = execFileSync("git", ["merge-file", "-p", oursPath, basePath, theirsPath], {
57
+ encoding: "utf-8",
58
+ stdio: ["ignore", "pipe", "pipe"],
59
+ });
60
+ } catch (err) {
61
+ const execErr = /** @type {NodeJS.ErrnoException & { status?: number, stdout?: string }} */ (err);
62
+ exitCode = Number(execErr.status ?? 1);
63
+ merged = String(execErr.stdout ?? "");
64
+ }
65
+ return { exitCode, merged };
66
+ } finally {
67
+ fs.rmSync(tempDir, { recursive: true, force: true });
68
+ }
69
+ }
70
+
71
+ /**
72
+ * @param {string} merged
73
+ * @returns {string[]}
74
+ */
75
+ function extractConflictHunkLabels(merged) {
76
+ const labels = [];
77
+ const pattern = /^<<<<<<< (.+)$/gm;
78
+ for (const match of merged.matchAll(pattern)) {
79
+ if (match[1]) labels.push(match[1].trim());
80
+ }
81
+ return labels;
82
+ }
83
+
84
+ /**
85
+ * @param {object} params
86
+ * @param {string} params.filePath
87
+ * @param {number} [params.waveIndex]
88
+ * @param {string[]} [params.conflictHunks]
89
+ */
90
+ export function formatAdoptionDocMergeFailure({ filePath, waveIndex, conflictHunks = [] }) {
91
+ const lines = [
92
+ `merge conflict on ${filePath} — adoption doc hunks could not be auto-merged safely`,
93
+ ];
94
+ if (conflictHunks.length > 0) {
95
+ lines.push(`Conflicting hunks: ${conflictHunks.join(", ")}`);
96
+ }
97
+ lines.push(
98
+ "Recovery: resolve conflicts in the lane worktree, commit on the lane branch, then `spine batch resume`",
99
+ );
100
+ if (waveIndex != null && Number.isFinite(waveIndex)) {
101
+ lines.push(
102
+ `Mixed-outcome override only: \`spine batch force-merge --wave ${waveIndex}\` then \`spine batch resume --force\``,
103
+ );
104
+ }
105
+ lines.push(
106
+ "Manual merge path: docs/adoption/operator-runbook.md § Lane merge conflicts; design: docs/design/integrate-conflict-recovery.md",
107
+ );
108
+ return lines.join("\n");
109
+ }
110
+
111
+ /**
112
+ * Attempt 3-way merge for docs/adoption/* using git merge-file (non-overlapping additive edits).
113
+ *
114
+ * @param {object} params
115
+ * @param {string} params.projectRoot
116
+ * @param {string} params.filePath
117
+ * @param {number} [params.waveIndex]
118
+ */
119
+ export function tryResolveAdoptionDocMergeConflict({ projectRoot, filePath, waveIndex }) {
120
+ if (!isAdoptionDocPath(filePath)) {
121
+ return { ok: false, reason: "not_adoption_doc" };
122
+ }
123
+
124
+ const base = readMergeStageContent(projectRoot, filePath, 1);
125
+ const ours = readMergeStageContent(projectRoot, filePath, 2);
126
+ const theirs = readMergeStageContent(projectRoot, filePath, 3);
127
+ if (base == null || ours == null || theirs == null) {
128
+ return {
129
+ ok: false,
130
+ failureClass: "MergeConflict",
131
+ error: formatAdoptionDocMergeFailure({
132
+ filePath,
133
+ waveIndex,
134
+ conflictHunks: ["missing merge stages"],
135
+ }),
136
+ };
137
+ }
138
+
139
+ const { exitCode, merged } = runGitMergeFile(ours, base, theirs);
140
+ if (exitCode !== 0) {
141
+ const conflictHunks = extractConflictHunkLabels(merged);
142
+ return {
143
+ ok: false,
144
+ failureClass: "MergeConflict",
145
+ error: formatAdoptionDocMergeFailure({ filePath, waveIndex, conflictHunks }),
146
+ conflictHunks,
147
+ };
148
+ }
149
+
150
+ const absPath = path.join(projectRoot, filePath);
151
+ fs.mkdirSync(path.dirname(absPath), { recursive: true });
152
+ fs.writeFileSync(absPath, merged, "utf-8");
153
+ gitExec(projectRoot, ["add", "--", filePath], { projectRoot });
154
+ return {
155
+ ok: true,
156
+ autoResolved: true,
157
+ strategy: "adoption_doc_merge_file",
158
+ filePath,
159
+ };
160
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Wave merge bookkeeping — detect waves missing mergeResults entries.
3
+ */
4
+
5
+ /**
6
+ * @param {object} state
7
+ * @returns {Set<number>}
8
+ */
9
+ export function succeededWaveMergeIndices(state) {
10
+ const mergeResults = state.mergeResults ?? [];
11
+ return new Set(
12
+ mergeResults
13
+ .filter((entry) => String(entry?.status ?? "").toLowerCase() === "succeeded")
14
+ .map((entry) => Number(entry.waveIndex))
15
+ .filter((waveIndex) => Number.isFinite(waveIndex)),
16
+ );
17
+ }
18
+
19
+ /**
20
+ * @param {object} state
21
+ * @param {number} waveIndex
22
+ */
23
+ export function waveTasksAllTerminal(state, waveIndex) {
24
+ const waveTaskIds = state.wavePlan?.[waveIndex] ?? [];
25
+ const tasks = state.tasks ?? [];
26
+ if (waveTaskIds.length === 0) {
27
+ return false;
28
+ }
29
+ return waveTaskIds.every((taskId) => {
30
+ const task = tasks.find((entry) => entry?.taskId === taskId);
31
+ if (!task) return false;
32
+ const status = String(task.status ?? "").toLowerCase();
33
+ return status === "succeeded" || status === "skipped";
34
+ });
35
+ }
36
+
37
+ /**
38
+ * First wave index whose tasks are terminal but lacks a succeeded mergeResults row.
39
+ *
40
+ * @param {object} state
41
+ * @returns {number | null}
42
+ */
43
+ export function findFirstWaveNeedingMerge(state) {
44
+ const succeeded = succeededWaveMergeIndices(state);
45
+ const wavePlan = state.wavePlan ?? [];
46
+ for (let waveIndex = 0; waveIndex < wavePlan.length; waveIndex++) {
47
+ if (succeeded.has(waveIndex)) {
48
+ continue;
49
+ }
50
+ if (waveTasksAllTerminal(state, waveIndex)) {
51
+ return waveIndex;
52
+ }
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /**
58
+ * @param {object} state
59
+ */
60
+ export function hasPendingWaveMerge(state) {
61
+ return findFirstWaveNeedingMerge(state) != null;
62
+ }
63
+
64
+ /**
65
+ * @param {object} state
66
+ * @param {number} waveIndex
67
+ */
68
+ export function isWaveForceMerged(state, waveIndex) {
69
+ return (state.resilience?.forceMergedWaves ?? []).includes(waveIndex);
70
+ }
71
+
72
+ /**
73
+ * @param {object} params
74
+ * @param {object} params.state
75
+ * @param {number} params.waveIndex
76
+ * @param {"succeeded" | "failed"} params.status
77
+ * @param {string | null} [params.mergeCommit]
78
+ * @param {number | null} [params.failedLane]
79
+ * @param {string | null} [params.failureReason]
80
+ */
81
+ export function recordWaveMergeResult({
82
+ state,
83
+ waveIndex,
84
+ status,
85
+ mergeCommit = null,
86
+ failedLane = null,
87
+ failureReason = null,
88
+ }) {
89
+ state.mergeResults = state.mergeResults ?? [];
90
+ const existingIndex = state.mergeResults.findIndex((entry) => entry?.waveIndex === waveIndex);
91
+ const row = {
92
+ waveIndex,
93
+ status,
94
+ forceMerged: isWaveForceMerged(state, waveIndex),
95
+ failedLane,
96
+ failureReason,
97
+ mergeCommit,
98
+ };
99
+ if (existingIndex >= 0) {
100
+ state.mergeResults[existingIndex] = { ...state.mergeResults[existingIndex], ...row };
101
+ } else {
102
+ state.mergeResults.push(row);
103
+ }
104
+ return row;
105
+ }
@@ -35,36 +35,100 @@ export function isPostMergeLimbo(state, git = {}) {
35
35
  }
36
36
 
37
37
  /**
38
- * Open integrate gate and mark batch completed (idempotent gate open).
38
+ * @param {object|null|undefined} state
39
+ * @param {number} waveIndex
40
+ */
41
+ export function isLastWaveIndex(state, waveIndex) {
42
+ if (!state || typeof state !== "object") return false;
43
+ const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
44
+ if (!Number.isFinite(totalWaves) || totalWaves <= 0) return false;
45
+ return waveIndex >= totalWaves - 1;
46
+ }
47
+
48
+ /**
49
+ * Finalize immediately after the last wave merge so post-merge limbo never opens
50
+ * (SP-280, SP-281 — attached engine + resume orphan race).
39
51
  *
40
52
  * @param {object} params
53
+ * @param {boolean} [params.resumed]
54
+ * @param {boolean} [params.resumeForced]
55
+ * @returns {ReturnType<typeof finalizeBatchForIntegrate>|null}
41
56
  */
42
- export function finalizeResumedBatchForIntegrate({
57
+ export function maybeFinalizeAfterWaveMerge({
43
58
  projectRoot,
44
59
  state,
45
60
  batchId,
46
61
  orchBranch,
62
+ waveIndex,
63
+ resumed = false,
47
64
  resumeForced = false,
48
65
  }) {
49
- state.endedAt = Date.now();
50
- openIntegrateGateAfterBatchComplete({
66
+ if (String(state.phase ?? "") === "completed") {
67
+ return null;
68
+ }
69
+ if (!isLastWaveIndex(state, waveIndex)) {
70
+ return null;
71
+ }
72
+ if (!isPostMergeLimbo(state)) {
73
+ return null;
74
+ }
75
+ return finalizeBatchForIntegrate({
51
76
  projectRoot,
77
+ state,
52
78
  batchId,
53
- batchState: { ...state, phase: "completed" },
54
- });
55
- state.phase = "completed";
56
- saveSpineBatchState(projectRoot, state);
57
- appendJournalEvent(projectRoot, batchId, "batch.completed", {
58
- taskIds: (state.tasks ?? []).map((task) => task.taskId),
59
- mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
60
- resumed: true,
61
- postMergeLimbo: true,
79
+ orchBranch,
80
+ resumed,
62
81
  resumeForced,
63
82
  });
83
+ }
64
84
 
85
+ /**
86
+ * Open integrate gate and mark batch completed (idempotent gate open).
87
+ * Shared by engine completion and resume post-merge limbo fast path (SP-204, SP-280).
88
+ *
89
+ * @param {object} params
90
+ */
91
+ export function finalizeBatchForIntegrate({
92
+ projectRoot,
93
+ state,
94
+ batchId,
95
+ orchBranch,
96
+ resumed = false,
97
+ resumeForced = false,
98
+ }) {
65
99
  const taskIds = (state.tasks ?? []).map((task) => task.taskId);
66
100
  const summaryTask =
67
101
  taskIds.length === 1 ? taskIds[0] : `${taskIds.length} tasks (${taskIds.join(", ")})`;
102
+ const alreadyCompleted = String(state.phase ?? "") === "completed";
103
+
104
+ if (!alreadyCompleted) {
105
+ state.endedAt = Date.now();
106
+ }
107
+
108
+ openIntegrateGateAfterBatchComplete({
109
+ projectRoot,
110
+ batchId,
111
+ batchState: { ...state, phase: "completed" },
112
+ });
113
+
114
+ if (!alreadyCompleted) {
115
+ state.phase = "completed";
116
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
117
+ appendJournalEvent(projectRoot, batchId, "batch.completed", {
118
+ taskIds,
119
+ mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
120
+ resumed,
121
+ postMergeLimbo: !resumed,
122
+ resumeForced,
123
+ });
124
+ } else {
125
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
126
+ }
127
+
128
+ const completionLabel = resumed ? "resumed and completed" : "completed";
129
+ const nextSteps = resumed
130
+ ? " → spine gate approve\n → spine integrate\n → spine batch complete\n"
131
+ : " → spine gate status\n → spine gate approve\n → spine integrate\n → spine batch complete\n";
68
132
 
69
133
  return {
70
134
  ok: true,
@@ -72,9 +136,17 @@ export function finalizeResumedBatchForIntegrate({
72
136
  batchId,
73
137
  taskIds,
74
138
  taskId: taskIds.length === 1 ? taskIds[0] : undefined,
139
+ orchBranch,
75
140
  mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
76
141
  output:
77
- `Batch ${batchId} resumed and completed: ${summaryTask} succeeded; merged to ${orchBranch}.\n` +
78
- ` → spine gate approve\n → spine integrate\n → spine batch complete\n`,
142
+ `Batch ${batchId} ${completionLabel}: ${summaryTask} succeeded; merged to ${orchBranch}.\n` +
143
+ nextSteps,
79
144
  };
80
145
  }
146
+
147
+ /**
148
+ * @param {object} params
149
+ */
150
+ export function finalizeResumedBatchForIntegrate(params) {
151
+ return finalizeBatchForIntegrate({ ...params, resumed: true });
152
+ }
@@ -5,8 +5,11 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
8
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
+ import { PACKAGE_ROOT } from "../config/spine-init-constants.mjs";
9
10
  import { resolveTasksRootPath } from "../config/env-overrides.mjs";
11
+ import { buildStalePathDoctorCheck } from "../doctor/stale-path.mjs";
12
+ import { loadGateRecord } from "./gate.mjs";
10
13
  import {
11
14
  buildDiagnosisOutput,
12
15
  inferLaunchFailureFromWorkerOutputTail,
@@ -20,14 +23,16 @@ import {
20
23
  detectBatchStateDrift,
21
24
  rebuildBatchStateFromJournal,
22
25
  } from "./journal-rebuild.mjs";
23
- import { extractJournalDiagnosisHints, journalPath, readJournalEvents } from "./journal.mjs";
26
+ import { extractJournalDiagnosisHints, findPlanReviewNestedSpawnBlockedFailure, journalPath, readJournalEvents } from "./journal.mjs";
24
27
  import { findLatestSalvageInspection } from "./salvage.mjs";
25
28
  import { countCommitsAhead } from "./lane-commit.mjs";
29
+ import { isProcessAlive } from "../process/liveness.mjs";
26
30
  import {
27
31
  loadBatchStateFile,
28
32
  parseBatchState,
29
33
  resolveBatchStatePath,
30
34
  } from "./batch-state-io.mjs";
35
+ import { readBatchEnginePid } from "./state.mjs";
31
36
 
32
37
  export { loadBatchStateFile, parseBatchState, resolveBatchStatePath } from "./batch-state-io.mjs";
33
38
 
@@ -398,6 +403,22 @@ function withFailureContext(diagnosis, failedTaskId, signals, exitReason = null)
398
403
  };
399
404
  }
400
405
 
406
+ /**
407
+ * @param {object[]} journalEvents
408
+ * @param {Record<string, unknown>|null|undefined} raw
409
+ * @param {string|null} taskId
410
+ */
411
+ function journalIndicatesResumeRulesStall(journalEvents, raw, taskId) {
412
+ const scoped = journalEventsSinceResume(journalEvents, raw);
413
+ const hasRulesSelected = scoped.some((event) => {
414
+ if (event.type !== "worker.rules_selected") return false;
415
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
416
+ return !taskId || !eventTaskId || eventTaskId === taskId;
417
+ });
418
+ const hasBatchResumed = scoped.some((event) => event.type === "batch.resumed");
419
+ return hasRulesSelected && hasBatchResumed;
420
+ }
421
+
401
422
  /**
402
423
  * @param {object} signals
403
424
  */
@@ -441,6 +462,16 @@ export function deriveDiagnosis(signals) {
441
462
 
442
463
  if (orphanRunning) {
443
464
  if (orphanRunning.kind === "lane" && orphanRunning.taskId) {
465
+ const enginePid = readBatchEnginePid(signals.raw);
466
+ const engineDead = enginePid == null || !isProcessAlive(enginePid);
467
+ const resumeRulesStall = journalIndicatesResumeRulesStall(
468
+ signals.journalEvents ?? [],
469
+ signals.raw,
470
+ orphanRunning.taskId,
471
+ );
472
+ if (engineDead && resumeRulesStall) {
473
+ return withFailureContext("engine_orphaned", orphanRunning.taskId, signals);
474
+ }
444
475
  return withFailureContext("worker_orphaned", orphanRunning.taskId, signals);
445
476
  }
446
477
  return withFailureContext("engine_orphaned", orphanRunning.taskId ?? null, signals);
@@ -688,6 +719,20 @@ export function reconcileBatch(ctx) {
688
719
  ? `spine batch retry ${signals.orphanRunning.taskId}`
689
720
  : null;
690
721
 
722
+ const integrateGateOpen =
723
+ signals.postMergeLimbo === true && batch.batchId
724
+ ? Boolean(loadGateRecord(projectRoot, batch.batchId))
725
+ : false;
726
+
727
+ const stalePathCheck = buildStalePathDoctorCheck({
728
+ packageRoot: PACKAGE_ROOT,
729
+ runningSpinePath: path.join(PACKAGE_ROOT, "bin", "spine.mjs"),
730
+ });
731
+ const stalePathSpine = stalePathCheck.warning === true;
732
+ const planReviewNestedSpawnBlocked =
733
+ diagnosis === "worker_orphaned" &&
734
+ findPlanReviewNestedSpawnBlockedFailure(journalEvents, failedTaskId);
735
+
691
736
  const output = buildDiagnosisOutput(diagnosis, {
692
737
  batchId: batch.batchId,
693
738
  phase: batch.phase,
@@ -701,6 +746,9 @@ export function reconcileBatch(ctx) {
701
746
  salvageRetryCommand,
702
747
  ghostRunningCluster,
703
748
  postMergeLimbo: signals.postMergeLimbo === true,
749
+ integrateGateOpen,
750
+ stalePathSpine,
751
+ planReviewNestedSpawnBlocked,
704
752
  });
705
753
 
706
754
  if (diagnosis === "git_unavailable") {
@@ -4,7 +4,7 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
- import { DEFAULT_TASKS_ROOT } from "../../bin/spine-init.mjs";
7
+ import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
8
8
  import { appendJournalEvent } from "./journal.mjs";
9
9
  import { recomputeTaskCounters } from "./state.mjs";
10
10
  import { loadTaskFileScopePaths } from "./engine-lanes.mjs";
@@ -7,6 +7,22 @@ import { appendJournalEvent } from "./journal.mjs";
7
7
  import { isPostMergeLimbo } from "./post-merge-limbo.mjs";
8
8
  import { clearBatchEnginePid, readBatchEnginePid } from "./state.mjs";
9
9
 
10
+ /**
11
+ * Drop lane workerPid values that no longer refer to live processes.
12
+ *
13
+ * @param {object} state
14
+ */
15
+ export function clearStaleLaneWorkerPids(state) {
16
+ for (const lane of state.lanes ?? []) {
17
+ if (!lane || typeof lane !== "object") continue;
18
+ const workerPid = Number(lane.workerPid);
19
+ if (!Number.isFinite(workerPid) || workerPid <= 0) continue;
20
+ if (!isProcessAlive(workerPid)) {
21
+ delete lane.workerPid;
22
+ }
23
+ }
24
+ }
25
+
10
26
  /**
11
27
  * SIGTERM a stale detached engine before the resume engine takes over.
12
28
  *
@@ -16,6 +32,7 @@ import { clearBatchEnginePid, readBatchEnginePid } from "./state.mjs";
16
32
  * @param {string} params.batchId
17
33
  * @param {string} params.fromPhase
18
34
  * @param {object} [params.git]
35
+ * @param {boolean} [params.allowRunningOrphanTerminate]
19
36
  */
20
37
  export function terminateStaleDetachedEngine({
21
38
  projectRoot,
@@ -23,6 +40,7 @@ export function terminateStaleDetachedEngine({
23
40
  batchId,
24
41
  fromPhase,
25
42
  git = {},
43
+ allowRunningOrphanTerminate = false,
26
44
  }) {
27
45
  const stalePid = readBatchEnginePid(state);
28
46
  if (!stalePid || stalePid === process.pid) {
@@ -37,7 +55,8 @@ export function terminateStaleDetachedEngine({
37
55
  const eligiblePhase =
38
56
  fromPhase === "paused" ||
39
57
  fromPhase === "failed" ||
40
- (fromPhase === "running" && isPostMergeLimbo(state, git));
58
+ (fromPhase === "running" && isPostMergeLimbo(state, git)) ||
59
+ (fromPhase === "running" && allowRunningOrphanTerminate);
41
60
  if (!eligiblePhase) {
42
61
  return { terminated: false, reason: "phase_not_eligible", stalePid };
43
62
  }
@@ -64,3 +83,41 @@ export function terminateStaleDetachedEngine({
64
83
  clearBatchEnginePid(state);
65
84
  return { terminated: true, stalePid };
66
85
  }
86
+
87
+ /**
88
+ * Prepare batch-state for orphan resume: clear dead engine/worker PIDs and terminate stale engines.
89
+ *
90
+ * @param {object} params
91
+ * @param {string} params.projectRoot
92
+ * @param {object} params.state
93
+ * @param {string} params.batchId
94
+ * @param {string} params.fromPhase
95
+ * @param {boolean} [params.orphanResume]
96
+ * @param {boolean} [params.engineConfirmedDead]
97
+ * @param {object} [params.git]
98
+ */
99
+ export function prepareOrphanResumeHandoff({
100
+ projectRoot,
101
+ state,
102
+ batchId,
103
+ fromPhase,
104
+ orphanResume = false,
105
+ engineConfirmedDead = false,
106
+ git = {},
107
+ }) {
108
+ if (orphanResume && engineConfirmedDead) {
109
+ clearBatchEnginePid(state);
110
+ }
111
+ clearStaleLaneWorkerPids(state);
112
+
113
+ const terminateResult = terminateStaleDetachedEngine({
114
+ projectRoot,
115
+ state,
116
+ batchId,
117
+ fromPhase,
118
+ git,
119
+ allowRunningOrphanTerminate: orphanResume && engineConfirmedDead,
120
+ });
121
+
122
+ return { terminateResult, orphanResume, engineConfirmedDead };
123
+ }