pi-spine 2.25.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 (35) hide show
  1. package/package.json +1 -1
  2. package/src/batch/abort.mjs +74 -38
  3. package/src/batch/attached-engine-handoff.mjs +2 -2
  4. package/src/batch/attached-runner-promote.mjs +1 -1
  5. package/src/batch/attached-runner-reconcile.mjs +1 -1
  6. package/src/batch/batch-meta-reconstruct.mjs +6 -1
  7. package/src/batch/batch-state-lock.mjs +173 -31
  8. package/src/batch/contract-exec.mjs +46 -45
  9. package/src/batch/contract-spawn.mjs +225 -0
  10. package/src/batch/contract-verify.mjs +2 -1
  11. package/src/batch/detached-wait.mjs +1 -1
  12. package/src/batch/engine-lanes/matrix-run.mjs +6 -6
  13. package/src/batch/engine-lanes/merge.mjs +135 -34
  14. package/src/batch/engine-lanes/review-final.mjs +1 -1
  15. package/src/batch/engine-lanes.mjs +11 -9
  16. package/src/batch/engine.mjs +10 -10
  17. package/src/batch/lifecycle-archive.mjs +76 -1
  18. package/src/batch/lifecycle-cleanup.mjs +110 -0
  19. package/src/batch/lifecycle.mjs +100 -72
  20. package/src/batch/parent-session-monitor.mjs +77 -70
  21. package/src/batch/pause.mjs +92 -25
  22. package/src/batch/post-merge-limbo.mjs +35 -5
  23. package/src/batch/resume-gate-reopen.mjs +24 -8
  24. package/src/batch/resume-multi.mjs +1 -1
  25. package/src/batch/resume.mjs +1 -1
  26. package/src/batch/sequence-run.mjs +26 -8
  27. package/src/batch/sequence-wait.mjs +87 -8
  28. package/src/batch/state-guards.mjs +39 -7
  29. package/src/batch/state-io.mjs +131 -17
  30. package/src/batch/state.mjs +1 -0
  31. package/src/batch/worker-host.mjs +32 -4
  32. package/src/config/defaults.mjs +15 -1
  33. package/src/config/preflight/git-batch.mjs +47 -0
  34. package/src/config/spine-config-schema.mjs +67 -1
  35. package/src/fs/atomic-write.mjs +37 -1
@@ -4,7 +4,7 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
- import { spawnSync, execFileSync } from "node:child_process";
7
+ import { setTimeout as sleep } from "node:timers/promises";
8
8
  import micromatch from "micromatch";
9
9
  import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
10
10
  import {
@@ -26,6 +26,7 @@ import {
26
26
  TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT,
27
27
  } from "../tasks/validate-contract-warn.mjs";
28
28
  import { formatRefusedContractMetacharMessage, isRefusedContractMetacharCommand } from "../tasks/packet/parse-prompt.mjs";
29
+ import { runShellCommandAsync } from "./contract-spawn.mjs";
29
30
 
30
31
  // Shared pre-spawn refusal envelope for the npm-scope (#187) and metachar (#268) guards.
31
32
  function refusedBeforeSpawnResult(/** @type {string} */ summary) {
@@ -82,17 +83,6 @@ function formatMaxBufferLabel(byteCount) {
82
83
  return `${byteCount}B`;
83
84
  }
84
85
 
85
- /**
86
- * Block the current thread for the given duration without busy-waiting.
87
- * Safe for CLI/batch tools; not suitable for servers.
88
- *
89
- * @param {number} ms
90
- */
91
- function sleepSync(ms) {
92
- if (ms <= 0) return;
93
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
94
- }
95
-
96
86
  /**
97
87
  * Write a failure log for a contract testCommand attempt to the task's .reviews/ directory.
98
88
  * Returns the written path, or null if taskFolder is not provided.
@@ -149,10 +139,10 @@ function formatRefusedNpmTestDashDashMessage(command) {
149
139
  /**
150
140
  * @param {string} worktreePath
151
141
  * @param {string} command
152
- * @param {{ maxBuffer?: number }} [options]
153
- * @returns {{ ok: boolean, exitCode: number, output: string, bufferOverflow?: boolean, summary?: string, refusedBeforeSpawn?: boolean }}
142
+ * @param {{ maxBuffer?: number, timeoutMs?: number }} [options]
143
+ * @returns {Promise<{ ok: boolean, exitCode: number, output: string, bufferOverflow?: boolean, summary?: string, refusedBeforeSpawn?: boolean, timedOut?: boolean }>}
154
144
  */
155
- export function runContractTestCommand(worktreePath, command, options = {}) {
145
+ export async function runContractTestCommand(worktreePath, command, options = {}) {
156
146
  const trimmed = String(command ?? "").trim();
157
147
  if (!trimmed || trimmed === "true") {
158
148
  return { ok: true, exitCode: 0, output: "" };
@@ -166,14 +156,11 @@ export function runContractTestCommand(worktreePath, command, options = {}) {
166
156
  }
167
157
 
168
158
  const maxBuffer = options.maxBuffer ?? CONTRACT_TEST_COMMAND_MAX_BUFFER;
169
- const shell = process.env.SHELL || (process.platform === "win32" ? "cmd.exe" : "/bin/sh");
170
- const shellFlag = process.platform === "win32" ? "/c" : "-c";
171
- const result = spawnSync(shell, [shellFlag, trimmed], {
172
- cwd: worktreePath,
159
+ const timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;
160
+ // Async primitive (SP-799): concurrent lanes keep running while this command executes.
161
+ const result = await runShellCommandAsync(worktreePath, trimmed, {
173
162
  env: buildContractTestEnv(),
174
- encoding: "utf-8",
175
- stdio: ["ignore", "pipe", "pipe"],
176
- timeout: 10 * 60 * 1000,
163
+ timeoutMs,
177
164
  maxBuffer,
178
165
  });
179
166
 
@@ -181,18 +168,30 @@ export function runContractTestCommand(worktreePath, command, options = {}) {
181
168
  const stderr = String(result.stderr ?? "");
182
169
  const output = `${stdout}\n${stderr}`;
183
170
 
184
- if (/** @type {NodeJS.ErrnoException | undefined} */ (result.error)?.code === "ENOBUFS") {
171
+ if (result.timedOut) {
172
+ // Report the timeout explicitly — a bare "exit 1" hides the real cause (#305).
173
+ const timeoutLabel = `${(timeoutMs / 60000).toFixed(2).replace(/\.?0+$/, "")} min`;
174
+ return {
175
+ ok: false,
176
+ exitCode: Number(result.exitCode ?? 1),
177
+ output,
178
+ timedOut: true,
179
+ summary: `testCommand timed out after ${timeoutLabel} and was terminated`,
180
+ };
181
+ }
182
+
183
+ if (result.truncated) {
185
184
  const limitLabel = formatMaxBufferLabel(maxBuffer);
186
185
  return {
187
186
  ok: false,
188
- exitCode: Number(result.status ?? 255),
187
+ exitCode: Number(result.exitCode ?? 255),
189
188
  output,
190
189
  bufferOverflow: true,
191
190
  summary: `testCommand output exceeded maxBuffer (${limitLabel}); use a scoped testCommand instead of full-suite commands. Command: ${trimmed}`,
192
191
  };
193
192
  }
194
193
 
195
- const exitCode = Number(result.status ?? 1);
194
+ const exitCode = Number(result.exitCode ?? 1);
196
195
  if (exitCode === 0) {
197
196
  return { ok: true, exitCode: 0, output };
198
197
  }
@@ -215,10 +214,10 @@ function resolveCoverageCommand(config) {
215
214
  /**
216
215
  * @param {string} worktreePath
217
216
  * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
218
- * @param {object} config
217
+ * @param {{ contractTestMaxBuffer?: number, testing?: { test?: string, testWithCoverage?: string } }} config
219
218
  * @param {string} [testCommandOutput]
220
219
  */
221
- function resolveLineCoverage(worktreePath, parsedContract, config, testCommandOutput = "") {
220
+ async function resolveLineCoverage(worktreePath, parsedContract, config, testCommandOutput = "") {
222
221
  let output = testCommandOutput;
223
222
  if (parsedContract.minLineCoverage != null) {
224
223
  const parsedFromTest = parseAggregateLineCoverage(output);
@@ -226,7 +225,7 @@ function resolveLineCoverage(worktreePath, parsedContract, config, testCommandOu
226
225
  return parsedFromTest;
227
226
  }
228
227
  const coverageCommand = resolveCoverageCommand(config);
229
- const coverageResult = runContractTestCommand(worktreePath, coverageCommand);
228
+ const coverageResult = await runContractTestCommand(worktreePath, coverageCommand, { maxBuffer: config?.contractTestMaxBuffer });
230
229
  output = coverageResult.output;
231
230
  }
232
231
  return parseAggregateLineCoverage(output);
@@ -305,24 +304,23 @@ export function prepareContractVerifyEnvironment(worktreePath, parsedContract, c
305
304
  * @param {string} [config.taskFolder] Task folder path for writing failure logs to .reviews/ (optional).
306
305
  * @param {{ testRetries?: number, testRetryDelayMs?: number }} [config.contract] Retry tuning for testCommand attempts.
307
306
  * @param {number} [config.contractTestMaxBuffer] stdout/stderr capture limit override.
307
+ * @param {number} [config.contractTestTimeoutMs] Wall-clock timeout override for testCommand attempts.
308
308
  * @param {{ test?: string, testWithCoverage?: string }} [config.testing] Coverage command selection.
309
- * @returns {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number }}
309
+ * @returns {Promise<{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number }>}
310
310
  */
311
- export function verifyContract(worktreePath, parsedContract, config = {}) {
311
+ export async function verifyContract(worktreePath, parsedContract, config = {}) {
312
312
  /** @type {Array<{ field: string, ok: boolean, message: string }>} */
313
313
  const checks = [];
314
314
  const baseBranch = config?.baseBranch ?? "main";
315
315
  const sinceCommit = config?.sinceCommit ?? config?.taskStartCommit ?? undefined;
316
316
  const committedFiles = listChangedFiles(worktreePath, baseBranch, sinceCommit);
317
-
318
- /** @type {string[]} */
319
- let indexAndWorktreeFiles = /** @type {string[]} */ ([]);
320
- try {
321
- const stdout = execFileSync("git", ["diff", "--name-only", "HEAD"], { cwd: worktreePath, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
322
- indexAndWorktreeFiles = stdout.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
323
- } catch {
324
- // Ignore git diff failures; fall back to committedFiles only.
325
- }
317
+
318
+ // Async + time-capped (30s) + buffer-capped git diff — a wedged git must never block lanes (#305).
319
+ const diffResult = await runShellCommandAsync(worktreePath, "git diff --name-only HEAD", {
320
+ timeoutMs: 30 * 1000,
321
+ maxBuffer: CONTRACT_TEST_COMMAND_MAX_BUFFER,
322
+ });
323
+ const indexAndWorktreeFiles = diffResult.exitCode === 0 ? diffResult.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean) : [];
326
324
 
327
325
  const changedFiles = [...new Set([...committedFiles, ...indexAndWorktreeFiles])];
328
326
 
@@ -335,11 +333,12 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
335
333
  const maxRetries = config?.contract?.testRetries ?? CONTRACT_TEST_DEFAULT_RETRIES;
336
334
  const retryDelayMs = config?.contract?.testRetryDelayMs ?? CONTRACT_TEST_RETRY_DELAY_MS;
337
335
  const totalAttempts = maxRetries + 1;
338
- let lastResult = /** @type {{ ok: boolean, exitCode: number, output: string, bufferOverflow?: boolean, summary?: string, refusedBeforeSpawn?: boolean } | null} */ (null), successAttempt = 0;
336
+ let lastResult = /** @type {{ ok: boolean, exitCode: number, output: string, bufferOverflow?: boolean, summary?: string, refusedBeforeSpawn?: boolean, timedOut?: boolean } | null} */ (null), successAttempt = 0;
339
337
 
340
338
  for (let attempt = 1; attempt <= totalAttempts; attempt++) {
341
- lastResult = runContractTestCommand(worktreePath, parsedContract.testCommand, {
339
+ lastResult = await runContractTestCommand(worktreePath, parsedContract.testCommand, {
342
340
  maxBuffer: config?.contractTestMaxBuffer,
341
+ timeoutMs: config?.contractTestTimeoutMs,
343
342
  });
344
343
 
345
344
  if (lastResult.ok) {
@@ -365,11 +364,11 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
365
364
  totalAttempts,
366
365
  });
367
366
  }
368
- sleepSync(retryDelayMs);
367
+ await sleep(retryDelayMs);
369
368
  }
370
369
  }
371
370
 
372
- const finalResult = /** @type {{ ok: boolean, exitCode: number, output: string, bufferOverflow?: boolean, summary?: string, refusedBeforeSpawn?: boolean }} */ (lastResult);
371
+ const finalResult = /** @type {{ ok: boolean, exitCode: number, output: string, bufferOverflow?: boolean, summary?: string, refusedBeforeSpawn?: boolean, timedOut?: boolean }} */ (lastResult);
373
372
  testCommandOutput = finalResult.output;
374
373
  testCommandOk = finalResult.ok;
375
374
  const attemptLabel = successAttempt > 1
@@ -382,7 +381,9 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
382
381
  ? `testCommand passed${attemptLabel}`
383
382
  : finalResult.bufferOverflow
384
383
  ? `Contract ${finalResult.summary}`
385
- : `Contract testCommand failed after ${totalAttempts} attempt(s) (exit ${finalResult.exitCode}): ${finalResult.summary || "(no output)"}`,
384
+ : finalResult.timedOut
385
+ ? `Contract testCommand failed after ${totalAttempts} attempt(s): ${finalResult.summary}`
386
+ : `Contract testCommand failed after ${totalAttempts} attempt(s) (exit ${finalResult.exitCode}): ${finalResult.summary || "(no output)"}`,
386
387
  });
387
388
  }
388
389
 
@@ -459,7 +460,7 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
459
460
  }
460
461
 
461
462
  if (parsedContract.minLineCoverage != null) {
462
- const actual = resolveLineCoverage(worktreePath, parsedContract, config, testCommandOutput);
463
+ const actual = await resolveLineCoverage(worktreePath, parsedContract, config, testCommandOutput);
463
464
  const required = parsedContract.minLineCoverage;
464
465
  if (actual == null) {
465
466
  checks.push({
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Async shell runner for contract commands (SP-799 / #305).
3
+ *
4
+ * runContractTestCommand originally ran its shell synchronously, which
5
+ * blocked the engine's event loop for the entire command; one slow contract
6
+ * check froze every concurrent lane. This module exposes the same shell
7
+ * semantics ($SHELL resolution, -c flag, capped capture) as a Promise-based
8
+ * primitive that never blocks and never leaks: on timeout the detached process
9
+ * group is terminated through terminateProcessTree so backgrounded
10
+ * grandchildren cannot outlive the run.
11
+ */
12
+
13
+ import { spawn } from "node:child_process";
14
+ import { terminateProcessTree } from "../process/terminate-tree.mjs";
15
+
16
+ /** Grace period between SIGTERM and SIGKILL once a command times out. */
17
+ const TIMEOUT_GRACE_MS = 2000;
18
+
19
+ /**
20
+ * Failsafe settle window after SIGKILL. SIGKILL cannot be ignored, but a
21
+ * grandchild outside the walked tree could still hold the stdio pipes open;
22
+ * settling regardless keeps the awaiter from hanging on process-tree escapees.
23
+ */
24
+ const TIMEOUT_KILL_FAILSAFE_MS = 2000;
25
+
26
+ /** Default wall-clock timeout; matches runContractTestCommand's 10-minute cap. */
27
+ const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
28
+
29
+ /** Default per-stream capture cap (10MB), matching contract-exec's sync default (#86). */
30
+ const DEFAULT_MAX_BUFFER = 10 * 1024 * 1024;
31
+
32
+ /** Exit code reported when the shell itself cannot be spawned (ENOENT convention). */
33
+ const SPAWN_ERROR_EXIT_CODE = 127;
34
+
35
+ /**
36
+ * Resolve the contract shell exactly like runContractTestCommand: $SHELL, else
37
+ * cmd.exe on Windows and /bin/sh elsewhere, with the matching command flag.
38
+ * Lives here (not in contract-exec.mjs) so the sync and async runners share one
39
+ * implementation instead of drifting. Returns a [shell, args] pair ready to
40
+ * spread into spawn().
41
+ *
42
+ * @param {string} command
43
+ * @param {string} [shellOverride]
44
+ * @returns {[string, string[]]}
45
+ */
46
+ export function resolveContractShellInvocation(command, shellOverride) {
47
+ const shell = shellOverride || process.env.SHELL || (process.platform === "win32" ? "cmd.exe" : "/bin/sh");
48
+ const shellFlag = process.platform === "win32" ? "/c" : "-c";
49
+ return [shell, [shellFlag, command]];
50
+ }
51
+
52
+ /**
53
+ * @typedef {Object} ShellCommandResult
54
+ * @property {number | null} exitCode Process exit code; null on timeout or signal-only death.
55
+ * @property {NodeJS.Signals | null} signal Terminating signal when the process was killed.
56
+ * @property {string} stdout Captured stdout (at most maxBuffer bytes, utf-8).
57
+ * @property {string} stderr Captured stderr (at most maxBuffer bytes, utf-8); carries the spawn error message.
58
+ * @property {boolean} timedOut True when the command exceeded timeoutMs and was tree-killed.
59
+ * @property {boolean} truncated True when either stream exceeded maxBuffer and bytes were discarded.
60
+ * @property {number} durationMs Wall-clock duration from spawn to settle.
61
+ */
62
+
63
+ /**
64
+ * Capture a piped stream up to maxBuffer bytes. Past the cap the pipe keeps
65
+ * draining (the data listener stays attached) but further bytes are discarded,
66
+ * so the child never blocks on a full pipe while `truncated` is reported.
67
+ *
68
+ * @param {import("node:stream").Readable} stream
69
+ * @param {number} maxBuffer
70
+ * @returns {{ text: () => string, isTruncated: () => boolean }}
71
+ */
72
+ function createCappedCapture(stream, maxBuffer) {
73
+ /** @type {Buffer[]} */
74
+ const chunks = [];
75
+ let total = 0;
76
+ let truncated = false;
77
+ stream.on("data", (/** @type {Buffer} */ chunk) => {
78
+ if (total >= maxBuffer) {
79
+ truncated = true;
80
+ return;
81
+ }
82
+ const remaining = maxBuffer - total;
83
+ if (chunk.length > remaining) {
84
+ truncated = true;
85
+ chunks.push(chunk.subarray(0, remaining));
86
+ total = maxBuffer;
87
+ return;
88
+ }
89
+ chunks.push(chunk);
90
+ total += chunk.length;
91
+ });
92
+ return {
93
+ text: () => Buffer.concat(chunks).toString("utf-8"),
94
+ isTruncated: () => truncated,
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Build the result for a spawn that failed before any process existed.
100
+ *
101
+ * @param {unknown} error
102
+ * @param {number} startedAt
103
+ * @returns {ShellCommandResult}
104
+ */
105
+ function makeSpawnErrorResult(error, startedAt) {
106
+ const message = error instanceof Error ? error.message : String(error);
107
+ return {
108
+ exitCode: SPAWN_ERROR_EXIT_CODE,
109
+ signal: null,
110
+ stdout: "",
111
+ stderr: message,
112
+ timedOut: false,
113
+ truncated: false,
114
+ durationMs: Date.now() - startedAt,
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Run a shell command asynchronously in `cwd`.
120
+ *
121
+ * Never rejects: spawn failures (e.g. ENOENT shell) resolve with exitCode 127
122
+ * and the error message in stderr. On timeout the process tree gets SIGTERM,
123
+ * then SIGKILL after a 2s grace period, and the result carries
124
+ * `timedOut: true` / `exitCode: null`.
125
+ *
126
+ * @param {string} cwd
127
+ * @param {string} command
128
+ * @param {{ env?: NodeJS.ProcessEnv, timeoutMs?: number, maxBuffer?: number, shell?: string }} [options]
129
+ * @returns {Promise<ShellCommandResult>}
130
+ */
131
+ export function runShellCommandAsync(cwd, command, options = {}) {
132
+ const {
133
+ env = process.env,
134
+ timeoutMs = DEFAULT_TIMEOUT_MS,
135
+ maxBuffer = DEFAULT_MAX_BUFFER,
136
+ shell: shellOverride,
137
+ } = options;
138
+ const startedAt = Date.now();
139
+
140
+ return new Promise((resolve) => {
141
+ /** @type {import("node:child_process").ChildProcess} */
142
+ let child;
143
+ try {
144
+ child = spawn(...resolveContractShellInvocation(String(command ?? ""), shellOverride), {
145
+ cwd,
146
+ env,
147
+ // Detached on POSIX makes the child a process-group leader so the
148
+ // negative-pid group kill in terminateProcessTree reaches every
149
+ // descendant, not just the shell.
150
+ detached: process.platform !== "win32",
151
+ stdio: ["ignore", "pipe", "pipe"],
152
+ });
153
+ } catch (error) {
154
+ // spawn() throws synchronously for invalid arguments; treat like a spawn failure.
155
+ resolve(makeSpawnErrorResult(error, startedAt));
156
+ return;
157
+ }
158
+
159
+ const stdoutCapture = child.stdout
160
+ ? createCappedCapture(child.stdout, maxBuffer)
161
+ : { text: () => "", isTruncated: () => false };
162
+ const stderrCapture = child.stderr
163
+ ? createCappedCapture(child.stderr, maxBuffer)
164
+ : { text: () => "", isTruncated: () => false };
165
+
166
+ let settled = false;
167
+ let timedOut = false;
168
+ /** @type {NodeJS.Timeout | null} */
169
+ let timeoutHandle = null;
170
+ /** @type {NodeJS.Timeout | null} */
171
+ let graceHandle = null;
172
+ /** @type {NodeJS.Timeout | null} */
173
+ let failsafeHandle = null;
174
+
175
+ const clearTimers = () => {
176
+ for (const handle of [timeoutHandle, graceHandle, failsafeHandle]) {
177
+ if (handle) clearTimeout(handle);
178
+ }
179
+ };
180
+
181
+ /**
182
+ * @param {Partial<ShellCommandResult>} overrides
183
+ */
184
+ const finish = (overrides = {}) => {
185
+ if (settled) return;
186
+ settled = true;
187
+ clearTimers();
188
+ resolve({
189
+ exitCode: null,
190
+ signal: null,
191
+ stdout: stdoutCapture.text(),
192
+ stderr: stderrCapture.text(),
193
+ timedOut,
194
+ truncated: stdoutCapture.isTruncated() || stderrCapture.isTruncated(),
195
+ durationMs: Date.now() - startedAt,
196
+ ...overrides,
197
+ });
198
+ };
199
+
200
+ child.on("error", (/** @type {Error} */ error) => {
201
+ if (settled) return;
202
+ finish({
203
+ exitCode: SPAWN_ERROR_EXIT_CODE,
204
+ stderr: `${stderrCapture.text()}\n${error.message}`.trim(),
205
+ });
206
+ });
207
+
208
+ // 'close' (not 'exit') waits for the stdio pipes to drain, so captured
209
+ // output is complete before the promise settles.
210
+ child.on("close", (/** @type {number | null} */ code, /** @type {NodeJS.Signals | null} */ signal) => {
211
+ finish({ exitCode: code, signal });
212
+ });
213
+
214
+ if (Number.isFinite(timeoutMs) && timeoutMs > 0) {
215
+ timeoutHandle = setTimeout(() => {
216
+ timedOut = true;
217
+ terminateProcessTree(child.pid, { signal: "SIGTERM" });
218
+ graceHandle = setTimeout(() => {
219
+ terminateProcessTree(child.pid, { signal: "SIGKILL" });
220
+ failsafeHandle = setTimeout(() => finish(), TIMEOUT_KILL_FAILSAFE_MS);
221
+ }, TIMEOUT_GRACE_MS);
222
+ }, timeoutMs);
223
+ }
224
+ });
225
+ }
@@ -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,
@@ -319,7 +319,7 @@ export async function runMatrixSubLane({
319
319
  } else {
320
320
  // Verify the contract per row (testCommand + fileScopeMustChange
321
321
  // substituted with this row's values). This is the per-row gate.
322
- const verify = verifyContract(worktreePath, contract, {
322
+ const verify = await verifyContract(worktreePath, contract, {
323
323
  matrixRow: values,
324
324
  baseBranch,
325
325
  });
@@ -534,7 +534,7 @@ export async function runMatrixTaskForResume({
534
534
  state.phase = "failed";
535
535
  state.endedAt = Date.now();
536
536
  state.lastError = String(output).slice(0, 500);
537
- saveEngineBatchState(projectRoot, state);
537
+ await saveEngineBatchState(projectRoot, state);
538
538
  return {
539
539
  isMatrix: true,
540
540
  ok: false,
@@ -673,7 +673,7 @@ export async function runMatrixTaskOnLane({
673
673
  skippedRowIds.push(row.rowId);
674
674
  }
675
675
  updateSegmentForTask(state, taskId, "running");
676
- saveEngineBatchState(projectRoot, state);
676
+ await saveEngineBatchState(projectRoot, state);
677
677
 
678
678
  appendJournalEvent(projectRoot, batchId, "task.started", {
679
679
  taskId,
@@ -708,7 +708,7 @@ export async function runMatrixTaskOnLane({
708
708
  const runningEntry = task.matrixRows.find((/** @type {any} */ m) => m.rowId === row.rowId);
709
709
  if (runningEntry) {
710
710
  runningEntry.status = "running";
711
- saveEngineBatchState(projectRoot, state);
711
+ await saveEngineBatchState(projectRoot, state);
712
712
  }
713
713
  try {
714
714
  return await runMatrixSubLane({
@@ -796,7 +796,7 @@ export async function runMatrixTaskOnLane({
796
796
  task.exitReason = `matrix_sub_lane_failed:${failedSummary}`;
797
797
  updateSegmentForTask(state, taskId, "failed");
798
798
  recomputeTaskCounters(state);
799
- saveEngineBatchState(projectRoot, state);
799
+ await saveEngineBatchState(projectRoot, state);
800
800
  recordMatrixEvent(projectRoot, batchId, "matrix.task_failed", {
801
801
  taskId,
802
802
  laneNumber,
@@ -873,7 +873,7 @@ export async function runMatrixTaskOnLane({
873
873
  task.exitReason = `matrix_row_merge_failed:${rowResult.rowId}`;
874
874
  updateSegmentForTask(state, taskId, "failed");
875
875
  recomputeTaskCounters(state);
876
- saveEngineBatchState(projectRoot, state);
876
+ await saveEngineBatchState(projectRoot, state);
877
877
  return {
878
878
  ok: false,
879
879
  workerResult: {