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.
@@ -23,6 +23,7 @@ export { assertOrchIntegratable } from "./integrate-assert.mjs";
23
23
  import { tryRestoreBranch } from "./integrate-git.mjs";
24
24
  export { tryRestoreBranch } from "./integrate-git.mjs";
25
25
  import { checkIntegrateGate } from "./gate.mjs";
26
+ import { isLiveEngineInActivePhase } from "./lifecycle-archive.mjs";
26
27
  import { appendJournalEvent } from "./journal.mjs";
27
28
  import { countCommitsAhead } from "./lane-commit.mjs";
28
29
  import { inspectGitState, loadBatchStateFile, parseBatchState } from "./reconcile.mjs";
@@ -78,6 +79,20 @@ function runIntegrateMerge({ projectRoot, baseBranch, orchBranch, batchId }) {
78
79
  return plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch, mergeMessage });
79
80
  }
80
81
 
82
+ /**
83
+ * Post-merge suggestion (#371): a live engine in an active phase is still
84
+ * finishing its land loop — wait instead of pointing at a refusing complete.
85
+ * @param {unknown} raw raw batch state read at entry
86
+ * @returns {{ suggestedCommand: string, alternatives: string[] }|null}
87
+ */
88
+ function postMergeCompletionSuggestion(raw) {
89
+ if (!isLiveEngineInActivePhase(raw)) return null;
90
+ return {
91
+ suggestedCommand: "spine wait --until completed --timeout 10m",
92
+ alternatives: ["spine batch complete"],
93
+ };
94
+ }
95
+
81
96
  /**
82
97
  * @param {object} ctx
83
98
  * @param {string} ctx.projectRoot
@@ -156,6 +171,7 @@ export function integrateOrchToBase(ctx) {
156
171
  });
157
172
 
158
173
  if (gitState.orchMergedToBase) {
174
+ const waiting = postMergeCompletionSuggestion(loaded.raw);
159
175
  return {
160
176
  ok: true,
161
177
  exitCode: 0,
@@ -163,7 +179,8 @@ export function integrateOrchToBase(ctx) {
163
179
  baseBranch,
164
180
  orchBranch,
165
181
  headline: `Orch branch already merged into ${baseBranch}`,
166
- suggestedCommand: "spine batch complete",
182
+ suggestedCommand: waiting?.suggestedCommand ?? "spine batch complete",
183
+ ...(waiting ? { alternatives: waiting.alternatives } : {}),
167
184
  alreadyMerged: true,
168
185
  };
169
186
  }
@@ -395,6 +412,7 @@ export function integrateOrchToBase(ctx) {
395
412
  baseCheckedOutAtStart,
396
413
  });
397
414
 
415
+ const waiting = postMergeCompletionSuggestion(loaded.raw);
398
416
  return {
399
417
  ok: true,
400
418
  exitCode: 0,
@@ -405,8 +423,10 @@ export function integrateOrchToBase(ctx) {
405
423
  commitsAhead,
406
424
  gateRequired: gateCheck.required ?? false,
407
425
  headline: `Integrated ${orchBranch} into ${baseBranch}`,
408
- suggestedCommand: "spine batch complete",
409
- alternatives: ["spine status --diagnose"],
426
+ suggestedCommand: waiting?.suggestedCommand ?? "spine batch complete",
427
+ alternatives: waiting
428
+ ? ["spine batch complete", "spine status --diagnose"]
429
+ : ["spine status --diagnose"],
410
430
  ...(dirtyOverlapWarning ? { warnings: [dirtyOverlapWarning] } : {}),
411
431
  };
412
432
  } catch (err) {
@@ -38,6 +38,44 @@ function hasJournalTerminalLifecycle(lastEvent) {
38
38
  return JOURNAL_TERMINAL_LIFECYCLE.has(String(lastEvent.type ?? ""));
39
39
  }
40
40
 
41
+ /** @type {ReadonlySet<string>} Review/contract pipeline events that show the engine is mid-flight on post-`.DONE` work (SP-850 / #356, #371). */
42
+ const POST_DONE_PIPELINE_EVENT_TYPES = new Set([
43
+ "review.started",
44
+ "review.completed",
45
+ "review.failed",
46
+ "contract.verified",
47
+ "contract.failed",
48
+ "task.verdict_recorded",
49
+ ]);
50
+
51
+ /**
52
+ * True when the journal shows post-`.DONE` engine work still open for a task
53
+ * (SP-850 / #356, #371): an unresolved `review.started` (code/plan/final), or a
54
+ * resolved review with no terminal lifecycle yet — the engine is between
55
+ * reviews or running contract verification (which has no "started" marker; it
56
+ * only journals `contract.verified`/`contract.failed` when it finishes). A
57
+ * worker legitimately writes `.DONE` before the engine reviews it, so this
58
+ * window is not state drift. Terminal lifecycle resolution is checked by the
59
+ * caller (`hasJournalTerminalLifecycle`); terminal-artifact completeness is
60
+ * checked separately via `journalShowsDoneInLaneTerminalArtifacts` so the
61
+ * #170 heal keeps its drift trigger.
62
+ *
63
+ * @param {object[]} events
64
+ * @param {string} taskId
65
+ */
66
+ export function journalHasOpenPostDonePipeline(events, taskId) {
67
+ if (!Array.isArray(events)) return false;
68
+ for (const event of events) {
69
+ const type = String(event?.type ?? "");
70
+ if (!POST_DONE_PIPELINE_EVENT_TYPES.has(type)) continue;
71
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
72
+ const eventTaskId = event.taskId ?? payload.taskId;
73
+ if (eventTaskId !== taskId) continue;
74
+ return true;
75
+ }
76
+ return false;
77
+ }
78
+
41
79
  /**
42
80
  * @param {object|null|undefined} classified
43
81
  */
@@ -244,7 +282,14 @@ export function detectBatchStateDrift(cachedState, rebuiltState, events = [], cl
244
282
  if (
245
283
  NON_TERMINAL_CACHE_STATUSES.has(cachedStatus) &&
246
284
  classifiedShowsDoneInLaneDrift(classified) &&
247
- !hasJournalTerminalLifecycle(lastEvent)
285
+ !hasJournalTerminalLifecycle(lastEvent) &&
286
+ // SP-850 / #356, #371: suppress the doneInLane drift entry while the
287
+ // post-`.DONE` review/contract pipeline is open (engine reviewing or
288
+ // verifying) and the terminal-artifact signature is not yet complete.
289
+ // When the signature IS complete (#170), keep the entry so
290
+ // reconcileBatchStateDrift can heal the stale cache to succeeded.
291
+ (!journalHasOpenPostDonePipeline(events, taskId) ||
292
+ journalShowsDoneInLaneTerminalArtifacts(events, taskId))
248
293
  ) {
249
294
  entries.push({
250
295
  taskId,
@@ -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) {
@@ -12,6 +12,8 @@ import {
12
12
  readBatchStateId,
13
13
  } from "./batch-state-io.mjs";
14
14
  import { removeLaneWorktrees, maxLaneNumberFromBatchState } from "./worktree.mjs";
15
+ import { isEngineProcessAlive } from "../process/liveness.mjs";
16
+ import { readBatchEnginePid, readBatchEngineStartedAt } from "./state-guards.mjs";
15
17
 
16
18
  /**
17
19
  * Phases a resume/pause/engine writer can leave behind between a terminal
@@ -23,6 +25,27 @@ import { removeLaneWorktrees, maxLaneNumberFromBatchState } from "./worktree.mjs
23
25
  */
24
26
  const ACTIVE_RESUME_PHASES = new Set(["planning", "running", "paused", "merging"]);
25
27
 
28
+ /**
29
+ * True when the batch is in an active resume phase and the recorded engine
30
+ * PID is alive — i.e. a detached engine is still finalizing its land loop
31
+ * (#371). Liveness is injectable so callers and tests can stub the probe
32
+ * (same shape as `isLiveEngineMidTask`).
33
+ *
34
+ * @param {unknown} raw raw batch state (e.g. the in-lock re-read)
35
+ * @param {object} [deps]
36
+ * @param {(raw: object) => boolean} [deps.isEngineAlive] injectable engine liveness probe
37
+ * @returns {boolean}
38
+ */
39
+ export function isLiveEngineInActivePhase(raw, deps = {}) {
40
+ if (!raw || typeof raw !== "object") return false;
41
+ const phase = String(/** @type {{ phase?: string }} */ (raw).phase ?? "");
42
+ if (!ACTIVE_RESUME_PHASES.has(phase)) return false;
43
+ const isEngineAlive =
44
+ deps.isEngineAlive ??
45
+ ((state) => isEngineProcessAlive(readBatchEnginePid(state), readBatchEngineStartedAt(state)));
46
+ return Boolean(isEngineAlive(raw));
47
+ }
48
+
26
49
  /**
27
50
  * Re-read the active batch state inside the terminal lock section
28
51
  * (SP-792 / #301) so archive, history, and clear act on the freshest on-disk
@@ -43,6 +66,8 @@ const ACTIVE_RESUME_PHASES = new Set(["planning", "running", "paused", "merging"
43
66
  * @param {boolean} [params.requireTerminalPhase] re-validate the terminal-phase precondition on the in-lock state
44
67
  * @param {boolean} [params.force] `dismiss --force` skips the phase re-validation
45
68
  * @param {string|null} [params.diagnosis] pre-lock diagnosis echoed on refusal
69
+ * @param {object} [params.deps]
70
+ * @param {(raw: object) => boolean} [params.deps.isEngineAlive] injectable engine liveness probe (#371)
46
71
  * @returns {{ state: { path: string, raw: object }|null, refusal: object|null }}
47
72
  */
48
73
  export function reloadStateForTerminalWrite({
@@ -53,6 +78,7 @@ export function reloadStateForTerminalWrite({
53
78
  requireTerminalPhase = false,
54
79
  force = false,
55
80
  diagnosis = null,
81
+ deps = {},
56
82
  }) {
57
83
  const refuse = () => ({
58
84
  ok: false,
@@ -77,6 +103,24 @@ export function reloadStateForTerminalWrite({
77
103
  if (requireTerminalPhase && !force) {
78
104
  const phase = String(/** @type {{ phase?: string }} */ (reloaded.raw).phase ?? "");
79
105
  if (ACTIVE_RESUME_PHASES.has(phase)) {
106
+ // #371: a live engine turned the batch active again between the pre-lock
107
+ // read and this reload — it is finishing its land loop, not crashing.
108
+ // Report a pending wait instead of the generic mid-write failure.
109
+ if (isLiveEngineInActivePhase(reloaded.raw, deps)) {
110
+ return {
111
+ state: null,
112
+ refusal: {
113
+ ok: false,
114
+ exitCode: 1,
115
+ pending: true,
116
+ error: "engine_finishing_land_loop",
117
+ headline: "Engine is finishing the land loop — wait for it to complete",
118
+ suggestedCommand: "spine wait --until completed --timeout 10m",
119
+ diagnosis: diagnosis ?? null,
120
+ batchId,
121
+ },
122
+ };
123
+ }
80
124
  return { state: null, refusal: refuse() };
81
125
  }
82
126
  }
@@ -102,6 +102,11 @@ function defaultRunGit(command, args, cwd) {
102
102
  /**
103
103
  * Resolve scope paths for reviewer rule glob matching by review phase.
104
104
  *
105
+ * `code` uses `git diff` paths, falling back to the PROMPT File Scope when the
106
+ * diff resolves to no paths (no baseline, git error, or empty diff) (#357).
107
+ * `final` uses baseline diff paths when a baseline is given and non-empty,
108
+ * else the PROMPT File Scope.
109
+ *
105
110
  * @param {object} params
106
111
  * @param {string} params.worktreePath Git worktree root for code reviews
107
112
  * @param {string} [params.baseline] Baseline commit for code review diff (optional)
@@ -123,12 +128,20 @@ export function resolveReviewScopePaths({
123
128
  case "plan":
124
129
  scopePaths = resolvePlanReviewScopePaths(taskFolder);
125
130
  break;
126
- case "code":
127
- scopePaths = resolveCodeReviewScopePaths(worktreePath, baseline, runGit);
131
+ case "code": {
132
+ const diffPaths = resolveCodeReviewScopePaths(worktreePath, baseline, runGit);
133
+ scopePaths =
134
+ diffPaths.length > 0 ? diffPaths : resolvePlanReviewScopePaths(taskFolder);
128
135
  break;
129
- case "final":
130
- scopePaths = [];
136
+ }
137
+ case "final": {
138
+ const diffPaths = baseline
139
+ ? resolveCodeReviewScopePaths(worktreePath, baseline, runGit)
140
+ : [];
141
+ scopePaths =
142
+ diffPaths.length > 0 ? diffPaths : resolvePlanReviewScopePaths(taskFolder);
131
143
  break;
144
+ }
132
145
  default:
133
146
  scopePaths = [];
134
147
  }
@@ -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