pi-spine 2.24.0 → 2.26.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 (53) hide show
  1. package/bin/spine-worker-runner.mjs +2 -1
  2. package/package.json +1 -1
  3. package/src/batch/abort.mjs +74 -38
  4. package/src/batch/attached-engine-handoff.mjs +2 -2
  5. package/src/batch/attached-runner-promote.mjs +15 -1
  6. package/src/batch/attached-runner-reconcile.mjs +1 -1
  7. package/src/batch/batch-meta-reconstruct.mjs +6 -1
  8. package/src/batch/batch-state-io.mjs +120 -45
  9. package/src/batch/batch-state-lock.mjs +173 -31
  10. package/src/batch/contract-exec.mjs +46 -45
  11. package/src/batch/contract-spawn.mjs +225 -0
  12. package/src/batch/contract-verify.mjs +2 -1
  13. package/src/batch/detached-wait.mjs +1 -1
  14. package/src/batch/engine-crash-guard.mjs +143 -0
  15. package/src/batch/engine-lanes/matrix-run.mjs +34 -8
  16. package/src/batch/engine-lanes/matrix.mjs +143 -8
  17. package/src/batch/engine-lanes/merge.mjs +135 -34
  18. package/src/batch/engine-lanes/review-final.mjs +1 -1
  19. package/src/batch/engine-lanes.mjs +11 -9
  20. package/src/batch/engine.mjs +10 -10
  21. package/src/batch/integrate-dirty-overlap.mjs +35 -0
  22. package/src/batch/integrate-worktree.mjs +106 -13
  23. package/src/batch/integrate.mjs +34 -93
  24. package/src/batch/journal-checksum.mjs +26 -0
  25. package/src/batch/journal.mjs +32 -13
  26. package/src/batch/lifecycle-archive.mjs +84 -3
  27. package/src/batch/lifecycle-cleanup.mjs +110 -0
  28. package/src/batch/lifecycle.mjs +100 -72
  29. package/src/batch/parent-session-monitor.mjs +77 -70
  30. package/src/batch/pause.mjs +92 -25
  31. package/src/batch/post-merge-limbo.mjs +35 -5
  32. package/src/batch/reconcile-batch.mjs +13 -1
  33. package/src/batch/resume-gate-reopen.mjs +24 -8
  34. package/src/batch/resume-multi.mjs +1 -1
  35. package/src/batch/resume.mjs +1 -1
  36. package/src/batch/salvage-batch-integrate.mjs +13 -17
  37. package/src/batch/sequence-run.mjs +26 -8
  38. package/src/batch/sequence-wait.mjs +87 -8
  39. package/src/batch/state-guards.mjs +39 -7
  40. package/src/batch/state-io.mjs +131 -17
  41. package/src/batch/state.mjs +23 -1
  42. package/src/batch/worker-heartbeat.mjs +29 -8
  43. package/src/batch/worker-host.mjs +61 -8
  44. package/src/batch/worker-output.mjs +9 -6
  45. package/src/batch/worker-prompt.mjs +4 -2
  46. package/src/batch/worker-spawn.mjs +99 -12
  47. package/src/config/defaults.mjs +15 -1
  48. package/src/config/preflight/discovery.mjs +20 -12
  49. package/src/config/preflight/git-batch.mjs +47 -0
  50. package/src/config/spine-config-schema.mjs +67 -1
  51. package/src/fs/atomic-write.mjs +37 -1
  52. package/src/planner/scope.mjs +3 -1
  53. package/src/tasks/packet/discover.mjs +59 -3
@@ -54,8 +54,9 @@ export {
54
54
  * @param {string} worktreePath
55
55
  * @param {object} parsedContract
56
56
  * @param {object} [config]
57
+ * @returns {Promise<{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number }>}
57
58
  */
58
- export function verifyContract(worktreePath, parsedContract, config = {}) {
59
+ export async function verifyContract(worktreePath, parsedContract, config = {}) {
59
60
  const effectiveContract = config?.matrixRow
60
61
  ? applyMatrixRowToContract(parsedContract, config.matrixRow)
61
62
  : parsedContract;
@@ -179,7 +179,7 @@ export function prepareDetachedResumeEngineHandoff(projectRoot) {
179
179
  orphanResume: orphanEligibility.allowOrphanResume,
180
180
  engineConfirmedDead: orphanEligibility.engineConfirmedDead,
181
181
  });
182
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
182
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
183
183
 
184
184
  return {
185
185
  ok: true,
@@ -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,
@@ -293,7 +319,7 @@ export async function runMatrixSubLane({
293
319
  } else {
294
320
  // Verify the contract per row (testCommand + fileScopeMustChange
295
321
  // substituted with this row's values). This is the per-row gate.
296
- const verify = verifyContract(worktreePath, contract, {
322
+ const verify = await verifyContract(worktreePath, contract, {
297
323
  matrixRow: values,
298
324
  baseBranch,
299
325
  });
@@ -508,7 +534,7 @@ export async function runMatrixTaskForResume({
508
534
  state.phase = "failed";
509
535
  state.endedAt = Date.now();
510
536
  state.lastError = String(output).slice(0, 500);
511
- saveEngineBatchState(projectRoot, state);
537
+ await saveEngineBatchState(projectRoot, state);
512
538
  return {
513
539
  isMatrix: true,
514
540
  ok: false,
@@ -647,7 +673,7 @@ export async function runMatrixTaskOnLane({
647
673
  skippedRowIds.push(row.rowId);
648
674
  }
649
675
  updateSegmentForTask(state, taskId, "running");
650
- saveEngineBatchState(projectRoot, state);
676
+ await saveEngineBatchState(projectRoot, state);
651
677
 
652
678
  appendJournalEvent(projectRoot, batchId, "task.started", {
653
679
  taskId,
@@ -682,7 +708,7 @@ export async function runMatrixTaskOnLane({
682
708
  const runningEntry = task.matrixRows.find((/** @type {any} */ m) => m.rowId === row.rowId);
683
709
  if (runningEntry) {
684
710
  runningEntry.status = "running";
685
- saveEngineBatchState(projectRoot, state);
711
+ await saveEngineBatchState(projectRoot, state);
686
712
  }
687
713
  try {
688
714
  return await runMatrixSubLane({
@@ -770,7 +796,7 @@ export async function runMatrixTaskOnLane({
770
796
  task.exitReason = `matrix_sub_lane_failed:${failedSummary}`;
771
797
  updateSegmentForTask(state, taskId, "failed");
772
798
  recomputeTaskCounters(state);
773
- saveEngineBatchState(projectRoot, state);
799
+ await saveEngineBatchState(projectRoot, state);
774
800
  recordMatrixEvent(projectRoot, batchId, "matrix.task_failed", {
775
801
  taskId,
776
802
  laneNumber,
@@ -847,7 +873,7 @@ export async function runMatrixTaskOnLane({
847
873
  task.exitReason = `matrix_row_merge_failed:${rowResult.rowId}`;
848
874
  updateSegmentForTask(state, taskId, "failed");
849
875
  recomputeTaskCounters(state);
850
- saveEngineBatchState(projectRoot, state);
876
+ await saveEngineBatchState(projectRoot, state);
851
877
  return {
852
878
  ok: false,
853
879
  workerResult: {
@@ -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
  }