pi-spine 2.3.0 → 2.3.2

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.
@@ -59,9 +59,26 @@ export function detectPostMergeLimboForResume({ projectRoot, state }) {
59
59
 
60
60
  export { hasPendingWaveMerge } from "./merge/wave-merge-state.mjs";
61
61
 
62
+ /**
63
+ * Whether every task is terminal-success (or skipped) for #196 drift recovery.
64
+ *
65
+ * @param {object|null|undefined} state
66
+ */
67
+ function allTasksTerminalSuccessForResume(state) {
68
+ const tasks = state?.tasks ?? [];
69
+ if (tasks.length < 1) return false;
70
+ return tasks.every((task) => {
71
+ const status = String(task?.status ?? "").toLowerCase();
72
+ return status === "succeeded" || status === "skipped";
73
+ });
74
+ }
75
+
62
76
  /**
63
77
  * Assess whether a running-phase batch may resume after a dead detached engine (SP-296).
64
78
  *
79
+ * Also covers SP-613 / #196: pidless engine + all tasks terminal-success + pending wave
80
+ * merge (doneInLane healed, enginePid cleared) must not dead-end on phase=running.
81
+ *
65
82
  * @param {object} params
66
83
  * @param {string} params.projectRoot
67
84
  * @param {object} params.state
@@ -83,17 +100,25 @@ export function assessRunningPhaseResumeEligibility({ projectRoot, state }) {
83
100
  const enginePid = readBatchEnginePid(state);
84
101
  const enginePidDead = enginePid != null && !isProcessAlive(enginePid);
85
102
  const pidlessEngineOrphan = enginePid == null && orphanRunning?.kind === "engine";
86
- const engineConfirmedDead = enginePidDead || pidlessEngineOrphan;
103
+ // Dead/missing engine with work finished but merge not landed — agent-safe detached resume (#196).
104
+ const pidlessTerminalSuccessPendingMerge =
105
+ enginePid == null &&
106
+ allTasksTerminalSuccessForResume(state) &&
107
+ hasPendingWaveMerge(state);
108
+ const engineConfirmedDead =
109
+ enginePidDead || pidlessEngineOrphan || pidlessTerminalSuccessPendingMerge;
87
110
 
88
111
  const allowOrphanResume =
89
112
  engineConfirmedDead &&
90
- orphanRunning != null &&
91
- (orphanRunning.kind === "engine" || orphanRunning.kind === "lane");
113
+ ((orphanRunning != null &&
114
+ (orphanRunning.kind === "engine" || orphanRunning.kind === "lane")) ||
115
+ pidlessTerminalSuccessPendingMerge);
92
116
 
93
117
  return {
94
118
  engineConfirmedDead,
95
119
  allowOrphanResume,
96
- orphanKind: orphanRunning?.kind ?? null,
120
+ orphanKind: orphanRunning?.kind ?? (pidlessTerminalSuccessPendingMerge ? "engine" : null),
121
+ terminalSuccessPendingMerge: pidlessTerminalSuccessPendingMerge,
97
122
  };
98
123
  }
99
124
 
@@ -115,19 +115,52 @@ function laneNumbersFromTasks(tasks) {
115
115
  return lanes;
116
116
  }
117
117
 
118
+ /**
119
+ * Journal rebuild may drop seed done* flags; merge them for salvage discovery (#196).
120
+ *
121
+ * @param {object} rebuiltTask
122
+ * @param {object[]|undefined} seedTasks
123
+ */
124
+ function enrichTaskWithSeedEvidence(rebuiltTask, seedTasks) {
125
+ const taskId = String(rebuiltTask?.taskId ?? "");
126
+ if (!taskId || !Array.isArray(seedTasks)) return rebuiltTask;
127
+ const seed = seedTasks.find((task) => String(task?.taskId ?? "") === taskId);
128
+ if (!seed) return rebuiltTask;
129
+ return {
130
+ ...rebuiltTask,
131
+ doneInLane: rebuiltTask?.doneInLane === true || seed.doneInLane === true,
132
+ doneFileFound: rebuiltTask?.doneFileFound === true || seed.doneFileFound === true,
133
+ doneOnMain: rebuiltTask?.doneOnMain === true || seed.doneOnMain === true,
134
+ classification:
135
+ rebuiltTask?.classification ??
136
+ seed.classification ??
137
+ undefined,
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Terminal-success / lane `.DONE` evidence — journal `lane.committed` is optional (#196 / FR-REL232-02).
143
+ * Git commits-ahead on the lane task branch remains the hard gate in `listSalvageableLanes`.
144
+ *
145
+ * @param {object} task
146
+ */
147
+ function isTerminalSuccessTask(task) {
148
+ const status = String(task?.status ?? "").toLowerCase();
149
+ if (status === "succeeded" || status === "skipped") return true;
150
+ if (task?.doneInLane === true || task?.doneFileFound === true || task?.doneOnMain === true) {
151
+ return true;
152
+ }
153
+ return String(task?.classification ?? "").toLowerCase() === "terminal-success";
154
+ }
155
+
118
156
  /**
119
157
  * @param {object} task
120
- * @param {Set<string>} committedTaskIds
121
158
  */
122
- function isSalvageableTask(task, committedTaskIds) {
159
+ function isSalvageableTask(task) {
123
160
  const taskId = String(task?.taskId ?? "");
124
161
  if (!taskId) return false;
125
- if (!committedTaskIds.has(taskId)) return false;
126
-
127
- const status = String(task?.status ?? "").toLowerCase();
128
- if (status !== "succeeded" && status !== "skipped") return false;
129
162
  if (isNonSalvageableExitReason(task?.exitReason)) return false;
130
- return true;
163
+ return isTerminalSuccessTask(task);
131
164
  }
132
165
 
133
166
  /**
@@ -165,11 +198,13 @@ export function listSalvageableLanes(projectRoot, batchId) {
165
198
  const rebuilt = rebuildBatchStateFromJournal(seedState, journalEvents);
166
199
  const baseBranch = String(rebuilt.baseBranch ?? seedState?.baseBranch ?? "main");
167
200
  const committedTaskIds = laneCommittedTaskIds(journalEvents);
201
+ const seedTasks = seedState?.tasks;
168
202
 
169
203
  /** @type {Map<number, { laneNumber: number, salvageableTasks: string[], excludedTasks: string[] }>} */
170
204
  const laneMap = new Map();
171
205
 
172
- for (const task of rebuilt.tasks ?? []) {
206
+ for (const rawTask of rebuilt.tasks ?? []) {
207
+ const task = enrichTaskWithSeedEvidence(rawTask, seedTasks);
173
208
  const laneNumber = Number(task?.laneNumber);
174
209
  if (!Number.isFinite(laneNumber) || laneNumber <= 0) continue;
175
210
 
@@ -182,17 +217,15 @@ export function listSalvageableLanes(projectRoot, batchId) {
182
217
  const status = String(task.status ?? "").toLowerCase();
183
218
  const hasLaneCommit = committedTaskIds.has(taskId);
184
219
 
185
- if (hasLaneCommit && isNonSalvageableExitReason(task.exitReason)) {
220
+ // Exclude non-salvageable exit reasons even when journal lacks lane.committed (#196).
221
+ if (isNonSalvageableExitReason(task.exitReason)) {
186
222
  laneEntry.excludedTasks.push(taskId);
187
223
  continue;
188
224
  }
189
225
 
190
- if (isSalvageableTask(task, committedTaskIds)) {
226
+ if (isSalvageableTask(task)) {
191
227
  laneEntry.salvageableTasks.push(taskId);
192
- } else if (
193
- hasLaneCommit &&
194
- (status === "failed" || isNonSalvageableExitReason(task.exitReason))
195
- ) {
228
+ } else if (hasLaneCommit && status === "failed") {
196
229
  laneEntry.excludedTasks.push(taskId);
197
230
  }
198
231
  }
@@ -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