pi-spine 2.28.1 → 2.30.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.
@@ -111,7 +111,12 @@ export function stripBatchFlagValueTokens(args) {
111
111
  export function formatLifecycleHuman(result, json = false) {
112
112
  if (json) return `${JSON.stringify(result, null, 2)}\n`;
113
113
 
114
- const lines = ["", result.ok ? "Batch lifecycle" : "Batch lifecycle failed", "", ` ${result.headline}`];
114
+ const lines = [
115
+ "",
116
+ result.ok ? "Batch lifecycle" : result.pending ? "Batch lifecycle pending" : "Batch lifecycle failed",
117
+ "",
118
+ ` ${result.headline}`,
119
+ ];
115
120
 
116
121
  if (result.error) {
117
122
  lines.push("", ` Error: ${result.error}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.28.1",
3
+ "version": "2.30.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -72,14 +72,17 @@
72
72
  }
73
73
  },
74
74
  "devDependencies": {
75
- "@earendil-works/pi-coding-agent": "^1.0.1",
75
+ "@earendil-works/pi-coding-agent": "^1.4.0",
76
76
  "@types/node": "^22.20.4",
77
- "eslint": "^10.11.0",
78
- "globals": "^17.12.0",
77
+ "eslint": "^10.14.0",
78
+ "globals": "^17.14.0",
79
79
  "typebox": "1.3.34",
80
80
  "typescript": "6.0.3"
81
81
  },
82
82
  "license": "MIT",
83
+ "overrides": {
84
+ "undici": "^8.12.2"
85
+ },
83
86
  "dependencies": {
84
87
  "picomatch": "^4.0.7"
85
88
  }
@@ -413,7 +413,7 @@ Individual steps can override the task-level review:
413
413
  | **1** | PROMPT.md + STATUS.md | Always |
414
414
  | **2** | `{tasksRoot}/CONTEXT.md` | When listed in "Context to Read First" |
415
415
  | **3** | Specific reference docs | Only what the task needs |
416
- | **4** | Cursor rules (when `.cursor/rules/` exists) | **Workers:** auto-selected per task via profile `worker.*`, PROMPT File Scope globs, `config.standards` append (FR-WORK-05). **Reviewers:** separate `profile.reviewer.*` selection with review-type scope — plan uses File Scope, code uses git diff paths, final uses always-only rules; 16 KiB cap, no `referenceDocs` (FR-REV-08) |
416
+ | **4** | Cursor rules (when `.cursor/rules/` exists) | **Workers:** auto-selected per task via profile `worker.*`, PROMPT File Scope globs, `config.standards` append (FR-WORK-05). **Reviewers:** separate `profile.reviewer.*` selection with review-type scope — plan uses File Scope; code uses git diff paths with File Scope fallback on empty diff or git error; final uses baseline diff paths with File Scope fallback; 16 KiB cap, no `referenceDocs` (FR-REV-08) |
417
417
 
418
418
  Populate "Context to Read First" from `referenceDocs` in spine config. Never list docs in `neverLoad`.
419
419
 
@@ -486,7 +486,7 @@ When decomposing a PRD, assign non-overlapping file scopes to tasks that should
486
486
 
487
487
  **Worker rules:** File Scope also drives **glob-matched Cursor rules** injected into batch workers (FR-WORK-05). Tasks touching `**/*.{js,mjs}` activate JS standards; Swift/Python tasks need scope paths that match those rule globs. Keep scope precise — wide scope pulls more rules and increases prompt byte usage.
488
488
 
489
- **Reviewer rules (FR-REV-08):** Plan reviews use the same File Scope for glob matching; code reviews use changed paths from `git diff`. Final reviews load always-on rules only. Worker-only packs (`taskplane-worker-cursor.mdc`) are excluded from reviewer context by default.
489
+ **Reviewer rules (FR-REV-08):** Plan reviews use the same File Scope for glob matching; code reviews use changed paths from `git diff`, falling back to the File Scope when the diff is empty or git fails (#357). Final reviews use baseline diff paths when available, else the File Scope — code and final reviews never run with an empty scope when the packet has a File Scope. Worker-only packs (`taskplane-worker-cursor.mdc`) are excluded from reviewer context by default.
490
490
 
491
491
  **Documentation paths in File Scope ([#144](https://github.com/beettlle/pi-spine/issues/144)):** Every path under **Must Update** in `## Documentation Requirements` **must** also appear in `## File Scope`. If a doc is advisory only, move it to **Check If Affected** — do not require workers to edit paths outside File Scope. Mismatches (e.g. SP-435, SP-451) caused out-of-scope edits and merge dirty-file failures.
492
492
 
@@ -37,6 +37,7 @@ Avoid `` `bin/a.mjs,bin/b.mjs` `` — `tasks validate` warns (or errors in requi
37
37
  | Field | When to include | Value format |
38
38
  |-------|-----------------|--------------|
39
39
  | `testCommand` | **Required** for code tasks (Review Level ≥ 1, Size M/L, or implementation steps) | Shell command in backticks; max 500 chars; no newlines. **Code tasks:** prefix with project lint/analyze (`npm run lint &&` for pi-spine; `flutter analyze` scoped for Flutter). Contract verify executes this command at final review — lint runs in-lane when authored here. Post-integrate `release:check` remains the whole-repo backstop (full suite + coverage). Use `` `true` `` for docs-only S tasks with no code changes. When `` `true` ``, **always** pair with `fileScopeMustChange` (see below). |
40
+ | `reviewCommand` | Code tasks adding a stet review gate (SP-845); **omit** for docs-only and `Type: execute` packets | `` `bash scripts/spine-stet-contract-run.sh <lenient\|default\|strict> SP-###` ``. Runs **once** after `testCommand` passes (skipped when the test step fails), never retries, and is bounded by `contract.reviewTimeoutMs` (default 20 min) with policy `contract.reviewPolicy` (`blocking` default; `advisory` journals `contract.review_advisory` and records a STATUS Discoveries row instead of failing). **Never chain stet onto `testCommand`** — the review then runs under the 10-minute test timeout instead of its own. Strictness by size: S → `lenient` or `default`; M → `default`; security-sensitive → `strict`. The gate blocks only findings at severity `warning` or above with confidence ≥ 0.8 (override with `SPINE_STET_MIN_SEVERITY` / `SPINE_STET_MIN_CONFIDENCE`). |
40
41
  | `fileScopeMustChange` | When you need proof specific paths were touched; **required** when `testCommand` is `` `true` `` | Comma-separated paths/globs relative to repo root; **one backtick per path** (not `` `a.mjs,b.mjs` ``). Trailing `/` means directory prefix match (e.g. `src/domain/types/` matches any file under that directory). For docs-only tasks, list at least one documentation deliverable path — without it, workers can pass contract by creating only `.DONE` (SP-214 batch `20260612T204048`, SP-457 batch `20260703T022335`). |
41
42
  | `fileScopeMustNotChange` | When **parallel lanes** must not collide on product paths (see semantics below) | Comma-separated paths/globs relative to repo root; **one backtick per path** |
42
43
  | `minLineCoverage` | Size L tasks that change application code (S/M rely on post-integrate `release:check` coverage) | Integer 0–100 (pi-spine policy: **77**) |
@@ -114,6 +115,7 @@ Symptom in journal: `testCommand` passes but `fileScopeMustNotChange` fails with
114
115
  | Field | Value |
115
116
  |-------|-------|
116
117
  | testCommand | `npm run lint && npm run typecheck && SPINE_WORKER_STUB=1 node --experimental-strip-types --test --test-reporter=dot tests/tasks/validate-prompt.test.mjs` |
118
+ | reviewCommand | `bash scripts/spine-stet-contract-run.sh <lenient\|default\|strict> SP-###` |
117
119
  | fileScopeMustChange | `src/tasks/packet/validate-prompt.mjs` |
118
120
  | minLineCoverage | 77 |
119
121
  ```
@@ -26,7 +26,12 @@ 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
+ import { buildContractTestEnv, runShellCommandAsync } from "./contract-spawn.mjs";
30
+ import { runContractReviewStep } from "./contract-review.mjs";
31
+
32
+ // Worker env stripping + re-export moved to contract-spawn.mjs (SP-845 keeps
33
+ // contract-review.mjs cycle-free); the public surface is unchanged.
34
+ export { CONTRACT_TEST_WORKER_ENV_KEYS, buildContractTestEnv } from "./contract-spawn.mjs";
30
35
 
31
36
  // Shared pre-spawn refusal envelope for the npm-scope (#187) and metachar (#268) guards.
32
37
  function refusedBeforeSpawnResult(/** @type {string} */ summary) {
@@ -42,33 +47,6 @@ export const CONTRACT_TEST_DEFAULT_RETRIES = 1;
42
47
  /** Default delay in ms between testCommand retry attempts. */
43
48
  export const CONTRACT_TEST_RETRY_DELAY_MS = 5000;
44
49
 
45
- /**
46
- * Worker-only env keys stripped from contract testCommand subprocesses so full-suite
47
- * tests match operator re-run outside worker-host (SP-491, issue #155).
48
- */
49
- export const CONTRACT_TEST_WORKER_ENV_KEYS = ["SPINE_IS_WORKER"];
50
-
51
- /**
52
- * Build env for contract testCommand subprocess — omits worker-only keys inherited from
53
- * worker-host.mjs that would false-fail batch-spawn integration tests (SP-482 guard).
54
- * Preserves parent batch id as SPINE_PARENT_BATCH_ID so nested-spawn guard can block
55
- * live engines in lane worktrees while still allowing isolated fixture tests (#162).
56
- *
57
- * @param {NodeJS.ProcessEnv} [sourceEnv]
58
- * @returns {NodeJS.ProcessEnv}
59
- */
60
- export function buildContractTestEnv(sourceEnv = process.env) {
61
- const env = { ...sourceEnv };
62
- for (const key of CONTRACT_TEST_WORKER_ENV_KEYS) {
63
- delete env[key];
64
- }
65
- if (env.SPINE_BATCH_ID && !env.SPINE_PARENT_BATCH_ID) {
66
- env.SPINE_PARENT_BATCH_ID = env.SPINE_BATCH_ID;
67
- }
68
- delete env.SPINE_BATCH_ID;
69
- return env;
70
- }
71
-
72
50
  /**
73
51
  * @param {number} byteCount
74
52
  */
@@ -302,7 +280,7 @@ export function prepareContractVerifyEnvironment(worktreePath, parsedContract, c
302
280
  * @param {string} [config.batchId] Batch ID for journal events (optional).
303
281
  * @param {string} [config.taskId] Task ID for journal events (optional).
304
282
  * @param {string} [config.taskFolder] Task folder path for writing failure logs to .reviews/ (optional).
305
- * @param {{ testRetries?: number, testRetryDelayMs?: number, testTimeoutMs?: number }} [config.contract] Retry and per-attempt timeout tuning (#369).
283
+ * @param {{ reviewPolicy?: "blocking" | "advisory", reviewTimeoutMs?: number, testRetries?: number, testRetryDelayMs?: number, testTimeoutMs?: number }} [config.contract] Retry/timeout tuning (#369) and review step policy (SP-845).
306
284
  * @param {number} [config.contractTestMaxBuffer] stdout/stderr capture limit override.
307
285
  * @param {{ test?: string, testWithCoverage?: string }} [config.testing] Coverage command selection.
308
286
  * @returns {Promise<{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number }>}
@@ -386,6 +364,13 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
386
364
  });
387
365
  }
388
366
 
367
+ // SP-845: reviewCommand runs once, only when the test step passed (or is absent).
368
+ // Failures never retry — reviewers resume their own session.
369
+ if (parsedContract.reviewCommand && (!parsedContract.testCommand || testCommandOk)) {
370
+ const reviewCheck = await runContractReviewStep(worktreePath, parsedContract, config);
371
+ if (reviewCheck) checks.push(reviewCheck);
372
+ }
373
+
389
374
  for (const pattern of parsedContract.fileScopeMustChange ?? []) {
390
375
  const matched = changedFiles.some((file) =>
391
376
  pattern.endsWith("/") ? file.startsWith(pattern) : matchesContractPattern(file, pattern),
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Contract reviewCommand step (SP-845).
3
+ *
4
+ * Runs once after testCommand passes, with its own timeout
5
+ * (`contract.reviewTimeoutMs`) and an explicit policy (`contract.reviewPolicy`
6
+ * = `blocking` | `advisory`). No retries: reviewers resume their own session,
7
+ * so a re-run would re-review rather than resume.
8
+ *
9
+ * Blocking: a non-zero exit or a timeout fails the contract with a
10
+ * `reviewCommand` check. Advisory: the check passes, but the engine journals
11
+ * `contract.review_advisory` and appends a row to the task STATUS.md
12
+ * Discoveries table so the failure stays visible.
13
+ */
14
+
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+
18
+ import { CONTRACT_REVIEW_TIMEOUT_DEFAULT_MS } from "../config/contract.mjs";
19
+ import { findContractCommandMetacharIssue } from "../tasks/packet/parse-prompt.mjs";
20
+ import { appendJournalEvent } from "./journal.mjs";
21
+ import { buildContractTestEnv, runShellCommandAsync } from "./contract-spawn.mjs";
22
+
23
+ /** Default stdout/stderr capture limit for contract reviewCommand (mirrors #86). */
24
+ export const CONTRACT_REVIEW_COMMAND_MAX_BUFFER = 10 * 1024 * 1024;
25
+
26
+ /** Policy applied when `contract.reviewPolicy` is unset — reviews block. */
27
+ export const CONTRACT_REVIEW_POLICY_DEFAULT = "blocking";
28
+
29
+ /**
30
+ * @typedef {Object} ContractReviewCommandResult
31
+ * @property {boolean} ok
32
+ * @property {number} exitCode
33
+ * @property {string} output
34
+ * @property {boolean} [timedOut]
35
+ * @property {boolean} [bufferOverflow]
36
+ * @property {boolean} [refusedBeforeSpawn]
37
+ * @property {string} [summary]
38
+ */
39
+
40
+ /**
41
+ * @param {number} timeoutMs
42
+ * @returns {string} e.g. "20 min" / "0.5 min", matching runContractTestCommand labels.
43
+ */
44
+ export function formatReviewTimeoutLabel(timeoutMs) {
45
+ return `${(timeoutMs / 60000).toFixed(2).replace(/\.?0+$/, "")} min`;
46
+ }
47
+
48
+ /**
49
+ * Shared pre-spawn refusal envelope, mirroring contract-exec's shape.
50
+ *
51
+ * @param {string} summary
52
+ */
53
+ function refusedBeforeSpawnResult(summary) {
54
+ return { ok: false, exitCode: 1, output: summary, summary, refusedBeforeSpawn: true };
55
+ }
56
+
57
+ /**
58
+ * Run the contract reviewCommand once.
59
+ *
60
+ * Mirrors runContractTestCommand's shell semantics ($SHELL, capped capture,
61
+ * tree-kill on timeout) minus the npm-scope guard and retries — reviewCommand
62
+ * never retries. "true" and empty commands pass without spawning, like
63
+ * testCommand.
64
+ *
65
+ * @param {string} worktreePath
66
+ * @param {string} command
67
+ * @param {{ timeoutMs?: number, maxBuffer?: number }} [options]
68
+ * @returns {Promise<ContractReviewCommandResult>}
69
+ */
70
+ export async function runContractReviewCommand(worktreePath, command, options = {}) {
71
+ const trimmed = String(command ?? "").trim();
72
+ if (!trimmed || trimmed === "true") {
73
+ return { ok: true, exitCode: 0, output: "" };
74
+ }
75
+
76
+ // Defense in depth: parse-prompt already rejects these at packet parse
77
+ // time; matrix-row substitution can still inject them afterwards (SP-781).
78
+ if (trimmed.includes("\n")) {
79
+ return refusedBeforeSpawnResult("Contract reviewCommand must not contain newlines");
80
+ }
81
+ const metacharIssue = findContractCommandMetacharIssue(trimmed);
82
+ if (metacharIssue) {
83
+ return refusedBeforeSpawnResult(
84
+ `Contract reviewCommand refused before spawn: ${metacharIssue} (command: ${trimmed}). reviewCommand runs through a shell; remove $, backticks, ;, |, || or lone & — && chains are allowed (#268).`,
85
+ );
86
+ }
87
+
88
+ const timeoutMs = options.timeoutMs ?? CONTRACT_REVIEW_TIMEOUT_DEFAULT_MS;
89
+ const maxBuffer = options.maxBuffer ?? CONTRACT_REVIEW_COMMAND_MAX_BUFFER;
90
+ const result = await runShellCommandAsync(worktreePath, trimmed, {
91
+ env: buildContractTestEnv(),
92
+ timeoutMs,
93
+ maxBuffer,
94
+ });
95
+
96
+ const output = `${String(result.stdout ?? "")}\n${String(result.stderr ?? "")}`;
97
+
98
+ if (result.timedOut) {
99
+ return {
100
+ ok: false,
101
+ exitCode: Number(result.exitCode ?? 1),
102
+ output,
103
+ timedOut: true,
104
+ summary: `reviewCommand timed out after ${formatReviewTimeoutLabel(timeoutMs)} and was terminated`,
105
+ };
106
+ }
107
+
108
+ if (result.truncated) {
109
+ return {
110
+ ok: false,
111
+ exitCode: Number(result.exitCode ?? 255),
112
+ output,
113
+ bufferOverflow: true,
114
+ summary: `reviewCommand output exceeded maxBuffer (${maxBuffer} bytes); use a scoped reviewCommand instead. Command: ${trimmed}`,
115
+ };
116
+ }
117
+
118
+ const exitCode = Number(result.exitCode ?? 1);
119
+ if (exitCode === 0) {
120
+ return { ok: true, exitCode: 0, output };
121
+ }
122
+
123
+ const detail = [
124
+ String(result.stdout ?? "").trim(),
125
+ String(result.stderr ?? "").trim(),
126
+ ]
127
+ .filter(Boolean)
128
+ .join("\n")
129
+ .slice(0, 500);
130
+ return {
131
+ ok: false,
132
+ exitCode,
133
+ output,
134
+ summary: `reviewCommand failed (exit ${exitCode})${detail ? `: ${detail}` : ""}`,
135
+ };
136
+ }
137
+
138
+ /**
139
+ * Resolve review step options from spine config (SP-845): the review timeout
140
+ * defaults to 20 minutes and is independent of `contract.testTimeoutMs`; the
141
+ * policy defaults to blocking.
142
+ *
143
+ * @param {{ contract?: { reviewTimeoutMs?: number, reviewPolicy?: string } }} [config]
144
+ * @returns {{ timeoutMs: number, policy: "blocking" | "advisory" }}
145
+ */
146
+ export function resolveContractReviewOptions(config = {}) {
147
+ return {
148
+ timeoutMs: config?.contract?.reviewTimeoutMs ?? CONTRACT_REVIEW_TIMEOUT_DEFAULT_MS,
149
+ policy:
150
+ config?.contract?.reviewPolicy === "advisory"
151
+ ? "advisory"
152
+ : CONTRACT_REVIEW_POLICY_DEFAULT,
153
+ };
154
+ }
155
+
156
+ /**
157
+ * Run the contract review step and build the `reviewCommand` check.
158
+ *
159
+ * @param {string} worktreePath
160
+ * @param {{ reviewCommand?: string | null }} parsedContract
161
+ * @param {{ contract?: { reviewTimeoutMs?: number, reviewPolicy?: string, testRetries?: number, testTimeoutMs?: number }, contractTestMaxBuffer?: number, projectRoot?: string, batchId?: string, taskId?: string, taskFolder?: string }} [config]
162
+ * verifyContract config — reads `contract.reviewTimeoutMs`,
163
+ * `contract.reviewPolicy`, `contractTestMaxBuffer`, plus projectRoot/batchId/
164
+ * taskId/taskFolder for advisory journaling.
165
+ * @returns {Promise<{ field: "reviewCommand", ok: boolean, message: string } | null>}
166
+ * null when the contract has no reviewCommand.
167
+ */
168
+ export async function runContractReviewStep(worktreePath, parsedContract, config = {}) {
169
+ const command = parsedContract?.reviewCommand;
170
+ if (!command) return null;
171
+
172
+ const { timeoutMs, policy } = resolveContractReviewOptions(config);
173
+ const result = await runContractReviewCommand(worktreePath, command, {
174
+ timeoutMs,
175
+ maxBuffer: config?.contractTestMaxBuffer,
176
+ });
177
+
178
+ if (result.ok) {
179
+ return { field: "reviewCommand", ok: true, message: "reviewCommand passed" };
180
+ }
181
+
182
+ const detail = result.summary ?? `reviewCommand failed (exit ${result.exitCode})`;
183
+ if (policy === "advisory") {
184
+ recordReviewAdvisory(config, {
185
+ exitCode: result.exitCode,
186
+ timedOut: result.timedOut === true,
187
+ summary: detail,
188
+ });
189
+ return {
190
+ field: "reviewCommand",
191
+ ok: true,
192
+ message: `Contract reviewCommand failed (advisory, not blocking): ${detail}`,
193
+ };
194
+ }
195
+
196
+ return { field: "reviewCommand", ok: false, message: `Contract reviewCommand failed: ${detail}` };
197
+ }
198
+
199
+ /**
200
+ * Advisory review failures never block, but they must stay visible: journal a
201
+ * `contract.review_advisory` event and append a row to the task STATUS.md
202
+ * Discoveries table.
203
+ *
204
+ * @param {{ contract?: { reviewTimeoutMs?: number, reviewPolicy?: string }, contractTestMaxBuffer?: number, projectRoot?: string, batchId?: string, taskId?: string, taskFolder?: string }} config
205
+ * @param {{ exitCode: number, timedOut: boolean, summary: string }} payload
206
+ */
207
+ function recordReviewAdvisory(config, payload) {
208
+ if (config?.projectRoot && config?.batchId) {
209
+ appendJournalEvent(config.projectRoot, config.batchId, "contract.review_advisory", {
210
+ taskId: config?.taskId,
211
+ exitCode: payload.exitCode,
212
+ timedOut: payload.timedOut,
213
+ summary: String(payload.summary ?? "").slice(0, 200),
214
+ });
215
+ }
216
+ appendReviewAdvisoryDiscovery(config?.taskFolder, payload.summary);
217
+ }
218
+
219
+ /**
220
+ * Append one row to the task STATUS.md Discoveries table (SP-845 advisory).
221
+ * Best-effort: skips silently when the task folder or Discoveries table is
222
+ * missing; never throws into contract verification.
223
+ *
224
+ * @param {string | undefined} taskFolder
225
+ * @param {string | undefined} summary
226
+ * @returns {boolean} true when a row was appended
227
+ */
228
+ export function appendReviewAdvisoryDiscovery(taskFolder, summary) {
229
+ if (!taskFolder) return false;
230
+ const statusPath = path.join(taskFolder, "STATUS.md");
231
+ let content;
232
+ try {
233
+ content = fs.readFileSync(statusPath, "utf-8");
234
+ } catch {
235
+ return false;
236
+ }
237
+ const lines = content.split("\n");
238
+ const headingIndex = lines.findIndex((line) => line.trim() === "## Discoveries");
239
+ if (headingIndex === -1) return false;
240
+
241
+ const cell = String(summary ?? "reviewCommand failed (advisory)")
242
+ .replace(/\|/g, "\\|")
243
+ .replace(/\r?\n/g, " ")
244
+ .slice(0, 160);
245
+ const row = `| ${cell} | advisory — noted, not blocking | contract review step |`;
246
+
247
+ // Insert after the Discoveries table's header separator so newest-first
248
+ // ordering matches the template; fall back to directly under the heading.
249
+ let insertAt = headingIndex + 1;
250
+ for (let index = headingIndex + 1; index < lines.length; index += 1) {
251
+ const line = lines[index];
252
+ if (line.startsWith("## ")) break;
253
+ if (/^\|[\s|-]+$/.test(line)) {
254
+ insertAt = index + 1;
255
+ break;
256
+ }
257
+ }
258
+
259
+ lines.splice(insertAt, 0, row);
260
+ try {
261
+ fs.writeFileSync(statusPath, lines.join("\n"), "utf-8");
262
+ } catch {
263
+ return false;
264
+ }
265
+ return true;
266
+ }
@@ -32,6 +32,37 @@ const DEFAULT_MAX_BUFFER = 10 * 1024 * 1024;
32
32
  /** Exit code reported when the shell itself cannot be spawned (ENOENT convention). */
33
33
  const SPAWN_ERROR_EXIT_CODE = 127;
34
34
 
35
+ /**
36
+ * Worker-only env keys stripped from contract command subprocesses so full-suite
37
+ * tests match operator re-run outside worker-host (SP-491, issue #155).
38
+ */
39
+ export const CONTRACT_TEST_WORKER_ENV_KEYS = ["SPINE_IS_WORKER"];
40
+
41
+ /**
42
+ * Build env for contract testCommand/reviewCommand subprocess — omits worker-only
43
+ * keys inherited from worker-host.mjs that would false-fail batch-spawn integration
44
+ * tests (SP-482 guard). Preserves parent batch id as SPINE_PARENT_BATCH_ID so the
45
+ * nested-spawn guard can block live engines in lane worktrees while still allowing
46
+ * isolated fixture tests (#162).
47
+ *
48
+ * Lives here (not in contract-exec.mjs) so the test and review runners (SP-845)
49
+ * share one implementation without an import cycle.
50
+ *
51
+ * @param {NodeJS.ProcessEnv} [sourceEnv]
52
+ * @returns {NodeJS.ProcessEnv}
53
+ */
54
+ export function buildContractTestEnv(sourceEnv = process.env) {
55
+ const env = { ...sourceEnv };
56
+ for (const key of CONTRACT_TEST_WORKER_ENV_KEYS) {
57
+ delete env[key];
58
+ }
59
+ if (env.SPINE_BATCH_ID && !env.SPINE_PARENT_BATCH_ID) {
60
+ env.SPINE_PARENT_BATCH_ID = env.SPINE_BATCH_ID;
61
+ }
62
+ delete env.SPINE_BATCH_ID;
63
+ return env;
64
+ }
65
+
35
66
  /**
36
67
  * Resolve the contract shell exactly like runContractTestCommand: $SHELL, else
37
68
  * cmd.exe on Windows and /bin/sh elsewhere, with the matching command flag.
@@ -306,17 +306,24 @@ export async function waitForDetachedBatchResume({
306
306
  continue;
307
307
  }
308
308
 
309
+ const updatedAt = Number(raw.updatedAt ?? 0);
310
+
309
311
  if (raw.phase === "failed" || raw.phase === "aborted") {
310
- return {
311
- ok: false,
312
- error: "batch_engine_failed",
313
- batchId,
314
- phase: raw.phase,
315
- lastError: raw.lastError ?? null,
316
- };
312
+ // SP-851: only a failure written after the resume started
313
+ // (updatedAt > updatedAtBefore) is an engine failure. A pre-resume
314
+ // terminal state (e.g. resuming an already-failed batch) keeps polling
315
+ // until the new engine writes `running` or the wait times out.
316
+ if (updatedAt > updatedAtBefore) {
317
+ return {
318
+ ok: false,
319
+ error: "batch_engine_failed",
320
+ batchId,
321
+ phase: raw.phase,
322
+ lastError: raw.lastError ?? null,
323
+ };
324
+ }
317
325
  }
318
326
 
319
- const updatedAt = Number(raw.updatedAt ?? 0);
320
327
  if (raw.phase === "running" && updatedAt > updatedAtBefore) {
321
328
  engineStarted = true;
322
329
  if (!waitTerminal) {
@@ -17,13 +17,21 @@ const LANE_COMMIT_EXIT_REASONS = new Set(["DirtyWorktree", "lane_commit_failed"]
17
17
  /** Suggested `contract.testTimeoutMs` after a timeout: double the 10-minute default. */
18
18
  const CONTRACT_TIMEOUT_SUGGESTED_MS = 20 * 60 * 1000;
19
19
 
20
+ /** Suggested `contract.reviewTimeoutMs` after a review timeout: double the 20-minute default (SP-845). */
21
+ const CONTRACT_REVIEW_TIMEOUT_SUGGESTED_MS = 40 * 60 * 1000;
22
+
20
23
  /**
21
24
  * True when the latest contract verification for `taskId` failed because its
22
25
  * testCommand timed out (#369), so diagnosis can name the timeout instead of
23
26
  * pointing at PROMPT.md scope.
24
27
  *
28
+ * SP-845: a `reviewCommand` timeout is distinguished from a test timeout —
29
+ * returns `"review"` for review timeouts (truthy, so `contractTimedOut`
30
+ * consumers keep working while builders can name `contract.reviewTimeoutMs`).
31
+ *
25
32
  * @param {Array<{ type?: string, payload?: Record<string, any> }>} journalEvents
26
33
  * @param {string|null|undefined} taskId
34
+ * @returns {boolean | "review"}
27
35
  */
28
36
  export function isContractTimeoutFailure(journalEvents, taskId) {
29
37
  if (!taskId || !Array.isArray(journalEvents)) return false;
@@ -32,6 +40,13 @@ export function isContractTimeoutFailure(journalEvents, taskId) {
32
40
  if (event?.type !== "contract.verified" && event?.type !== "contract.failed") continue;
33
41
  if (event.payload?.taskId !== taskId) continue;
34
42
  const checks = Array.isArray(event.payload?.checks) ? event.payload.checks : [];
43
+ if (
44
+ checks.some(
45
+ (check) => check?.field === "reviewCommand" && check.ok === false && /timed out after/.test(String(check.message ?? "")),
46
+ )
47
+ ) {
48
+ return "review";
49
+ }
35
50
  return checks.some(
36
51
  (check) => check?.field === "testCommand" && check.ok === false && /timed out after/.test(String(check.message ?? "")),
37
52
  );
@@ -52,7 +67,7 @@ export function isPrimaryTaskFailureExitReason(exitReason) {
52
67
  * @param {string|null} [ctx.exitReason]
53
68
  * @param {string|null} [ctx.failedTaskId]
54
69
  * @param {boolean} [ctx.mergeGitignoredFailure]
55
- * @param {boolean} [ctx.contractTimedOut]
70
+ * @param {boolean | "review"} [ctx.contractTimedOut] SP-845: "review" marks a reviewCommand timeout.
56
71
  */
57
72
  export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
58
73
  if (LANE_COMMIT_EXIT_REASONS.has(ctx.exitReason ?? "")) {
@@ -76,8 +91,11 @@ export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
76
91
  : `${batchLabel} review attempts exhausted — fix scope or implementation, then retry`;
77
92
  }
78
93
  if (ctx.exitReason === "contract_failed" && ctx.contractTimedOut) {
79
- const subject = ctx.failedTaskId ? `task ${ctx.failedTaskId} contract testCommand` : "contract testCommand";
80
- return `${batchLabel} ${subject} timed out — raise contract.testTimeoutMs or speed up the command, then retry`;
94
+ const isReviewTimeout = ctx.contractTimedOut === "review";
95
+ const field = isReviewTimeout ? "reviewCommand" : "testCommand";
96
+ const key = isReviewTimeout ? "contract.reviewTimeoutMs" : "contract.testTimeoutMs";
97
+ const subject = ctx.failedTaskId ? `task ${ctx.failedTaskId} contract ${field}` : `contract ${field}`;
98
+ return `${batchLabel} ${subject} timed out — raise ${key} or speed up the command, then retry`;
81
99
  }
82
100
  if (ctx.exitReason === "contract_failed") {
83
101
  return ctx.failedTaskId
@@ -125,7 +143,7 @@ export function buildDirtyWorktreeSuggestedCommand(ctx = {}) {
125
143
  * @param {string|null} [ctx.exitReason]
126
144
  * @param {string|null} [ctx.failedTaskId]
127
145
  * @param {string} [ctx.tasksRoot]
128
- * @param {boolean} [ctx.contractTimedOut]
146
+ * @param {boolean | "review"} [ctx.contractTimedOut] SP-845: "review" marks a reviewCommand timeout.
129
147
  */
130
148
  export function buildPrimaryFailureSuggestedCommand(ctx = {}) {
131
149
  if (LANE_COMMIT_EXIT_REASONS.has(ctx.exitReason ?? "")) {
@@ -143,7 +161,12 @@ export function buildPrimaryFailureSuggestedCommand(ctx = {}) {
143
161
  }
144
162
  if (ctx.exitReason === "contract_failed" && ctx.contractTimedOut) {
145
163
  const retry = ctx.failedTaskId ? `spine batch retry ${ctx.failedTaskId}` : "spine batch resume";
146
- return `spine settings set contract.testTimeoutMs ${CONTRACT_TIMEOUT_SUGGESTED_MS} && ${retry}`;
164
+ const suggested =
165
+ ctx.contractTimedOut === "review"
166
+ ? CONTRACT_REVIEW_TIMEOUT_SUGGESTED_MS
167
+ : CONTRACT_TIMEOUT_SUGGESTED_MS;
168
+ const key = ctx.contractTimedOut === "review" ? "contract.reviewTimeoutMs" : "contract.testTimeoutMs";
169
+ return `spine settings set ${key} ${suggested} && ${retry}`;
147
170
  }
148
171
  if (ctx.exitReason === "contract_failed") {
149
172
  const tasksRoot = ctx.tasksRoot ?? "spine-tasks";
@@ -61,6 +61,13 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
61
61
  case "completed_manual":
62
62
  return "spine batch dismiss";
63
63
  case "state_drift":
64
+ // SP-850 / #356, #371: the engine is verifiably alive and the phase is
65
+ // running — the drift window is the in-flight post-`.DONE`
66
+ // review/contract pipeline. Wait for it instead of force-resuming over
67
+ // live work.
68
+ if (ctx.phase === "running" && ctx.engineStillRunning === true) {
69
+ return "spine wait --until completed,failed,needs_integrate --timeout 2h";
70
+ }
64
71
  // Agent-safe detached recovery (#196 / SP-613) — never suggest --attached.
65
72
  if (
66
73
  ctx.phase === "running" ||
@@ -9,6 +9,7 @@ import {
9
9
  sanitizeGitignoredArtifactsBeforeLaneCommit,
10
10
  sanitizeOutOfScopeCoverageBeforeLaneCommit,
11
11
  } from "../lane-dirty-check.mjs";
12
+ import { resolveLaneCommitKeepPaths } from "../../config/spine-config-schema.mjs";
12
13
  import {
13
14
  recomputeTaskCounters,
14
15
  saveSpineBatchState,
@@ -54,10 +55,12 @@ export function commitLaneAndValidateWorktree({
54
55
  config,
55
56
  }) {
56
57
  const preCommitPorcelain = gitPorcelain(worktreePath);
58
+ const keepPaths = resolveLaneCommitKeepPaths({ config });
57
59
  sanitizeGitignoredArtifactsBeforeLaneCommit(worktreePath, {
58
60
  projectRoot,
59
61
  porcelain: preCommitPorcelain,
60
62
  enabled: config?.lanes?.autoCleanGitignoredArtifacts !== false,
63
+ keepPaths,
61
64
  });
62
65
  sanitizeOutOfScopeCoverageBeforeLaneCommit(worktreePath, fileScopePaths, {
63
66
  projectRoot,
@@ -79,6 +82,7 @@ export function commitLaneAndValidateWorktree({
79
82
  ignorePatterns,
80
83
  fileScopePaths,
81
84
  canceledMatrixRowIds,
85
+ keepPaths,
82
86
  });
83
87
  if (!laneCommit.ok) {
84
88
  task.status = "failed";