pi-spine 2.24.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.
@@ -36,6 +36,7 @@ import {
36
36
  writeWorkerDoneMarker,
37
37
  } from "../src/batch/worker-output.mjs";
38
38
  import { buildWorkerTailPrompt, taskIdFromFolder } from "../src/batch/worker-prompt.mjs";
39
+ import { taskIdFromFolderName } from "../src/tasks/packet/discover.mjs";
39
40
  import { DEFAULT_TASKS_ROOT } from "../src/config/spine-init-constants.mjs";
40
41
  import {
41
42
  isPiExtensionConflictOutput,
@@ -312,7 +313,7 @@ async function runWorkerRunner() {
312
313
  const mode = process.argv.includes("--stub") ? "stub" : "pi";
313
314
 
314
315
  if (mode === "stub") {
315
- const parsedTaskId = path.basename(taskFolder).match(/^([A-Z]+-\d+)/)?.[1] ?? "";
316
+ const parsedTaskId = taskIdFromFolderName(path.basename(taskFolder)) ?? "";
316
317
  const failTasks = String(process.env.SPINE_WORKER_STUB_FAIL_TASKS ?? "")
317
318
  .split(/[,\s]+/)
318
319
  .filter(Boolean);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.24.0",
3
+ "version": "2.25.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -19,6 +19,7 @@ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
19
19
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
20
20
  import { resolveAttachedMilestonePollMs } from "../config/spine-config-schema.mjs";
21
21
  import { startParentSessionMonitor } from "./parent-session-monitor.mjs";
22
+ import { installEngineCrashHandlers } from "./engine-crash-guard.mjs";
22
23
  import {
23
24
  enforceAttachedEngineSingleOwner,
24
25
  reconcilePausedResumeDoneInLane,
@@ -240,6 +241,15 @@ export async function startAttachedMilestoneReporter({
240
241
  stop: async () => {
241
242
  stopped = true;
242
243
  await loopPromise;
244
+ // A fast engine can finish inside one poll interval, so the loop above
245
+ // may never have discovered the batchId (#308 follow-up: the worker
246
+ // poll loop no longer idles 5s per poll, shortening attached runs).
247
+ // Discover it here so the final flush still prints milestones — a
248
+ // completed batch must always surface [spine] batch.completed.
249
+ if (!batchId) {
250
+ const loaded = loadSpineBatchState(projectRoot);
251
+ batchId = loaded.raw?.batchId ? String(loaded.raw.batchId) : null;
252
+ }
243
253
  if (batchId) {
244
254
  const events = readJournalEventsCached(projectRoot, batchId);
245
255
  for (const event of events) {
@@ -282,6 +292,9 @@ export async function runAttachedBatchEngine({
282
292
  }
283
293
 
284
294
  installAttachedExitFinalizeHandlers({ projectRoot, spineBin });
295
+ // Scoped to this engine run: journal `engine.crashed` + fail the batch on a
296
+ // process-level crash, then uninstall so handlers never leak into importers (SP-788).
297
+ const uninstallEngineCrashGuard = installEngineCrashHandlers({ projectRoot });
285
298
  const reporter = await startAttachedMilestoneReporter({ projectRoot, write });
286
299
  /** @type {{ stop: () => Promise<void> }} */
287
300
  let parentMonitor = { stop: async () => {} };
@@ -301,6 +314,7 @@ export async function runAttachedBatchEngine({
301
314
  }
302
315
  return result;
303
316
  } finally {
317
+ uninstallEngineCrashGuard();
304
318
  await parentMonitor.stop();
305
319
  await reporter.stop();
306
320
  }
@@ -7,6 +7,7 @@ import path from "node:path";
7
7
  import { isProcessAlive } from "../process/liveness.mjs";
8
8
  import { parseSpineBatchState } from "./readers/spine-state.mjs";
9
9
  import { parseTaskplaneBatchState } from "./readers/taskplane-state.mjs";
10
+ import { withBatchStateLock } from "./batch-state-lock.mjs";
10
11
 
11
12
  /** Terminal phases safe to clear before a new batch start (SP-441 / #94). */
12
13
  const TERMINAL_PHASES_FOR_HANDOFF = new Set(["completed", "failed", "aborted", "merge_blocked"]);
@@ -126,77 +127,151 @@ export function readAliveBatchEnginePid(raw) {
126
127
  return enginePid;
127
128
  }
128
129
 
130
+ /**
131
+ * Detect a Taskplane-owned batch-state path (`.pi/`) that spine must never
132
+ * modify (SP-786 / #303). Spine start/clear paths act on `.spine/` state only.
133
+ *
134
+ * @param {string} batchStatePath
135
+ */
136
+ function isForeignBatchStatePath(batchStatePath) {
137
+ return batchStatePath.includes(`${path.sep}.pi${path.sep}`);
138
+ }
139
+
140
+ /**
141
+ * Rename a corrupt batch-state file to a collision-safe quarantine name in the
142
+ * same directory (SP-786 / #303). Never unlink: the file is evidence for
143
+ * post-mortem inspection. Uses a UTC timestamp plus a numeric suffix when the
144
+ * name is already taken (two corruptions within the same millisecond).
145
+ *
146
+ * @param {string} batchStatePath
147
+ * @returns {string} the quarantined file path
148
+ */
149
+ function quarantineCorruptBatchState(batchStatePath) {
150
+ const dir = path.dirname(batchStatePath);
151
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
152
+ let quarantinedPath = path.join(dir, `batch-state.corrupt-${stamp}.json`);
153
+ let attempt = 1;
154
+ while (fs.existsSync(quarantinedPath)) {
155
+ quarantinedPath = path.join(dir, `batch-state.corrupt-${stamp}-${attempt}.json`);
156
+ attempt += 1;
157
+ }
158
+ fs.renameSync(batchStatePath, quarantinedPath);
159
+ return quarantinedPath;
160
+ }
161
+
129
162
  /**
130
163
  * Remove active batch-state only when on-disk batch matches expected (SP-441 / #94).
131
164
  * Prevents complete/dismiss from clearing a newer batch after a concurrent start handoff.
132
165
  *
166
+ * Spine-owned path only: a Taskplane-owned `.pi/batch-state.json` is never
167
+ * renamed or unlinked here (SP-786 / #303). A corrupt spine-owned state file
168
+ * is quarantined (renamed), never deleted. The read-check-mutate sequence runs
169
+ * under the global batch-state lock; `projectRoot` may be omitted and is then
170
+ * derived from the `.spine` parent directory of `batchStatePath`.
171
+ *
133
172
  * @param {string|null} batchStatePath
134
173
  * @param {string} expectedBatchId
135
- * @returns {{ cleared: boolean, reason?: string, activeBatchId?: string }}
174
+ * @param {string|null} [projectRoot] derived from the `.spine` parent when omitted
175
+ * @returns {{ cleared: boolean, reason?: string, activeBatchId?: string, quarantinedPath?: string }}
136
176
  */
137
- export function clearActiveBatchStateIfMatches(batchStatePath, expectedBatchId) {
177
+ export function clearActiveBatchStateIfMatches(batchStatePath, expectedBatchId, projectRoot = null) {
138
178
  if (!batchStatePath || !fs.existsSync(batchStatePath)) {
139
179
  return { cleared: false, reason: "missing" };
140
180
  }
141
-
142
- try {
143
- const onDisk = JSON.parse(fs.readFileSync(batchStatePath, "utf-8"));
144
- const onDiskBatchId = readBatchStateId(onDisk);
145
- if (onDiskBatchId && onDiskBatchId !== expectedBatchId) {
146
- return {
147
- cleared: false,
148
- reason: "batch_id_mismatch",
149
- activeBatchId: onDiskBatchId,
150
- };
151
- }
152
- } catch {
153
- // Corrupt active state — remove so a new batch can start cleanly.
181
+ if (isForeignBatchStatePath(batchStatePath)) {
182
+ return { cleared: false, reason: "foreign_state" };
154
183
  }
155
184
 
156
- fs.unlinkSync(batchStatePath);
157
- return { cleared: true };
185
+ // Derive the lock root from `<root>/.spine/batch-state.json` when no caller supplies one.
186
+ const lockRoot = projectRoot ?? path.dirname(path.dirname(batchStatePath));
187
+ const result = /** @type {{ cleared: boolean, reason?: string, activeBatchId?: string, quarantinedPath?: string }} */ (
188
+ withBatchStateLock(lockRoot, () => {
189
+ try {
190
+ const onDisk = JSON.parse(fs.readFileSync(batchStatePath, "utf-8"));
191
+ const onDiskBatchId = readBatchStateId(onDisk);
192
+ if (onDiskBatchId && onDiskBatchId !== expectedBatchId) {
193
+ return {
194
+ cleared: false,
195
+ reason: "batch_id_mismatch",
196
+ activeBatchId: onDiskBatchId,
197
+ };
198
+ }
199
+ } catch (err) {
200
+ if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") {
201
+ return { cleared: false, reason: "missing" };
202
+ }
203
+ // Corrupt active state — quarantine for inspection, never delete (SP-786 / #303).
204
+ const quarantinedPath = quarantineCorruptBatchState(batchStatePath);
205
+ return { cleared: false, reason: "corrupt", quarantinedPath };
206
+ }
207
+
208
+ fs.unlinkSync(batchStatePath);
209
+ return { cleared: true };
210
+ })
211
+ );
212
+ return result;
158
213
  }
159
214
 
160
215
  /**
161
216
  * Clear a terminal completed batch-state pointer before spine batch start (SP-441 / #94).
162
217
  *
218
+ * Spine-owned path only (SP-786 / #303): when `.spine/batch-state.json` is
219
+ * absent, a Taskplane-owned `.pi/batch-state.json` is reported as
220
+ * `foreign_state` and never renamed or unlinked. A corrupt spine-owned state
221
+ * file is quarantined (renamed), never deleted. The read-check-mutate sequence
222
+ * runs under the global batch-state lock.
223
+ *
163
224
  * @param {string} projectRoot
164
- * @returns {{ cleared: boolean, reason?: string, batchId?: string }}
225
+ * @returns {{ cleared: boolean, reason?: string, batchId?: string, quarantinedPath?: string }}
165
226
  */
166
227
  export function clearStaleTerminalBatchStateForStart(projectRoot) {
167
- const resolved = resolveBatchStatePath(projectRoot);
168
- if (!resolved || !fs.existsSync(resolved)) {
228
+ const spinePath = path.join(projectRoot, ".spine", "batch-state.json");
229
+ const piPath = path.join(projectRoot, ".pi", "batch-state.json");
230
+
231
+ if (!fs.existsSync(spinePath)) {
232
+ if (fs.existsSync(piPath)) {
233
+ return { cleared: false, reason: "foreign_state" };
234
+ }
169
235
  return { cleared: false, reason: "missing" };
170
236
  }
171
237
 
172
- /** @type {unknown} */
173
- let raw;
174
- try {
175
- raw = JSON.parse(fs.readFileSync(resolved, "utf-8"));
176
- } catch {
177
- fs.unlinkSync(resolved);
178
- return { cleared: true, reason: "corrupt" };
179
- }
238
+ const result = /** @type {{ cleared: boolean, reason?: string, batchId?: string, quarantinedPath?: string }} */ (
239
+ withBatchStateLock(projectRoot, () => {
240
+ /** @type {unknown} */
241
+ let raw;
242
+ try {
243
+ raw = JSON.parse(fs.readFileSync(spinePath, "utf-8"));
244
+ } catch (err) {
245
+ if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") {
246
+ return { cleared: false, reason: "missing" };
247
+ }
248
+ // Corrupt state — quarantine for inspection, never delete (SP-786 / #303).
249
+ const quarantinedPath = quarantineCorruptBatchState(spinePath);
250
+ return { cleared: false, reason: "corrupt", quarantinedPath };
251
+ }
180
252
 
181
- const batchId = readBatchStateId(raw);
182
- const phase = String(/** @type {{ phase?: string }} */ (raw)?.phase ?? "");
183
- const ownerPid = readBatchStateEnginePid(raw);
253
+ const batchId = readBatchStateId(raw);
254
+ const phase = String(/** @type {{ phase?: string }} */ (raw)?.phase ?? "");
255
+ const ownerPid = readBatchStateEnginePid(raw);
184
256
 
185
- if (ACTIVE_PHASES_FOR_HANDOFF.has(phase) && !/** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
186
- return { cleared: false, reason: "active", batchId };
187
- }
257
+ if (ACTIVE_PHASES_FOR_HANDOFF.has(phase) && !/** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
258
+ return { cleared: false, reason: "active", batchId };
259
+ }
188
260
 
189
- if (ownerPid && isProcessAlive(ownerPid)) {
190
- throw new Error(
191
- `Active batch ${batchId || "(unknown)"} engine still running (pid=${ownerPid}). ` +
192
- "Wait for it to exit or run spine batch dismiss before spine batch start.",
193
- );
194
- }
261
+ if (ownerPid && isProcessAlive(ownerPid)) {
262
+ throw new Error(
263
+ `Active batch ${batchId || "(unknown)"} engine still running (pid=${ownerPid}). ` +
264
+ "Wait for it to exit or run spine batch dismiss before spine batch start.",
265
+ );
266
+ }
195
267
 
196
- if (TERMINAL_PHASES_FOR_HANDOFF.has(phase) || /** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
197
- fs.unlinkSync(resolved);
198
- return { cleared: true, reason: "stale_terminal", batchId };
199
- }
268
+ if (TERMINAL_PHASES_FOR_HANDOFF.has(phase) || /** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
269
+ fs.unlinkSync(spinePath);
270
+ return { cleared: true, reason: "stale_terminal", batchId };
271
+ }
200
272
 
201
- return { cleared: false, reason: "idle", batchId };
273
+ return { cleared: false, reason: "idle", batchId };
274
+ })
275
+ );
276
+ return result;
202
277
  }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Attached-engine crash guard (SP-788 / #306 item 5).
3
+ *
4
+ * Registers `uncaughtException` / `unhandledRejection` listeners for the
5
+ * duration of one attached engine run only. On a crash the guard journals
6
+ * `engine.crashed`, marks the batch failed, and exits non-zero — the journal
7
+ * and batch-state must never be left on a `running` orphan after a crash.
8
+ *
9
+ * All side effects are injectable via `deps` so tests never touch real
10
+ * process exit or real crash paths.
11
+ */
12
+
13
+ import { appendJournalEvent } from "./journal.mjs";
14
+ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
15
+
16
+ /** Same cap `failBatchFromEngineError` applies to `lastError` in batch state. */
17
+ const ERROR_MESSAGE_CAP = 500;
18
+ /** Keep the head of the stack: frames near the throw site are the useful ones. */
19
+ const STACK_LINE_CAP = 20;
20
+
21
+ /**
22
+ * Resolve the active batch id from batch-state.json, or null when absent.
23
+ *
24
+ * @param {string} projectRoot
25
+ * @returns {string|null}
26
+ */
27
+ function resolveActiveBatchId(projectRoot) {
28
+ const loaded = loadSpineBatchState(projectRoot);
29
+ const batchId = loaded.raw?.batchId;
30
+ return typeof batchId === "string" && batchId ? batchId : null;
31
+ }
32
+
33
+ /**
34
+ * Cap an error message to the journal-friendly length.
35
+ *
36
+ * @param {unknown} error
37
+ * @returns {string}
38
+ */
39
+ function crashMessage(error) {
40
+ const message = error instanceof Error ? error.message : String(error);
41
+ return message.slice(0, ERROR_MESSAGE_CAP);
42
+ }
43
+
44
+ /**
45
+ * First ~20 lines of the error stack (empty for non-Error throws).
46
+ *
47
+ * @param {unknown} error
48
+ * @returns {string}
49
+ */
50
+ function crashStack(error) {
51
+ const stack = error instanceof Error && typeof error.stack === "string" ? error.stack : "";
52
+ return stack.split("\n").slice(0, STACK_LINE_CAP).join("\n");
53
+ }
54
+
55
+ /**
56
+ * Real mark-failed: same terminal fields as the failed paths in resume.mjs
57
+ * (`phase = "failed"`, `endedAt`, `lastError`) persisted via saveSpineBatchState.
58
+ *
59
+ * @param {object} params
60
+ * @param {string} params.projectRoot
61
+ * @param {string} params.batchId
62
+ * @param {string} params.message
63
+ * @param {number} [params.endedAt]
64
+ * @returns {boolean} false when there is no on-disk batch state to fail
65
+ */
66
+ function defaultMarkBatchFailed({ projectRoot, batchId, message, endedAt }) {
67
+ const loaded = loadSpineBatchState(projectRoot);
68
+ if (!loaded.raw) return false;
69
+ // Fail only the batch that was active at crash time — never a batch that
70
+ // appeared in batch-state.json between resolution and this write.
71
+ if (loaded.raw.batchId !== batchId) return false;
72
+ loaded.raw.phase = "failed";
73
+ loaded.raw.endedAt = typeof endedAt === "number" ? endedAt : Date.now();
74
+ loaded.raw.lastError = String(message).slice(0, ERROR_MESSAGE_CAP);
75
+ saveSpineBatchState(projectRoot, loaded.raw);
76
+ return true;
77
+ }
78
+
79
+ /**
80
+ * Install process-level crash handlers for one attached engine run.
81
+ *
82
+ * The handlers run once (re-entrancy guarded): journal `engine.crashed`,
83
+ * mark the batch failed, then exit non-zero. If journaling or the state
84
+ * save itself throws, the original error still reaches stderr and the
85
+ * process still exits non-zero — a crash guard must never swallow a crash.
86
+ *
87
+ * @param {object} params
88
+ * @param {string} params.projectRoot
89
+ * @param {object} [params.deps] Injectable side effects (all optional).
90
+ * @param {(projectRoot: string, batchId: string, type: string, payload: object) => unknown} [params.deps.appendJournalEvent]
91
+ * @param {(params: { projectRoot: string, batchId: string, message: string, endedAt?: number }) => boolean} [params.deps.markBatchFailed]
92
+ * @param {(code?: number) => void} [params.deps.exit]
93
+ * @param {() => number} [params.deps.now]
94
+ * @returns {() => void} Uninstall — removes both listeners.
95
+ */
96
+ export function installEngineCrashHandlers({ projectRoot, deps = {} }) {
97
+ const {
98
+ appendJournalEvent: appendEvent = appendJournalEvent,
99
+ markBatchFailed = defaultMarkBatchFailed,
100
+ exit = /** @type {(code?: number) => void} */ ((code) => process.exit(code)),
101
+ now = /** @type {() => number} */ (() => Date.now()),
102
+ } = deps ?? {};
103
+
104
+ /** Guard against a second fault firing while the first is being journaled. */
105
+ let handling = false;
106
+
107
+ const handle = (/** @type {string} */ kind, /** @type {unknown} */ error) => {
108
+ if (handling) return;
109
+ handling = true;
110
+
111
+ const message = crashMessage(error);
112
+ try {
113
+ const batchId = resolveActiveBatchId(projectRoot);
114
+ if (batchId) {
115
+ appendEvent(projectRoot, batchId, "engine.crashed", {
116
+ kind,
117
+ error: message,
118
+ stack: crashStack(error),
119
+ });
120
+ markBatchFailed({ projectRoot, batchId, message, endedAt: now() });
121
+ } else {
122
+ process.stderr.write("[spine] engine crashed but no active batch state found; nothing to journal\n");
123
+ }
124
+ } catch (guardError) {
125
+ // Never swallow: the original crash must surface even if the
126
+ // journal write or the state save is what failed.
127
+ const guardMessage = guardError instanceof Error ? guardError.message : String(guardError);
128
+ process.stderr.write(`[spine] engine crash guard failed: ${guardMessage}\n`);
129
+ }
130
+ process.stderr.write(`[spine] engine crashed (${kind}): ${message}\n`);
131
+ exit(1);
132
+ };
133
+
134
+ const onUncaughtException = (/** @type {unknown} */ error) => handle("uncaughtException", error);
135
+ const onUnhandledRejection = (/** @type {unknown} */ reason) => handle("unhandledRejection", reason);
136
+ process.on("uncaughtException", onUncaughtException);
137
+ process.on("unhandledRejection", onUnhandledRejection);
138
+
139
+ return function uninstall() {
140
+ process.removeListener("uncaughtException", onUncaughtException);
141
+ process.removeListener("unhandledRejection", onUnhandledRejection);
142
+ };
143
+ }
@@ -34,7 +34,11 @@ import {
34
34
  } from "../state.mjs";
35
35
  import { runWorker } from "../worker-host.mjs";
36
36
  import { resolveWorktreeSetupIgnorePaths } from "../../config/spine-config-load.mjs";
37
- import { parseContract } from "../../tasks/packet/parse-prompt.mjs";
37
+ import {
38
+ findContractCommandMetacharIssue,
39
+ isRefusedContractMetacharCommand,
40
+ parseContract,
41
+ } from "../../tasks/packet/parse-prompt.mjs";
38
42
  import { verifyContract } from "../contract-verify.mjs";
39
43
  import { gitExec } from "../git-exec.mjs";
40
44
 
@@ -50,6 +54,21 @@ export function readParentContract(parentTaskFolderAbs) {
50
54
  return parseContract(fs.readFileSync(promptPath, "utf-8"));
51
55
  }
52
56
 
57
+ /**
58
+ * Matrix-specific refusal copy for an execute row whose substituted command
59
+ * contains shell metacharacters (#297). Deliberately distinct from the
60
+ * contract-verify copy ("Contract testCommand refused before spawn") so
61
+ * operators can tell a bad row value from a bad authored command.
62
+ *
63
+ * @param {string} rowId
64
+ * @param {string} command
65
+ * @returns {string}
66
+ */
67
+ function formatMatrixRowRefusedMetacharMessage(rowId, command) {
68
+ const issue = findContractCommandMetacharIssue(String(command ?? "").trim());
69
+ return `matrix row command refused before spawn: row '${rowId}' substitutes to a command containing ${issue ?? "shell metacharacters"} (command: ${command}). Row values flow into runCommand through /bin/sh -c; remove $, backticks, ;, |, || or lone & from the row value — && chains are allowed (#268, #297).`;
70
+ }
71
+
53
72
  /**
54
73
  * Serve a matrix LLM row its row-substituted PROMPT.md (#232). Reads the parent
55
74
  * PROMPT.md (same source convention as `readParentContract`), substitutes
@@ -251,7 +270,14 @@ export async function runMatrixSubLane({
251
270
  };
252
271
  } else {
253
272
  const command = substituteRowCommand(rawCommand, values);
254
- const run = await runShellInDir(worktreePath, command, matrixEnv);
273
+ // Guard AFTER substitution, BEFORE spawn (#297): parse-time validation only
274
+ // saw the raw template, so a row value can reintroduce shell metacharacters
275
+ // into an otherwise-clean command. Refused rows never reach /bin/sh — the
276
+ // ternary short-circuits before `runShellInDir` — and the refusal message
277
+ // flows through the failed-row path, which journals `matrix.sub_lane.failed`.
278
+ const run = isRefusedContractMetacharCommand(command)
279
+ ? { exitCode: 1, output: formatMatrixRowRefusedMetacharMessage(rowId, command) }
280
+ : await runShellInDir(worktreePath, command, matrixEnv);
255
281
  if (run.exitCode !== 0) {
256
282
  result = {
257
283
  rowId,
@@ -22,6 +22,7 @@ import {
22
22
  substituteMatrixVariables,
23
23
  } from "../../planner/matrix.mjs";
24
24
  import { gitExec } from "../git-exec.mjs";
25
+ import { terminateProcessTree } from "../../process/terminate-tree.mjs";
25
26
  import {
26
27
  normalizeLaneWorktreeGitPaths,
27
28
  runWorktreeSetupHook,
@@ -285,35 +286,169 @@ export function buildMatrixRowEnv({ taskId, rowId, rowIndex, rowCount }) {
285
286
  };
286
287
  }
287
288
 
289
+ /**
290
+ * Default matrix row shell timeout (SP-783 / #297). Matches the contract
291
+ * `testCommand` timeout so a hung row cannot hold a global lane slot forever.
292
+ *
293
+ * @type {number}
294
+ */
295
+ export const DEFAULT_MATRIX_ROW_TIMEOUT_MS = 600_000;
296
+
297
+ /**
298
+ * Default matrix row output cap (SP-783 / #297). Matches the worker-output
299
+ * default so a chatty row keeps only a bounded tail in engine memory.
300
+ *
301
+ * @type {number}
302
+ */
303
+ export const DEFAULT_MATRIX_ROW_OUTPUT_MAX_BYTES = 262_144;
304
+
305
+ /** Grace between SIGTERM and the SIGKILL escalation when a row times out. */
306
+ const TREE_KILL_GRACE_MS = 5_000;
307
+
308
+ /** Marker prefixed to output when the cap dropped bytes (SP-783 / #297). */
309
+ const OUTPUT_TRUNCATION_MARKER_PREFIX = "[… ";
310
+ const OUTPUT_TRUNCATION_MARKER_SUFFIX = " bytes truncated …]\n";
311
+
312
+ /**
313
+ * Resolve the `SPINE_MATRIX_ROW_TIMEOUT_MS` override (positive integer ms),
314
+ * mirroring `SPINE_SYNC_TIMEOUT_MS`: invalid or absent values return null so
315
+ * the caller falls back to the default instead of failing the row.
316
+ *
317
+ * @param {{ env?: Record<string, string | undefined> }} [params]
318
+ * @returns {number | null} Override in ms, or null when unset/invalid.
319
+ */
320
+ export function resolveMatrixRowTimeoutOverride(params = {}) {
321
+ const env = params.env ?? process.env;
322
+ const raw = env.SPINE_MATRIX_ROW_TIMEOUT_MS;
323
+ if (raw == null || raw === "") return null;
324
+ const parsed = Number(raw);
325
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
326
+ }
327
+
288
328
  /**
289
329
  * Run a shell command in a directory, resolving with exit code and combined output.
290
330
  * Uses async spawn so concurrent rows genuinely overlap (required for maxParallel).
291
331
  *
332
+ * Bounded by default (SP-783 / #297): a row that outlives `timeoutMs` gets its
333
+ * whole process tree terminated (SIGTERM, then SIGKILL after a short grace —
334
+ * the shell is spawned detached so it is a process-group leader whose
335
+ * descendants are reachable) and resolves with `exitCode: 124` and
336
+ * `timedOut: true`. Output is kept as a bounded tail of at most
337
+ * `maxOutputBytes` bytes; when the cap dropped anything the result is prefixed
338
+ * with a truncation marker and carries `outputTruncated: true`.
339
+ *
292
340
  * @param {string} cwd
293
341
  * @param {string} command
294
342
  * @param {Record<string, string> | null} [extraEnv] Extra environment variables
295
343
  * layered over `process.env` (matrix row identity, #229). Null injects nothing.
296
- * @returns {Promise<{ exitCode: number, output: string }>}
344
+ * @param {{ timeoutMs?: number, maxOutputBytes?: number }} [options]
345
+ * `timeoutMs` defaults to `SPINE_MATRIX_ROW_TIMEOUT_MS` (positive integer)
346
+ * when set, else `DEFAULT_MATRIX_ROW_TIMEOUT_MS`; `maxOutputBytes` defaults
347
+ * to `DEFAULT_MATRIX_ROW_OUTPUT_MAX_BYTES`.
348
+ * @returns {Promise<{ exitCode: number, output: string, timedOut?: boolean, outputTruncated?: boolean }>}
297
349
  */
298
- export function runShellInDir(cwd, command, extraEnv = null) {
350
+ export function runShellInDir(cwd, command, extraEnv = null, options = {}) {
351
+ const optionTimeoutMs = Number(options.timeoutMs);
352
+ const timeoutMs =
353
+ Number.isInteger(optionTimeoutMs) && optionTimeoutMs > 0
354
+ ? optionTimeoutMs
355
+ : (resolveMatrixRowTimeoutOverride() ?? DEFAULT_MATRIX_ROW_TIMEOUT_MS);
356
+ const optionMaxOutputBytes = Number(options.maxOutputBytes);
357
+ const maxOutputBytes =
358
+ Number.isInteger(optionMaxOutputBytes) && optionMaxOutputBytes > 0
359
+ ? optionMaxOutputBytes
360
+ : DEFAULT_MATRIX_ROW_OUTPUT_MAX_BYTES;
361
+
299
362
  return new Promise((resolve) => {
363
+ let settled = false;
364
+ let timedOut = false;
365
+ let droppedBytes = 0;
366
+ /** @type {NodeJS.Timeout | undefined} */
367
+ let killGraceTimer;
368
+
369
+ // Bounded tail buffer: once the cap is exceeded, chunks are dropped from
370
+ // the front (copying the retained slice) so memory stays O(maxOutputBytes)
371
+ // no matter how chatty the row is — never the full stream.
372
+ /** @type {Buffer[]} */
373
+ const tailChunks = [];
374
+ let tailBytes = 0;
375
+ /** @type {(chunk: unknown) => void} */
376
+ const append = (chunk) => {
377
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
378
+ if (buf.length === 0) return;
379
+ tailChunks.push(buf);
380
+ tailBytes += buf.length;
381
+ while (tailBytes > maxOutputBytes && tailChunks.length > 0) {
382
+ const excess = tailBytes - maxOutputBytes;
383
+ const first = tailChunks[0];
384
+ if (first.length > excess) {
385
+ tailChunks[0] = Buffer.from(first.subarray(excess));
386
+ droppedBytes += excess;
387
+ tailBytes = maxOutputBytes;
388
+ } else {
389
+ tailChunks.shift();
390
+ droppedBytes += first.length;
391
+ tailBytes -= first.length;
392
+ }
393
+ }
394
+ };
395
+
300
396
  const child = spawn("/bin/sh", ["-c", command], {
301
397
  cwd,
302
398
  env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
303
399
  stdio: ["ignore", "pipe", "pipe"],
400
+ // Process-group leader on POSIX so tree termination reaches grandchildren.
401
+ detached: process.platform !== "win32",
304
402
  });
305
- let output = "";
306
- /** @type {(chunk: unknown) => void} */
307
- const append = (chunk) => {
308
- output += String(chunk);
403
+
404
+ /** @param {{ exitCode: number, output: string, timedOut?: boolean, outputTruncated?: boolean }} result */
405
+ const settle = (result) => {
406
+ if (settled) return;
407
+ settled = true;
408
+ clearTimeout(timeoutTimer);
409
+ clearTimeout(killGraceTimer);
410
+ resolve(result);
309
411
  };
412
+
413
+ /** @type {NodeJS.Timeout} */
414
+ const timeoutTimer = setTimeout(() => {
415
+ timedOut = true;
416
+ terminateProcessTree(child.pid, { signal: "SIGTERM" });
417
+ // Escalate when the tree ignores SIGTERM past the grace window.
418
+ killGraceTimer = setTimeout(() => {
419
+ if (!settled) terminateProcessTree(child.pid, { signal: "SIGKILL" });
420
+ }, TREE_KILL_GRACE_MS);
421
+ killGraceTimer.unref();
422
+ }, timeoutMs);
423
+ timeoutTimer.unref();
424
+
310
425
  child.stdout?.on("data", append);
311
426
  child.stderr?.on("data", append);
312
427
  child.on("error", (err) => {
313
- resolve({ exitCode: 1, output: output + String(err) });
428
+ settle({
429
+ exitCode: 1,
430
+ output: Buffer.concat(tailChunks).toString("utf8") + String(err),
431
+ });
314
432
  });
315
433
  child.on("close", (code) => {
316
- resolve({ exitCode: code ?? 1, output });
434
+ const tail = Buffer.concat(tailChunks).toString("utf8");
435
+ if (timedOut) {
436
+ settle({
437
+ exitCode: 124,
438
+ output: `${tail}matrix row command timed out after ${timeoutMs}ms\n`,
439
+ timedOut: true,
440
+ ...(droppedBytes > 0 ? { outputTruncated: true } : {}),
441
+ });
442
+ return;
443
+ }
444
+ settle({
445
+ exitCode: code ?? 1,
446
+ output:
447
+ droppedBytes > 0
448
+ ? `${OUTPUT_TRUNCATION_MARKER_PREFIX}${droppedBytes}${OUTPUT_TRUNCATION_MARKER_SUFFIX}${tail}`
449
+ : tail,
450
+ ...(droppedBytes > 0 ? { outputTruncated: true } : {}),
451
+ });
317
452
  });
318
453
  });
319
454
  }