pi-spine 2.3.0 → 2.3.1

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.
@@ -8,6 +8,11 @@ import { spawnSync } from "node:child_process";
8
8
  import { fileURLToPath } from "node:url";
9
9
 
10
10
  import { c, FAIL, OK } from "./shared.mjs";
11
+ import {
12
+ BATCH_MODULE_LOC_LIMIT,
13
+ evaluateBatchLocPolicy,
14
+ listBatchModuleLineCounts,
15
+ } from "../../src/config/preflight/loc-capstone.mjs";
11
16
 
12
17
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
18
 
@@ -16,24 +21,7 @@ export const PHASE23_GRANDFATHERED_OVER_500 = [];
16
21
 
17
22
  const PHASE23_ENGINE_LANES_MAX = 500;
18
23
 
19
- /**
20
- * @param {string} projectRoot
21
- */
22
- function listBatchModuleLineCounts(projectRoot) {
23
- const batchDir = path.join(projectRoot, "src/batch");
24
- if (!fs.existsSync(batchDir)) return [];
25
-
26
- return fs
27
- .readdirSync(batchDir)
28
- .filter((name) => name.endsWith(".mjs"))
29
- .map((name) => {
30
- const relPath = path.posix.join("src/batch", name);
31
- const absPath = path.join(batchDir, name);
32
- const lines = fs.readFileSync(absPath, "utf-8").split(/\r?\n/).length;
33
- return { relPath, lines };
34
- })
35
- .sort((left, right) => left.relPath.localeCompare(right.relPath));
36
- }
24
+ export { listBatchModuleLineCounts, evaluateBatchLocPolicy, BATCH_MODULE_LOC_LIMIT };
37
25
 
38
26
  /**
39
27
  * @param {object} params
@@ -94,17 +82,15 @@ export function runPhase23ExitVerify({ projectRoot, skipTest = false }) {
94
82
  : `engine-lanes.mjs exceeds ${PHASE23_ENGINE_LANES_MAX} LOC (${engineLanes?.lines ?? "missing"})`,
95
83
  });
96
84
 
97
- const over500 = modules.filter((entry) => entry.lines > 500);
98
- const ungrandfathered = over500.filter(
99
- (entry) => !PHASE23_GRANDFATHERED_OVER_500.includes(entry.relPath),
100
- );
101
- const locPolicyOk = ungrandfathered.length === 0;
85
+ const locPolicy = evaluateBatchLocPolicy(projectRoot, {
86
+ grandfathered: PHASE23_GRANDFATHERED_OVER_500,
87
+ });
102
88
  checks.push({
103
89
  id: "batch-loc-policy",
104
- ok: locPolicyOk,
105
- message: locPolicyOk
106
- ? `batch module LOC policy ok (${over500.length} grandfathered >500)`
107
- : `unexpected >500 LOC modules: ${ungrandfathered.map((entry) => `${entry.relPath} (${entry.lines})`).join(", ")}`,
90
+ ok: locPolicy.ok,
91
+ message: locPolicy.ok
92
+ ? `batch module LOC policy ok (${locPolicy.overLimit.length} grandfathered >${BATCH_MODULE_LOC_LIMIT})`
93
+ : `unexpected >${BATCH_MODULE_LOC_LIMIT} LOC modules: ${locPolicy.ungrandfathered.map((entry) => `${entry.relPath} (${entry.lines})`).join(", ")}`,
108
94
  });
109
95
 
110
96
  const realPiWorkflow = path.join(projectRoot, ".github/workflows/real-pi.yml");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.3.0",
3
+ "version": "2.3.1",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -56,6 +56,25 @@ export { inferLaunchFailureFromWorkerOutputTail, inferLaunchFailureKind } from "
56
56
 
57
57
  const INVALID_BARE_RETRY_FORCE = /^spine batch retry --force$/;
58
58
 
59
+ /**
60
+ * Gate-ready batches must not headline historical merge/gitignored blockers (#195 / FR-REL231-01).
61
+ *
62
+ * @param {string} diagnosis
63
+ * @param {object} [ctx]
64
+ * @param {boolean} [ctx.allTasksTerminalSuccess]
65
+ * @param {boolean} [ctx.integrateGateOpen]
66
+ * @returns {boolean}
67
+ */
68
+ export function isGateReadyHeadlineContext(diagnosis, ctx = {}) {
69
+ if (diagnosis === "needs_integrate") {
70
+ return true;
71
+ }
72
+ if (ctx.allTasksTerminalSuccess === true && ctx.integrateGateOpen === true) {
73
+ return true;
74
+ }
75
+ return false;
76
+ }
77
+
59
78
  /**
60
79
  * Retry suggestions must include a task id; journal salvage payloads may be stale.
61
80
  *
@@ -121,10 +140,16 @@ const REVIEW_SPAWN_FAILURE_EXIT_REASONS = new Set([
121
140
  * @param {string[]|null} [ctx.gitignoredPaths]
122
141
  */
123
142
  export function buildSuggestedCommand(diagnosis, ctx = {}) {
124
- if (ctx.mergeGitignoredFailure) {
143
+ const preferGateReady = isGateReadyHeadlineContext(diagnosis, ctx);
144
+ // Prefer gate-approve / land-loop next step over recovered merge/gitignored repair (#195).
145
+ if (ctx.mergeGitignoredFailure && !preferGateReady) {
125
146
  return buildGitignoredMergeRepairCommand(ctx.taskBranch, ctx.gitignoredPaths);
126
147
  }
127
- if (ctx.mergeFailed && (diagnosis === "failed" || diagnosis === "needs_retry")) {
148
+ if (
149
+ ctx.mergeFailed &&
150
+ !preferGateReady &&
151
+ (diagnosis === "failed" || diagnosis === "needs_retry")
152
+ ) {
128
153
  return "spine batch resume --force";
129
154
  }
130
155
  if (ctx.phase === "merge_blocked") {
@@ -263,12 +288,18 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
263
288
  */
264
289
  export function buildHeadline(diagnosis, ctx = {}) {
265
290
  const batchLabel = ctx.batchId ? `Batch ${ctx.batchId}` : "Batch";
291
+ const preferGateReady = isGateReadyHeadlineContext(diagnosis, ctx);
266
292
 
267
- if (ctx.mergeGitignoredFailure) {
293
+ // Historical merge/gitignored signals stay in diagnose signals — not the primary headline (#195).
294
+ if (ctx.mergeGitignoredFailure && !preferGateReady) {
268
295
  return `${batchLabel} merge blocked by gitignored paths on a lane branch — drop cached ignored files, then resume`;
269
296
  }
270
297
 
271
- if (ctx.mergeFailed && (diagnosis === "failed" || diagnosis === "needs_retry")) {
298
+ if (
299
+ ctx.mergeFailed &&
300
+ !preferGateReady &&
301
+ (diagnosis === "failed" || diagnosis === "needs_retry")
302
+ ) {
272
303
  return buildMergeFailureHeadline(batchLabel, ctx);
273
304
  }
274
305
 
@@ -0,0 +1,126 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Orch→lane sync when satisfied deps share File Scope (FR-REL231-03 / #191).
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { resolveTasksRootPath } from "../../config/env-overrides.mjs";
9
+ import { discoverTasks, loadDependenciesJson } from "../../tasks/packet/index.mjs";
10
+ import { loadTaskFileScopePaths } from "./queue.mjs";
11
+ import { syncLaneWorktreeFromOrch } from "../worktree.mjs";
12
+
13
+ /**
14
+ * @param {string} projectRoot
15
+ * @param {object} [config]
16
+ */
17
+ function resolveBatchTasksRoot(projectRoot, config) {
18
+ return resolveTasksRootPath(projectRoot, config) ?? path.join(projectRoot, "spine-tasks");
19
+ }
20
+
21
+ /**
22
+ * @param {string} tasksRoot
23
+ * @param {string} taskId
24
+ * @param {object[]} [stateTasks]
25
+ */
26
+ function resolveTaskFolderPath(tasksRoot, taskId, stateTasks = []) {
27
+ const fromState = stateTasks.find((entry) => entry?.taskId === taskId)?.taskFolder;
28
+ if (typeof fromState === "string" && fromState.trim() && fs.existsSync(fromState)) {
29
+ return fromState;
30
+ }
31
+ if (!fs.existsSync(tasksRoot)) return null;
32
+ const match = discoverTasks(tasksRoot).find((entry) => entry.taskId === taskId);
33
+ return match?.folderPath ?? null;
34
+ }
35
+
36
+ /**
37
+ * Satisfied deps that share at least one File Scope path with the current task.
38
+ *
39
+ * @param {object} params
40
+ * @param {string} params.projectRoot
41
+ * @param {object} params.state
42
+ * @param {string} params.taskId
43
+ * @param {string[]} params.fileScopePaths
44
+ * @param {object} [params.config]
45
+ * @returns {Array<{ depId: string, overlap: string[] }>}
46
+ */
47
+ export function collectSharedScopeSatisfiedDeps({
48
+ projectRoot,
49
+ state,
50
+ taskId,
51
+ fileScopePaths,
52
+ config = {},
53
+ }) {
54
+ if (!Array.isArray(fileScopePaths) || fileScopePaths.length === 0) return [];
55
+
56
+ const tasksRoot = resolveBatchTasksRoot(projectRoot, config);
57
+ const deps = loadDependenciesJson(tasksRoot).tasks?.[taskId] ?? [];
58
+ if (!Array.isArray(deps) || deps.length === 0) return [];
59
+
60
+ const scopeSet = new Set(fileScopePaths);
61
+ const stateTasks = Array.isArray(state?.tasks) ? state.tasks : [];
62
+ /** @type {Array<{ depId: string, overlap: string[] }>} */
63
+ const shared = [];
64
+
65
+ for (const depId of deps) {
66
+ const depTask = stateTasks.find((entry) => entry?.taskId === depId);
67
+ if (!depTask || depTask.status !== "succeeded") continue;
68
+
69
+ const depFolder = resolveTaskFolderPath(tasksRoot, depId, stateTasks);
70
+ if (!depFolder) continue;
71
+
72
+ const scopeResult = loadTaskFileScopePaths(depFolder);
73
+ if (!scopeResult.ok) continue;
74
+
75
+ const overlap = (scopeResult.fileScopePaths ?? []).filter((filePath) =>
76
+ scopeSet.has(filePath),
77
+ );
78
+ if (overlap.length > 0) {
79
+ shared.push({ depId, overlap });
80
+ }
81
+ }
82
+
83
+ return shared;
84
+ }
85
+
86
+ /**
87
+ * @param {object} params
88
+ * @returns {{ ok: true, synced: boolean, skipped?: boolean, sharedDeps: Array<{ depId: string, overlap: string[] }>, headSha?: string } | { ok: false, error: string, sharedDeps: Array<{ depId: string, overlap: string[] }> }}
89
+ */
90
+ export function ensureLaneSyncedForSharedScopeDeps({
91
+ projectRoot,
92
+ state,
93
+ taskId,
94
+ fileScopePaths,
95
+ worktreePath,
96
+ config = {},
97
+ }) {
98
+ const sharedDeps = collectSharedScopeSatisfiedDeps({
99
+ projectRoot,
100
+ state,
101
+ taskId,
102
+ fileScopePaths,
103
+ config,
104
+ });
105
+ if (sharedDeps.length === 0) {
106
+ return { ok: true, synced: false, skipped: true, sharedDeps };
107
+ }
108
+
109
+ try {
110
+ const result = syncLaneWorktreeFromOrch({
111
+ worktreePath,
112
+ orchBranch: state?.orchBranch,
113
+ projectRoot,
114
+ });
115
+ return {
116
+ ok: true,
117
+ synced: !result.skipped,
118
+ skipped: result.skipped,
119
+ sharedDeps,
120
+ headSha: result.headSha,
121
+ };
122
+ } catch (err) {
123
+ const message = err instanceof Error ? err.message : String(err);
124
+ return { ok: false, error: message, sharedDeps };
125
+ }
126
+ }
@@ -22,6 +22,7 @@ import {
22
22
  } from "./state.mjs";
23
23
  import { runWorker } from "./worker-host.mjs";
24
24
  import { runCodeReviewPhase, runFinalReviewPhase } from "./engine-lanes/review.mjs";
25
+ import { ensureLaneSyncedForSharedScopeDeps } from "./engine-lanes/orch-sync.mjs";
25
26
 
26
27
  export {
27
28
  buildTasksAndLanesFromPlan,
@@ -46,6 +47,12 @@ export {
46
47
  tryAutoResolveRulesManifestMergeConflict,
47
48
  } from "./engine-lanes/merge.mjs";
48
49
 
50
+ export { syncLaneWorktreeFromOrch } from "./worktree.mjs";
51
+ export {
52
+ collectSharedScopeSatisfiedDeps,
53
+ ensureLaneSyncedForSharedScopeDeps,
54
+ } from "./engine-lanes/orch-sync.mjs";
55
+
49
56
  /**
50
57
  * @param {string} fromPhase
51
58
  * @param {string} toPhase
@@ -121,6 +128,68 @@ export async function runTaskOnLane({
121
128
  }
122
129
  const fileScopePaths = scopeResult.fileScopePaths;
123
130
 
131
+ const syncResult = ensureLaneSyncedForSharedScopeDeps({
132
+ projectRoot,
133
+ state,
134
+ taskId,
135
+ fileScopePaths,
136
+ worktreePath: wt,
137
+ config,
138
+ });
139
+ if (!syncResult.ok) {
140
+ task.status = "failed";
141
+ task.endedAt = Date.now();
142
+ task.exitReason = "orch_sync_failed";
143
+ if (!task.startedAt) task.startedAt = Date.now();
144
+ updateSegmentForTask(state, taskId, "failed");
145
+ recomputeTaskCounters(state);
146
+ saveEngineBatchState(projectRoot, state);
147
+ appendJournalEvent(projectRoot, batchId, "lane.orch_sync_failed", {
148
+ taskId,
149
+ laneNumber,
150
+ laneId: lane.laneId,
151
+ correlationId: laneCorrelationId,
152
+ error: syncResult.error,
153
+ sharedDeps: syncResult.sharedDeps,
154
+ });
155
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
156
+ taskId,
157
+ laneNumber,
158
+ laneId: lane.laneId,
159
+ correlationId: laneCorrelationId,
160
+ classification: "orch_sync_failed",
161
+ exitCode: 1,
162
+ output: syncResult.error,
163
+ });
164
+ recordLaneTaskMetric({
165
+ projectRoot,
166
+ batchId,
167
+ task,
168
+ config,
169
+ taskFolder: taskFolderInWorktree,
170
+ });
171
+ return {
172
+ ok: false,
173
+ workerResult: {
174
+ ok: false,
175
+ classification: "orch_sync_failed",
176
+ output: syncResult.error,
177
+ exitCode: 1,
178
+ },
179
+ };
180
+ }
181
+ if (syncResult.synced) {
182
+ appendJournalEvent(projectRoot, batchId, "lane.orch_synced", {
183
+ taskId,
184
+ laneNumber,
185
+ laneId: lane.laneId,
186
+ correlationId: laneCorrelationId,
187
+ orchBranch: state.orchBranch,
188
+ headSha: syncResult.headSha,
189
+ sharedDeps: syncResult.sharedDeps,
190
+ });
191
+ }
192
+
124
193
  task.status = "running";
125
194
  if (!task.startedAt) task.startedAt = Date.now();
126
195
  updateSegmentForTask(state, taskId, "running");
@@ -10,6 +10,7 @@ import { deriveMacroPhase, macroPhaseLabel } from "./macro-phase.mjs";
10
10
  import {
11
11
  buildDiagnosisOutput,
12
12
  inferMergeGitignoredFailure,
13
+ isGateReadyHeadlineContext,
13
14
  } from "./diagnosis.mjs";
14
15
  import {
15
16
  classifyTasks,
@@ -344,7 +345,7 @@ export function reconcileBatch(ctx, _lightRetry = false) {
344
345
  diagnosis === "worker_orphaned" &&
345
346
  findPlanReviewNestedSpawnBlockedFailure(journalEvents, failedTaskId);
346
347
 
347
- const mergeGitignoredFailure = inferMergeGitignoredFailure({
348
+ const mergeGitignoredFailureInferred = inferMergeGitignoredFailure({
348
349
  exitReason,
349
350
  failureClass: batch.raw?.mergeResults?.find((entry) => entry?.failureClass)?.failureClass ?? null,
350
351
  lastError: batch.raw?.lastError ?? null,
@@ -359,6 +360,17 @@ export function reconcileBatch(ctx, _lightRetry = false) {
359
360
  signals.failedWaveIndex = mergeFailureSummary.failedWaveIndex;
360
361
  signals.failedLane = mergeFailureSummary.failedLane;
361
362
  signals.lastError = mergeFailureSummary.lastError;
363
+ // Keep historical gitignored merge evidence in signals; demote for headline once gate-ready (#195).
364
+ signals.mergeGitignoredFailure = mergeGitignoredFailureInferred;
365
+ const gateReadyHeadline = isGateReadyHeadlineContext(diagnosis, {
366
+ allTasksTerminalSuccess: signals.allTasksTerminalSuccess === true,
367
+ integrateGateOpen,
368
+ });
369
+ const mergeGitignoredFailure = gateReadyHeadline ? false : mergeGitignoredFailureInferred;
370
+ const mergeFailedForHeadline = gateReadyHeadline ? false : mergeFailureSummary.mergeFailed;
371
+ if (ctx.verbose && gateReadyHeadline && mergeGitignoredFailureInferred) {
372
+ signals.mergeGitignoredFailureSuperseded = true;
373
+ }
362
374
  const gitignoredPaths = extractGitignoredPathsFromJournal(journalEvents, failedTaskId);
363
375
  const taskBranch =
364
376
  failedTaskId != null
@@ -406,7 +418,7 @@ export function reconcileBatch(ctx, _lightRetry = false) {
406
418
  stalePathSpine,
407
419
  planReviewNestedSpawnBlocked,
408
420
  mergeGitignoredFailure,
409
- mergeFailed: mergeFailureSummary.mergeFailed,
421
+ mergeFailed: mergeFailedForHeadline,
410
422
  failedWaveIndex: mergeFailureSummary.failedWaveIndex,
411
423
  failedLane: mergeFailureSummary.failedLane,
412
424
  lastError: mergeFailureSummary.lastError,
@@ -27,6 +27,7 @@ import {
27
27
  resolveWorkerPhase,
28
28
  terminateHungWorkerChild,
29
29
  } from "./worker-spawn.mjs";
30
+ import { terminateProcessTree } from "../process/terminate-tree.mjs";
30
31
 
31
32
  /** @typedef {import("./worker-spawn.mjs").WorkerPhase} WorkerPhase */
32
33
  /** @typedef {import("./worker-spawn.mjs").WorkerChildHandle} WorkerChildHandle */
@@ -165,7 +166,13 @@ export async function pollWorkerUntilSettled({
165
166
  const abortSignal = readAbortSignal(projectRoot, batchId);
166
167
  if (abortSignal) {
167
168
  const hard = Boolean(abortSignal.hard);
168
- workerChild.kill(hard ? "SIGKILL" : "SIGTERM");
169
+ const signal = hard ? "SIGKILL" : "SIGTERM";
170
+ const pid = workerChild.pid ?? 0;
171
+ if (pid > 0) {
172
+ terminateProcessTree(pid, { signal });
173
+ } else {
174
+ workerChild.kill(signal);
175
+ }
169
176
  const { output } = await childDone;
170
177
  return {
171
178
  kind: "failure",
@@ -29,13 +29,15 @@ import {
29
29
  createWorkerPollState,
30
30
  pollWorkerUntilSettled,
31
31
  } from "./worker-heartbeat.mjs";
32
+ import { terminateProcessTree } from "../process/terminate-tree.mjs";
32
33
 
33
34
  export { buildWorkerChildEnv } from "./worker-spawn.mjs";
34
35
 
35
36
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
36
37
 
37
38
  /**
38
- * Force-terminate lane worker processes tracked in batch state.
39
+ * Force-terminate lane worker process trees tracked in batch state.
40
+ * Reaps nested `pi` grandchildren, not only the tracked runner PID (SP-609 / #194).
39
41
  *
40
42
  * @param {unknown[]} lanes
41
43
  * @param {{ hard?: boolean }} [options]
@@ -52,12 +54,9 @@ export function terminateLaneWorkers(lanes, { hard = true } = {}) {
52
54
  const laneNumber = Number(
53
55
  /** @type {{ laneNumber?: number }} */ (lane).laneNumber ?? 1,
54
56
  );
55
- try {
56
- process.kill(workerPid, signal);
57
- terminated.push({ laneNumber, workerPid, signal });
58
- } catch {
59
- // process may already be gone
60
- }
57
+ const result = terminateProcessTree(workerPid, { signal });
58
+ if (result.signaled.length === 0) continue;
59
+ terminated.push({ laneNumber, workerPid, signal });
61
60
  }
62
61
  return terminated;
63
62
  }
@@ -10,6 +10,7 @@ import { startAgentSessionWorker } from "./agent-session-worker.mjs";
10
10
  import { resolveWorkerBackend } from "../config/worker-backend.mjs";
11
11
  import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
12
12
  import { resolveSafeWorkerLaunchScript } from "../config/worker-launch-script.mjs";
13
+ import { terminateProcessTree } from "../process/terminate-tree.mjs";
13
14
 
14
15
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
16
  const PACKAGE_ROOT = path.resolve(__dirname, "../..");
@@ -197,19 +198,29 @@ export function resolveWorkerPhase({
197
198
  }
198
199
 
199
200
  /**
200
- * SIGTERM then SIGKILL when a worker stays alive after post-.DONE grace.
201
+ * SIGTERM then SIGKILL the worker process tree when a child stays alive
202
+ * after post-.DONE grace (reaps nested `pi` grandchildren — SP-609 / #194).
201
203
  *
202
204
  * @param {WorkerChildHandle} child
203
205
  * @param {Promise<{ exitCode: number; output: string }>} childDone
204
206
  */
205
207
  export async function terminateHungWorkerChild(child, childDone) {
206
- child.kill("SIGTERM");
208
+ const pid = child.pid ?? 0;
209
+ if (pid > 0) {
210
+ terminateProcessTree(pid, { signal: "SIGTERM" });
211
+ } else if (typeof child.kill === "function") {
212
+ child.kill("SIGTERM");
213
+ }
207
214
  const raced = await Promise.race([childDone, sleep(POST_DONE_KILL_BACKOFF_MS)]);
208
215
  if (raced && typeof raced === "object" && "exitCode" in raced) {
209
216
  return raced;
210
217
  }
211
- if (child.exitCode === null && typeof child.kill === "function") {
212
- child.kill("SIGKILL");
218
+ if (child.exitCode === null) {
219
+ if (pid > 0) {
220
+ terminateProcessTree(pid, { signal: "SIGKILL" });
221
+ } else if (typeof child.kill === "function") {
222
+ child.kill("SIGKILL");
223
+ }
213
224
  }
214
225
  return childDone;
215
226
  }
@@ -11,6 +11,7 @@ import {
11
11
  listStaleSpineWorktreeBatchIds,
12
12
  resolveInProgressSpineBatchId,
13
13
  } from "../doctor/stale-worktrees.mjs";
14
+ import { gitExec } from "./git-exec.mjs";
14
15
 
15
16
  const WORKTREE_SETUP_HOOK_TIMEOUT_MS = 120_000;
16
17
 
@@ -250,6 +251,73 @@ export function provisionLaneWorktree({
250
251
  return { worktreePath, taskBranch, orchBranch };
251
252
  }
252
253
 
254
+ /**
255
+ * Merge orch into a lane worktree so shared-scope dep commits are ancestors of HEAD
256
+ * before the next task starts (FR-REL231-03 / #191).
257
+ *
258
+ * @param {{ worktreePath: string, orchBranch: string, projectRoot?: string }} params
259
+ * @returns {{ ok: true, skipped: boolean, reason?: string, headSha: string }}
260
+ */
261
+ export function syncLaneWorktreeFromOrch({ worktreePath, orchBranch, projectRoot }) {
262
+ if (!worktreePath || !fs.existsSync(worktreePath)) {
263
+ throw new Error(
264
+ `Cannot sync lane worktree from orch: worktree missing (${worktreePath ?? "unset"}). Recreate the lane worktree or resume the batch.`,
265
+ );
266
+ }
267
+ if (!orchBranch || typeof orchBranch !== "string") {
268
+ throw new Error("Cannot sync lane worktree from orch: orchBranch is missing from batch state.");
269
+ }
270
+
271
+ const identityRoot = projectRoot ?? worktreePath;
272
+ const orchSha = gitExec(worktreePath, ["rev-parse", "--verify", orchBranch], {
273
+ projectRoot: identityRoot,
274
+ });
275
+ if (!orchSha) {
276
+ throw new Error(`Cannot sync lane worktree from orch: failed to resolve ${orchBranch}.`);
277
+ }
278
+
279
+ const alreadyContains = gitExec(
280
+ worktreePath,
281
+ ["merge-base", "--is-ancestor", orchBranch, "HEAD"],
282
+ { throwOnError: false, projectRoot: identityRoot },
283
+ );
284
+ if (alreadyContains !== null) {
285
+ return {
286
+ ok: true,
287
+ skipped: true,
288
+ reason: "already_contains_orch",
289
+ headSha: gitExec(worktreePath, ["rev-parse", "HEAD"], { projectRoot: identityRoot }) ?? "",
290
+ };
291
+ }
292
+
293
+ const porcelain = gitExec(worktreePath, ["status", "--porcelain"], { projectRoot: identityRoot });
294
+ if (porcelain) {
295
+ throw new Error(
296
+ `Cannot sync lane worktree from ${orchBranch}: worktree is dirty (${worktreePath}). Commit or discard lane changes, then retry. Dirty paths:\n${porcelain}`,
297
+ );
298
+ }
299
+
300
+ try {
301
+ gitExec(
302
+ worktreePath,
303
+ ["merge", "--no-edit", "-m", `sync lane from ${orchBranch} before task start`, orchBranch],
304
+ { projectRoot: identityRoot },
305
+ );
306
+ } catch (err) {
307
+ gitExec(worktreePath, ["merge", "--abort"], { throwOnError: false, projectRoot: identityRoot });
308
+ const detail = err instanceof Error ? err.message : String(err);
309
+ throw new Error(
310
+ `Failed to sync lane worktree from ${orchBranch} (${orchSha.slice(0, 12)}): ${detail}. Resolve the conflict in ${worktreePath}, or remove the lane worktree and resume the batch.`,
311
+ );
312
+ }
313
+
314
+ return {
315
+ ok: true,
316
+ skipped: false,
317
+ headSha: gitExec(worktreePath, ["rev-parse", "HEAD"], { projectRoot: identityRoot }) ?? "",
318
+ };
319
+ }
320
+
253
321
  /**
254
322
  * @param {string} projectRoot
255
323
  * @param {string} batchId
@@ -430,7 +430,12 @@ export function runPreflightPlanCheck(ctx) {
430
430
  };
431
431
  }
432
432
 
433
- const plan = buildPlan({ scope: "pending", config, tasksRoot: tasksRootPath });
433
+ const plan = buildPlan({
434
+ scope: "pending",
435
+ config,
436
+ tasksRoot: tasksRootPath,
437
+ projectRoot,
438
+ });
434
439
  const waveCount = plan.waves?.length ?? 0;
435
440
  const planText = formatPlanHuman(plan).trimEnd();
436
441
  const planWarnings = [];
@@ -0,0 +1,274 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * LOC-capstone / empty-grandfather readiness (FR-REL231-04 / #192).
4
+ *
5
+ * Blocks scheduling when a pending task would empty PHASE23_GRANDFATHERED_OVER_500
6
+ * while batch-loc-policy would still fail after that change.
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { loadSpineConfig } from "../spine-config-load.mjs";
11
+ import { discoverTasks } from "../../tasks/packet/discover.mjs";
12
+ import { summarizePendingScope } from "../../planner/pending.mjs";
13
+ import { parsePrompt } from "../../tasks/packet/parse-prompt.mjs";
14
+ import { readUtf8FilesBatchSync, resolveTasksRoot } from "./discovery.mjs";
15
+
16
+ export const BATCH_MODULE_LOC_LIMIT = 500;
17
+ export const VERIFY_MJS_REL = "bin/spine-cli/verify.mjs";
18
+
19
+ function makeCheck(id, ok, message, extra = {}) {
20
+ return { id, ok, message, ...extra };
21
+ }
22
+
23
+ /**
24
+ * Count lines in each `src/batch/*.mjs` module (same basis as batch-loc-policy).
25
+ *
26
+ * @param {string} projectRoot
27
+ * @returns {Array<{ relPath: string, lines: number }>}
28
+ */
29
+ export function listBatchModuleLineCounts(projectRoot) {
30
+ const batchDir = path.join(projectRoot, "src/batch");
31
+ if (!fs.existsSync(batchDir)) return [];
32
+
33
+ return fs
34
+ .readdirSync(batchDir)
35
+ .filter((name) => name.endsWith(".mjs"))
36
+ .map((name) => {
37
+ const relPath = path.posix.join("src/batch", name);
38
+ const absPath = path.join(batchDir, name);
39
+ const lines = fs.readFileSync(absPath, "utf-8").split(/\r?\n/).length;
40
+ return { relPath, lines };
41
+ })
42
+ .sort((left, right) => left.relPath.localeCompare(right.relPath));
43
+ }
44
+
45
+ /**
46
+ * Evaluate batch-loc-policy without mutating the grandfather list.
47
+ *
48
+ * @param {string} projectRoot
49
+ * @param {{ grandfathered?: string[] }} [options]
50
+ * @returns {{ ok: boolean, overLimit: Array<{ relPath: string, lines: number }>, ungrandfathered: Array<{ relPath: string, lines: number }> }}
51
+ */
52
+ export function evaluateBatchLocPolicy(projectRoot, options = {}) {
53
+ const grandfathered = options.grandfathered ?? [];
54
+ const grandfatheredSet = new Set(grandfathered);
55
+ const modules = listBatchModuleLineCounts(projectRoot);
56
+ const overLimit = modules.filter((entry) => entry.lines > BATCH_MODULE_LOC_LIMIT);
57
+ const ungrandfathered = overLimit.filter((entry) => !grandfatheredSet.has(entry.relPath));
58
+ return {
59
+ ok: ungrandfathered.length === 0,
60
+ overLimit,
61
+ ungrandfathered,
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Simulate emptying PHASE23_GRANDFATHERED_OVER_500 (evaluate with empty allow-list).
67
+ *
68
+ * @param {string} projectRoot
69
+ */
70
+ export function evaluateBatchLocPolicyAfterEmptyGrandfather(projectRoot) {
71
+ return evaluateBatchLocPolicy(projectRoot, { grandfathered: [] });
72
+ }
73
+
74
+ /**
75
+ * @param {{ title?: string | null, missionText?: string, fileScope?: string[], folderName?: string }} task
76
+ */
77
+ export function isLocCapstoneEmptyGrandfatherMission(task) {
78
+ const title = task.title ?? "";
79
+ const missionText = task.missionText ?? "";
80
+ const folderName = task.folderName ?? "";
81
+ const fileScope = Array.isArray(task.fileScope) ? task.fileScope : [];
82
+ const haystack = `${title}\n${missionText}\n${folderName}`;
83
+
84
+ // Readiness / blocker packets mention emptying but must not self-trigger.
85
+ if (/\breadiness\b/i.test(haystack) && /\b(block|gate|must not)\b/i.test(haystack)) {
86
+ return false;
87
+ }
88
+
89
+ if (/grandfather[-_]list[-_]empty|empty[-_]grandfather/i.test(folderName)) {
90
+ return true;
91
+ }
92
+
93
+ if (/\bempty\s+PHASE23_GRANDFATHERED_OVER_500\b/i.test(haystack)) {
94
+ return true;
95
+ }
96
+
97
+ if (/remove\s+all\s+entries\s+from[\s`*]*PHASE23_GRANDFATHERED_OVER_500/i.test(haystack)) {
98
+ return true;
99
+ }
100
+
101
+ if (/set\s+[`'*]?PHASE23_GRANDFATHERED_OVER_500[`'*]?\s+to\s+[`'*]?\[\s*\]/i.test(haystack)) {
102
+ return true;
103
+ }
104
+
105
+ const touchesVerify = fileScope.some(
106
+ (entry) =>
107
+ entry === VERIFY_MJS_REL ||
108
+ entry.endsWith(`/${VERIFY_MJS_REL}`) ||
109
+ entry.includes("bin/spine-cli/verify.mjs"),
110
+ );
111
+ if (
112
+ touchesVerify &&
113
+ /PHASE23_GRANDFATHERED_OVER_500/.test(haystack) &&
114
+ /\b(empty(?:ing)?|clear(?:ing)?)\b/i.test(haystack) &&
115
+ !/\bmust not\b/i.test(haystack)
116
+ ) {
117
+ return true;
118
+ }
119
+
120
+ return false;
121
+ }
122
+
123
+ /**
124
+ * Format over-limit modules for operator-facing errors.
125
+ *
126
+ * @param {Array<{ relPath: string, lines: number }>} modules
127
+ */
128
+ export function formatOverLimitModules(modules) {
129
+ return modules.map((entry) => `${entry.relPath} (${entry.lines})`).join(", ");
130
+ }
131
+
132
+ /**
133
+ * @param {object} ctx
134
+ * @param {string} ctx.projectRoot
135
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
136
+ * @returns {Array<{ taskId: string, title: string | null, folderName: string }>}
137
+ */
138
+ export function listPendingLocCapstoneTasks(ctx) {
139
+ const configResult = ctx.configResult ?? loadSpineConfig(ctx.projectRoot);
140
+ const tasksRootPath = resolveTasksRoot(ctx.projectRoot, configResult);
141
+ if (!tasksRootPath) {
142
+ return [];
143
+ }
144
+
145
+ const discovered = discoverTasks(tasksRootPath);
146
+ const { pendingIds } = summarizePendingScope(discovered, tasksRootPath);
147
+ const pendingIdSet = new Set(pendingIds);
148
+ /** @type {Array<{ discoveredTask: (typeof discovered)[number], promptPath: string }>} */
149
+ const pendingPrompts = [];
150
+
151
+ for (const discoveredTask of discovered) {
152
+ if (!pendingIdSet.has(discoveredTask.taskId)) continue;
153
+ pendingPrompts.push({
154
+ discoveredTask,
155
+ promptPath: path.join(discoveredTask.folderPath, "PROMPT.md"),
156
+ });
157
+ }
158
+
159
+ const promptContents = readUtf8FilesBatchSync(
160
+ pendingPrompts.map((entry) => entry.promptPath),
161
+ );
162
+
163
+ /** @type {Array<{ taskId: string, title: string | null, folderName: string }>} */
164
+ const matches = [];
165
+ for (const { discoveredTask, promptPath } of pendingPrompts) {
166
+ const markdown = promptContents.get(promptPath) ?? "";
167
+ const prompt = parsePrompt(markdown);
168
+ const missionText = prompt.sections?.Mission ?? "";
169
+ if (
170
+ !isLocCapstoneEmptyGrandfatherMission({
171
+ title: prompt.title,
172
+ missionText,
173
+ fileScope: prompt.fileScope,
174
+ folderName: path.basename(discoveredTask.folderPath),
175
+ })
176
+ ) {
177
+ continue;
178
+ }
179
+ matches.push({
180
+ taskId: discoveredTask.taskId,
181
+ title: prompt.title,
182
+ folderName: path.basename(discoveredTask.folderPath),
183
+ });
184
+ }
185
+
186
+ return matches;
187
+ }
188
+
189
+ /**
190
+ * Fail closed when a pending LOC-capstone would empty the grandfather list
191
+ * while any src/batch/*.mjs still exceeds the LOC limit.
192
+ *
193
+ * @param {object} ctx
194
+ * @param {string} ctx.projectRoot
195
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
196
+ */
197
+ export function checkLocCapstoneReadiness(ctx) {
198
+ try {
199
+ const capstoneTasks = listPendingLocCapstoneTasks(ctx);
200
+ if (capstoneTasks.length === 0) {
201
+ return makeCheck(
202
+ "loc-capstone-readiness",
203
+ true,
204
+ "no pending empty-grandfather / LOC-capstone tasks",
205
+ );
206
+ }
207
+
208
+ const policy = evaluateBatchLocPolicyAfterEmptyGrandfather(ctx.projectRoot);
209
+ const taskPreview = capstoneTasks.map((task) => task.taskId).join(", ");
210
+ if (policy.ok) {
211
+ return makeCheck(
212
+ "loc-capstone-readiness",
213
+ true,
214
+ `LOC-capstone ready (${taskPreview}): batch-loc-policy would pass with empty grandfather`,
215
+ { details: { taskIds: capstoneTasks.map((task) => task.taskId) } },
216
+ );
217
+ }
218
+
219
+ const moduleList = formatOverLimitModules(policy.ungrandfathered);
220
+ return makeCheck(
221
+ "loc-capstone-readiness",
222
+ false,
223
+ `LOC-capstone not ready (${taskPreview}): emptying PHASE23_GRANDFATHERED_OVER_500 would fail batch-loc-policy — still over ${BATCH_MODULE_LOC_LIMIT} LOC: ${moduleList}`,
224
+ {
225
+ details: {
226
+ taskIds: capstoneTasks.map((task) => task.taskId),
227
+ overLimitModules: policy.ungrandfathered,
228
+ },
229
+ suggestedCommand:
230
+ "Split remaining src/batch/*.mjs modules to ≤500 LOC before scheduling the empty-grandfather / LOC-capstone task",
231
+ },
232
+ );
233
+ } catch (err) {
234
+ const message = err?.message ?? String(err);
235
+ return makeCheck(
236
+ "loc-capstone-readiness",
237
+ false,
238
+ `LOC-capstone readiness check failed closed: ${message}`,
239
+ { suggestedCommand: "spine preflight" },
240
+ );
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Planner-time assert: throw when selected tasks include a blocked LOC-capstone.
246
+ *
247
+ * @param {object} args
248
+ * @param {string} args.projectRoot
249
+ * @param {Array<{ taskId: string, title?: string | null, fileScope?: string[], missionText?: string, folderName?: string }>} args.tasks
250
+ */
251
+ export function assertLocCapstoneReadinessForPlan({ projectRoot, tasks }) {
252
+ const capstoneTasks = tasks.filter((task) =>
253
+ isLocCapstoneEmptyGrandfatherMission({
254
+ title: task.title,
255
+ missionText: task.missionText ?? "",
256
+ fileScope: task.fileScope,
257
+ folderName: task.folderName ?? task.taskId,
258
+ }),
259
+ );
260
+ if (capstoneTasks.length === 0) {
261
+ return;
262
+ }
263
+
264
+ const policy = evaluateBatchLocPolicyAfterEmptyGrandfather(projectRoot);
265
+ if (policy.ok) {
266
+ return;
267
+ }
268
+
269
+ const taskPreview = capstoneTasks.map((task) => task.taskId).join(", ");
270
+ const moduleList = formatOverLimitModules(policy.ungrandfathered);
271
+ throw new Error(
272
+ `LOC-capstone not ready (${taskPreview}): emptying PHASE23_GRANDFATHERED_OVER_500 would fail batch-loc-policy — still over ${BATCH_MODULE_LOC_LIMIT} LOC: ${moduleList}`,
273
+ );
274
+ }
@@ -28,6 +28,7 @@ import {
28
28
  checkPrelandedFileScopeWarn,
29
29
  runPreflightPlanCheck,
30
30
  } from "./preflight/integrate-plan.mjs";
31
+ import { checkLocCapstoneReadiness } from "./preflight/loc-capstone.mjs";
31
32
  import { INTEGRATE_DEFAULTS } from "./defaults.mjs";
32
33
  import { parseContract } from "../tasks/packet/parse-prompt.mjs";
33
34
  import { hasReleaseCriticalContract, isStubWorkerMode } from "../batch/contract-verify.mjs";
@@ -65,6 +66,18 @@ export {
65
66
  runPreflightPlanCheck,
66
67
  } from "./preflight/integrate-plan.mjs";
67
68
 
69
+ export {
70
+ assertLocCapstoneReadinessForPlan,
71
+ BATCH_MODULE_LOC_LIMIT,
72
+ checkLocCapstoneReadiness,
73
+ evaluateBatchLocPolicy,
74
+ evaluateBatchLocPolicyAfterEmptyGrandfather,
75
+ formatOverLimitModules,
76
+ isLocCapstoneEmptyGrandfatherMission,
77
+ listBatchModuleLineCounts,
78
+ listPendingLocCapstoneTasks,
79
+ } from "./preflight/loc-capstone.mjs";
80
+
68
81
  const CONCURRENT_DEV_LABEL = "concurrent development on base branch";
69
82
 
70
83
  /**
@@ -360,6 +373,7 @@ export function runBatchPreflight(options) {
360
373
  checks.push(checkWorktreeSetupHook(ctx));
361
374
  checks.push(checkTasksValidate(ctx));
362
375
  checks.push(checkStubReleaseCritical(ctx));
376
+ checks.push(checkLocCapstoneReadiness(ctx));
363
377
  checks.push(checkOrchMergeConflictWarn(ctx));
364
378
  checks.push(checkPrelandedFileScopeWarn(ctx));
365
379
 
@@ -17,11 +17,13 @@ import { buildGraph, topoWaves } from './graph.mjs';
17
17
  import { findCyclePath } from './cycles.mjs';
18
18
  import { parseScope } from './scope.mjs';
19
19
  import { collectWaveSizeWarnings, formatFileScopeOverlapWarnings, planWaves } from './waves.mjs';
20
+ import { assertLocCapstoneReadinessForPlan } from '../config/preflight/loc-capstone.mjs';
21
+ import path from 'node:path';
20
22
 
21
23
  /**
22
- * @param {{ scope?: any, config: { lanes?: { maxParallel?: number, queueExcess?: boolean } }, tasksRoot: string }} args
24
+ * @param {{ scope?: any, config: { lanes?: { maxParallel?: number, queueExcess?: boolean } }, tasksRoot: string, projectRoot?: string }} args
23
25
  */
24
- export function buildPlan({ scope, config, tasksRoot }) {
26
+ export function buildPlan({ scope, config, tasksRoot, projectRoot }) {
25
27
  if (!tasksRoot) throw new Error('buildPlan requires tasksRoot');
26
28
  if (!config) throw new Error('buildPlan requires config');
27
29
 
@@ -32,7 +34,7 @@ export function buildPlan({ scope, config, tasksRoot }) {
32
34
 
33
35
  const depsJson = loadDependenciesJson(tasksRoot);
34
36
 
35
- /** @type {Record<string, { taskId: string, title: string|null, fileScope: string[], dependencies: string[] }> } */
37
+ /** @type {Record<string, { taskId: string, title: string|null, fileScope: string[], dependencies: string[], missionText?: string, folderName?: string }> } */
36
38
  const tasksById = {};
37
39
  /** @type {Array<{ taskId: string, promptPath?: string, errors: string[] }>} */
38
40
  const promptValidationFailures = [];
@@ -56,6 +58,8 @@ export function buildPlan({ scope, config, tasksRoot }) {
56
58
  title: prompt.title ?? null,
57
59
  fileScope: Array.isArray(prompt.fileScope) ? prompt.fileScope : [],
58
60
  dependencies: mergedDeps,
61
+ missionText: prompt.sections?.Mission ?? '',
62
+ folderName: path.basename(discoveredTask.folderPath),
59
63
  };
60
64
  }
61
65
 
@@ -63,6 +67,13 @@ export function buildPlan({ scope, config, tasksRoot }) {
63
67
  throw new Error(formatPromptValidationFailures(promptValidationFailures));
64
68
  }
65
69
 
70
+ const resolvedProjectRoot =
71
+ projectRoot ?? path.resolve(tasksRoot, '..');
72
+ assertLocCapstoneReadinessForPlan({
73
+ projectRoot: resolvedProjectRoot,
74
+ tasks: selectedIdsSorted.map((taskId) => tasksById[taskId]).filter(Boolean),
75
+ });
76
+
66
77
  /** @type {Record<string, string[]>} */
67
78
  const depsByTask = {};
68
79
  for (const taskId of selectedIdsSorted) {
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Process-tree terminate — reap a PID and its descendants (SP-609 / #194).
3
+ *
4
+ * Killing only the tracked workerPid leaves nested `pi` grandchildren alive.
5
+ * List children before signaling the parent so reparenting to init cannot hide them.
6
+ */
7
+
8
+ import { spawnSync } from "node:child_process";
9
+
10
+ /** Hard cap on BFS depth when walking the process tree. */
11
+ const MAX_TREE_DEPTH = 32;
12
+
13
+ /** Hard cap on total descendant PIDs collected. */
14
+ const MAX_DESCENDANTS = 256;
15
+
16
+ /**
17
+ * @param {unknown} pid
18
+ * @returns {number[]}
19
+ */
20
+ export function listDirectChildPids(pid) {
21
+ const parent = Number(pid);
22
+ if (!Number.isFinite(parent) || parent <= 0) return [];
23
+ if (process.platform === "win32") {
24
+ return listDirectChildPidsWindows(parent);
25
+ }
26
+ const result = spawnSync("pgrep", ["-P", String(parent)], {
27
+ encoding: "utf-8",
28
+ timeout: 5_000,
29
+ });
30
+ if (result.status !== 0 && result.status !== 1) {
31
+ return [];
32
+ }
33
+ const stdout = result.stdout ?? "";
34
+ return stdout
35
+ .split(/\s+/)
36
+ .map((line) => Number(line.trim()))
37
+ .filter((n) => Number.isFinite(n) && n > 0);
38
+ }
39
+
40
+ /**
41
+ * @param {number} parent
42
+ * @returns {number[]}
43
+ */
44
+ function listDirectChildPidsWindows(parent) {
45
+ const result = spawnSync(
46
+ "wmic",
47
+ ["process", "where", `ParentProcessId=${parent}`, "get", "ProcessId", "/value"],
48
+ { encoding: "utf-8", timeout: 5_000, windowsHide: true },
49
+ );
50
+ if (result.error || (result.status !== 0 && result.status !== 1)) {
51
+ return [];
52
+ }
53
+ const stdout = result.stdout ?? "";
54
+ /** @type {number[]} */
55
+ const children = [];
56
+ for (const match of stdout.matchAll(/ProcessId=(\d+)/g)) {
57
+ const n = Number(match[1]);
58
+ if (Number.isFinite(n) && n > 0) children.push(n);
59
+ }
60
+ return children;
61
+ }
62
+
63
+ /**
64
+ * Breadth-first descendant PIDs (excludes the root). Bounded depth and count.
65
+ *
66
+ * @param {unknown} pid
67
+ * @returns {number[]}
68
+ */
69
+ export function listDescendantPids(pid) {
70
+ const root = Number(pid);
71
+ if (!Number.isFinite(root) || root <= 0) return [];
72
+ /** @type {number[]} */
73
+ const descendants = [];
74
+ /** @type {Set<number>} */
75
+ const seen = new Set([root]);
76
+ /** @type {Array<{ pid: number, depth: number }>} */
77
+ const queue = [{ pid: root, depth: 0 }];
78
+
79
+ while (queue.length > 0) {
80
+ const current = queue.shift();
81
+ if (!current) break;
82
+ if (current.depth >= MAX_TREE_DEPTH) continue;
83
+ if (descendants.length >= MAX_DESCENDANTS) break;
84
+ for (const child of listDirectChildPids(current.pid)) {
85
+ if (seen.has(child)) continue;
86
+ seen.add(child);
87
+ descendants.push(child);
88
+ if (descendants.length >= MAX_DESCENDANTS) break;
89
+ queue.push({ pid: child, depth: current.depth + 1 });
90
+ }
91
+ }
92
+ return descendants;
93
+ }
94
+
95
+ /**
96
+ * @param {number} pid
97
+ * @param {NodeJS.Signals} signal
98
+ * @returns {boolean} true when the signal was delivered
99
+ */
100
+ function tryKill(pid, signal) {
101
+ try {
102
+ process.kill(pid, signal);
103
+ return true;
104
+ } catch {
105
+ return false;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Terminate a process and its descendants.
111
+ *
112
+ * On Unix, also attempts process-group kill (`-pid`) when the target is a
113
+ * group leader. On Windows, prefers `taskkill /T` then falls back to tree walk.
114
+ *
115
+ * @param {unknown} pid
116
+ * @param {{ signal?: NodeJS.Signals }} [options]
117
+ * @returns {{ rootPid: number, signal: NodeJS.Signals, descendantPids: number[], signaled: number[] }}
118
+ */
119
+ export function terminateProcessTree(pid, { signal = "SIGKILL" } = {}) {
120
+ const rootPid = Number(pid);
121
+ /** @type {number[]} */
122
+ const signaled = [];
123
+ if (!Number.isFinite(rootPid) || rootPid <= 0) {
124
+ return { rootPid: 0, signal, descendantPids: [], signaled };
125
+ }
126
+
127
+ if (process.platform === "win32") {
128
+ const taskkill = spawnSync(
129
+ "taskkill",
130
+ ["/PID", String(rootPid), "/T", "/F"],
131
+ { encoding: "utf-8", timeout: 10_000, windowsHide: true },
132
+ );
133
+ if (taskkill.status === 0) {
134
+ return { rootPid, signal, descendantPids: [], signaled: [rootPid] };
135
+ }
136
+ }
137
+
138
+ const descendantPids = listDescendantPids(rootPid);
139
+
140
+ // Deepest-first so parents do not reparent before children are signaled.
141
+ for (let i = descendantPids.length - 1; i >= 0; i -= 1) {
142
+ const childPid = descendantPids[i];
143
+ if (tryKill(childPid, signal)) signaled.push(childPid);
144
+ }
145
+
146
+ if (process.platform !== "win32") {
147
+ // Negative PID = process group; succeeds when root is the group leader.
148
+ tryKill(-rootPid, signal);
149
+ }
150
+
151
+ if (tryKill(rootPid, signal)) signaled.push(rootPid);
152
+
153
+ return { rootPid, signal, descendantPids, signaled };
154
+ }