pi-spine 1.10.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/bin/spine-cleanup.mjs +89 -0
  2. package/bin/spine-doctor.mjs +8 -0
  3. package/bin/spine.mjs +13 -0
  4. package/package.json +4 -1
  5. package/skills/create-spine-tasks/SKILL.md +29 -0
  6. package/skills/create-spine-tasks/references/contract-template.md +11 -0
  7. package/skills/create-spine-tasks/references/prompt-template.md +15 -20
  8. package/skills/spine-autonomous-operator/SKILL.md +19 -3
  9. package/skills/spine-autonomous-operator/references/agent-shell-batch-policy.md +18 -0
  10. package/skills/spine-orchestrate-waves/SKILL.md +9 -2
  11. package/skills/spine-orchestrate-waves/references/outer-loop.md +24 -2
  12. package/skills/spine-release-operator/SKILL.md +25 -2
  13. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +96 -0
  14. package/skills/spine-release-operator/references/release-manifest-template.md +7 -3
  15. package/src/batch/abort.mjs +10 -14
  16. package/src/batch/diagnosis-merge-failure.mjs +66 -0
  17. package/src/batch/diagnosis-parent-exit.mjs +125 -0
  18. package/src/batch/diagnosis.mjs +26 -73
  19. package/src/batch/engine-lanes/watch.mjs +4 -2
  20. package/src/batch/heartbeat-subprocess.mjs +214 -0
  21. package/src/batch/heartbeat.mjs +38 -63
  22. package/src/batch/lane-dirty-check.mjs +10 -0
  23. package/src/batch/lifecycle.mjs +1 -18
  24. package/src/batch/reconcile.mjs +11 -0
  25. package/src/batch/review.mjs +20 -0
  26. package/src/batch/worktree.mjs +130 -1
  27. package/src/config/preflight/git-batch.mjs +14 -3
  28. package/src/dashboard/public/dashboard.js +6 -2
  29. package/src/dashboard/snapshot.mjs +85 -11
  30. package/src/doctor/duplicate-install.mjs +148 -0
  31. package/src/doctor/pi-cli-resolution.mjs +222 -0
  32. package/src/doctor/run-doctor-checks.mjs +4 -0
  33. package/src/doctor/stale-worktrees.mjs +1 -1
  34. package/src/tasks/packet/parse-prompt.mjs +29 -0
@@ -0,0 +1,214 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Subprocess heartbeat signals for long-running worker steps (issue #134 / SP-548).
4
+ */
5
+
6
+ /** @typedef {"launching" | "pi" | "verify" | "subprocess" | "unknown"} WorkerPhase */
7
+
8
+ const SUBPROCESS_COMMAND_MAX_LEN = 120;
9
+
10
+ const SUBPROCESS_FRIENDLY_LABELS = Object.freeze([
11
+ [/^npm\s+run\s+coverage(?::\w+)?/i, "coverage"],
12
+ [/^npm\s+run\s+typecheck/i, "typecheck"],
13
+ [/^npm\s+test\b/i, "tests"],
14
+ [/^node\s+--test\b/i, "tests"],
15
+ ]);
16
+
17
+ const SUBPROCESS_STRING_REDACT_PATTERNS = [
18
+ /(?:bearer|token|secret|password|api[_-]?key)\s*[:=]\s*\S+/gi,
19
+ /sk-[a-zA-Z0-9]{20,}/g,
20
+ /ghp_[a-zA-Z0-9]{20,}/g,
21
+ /\b[A-Z][A-Z0-9_]*=\S+/g,
22
+ ];
23
+
24
+ /**
25
+ * @param {string} text
26
+ */
27
+ function redactSubprocessCommandText(text) {
28
+ let out = text;
29
+ for (const pattern of SUBPROCESS_STRING_REDACT_PATTERNS) {
30
+ out = out.replace(pattern, "[REDACTED]");
31
+ }
32
+ return out.replace(/\s+/g, " ").trim();
33
+ }
34
+
35
+ /**
36
+ * @param {string} raw
37
+ */
38
+ function stripLeadingEnvAssignments(command) {
39
+ let rest = command.trim();
40
+ while (/^[A-Za-z_][A-Za-z0-9_]*=\S+\s+/.test(rest)) {
41
+ rest = rest.replace(/^[A-Za-z_][A-Za-z0-9_]*=\S+\s+/, "");
42
+ }
43
+ return rest.trim();
44
+ }
45
+
46
+ /**
47
+ * Redact secrets and shorten a subprocess command for heartbeat payloads.
48
+ *
49
+ * @param {string} raw
50
+ */
51
+ export function redactSubprocessCommand(raw) {
52
+ if (!raw || typeof raw !== "string") return null;
53
+ const head = raw.split(/\s*(?:&&|;|\|)\s*/)[0]?.trim() ?? "";
54
+ if (!head) return null;
55
+ const withoutEnv = stripLeadingEnvAssignments(head);
56
+ const redacted = redactSubprocessCommandText(withoutEnv);
57
+ const trimmed =
58
+ redacted.length > SUBPROCESS_COMMAND_MAX_LEN
59
+ ? `${redacted.slice(0, SUBPROCESS_COMMAND_MAX_LEN - 1)}…`
60
+ : redacted;
61
+ for (const [pattern, label] of SUBPROCESS_FRIENDLY_LABELS) {
62
+ if (pattern.test(trimmed)) return label;
63
+ }
64
+ return trimmed;
65
+ }
66
+
67
+ /**
68
+ * @param {object} event
69
+ * @param {object} filter
70
+ * @param {number} [filter.laneNumber]
71
+ * @param {string} [filter.laneId]
72
+ * @param {string} [filter.taskId]
73
+ */
74
+ function subprocessEventMatches(event, { laneNumber, laneId, taskId }) {
75
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
76
+ const expectedLaneId =
77
+ laneNumber != null ? `lane-${laneNumber}` : typeof laneId === "string" ? laneId : null;
78
+ if (taskId && event.taskId && event.taskId !== taskId) return false;
79
+ if (payload.taskId && taskId && payload.taskId !== taskId) return false;
80
+ if (expectedLaneId && event.laneId && event.laneId !== expectedLaneId) return false;
81
+ if (expectedLaneId && payload.laneId && payload.laneId !== expectedLaneId) return false;
82
+ if (laneNumber != null && payload.laneNumber != null && payload.laneNumber !== laneNumber) {
83
+ return false;
84
+ }
85
+ return true;
86
+ }
87
+
88
+ /**
89
+ * Latest active subprocess signal from worker journal events (issue #134 / SP-548).
90
+ *
91
+ * @param {object[]} events
92
+ * @param {object} filter
93
+ * @param {number} [filter.laneNumber]
94
+ * @param {string} [filter.laneId]
95
+ * @param {string} [filter.taskId]
96
+ */
97
+ export function findLatestSubprocessSignal(events, { laneNumber, laneId, taskId }) {
98
+ for (let index = events.length - 1; index >= 0; index -= 1) {
99
+ const event = events[index];
100
+ if (!subprocessEventMatches(event, { laneNumber, laneId, taskId })) continue;
101
+
102
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
103
+ const ts = Date.parse(event.timestamp);
104
+ if (Number.isNaN(ts)) continue;
105
+
106
+ if (event.type === "task.subprocess_ended") {
107
+ return null;
108
+ }
109
+
110
+ const rawCommand =
111
+ typeof payload.subprocessCommand === "string"
112
+ ? payload.subprocessCommand
113
+ : typeof payload.subprocessLabel === "string"
114
+ ? payload.subprocessLabel
115
+ : null;
116
+ if (!rawCommand) continue;
117
+
118
+ if (event.type === "task.subprocess_active" || event.type === "task.step_completed") {
119
+ const subprocessCommand = redactSubprocessCommand(rawCommand);
120
+ if (!subprocessCommand) continue;
121
+ return { subprocessCommand, subprocessStartedAtMs: ts };
122
+ }
123
+ }
124
+
125
+ return null;
126
+ }
127
+
128
+ /**
129
+ * @param {WorkerPhase} enginePhase
130
+ * @param {object | null | undefined} signals
131
+ */
132
+ export function resolveEffectiveWorkerPhase(enginePhase, signals) {
133
+ if (signals?.subprocessCommand) return "subprocess";
134
+ return enginePhase;
135
+ }
136
+
137
+ /**
138
+ * Progress-class heartbeat fields are omitted during launcher preflight so retries
139
+ * do not reuse stale STATUS / git checkpoint signals from a prior attempt.
140
+ *
141
+ * @param {object} signals
142
+ * @param {WorkerPhase} workerPhase
143
+ * @param {"worker_alive" | "checkpoint" | "file_scope_activity"} heartbeatKind
144
+ */
145
+ export function buildHeartbeatPayloadFields(signals, workerPhase, heartbeatKind) {
146
+ const effectivePhase = resolveEffectiveWorkerPhase(workerPhase, signals);
147
+ const includeProgressFields =
148
+ effectivePhase !== "launching" &&
149
+ (heartbeatKind === "checkpoint" || heartbeatKind === "file_scope_activity");
150
+
151
+ /** @type {Record<string, unknown>} */
152
+ const payload = {
153
+ statusMtimeMs: null,
154
+ lastCommitAtMs: null,
155
+ fileScopeMtimeMs: null,
156
+ dirtyPathCount: 0,
157
+ };
158
+
159
+ if (effectivePhase === "subprocess" && signals?.subprocessCommand) {
160
+ payload.subprocessCommand = signals.subprocessCommand;
161
+ payload.subprocessStartedAtMs = signals.subprocessStartedAtMs ?? null;
162
+ }
163
+
164
+ if (!includeProgressFields) {
165
+ return payload;
166
+ }
167
+
168
+ return {
169
+ ...payload,
170
+ statusMtimeMs: signals.statusMtimeMs,
171
+ lastCommitAtMs: signals.lastCommitAtMs,
172
+ fileScopeMtimeMs: signals.fileScopeMtimeMs,
173
+ dirtyPathCount: signals.dirtyPaths?.length ?? 0,
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Bounded lane.progress_snapshot payload (issue #48).
179
+ *
180
+ * @param {object} signals
181
+ * @param {WorkerPhase} workerPhase
182
+ */
183
+ export function buildProgressSnapshotPayload(signals, workerPhase) {
184
+ const effectivePhase = resolveEffectiveWorkerPhase(workerPhase, signals);
185
+ /** @type {Record<string, unknown>} */
186
+ const payload = {
187
+ workerPhase: effectivePhase,
188
+ dirtyPathCount: signals.dirtyPaths?.length ?? 0,
189
+ lastCommitAtMs: signals.lastCommitAtMs ?? null,
190
+ statusMtimeMs: signals.statusMtimeMs ?? null,
191
+ stepCompletedAtMs: signals.stepCompletedAtMs ?? null,
192
+ };
193
+ if (effectivePhase === "subprocess" && signals?.subprocessCommand) {
194
+ payload.subprocessCommand = signals.subprocessCommand;
195
+ payload.subprocessStartedAtMs = signals.subprocessStartedAtMs ?? null;
196
+ }
197
+ return payload;
198
+ }
199
+
200
+ /**
201
+ * @param {object | null} prev
202
+ * @param {object} next
203
+ */
204
+ export function progressSnapshotPayloadChanged(prev, next) {
205
+ if (!prev) return true;
206
+ if (prev.workerPhase !== next.workerPhase) return true;
207
+ if (prev.dirtyPathCount !== next.dirtyPathCount) return true;
208
+ if (prev.lastCommitAtMs !== next.lastCommitAtMs) return true;
209
+ if (prev.statusMtimeMs !== next.statusMtimeMs) return true;
210
+ if (prev.stepCompletedAtMs !== next.stepCompletedAtMs) return true;
211
+ if (prev.subprocessCommand !== next.subprocessCommand) return true;
212
+ if (prev.subprocessStartedAtMs !== next.subprocessStartedAtMs) return true;
213
+ return false;
214
+ }
@@ -11,6 +11,12 @@ import {
11
11
  resolveDebouncedScopedDirtyPaths,
12
12
  resolveFileScopeMtimeMs,
13
13
  } from "./heartbeat-git-debounce.mjs";
14
+ import {
15
+ findLatestSubprocessSignal,
16
+ resolveEffectiveWorkerPhase,
17
+ buildHeartbeatPayloadFields,
18
+ buildProgressSnapshotPayload,
19
+ } from "./heartbeat-subprocess.mjs";
14
20
 
15
21
  export {
16
22
  clearGitPorcelainDebounceCache,
@@ -18,6 +24,15 @@ export {
18
24
  resetGitPorcelainCallCount,
19
25
  } from "./heartbeat-git-debounce.mjs";
20
26
 
27
+ export {
28
+ findLatestSubprocessSignal,
29
+ redactSubprocessCommand,
30
+ resolveEffectiveWorkerPhase,
31
+ buildHeartbeatPayloadFields,
32
+ buildProgressSnapshotPayload,
33
+ progressSnapshotPayloadChanged,
34
+ } from "./heartbeat-subprocess.mjs";
35
+
21
36
  const DEFAULT_STALL_TIMEOUT_MIN = 60;
22
37
  const DEFAULT_GRACE_AFTER_PROGRESS_MIN = 15;
23
38
  const DEFAULT_HEARTBEAT_INTERVAL_MIN = 10;
@@ -30,7 +45,7 @@ const CHECKPOINT_WARNING_SUGGESTION =
30
45
  "Commit step work and call spine_report_progress so stall grace tracks checkpoints, not file edits alone.";
31
46
 
32
47
  /** @typedef {"worker_alive" | "checkpoint" | "file_scope_activity"} HeartbeatKind */
33
- /** @typedef {"launching" | "pi" | "verify" | "unknown"} WorkerPhase */
48
+ /** @typedef {"launching" | "pi" | "verify" | "subprocess" | "unknown"} WorkerPhase */
34
49
 
35
50
  /** @type {readonly HeartbeatKind[]} */
36
51
  export const HEARTBEAT_KINDS = Object.freeze([
@@ -40,7 +55,13 @@ export const HEARTBEAT_KINDS = Object.freeze([
40
55
  ]);
41
56
 
42
57
  /** @type {readonly WorkerPhase[]} */
43
- export const WORKER_PHASES = Object.freeze(["launching", "pi", "verify", "unknown"]);
58
+ export const WORKER_PHASES = Object.freeze([
59
+ "launching",
60
+ "pi",
61
+ "verify",
62
+ "subprocess",
63
+ "unknown",
64
+ ]);
44
65
 
45
66
  /**
46
67
  * @param {object} [config]
@@ -196,6 +217,8 @@ export function collectProgressSignals({
196
217
  );
197
218
 
198
219
  let stepCompletedAtMs = null;
220
+ let subprocessCommand = null;
221
+ let subprocessStartedAtMs = null;
199
222
  if (journalContext?.projectRoot && journalContext?.batchId) {
200
223
  const events = readJournalEventsCached(journalContext.projectRoot, journalContext.batchId);
201
224
  stepCompletedAtMs = findLatestStepCompletedMs(events, {
@@ -203,6 +226,15 @@ export function collectProgressSignals({
203
226
  laneId: journalContext.laneId,
204
227
  taskId: journalContext.taskId,
205
228
  });
229
+ const subprocess = findLatestSubprocessSignal(events, {
230
+ laneNumber: journalContext.laneNumber,
231
+ laneId: journalContext.laneId,
232
+ taskId: journalContext.taskId,
233
+ });
234
+ if (subprocess) {
235
+ subprocessCommand = subprocess.subprocessCommand;
236
+ subprocessStartedAtMs = subprocess.subprocessStartedAtMs;
237
+ }
206
238
  }
207
239
 
208
240
  return {
@@ -211,6 +243,8 @@ export function collectProgressSignals({
211
243
  fileScopeMtimeMs,
212
244
  stepCompletedAtMs,
213
245
  dirtyPaths,
246
+ subprocessCommand,
247
+ subprocessStartedAtMs,
214
248
  };
215
249
  }
216
250
 
@@ -323,66 +357,6 @@ export function resolveHeartbeatKind({
323
357
  return "worker_alive";
324
358
  }
325
359
 
326
- /**
327
- * Progress-class heartbeat fields are omitted during launcher preflight so retries
328
- * do not reuse stale STATUS / git checkpoint signals from a prior attempt.
329
- *
330
- * @param {object} signals
331
- * @param {WorkerPhase} workerPhase
332
- * @param {HeartbeatKind} heartbeatKind
333
- */
334
- export function buildHeartbeatPayloadFields(signals, workerPhase, heartbeatKind) {
335
- const includeProgressFields =
336
- workerPhase !== "launching" &&
337
- (heartbeatKind === "checkpoint" || heartbeatKind === "file_scope_activity");
338
-
339
- if (!includeProgressFields) {
340
- return {
341
- statusMtimeMs: null,
342
- lastCommitAtMs: null,
343
- fileScopeMtimeMs: null,
344
- dirtyPathCount: 0,
345
- };
346
- }
347
-
348
- return {
349
- statusMtimeMs: signals.statusMtimeMs,
350
- lastCommitAtMs: signals.lastCommitAtMs,
351
- fileScopeMtimeMs: signals.fileScopeMtimeMs,
352
- dirtyPathCount: signals.dirtyPaths?.length ?? 0,
353
- };
354
- }
355
-
356
- /**
357
- * Bounded lane.progress_snapshot payload (issue #48).
358
- *
359
- * @param {object} signals
360
- * @param {WorkerPhase} workerPhase
361
- */
362
- export function buildProgressSnapshotPayload(signals, workerPhase) {
363
- return {
364
- workerPhase,
365
- dirtyPathCount: signals.dirtyPaths?.length ?? 0,
366
- lastCommitAtMs: signals.lastCommitAtMs ?? null,
367
- statusMtimeMs: signals.statusMtimeMs ?? null,
368
- stepCompletedAtMs: signals.stepCompletedAtMs ?? null,
369
- };
370
- }
371
-
372
- /**
373
- * @param {object | null} prev
374
- * @param {object} next
375
- */
376
- export function progressSnapshotPayloadChanged(prev, next) {
377
- if (!prev) return true;
378
- if (prev.workerPhase !== next.workerPhase) return true;
379
- if (prev.dirtyPathCount !== next.dirtyPathCount) return true;
380
- if (prev.lastCommitAtMs !== next.lastCommitAtMs) return true;
381
- if (prev.statusMtimeMs !== next.statusMtimeMs) return true;
382
- if (prev.stepCompletedAtMs !== next.stepCompletedAtMs) return true;
383
- return false;
384
- }
385
-
386
360
  /**
387
361
  * @param {object} params
388
362
  * @param {number} params.now
@@ -430,13 +404,14 @@ export function recordLaneHeartbeat({
430
404
  workerPhase = "unknown",
431
405
  heartbeatKind = "worker_alive",
432
406
  }) {
407
+ const effectivePhase = resolveEffectiveWorkerPhase(workerPhase, signals);
433
408
  const progressFields = buildHeartbeatPayloadFields(signals, workerPhase, heartbeatKind);
434
409
  appendJournalEvent(projectRoot, batchId, "lane.heartbeat", {
435
410
  laneNumber,
436
411
  taskId,
437
412
  correlationId,
438
413
  heartbeatKind,
439
- workerPhase,
414
+ workerPhase: effectivePhase,
440
415
  ...progressFields,
441
416
  });
442
417
  }
@@ -32,6 +32,10 @@ export const GITIGNORED_ARTIFACT_MARKERS = [
32
32
  "__pycache__/",
33
33
  "/graphify-out/",
34
34
  "graphify-out/",
35
+ "/.review/",
36
+ ".review/",
37
+ "/.spine/runtime/",
38
+ ".spine/runtime/",
35
39
  ];
36
40
 
37
41
  /** Flutter build output dir that can pollute unscoped `flutter analyze` (#78). */
@@ -516,6 +520,12 @@ function gitignoredArtifactRootForPath(filePath) {
516
520
  if (normalized === "graphify-out" || normalized.startsWith("graphify-out/")) {
517
521
  return "graphify-out";
518
522
  }
523
+ if (normalized === ".review" || normalized.startsWith(".review/")) {
524
+ return ".review";
525
+ }
526
+ if (normalized === ".spine/runtime" || normalized.startsWith(".spine/runtime/")) {
527
+ return ".spine/runtime";
528
+ }
519
529
  return null;
520
530
  }
521
531
 
@@ -18,7 +18,7 @@ import {
18
18
  readAliveBatchEnginePid,
19
19
  } from "./batch-state-io.mjs";
20
20
  import { terminateLaneWorkers } from "./worker-host.mjs";
21
- import { removeLaneWorktrees } from "./worktree.mjs";
21
+ import { removeLaneWorktrees, maxLaneNumberFromBatchState } from "./worktree.mjs";
22
22
  import { terminateSupervisorIfRunning } from "./supervisor-spawn.mjs";
23
23
  import { bumpDashboardInvalidateSignal } from "../dashboard/cache-invalidate.mjs";
24
24
 
@@ -117,23 +117,6 @@ function clearCompletedBatchState(batchStatePath, batchId) {
117
117
  clearActiveBatchStateIfMatches(batchStatePath, batchId);
118
118
  }
119
119
 
120
- /**
121
- * @param {unknown} raw
122
- */
123
- function maxLaneNumberFromBatchState(raw) {
124
- const lanes = /** @type {{ lanes?: unknown }} */ (raw)?.lanes;
125
- if (!Array.isArray(lanes) || lanes.length === 0) return 1;
126
- let max = 1;
127
- for (const lane of lanes) {
128
- if (!lane || typeof lane !== "object") continue;
129
- const laneNumber = Number(/** @type {{ laneNumber?: number }} */ (lane).laneNumber);
130
- if (Number.isFinite(laneNumber) && laneNumber > max) {
131
- max = laneNumber;
132
- }
133
- }
134
- return max;
135
- }
136
-
137
120
  /**
138
121
  * @param {object|null|undefined} config
139
122
  */
@@ -23,6 +23,7 @@ import {
23
23
  import { findLatestReviewHonorSignal } from "./review.mjs";
24
24
  import { summarizeMergeFailures } from "./diagnosis-merge-failure.mjs";
25
25
  import { inferWorkerDoneMissingFailure } from "./diagnosis-worker-done-missing.mjs";
26
+ import { inferEngineOrphanCause } from "./diagnosis-parent-exit.mjs";
26
27
  import {
27
28
  findStubMarkedSucceededTask,
28
29
  inferStubExitReasonForTask,
@@ -1434,6 +1435,14 @@ export function reconcileBatch(ctx, _lightRetry = false) {
1434
1435
  signals.reviewHonor = reviewHonorSignal;
1435
1436
  }
1436
1437
 
1438
+ const enginePid = readBatchEnginePid(batch.raw);
1439
+ const staleEnginePid =
1440
+ enginePid != null && !isProcessAlive(enginePid);
1441
+ const engineOrphanCause =
1442
+ diagnosis === "engine_orphaned"
1443
+ ? inferEngineOrphanCause({ journalEvents, staleEnginePid })
1444
+ : null;
1445
+
1437
1446
  const output = buildDiagnosisOutput(diagnosis, {
1438
1447
  batchId: batch.batchId,
1439
1448
  phase: batch.phase,
@@ -1467,6 +1476,8 @@ export function reconcileBatch(ctx, _lightRetry = false) {
1467
1476
  macroPhase,
1468
1477
  reviewHonorSignal,
1469
1478
  ...(doneMissingContext ?? {}),
1479
+ engineOrphanCause,
1480
+ staleEnginePid,
1470
1481
  humanBaseSync,
1471
1482
  overlapPaths: humanBaseSync?.overlapPaths ?? [],
1472
1483
  });
@@ -363,6 +363,26 @@ export function findLatestReviewHonorSignal(journalEvents, activeTaskId = null)
363
363
  return null;
364
364
  }
365
365
 
366
+ /**
367
+ * @param {object|null|undefined} reviewHonorSignal
368
+ * @returns {string|null}
369
+ */
370
+ export function buildReviewHonorHeadlineSuffix(reviewHonorSignal) {
371
+ if (!reviewHonorSignal?.kind) return null;
372
+ const reviewLabel =
373
+ reviewHonorSignal.reviewType === "final" ? "final review" : "code review";
374
+ if (reviewHonorSignal.kind === "review.crash_recovered") {
375
+ return `recovered ${reviewLabel} crash — prior verdict honored from ${reviewHonorSignal.honorSource ?? "artifact"}`;
376
+ }
377
+ if (reviewHonorSignal.kind === "review.skipped_fresh_artifact") {
378
+ return `skipped redundant ${reviewLabel} — fresh artifact honored`;
379
+ }
380
+ if (reviewHonorSignal.kind === "review.resumed") {
381
+ return `${reviewLabel} resumed after operator retry`;
382
+ }
383
+ return null;
384
+ }
385
+
366
386
  /**
367
387
  * Latest `.reviews/final-*.md` by mtime, if any.
368
388
  * @param {string} taskFolder
@@ -7,6 +7,10 @@ import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync, spawnSync } from "node:child_process";
9
9
  import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
10
+ import {
11
+ listStaleSpineWorktreeBatchIds,
12
+ resolveInProgressSpineBatchId,
13
+ } from "../doctor/stale-worktrees.mjs";
10
14
 
11
15
  const WORKTREE_SETUP_HOOK_TIMEOUT_MS = 120_000;
12
16
 
@@ -145,13 +149,56 @@ export function repairLaneWorktreeGitMetadata({ projectRoot, worktreePath }) {
145
149
  assertLaneWorktreeGitHealthy(worktreePath);
146
150
  }
147
151
 
152
+ /**
153
+ * @param {string} projectRoot
154
+ * @param {string} batchId
155
+ */
156
+ export function batchWorktreeDir(projectRoot, batchId) {
157
+ return path.join(projectRoot, ".worktrees", `spine-${batchId}`);
158
+ }
159
+
148
160
  /**
149
161
  * @param {string} projectRoot
150
162
  * @param {string} batchId
151
163
  * @param {number} laneNumber
152
164
  */
153
165
  export function laneWorktreePath(projectRoot, batchId, laneNumber = 1) {
154
- return path.join(projectRoot, ".worktrees", `spine-${batchId}`, `lane-${laneNumber}`);
166
+ return path.join(batchWorktreeDir(projectRoot, batchId), `lane-${laneNumber}`);
167
+ }
168
+
169
+ /**
170
+ * @param {unknown} batchState
171
+ */
172
+ export function maxLaneNumberFromBatchState(batchState) {
173
+ const lanes = /** @type {{ lanes?: unknown }} */ (batchState)?.lanes;
174
+ if (!Array.isArray(lanes) || lanes.length === 0) return 1;
175
+ let max = 1;
176
+ for (const lane of lanes) {
177
+ if (!lane || typeof lane !== "object") continue;
178
+ const laneNumber = Number(/** @type {{ laneNumber?: number }} */ (lane).laneNumber);
179
+ if (Number.isFinite(laneNumber) && laneNumber > max) {
180
+ max = laneNumber;
181
+ }
182
+ }
183
+ return max;
184
+ }
185
+
186
+ /**
187
+ * Remove `.worktrees/spine-<batchId>/` when it has no remaining entries.
188
+ *
189
+ * @param {string} projectRoot
190
+ * @param {string} batchId
191
+ * @returns {boolean} true when the batch shell dir was removed
192
+ */
193
+ export function removeEmptyBatchWorktreeDir(projectRoot, batchId) {
194
+ const batchDir = batchWorktreeDir(projectRoot, batchId);
195
+ if (!fs.existsSync(batchDir)) return false;
196
+
197
+ const entries = fs.readdirSync(batchDir);
198
+ if (entries.length > 0) return false;
199
+
200
+ fs.rmdirSync(batchDir);
201
+ return true;
155
202
  }
156
203
 
157
204
  /**
@@ -228,6 +275,7 @@ export function removeLaneWorktrees(projectRoot, batchId, maxLaneNumber) {
228
275
  for (let laneNumber = 1; laneNumber <= maxLaneNumber; laneNumber++) {
229
276
  removeLaneWorktree(projectRoot, batchId, laneNumber);
230
277
  }
278
+ removeEmptyBatchWorktreeDir(projectRoot, batchId);
231
279
  }
232
280
 
233
281
  /**
@@ -298,3 +346,84 @@ export function runWorktreeSetupHook({
298
346
 
299
347
  return { ok: true, durationMs };
300
348
  }
349
+
350
+ /**
351
+ * Scan stale spine batch worktree dirs and empty shells eligible for cleanup.
352
+ *
353
+ * @param {string} projectRoot
354
+ * @param {string|null} [activeBatchId]
355
+ * @returns {{ batchIds: string[], emptyShells: string[], danglingWorktrees: string[] }}
356
+ */
357
+ export function scanStaleWorktrees(projectRoot, activeBatchId = null) {
358
+ const inProgressBatchId =
359
+ activeBatchId === undefined ? resolveInProgressSpineBatchId(projectRoot) : activeBatchId;
360
+ const batchIds = listStaleSpineWorktreeBatchIds(projectRoot, inProgressBatchId);
361
+
362
+ /** @type {string[]} */
363
+ const emptyShells = [];
364
+ for (const batchId of batchIds) {
365
+ const batchDir = batchWorktreeDir(projectRoot, batchId);
366
+ if (!fs.existsSync(batchDir)) continue;
367
+ const entries = fs.readdirSync(batchDir);
368
+ if (entries.length === 0) {
369
+ emptyShells.push(batchId);
370
+ }
371
+ }
372
+
373
+ /** @type {string[]} */
374
+ let danglingWorktrees = [];
375
+ try {
376
+ const pruneOutput = git(projectRoot, ["worktree", "prune", "--dry-run", "--verbose"]);
377
+ danglingWorktrees = pruneOutput
378
+ .split(/\r?\n/)
379
+ .map((line) => line.trim())
380
+ .filter((line) => line.length > 0);
381
+ } catch {
382
+ danglingWorktrees = [];
383
+ }
384
+
385
+ return { batchIds, emptyShells, danglingWorktrees };
386
+ }
387
+
388
+ /**
389
+ * Prune empty batch shells and git worktree admin metadata.
390
+ *
391
+ * @param {string} projectRoot
392
+ * @param {object} [options]
393
+ * @param {boolean} [options.dryRun]
394
+ * @param {string|null} [options.activeBatchId]
395
+ * @returns {{ removedShells: string[], prunedWorktrees: string[] }}
396
+ */
397
+ export function pruneStaleWorktrees(projectRoot, { dryRun = false, activeBatchId = null } = {}) {
398
+ const scan = scanStaleWorktrees(projectRoot, activeBatchId);
399
+ /** @type {string[]} */
400
+ const removedShells = [];
401
+
402
+ for (const batchId of scan.emptyShells) {
403
+ if (dryRun) {
404
+ removedShells.push(batchId);
405
+ continue;
406
+ }
407
+ if (removeEmptyBatchWorktreeDir(projectRoot, batchId)) {
408
+ removedShells.push(batchId);
409
+ }
410
+ }
411
+
412
+ /** @type {string[]} */
413
+ let prunedWorktrees = [];
414
+ if (dryRun) {
415
+ prunedWorktrees = scan.danglingWorktrees;
416
+ } else {
417
+ try {
418
+ const pruneOutput = git(projectRoot, ["worktree", "prune", "--verbose"]);
419
+ prunedWorktrees = pruneOutput
420
+ .split(/\r?\n/)
421
+ .map((line) => line.trim())
422
+ .filter((line) => line.length > 0);
423
+ } catch {
424
+ prunedWorktrees = [];
425
+ }
426
+ }
427
+
428
+ return { removedShells, prunedWorktrees };
429
+ }
@@ -14,19 +14,26 @@ import { METRICS_DEFAULTS } from "../defaults.mjs";
14
14
  const HEALTHY_ACTIVE_PHASES = new Set(["planning", "running", "paused"]);
15
15
  const LIMBO_DIAGNOSES = new Set(["limbo_stale", "completed_manual"]);
16
16
  const PI_SESSION_METADATA_PREFIX = ".pi/";
17
+ const PI_SMART_ROUTER_PREFIX = ".pi-smart-router/";
17
18
 
18
19
  function makeCheck(id, ok, message, extra = {}) {
19
20
  return { id, ok, message, ...extra };
20
21
  }
21
22
 
22
23
  /**
23
- * Pi session metadata under `.pi/` is not project source (issue #81).
24
+ * Pi session metadata under `.pi/` and ephemeral `.pi-smart-router/` WAL dirs
25
+ * are not project source (issues #81, v1.10.1 preflight git-clean).
24
26
  *
25
27
  * @param {string} relPath
26
28
  */
27
29
  export function isPiSessionMetadataPath(relPath) {
28
30
  const normalized = String(relPath).replace(/\\/g, "/").replace(/^\.\/+/, "");
29
- return normalized === ".pi" || normalized.startsWith(PI_SESSION_METADATA_PREFIX);
31
+ return (
32
+ normalized === ".pi" ||
33
+ normalized.startsWith(PI_SESSION_METADATA_PREFIX) ||
34
+ normalized === ".pi-smart-router" ||
35
+ normalized.startsWith(PI_SMART_ROUTER_PREFIX)
36
+ );
30
37
  }
31
38
 
32
39
  /**
@@ -155,7 +162,11 @@ export function checkGitClean(ctx) {
155
162
 
156
163
  if (dirtyPaths.length === 0) {
157
164
  if (allDirtyPaths.length > 0) {
158
- return makeCheck("git-clean", true, "working tree clean (.pi/ session metadata ignored)");
165
+ return makeCheck(
166
+ "git-clean",
167
+ true,
168
+ "working tree clean (pi session metadata ignored)",
169
+ );
159
170
  }
160
171
  return makeCheck("git-clean", true, "working tree clean");
161
172
  }