pi-spine 2.28.1 → 2.29.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.28.1",
3
+ "version": "2.29.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -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.
@@ -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";
@@ -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";
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Lane-commit keep paths (SP-844 / #349): gitignored artifact roots that hold
3
+ * active tool state — stet sessions, baseline refs — which the lane-commit
4
+ * sanitizer must preserve across lane commits serialized on one worktree.
5
+ */
6
+
7
+ /**
8
+ * Normalize a keep path for root comparison: backslashes → slashes, no
9
+ * leading "./", no trailing slash.
10
+ *
11
+ * @param {string} keepPath
12
+ * @returns {string}
13
+ */
14
+ export function normalizeKeepPath(keepPath) {
15
+ let normalized = String(keepPath).trim().replace(/\\/g, "/");
16
+ while (normalized.startsWith("./")) normalized = normalized.slice(2);
17
+ while (normalized.endsWith("/")) {
18
+ normalized = normalized.slice(0, -1);
19
+ }
20
+ return normalized;
21
+ }
22
+
23
+ /**
24
+ * Whether a cleaned artifact root is covered by a keep path. `.review/` keeps
25
+ * the artifact root `.review` and every root under it.
26
+ *
27
+ * @param {string} artifactRoot
28
+ * @param {string[]} keepPaths
29
+ * @returns {boolean}
30
+ */
31
+ export function isKeptArtifactRoot(artifactRoot, keepPaths) {
32
+ if (!artifactRoot || !Array.isArray(keepPaths) || keepPaths.length === 0) {
33
+ return false;
34
+ }
35
+ const root = normalizeKeepPath(artifactRoot);
36
+ if (root === "") return false;
37
+ return keepPaths.some((keepPath) => {
38
+ const kept = normalizeKeepPath(keepPath);
39
+ return kept !== "" && (root === kept || root.startsWith(`${kept}/`));
40
+ });
41
+ }
42
+
43
+ /**
44
+ * Split artifact roots into roots the sanitizer may clean and roots that must
45
+ * survive the lane commit.
46
+ *
47
+ * @param {string[]} artifactRoots
48
+ * @param {string[]} [keepPaths]
49
+ * @returns {{ cleanableRoots: string[], keptRoots: string[] }}
50
+ */
51
+ export function partitionArtifactRootsByKeepPaths(artifactRoots, keepPaths = []) {
52
+ const cleanableRoots = [];
53
+ const keptRoots = [];
54
+ for (const root of Array.isArray(artifactRoots) ? artifactRoots : []) {
55
+ if (isKeptArtifactRoot(root, keepPaths)) {
56
+ keptRoots.push(root);
57
+ } else {
58
+ cleanableRoots.push(root);
59
+ }
60
+ }
61
+ return { cleanableRoots, keptRoots };
62
+ }
63
+
64
+ /**
65
+ * Whether a gitignored path sits under a kept root — kept paths are
66
+ * operator-blessed tool state, not cleanable artifacts, so the lane-commit
67
+ * dirty gate must not count them (SP-844 / #349).
68
+ *
69
+ * @param {string} filePath
70
+ * @param {string[]} keepPaths
71
+ * @returns {boolean}
72
+ */
73
+ export function isPathUnderKeptRoot(filePath, keepPaths) {
74
+ return isKeptArtifactRoot(filePath, keepPaths);
75
+ }
@@ -7,6 +7,9 @@ import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
9
  import { filterGitignoredPaths, gitAddFilteredPaths } from "./git-helpers.mjs";
10
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
11
+ import { resolveLaneCommitKeepPaths } from "../config/spine-config-schema.mjs";
12
+ import { isPathUnderKeptRoot } from "./lane-commit-keep-paths.mjs";
10
13
  import {
11
14
  classifyGitignoredPaths,
12
15
  formatGitignoredRemediationMessage,
@@ -231,6 +234,7 @@ function listPorcelainPaths(porcelain) {
231
234
  * @param {string[]} [params.ignorePatterns] Hook paths to skip (default includes `.venv`)
232
235
  * @param {string[]} [params.fileScopePaths] Task fileScope — paths here are never skipped
233
236
  * @param {string[]} [params.canceledMatrixRowIds] Row ids canceled by the operator (#230) — their expanded fileScope patterns are excluded
237
+ * @param {string[]} [params.keepPaths] Gitignored roots to preserve (default `lanes.laneCommitKeepPaths`, `.review/`)
234
238
  * @returns {{ ok: true, committed: boolean, commitSha?: string, skippedGitignoredPaths?: string[], skippedIgnorePaths?: string[] } | { ok: false, error: string, failureClass: string, gitignoredPaths?: string[] }}
235
239
  */
236
240
  export function commitLaneWorktree({
@@ -244,11 +248,15 @@ export function commitLaneWorktree({
244
248
  ignorePatterns,
245
249
  fileScopePaths = [],
246
250
  canceledMatrixRowIds = [],
251
+ keepPaths,
247
252
  }) {
248
253
  const identityRoot = projectRoot ?? worktreePath;
249
254
  const effectiveIgnorePatterns = Array.isArray(ignorePatterns)
250
255
  ? ignorePatterns
251
256
  : [...DEFAULT_WORKTREE_SETUP_IGNORE_PATHS];
257
+ const effectiveKeepPaths = Array.isArray(keepPaths)
258
+ ? keepPaths
259
+ : resolveLaneCommitKeepPaths({ config: loadSpineConfig(identityRoot).config ?? {} });
252
260
  try {
253
261
  const porcelain = gitPorcelain(worktreePath);
254
262
  const dirtyPaths = listPorcelainPaths(porcelain);
@@ -258,7 +266,9 @@ export function commitLaneWorktree({
258
266
  const stageCandidatePaths = dirtyPaths.filter(
259
267
  (filePath) => !shouldSkipHookIgnorePath(filePath, effectiveIgnorePatterns, fileScopePaths),
260
268
  );
261
- const ignoredUntrackedPaths = listIgnoredUntrackedPaths(worktreePath);
269
+ const ignoredUntrackedPaths = listIgnoredUntrackedPaths(worktreePath).filter(
270
+ (filePath) => !isPathUnderKeptRoot(filePath, effectiveKeepPaths),
271
+ );
262
272
  // Only-hook-noise dirty (e.g. untracked `.venv` symlink) is not a DirtyWorktree failure.
263
273
  if (stageCandidatePaths.length === 0 && ignoredUntrackedPaths.length === 0) {
264
274
  return {
@@ -333,7 +343,9 @@ export function commitLaneWorktree({
333
343
  worktreePath,
334
344
  stageCandidatePaths,
335
345
  );
336
- let gitignoredPaths = [...new Set([...gitignoredDirtyPaths, ...ignoredUntrackedPaths])];
346
+ let gitignoredPaths = [...new Set([...gitignoredDirtyPaths, ...ignoredUntrackedPaths])].filter(
347
+ (filePath) => !isPathUnderKeptRoot(filePath, effectiveKeepPaths),
348
+ );
337
349
  if (stageable.length === 0 && gitignoredPaths.length > 0) {
338
350
  let { indexTracked, worktreeOnly } = classifyGitignoredPaths(worktreePath, gitignoredPaths);
339
351
  // SP-659 / #206: marked artifacts may regenerate after the pre-commit sanitize.
@@ -345,8 +357,11 @@ export function commitLaneWorktree({
345
357
  if (worktreeOnlyMarkedArtifacts) {
346
358
  sanitizeGitignoredArtifactsBeforeLaneCommit(worktreePath, {
347
359
  projectRoot: identityRoot,
360
+ keepPaths: effectiveKeepPaths,
348
361
  });
349
- gitignoredPaths = listIgnoredUntrackedPaths(worktreePath);
362
+ gitignoredPaths = listIgnoredUntrackedPaths(worktreePath).filter(
363
+ (filePath) => !isPathUnderKeptRoot(filePath, effectiveKeepPaths),
364
+ );
350
365
  if (gitignoredPaths.length === 0) {
351
366
  return {
352
367
  ok: true,
@@ -393,6 +408,7 @@ export function commitLaneWorktree({
393
408
  // SP-659 / #206: post-commit hooks may regenerate marked gitignored artifacts.
394
409
  sanitizeGitignoredArtifactsBeforeLaneCommit(worktreePath, {
395
410
  projectRoot: identityRoot,
411
+ keepPaths: effectiveKeepPaths,
396
412
  });
397
413
  return {
398
414
  ok: true,
@@ -9,7 +9,9 @@ import { execFileSync } from "node:child_process";
9
9
  import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
12
+ import { resolveLaneCommitKeepPaths } from "../config/spine-config-schema.mjs";
12
13
  import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
14
+ import { partitionArtifactRootsByKeepPaths } from "./lane-commit-keep-paths.mjs";
13
15
  import { gitPorcelain } from "./lane-commit.mjs";
14
16
  import { gitExec } from "./git-exec.mjs";
15
17
 
@@ -319,16 +321,17 @@ function listIgnoredUntrackedPaths(worktreePath) {
319
321
 
320
322
  /**
321
323
  * Auto-clean worktree-only gitignored artifacts under known dirs before lane dirty gate.
324
+ * Roots covered by keep paths (`lanes.laneCommitKeepPaths`, default `.review/`) survive — active tool state, not artifacts (SP-844 / #349).
322
325
  *
323
326
  * @param {string} worktreePath
324
- * @param {{ projectRoot?: string, porcelain?: string, enabled?: boolean }} [options]
325
- * @returns {{ cleanedRoots: string[] }}
327
+ * @param {{ projectRoot?: string, porcelain?: string, enabled?: boolean, keepPaths?: string[] }} [options]
328
+ * @returns {{ cleanedRoots: string[], keptRoots: string[] }}
326
329
  */
327
330
  export function sanitizeGitignoredArtifactsBeforeLaneCommit(
328
331
  worktreePath,
329
- { projectRoot, porcelain, enabled = true } = {},
332
+ { projectRoot, porcelain, enabled = true, keepPaths } = {},
330
333
  ) {
331
- if (!enabled) return { cleanedRoots: [] };
334
+ if (!enabled) return { cleanedRoots: [], keptRoots: [] };
332
335
 
333
336
  const identityRoot = projectRoot ?? worktreePath;
334
337
  const rawPorcelain = typeof porcelain === "string" ? porcelain : "";
@@ -336,19 +339,26 @@ export function sanitizeGitignoredArtifactsBeforeLaneCommit(
336
339
  const ignoredUntrackedPaths = listIgnoredUntrackedPaths(worktreePath);
337
340
  const gitignoredCandidates = [...new Set([...dirtyPaths, ...ignoredUntrackedPaths])];
338
341
  if (gitignoredCandidates.length === 0) {
339
- return { cleanedRoots: [] };
342
+ return { cleanedRoots: [], keptRoots: [] };
340
343
  }
341
344
 
342
345
  const { worktreeOnly } = classifyGitignoredPaths(worktreePath, gitignoredCandidates);
343
346
  const artifactRoots = listGitignoredArtifactRoots(worktreeOnly);
344
- for (const root of artifactRoots) {
347
+ const effectiveKeepPaths = Array.isArray(keepPaths)
348
+ ? keepPaths
349
+ : resolveLaneCommitKeepPaths({ config: loadSpineConfig(identityRoot).config ?? {} });
350
+ const { cleanableRoots, keptRoots } = partitionArtifactRootsByKeepPaths(
351
+ artifactRoots,
352
+ effectiveKeepPaths,
353
+ );
354
+ for (const root of cleanableRoots) {
345
355
  gitExec(worktreePath, ["clean", "-fdX", "--", root], {
346
356
  projectRoot: identityRoot,
347
357
  throwOnError: false,
348
358
  });
349
359
  }
350
360
 
351
- return { cleanedRoots: artifactRoots };
361
+ return { cleanedRoots: cleanableRoots, keptRoots };
352
362
  }
353
363
 
354
364
  export function classifyGitignoredPaths(worktreePath, gitignoredPaths) {
@@ -10,6 +10,17 @@ export const CONTRACT_MODES = Object.freeze(["required", "optional", "legacy"]);
10
10
  export const CONTRACT_TEST_TIMEOUT_MIN_MS = 1000;
11
11
  export const CONTRACT_TEST_TIMEOUT_MAX_MS = 4 * 60 * 60 * 1000;
12
12
 
13
+ /**
14
+ * Bounds for `contract.reviewTimeoutMs` (SP-845): same envelope as the test
15
+ * timeout, but a 20-minute default because review runs once with no retries.
16
+ */
17
+ export const CONTRACT_REVIEW_TIMEOUT_MIN_MS = CONTRACT_TEST_TIMEOUT_MIN_MS;
18
+ export const CONTRACT_REVIEW_TIMEOUT_MAX_MS = CONTRACT_TEST_TIMEOUT_MAX_MS;
19
+ export const CONTRACT_REVIEW_TIMEOUT_DEFAULT_MS = 20 * 60 * 1000;
20
+
21
+ /** Policies for `contract.reviewPolicy` (SP-845). */
22
+ export const CONTRACT_REVIEW_POLICIES = Object.freeze(["blocking", "advisory"]);
23
+
13
24
  /**
14
25
  * @param {unknown} config
15
26
  * @returns {{ code: string, message: string, suggestedCommand: string } | null}
@@ -64,6 +75,35 @@ export function validateContractConfig(config) {
64
75
  }
65
76
  }
66
77
 
78
+ if (contract.reviewTimeoutMs != null) {
79
+ const reviewTimeoutMs = contract.reviewTimeoutMs;
80
+ const isValidReviewTimeout =
81
+ typeof reviewTimeoutMs === "number" &&
82
+ Number.isInteger(reviewTimeoutMs) &&
83
+ reviewTimeoutMs >= CONTRACT_REVIEW_TIMEOUT_MIN_MS &&
84
+ reviewTimeoutMs <= CONTRACT_REVIEW_TIMEOUT_MAX_MS;
85
+ if (!isValidReviewTimeout) {
86
+ return {
87
+ code: "CONFIG_CONTRACT_REVIEW_TIMEOUT_INVALID",
88
+ message: `contract.reviewTimeoutMs must be an integer between ${CONTRACT_REVIEW_TIMEOUT_MIN_MS} and ${CONTRACT_REVIEW_TIMEOUT_MAX_MS} when set`,
89
+ suggestedCommand: "spine settings set contract.reviewTimeoutMs 1200000",
90
+ };
91
+ }
92
+ }
93
+
94
+ if (contract.reviewPolicy != null) {
95
+ if (
96
+ typeof contract.reviewPolicy !== "string" ||
97
+ !CONTRACT_REVIEW_POLICIES.includes(contract.reviewPolicy)
98
+ ) {
99
+ return {
100
+ code: "CONFIG_CONTRACT_REVIEW_POLICY_INVALID",
101
+ message: `contract.reviewPolicy must be one of: ${CONTRACT_REVIEW_POLICIES.join(", ")}`,
102
+ suggestedCommand: "spine settings set contract.reviewPolicy blocking",
103
+ };
104
+ }
105
+ }
106
+
67
107
  if (contract.legacyTaskIdPrefixes != null) {
68
108
  if (!Array.isArray(contract.legacyTaskIdPrefixes)) {
69
109
  return {
@@ -10,7 +10,7 @@
10
10
 
11
11
  import { CONTRACT_TEST_TIMEOUT_MAX_MS, CONTRACT_TEST_TIMEOUT_MIN_MS } from "./contract.mjs";
12
12
 
13
- /** @typedef {"boolean" | "number" | "string" | "enum"} SettingFieldType */
13
+ /** @typedef {"boolean" | "number" | "string" | "enum" | "stringList"} SettingFieldType */
14
14
 
15
15
  /**
16
16
  * @typedef {object} SettingField
@@ -45,6 +45,11 @@ export const SETTINGS_FIELDS = Object.freeze([
45
45
  label: "Auto integrate between waves",
46
46
  type: "boolean",
47
47
  },
48
+ {
49
+ path: "lanes.laneCommitKeepPaths",
50
+ label: "Lane commit keep paths (comma-separated gitignored roots the sanitizer preserves, e.g. .review/)",
51
+ type: "stringList",
52
+ },
48
53
  {
49
54
  path: "gates.requireBeforeIntegrate",
50
55
  label: "Require gate before integrate",
@@ -71,6 +76,19 @@ export const SETTINGS_FIELDS = Object.freeze([
71
76
  min: CONTRACT_TEST_TIMEOUT_MIN_MS,
72
77
  max: CONTRACT_TEST_TIMEOUT_MAX_MS,
73
78
  },
79
+ {
80
+ path: "contract.reviewTimeoutMs",
81
+ label: "Contract reviewCommand timeout (ms; default 1200000)",
82
+ type: "number",
83
+ min: CONTRACT_TEST_TIMEOUT_MIN_MS,
84
+ max: CONTRACT_TEST_TIMEOUT_MAX_MS,
85
+ },
86
+ {
87
+ path: "contract.reviewPolicy",
88
+ label: "Contract reviewCommand policy (blocking fails the contract, advisory only records)",
89
+ type: "enum",
90
+ enum: ["blocking", "advisory"],
91
+ },
74
92
  {
75
93
  path: "agents.worker.model",
76
94
  label: "Worker model",
@@ -245,6 +263,8 @@ function validateForField(field, rawValue) {
245
263
  return validateString(rawValue, field);
246
264
  case "enum":
247
265
  return validateEnum(rawValue, field);
266
+ case "stringList":
267
+ return validateStringList(rawValue);
248
268
  default:
249
269
  return { ok: false, error: `Unsupported field type: ${field.type}` };
250
270
  }
@@ -285,6 +305,35 @@ function validateNumber(rawValue, field) {
285
305
  return { ok: true, normalizedValue: coerced };
286
306
  }
287
307
 
308
+ /**
309
+ * Comma-separated path list. Accepts a raw string from the settings CLI / slash
310
+ * command or an already-split array; normalizes to a string array so the
311
+ * written spine-config.json value matches `resolveLaneCommitKeepPaths`.
312
+ *
313
+ * @param {unknown} rawValue
314
+ */
315
+ function validateStringList(rawValue) {
316
+ if (rawValue == null) {
317
+ return { ok: true, normalizedValue: [] };
318
+ }
319
+ if (Array.isArray(rawValue)) {
320
+ for (const entry of rawValue) {
321
+ if (typeof entry !== "string" || entry.trim() === "") {
322
+ return { ok: false, error: "List entries must be non-empty strings" };
323
+ }
324
+ }
325
+ return { ok: true, normalizedValue: rawValue.map((entry) => entry.trim()) };
326
+ }
327
+ if (typeof rawValue !== "string" && typeof rawValue !== "number") {
328
+ return { ok: false, error: "Expected a comma-separated string" };
329
+ }
330
+ const parts = String(rawValue)
331
+ .split(",")
332
+ .map((part) => part.trim())
333
+ .filter((part) => part !== "");
334
+ return { ok: true, normalizedValue: parts };
335
+ }
336
+
288
337
  /**
289
338
  * @param {unknown} rawValue
290
339
  * @param {SettingField} field
@@ -33,6 +33,38 @@ export const ORCHESTRATOR_DEFAULTS = Object.freeze({
33
33
  sequenceStallMs: DEFAULT_SEQUENCE_STALL_MS,
34
34
  });
35
35
 
36
+ /**
37
+ * Gitignored artifact roots the lane-commit sanitizer must not `git clean`.
38
+ * `.review/` holds the stet session the worktreeSetupHook opened for the whole
39
+ * lane; cleaning it breaks the next task's stet-gated contract (SP-844 / #349).
40
+ *
41
+ * @type {Readonly<string[]>}
42
+ */
43
+ export const DEFAULT_LANE_COMMIT_KEEP_PATHS = Object.freeze([".review/"]);
44
+
45
+ /**
46
+ * Resolve `lanes.laneCommitKeepPaths`. An explicit array replaces the default;
47
+ * anything else (unset, wrong type) falls back to it. Entries are trimmed;
48
+ * empty entries are dropped, so `[""]` degrades to "no keeps".
49
+ *
50
+ * @param {{ config?: Record<string, any> }} [options]
51
+ * @returns {string[]}
52
+ */
53
+ export function resolveLaneCommitKeepPaths({ config = {} } = {}) {
54
+ const raw = config?.lanes?.laneCommitKeepPaths;
55
+ if (!Array.isArray(raw)) {
56
+ return [...DEFAULT_LANE_COMMIT_KEEP_PATHS];
57
+ }
58
+ const paths = [];
59
+ for (const entry of raw) {
60
+ if (typeof entry !== "string") continue;
61
+ const trimmed = entry.trim();
62
+ if (trimmed === "") continue;
63
+ paths.push(trimmed);
64
+ }
65
+ return paths;
66
+ }
67
+
36
68
  /**
37
69
  * @param {unknown} value
38
70
  * @param {string} fieldLabel
@@ -24,6 +24,7 @@ const STEP_HEADING_RE = /^### Step (\d+): (.+)$/gm;
24
24
  export const CONTRACT_FIELD_NAMES = Object.freeze([
25
25
  "testCommand",
26
26
  "runCommand",
27
+ "reviewCommand",
27
28
  "fileScopeMustChange",
28
29
  "fileScopeMustNotChange",
29
30
  "minLineCoverage",
@@ -328,6 +329,7 @@ function collectDuplicateStepNumberErrors(steps) {
328
329
  * @returns {{
329
330
  * testCommand: string | null,
330
331
  * runCommand: string | null,
332
+ * reviewCommand: string | null,
331
333
  * fileScopeMustChange: string[],
332
334
  * fileScopeMustNotChange: string[],
333
335
  * minLineCoverage: number | null,
@@ -352,6 +354,7 @@ export function parseContract(markdown) {
352
354
  const parsed = {
353
355
  testCommand: null,
354
356
  runCommand: null,
357
+ reviewCommand: null,
355
358
  fileScopeMustChange: [],
356
359
  fileScopeMustNotChange: [],
357
360
  minLineCoverage: null,
@@ -469,44 +472,26 @@ function applyContractField(parsed, field, rawValue) {
469
472
  }
470
473
 
471
474
  switch (field) {
472
- case "testCommand": {
475
+ case "testCommand":
476
+ case "runCommand":
477
+ case "reviewCommand": {
473
478
  const command = parseContractScalar(value);
474
479
  if (command.includes("\n")) {
475
- parsed.errors.push("Contract testCommand must not contain newlines");
480
+ parsed.errors.push(`Contract ${field} must not contain newlines`);
476
481
  return;
477
482
  }
478
483
  if (command.length > TEST_COMMAND_MAX_LENGTH) {
479
- parsed.errors.push(`Contract testCommand exceeds ${TEST_COMMAND_MAX_LENGTH} characters`);
484
+ parsed.errors.push(`Contract ${field} exceeds ${TEST_COMMAND_MAX_LENGTH} characters`);
480
485
  return;
481
486
  }
482
- const testCommandIssue = findContractCommandMetacharIssue(command);
483
- if (testCommandIssue) {
487
+ const commandMetacharIssue = findContractCommandMetacharIssue(command);
488
+ if (commandMetacharIssue) {
484
489
  parsed.errors.push(
485
- `Contract testCommand contains forbidden shell metacharacters: ${testCommandIssue}; ${CONTRACT_METACHAR_FIX_HINT}`,
490
+ `Contract ${field} contains forbidden shell metacharacters: ${commandMetacharIssue}; ${CONTRACT_METACHAR_FIX_HINT}`,
486
491
  );
487
492
  return;
488
493
  }
489
- parsed.testCommand = command;
490
- return;
491
- }
492
- case "runCommand": {
493
- const command = parseContractScalar(value);
494
- if (command.includes("\n")) {
495
- parsed.errors.push("Contract runCommand must not contain newlines");
496
- return;
497
- }
498
- if (command.length > TEST_COMMAND_MAX_LENGTH) {
499
- parsed.errors.push(`Contract runCommand exceeds ${TEST_COMMAND_MAX_LENGTH} characters`);
500
- return;
501
- }
502
- const runCommandIssue = findContractCommandMetacharIssue(command);
503
- if (runCommandIssue) {
504
- parsed.errors.push(
505
- `Contract runCommand contains forbidden shell metacharacters: ${runCommandIssue}; ${CONTRACT_METACHAR_FIX_HINT}`,
506
- );
507
- return;
508
- }
509
- parsed.runCommand = command;
494
+ parsed[field] = command;
510
495
  return;
511
496
  }
512
497
  case "fileScopeMustChange":
@@ -215,6 +215,8 @@ function patternBlocksCurrentTaskFolder(pattern, taskId, tasksRoot) {
215
215
  function isContractTableEmpty(parsed) {
216
216
  return (
217
217
  parsed.testCommand === null &&
218
+ parsed.runCommand === null &&
219
+ parsed.reviewCommand === null &&
218
220
  parsed.fileScopeMustChange.length === 0 &&
219
221
  parsed.fileScopeMustNotChange.length === 0 &&
220
222
  parsed.minLineCoverage === null &&
@@ -1,366 +0,0 @@
1
- // @ts-nocheck
2
- /**
3
- * Lane-commit dirty hygiene: coverage restore/clean, gitignored artifact
4
- * sanitization, and post-lane-commit porcelain resolution (SP-601 / #117).
5
- */
6
-
7
- import { execFileSync } from "node:child_process";
8
- import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
- import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
10
- import { gitPorcelain } from "./lane-commit.mjs";
11
- import { gitExec } from "./git-exec.mjs";
12
- import {
13
- extractPorcelainPath,
14
- filterOutOfScopeCoveragePorcelain,
15
- isSymlinkOnlyDriftPorcelain,
16
- listOutOfScopeCoveragePaths,
17
- listOutOfScopeCoverageRoots,
18
- listPorcelainPaths,
19
- listTrackedPorcelainPaths,
20
- repairSetupHookSymlinkDrift,
21
- } from "./lane-dirty-check-git.mjs";
22
-
23
- /**
24
- * Path segments for gitignored build artifacts that npm test and similar tools
25
- * regenerate in lane worktrees (SP-471 / #95).
26
- */
27
- export const GITIGNORED_ARTIFACT_MARKERS = [
28
- "/node_modules/",
29
- "node_modules/",
30
- "/coverage/",
31
- "coverage/",
32
- "/__pycache__/",
33
- "__pycache__/",
34
- "/graphify-out/",
35
- "graphify-out/",
36
- "/.review/",
37
- ".review/",
38
- "/.pi-smart-router/",
39
- ".pi-smart-router/",
40
- "/.spine/runtime/",
41
- ".spine/runtime/",
42
- ];
43
-
44
- /**
45
- * Restore tracked and remove untracked out-of-scope coverage before lane commit.
46
- *
47
- * @param {string} worktreePath
48
- * @param {string[]} [fileScopePaths]
49
- * @param {{ projectRoot?: string, porcelain?: string }} [options]
50
- * @returns {{ restored: string[], cleanedRoots: string[] }}
51
- */
52
- export function sanitizeOutOfScopeCoverageBeforeLaneCommit(
53
- worktreePath,
54
- fileScopePaths,
55
- { projectRoot, porcelain } = {},
56
- ) {
57
- const identityRoot = projectRoot ?? worktreePath;
58
- const rawPorcelain = porcelain ?? "";
59
- const dirtyPaths = listPorcelainPaths(rawPorcelain);
60
- const { restored } = restoreOutOfScopeCoverageArtifacts(worktreePath, fileScopePaths, {
61
- projectRoot: identityRoot,
62
- dirtyPaths,
63
- porcelain: rawPorcelain,
64
- });
65
-
66
- const cleanedRoots = listOutOfScopeCoverageRoots(dirtyPaths, fileScopePaths);
67
- for (const root of cleanedRoots) {
68
- gitExec(worktreePath, ["clean", "-fd", "--", root], {
69
- projectRoot: identityRoot,
70
- throwOnError: false,
71
- });
72
- }
73
-
74
- return { restored, cleanedRoots };
75
- }
76
-
77
- /**
78
- * Restore tracked coverage artifacts that are outside task file scope.
79
- *
80
- * @param {string} worktreePath
81
- * @param {string[]} [fileScopePaths]
82
- * @param {{ projectRoot?: string, dirtyPaths?: string[], porcelain?: string }} [options]
83
- * @returns {{ restored: string[] }}
84
- */
85
- export function restoreOutOfScopeCoverageArtifacts(
86
- worktreePath,
87
- fileScopePaths,
88
- { projectRoot, dirtyPaths, porcelain } = {},
89
- ) {
90
- const identityRoot = projectRoot ?? worktreePath;
91
- const candidates = Array.isArray(dirtyPaths) ? dirtyPaths : [];
92
- const outOfScope = listOutOfScopeCoveragePaths(candidates, fileScopePaths);
93
- if (outOfScope.length === 0) {
94
- return { restored: [] };
95
- }
96
-
97
- const trackedPaths = listTrackedPorcelainPaths(porcelain ?? "");
98
- const toRestore = trackedPaths.size > 0
99
- ? outOfScope.filter((filePath) => trackedPaths.has(filePath))
100
- : outOfScope;
101
- if (toRestore.length === 0) {
102
- return { restored: [] };
103
- }
104
-
105
- gitExec(
106
- worktreePath,
107
- ["restore", "--source=HEAD", "--worktree", "--", ...toRestore],
108
- { projectRoot: identityRoot },
109
- );
110
- return { restored: toRestore };
111
- }
112
-
113
- /**
114
- * @param {string} filePath
115
- * @returns {boolean}
116
- */
117
- export function isGitignoredArtifactPath(filePath) {
118
- if (!filePath || typeof filePath !== "string") return false;
119
- const normalized = filePath.replace(/\\/g, "/");
120
- return GITIGNORED_ARTIFACT_MARKERS.some(
121
- (marker) =>
122
- normalized === marker.slice(0, -1) ||
123
- normalized.startsWith(marker) ||
124
- normalized.includes(marker),
125
- );
126
- }
127
-
128
- /**
129
- * @param {string} filePath
130
- * @returns {string | null}
131
- */
132
- function gitignoredArtifactRootForPath(filePath) {
133
- const normalized = filePath.replace(/\\/g, "/");
134
- for (const marker of ["/node_modules/", "/coverage/", "/__pycache__/", "/graphify-out/"]) {
135
- const markerIdx = normalized.indexOf(marker);
136
- if (markerIdx >= 0) {
137
- return normalized.slice(0, markerIdx + marker.length - 1);
138
- }
139
- }
140
- if (normalized === "node_modules" || normalized.startsWith("node_modules/")) {
141
- return "node_modules";
142
- }
143
- if (normalized === "coverage" || normalized.startsWith("coverage/")) {
144
- return "coverage";
145
- }
146
- if (normalized === "__pycache__" || normalized.startsWith("__pycache__/")) {
147
- return "__pycache__";
148
- }
149
- if (normalized === "graphify-out" || normalized.startsWith("graphify-out/")) {
150
- return "graphify-out";
151
- }
152
- if (normalized === ".review" || normalized.startsWith(".review/")) {
153
- return ".review";
154
- }
155
- if (normalized === ".pi-smart-router" || normalized.startsWith(".pi-smart-router/")) {
156
- return ".pi-smart-router";
157
- }
158
- if (normalized === ".spine/runtime" || normalized.startsWith(".spine/runtime/")) {
159
- return ".spine/runtime";
160
- }
161
- return null;
162
- }
163
-
164
- /**
165
- * @param {string[]} filePaths
166
- * @returns {string[]}
167
- */
168
- export function listGitignoredArtifactRoots(filePaths) {
169
- const roots = new Set();
170
- for (const filePath of filePaths) {
171
- if (!isGitignoredArtifactPath(filePath)) continue;
172
- const root = gitignoredArtifactRootForPath(filePath);
173
- if (root) roots.add(root);
174
- }
175
- return [...roots].sort();
176
- }
177
-
178
- /**
179
- * @param {string} worktreePath
180
- * @returns {string[]}
181
- */
182
- function listIgnoredUntrackedPaths(worktreePath) {
183
- let output = "";
184
- try {
185
- output = execFileSync("git", ["ls-files", "-o", "-i", "--exclude-standard"], {
186
- cwd: worktreePath,
187
- encoding: "utf-8",
188
- stdio: ["ignore", "pipe", "pipe"],
189
- }).trim();
190
- } catch {
191
- return [];
192
- }
193
- if (!output) return [];
194
- return output.split("\n").map((line) => line.trim()).filter(Boolean);
195
- }
196
-
197
- /**
198
- * Auto-clean worktree-only gitignored artifacts under known dirs before lane dirty gate.
199
- *
200
- * @param {string} worktreePath
201
- * @param {{ projectRoot?: string, porcelain?: string, enabled?: boolean }} [options]
202
- * @returns {{ cleanedRoots: string[] }}
203
- */
204
- export function sanitizeGitignoredArtifactsBeforeLaneCommit(
205
- worktreePath,
206
- { projectRoot, porcelain, enabled = true } = {},
207
- ) {
208
- if (!enabled) return { cleanedRoots: [] };
209
-
210
- const identityRoot = projectRoot ?? worktreePath;
211
- const rawPorcelain = typeof porcelain === "string" ? porcelain : "";
212
- const dirtyPaths = listPorcelainPaths(rawPorcelain);
213
- const ignoredUntrackedPaths = listIgnoredUntrackedPaths(worktreePath);
214
- const gitignoredCandidates = [...new Set([...dirtyPaths, ...ignoredUntrackedPaths])];
215
- if (gitignoredCandidates.length === 0) {
216
- return { cleanedRoots: [] };
217
- }
218
-
219
- const { worktreeOnly } = classifyGitignoredPaths(worktreePath, gitignoredCandidates);
220
- const artifactRoots = listGitignoredArtifactRoots(worktreeOnly);
221
- for (const root of artifactRoots) {
222
- gitExec(worktreePath, ["clean", "-fdX", "--", root], {
223
- projectRoot: identityRoot,
224
- throwOnError: false,
225
- });
226
- }
227
-
228
- return { cleanedRoots: artifactRoots };
229
- }
230
-
231
- export function classifyGitignoredPaths(worktreePath, gitignoredPaths) {
232
- if (!Array.isArray(gitignoredPaths) || gitignoredPaths.length === 0) {
233
- return { indexTracked: [], worktreeOnly: [] };
234
- }
235
-
236
- let indexedOutput = "";
237
- try {
238
- indexedOutput = execFileSync(
239
- "git",
240
- ["ls-files", "--cached", "--", ...gitignoredPaths],
241
- {
242
- cwd: worktreePath,
243
- encoding: "utf-8",
244
- stdio: ["ignore", "pipe", "pipe"],
245
- },
246
- ).trim();
247
- } catch {
248
- // If ls-files fails, treat all as worktree-only (safe fallback).
249
- return { indexTracked: [], worktreeOnly: [...gitignoredPaths] };
250
- }
251
-
252
- const indexedSet = new Set(
253
- indexedOutput ? indexedOutput.split("\n").map((l) => l.trim()).filter(Boolean) : [],
254
- );
255
- const indexTracked = [];
256
- const worktreeOnly = [];
257
- for (const p of gitignoredPaths) {
258
- if (indexedSet.has(p)) {
259
- indexTracked.push(p);
260
- } else {
261
- worktreeOnly.push(p);
262
- }
263
- }
264
- return { indexTracked, worktreeOnly };
265
- }
266
-
267
- /**
268
- * Build a remediation message appropriate for the gitignored path classification.
269
- *
270
- * @param {string[]} indexTracked
271
- * @param {string[]} worktreeOnly
272
- * @returns {string}
273
- */
274
- export function formatGitignoredRemediationMessage(indexTracked, worktreeOnly) {
275
- const allPaths = [...indexTracked, ...worktreeOnly];
276
- const preview = allPaths.slice(0, 20).join(", ");
277
- const suffix = allPaths.length > 20 ? "…" : "";
278
- const prefix = `Lane worktree has gitignored dirty files only (${preview}${suffix})`;
279
-
280
- if (indexTracked.length > 0 && worktreeOnly.length > 0) {
281
- return (
282
- `${prefix} — ` +
283
- `remove index-tracked paths with git rm --cached on the task branch, ` +
284
- `then git clean -fdX to remove worktree-only artifacts before resume`
285
- );
286
- }
287
- if (indexTracked.length > 0) {
288
- return (
289
- `${prefix} — ` +
290
- `remove from the index with git rm --cached on the task branch before resume`
291
- );
292
- }
293
- return (
294
- `${prefix} — ` +
295
- `worktree-only artifacts (not in git index); clean with git clean -fdX before resume`
296
- );
297
- }
298
-
299
- /**
300
- * Resolve porcelain for post-lane-commit validation: restore ephemeral coverage, then filter.
301
- *
302
- * @param {string} worktreePath
303
- * @param {object} [options]
304
- * @param {string[]} [options.fileScopePaths]
305
- * @param {string[]} [options.ignorePatterns]
306
- * @param {string} [options.projectRoot]
307
- * @param {string} [options.porcelain]
308
- * @returns {string}
309
- */
310
- export function resolvePostLaneCommitPorcelain(
311
- worktreePath,
312
- { fileScopePaths, ignorePatterns = [], projectRoot, porcelain, config, batchId, laneNumber } = {},
313
- ) {
314
- const rawPorcelain = typeof porcelain === "string" ? porcelain : "";
315
- const dirtyPaths = listPorcelainPaths(rawPorcelain);
316
- const { restored } = restoreOutOfScopeCoverageArtifacts(worktreePath, fileScopePaths, {
317
- projectRoot,
318
- dirtyPaths,
319
- porcelain: rawPorcelain,
320
- });
321
-
322
- let effectivePorcelain = rawPorcelain;
323
- if (restored.length > 0) {
324
- const restoredSet = new Set(restored);
325
- const kept = [];
326
- for (const line of rawPorcelain.split("\n")) {
327
- if (!line.trim()) continue;
328
- const filePath = extractPorcelainPath(line);
329
- if (filePath && restoredSet.has(filePath)) continue;
330
- kept.push(line);
331
- }
332
- effectivePorcelain = kept.length === 0 ? "" : kept.join("\n");
333
- }
334
-
335
- let filtered = filterOutOfScopeCoveragePorcelain(effectivePorcelain, fileScopePaths, ignorePatterns);
336
- if (!filtered?.trim()) {
337
- return "";
338
- }
339
-
340
- if (isSymlinkOnlyDriftPorcelain(filtered)) {
341
- const identityRoot = projectRoot ?? worktreePath;
342
- const effectiveConfig = config ?? loadSpineConfig(identityRoot).config ?? {};
343
- if (resolveWorktreeSetupHook(identityRoot, effectiveConfig)) {
344
- repairSetupHookSymlinkDrift(worktreePath, {
345
- projectRoot: identityRoot,
346
- config: effectiveConfig,
347
- batchId,
348
- laneNumber,
349
- });
350
- const refreshedPorcelain = gitPorcelain(worktreePath);
351
- filtered = filterOutOfScopeCoveragePorcelain(
352
- refreshedPorcelain,
353
- fileScopePaths,
354
- ignorePatterns,
355
- );
356
- if (!filtered?.trim()) {
357
- return "";
358
- }
359
- if (isSymlinkOnlyDriftPorcelain(filtered)) {
360
- return "";
361
- }
362
- }
363
- }
364
-
365
- return filtered;
366
- }