pi-spine 2.23.0 → 2.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-worker-runner.mjs +2 -1
  3. package/package.json +5 -5
  4. package/src/batch/attached-runner-promote.mjs +14 -0
  5. package/src/batch/batch-state-io.mjs +120 -45
  6. package/src/batch/engine-crash-guard.mjs +143 -0
  7. package/src/batch/engine-lanes/matrix-run.mjs +28 -2
  8. package/src/batch/engine-lanes/matrix.mjs +143 -8
  9. package/src/batch/integrate-dirty-overlap.mjs +35 -0
  10. package/src/batch/integrate-worktree.mjs +106 -13
  11. package/src/batch/integrate.mjs +34 -93
  12. package/src/batch/journal-checksum.mjs +26 -0
  13. package/src/batch/journal.mjs +32 -13
  14. package/src/batch/lifecycle-archive.mjs +8 -2
  15. package/src/batch/lifecycle.mjs +2 -2
  16. package/src/batch/reconcile-batch.mjs +26 -19
  17. package/src/batch/reconcile-classify.mjs +21 -11
  18. package/src/batch/reconcile-diagnosis-context.mjs +1 -2
  19. package/src/batch/reconcile-diagnosis.mjs +18 -19
  20. package/src/batch/reconcile-light-cache.mjs +0 -1
  21. package/src/batch/reconcile-orphan.mjs +9 -8
  22. package/src/batch/reconcile.mjs +0 -1
  23. package/src/batch/salvage-batch-integrate.mjs +13 -17
  24. package/src/batch/state.mjs +22 -1
  25. package/src/batch/worker-heartbeat.mjs +29 -8
  26. package/src/batch/worker-host.mjs +29 -4
  27. package/src/batch/worker-output.mjs +9 -6
  28. package/src/batch/worker-prompt.mjs +4 -2
  29. package/src/batch/worker-spawn.mjs +99 -12
  30. package/src/config/preflight/discovery.mjs +20 -12
  31. package/src/doctor/run-doctor-checks.mjs +41 -3
  32. package/src/planner/scope.mjs +3 -1
  33. package/src/tasks/packet/discover.mjs +59 -3
@@ -8,10 +8,10 @@ import readline from "node:readline/promises";
8
8
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
9
  import { countCommitsAhead } from "./lane-commit.mjs";
10
10
  import { checkIntegrateGate } from "./gate.mjs";
11
- import { gitExec } from "./git-exec.mjs";
12
- import { mergeOrchIntoBaseIsolated, syncPlumbingMergePathsToWorktree } from "./integrate-worktree.mjs";
11
+ import { mergeOrchIntoBaseIsolated, syncMergeResultToCheckedOutBase } from "./integrate-worktree.mjs";
12
+ import { reportDirtyOverlap } from "./integrate-dirty-overlap.mjs";
13
13
  import { appendJournalEvent } from "./journal.mjs";
14
- import { resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
14
+ import { listIntegrateDirtyPaths, resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
15
15
  import {
16
16
  gateBlockedOnMissingGate,
17
17
  openGateFromSalvageEvidence,
@@ -20,14 +20,6 @@ import { healAfterSalvageLand } from "./salvage-batch-integrate-heal.mjs";
20
20
  import { laneTaskBranch } from "./worktree.mjs";
21
21
  import { listSalvageableLanes } from "./salvage-batch-list.mjs";
22
22
 
23
- /**
24
- * @param {string} projectRoot
25
- * @param {string[]} args
26
- */
27
- function git(projectRoot, args) {
28
- return gitExec(projectRoot, args, { projectRoot });
29
- }
30
-
31
23
  /**
32
24
  * Default interactive confirmation for salvage integrate.
33
25
  *
@@ -324,6 +316,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
324
316
  gateOpenedBySalvage,
325
317
  });
326
318
 
319
+ const preMergeDirtyPaths = listIntegrateDirtyPaths(projectRoot); // before merge moves base ref (SP-784)
327
320
  const mergeResult = mergeOrchIntoBaseIsolated({
328
321
  projectRoot,
329
322
  baseBranch,
@@ -358,12 +351,9 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
358
351
  }
359
352
 
360
353
  const mergeCommit = mergeResult.mergeCommit;
361
- /** @type {{ ok: boolean, timedOut?: boolean, error?: string } | null} */
362
- let syncResult = null;
363
- if (mergeResult.mode === "plumbing") {
364
- const baseSha = git(projectRoot, ["rev-parse", `${mergeCommit}^1`]);
365
- syncResult = syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit);
366
- }
354
+ const syncResult = syncMergeResultToCheckedOutBase(projectRoot, baseBranch, mergeResult, {
355
+ dirtyPaths: preMergeDirtyPaths,
356
+ });
367
357
 
368
358
  if (syncResult && !syncResult.ok) {
369
359
  appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
@@ -391,6 +381,11 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
391
381
  };
392
382
  }
393
383
 
384
+ const dirtyOverlapWarning = reportDirtyOverlap({
385
+ projectRoot, batchId: resolvedBatchId, baseBranch, orchBranch: taskBranch, mergeCommit,
386
+ skippedDirtyPaths: syncResult?.skippedDirtyPaths, laneNumber: laneNum,
387
+ });
388
+
394
389
  // Landed lane work clears the salvaged tasks' failure gate (#292 / SP-763).
395
390
  const heal = healAfterSalvageLand(projectRoot, resolvedBatchId, lane, mergeCommit);
396
391
 
@@ -419,6 +414,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
419
414
  healedTaskIds: heal.healedTaskIds,
420
415
  healError: heal.healError,
421
416
  gateOpenedBySalvage,
417
+ ...(dirtyOverlapWarning ? { warnings: [dirtyOverlapWarning] } : {}),
422
418
  headline: `Salvaged lane ${laneNum} (${taskBranch}) into ${baseBranch}`,
423
419
  suggestedCommand: "spine status --diagnose",
424
420
  };
@@ -125,10 +125,24 @@ export function failBatchFromEngineError({
125
125
  }
126
126
 
127
127
  /**
128
+ * Fail closed when the on-disk batch state must not be silently replaced.
129
+ *
130
+ * Corrupt spine-owned state is quarantined (never deleted) and start refuses
131
+ * with an actionable recovery message (SP-786 / #303). This gate runs even
132
+ * when preflight is skipped: the engine calls `assertNoActiveBatch`
133
+ * unconditionally on every start path. A Taskplane-owned `.pi/batch-state.json`
134
+ * is never modified — a corrupt one is reported instead.
135
+ *
128
136
  * @param {string} projectRoot
129
137
  */
130
138
  export function assertNoActiveBatch(projectRoot) {
131
- clearStaleTerminalBatchStateForStart(projectRoot);
139
+ const clearResult = clearStaleTerminalBatchStateForStart(projectRoot);
140
+ if (clearResult.reason === "corrupt") {
141
+ throw new Error(
142
+ `Batch state was corrupt and has been quarantined to ${clearResult.quarantinedPath}. ` +
143
+ "Inspect it and the journal (spine status --diagnose), then run spine batch dismiss --force before starting a new batch.",
144
+ );
145
+ }
132
146
 
133
147
  const spine = loadSpineBatchState(projectRoot);
134
148
  if (spine.path && spine.raw) {
@@ -141,6 +155,13 @@ export function assertNoActiveBatch(projectRoot) {
141
155
  }
142
156
 
143
157
  const any = loadBatchStateFile(projectRoot);
158
+ if (any.path && any.parseError) {
159
+ // Corrupt Taskplane-owned state: reported, never modified by spine (SP-786 / #303).
160
+ throw new Error(
161
+ `Batch state at ${any.path} is corrupt and was left unmodified by spine (${any.parseError}). ` +
162
+ "Inspect it (spine status --diagnose), then repair or remove it with the owning tool before starting a new batch.",
163
+ );
164
+ }
144
165
  if (any.path && any.raw) {
145
166
  const phase = String(any.raw.phase ?? "");
146
167
  const active =
@@ -37,10 +37,20 @@ import { terminateProcessTree } from "../process/terminate-tree.mjs";
37
37
  /**
38
38
  * @param {number} ms
39
39
  */
40
- function sleep(ms) {
40
+ function defaultSleep(ms) {
41
41
  return new Promise((resolve) => setTimeout(resolve, ms));
42
42
  }
43
43
 
44
+ /**
45
+ * Injectable timing for `pollWorkerUntilSettled` (SP-779 / #308). Tests pass a
46
+ * virtual clock so stall classification is wall-clock independent; production
47
+ * callers omit `deps` and keep the Date.now/setTimeout defaults.
48
+ *
49
+ * @typedef {object} WorkerPollDeps
50
+ * @property {() => number} [now] Clock read at the top of every poll (default `Date.now`).
51
+ * @property {(ms: number) => Promise<void>} [sleep] Inter-poll wait (default `setTimeout`).
52
+ */
53
+
44
54
  /**
45
55
  * @typedef {object} WorkerPollState
46
56
  * @property {number} stallAnchorAt
@@ -112,6 +122,7 @@ export function createWorkerPollState(startedAt, workerPhase) {
112
122
  * signals?: object;
113
123
  * }) => object} params.buildFailureResult
114
124
  * @param {string} params.workerMode
125
+ * @param {WorkerPollDeps} [params.deps] Injectable timing; defaults preserve production behavior.
115
126
  * @returns {Promise<
116
127
  * | { kind: "settled"; postDoneTerminated: boolean }
117
128
  * | { kind: "failure"; result: object }
@@ -139,7 +150,9 @@ export async function pollWorkerUntilSettled({
139
150
  onHeartbeat,
140
151
  buildFailureResult,
141
152
  workerMode,
153
+ deps = {},
142
154
  }) {
155
+ const { now: nowFn = Date.now, sleep: sleepFn = defaultSleep } = deps;
143
156
  let {
144
157
  stallAnchorAt,
145
158
  lastCheckpointAt,
@@ -157,7 +170,7 @@ export async function pollWorkerUntilSettled({
157
170
 
158
171
  while (true) {
159
172
  const doneOnDisk = fs.existsSync(donePath);
160
- const now = Date.now();
173
+ const now = nowFn();
161
174
 
162
175
  if (doneOnDisk && postDoneStartedAt === null) {
163
176
  postDoneStartedAt = now;
@@ -208,7 +221,10 @@ export async function pollWorkerUntilSettled({
208
221
  await terminateHungWorkerChild(workerChild, childDone);
209
222
  break;
210
223
  }
211
- await sleep(Math.min(stallConfig.pollIntervalMs, 5_000));
224
+ // #308: race the inter-poll wait against child exit so a worker that
225
+ // finishes right after writing .DONE is observed on its next wake
226
+ // instead of a full interval later.
227
+ await Promise.race([sleepFn(Math.min(stallConfig.pollIntervalMs, 5_000)), childDone]);
212
228
  continue;
213
229
  }
214
230
 
@@ -346,6 +362,15 @@ export async function pollWorkerUntilSettled({
346
362
  lastHeartbeatAt = now;
347
363
  }
348
364
 
365
+ // #308: observe child exit before the stall deadline. A worker that exits
366
+ // on its own between polls is settled work, never a stall — even when the
367
+ // next poll lands past the budget (the old order classified such exits
368
+ // `stall_timeout`). The bottom sleep races `childDone`, so exits are seen
369
+ // promptly; handles resolve `childDone` only after `exitCode` is set.
370
+ if (workerChild.exitCode !== null) {
371
+ break;
372
+ }
373
+
349
374
  const stallDeadline = computeStallDeadline({
350
375
  startedAt,
351
376
  lastProgressAt: lastCheckpointAt,
@@ -396,11 +421,7 @@ export async function pollWorkerUntilSettled({
396
421
  };
397
422
  }
398
423
 
399
- if (workerChild.exitCode !== null) {
400
- break;
401
- }
402
-
403
- await sleep(Math.min(stallConfig.pollIntervalMs, 5_000));
424
+ await Promise.race([sleepFn(Math.min(stallConfig.pollIntervalMs, 5_000)), childDone]);
404
425
  }
405
426
 
406
427
  return { kind: "settled", postDoneTerminated };
@@ -13,7 +13,11 @@ import {
13
13
  import { parseContract, parsePrompt } from "../tasks/packet/parse-prompt.mjs";
14
14
  import { appendJournalEvent } from "./journal.mjs";
15
15
  import { assertReviewToolAvailable } from "./review.mjs";
16
- import { finalizeWorkerOutput, createWorkerLiveLogWriter } from "./worker-output.mjs";
16
+ import {
17
+ finalizeWorkerOutput,
18
+ createWorkerLiveLogWriter,
19
+ resolveWorkerOutputConfig,
20
+ } from "./worker-output.mjs";
17
21
  import { resolveWorkerBackend } from "../config/worker-backend.mjs";
18
22
  import { commandExists } from "../util/command-exists.mjs";
19
23
  import {
@@ -262,6 +266,7 @@ export async function runWorker({
262
266
  childPastPreflight = true;
263
267
  });
264
268
  onWorkerPid?.(workerChild.pid ?? 0);
269
+ const outputConfig = resolveWorkerOutputConfig(config);
265
270
  const liveLogWriter = createWorkerLiveLogWriter({
266
271
  projectRoot,
267
272
  batchId,
@@ -269,7 +274,7 @@ export async function runWorker({
269
274
  taskId,
270
275
  config,
271
276
  });
272
- const childDone = collectChildOutput(workerChild, liveLogWriter);
277
+ const childDone = collectChildOutput(workerChild, liveLogWriter, outputConfig.maxBytes);
273
278
 
274
279
  const pollState = createWorkerPollState(startedAt, initialWorkerPhase);
275
280
  const pollOutcome = await pollWorkerUntilSettled({
@@ -315,12 +320,32 @@ export async function runWorker({
315
320
 
316
321
  const childResult = await Promise.race([childDone, sleep(CHILD_DONE_TIMEOUT_MS).then(() => null)]);
317
322
  let exitCode, output;
323
+ /** @type {boolean} */
324
+ let spawnFailed = false;
318
325
  if (childResult) {
319
- ({ exitCode, output } = childResult);
326
+ ({ exitCode, output, spawnError: spawnFailed = false } = childResult);
320
327
  } else {
321
328
  // close event didn't fire — sub-processes likely hold stdio pipes open.
322
329
  const fallback = await terminateHungWorkerChild(workerChild, childDone);
323
- ({ exitCode, output } = fallback);
330
+ ({ exitCode, output, spawnError: spawnFailed = false } = fallback);
331
+ }
332
+ // SP-787 (#306): the child never spawned (EACCES/ENOENT/missing execPath).
333
+ // Report `launch_failed` for this lane through the standard failure path so
334
+ // the engine keeps running; no worker code ran, so .DONE cannot be honored.
335
+ if (spawnFailed) {
336
+ return buildWorkerFailureResult({
337
+ rawOutput: output,
338
+ classification: "launch_failed",
339
+ exitCode,
340
+ mode: workerMode,
341
+ doneFound: fs.existsSync(donePath),
342
+ projectRoot,
343
+ batchId,
344
+ laneNumber,
345
+ taskId,
346
+ laneCorrelationId,
347
+ config,
348
+ });
324
349
  }
325
350
  const doneFound = fs.existsSync(donePath);
326
351
  if (postDoneTerminated && !doneFound) {
@@ -192,7 +192,9 @@ export function truncateLiveLogBytes(text, maxBytes) {
192
192
  }
193
193
 
194
194
  /**
195
- * Append redacted worker output to the live log with a rolling byte cap.
195
+ * Append redacted worker output to the live log (SP-787 / #306). The hot path
196
+ * is a pure append — the file is never re-read per chunk. Only when it has
197
+ * grown past twice `workerLiveLogMaxBytes` is it truncated back to the cap.
196
198
  *
197
199
  * @param {object} params
198
200
  * @param {string} params.logPath
@@ -205,12 +207,13 @@ export function appendWorkerLiveLogChunk({ logPath, rawChunk, outputConfig }) {
205
207
  const redacted = redactWorkerOutput(String(rawChunk), outputConfig);
206
208
  if (!redacted) return;
207
209
 
208
- const prior = fs.existsSync(logPath) ? fs.readFileSync(logPath, "utf-8") : "";
209
- const combined = `${prior}${redacted}`;
210
- const capped = truncateLiveLogBytes(combined, outputConfig.workerLiveLogMaxBytes);
211
- if (!capped) return;
212
-
213
210
  fs.mkdirSync(path.dirname(logPath), { recursive: true });
211
+ fs.appendFileSync(logPath, redacted);
212
+
213
+ const size = fs.statSync(logPath, { throwIfNoEntry: false })?.size ?? 0;
214
+ if (size <= outputConfig.workerLiveLogMaxBytes * 2) return;
215
+
216
+ const capped = truncateLiveLogBytes(fs.readFileSync(logPath, "utf-8"), outputConfig.workerLiveLogMaxBytes);
214
217
  writeTextAtomic(logPath, capped);
215
218
  }
216
219
 
@@ -6,6 +6,7 @@
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { buildWorkerContextAsync } from "../config/worker-context.mjs";
9
+ import { taskIdFromFolderName } from "../tasks/packet/discover.mjs";
9
10
 
10
11
  export function buildReviewLevelHint(reviewLevel) {
11
12
  if (reviewLevel <= 0) {
@@ -44,7 +45,7 @@ export async function buildWorkerTailPrompt({
44
45
  worktreePath,
45
46
  taskFolder,
46
47
  donePath,
47
- taskIdHint = path.basename(taskFolder).match(/^([A-Z]+-\d+)/)?.[1] ?? "TASK-ID",
48
+ taskIdHint = taskIdFromFolder(taskFolder),
48
49
  reviewLevel = 0,
49
50
  includePromptInclude = false,
50
51
  config = {},
@@ -81,5 +82,6 @@ export async function buildWorkerTailPrompt({
81
82
  }
82
83
 
83
84
  export function taskIdFromFolder(taskFolder) {
84
- return path.basename(taskFolder).match(/^([A-Z]+-\d+)/)?.[1] ?? "TASK-ID";
85
+ // Shared pattern (SP-785, #300); keeps the TASK-ID fallback for unparseable names.
86
+ return taskIdFromFolderName(path.basename(taskFolder)) ?? "TASK-ID";
85
87
  }
@@ -7,6 +7,7 @@ import path from "node:path";
7
7
  import { spawn } from "node:child_process";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { startAgentSessionWorker } from "./agent-session-worker.mjs";
10
+ import { DEFAULT_MAX_BYTES } from "./worker-output.mjs";
10
11
  import { resolveWorkerBackend } from "../config/worker-backend.mjs";
11
12
  import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
12
13
  import { resolveSafeWorkerLaunchScript } from "../config/worker-launch-script.mjs";
@@ -215,12 +216,13 @@ export function spawnExecutionOnlyHandle({
215
216
  config,
216
217
  });
217
218
 
218
- // Create a wrapper script that runs the command and then creates .DONE
219
- // This matches the behavior expected by the heartbeat loop.
220
- // We run `/bin/sh -c "<command> && touch .DONE"`
221
- const script = `${command} && touch "${path.join(taskFolder, ".DONE")}"`;
222
-
223
- return spawn("/bin/sh", ["-c", script], {
219
+ // Run the command, then create the .DONE marker. The path is passed as a
220
+ // positional parameter (`$1`) instead of being interpolated into the script
221
+ // string, so a task folder containing `"`, `$(`, or a backtick is never
222
+ // evaluated as shell code (SP-787 / #306). The third element is `$0`.
223
+ const donePath = path.join(taskFolder, ".DONE");
224
+
225
+ return spawn("/bin/sh", ["-c", `${command} && touch "$1"`, "sh", donePath], {
224
226
  cwd: worktreePath,
225
227
  env,
226
228
  stdio: ["ignore", "pipe", "pipe"],
@@ -286,28 +288,113 @@ export async function terminateHungWorkerChild(child, childDone) {
286
288
  }
287
289
 
288
290
  /**
291
+ * Append `text` to a bounded tail buffer, keeping only the last `maxBytes`.
292
+ *
293
+ * @param {Buffer<ArrayBufferLike>} tail
294
+ * @param {string} text
295
+ * @param {number} maxBytes
296
+ * @returns {Buffer<ArrayBufferLike>}
297
+ */
298
+ function appendToBoundedTail(tail, text, maxBytes) {
299
+ const chunk = Buffer.from(text, "utf-8");
300
+ if (maxBytes <= 0) return Buffer.alloc(0);
301
+ const combined = tail.byteLength === 0 ? chunk : Buffer.concat([tail, chunk]);
302
+ return combined.byteLength > maxBytes
303
+ ? combined.subarray(combined.byteLength - maxBytes)
304
+ : combined;
305
+ }
306
+
307
+ /**
308
+ * Collect child stdout/stderr into a bounded tail (SP-787 / #306) and settle
309
+ * on either `close` or a spawn `error`, whichever comes first. A child that
310
+ * never spawned (EACCES/ENOENT, missing execPath) emits `error` and then a
311
+ * synthetic `close`, so the error path resolves once with `spawnError: true`
312
+ * and the conventional exit code 127; the close handler is guarded so the
313
+ * later close cannot override the spawn failure. Without the `error` listener
314
+ * the engine itself would crash on the unhandled event and lose every lane.
315
+ *
289
316
  * @param {WorkerChildHandle} child
290
317
  * @param {{ append: (rawChunk: string) => void } | null} [liveLogWriter]
318
+ * @param {number} [maxBytes] Byte cap for the collected output tail; defaults
319
+ * to the worker output cap. Memory stays bounded regardless of child runtime.
320
+ * @returns {Promise<{ exitCode: number; output: string; spawnError?: boolean }>}
291
321
  */
292
- export function collectChildOutput(child, liveLogWriter) {
322
+ export function collectChildOutput(child, liveLogWriter, maxBytes) {
293
323
  if ("wait" in child && typeof child.wait === "function") {
294
324
  return child.wait();
295
325
  }
326
+ const cap =
327
+ typeof maxBytes === "number" && Number.isFinite(maxBytes) && maxBytes > 0
328
+ ? maxBytes
329
+ : DEFAULT_MAX_BYTES;
296
330
  return new Promise((resolve) => {
297
- let stdout = "";
298
- let stderr = "";
331
+ /** @type {Buffer<ArrayBufferLike>} */
332
+ let stdoutTail = Buffer.alloc(0);
333
+ /** @type {Buffer<ArrayBufferLike>} */
334
+ let stderrTail = Buffer.alloc(0);
335
+ /** @type {string|null} */
336
+ let spawnErrorMessage = null;
337
+ let settled = false;
338
+
339
+ // stdout-then-stderr order as before; the combined string keeps the last
340
+ // `cap` bytes overall.
341
+ const combinedOutput = () => {
342
+ const combined = Buffer.concat([stdoutTail, stderrTail]);
343
+ const bounded =
344
+ combined.byteLength > cap
345
+ ? combined.subarray(combined.byteLength - cap)
346
+ : combined;
347
+ return bounded.toString("utf-8");
348
+ };
349
+ const settle = (
350
+ /** @type {() => { exitCode: number; output: string; spawnError?: boolean }} */ build,
351
+ ) => {
352
+ if (settled) return;
353
+ settled = true;
354
+ resolve(build());
355
+ };
356
+ const spawnFailureResult = () => ({
357
+ exitCode: 127,
358
+ output: `${combinedOutput()}${spawnErrorMessage ?? ""}`,
359
+ spawnError: true,
360
+ });
361
+
299
362
  child.stdout?.on("data", (/** @type {Buffer | string} */ chunk) => {
300
363
  const text = chunk.toString();
301
- stdout += text;
364
+ stdoutTail = appendToBoundedTail(stdoutTail, text, cap);
302
365
  liveLogWriter?.append(text);
303
366
  });
304
367
  child.stderr?.on("data", (/** @type {Buffer | string} */ chunk) => {
305
368
  const text = chunk.toString();
306
- stderr += text;
369
+ stderrTail = appendToBoundedTail(stderrTail, text, cap);
307
370
  liveLogWriter?.append(text);
308
371
  });
372
+ child.on?.("error", (/** @type {unknown} */ err) => {
373
+ spawnErrorMessage = String(err);
374
+ // A child that failed to spawn has no real exit status. Flag the handle
375
+ // as settled so poll loops keyed on `exitCode` stop polling — older
376
+ // runtimes leave `exitCode` null on failed spawns (Node ≥22 sets a
377
+ // negative errno instead). The property is a plain writable own field.
378
+ if (child.exitCode === null || child.exitCode < 0) {
379
+ try {
380
+ // exitCode is readonly on the Node ChildProcess type; a failed spawn
381
+ // has no real status, so flagging it is safe and intentional.
382
+ const writableExitCode = /** @type {{ exitCode: number | null }} */ (
383
+ /** @type {unknown} */ (child)
384
+ );
385
+ writableExitCode.exitCode = 127;
386
+ } catch {
387
+ // Read-only test double; the resolved promise still settles the host.
388
+ }
389
+ }
390
+ settle(spawnFailureResult);
391
+ });
309
392
  child.on?.("close", (/** @type {number | null} */ code) => {
310
- resolve({ exitCode: code ?? 1, output: `${stdout}${stderr}` });
393
+ if (spawnErrorMessage !== null) {
394
+ settle(spawnFailureResult);
395
+ return;
396
+ }
397
+ settle(() => ({ exitCode: code ?? 1, output: combinedOutput() }));
311
398
  });
312
399
  });
313
400
  }
@@ -6,13 +6,12 @@ import { loadSpineConfig } from "../spine-config-load.mjs";
6
6
  import { missingConfigHint } from "../missing-config-hint.mjs";
7
7
  import { resolveTasksRootPath } from "../env-overrides.mjs";
8
8
  import { validateWorktreeSetupHookConfig } from "../worktree-setup-hook.mjs";
9
- import { discoverTasks } from "../../tasks/packet/discover.mjs";
9
+ import { discoverTasks, TASK_ID_RE, taskIdFromFolderName } from "../../tasks/packet/discover.mjs";
10
10
  import { NO_PENDING_TASKS_ERROR } from "../../planner/scope.mjs";
11
11
  import { summarizePendingScope } from "../../planner/pending.mjs";
12
12
  import { validatePrompt } from "../../tasks/packet/validate-prompt.mjs";
13
13
 
14
14
  const DEPENDENCIES_SCHEMA_VERSION = 1;
15
- const TASK_ID_PATTERN = /^[A-Z]{2,}-\d{3,}$/;
16
15
 
17
16
  function makeCheck(id, ok, message, extra = {}) {
18
17
  return { id, ok, message, ...extra };
@@ -31,24 +30,33 @@ export function resolveTasksRoot(projectRoot, configResult) {
31
30
  return resolveTasksRootPath(projectRoot, loaded.config);
32
31
  }
33
32
 
33
+ /**
34
+ * Task ID from a folder name — delegates to the shared pattern (SP-785, #300).
35
+ *
36
+ * @param {string} folderName
37
+ * @returns {string | null}
38
+ */
34
39
  export function taskIdFromFolder(folderName) {
35
- const match = String(folderName).match(/^([A-Z]{2,}-\d{3,})/);
36
- return match?.[1] ?? null;
40
+ return taskIdFromFolderName(folderName);
37
41
  }
38
42
 
43
+ /**
44
+ * Discoverable task folders (PREFIX-###-slug with PROMPT.md), numeric order.
45
+ * Delegates to the planner's discoverTasks so preflight and planner agree.
46
+ *
47
+ * @param {string} tasksRootPath
48
+ * @returns {string[]}
49
+ */
39
50
  export function discoverTaskFolders(tasksRootPath) {
40
51
  if (!tasksRootPath || !fs.existsSync(tasksRootPath)) return [];
41
52
 
42
- return fs
43
- .readdirSync(tasksRootPath, { withFileTypes: true })
44
- .filter((entry) => entry.isDirectory())
45
- .map((entry) => entry.name)
46
- .filter((name) => fs.existsSync(path.join(tasksRootPath, name, "PROMPT.md")))
47
- .sort();
53
+ return discoverTasks(tasksRootPath).map((task) => task.folderName);
48
54
  }
49
55
 
50
56
  export function discoverTaskIds(tasksRootPath) {
51
- return [...new Set(discoverTaskFolders(tasksRootPath).map(taskIdFromFolder).filter(Boolean))].sort();
57
+ if (!tasksRootPath || !fs.existsSync(tasksRootPath)) return [];
58
+
59
+ return discoverTasks(tasksRootPath).map((task) => task.taskId);
52
60
  }
53
61
 
54
62
  /**
@@ -148,7 +156,7 @@ export function checkDependenciesJson(ctx) {
148
156
  }
149
157
 
150
158
  const taskIds = Object.keys(parsed.tasks);
151
- const invalidIds = taskIds.filter((id) => !TASK_ID_PATTERN.test(id));
159
+ const invalidIds = taskIds.filter((id) => !TASK_ID_RE.test(id));
152
160
  if (invalidIds.length > 0) {
153
161
  return makeCheck(
154
162
  "dependencies-json",
@@ -1,4 +1,3 @@
1
- // @ts-nocheck
2
1
  /**
3
2
  * Doctor check orchestration — library surface for preflight and CLI.
4
3
  */
@@ -56,6 +55,11 @@ const SPINE_CLI_ENTRY = path.join(PACKAGE_ROOT, "bin", "spine.mjs");
56
55
 
57
56
  const REQUIRED_AGENT_FILES = ["worker.md", "reviewer.md", "supervisor.md"];
58
57
 
58
+ /**
59
+ * @param {string} cmd
60
+ * @param {string} [flag]
61
+ * @returns {string | null}
62
+ */
59
63
  function getVersion(cmd, flag = "--version") {
60
64
  let result;
61
65
  try {
@@ -94,6 +98,10 @@ function getMinPiVersion() {
94
98
  }
95
99
  }
96
100
 
101
+ /**
102
+ * @param {unknown} versionText
103
+ * @returns {{ major: number, minor: number, patch: number } | null}
104
+ */
97
105
  function parseSemver(versionText) {
98
106
  const match = String(versionText ?? "")
99
107
  .trim()
@@ -106,6 +114,11 @@ function parseSemver(versionText) {
106
114
  };
107
115
  }
108
116
 
117
+ /**
118
+ * @param {{ major: number, minor: number, patch: number } | null} a
119
+ * @param {{ major: number, minor: number, patch: number } | null} b
120
+ * @returns {number | null}
121
+ */
109
122
  function compareSemver(a, b) {
110
123
  if (!a || !b) return null;
111
124
  if (a.major !== b.major) return a.major - b.major;
@@ -113,6 +126,10 @@ function compareSemver(a, b) {
113
126
  return a.patch - b.patch;
114
127
  }
115
128
 
129
+ /**
130
+ * @param {string} dir
131
+ * @returns {boolean}
132
+ */
116
133
  function isInsideGitRepo(dir) {
117
134
  try {
118
135
  execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
@@ -138,6 +155,10 @@ function gitSupportsWorktrees() {
138
155
  }
139
156
  }
140
157
 
158
+ /**
159
+ * @param {string} output
160
+ * @returns {{ provider: string, id: string } | null}
161
+ */
141
162
  function parsePiListModelsOutput(output) {
142
163
  const lines = output.split(/\r?\n/).filter(Boolean);
143
164
  let providerCol = 0;
@@ -170,6 +191,10 @@ function parsePiListModelsOutput(output) {
170
191
 
171
192
  const LIST_MODELS_TIMEOUT_MS = 30_000;
172
193
 
194
+ /**
195
+ * @param {any} err
196
+ * @returns {boolean}
197
+ */
173
198
  function isListModelsTimeout(err) {
174
199
  return err?.code === "ETIMEDOUT";
175
200
  }
@@ -189,6 +214,7 @@ function listModelsTimeoutCheck() {
189
214
  * @param {object} [options]
190
215
  * @param {(cmd: string, args: string[], opts: object) => any} [options.spawn]
191
216
  * @param {(cmd: string) => boolean} [options.commandExistsFn]
217
+ * @returns {{ ok: boolean, warning?: boolean, detail?: string, suggestedCommand?: string }}
192
218
  */
193
219
  export function checkModelProvider({ spawn = spawnSync, commandExistsFn = commandExists } = {}) {
194
220
  if (!commandExistsFn("pi")) {
@@ -206,7 +232,7 @@ export function checkModelProvider({ spawn = spawnSync, commandExistsFn = comman
206
232
  if (isListModelsTimeout(err)) return listModelsTimeoutCheck();
207
233
  return {
208
234
  ok: false,
209
- detail: err.message,
235
+ detail: /** @type {Error} */ (err).message,
210
236
  suggestedCommand: "pi login",
211
237
  };
212
238
  }
@@ -237,6 +263,10 @@ ${result?.stderr ?? ""}`.trim();
237
263
  };
238
264
  }
239
265
 
266
+ /**
267
+ * @param {string} projectRoot
268
+ * @param {ReturnType<typeof loadSpineConfig>} configResult
269
+ */
240
270
  function resolveTasksRoot(projectRoot, configResult) {
241
271
  if (!configResult.config) {
242
272
  return null;
@@ -244,6 +274,9 @@ function resolveTasksRoot(projectRoot, configResult) {
244
274
  return resolveTasksRootPath(projectRoot, configResult.config);
245
275
  }
246
276
 
277
+ /**
278
+ * @param {unknown} command
279
+ */
247
280
  function isTestingCommandEmpty(command) {
248
281
  return !command || String(command).trim() === "";
249
282
  }
@@ -251,7 +284,7 @@ function isTestingCommandEmpty(command) {
251
284
  /**
252
285
  * Warn when evidence gates expect commands that are missing (SP-112).
253
286
  *
254
- * @param {object} [config]
287
+ * @param {Record<string, any>} [config]
255
288
  * @returns {Array<{ label: string, ok: boolean, warning?: boolean, detail: string, suggestedCommand?: string }>}
256
289
  */
257
290
  export function buildTestingEvidenceDoctorChecks(config = {}) {
@@ -286,6 +319,11 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
286
319
  const checks = [];
287
320
  let issueCount = 0;
288
321
 
322
+ /**
323
+ * @param {string} label
324
+ * @param {boolean} ok
325
+ * @param {Record<string, any>} [extra]
326
+ */
289
327
  const record = (label, ok, extra = {}) => {
290
328
  checks.push({ label, ok, ...extra });
291
329
  if (!ok) issueCount++;
@@ -12,7 +12,9 @@
12
12
  import path from 'node:path';
13
13
  import { summarizePendingScope } from './pending.mjs';
14
14
 
15
- export const TASK_ID_RE = /^[A-Z][A-Z0-9]*-\d{3,}$/;
15
+ // Single source of truth (SP-785, #300): re-export the shared task-ID regex.
16
+ import { TASK_ID_RE } from '../tasks/packet/discover.mjs';
17
+ export { TASK_ID_RE };
16
18
 
17
19
  export const NO_PENDING_TASKS_ERROR = 'No pending tasks (all discovered tasks have .DONE).';
18
20