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
@@ -24,6 +24,7 @@
24
24
  import crypto from "node:crypto";
25
25
  import fs from "node:fs";
26
26
  import path from "node:path";
27
+ import { setTimeout as sleepAsync } from "node:timers/promises";
27
28
  import {
28
29
  ENGINE_STARTTIME_TOLERANCE_MS,
29
30
  isProcessAlive,
@@ -172,6 +173,93 @@ function tryCreateLockFile(lockPath, token) {
172
173
  }
173
174
  }
174
175
 
176
+ /**
177
+ * Steal the lock by renaming it out of the acquisition path, but only when
178
+ * the renamed file is still the exact lock that was judged stale (SP-794 /
179
+ * GitHub #302 defect 1).
180
+ *
181
+ * A bare `unlinkSync` could remove a lock a different waiter had freshly
182
+ * acquired after the staleness judgment: two concurrent breakers of the same
183
+ * dead holder would both "win", each running the critical section while the
184
+ * other holds it. `renameSync` is atomic, so at most one breaker ever moves a
185
+ * given lock file; the token/content re-check guarantees the moved file is
186
+ * the same one the breaker judged stale. Exported for direct unit testing of
187
+ * the put-back branch, which cannot be scheduled deterministically through
188
+ * `withBatchStateLock`.
189
+ *
190
+ * @param {string} lockPath
191
+ * @param {string} staleToken ownership token observed when the lock was
192
+ * judged stale; empty for corrupt/invalid payloads that carry no token.
193
+ * @param {string} reason diagnostic label for the steal log
194
+ * @param {string | null} [staleContent] raw payload text observed when the
195
+ * lock was judged stale; compared in full when `staleToken` is empty.
196
+ */
197
+ export function stealIfTokenMatches(lockPath, staleToken, reason, staleContent = null) {
198
+ const stolenPath = `${lockPath}.break.${process.pid}.${newOwnershipToken()}`;
199
+ try {
200
+ fs.renameSync(lockPath, stolenPath);
201
+ } catch {
202
+ // ENOENT: another breaker or the holder's release already removed the
203
+ // lock — nothing to steal. Any other FS error also leaves lockPath
204
+ // untouched; treat it as a lost race so the acquire loop keeps its
205
+ // wait-then-timeout behavior (the unlink-based break this replaces
206
+ // swallowed its failures the same way).
207
+ return;
208
+ }
209
+ // Below this point nothing throws: every op is wrapped so a live holder's
210
+ // lock file is never stranded away from lockPath.
211
+
212
+ /** @type {string | null} */
213
+ let currentContent = null;
214
+ try {
215
+ currentContent = fs.readFileSync(stolenPath, "utf-8");
216
+ } catch {
217
+ currentContent = null;
218
+ }
219
+ let sameStaleLock = false;
220
+ if (typeof staleToken === "string" && staleToken.length > 0) {
221
+ try {
222
+ const current = JSON.parse(currentContent ?? "");
223
+ sameStaleLock =
224
+ current != null &&
225
+ typeof current === "object" &&
226
+ String(/** @type {{ token?: unknown }} */ (current).token ?? "") === staleToken;
227
+ } catch {
228
+ sameStaleLock = false;
229
+ }
230
+ } else {
231
+ // Corrupt/invalid payloads carry no trustworthy token — compare the
232
+ // full file content instead.
233
+ sameStaleLock = currentContent != null && currentContent === staleContent;
234
+ }
235
+
236
+ if (sameStaleLock) {
237
+ logLockBreak(lockPath, reason);
238
+ try {
239
+ fs.unlinkSync(stolenPath);
240
+ } catch {
241
+ /* already removed */
242
+ }
243
+ return;
244
+ }
245
+
246
+ // The lock at lockPath was replaced between the staleness judgment and the
247
+ // rename — a new holder now owns it. Put the file back; EEXIST means a
248
+ // third process already acquired lockPath in the microscopic gap, which is
249
+ // also fine. Either way the renamed copy is discarded.
250
+ try {
251
+ fs.linkSync(stolenPath, lockPath);
252
+ } catch {
253
+ /* EEXIST — someone else owns lockPath now; discard the copy below */
254
+ } finally {
255
+ try {
256
+ fs.unlinkSync(stolenPath);
257
+ } catch {
258
+ /* already removed */
259
+ }
260
+ }
261
+ }
262
+
175
263
  /**
176
264
  * Break the lock when the recorded holder cannot still own it: dead PID,
177
265
  * abandoned corrupt payload, same-process leak (no active holder), or a live
@@ -186,9 +274,12 @@ function tryCreateLockFile(lockPath, token) {
186
274
  function breakStaleLock(lockPath) {
187
275
  /** @type {{ pid?: number, startedAt?: number, token?: string } | null} */
188
276
  let holder = null;
277
+ /** @type {string | null} raw payload text, for content-compare steals. */
278
+ let rawContent = null;
189
279
  let corrupt = false;
190
280
  try {
191
- holder = JSON.parse(fs.readFileSync(lockPath, "utf-8"));
281
+ rawContent = fs.readFileSync(lockPath, "utf-8");
282
+ holder = JSON.parse(rawContent);
192
283
  if (!holder || typeof holder !== "object") corrupt = true;
193
284
  } catch {
194
285
  corrupt = true;
@@ -211,23 +302,13 @@ function breakStaleLock(lockPath) {
211
302
  } catch {
212
303
  return;
213
304
  }
214
- try {
215
- logLockBreak(lockPath, "corrupt-stale");
216
- fs.unlinkSync(lockPath);
217
- } catch {
218
- /* raced unlink */
219
- }
305
+ stealIfTokenMatches(lockPath, "", "corrupt-stale", rawContent);
220
306
  return;
221
307
  }
222
308
 
223
309
  const holderPid = Number(holder?.pid);
224
310
  if (!Number.isFinite(holderPid) || holderPid <= 0) {
225
- try {
226
- logLockBreak(lockPath, "invalid-pid");
227
- fs.unlinkSync(lockPath);
228
- } catch {
229
- /* raced unlink */
230
- }
311
+ stealIfTokenMatches(lockPath, "", "invalid-pid", rawContent);
231
312
  return;
232
313
  }
233
314
 
@@ -242,12 +323,12 @@ function breakStaleLock(lockPath) {
242
323
  if (stillHeldByToken || stillHeldByPath) {
243
324
  return;
244
325
  }
245
- try {
246
- logLockBreak(lockPath, `leakedSelf token=${token} mapSize=${heldByThisProcess.size}`);
247
- fs.unlinkSync(lockPath);
248
- } catch {
249
- /* raced unlink */
250
- }
326
+ stealIfTokenMatches(
327
+ lockPath,
328
+ token,
329
+ `leakedSelf token=${token} mapSize=${heldByThisProcess.size}`,
330
+ rawContent,
331
+ );
251
332
  return;
252
333
  }
253
334
 
@@ -255,12 +336,12 @@ function breakStaleLock(lockPath) {
255
336
  // under suite load the PID is often recycled by an unrelated live process,
256
337
  // and refusing to break left waiters stuck until timeout (stale-lock flake).
257
338
  if (holderPid !== process.pid && !isProcessAlive(holderPid)) {
258
- try {
259
- logLockBreak(lockPath, `deadPid holder=${holderPid}`);
260
- fs.unlinkSync(lockPath);
261
- } catch {
262
- /* raced unlink */
263
- }
339
+ stealIfTokenMatches(
340
+ lockPath,
341
+ String(holder?.token ?? ""),
342
+ `deadPid holder=${holderPid}`,
343
+ rawContent,
344
+ );
264
345
  return;
265
346
  }
266
347
 
@@ -281,12 +362,12 @@ function breakStaleLock(lockPath) {
281
362
  }
282
363
  if (liveStart == null || !Number.isFinite(liveStart) || liveStart <= 0) return;
283
364
  if (liveStart - expectedStart > STARTTIME_TOLERANCE_MS) {
284
- try {
285
- logLockBreak(lockPath, `pidRecycled holder=${holderPid}`);
286
- fs.unlinkSync(lockPath);
287
- } catch {
288
- /* raced unlink */
289
- }
365
+ stealIfTokenMatches(
366
+ lockPath,
367
+ String(holder?.token ?? ""),
368
+ `pidRecycled holder=${holderPid}`,
369
+ rawContent,
370
+ );
290
371
  }
291
372
  }
292
373
  }
@@ -355,3 +436,64 @@ export function withBatchStateLock(projectRoot, fn, options = {}) {
355
436
  }
356
437
  }
357
438
  }
439
+
440
+ /**
441
+ * Async twin of `withBatchStateLock` for event-loop callers (SP-797 / #302):
442
+ * same acquire loop, stale breaking, token release, and re-entrancy, but the
443
+ * contention wait yields via `node:timers/promises` instead of blocking the
444
+ * thread — a CLI-held lock can no longer freeze engine heartbeats, pipe
445
+ * draining, and stall timers. `fn` MUST stay synchronous: no `await` between
446
+ * acquire and release, or the re-entrancy map breaks. Uncontended calls reach
447
+ * `fn` before the first `await`. Waits >1 s log one `[spine]` stderr line.
448
+ *
449
+ * @param {string} projectRoot
450
+ * @param {() => unknown} fn synchronous critical section
451
+ * @param {{ timeoutMs?: number }} [options]
452
+ * @returns {Promise<unknown>} `fn`'s return value
453
+ */
454
+ export async function withBatchStateLockAsync(projectRoot, fn, options = {}) {
455
+ const lockPath = batchStateLockPath(projectRoot);
456
+
457
+ // Re-entrant pass-through: nested sync/async calls from this process run directly.
458
+ if (heldByThisProcess.has(lockPath)) {
459
+ return fn();
460
+ }
461
+
462
+ const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : DEFAULT_TIMEOUT_MS;
463
+ const deadline = Date.now() + timeoutMs;
464
+ const token = newOwnershipToken();
465
+ const waitStartedAt = Date.now();
466
+
467
+ for (;;) {
468
+ if (tryCreateLockFile(lockPath, token)) break;
469
+ breakStaleLock(lockPath);
470
+ if (Date.now() >= deadline) {
471
+ throw new Error(
472
+ `Timed out acquiring batch-state lock (${path.relative(projectRoot, lockPath)}) ` +
473
+ `after ${timeoutMs}ms — another spine process may be holding it`,
474
+ );
475
+ }
476
+ await sleepAsync(POLL_INTERVAL_MS);
477
+ }
478
+
479
+ const waitedMs = Date.now() - waitStartedAt;
480
+ heldByThisProcess.set(lockPath, token);
481
+ try {
482
+ return fn();
483
+ } finally {
484
+ // Token-gated unlink before map clear (see `withBatchStateLock`).
485
+ try {
486
+ releaseLockFile(lockPath, token);
487
+ } finally {
488
+ heldByThisProcess.delete(lockPath);
489
+ if (waitedMs > 1_000) {
490
+ const rel = path.relative(projectRoot, lockPath);
491
+ try {
492
+ process.stderr.write(`[spine] batch-state lock wait took ${waitedMs}ms (${rel}) — another spine process held it\n`);
493
+ } catch {
494
+ /* diagnostic only — never fail a state save on stderr */
495
+ }
496
+ }
497
+ }
498
+ }
499
+ }
@@ -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
+ }