pi-spine 1.2.0 → 1.3.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 (60) hide show
  1. package/README.md +4 -4
  2. package/bin/spine-cli/verify.mjs +3 -0
  3. package/bin/spine-plan.mjs +49 -1
  4. package/bin/spine-worker-runner.mjs +136 -4
  5. package/package.json +1 -1
  6. package/skills/create-spine-tasks/SKILL.md +7 -2
  7. package/skills/create-spine-tasks/references/contract-template.md +95 -3
  8. package/src/batch/attached-runner.mjs +81 -5
  9. package/src/batch/contract-stub-delivery.mjs +110 -0
  10. package/src/batch/contract-task-start.mjs +204 -0
  11. package/src/batch/contract-verify.mjs +55 -8
  12. package/src/batch/detached-start.mjs +72 -2
  13. package/src/batch/diagnosis-launch-failure.mjs +114 -0
  14. package/src/batch/diagnosis-primary-failure.mjs +89 -0
  15. package/src/batch/diagnosis-tail-state.mjs +57 -0
  16. package/src/batch/diagnosis.mjs +22 -113
  17. package/src/batch/engine-lanes/commit.mjs +145 -0
  18. package/src/batch/engine-lanes/review.mjs +67 -87
  19. package/src/batch/engine-lanes.mjs +21 -79
  20. package/src/batch/engine.mjs +46 -0
  21. package/src/batch/heartbeat.mjs +2 -2
  22. package/src/batch/integrate-assert.mjs +69 -0
  23. package/src/batch/integrate-worktree.mjs +354 -0
  24. package/src/batch/integrate.mjs +195 -102
  25. package/src/batch/journal-rebuild.mjs +48 -2
  26. package/src/batch/journal.mjs +63 -0
  27. package/src/batch/lane-dirty-check.mjs +437 -0
  28. package/src/batch/limbo-detect.mjs +34 -0
  29. package/src/batch/macro-phase.mjs +76 -0
  30. package/src/batch/metrics.mjs +2 -0
  31. package/src/batch/pause.mjs +18 -7
  32. package/src/batch/post-merge-limbo.mjs +3 -28
  33. package/src/batch/reconcile.mjs +79 -9
  34. package/src/batch/resume-common.mjs +27 -0
  35. package/src/batch/resume-multi-lanes.mjs +11 -0
  36. package/src/batch/resume-multi.mjs +2 -0
  37. package/src/batch/resume.mjs +8 -1
  38. package/src/batch/retry.mjs +41 -10
  39. package/src/batch/rules-manifest-drift.mjs +43 -2
  40. package/src/batch/sequence-state.mjs +290 -0
  41. package/src/batch/sequence.mjs +113 -51
  42. package/src/batch/state.mjs +16 -0
  43. package/src/batch/worker-host.mjs +1 -0
  44. package/src/cli/sequence.mjs +14 -1
  45. package/src/cli/settings-set.mjs +33 -3
  46. package/src/config/model-id.mjs +103 -0
  47. package/src/config/spine-init-constants.mjs +1 -0
  48. package/src/config/spine-preflight-lib.mjs +23 -1
  49. package/src/dashboard/public/dashboard.js +14 -3
  50. package/src/dashboard/running-tail-state.mjs +31 -0
  51. package/src/dashboard/server.mjs +4 -0
  52. package/src/dashboard/snapshot.mjs +260 -28
  53. package/src/dashboard/view.mjs +112 -2
  54. package/src/doctor/agent-models.mjs +53 -0
  55. package/src/doctor/batch-size-guidance.mjs +30 -2
  56. package/src/doctor/pi-extension-conflict.mjs +169 -0
  57. package/src/doctor/run-doctor-checks.mjs +6 -0
  58. package/src/planner/scope.mjs +5 -1
  59. package/src/tasks/packet/parse-prompt.mjs +31 -1
  60. package/src/tasks/packet/validate-contract.mjs +108 -0
@@ -0,0 +1,437 @@
1
+ /**
2
+ * Post-lane-commit dirty worktree hygiene (SP-427 / #73).
3
+ * Coverage artifacts regenerated by npm test are ephemeral when not in task file scope.
4
+ */
5
+
6
+ import path from "node:path";
7
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
8
+ import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
9
+ import { filterPorcelain, gitPorcelain } from "./lane-commit.mjs";
10
+ import { gitExec } from "./git-exec.mjs";
11
+ import { runWorktreeSetupHook } from "./worktree.mjs";
12
+
13
+ /**
14
+ * Path segments that identify generated coverage report artifacts.
15
+ * Matches extension/coverage, root coverage dirs, and nested coverage paths.
16
+ */
17
+ export const COVERAGE_ARTIFACT_MARKERS = ["/coverage/", "coverage/"];
18
+
19
+ /**
20
+ * @param {string} filePath
21
+ * @returns {boolean}
22
+ */
23
+ export function isCoverageArtifactPath(filePath) {
24
+ if (!filePath || typeof filePath !== "string") return false;
25
+ const normalized = filePath.replace(/\\/g, "/");
26
+ return COVERAGE_ARTIFACT_MARKERS.some(
27
+ (marker) =>
28
+ normalized === marker.slice(0, -1) ||
29
+ normalized.startsWith(marker) ||
30
+ normalized.includes(marker),
31
+ );
32
+ }
33
+
34
+ /**
35
+ * @param {string} filePath
36
+ * @param {string[]} [fileScopePaths]
37
+ * @returns {boolean}
38
+ */
39
+ export function isPathInFileScope(filePath, fileScopePaths) {
40
+ if (!filePath || !Array.isArray(fileScopePaths) || fileScopePaths.length === 0) {
41
+ return false;
42
+ }
43
+
44
+ const normalizedPath = filePath.replace(/\\/g, "/");
45
+ const scopePrefixes = [];
46
+ for (const rel of fileScopePaths) {
47
+ if (!rel || typeof rel !== "string") continue;
48
+ const normalized = rel.replace(/\\/g, "/");
49
+ scopePrefixes.push(normalized.endsWith("/") ? normalized : `${normalized}/`);
50
+ scopePrefixes.push(normalized);
51
+ }
52
+
53
+ return scopePrefixes.some(
54
+ (prefix) => normalizedPath === prefix || normalizedPath.startsWith(prefix),
55
+ );
56
+ }
57
+
58
+ /**
59
+ * @param {string} line
60
+ * @returns {string | null}
61
+ */
62
+ function extractPorcelainPath(line) {
63
+ if (!line.trim()) return null;
64
+ let filePath = line.length > 2 && line[2] === " " ? line.slice(3) : line.slice(2);
65
+ filePath = filePath.trim();
66
+ if (!filePath) return null;
67
+ if (filePath.includes(" -> ")) {
68
+ return filePath.split(" -> ").pop()?.trim() ?? null;
69
+ }
70
+ return filePath;
71
+ }
72
+
73
+ /**
74
+ * @param {string} porcelain
75
+ * @returns {string[]}
76
+ */
77
+ export function listPorcelainPaths(porcelain) {
78
+ if (!porcelain?.trim()) return [];
79
+ return porcelain
80
+ .split("\n")
81
+ .map((line) => extractPorcelainPath(line))
82
+ .filter((entry) => Boolean(entry));
83
+ }
84
+
85
+ /**
86
+ * @param {string[]} dirtyPaths
87
+ * @param {string[]} [fileScopePaths]
88
+ * @returns {string[]}
89
+ */
90
+ export function listOutOfScopeCoveragePaths(dirtyPaths, fileScopePaths) {
91
+ if (!Array.isArray(dirtyPaths) || dirtyPaths.length === 0) return [];
92
+ return dirtyPaths.filter(
93
+ (filePath) => isCoverageArtifactPath(filePath) && !isPathInFileScope(filePath, fileScopePaths),
94
+ );
95
+ }
96
+
97
+ /**
98
+ * @param {string} filePath
99
+ * @returns {string | null}
100
+ */
101
+ function coverageRootForPath(filePath) {
102
+ const normalized = filePath.replace(/\\/g, "/");
103
+ const markerIdx = normalized.indexOf("/coverage/");
104
+ if (markerIdx >= 0) {
105
+ return normalized.slice(0, markerIdx + "/coverage".length);
106
+ }
107
+ if (normalized === "coverage" || normalized.startsWith("coverage/")) {
108
+ return "coverage";
109
+ }
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * @param {string[]} filePaths
115
+ * @param {string[]} [fileScopePaths]
116
+ * @returns {string[]}
117
+ */
118
+ export function listOutOfScopeCoverageRoots(filePaths, fileScopePaths) {
119
+ const roots = new Set();
120
+ for (const filePath of filePaths) {
121
+ if (!isCoverageArtifactPath(filePath) || isPathInFileScope(filePath, fileScopePaths)) {
122
+ continue;
123
+ }
124
+ const root = coverageRootForPath(filePath);
125
+ if (root && !isPathInFileScope(root, fileScopePaths)) {
126
+ roots.add(root);
127
+ }
128
+ }
129
+ return [...roots].sort();
130
+ }
131
+
132
+ /**
133
+ * Restore tracked and remove untracked out-of-scope coverage before lane commit.
134
+ *
135
+ * @param {string} worktreePath
136
+ * @param {string[]} [fileScopePaths]
137
+ * @param {{ projectRoot?: string, porcelain?: string }} [options]
138
+ * @returns {{ restored: string[], cleanedRoots: string[] }}
139
+ */
140
+ export function sanitizeOutOfScopeCoverageBeforeLaneCommit(
141
+ worktreePath,
142
+ fileScopePaths,
143
+ { projectRoot, porcelain } = {},
144
+ ) {
145
+ const identityRoot = projectRoot ?? worktreePath;
146
+ const rawPorcelain = porcelain ?? "";
147
+ const dirtyPaths = listPorcelainPaths(rawPorcelain);
148
+ const { restored } = restoreOutOfScopeCoverageArtifacts(worktreePath, fileScopePaths, {
149
+ projectRoot: identityRoot,
150
+ dirtyPaths,
151
+ porcelain: rawPorcelain,
152
+ });
153
+
154
+ const cleanedRoots = listOutOfScopeCoverageRoots(dirtyPaths, fileScopePaths);
155
+ for (const root of cleanedRoots) {
156
+ gitExec(worktreePath, ["clean", "-fd", "--", root], {
157
+ projectRoot: identityRoot,
158
+ throwOnError: false,
159
+ });
160
+ }
161
+
162
+ return { restored, cleanedRoots };
163
+ }
164
+
165
+ /**
166
+ * @param {string} porcelain
167
+ * @returns {Set<string>}
168
+ */
169
+ function listTrackedPorcelainPaths(porcelain) {
170
+ const tracked = new Set();
171
+ if (!porcelain?.trim()) return tracked;
172
+ for (const line of porcelain.split("\n")) {
173
+ if (!line.trim()) continue;
174
+ const status = line.slice(0, 2);
175
+ if (status === "??" || status === "!!") continue;
176
+ const filePath = extractPorcelainPath(line);
177
+ if (filePath) tracked.add(filePath);
178
+ }
179
+ return tracked;
180
+ }
181
+
182
+ /**
183
+ * Restore tracked coverage artifacts that are outside task file scope.
184
+ *
185
+ * @param {string} worktreePath
186
+ * @param {string[]} [fileScopePaths]
187
+ * @param {{ projectRoot?: string, dirtyPaths?: string[], porcelain?: string }} [options]
188
+ * @returns {{ restored: string[] }}
189
+ */
190
+ export function restoreOutOfScopeCoverageArtifacts(
191
+ worktreePath,
192
+ fileScopePaths,
193
+ { projectRoot, dirtyPaths, porcelain } = {},
194
+ ) {
195
+ const identityRoot = projectRoot ?? worktreePath;
196
+ const candidates = Array.isArray(dirtyPaths) ? dirtyPaths : [];
197
+ const outOfScope = listOutOfScopeCoveragePaths(candidates, fileScopePaths);
198
+ if (outOfScope.length === 0) {
199
+ return { restored: [] };
200
+ }
201
+
202
+ const trackedPaths = listTrackedPorcelainPaths(porcelain ?? "");
203
+ const toRestore = trackedPaths.size > 0
204
+ ? outOfScope.filter((filePath) => trackedPaths.has(filePath))
205
+ : outOfScope;
206
+ if (toRestore.length === 0) {
207
+ return { restored: [] };
208
+ }
209
+
210
+ gitExec(
211
+ worktreePath,
212
+ ["restore", "--source=HEAD", "--worktree", "--", ...toRestore],
213
+ { projectRoot: identityRoot },
214
+ );
215
+ return { restored: toRestore };
216
+ }
217
+
218
+ /**
219
+ * Drop out-of-scope coverage artifact lines from porcelain after ignore patterns.
220
+ *
221
+ * @param {string} porcelain
222
+ * @param {string[]} [fileScopePaths]
223
+ * @param {string[]} [ignorePatterns]
224
+ * @returns {string}
225
+ */
226
+ /**
227
+ * @param {string} line
228
+ * @returns {boolean}
229
+ */
230
+ export function isSymlinkDeletionPorcelainLine(line) {
231
+ if (!line?.trim() || line.length < 3) return false;
232
+ const indexStatus = line[0];
233
+ const worktreeStatus = line[1];
234
+ const disallowed = new Set(["M", "A", "R", "C", "U"]);
235
+ if (disallowed.has(indexStatus) || disallowed.has(worktreeStatus)) {
236
+ return false;
237
+ }
238
+ return indexStatus === "D" || worktreeStatus === "D";
239
+ }
240
+
241
+ /**
242
+ * @param {string} line
243
+ * @returns {boolean}
244
+ */
245
+ export function isWorktreeDeletionPorcelainLine(line) {
246
+ return isSymlinkDeletionPorcelainLine(line) && line[1] === "D";
247
+ }
248
+
249
+ /**
250
+ * True when every porcelain line is a symlink/hook deletion (` D`, `D `, or `DD`).
251
+ *
252
+ * @param {string} porcelain
253
+ * @returns {boolean}
254
+ */
255
+ export function isSymlinkOnlyDriftPorcelain(porcelain) {
256
+ if (!porcelain?.trim()) return false;
257
+ for (const line of porcelain.split("\n")) {
258
+ if (!line.trim()) continue;
259
+ if (!isSymlinkDeletionPorcelainLine(line)) return false;
260
+ }
261
+ return true;
262
+ }
263
+
264
+ /**
265
+ * @param {string} worktreePath
266
+ * @returns {{ batchId: string, laneNumber: number } | null}
267
+ */
268
+ export function parseLaneWorktreeIdentity(worktreePath) {
269
+ const normalized = worktreePath.replace(/\\/g, "/");
270
+ const match = normalized.match(/\/\.worktrees\/spine-([^/]+)\/lane-(\d+)\/?$/);
271
+ if (!match) return null;
272
+ return { batchId: match[1], laneNumber: Number(match[2]) };
273
+ }
274
+
275
+ /**
276
+ * @param {string} porcelain
277
+ * @returns {string}
278
+ */
279
+ export function filterSetupHookSymlinkDriftPorcelain(porcelain) {
280
+ if (!porcelain?.trim() || !isSymlinkOnlyDriftPorcelain(porcelain)) {
281
+ return porcelain ?? "";
282
+ }
283
+ return "";
284
+ }
285
+
286
+ /**
287
+ * Re-run worktreeSetupHook to recreate hook-managed symlinks after drift.
288
+ *
289
+ * @param {string} worktreePath
290
+ * @param {{ projectRoot: string, config?: object, batchId?: string, laneNumber?: number }} options
291
+ * @returns {{ repaired: boolean, reason?: string }}
292
+ */
293
+ export function repairSetupHookSymlinkDrift(worktreePath, { projectRoot, config, batchId, laneNumber }) {
294
+ const effectiveConfig = config ?? loadSpineConfig(projectRoot).config ?? {};
295
+ const hookPath = resolveWorktreeSetupHook(projectRoot, effectiveConfig);
296
+ if (!hookPath) {
297
+ return { repaired: false, reason: "no_hook" };
298
+ }
299
+
300
+ const identity = parseLaneWorktreeIdentity(worktreePath);
301
+ const effectiveBatchId = batchId ?? identity?.batchId ?? "unknown";
302
+ const effectiveLaneNumber = laneNumber ?? identity?.laneNumber ?? 1;
303
+
304
+ try {
305
+ runWorktreeSetupHook({
306
+ projectRoot,
307
+ worktreePath,
308
+ batchId: effectiveBatchId,
309
+ laneNumber: effectiveLaneNumber,
310
+ config: effectiveConfig,
311
+ });
312
+ return { repaired: true };
313
+ } catch {
314
+ return { repaired: false, reason: "hook_failed" };
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Repair or ignore symlink-only deletions from worktreeSetupHook paths (#87 / SP-429).
320
+ *
321
+ * @param {string} worktreePath
322
+ * @param {string} porcelain
323
+ * @param {{ projectRoot?: string, config?: object, batchId?: string, laneNumber?: number }} [options]
324
+ * @returns {string}
325
+ */
326
+ export function resolveSetupHookSymlinkDriftPorcelain(
327
+ worktreePath,
328
+ porcelain,
329
+ { projectRoot, config, batchId, laneNumber } = {},
330
+ ) {
331
+ if (!porcelain?.trim() || !isSymlinkOnlyDriftPorcelain(porcelain)) {
332
+ return porcelain ?? "";
333
+ }
334
+
335
+ const identityRoot = projectRoot ?? worktreePath;
336
+ const effectiveConfig = config ?? loadSpineConfig(identityRoot).config ?? {};
337
+ if (!resolveWorktreeSetupHook(identityRoot, effectiveConfig)) {
338
+ return porcelain;
339
+ }
340
+
341
+ const repair = repairSetupHookSymlinkDrift(worktreePath, {
342
+ projectRoot: identityRoot,
343
+ config: effectiveConfig,
344
+ batchId,
345
+ laneNumber,
346
+ });
347
+ if (repair.repaired) {
348
+ return porcelain;
349
+ }
350
+
351
+ return filterSetupHookSymlinkDriftPorcelain(porcelain);
352
+ }
353
+
354
+ export function filterOutOfScopeCoveragePorcelain(porcelain, fileScopePaths, ignorePatterns = []) {
355
+ const afterIgnore = filterPorcelain(porcelain, ignorePatterns);
356
+ if (!afterIgnore?.trim()) return "";
357
+
358
+ const kept = [];
359
+ for (const line of afterIgnore.split("\n")) {
360
+ if (!line.trim()) continue;
361
+ const filePath = extractPorcelainPath(line);
362
+ if (filePath && isCoverageArtifactPath(filePath) && !isPathInFileScope(filePath, fileScopePaths)) {
363
+ continue;
364
+ }
365
+ kept.push(line);
366
+ }
367
+ return kept.length === 0 ? "" : kept.join("\n");
368
+ }
369
+
370
+ /**
371
+ * Resolve porcelain for post-lane-commit validation: restore ephemeral coverage, then filter.
372
+ *
373
+ * @param {string} worktreePath
374
+ * @param {object} [options]
375
+ * @param {string[]} [options.fileScopePaths]
376
+ * @param {string[]} [options.ignorePatterns]
377
+ * @param {string} [options.projectRoot]
378
+ * @param {string} [options.porcelain]
379
+ * @returns {string}
380
+ */
381
+ export function resolvePostLaneCommitPorcelain(
382
+ worktreePath,
383
+ { fileScopePaths, ignorePatterns = [], projectRoot, porcelain, config, batchId, laneNumber } = {},
384
+ ) {
385
+ const rawPorcelain = typeof porcelain === "string" ? porcelain : "";
386
+ const dirtyPaths = listPorcelainPaths(rawPorcelain);
387
+ const { restored } = restoreOutOfScopeCoverageArtifacts(worktreePath, fileScopePaths, {
388
+ projectRoot,
389
+ dirtyPaths,
390
+ porcelain: rawPorcelain,
391
+ });
392
+
393
+ let effectivePorcelain = rawPorcelain;
394
+ if (restored.length > 0) {
395
+ const restoredSet = new Set(restored);
396
+ const kept = [];
397
+ for (const line of rawPorcelain.split("\n")) {
398
+ if (!line.trim()) continue;
399
+ const filePath = extractPorcelainPath(line);
400
+ if (filePath && restoredSet.has(filePath)) continue;
401
+ kept.push(line);
402
+ }
403
+ effectivePorcelain = kept.length === 0 ? "" : kept.join("\n");
404
+ }
405
+
406
+ let filtered = filterOutOfScopeCoveragePorcelain(effectivePorcelain, fileScopePaths, ignorePatterns);
407
+ if (!filtered?.trim()) {
408
+ return "";
409
+ }
410
+
411
+ if (isSymlinkOnlyDriftPorcelain(filtered)) {
412
+ const identityRoot = projectRoot ?? worktreePath;
413
+ const effectiveConfig = config ?? loadSpineConfig(identityRoot).config ?? {};
414
+ if (resolveWorktreeSetupHook(identityRoot, effectiveConfig)) {
415
+ repairSetupHookSymlinkDrift(worktreePath, {
416
+ projectRoot: identityRoot,
417
+ config: effectiveConfig,
418
+ batchId,
419
+ laneNumber,
420
+ });
421
+ const refreshedPorcelain = gitPorcelain(worktreePath);
422
+ filtered = filterOutOfScopeCoveragePorcelain(
423
+ refreshedPorcelain,
424
+ fileScopePaths,
425
+ ignorePatterns,
426
+ );
427
+ if (!filtered?.trim()) {
428
+ return "";
429
+ }
430
+ if (isSymlinkOnlyDriftPorcelain(filtered)) {
431
+ return "";
432
+ }
433
+ }
434
+ }
435
+
436
+ return filtered;
437
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Post-merge limbo predicates — pure state readers (leaf module, SP-424 / #83-A).
3
+ */
4
+
5
+ /**
6
+ * Whether batch state matches post-merge limbo: tasks and merges succeeded,
7
+ * phase still running, orch branch exists but not merged to base.
8
+ *
9
+ * @param {object|null|undefined} state
10
+ * @param {object} [git]
11
+ */
12
+ export function isPostMergeLimbo(state, git = {}) {
13
+ if (!state || typeof state !== "object") return false;
14
+ const phase = String(state.phase ?? "");
15
+ if (phase !== "running" || state.endedAt != null) return false;
16
+
17
+ const tasks = state.tasks ?? [];
18
+ if (tasks.length === 0) return false;
19
+ const allSucceeded = tasks.every((task) => String(task?.status ?? "") === "succeeded");
20
+ if (!allSucceeded) return false;
21
+
22
+ const mergeResults = state.mergeResults ?? [];
23
+ if (
24
+ mergeResults.length === 0 ||
25
+ !mergeResults.every((entry) => String(entry?.status ?? "") === "succeeded")
26
+ ) {
27
+ return false;
28
+ }
29
+
30
+ if (git.orchMergedToBase) return false;
31
+ if (git.orchBranchExists === false) return false;
32
+
33
+ return true;
34
+ }
@@ -148,6 +148,37 @@ function hasOpenIntegrate(journalEvents) {
148
148
  return lastIntegrateIdx >= 0 && lastIntegrateType === "integrate.started";
149
149
  }
150
150
 
151
+ const MERGE_JOURNAL_TYPES = new Set([
152
+ "batch.merge_started",
153
+ "batch.merge_completed",
154
+ "batch.merge_blocked",
155
+ ]);
156
+
157
+ const LAND_LOOP_JOURNAL_TYPES = new Set([
158
+ "gate.opened",
159
+ "gate.evidence_collecting",
160
+ "gate.evidence_completed",
161
+ "batch.land_loop_finalized",
162
+ ]);
163
+
164
+ /**
165
+ * @param {object[]} journalEvents
166
+ * @returns {boolean}
167
+ */
168
+ function hasJournalMergeActivity(journalEvents) {
169
+ if (!Array.isArray(journalEvents) || journalEvents.length === 0) return false;
170
+ return journalEvents.some((event) => MERGE_JOURNAL_TYPES.has(event.type));
171
+ }
172
+
173
+ /**
174
+ * @param {object[]} journalEvents
175
+ * @returns {boolean}
176
+ */
177
+ function hasJournalLandLoopActivity(journalEvents) {
178
+ if (!Array.isArray(journalEvents) || journalEvents.length === 0) return false;
179
+ return journalEvents.some((event) => LAND_LOOP_JOURNAL_TYPES.has(event.type));
180
+ }
181
+
151
182
  /**
152
183
  * @param {object|null|undefined} gateRecord
153
184
  * @param {boolean} postMergeLimbo
@@ -157,9 +188,46 @@ function hasOpenIntegrate(journalEvents) {
157
188
  function isGatingState(gateRecord, postMergeLimbo, diagnosis) {
158
189
  if (gateRecord && gateRecord.status === "pending") return true;
159
190
  if (postMergeLimbo && diagnosis === "needs_integrate") return true;
191
+ if (postMergeLimbo && diagnosis === "running") return true;
160
192
  return false;
161
193
  }
162
194
 
195
+ /**
196
+ * @param {DeriveMacroPhaseInput} input
197
+ * @returns {MacroPhase|null}
198
+ */
199
+ function deriveRunningTailMacroPhase(input) {
200
+ const diagnosis = input.diagnosis ?? null;
201
+ const batchPhase = input.batchPhase ?? null;
202
+ if (diagnosis !== "running") return null;
203
+ if (batchPhase !== "running" && batchPhase !== "merging") return null;
204
+ if (input.hasActiveWorkerTasks === true) return null;
205
+
206
+ const journalEvents = input.journalEvents ?? [];
207
+ if (hasJournalLandLoopActivity(journalEvents)) {
208
+ return "gating";
209
+ }
210
+
211
+ const mergeResults = input.mergeResults;
212
+ if (Array.isArray(mergeResults) && mergeResults.length > 0) {
213
+ return "merging";
214
+ }
215
+
216
+ if (hasJournalMergeActivity(journalEvents)) {
217
+ return "merging";
218
+ }
219
+
220
+ if (input.postMergeLimbo === true) {
221
+ return "gating";
222
+ }
223
+
224
+ if (input.allTasksTerminalSuccess === true && input.mergeResultsEmpty !== false) {
225
+ return "merging";
226
+ }
227
+
228
+ return null;
229
+ }
230
+
163
231
  /**
164
232
  * @typedef {object} DeriveMacroPhaseInput
165
233
  * @property {string|null|undefined} diagnosis
@@ -169,6 +237,9 @@ function isGatingState(gateRecord, postMergeLimbo, diagnosis) {
169
237
  * @property {object|null|undefined} [gateRecord]
170
238
  * @property {boolean} [postMergeLimbo]
171
239
  * @property {object[]} [journalEvents]
240
+ * @property {boolean} [hasActiveWorkerTasks]
241
+ * @property {boolean} [allTasksTerminalSuccess]
242
+ * @property {boolean} [mergeResultsEmpty]
172
243
  */
173
244
 
174
245
  /**
@@ -222,5 +293,10 @@ export function deriveMacroPhase(input) {
222
293
  return "planning";
223
294
  }
224
295
 
296
+ const runningTailPhase = deriveRunningTailMacroPhase(input);
297
+ if (runningTailPhase != null) {
298
+ return runningTailPhase;
299
+ }
300
+
225
301
  return "executing";
226
302
  }
@@ -164,6 +164,8 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder,
164
164
  record.durationMs = Math.max(0, endedMs - startedMs);
165
165
  }
166
166
  if (task.exitReason) record.exitReason = task.exitReason;
167
+ if (task.exitReason === "contract_failed") record.failureKind = "contract";
168
+ if (task.exitReason === "review_exhausted") record.failureKind = "reviewer";
167
169
  if (reviewLevel > 0) record.reviewLevel = reviewLevel;
168
170
  if (task.finalVerdict != null) record.finalVerdict = task.finalVerdict;
169
171
  if (task.finalAttempts != null) record.finalAttempts = task.finalAttempts;
@@ -80,8 +80,9 @@ export function enforceOperatorPauseOnDisk(projectRoot) {
80
80
  const loaded = loadSpineBatchState(projectRoot);
81
81
  if (!loaded.raw) return false;
82
82
  const batchId = String(loaded.raw.batchId ?? "");
83
- if (!batchId || !isOperatorPauseActive(projectRoot, batchId)) return false;
83
+ if (!batchId) return false;
84
84
  if (loaded.raw.phase === "paused") return true;
85
+ if (!isOperatorPauseActive(projectRoot, batchId)) return false;
85
86
  loaded.raw.phase = "paused";
86
87
  saveSpineBatchState(projectRoot, loaded.raw, { bypassWriteGuard: true });
87
88
  return true;
@@ -124,10 +125,14 @@ export async function waitForPauseConfirmation({
124
125
  sleepFn = defaultSleep,
125
126
  }) {
126
127
  const deadline = Date.now() + confirmGraceMs;
128
+ let sawPauseOnDisk = false;
129
+ let sawRunningAfterPauseOnDisk = false;
127
130
  while (Date.now() < deadline) {
128
131
  const currentPhase = String(loadSpineBatchState(projectRoot).raw?.phase ?? "");
129
132
  if (currentPhase === "paused") {
130
- return true;
133
+ sawPauseOnDisk = true;
134
+ } else if (sawPauseOnDisk && currentPhase === "running") {
135
+ sawRunningAfterPauseOnDisk = true;
131
136
  }
132
137
  const remaining = deadline - Date.now();
133
138
  if (remaining <= 0) {
@@ -135,7 +140,8 @@ export async function waitForPauseConfirmation({
135
140
  }
136
141
  await sleepFn(Math.min(pollIntervalMs, remaining));
137
142
  }
138
- return String(loadSpineBatchState(projectRoot).raw?.phase ?? "") === "paused";
143
+ const finalPhase = String(loadSpineBatchState(projectRoot).raw?.phase ?? "");
144
+ return finalPhase === "paused" && !sawRunningAfterPauseOnDisk;
139
145
  }
140
146
 
141
147
  /**
@@ -176,8 +182,7 @@ export async function pauseBatch({
176
182
  enginePid != null && enginePid !== process.pid && isProcessAlive(enginePid);
177
183
 
178
184
  state.phase = "paused";
179
- saveSpineBatchState(projectRoot, state);
180
- recordResumePhaseTransition(projectRoot, batchId, fromPhase, "paused");
185
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
181
186
 
182
187
  if (attachedEngineAlive) {
183
188
  const confirmed = await waitForPauseConfirmation({
@@ -190,6 +195,10 @@ export async function pauseBatch({
190
195
  if (!confirmed) {
191
196
  const current = loadSpineBatchState(projectRoot).raw;
192
197
  const currentPhase = String(current?.phase ?? "unknown");
198
+ if (current) {
199
+ current.phase = fromPhase;
200
+ saveSpineBatchState(projectRoot, current, { bypassWriteGuard: true });
201
+ }
193
202
  appendJournalEvent(projectRoot, batchId, "batch.pause_failed", {
194
203
  fromPhase,
195
204
  enginePid,
@@ -198,7 +207,7 @@ export async function pauseBatch({
198
207
  });
199
208
  const output =
200
209
  `Pause not confirmed: batch-state phase is still "${currentPhase}" after ${confirmGraceMs}ms.\n` +
201
- `Journal recorded batch.paused but attached engine (PID ${enginePid}) did not persist phase: paused.\n` +
210
+ `Attached engine (PID ${enginePid}) did not persist phase: paused — batch.paused was not recorded.\n` +
202
211
  "Stop the attached engine or wait for the current step to finish, then run spine batch pause again.\n" +
203
212
  "spine batch retry is blocked while phase is running — retry only after phase is paused.\n";
204
213
  return {
@@ -207,12 +216,14 @@ export async function pauseBatch({
207
216
  error: "pause_not_confirmed",
208
217
  output,
209
218
  batchId,
210
- phase: currentPhase,
219
+ phase: fromPhase,
211
220
  enginePid,
212
221
  };
213
222
  }
214
223
  }
215
224
 
225
+ recordResumePhaseTransition(projectRoot, batchId, fromPhase, "paused");
226
+
216
227
  return {
217
228
  ok: true,
218
229
  exitCode: 0,