pi-spine 2.2.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.
Files changed (56) hide show
  1. package/bin/spine-cli/verify.mjs +15 -46
  2. package/package.json +1 -1
  3. package/src/batch/attached-runner-promote.mjs +370 -0
  4. package/src/batch/attached-runner-reconcile.mjs +291 -0
  5. package/src/batch/attached-runner.mjs +24 -645
  6. package/src/batch/batch-guards.mjs +69 -0
  7. package/src/batch/contract-exec.mjs +483 -0
  8. package/src/batch/contract-parse.mjs +243 -0
  9. package/src/batch/contract-verify.mjs +32 -707
  10. package/src/batch/detached-diagnostics.mjs +255 -0
  11. package/src/batch/detached-run.mjs +326 -0
  12. package/src/batch/detached-start.mjs +18 -894
  13. package/src/batch/detached-wait.mjs +346 -0
  14. package/src/batch/diagnosis.mjs +35 -4
  15. package/src/batch/engine-lanes/orch-sync.mjs +126 -0
  16. package/src/batch/engine-lanes.mjs +69 -0
  17. package/src/batch/engine.mjs +8 -67
  18. package/src/batch/integrate-git.mjs +21 -0
  19. package/src/batch/integrate.mjs +5 -15
  20. package/src/batch/journal-rebuild-structural.mjs +352 -0
  21. package/src/batch/journal-rebuild.mjs +16 -348
  22. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  23. package/src/batch/lane-dirty-check-git.mjs +298 -0
  24. package/src/batch/lane-dirty-check.mjs +31 -297
  25. package/src/batch/reconcile-batch.mjs +495 -0
  26. package/src/batch/reconcile-classify.mjs +433 -0
  27. package/src/batch/reconcile-diagnosis.mjs +459 -0
  28. package/src/batch/reconcile-light-cache.mjs +61 -0
  29. package/src/batch/reconcile-orphan.mjs +198 -0
  30. package/src/batch/reconcile.mjs +19 -1693
  31. package/src/batch/resume-multi-lanes.mjs +6 -148
  32. package/src/batch/resume-multi-queue.mjs +159 -0
  33. package/src/batch/resume-single-validate.mjs +25 -0
  34. package/src/batch/resume.mjs +3 -20
  35. package/src/batch/review-artifacts.mjs +419 -0
  36. package/src/batch/review-step-run.mjs +383 -0
  37. package/src/batch/review-step.mjs +451 -0
  38. package/src/batch/review.mjs +32 -1199
  39. package/src/batch/salvage-batch-list.mjs +291 -0
  40. package/src/batch/salvage-batch.mjs +10 -284
  41. package/src/batch/sequence-plan.mjs +234 -0
  42. package/src/batch/sequence-run.mjs +418 -0
  43. package/src/batch/sequence-wait.mjs +167 -0
  44. package/src/batch/sequence.mjs +22 -783
  45. package/src/batch/state-guards.mjs +284 -0
  46. package/src/batch/state-io.mjs +135 -0
  47. package/src/batch/state.mjs +27 -396
  48. package/src/batch/worker-heartbeat.mjs +382 -0
  49. package/src/batch/worker-host.mjs +56 -548
  50. package/src/batch/worker-spawn.mjs +326 -0
  51. package/src/batch/worktree.mjs +68 -0
  52. package/src/config/preflight/integrate-plan.mjs +6 -1
  53. package/src/config/preflight/loc-capstone.mjs +274 -0
  54. package/src/config/spine-preflight-lib.mjs +14 -0
  55. package/src/planner/index.mjs +14 -3
  56. package/src/process/terminate-tree.mjs +154 -0
@@ -0,0 +1,326 @@
1
+ // @ts-check
2
+ /**
3
+ * pi-spine worker spawn — child process setup, env, and output streaming (SP-581).
4
+ */
5
+
6
+ import path from "node:path";
7
+ import { spawn } from "node:child_process";
8
+ import { fileURLToPath } from "node:url";
9
+ import { startAgentSessionWorker } from "./agent-session-worker.mjs";
10
+ import { resolveWorkerBackend } from "../config/worker-backend.mjs";
11
+ import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
12
+ import { resolveSafeWorkerLaunchScript } from "../config/worker-launch-script.mjs";
13
+ import { terminateProcessTree } from "../process/terminate-tree.mjs";
14
+
15
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
+ const PACKAGE_ROOT = path.resolve(__dirname, "../..");
17
+
18
+ export const POST_DONE_KILL_BACKOFF_MS = 5_000;
19
+ export const CHILD_DONE_TIMEOUT_MS = 15_000;
20
+
21
+ /** @typedef {"launching" | "pi" | "verify" | "unknown"} WorkerPhase */
22
+
23
+ /**
24
+ * @typedef {import("node:child_process").ChildProcess | {
25
+ * pid: number;
26
+ * exitCode: number | null;
27
+ * kill: (signal?: NodeJS.Signals) => boolean;
28
+ * wait?: () => Promise<{ exitCode: number; output: string }>;
29
+ * stdout?: NodeJS.ReadableStream | null;
30
+ * stderr?: NodeJS.ReadableStream | null;
31
+ * on?: import("node:events").EventEmitter["on"];
32
+ * }} WorkerChildHandle
33
+ */
34
+
35
+ /**
36
+ * @param {number} ms
37
+ */
38
+ function sleep(ms) {
39
+ return new Promise((resolve) => setTimeout(resolve, ms));
40
+ }
41
+
42
+ /**
43
+ * @param {string} projectRoot
44
+ * @param {object} [config]
45
+ * @returns {string|null}
46
+ */
47
+ export function resolveWorkerLaunchScript(projectRoot, config = {}) {
48
+ return resolveSafeWorkerLaunchScript(projectRoot, config);
49
+ }
50
+
51
+ /**
52
+ * @param {object} params
53
+ * @param {string} params.taskFolder
54
+ * @param {string} params.worktreePath
55
+ * @param {string} [params.projectRoot]
56
+ * @param {string} [params.batchId]
57
+ * @param {number} [params.laneNumber]
58
+ * @param {string} [params.taskId]
59
+ * @param {string} [params.laneCorrelationId]
60
+ * @param {string[]} [params.fileScopePaths]
61
+ * @param {object} [params.config]
62
+ * @param {number} [params.piTimeoutMs]
63
+ */
64
+ export function buildWorkerChildEnv({
65
+ taskFolder,
66
+ worktreePath,
67
+ projectRoot,
68
+ batchId,
69
+ laneNumber,
70
+ taskId,
71
+ laneCorrelationId,
72
+ fileScopePaths = [],
73
+ config = {},
74
+ piTimeoutMs,
75
+ }) {
76
+ const runner = path.join(PACKAGE_ROOT, "bin", "spine-worker-runner.mjs");
77
+ /** @type {NodeJS.ProcessEnv} */
78
+ const env = {
79
+ ...process.env,
80
+ SPINE_TASK_FOLDER: taskFolder,
81
+ SPINE_WORKTREE: worktreePath,
82
+ SPINE_WORKER_RUNNER: runner,
83
+ SPINE_IS_WORKER: "1",
84
+ PI_SPINE_ROOT: resolvePiSpineRoot(config, projectRoot ?? process.cwd()),
85
+ };
86
+ if (projectRoot) env.SPINE_PROJECT_ROOT = projectRoot;
87
+ if (worktreePath) env.SPINE_RULES_PROJECT_ROOT = worktreePath;
88
+ if (batchId) {
89
+ env.SPINE_BATCH_ID = batchId;
90
+ env.SPINE_JOURNAL_ATTACH = "1";
91
+ delete env.SPINE_SUPPRESS_JOURNAL_ATTACH;
92
+ }
93
+ if (laneNumber != null) env.SPINE_LANE_NUMBER = String(laneNumber);
94
+ if (taskId) env.SPINE_TASK_ID = taskId;
95
+ if (laneCorrelationId) env.SPINE_LANE_CORRELATION_ID = laneCorrelationId;
96
+ if (Array.isArray(fileScopePaths) && fileScopePaths.length > 0) {
97
+ env.SPINE_TASK_FILE_SCOPE = JSON.stringify(fileScopePaths);
98
+ }
99
+ if (process.env.SPINE_WORKER_STUB === "1") {
100
+ env.SPINE_REVIEW_STUB = "1";
101
+ }
102
+ if (piTimeoutMs != null && Number.isFinite(piTimeoutMs) && piTimeoutMs > 0) {
103
+ env.SPINE_WORKER_PI_TIMEOUT_MS = String(
104
+ process.env.SPINE_WORKER_PI_TIMEOUT_MS ?? piTimeoutMs,
105
+ );
106
+ }
107
+ return env;
108
+ }
109
+
110
+ /**
111
+ * @param {object} params
112
+ * @param {string} params.worktreePath
113
+ * @param {string} params.taskFolder
114
+ * @param {boolean} params.useStub
115
+ * @param {number} params.timeoutMs
116
+ * @param {string} [params.projectRoot]
117
+ * @param {string} [params.batchId]
118
+ * @param {number} [params.laneNumber]
119
+ * @param {string} [params.taskId]
120
+ * @param {string} [params.laneCorrelationId]
121
+ * @param {string[]} [params.fileScopePaths]
122
+ * @param {object} [params.config]
123
+ * @param {number} [params.piTimeoutMs]
124
+ */
125
+ export function spawnWorkerChild({
126
+ worktreePath,
127
+ taskFolder,
128
+ useStub,
129
+ timeoutMs: _timeoutMs,
130
+ projectRoot,
131
+ batchId,
132
+ laneNumber,
133
+ taskId,
134
+ laneCorrelationId,
135
+ fileScopePaths = [],
136
+ config = {},
137
+ piTimeoutMs,
138
+ }) {
139
+ const runner = path.join(PACKAGE_ROOT, "bin", "spine-worker-runner.mjs");
140
+ const env = buildWorkerChildEnv({
141
+ taskFolder,
142
+ worktreePath,
143
+ projectRoot,
144
+ batchId,
145
+ laneNumber,
146
+ taskId,
147
+ laneCorrelationId,
148
+ fileScopePaths,
149
+ config,
150
+ piTimeoutMs,
151
+ });
152
+ const args = useStub ? ["--stub"] : ["--pi"];
153
+
154
+ const launchScript = projectRoot ? resolveWorkerLaunchScript(projectRoot, config) : null;
155
+ if (launchScript) {
156
+ return spawn(launchScript, [runner, ...args], {
157
+ cwd: worktreePath,
158
+ env,
159
+ stdio: ["ignore", "pipe", "pipe"],
160
+ });
161
+ }
162
+
163
+ return spawn(process.execPath, [runner, ...args], {
164
+ cwd: worktreePath,
165
+ env,
166
+ stdio: ["ignore", "pipe", "pipe"],
167
+ });
168
+ }
169
+
170
+ /**
171
+ * @param {WorkerChildHandle} child
172
+ * @param {() => void} onPreflightComplete
173
+ */
174
+ export function markChildPastPreflight(child, onPreflightComplete) {
175
+ if (typeof child.stdout?.on === "function") {
176
+ child.stdout.on("data", onPreflightComplete);
177
+ }
178
+ if (typeof child.stderr?.on === "function") {
179
+ child.stderr.on("data", onPreflightComplete);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * @param {object} params
185
+ * @param {boolean} params.childPastPreflight
186
+ * @param {boolean} params.useStub
187
+ * @param {string} params.workerBackend
188
+ * @returns {WorkerPhase}
189
+ */
190
+ export function resolveWorkerPhase({
191
+ childPastPreflight,
192
+ useStub,
193
+ workerBackend,
194
+ }) {
195
+ if (!childPastPreflight) return "launching";
196
+ if (useStub || workerBackend === "agentSession") return "pi";
197
+ return "pi";
198
+ }
199
+
200
+ /**
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).
203
+ *
204
+ * @param {WorkerChildHandle} child
205
+ * @param {Promise<{ exitCode: number; output: string }>} childDone
206
+ */
207
+ export async function terminateHungWorkerChild(child, childDone) {
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
+ }
214
+ const raced = await Promise.race([childDone, sleep(POST_DONE_KILL_BACKOFF_MS)]);
215
+ if (raced && typeof raced === "object" && "exitCode" in raced) {
216
+ return raced;
217
+ }
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
+ }
224
+ }
225
+ return childDone;
226
+ }
227
+
228
+ /**
229
+ * @param {WorkerChildHandle} child
230
+ * @param {{ append: (rawChunk: string) => void } | null} [liveLogWriter]
231
+ */
232
+ export function collectChildOutput(child, liveLogWriter) {
233
+ if ("wait" in child && typeof child.wait === "function") {
234
+ return child.wait();
235
+ }
236
+ return new Promise((resolve) => {
237
+ let stdout = "";
238
+ let stderr = "";
239
+ child.stdout?.on("data", (/** @type {Buffer | string} */ chunk) => {
240
+ const text = chunk.toString();
241
+ stdout += text;
242
+ liveLogWriter?.append(text);
243
+ });
244
+ child.stderr?.on("data", (/** @type {Buffer | string} */ chunk) => {
245
+ const text = chunk.toString();
246
+ stderr += text;
247
+ liveLogWriter?.append(text);
248
+ });
249
+ child.on?.("close", (/** @type {number | null} */ code) => {
250
+ resolve({ exitCode: code ?? 1, output: `${stdout}${stderr}` });
251
+ });
252
+ });
253
+ }
254
+
255
+ /**
256
+ * @param {object} params
257
+ * @param {string} params.worktreePath
258
+ * @param {string} params.taskFolder
259
+ * @param {boolean} params.useStub
260
+ * @param {number} params.timeoutMs
261
+ * @param {number} [params.piTimeoutMs]
262
+ * @param {string} [params.projectRoot]
263
+ * @param {string} [params.batchId]
264
+ * @param {number} [params.laneNumber]
265
+ * @param {string} [params.taskId]
266
+ * @param {string} [params.laneCorrelationId]
267
+ * @param {string[]} [params.fileScopePaths]
268
+ * @param {object} [params.config]
269
+ * @param {object} [params.workerBackendDeps]
270
+ */
271
+ export function spawnWorkerHandle({
272
+ worktreePath,
273
+ taskFolder,
274
+ useStub,
275
+ timeoutMs,
276
+ piTimeoutMs,
277
+ projectRoot,
278
+ batchId,
279
+ laneNumber,
280
+ taskId,
281
+ laneCorrelationId,
282
+ fileScopePaths = [],
283
+ config,
284
+ workerBackendDeps,
285
+ }) {
286
+ const journal =
287
+ projectRoot && batchId
288
+ ? {
289
+ projectRoot,
290
+ batchId,
291
+ taskId,
292
+ laneNumber,
293
+ correlationId: laneCorrelationId,
294
+ }
295
+ : undefined;
296
+
297
+ if (!useStub && resolveWorkerBackend(config) === "agentSession") {
298
+ return startAgentSessionWorker(
299
+ /** @type {{ worktreePath: string; taskFolder: string; config?: object; taskFileScope?: string[]; journal?: import("../config/worker-context.mjs").WorkerRulesJournalContext; projectRoot?: string }} */ ({
300
+ worktreePath,
301
+ taskFolder,
302
+ config,
303
+ taskFileScope: fileScopePaths,
304
+ journal,
305
+ projectRoot,
306
+ }),
307
+ workerBackendDeps ?? {},
308
+ );
309
+ }
310
+
311
+ return spawnWorkerChild({
312
+ worktreePath,
313
+ taskFolder,
314
+ useStub,
315
+ timeoutMs,
316
+ piTimeoutMs,
317
+ projectRoot,
318
+ batchId,
319
+ laneNumber,
320
+ taskId,
321
+ laneCorrelationId,
322
+ fileScopePaths,
323
+ config,
324
+ });
325
+ }
326
+
@@ -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
+ }