pi-spine 2.25.0 → 2.27.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 (66) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +14 -1
  4. package/package.json +3 -3
  5. package/skills/spine-release-operator/SKILL.md +3 -0
  6. package/src/batch/abort.mjs +74 -38
  7. package/src/batch/attached-engine-handoff.mjs +2 -2
  8. package/src/batch/attached-runner-promote.mjs +1 -1
  9. package/src/batch/attached-runner-reconcile.mjs +1 -1
  10. package/src/batch/batch-meta-reconstruct.mjs +9 -1
  11. package/src/batch/batch-state-lock.mjs +173 -31
  12. package/src/batch/contract-exec.mjs +48 -47
  13. package/src/batch/contract-parse.mjs +2 -2
  14. package/src/batch/contract-prelanded.mjs +2 -2
  15. package/src/batch/contract-spawn.mjs +225 -0
  16. package/src/batch/contract-verify.mjs +2 -1
  17. package/src/batch/detached-wait.mjs +1 -1
  18. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  19. package/src/batch/diagnosis-pending-lane.mjs +34 -1
  20. package/src/batch/engine-lanes/matrix-run.mjs +6 -6
  21. package/src/batch/engine-lanes/merge.mjs +135 -34
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  24. package/src/batch/engine-lanes/review-code.mjs +1 -0
  25. package/src/batch/engine-lanes/review-final.mjs +83 -46
  26. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  27. package/src/batch/engine-lanes/review-poll.mjs +47 -1
  28. package/src/batch/engine-lanes.mjs +17 -16
  29. package/src/batch/engine.mjs +10 -10
  30. package/src/batch/journal.mjs +15 -0
  31. package/src/batch/lifecycle-archive.mjs +76 -1
  32. package/src/batch/lifecycle-cleanup.mjs +110 -0
  33. package/src/batch/lifecycle.mjs +100 -72
  34. package/src/batch/metrics.mjs +13 -1
  35. package/src/batch/parent-session-monitor.mjs +77 -70
  36. package/src/batch/pause.mjs +92 -25
  37. package/src/batch/post-merge-limbo.mjs +35 -5
  38. package/src/batch/provider-quota.mjs +220 -0
  39. package/src/batch/quota-fallback.mjs +319 -0
  40. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  41. package/src/batch/resume-gate-reopen.mjs +24 -8
  42. package/src/batch/resume-multi-queue.mjs +25 -10
  43. package/src/batch/resume-multi.mjs +1 -1
  44. package/src/batch/resume.mjs +1 -1
  45. package/src/batch/review-artifacts.mjs +93 -15
  46. package/src/batch/review-spawn-retry.mjs +106 -0
  47. package/src/batch/review-spawn.mjs +48 -2
  48. package/src/batch/review-step-run.mjs +96 -6
  49. package/src/batch/reviewer-output.mjs +162 -0
  50. package/src/batch/sequence-run.mjs +26 -8
  51. package/src/batch/sequence-wait.mjs +87 -8
  52. package/src/batch/state-guards.mjs +39 -7
  53. package/src/batch/state-io.mjs +131 -17
  54. package/src/batch/state.mjs +1 -0
  55. package/src/batch/worker-host.mjs +81 -7
  56. package/src/config/cursor-rules/discover.mjs +2 -2
  57. package/src/config/cursor-rules/match-globs.mjs +6 -4
  58. package/src/config/defaults.mjs +15 -1
  59. package/src/config/env-overrides.mjs +41 -4
  60. package/src/config/preflight/git-batch.mjs +47 -0
  61. package/src/config/settings-fields.mjs +6 -0
  62. package/src/config/spine-config-schema.mjs +91 -1
  63. package/src/doctor/quota-risk.mjs +45 -0
  64. package/src/fs/atomic-write.mjs +37 -1
  65. package/src/planner/file-scope.mjs +6 -6
  66. package/src/tasks/packet/validate-contract.mjs +3 -3
@@ -4,8 +4,8 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
- import { spawnSync, execFileSync } from "node:child_process";
8
- import micromatch from "micromatch";
7
+ import { setTimeout as sleep } from "node:timers/promises";
8
+ import picomatch from "picomatch";
9
9
  import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
10
10
  import {
11
11
  isBaseFileScopeSatisfied,
@@ -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);
@@ -265,7 +264,7 @@ function findArtifactMatch(worktreePath, artifactPattern) {
265
264
  stack.push({ abs: entryAbs, rel: entryRel });
266
265
  continue;
267
266
  }
268
- if (micromatch.isMatch(entryRel, normalized)) {
267
+ if (picomatch(normalized, { dot: true })(entryRel)) {
269
268
  return { ok: true, matchedPath: entryRel };
270
269
  }
271
270
  }
@@ -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({
@@ -5,7 +5,7 @@
5
5
 
6
6
  import fs from "node:fs";
7
7
  import { execFileSync } from "node:child_process";
8
- import micromatch from "micromatch";
8
+ import picomatch from "picomatch";
9
9
  import { resolveContractMode } from "../tasks/packet/validate-contract.mjs";
10
10
  import {
11
11
  isBaseScopeSatisfied,
@@ -199,7 +199,7 @@ export function listChangedFiles(worktreePath, baseBranch = "main", sinceCommit
199
199
  * @param {string} pattern
200
200
  */
201
201
  export function matchesContractPattern(file, pattern) {
202
- return micromatch.isMatch(file, pattern, { dot: true });
202
+ return picomatch(pattern, { dot: true })(file);
203
203
  }
204
204
 
205
205
  /**
@@ -5,7 +5,7 @@
5
5
 
6
6
  import path from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
- import micromatch from "micromatch";
8
+ import picomatch from "picomatch";
9
9
  import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
10
10
 
11
11
  /**
@@ -13,7 +13,7 @@ import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
13
13
  * @param {string} pattern
14
14
  */
15
15
  function matchesPattern(file, pattern) {
16
- return micromatch.isMatch(file, pattern, { dot: true });
16
+ return picomatch(pattern, { dot: true })(file);
17
17
  }
18
18
 
19
19
  /**
@@ -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,
@@ -4,6 +4,41 @@
4
4
  * Kept out of diagnosis.mjs so the parent stays under the phase23 LOC cap.
5
5
  */
6
6
 
7
+ /**
8
+ * True when the latest quota-exhaustion journal payload came from
9
+ * `batch.quota_fallback_exhausted` — the parallel arrays are unique to that
10
+ * event (SP-808), so a fallback hop that died too is distinguishable from a
11
+ * plain worker exhaustion without carrying the event type through the ctx.
12
+ *
13
+ * @param {object|null} lastQuotaExhausted
14
+ * @returns {boolean}
15
+ */
16
+ function isFallbackChainExhausted(lastQuotaExhausted) {
17
+ return Array.isArray(lastQuotaExhausted?.exhaustedPools);
18
+ }
19
+
20
+ /**
21
+ * Human-readable reset windows for the exhausted pool(s): a single
22
+ * "resets <raw>" for a worker exhaustion, or one per pool when the fallback
23
+ * chain died too (#329 wants the operator to see every window). Falls back to
24
+ * "reset time unknown" — the raw provider text carries no timezone, so it is
25
+ * shown verbatim rather than parsed into a wrong clock time.
26
+ *
27
+ * @param {object|null} lastQuotaExhausted
28
+ * @returns {string}
29
+ */
30
+ function quotaResetSummary(lastQuotaExhausted) {
31
+ if (isFallbackChainExhausted(lastQuotaExhausted)) {
32
+ const pools = /** @type {string[]} */ (lastQuotaExhausted.exhaustedPools);
33
+ const resets = Array.isArray(lastQuotaExhausted.resetAtRaw) ? lastQuotaExhausted.resetAtRaw : [];
34
+ return pools
35
+ .map((pool, index) => `${pool} resets ${resets[index] ?? "unknown"}`)
36
+ .join(", ");
37
+ }
38
+ const reset = lastQuotaExhausted?.resetAtRaw;
39
+ return typeof reset === "string" && reset ? `resets ${reset}` : "reset time unknown";
40
+ }
41
+
7
42
  /**
8
43
  * SBAR Background — short decision-relevant facts that explain the state the
9
44
  * assessment was derived from. Facts are additive; consumers that ignore
@@ -32,6 +67,27 @@ export function buildBackground(diagnosis, ctx = {}) {
32
67
  `Failed task: ${ctx.failedTaskId}${ctx.exitReason ? ` (exit: ${ctx.exitReason})` : ""}`,
33
68
  );
34
69
  }
70
+ // SP-810 (partial #329): when a fallback hop is active, operators must see
71
+ // which pool died, when it resets, and where the batch landed — plus the
72
+ // paste-ready manifest line the #248 pin policy requires them to record.
73
+ if (ctx.quotaFallback && typeof ctx.quotaFallback === "object" && ctx.quotaFallback.toProfile) {
74
+ const fallback = ctx.quotaFallback;
75
+ facts.push(
76
+ `Quota fallback active: ${fallback.exhaustedPool ?? "?"} exhausted (resets ${
77
+ fallback.resetAtRaw ?? "unknown"
78
+ }, provider local time) → ${fallback.toProfile} (${fallback.toModel ?? "?"}) since ${
79
+ fallback.at ?? "?"
80
+ }, triggered by ${fallback.triggerTaskId ?? "?"}`,
81
+ );
82
+ // Manifest text stays ASCII (`->`) exactly as operators paste it into the
83
+ // release manifest; the date is the YYYY-MM-DD slice of the hop timestamp.
84
+ const overrideDate = typeof fallback.at === "string" ? fallback.at.slice(0, 10) : "?";
85
+ facts.push(
86
+ `Agent pin override: yes (${overrideDate}, auto quota fallback ${
87
+ fallback.exhaustedPool ?? "?"
88
+ } -> ${fallback.toProfile}, batch ${ctx.batchId ?? "?"})`,
89
+ );
90
+ }
35
91
  if (ctx.launchFailureKind) {
36
92
  facts.push(`Launch failure kind: ${ctx.launchFailureKind}`);
37
93
  }
@@ -87,6 +143,24 @@ export function buildAssessmentReason(diagnosis, ctx = {}) {
87
143
  case "completed_manual":
88
144
  return "Work is already on the base branch while the batch record is still active — operator completed it manually";
89
145
  case "needs_retry":
146
+ // SP-810 (partial #329): a quota exhaustion with no fallback that can
147
+ // take over must not imply an immediate retry will work — show the
148
+ // reset window instead. Fallback is hopeless when no hop is persisted
149
+ // (unset/refused) or the fallback chain itself exhausted (stop event).
150
+ if (
151
+ ctx.failedTaskId &&
152
+ ctx.exitReason === "provider_quota_exhausted" &&
153
+ (ctx.quotaFallback == null || isFallbackChainExhausted(ctx.lastQuotaExhausted))
154
+ ) {
155
+ return `Task ${ctx.failedTaskId} exited "provider_quota_exhausted": provider quota is exhausted (${quotaResetSummary(
156
+ ctx.lastQuotaExhausted,
157
+ )}, provider local time) and no quota fallback can take over — an immediate retry hits the same quota limit`;
158
+ }
159
+ // Transient overload never falls back (#329) and clears on its own, so
160
+ // here a plain retry genuinely is the right move.
161
+ if (ctx.failedTaskId && ctx.exitReason === "provider_overloaded") {
162
+ return `Task ${ctx.failedTaskId} exited "provider_overloaded": transient provider overload — retry is reasonable`;
163
+ }
90
164
  if (ctx.failedTaskId && ctx.exitReason) {
91
165
  return `Task ${ctx.failedTaskId} exited "${ctx.exitReason}" without completing its contract, so the batch cannot proceed until it is retried`;
92
166
  }
@@ -3,6 +3,9 @@
3
3
  * Pending lane land diagnosis — lane `.DONE` without main land (#201 / SP-645).
4
4
  */
5
5
 
6
+ import { isEngineProcessAlive } from "../process/liveness.mjs";
7
+ import { readBatchEnginePid, readBatchEngineStartedAt } from "./state-guards.mjs";
8
+
6
9
  /**
7
10
  * Tasks with lane `.DONE` but not on main — lane commits never landed (#201 / SP-645).
8
11
  *
@@ -14,11 +17,41 @@ export function findPendingLaneLandTasks(tasks) {
14
17
  return tasks.filter((task) => task?.doneInLane === true && task?.doneOnMain !== true);
15
18
  }
16
19
 
20
+ /**
21
+ * Guard for #330 / SP-815: the batch engine is alive AND the raw batch state
22
+ * still shows live activity (phase "running" or a running task). Reconciled
23
+ * signals can already look terminal-success mid-wave because a lane `.DONE`
24
+ * is reconciled (`done_in_lane_terminal`) before the engine finishes code and
25
+ * final review — so salvage guidance must be suppressed until the engine
26
+ * exits or the state goes terminal. Both conditions must hold: a crashed
27
+ * engine with a stale running phase still deserves salvage guidance.
28
+ *
29
+ * @param {object|null|undefined} raw raw batch state (`signals.raw`)
30
+ * @param {object} [deps]
31
+ * @param {(raw: object) => boolean} [deps.isEngineAlive] injectable engine liveness probe
32
+ * @returns {boolean}
33
+ */
34
+ export function isLiveEngineMidTask(raw, deps = {}) {
35
+ if (!raw || typeof raw !== "object") return false;
36
+ const isEngineAlive =
37
+ deps.isEngineAlive ??
38
+ ((state) => isEngineProcessAlive(readBatchEnginePid(state), readBatchEngineStartedAt(state)));
39
+ if (!isEngineAlive(raw)) return false;
40
+ if (raw.phase === "running") return true;
41
+ const tasks = Array.isArray(raw.tasks) ? raw.tasks : [];
42
+ return tasks.some((task) => task?.status === "running");
43
+ }
44
+
17
45
  /**
18
46
  * @param {object} signals
47
+ * @param {object} [deps]
48
+ * @param {(raw: object) => boolean} [deps.isEngineAlive] injectable engine liveness probe
19
49
  * @returns {boolean}
20
50
  */
21
- export function shouldDiagnosePendingLaneLand(signals) {
51
+ export function shouldDiagnosePendingLaneLand(signals, deps = {}) {
52
+ // Live engine mid-task: the lane may be about to land under the engine
53
+ // itself — never suggest salvage while it is still running (#330 / SP-815).
54
+ if (isLiveEngineMidTask(signals?.raw, deps)) return false;
22
55
  const pending = findPendingLaneLandTasks(signals.tasks);
23
56
  if (pending.length === 0) return false;
24
57
  // Only when orch already appears merged — otherwise healthy pre-integrate