pi-spine 2.28.0 → 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.
@@ -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) {
@@ -180,6 +180,9 @@ function extractResetAtRaw(message) {
180
180
  return match[1].trim().replace(/[.!]+$/, "");
181
181
  }
182
182
 
183
+ /** Kimi's flat-body `type` for the weekly (7-day) usage limit (#367). */
184
+ const KIMI_WEEKLY_QUOTA_TYPE = "exceeded_current_quota_error";
185
+
183
186
  /** Google retry hints below this many seconds mean a short (per-minute) window. */
184
187
  const GOOGLE_TRANSIENT_RETRY_SECONDS = 120;
185
188
 
@@ -229,6 +232,8 @@ function readGoogleQuotaDetails(details) {
229
232
  * Rules (#329):
230
233
  * - z.ai 429, top-level `code` "1308" (5-hour window) or "1310"
231
234
  * (weekly/monthly) → quota_exhausted.
235
+ * - Kimi 429, flat top-level `type` "exceeded_current_quota_error"
236
+ * (weekly 7-day limit) → quota_exhausted (#367).
232
237
  * - Kimi 403, `error.type` "permission_error", message mentions
233
238
  * "usage limit" (billing-cycle exhaustion) → quota_exhausted.
234
239
  * - Kimi 429, `error.type` "rate_limit_error", message mentions
@@ -257,6 +262,20 @@ function classifyPayload(httpStatus, payload) {
257
262
  };
258
263
  }
259
264
 
265
+ // Kimi weekly (7-day) limit: flat `{"message":"...","type":"exceeded_current_quota_error"}` (#367).
266
+ if (
267
+ httpStatus === 429 &&
268
+ payload.type === KIMI_WEEKLY_QUOTA_TYPE &&
269
+ typeof payload.message === "string"
270
+ ) {
271
+ return {
272
+ kind: "quota_exhausted",
273
+ providerCode: KIMI_WEEKLY_QUOTA_TYPE,
274
+ resetAtRaw: null,
275
+ message: truncateMessage(payload.message),
276
+ };
277
+ }
278
+
260
279
  // Kimi: nested error envelope `{"error":{"type":...,"message":...}}`.
261
280
  const error = payload.error && typeof payload.error === "object" ? payload.error : null;
262
281
  const errorMessage = typeof error?.message === "string" ? error.message : null;
@@ -299,6 +299,30 @@ export function listHumanOnlyPaths(projectRoot, snapshot, humanHead, orchBranch)
299
299
  }
300
300
  }
301
301
 
302
+ /**
303
+ * Paths touched on both sides only overlap when their contents differ: the same
304
+ * template sync landing on main and orch is not a divergence. One `git diff`
305
+ * call covers every candidate; a git failure keeps all candidates (fail closed).
306
+ *
307
+ * @param {string} projectRoot @param {string} humanRef @param {string} orchRef @param {string[]} candidatePaths
308
+ * @returns {string[]}
309
+ */
310
+ function keepPathsWithDifferentContent(projectRoot, humanRef, orchRef, candidatePaths) {
311
+ if (candidatePaths.length === 0 || !orchRef) return candidatePaths;
312
+ try {
313
+ const output = execFileSync("git", ["diff", "--name-only", humanRef, orchRef, "--", ...candidatePaths], {
314
+ cwd: projectRoot,
315
+ encoding: "utf-8",
316
+ stdio: ["ignore", "pipe", "pipe"],
317
+ timeout: 5000,
318
+ });
319
+ const differing = new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
320
+ return candidatePaths.filter((filePath) => differing.has(filePath));
321
+ } catch {
322
+ return candidatePaths;
323
+ }
324
+ }
325
+
302
326
  /** @param {string} projectRoot @param {string} ref @param {string} filePath */
303
327
  function pathExistsAtRef(projectRoot, ref, filePath) {
304
328
  try {
@@ -382,7 +406,10 @@ export function inspectHumanBaseSync(ctx) {
382
406
  resolvedOrch && gitRefExists(projectRoot, resolvedOrch)
383
407
  ? listGitChangedPaths(projectRoot, snapshot, resolvedOrch)
384
408
  : landPaths;
385
- const overlapPaths = humanPaths.filter((filePath) => orchPaths.includes(filePath));
409
+ const orchPathSet = new Set(orchPaths);
410
+ const touchedByBoth = humanPaths.filter((filePath) => orchPathSet.has(filePath));
411
+ const orchContentRef = resolvedOrch ?? baseTip;
412
+ const overlapPaths = keepPathsWithDifferentContent(projectRoot, humanHead, orchContentRef, touchedByBoth);
386
413
 
387
414
  if (overlapPaths.length > 0) {
388
415
  return {
@@ -1,6 +1,7 @@
1
1
  /** Diagnosis output context after reconcile signal enrichment (#201 / SP-645). */
2
2
 
3
3
  import { findPendingLaneLandTasks } from "./diagnosis-pending-lane.mjs";
4
+ import { isContractTimeoutFailure } from "./diagnosis-primary-failure.mjs";
4
5
 
5
6
  /**
6
7
  * @param {Record<string, any>} params
@@ -73,6 +74,7 @@ export function buildReconcileDiagnosisContext(params) {
73
74
  lastQuotaExhausted,
74
75
  driftTaskStatus,
75
76
  exitReason,
77
+ contractTimedOut: exitReason === "contract_failed" && isContractTimeoutFailure(journalEvents, failedTaskId),
76
78
  launchFailureKind: resolvedLaunchFailureKind,
77
79
  gitMerged: git.orchMergedToBase,
78
80
  pendingTaskCount,
@@ -58,14 +58,16 @@ export async function waitForSequenceBatchTerminal({
58
58
  stallMs = DEFAULT_SEQUENCE_STALL_MS,
59
59
  enginePid = null,
60
60
  reconcileFn = reconcileBatch,
61
+ now = Date.now,
62
+ sleepFn = sleep,
61
63
  }) {
62
- const startedAt = Date.now();
64
+ const startedAt = now();
63
65
  const deadline = startedAt + timeoutMs;
64
66
  const hardCap = startedAt + maxWaitMs;
65
67
  let lastProgressAt = startedAt;
66
68
  let useLightReconcile = false;
67
- while (Date.now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
68
- if (Date.now() >= hardCap) {
69
+ while (now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
70
+ if (now() >= hardCap) {
69
71
  const reconciliation = reconcileFn({ projectRoot });
70
72
  return {
71
73
  ok: false,
@@ -100,7 +102,7 @@ export async function waitForSequenceBatchTerminal({
100
102
  if (progressAt != null && progressAt > lastProgressAt) {
101
103
  lastProgressAt = progressAt;
102
104
  }
103
- if (Date.now() - lastProgressAt >= stallMs) {
105
+ if (now() - lastProgressAt >= stallMs) {
104
106
  return {
105
107
  ok: false,
106
108
  error: "engine_stalled",
@@ -110,7 +112,7 @@ export async function waitForSequenceBatchTerminal({
110
112
  suggestedCommand: "spine status --diagnose",
111
113
  };
112
114
  }
113
- await sleep(pollIntervalMs);
115
+ await sleepFn(pollIntervalMs);
114
116
  }
115
117
  const reconciliation = reconcileFn({ projectRoot });
116
118
  return {
@@ -10,6 +10,7 @@ import { withBatchStateLock } from "./batch-state-lock.mjs";
10
10
  import {
11
11
  clearBatchEnginePid,
12
12
  evaluateBatchStateWriteGuard,
13
+ readBatchEnginePid,
13
14
  TERMINAL_BATCH_PHASES,
14
15
  } from "./state-guards.mjs";
15
16
 
@@ -53,29 +54,54 @@ function archivedBatchStatePath(projectRoot, batchId) {
53
54
  return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
54
55
  }
55
56
 
57
+ /**
58
+ * Rejection counts per `projectRoot|batchId|reason|ownerPid`. A non-engine writer
59
+ * can hit the guard dozens of times during one contract/merge (28 in v2.28 Batch B);
60
+ * one report per key, plus a count at each power of ten, keeps the signal without
61
+ * the noise.
62
+ *
63
+ * @type {Map<string, number>}
64
+ */
65
+ const rejectedWriteCounts = new Map();
66
+
67
+ /** @param {number} count */
68
+ function isRejectionReportMilestone(count) {
69
+ return count === 1 || (count >= 10 && Number.isInteger(Math.log10(count)));
70
+ }
71
+
56
72
  /**
57
73
  * Make a rejected batch-state write visible instead of silent (#293 / SP-790):
58
74
  * journal `batch.state_write_rejected` (when the incoming state carries a batchId)
59
75
  * and print one `[spine]` line to stderr so a swallowed late write is diagnosable.
76
+ * Repeats of the same rejection are counted and reported at 10, 100, 1000, …
60
77
  *
61
78
  * @param {string} projectRoot
62
79
  * @param {Record<string, any>} state
63
80
  * @param {string} reason
81
+ * @param {number|null} ownerPid Engine PID recorded on disk when the write was refused.
64
82
  */
65
- function reportRejectedBatchStateWrite(projectRoot, state, reason) {
83
+ function reportRejectedBatchStateWrite(projectRoot, state, reason, ownerPid) {
66
84
  const batchId = String(state?.batchId ?? "");
85
+ const key = `${projectRoot}|${batchId}|${reason}|${ownerPid ?? ""}`;
86
+ const count = (rejectedWriteCounts.get(key) ?? 0) + 1;
87
+ rejectedWriteCounts.set(key, count);
88
+ if (!isRejectionReportMilestone(count)) return;
89
+
67
90
  if (batchId) {
68
91
  try {
69
92
  appendJournalEvent(projectRoot, batchId, "batch.state_write_rejected", {
70
93
  reason,
71
94
  incomingPhase: String(state.phase ?? ""),
95
+ ownerPid,
96
+ rejectedCount: count,
72
97
  });
73
98
  } catch {
74
99
  /* journal failure must not turn a guarded no-op into a crash */
75
100
  }
76
101
  }
102
+ const repeat = count > 1 ? ` (${count} rejections so far)` : "";
77
103
  console.error(
78
- `[spine] refused batch-state write (${reason}) for batch ${batchId || "unknown"} — keeping on-disk state`,
104
+ `[spine] refused batch-state write (${reason}) for batch ${batchId || "unknown"} — keeping on-disk state${repeat}`,
79
105
  );
80
106
  }
81
107
 
@@ -101,8 +127,8 @@ function persistSpineBatchStateGuarded(projectRoot, state, options) {
101
127
  });
102
128
  if (!guard.allowed) {
103
129
  const reason = String(guard.reason ?? "unknown");
104
- reportRejectedBatchStateWrite(projectRoot, state, reason);
105
130
  const loaded = loadSpineBatchState(projectRoot);
131
+ reportRejectedBatchStateWrite(projectRoot, state, reason, loaded.raw ? readBatchEnginePid(loaded.raw) : null);
106
132
  return { ok: false, reason, state: loaded.raw ?? state };
107
133
  }
108
134
 
@@ -6,6 +6,21 @@
6
6
  /** @type {readonly string[]} */
7
7
  export const CONTRACT_MODES = Object.freeze(["required", "optional", "legacy"]);
8
8
 
9
+ /** Bounds for `contract.testTimeoutMs` (#369): 1 second to 4 hours. */
10
+ export const CONTRACT_TEST_TIMEOUT_MIN_MS = 1000;
11
+ export const CONTRACT_TEST_TIMEOUT_MAX_MS = 4 * 60 * 60 * 1000;
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
+
9
24
  /**
10
25
  * @param {unknown} config
11
26
  * @returns {{ code: string, message: string, suggestedCommand: string } | null}
@@ -44,6 +59,51 @@ export function validateContractConfig(config) {
44
59
  }
45
60
  }
46
61
 
62
+ if (contract.testTimeoutMs != null) {
63
+ const timeoutMs = contract.testTimeoutMs;
64
+ const isValid =
65
+ typeof timeoutMs === "number" &&
66
+ Number.isInteger(timeoutMs) &&
67
+ timeoutMs >= CONTRACT_TEST_TIMEOUT_MIN_MS &&
68
+ timeoutMs <= CONTRACT_TEST_TIMEOUT_MAX_MS;
69
+ if (!isValid) {
70
+ return {
71
+ code: "CONFIG_CONTRACT_TEST_TIMEOUT_INVALID",
72
+ message: `contract.testTimeoutMs must be an integer between ${CONTRACT_TEST_TIMEOUT_MIN_MS} and ${CONTRACT_TEST_TIMEOUT_MAX_MS} when set`,
73
+ suggestedCommand: "spine settings set contract.testTimeoutMs 1200000",
74
+ };
75
+ }
76
+ }
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
+
47
107
  if (contract.legacyTaskIdPrefixes != null) {
48
108
  if (!Array.isArray(contract.legacyTaskIdPrefixes)) {
49
109
  return {
@@ -8,7 +8,9 @@
8
8
  * Only `lanes.maxParallel` is editable via `spine settings set`; tasks root is env/file only.
9
9
  */
10
10
 
11
- /** @typedef {"boolean" | "number" | "string" | "enum"} SettingFieldType */
11
+ import { CONTRACT_TEST_TIMEOUT_MAX_MS, CONTRACT_TEST_TIMEOUT_MIN_MS } from "./contract.mjs";
12
+
13
+ /** @typedef {"boolean" | "number" | "string" | "enum" | "stringList"} SettingFieldType */
12
14
 
13
15
  /**
14
16
  * @typedef {object} SettingField
@@ -43,6 +45,11 @@ export const SETTINGS_FIELDS = Object.freeze([
43
45
  label: "Auto integrate between waves",
44
46
  type: "boolean",
45
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
+ },
46
53
  {
47
54
  path: "gates.requireBeforeIntegrate",
48
55
  label: "Require gate before integrate",
@@ -62,6 +69,26 @@ export const SETTINGS_FIELDS = Object.freeze([
62
69
  min: 1,
63
70
  max: 10,
64
71
  },
72
+ {
73
+ path: "contract.testTimeoutMs",
74
+ label: "Contract testCommand timeout per attempt (ms; default 600000)",
75
+ type: "number",
76
+ min: CONTRACT_TEST_TIMEOUT_MIN_MS,
77
+ max: CONTRACT_TEST_TIMEOUT_MAX_MS,
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
+ },
65
92
  {
66
93
  path: "agents.worker.model",
67
94
  label: "Worker model",
@@ -236,6 +263,8 @@ function validateForField(field, rawValue) {
236
263
  return validateString(rawValue, field);
237
264
  case "enum":
238
265
  return validateEnum(rawValue, field);
266
+ case "stringList":
267
+ return validateStringList(rawValue);
239
268
  default:
240
269
  return { ok: false, error: `Unsupported field type: ${field.type}` };
241
270
  }
@@ -276,6 +305,35 @@ function validateNumber(rawValue, field) {
276
305
  return { ok: true, normalizedValue: coerced };
277
306
  }
278
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
+
279
337
  /**
280
338
  * @param {unknown} rawValue
281
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
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Agent prompt drift check: `.spine/agents/*.md` vs the packaged
3
+ * `templates/agents/*.md` the CLI ships.
4
+ *
5
+ * Workers, reviewers and the supervisor read the project copy, not the template.
6
+ * FR-WORK-08 lets a project append overrides after the base template, so a copy
7
+ * is current when it starts with the template text; anything else means template
8
+ * fixes (for example the final PASS/REVISE/REPLAN verdict shape) never reach the
9
+ * agents. Advisory only: the operator decides how to merge local edits.
10
+ */
11
+
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+
15
+ import { AGENT_STUB_FILES, TEMPLATE_PATHS } from "../config/spine-init-constants.mjs";
16
+
17
+ /** @param {string} text */
18
+ function normalizeAgentText(text) {
19
+ return text.replace(/\r\n/g, "\n").trimEnd();
20
+ }
21
+
22
+ /**
23
+ * @param {object} params
24
+ * @param {string} params.projectRoot
25
+ * @param {Array<{ templateKey: string, destName: string }>} [params.agentFiles]
26
+ * @param {Record<string, string>} [params.templatePaths] templateKey → absolute template path
27
+ * @returns {{ label: string, ok: boolean, warning?: boolean, detail: string, suggestedCommand?: string }}
28
+ */
29
+ export function buildAgentTemplateDriftDoctorCheck({
30
+ projectRoot,
31
+ agentFiles = AGENT_STUB_FILES,
32
+ templatePaths = TEMPLATE_PATHS.agents,
33
+ }) {
34
+ /** @type {string[]} */
35
+ const drifted = [];
36
+ let compared = 0;
37
+
38
+ for (const { templateKey, destName } of agentFiles) {
39
+ const projectPath = path.join(projectRoot, ".spine", "agents", destName);
40
+ const templatePath = templatePaths[templateKey];
41
+ if (!templatePath || !fs.existsSync(projectPath) || !fs.existsSync(templatePath)) continue;
42
+ compared += 1;
43
+ const projectText = normalizeAgentText(fs.readFileSync(projectPath, "utf-8"));
44
+ const templateText = normalizeAgentText(fs.readFileSync(templatePath, "utf-8"));
45
+ if (!projectText.startsWith(templateText)) {
46
+ drifted.push(`.spine/agents/${destName}`);
47
+ }
48
+ }
49
+
50
+ if (drifted.length === 0) {
51
+ return {
52
+ label: "agent prompts match templates",
53
+ ok: true,
54
+ detail: compared === 0 ? "no agent files to compare" : `${compared} agent file(s) start with the packaged template`,
55
+ };
56
+ }
57
+
58
+ return {
59
+ label: "agent prompts match templates",
60
+ ok: true,
61
+ warning: true,
62
+ detail: `${drifted.join(", ")} no longer start with the packaged template; template fixes do not reach these agents`,
63
+ suggestedCommand: `diff templates/agents/<file> .spine/agents/<file> — rebase local edits after the template (or spine init --force to reset)`,
64
+ };
65
+ }
@@ -23,6 +23,8 @@ import {
23
23
  buildStallConfigDoctorCheck,
24
24
  } from "./stall-config.mjs";
25
25
  import { buildRulesManifestDoctorCheck } from "./rules-manifest.mjs";
26
+ import { buildAgentTemplateDriftDoctorCheck } from "./agent-template-drift.mjs";
27
+ import { buildStetCapacityDoctorCheck } from "./stet-capacity.mjs";
26
28
  import { buildWorktreeHealthDoctorCheck } from "./worktree-health.mjs";
27
29
  import { buildGitignoredPubspecAssetsDoctorCheck } from "../config/worktree-setup-hook.mjs";
28
30
  import { buildStaleWorktreesDoctorCheck } from "./stale-worktrees.mjs";
@@ -536,6 +538,8 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
536
538
  suggestedCommand: "spine init",
537
539
  });
538
540
  }
541
+ checks.push(buildAgentTemplateDriftDoctorCheck({ projectRoot }));
542
+ checks.push(buildStetCapacityDoctorCheck());
539
543
 
540
544
  const tasksRootPath = resolveTasksRoot(projectRoot, configResult);
541
545
  const metricsPath = path.join(