pi-spine 1.2.0 → 1.4.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 (76) hide show
  1. package/README.md +4 -4
  2. package/bin/spine-cli/verify.mjs +6 -0
  3. package/bin/spine-deps.mjs +0 -2
  4. package/bin/spine-plan.mjs +49 -1
  5. package/bin/spine-rules.mjs +0 -2
  6. package/bin/spine-settings.mjs +0 -2
  7. package/bin/spine-worker-runner.mjs +136 -4
  8. package/bin/spine.mjs +2 -5
  9. package/package.json +2 -2
  10. package/skills/create-spine-tasks/SKILL.md +7 -2
  11. package/skills/create-spine-tasks/references/contract-template.md +95 -3
  12. package/src/batch/attached-engine-handoff.mjs +0 -1
  13. package/src/batch/attached-runner.mjs +81 -5
  14. package/src/batch/contract-stub-delivery.mjs +110 -0
  15. package/src/batch/contract-task-start.mjs +204 -0
  16. package/src/batch/contract-verify.mjs +160 -16
  17. package/src/batch/detached-start.mjs +72 -2
  18. package/src/batch/diagnosis-launch-failure.mjs +114 -0
  19. package/src/batch/diagnosis-primary-failure.mjs +89 -0
  20. package/src/batch/diagnosis-retry-limbo.mjs +1 -1
  21. package/src/batch/diagnosis-tail-state.mjs +57 -0
  22. package/src/batch/diagnosis.mjs +22 -114
  23. package/src/batch/engine-lanes/commit.mjs +145 -0
  24. package/src/batch/engine-lanes/merge.mjs +1 -2
  25. package/src/batch/engine-lanes/review.mjs +124 -121
  26. package/src/batch/engine-lanes.mjs +21 -81
  27. package/src/batch/engine.mjs +46 -1
  28. package/src/batch/evidence.mjs +1 -2
  29. package/src/batch/git-exec.mjs +5 -2
  30. package/src/batch/heartbeat.mjs +2 -2
  31. package/src/batch/integrate-assert.mjs +69 -0
  32. package/src/batch/integrate-worktree.mjs +354 -0
  33. package/src/batch/integrate.mjs +195 -102
  34. package/src/batch/journal-rebuild.mjs +158 -3
  35. package/src/batch/journal.mjs +63 -0
  36. package/src/batch/lane-commit.mjs +6 -5
  37. package/src/batch/lane-dirty-check.mjs +513 -0
  38. package/src/batch/limbo-detect.mjs +34 -0
  39. package/src/batch/macro-phase.mjs +76 -0
  40. package/src/batch/metrics.mjs +2 -0
  41. package/src/batch/pause.mjs +18 -7
  42. package/src/batch/post-merge-limbo.mjs +3 -28
  43. package/src/batch/reconcile.mjs +79 -10
  44. package/src/batch/resume-common.mjs +27 -0
  45. package/src/batch/resume-multi-lanes.mjs +11 -0
  46. package/src/batch/resume-multi.mjs +3 -1
  47. package/src/batch/resume.mjs +8 -4
  48. package/src/batch/retry.mjs +41 -10
  49. package/src/batch/review-spawn.mjs +1 -1
  50. package/src/batch/review.mjs +0 -4
  51. package/src/batch/rules-manifest-drift.mjs +43 -2
  52. package/src/batch/sequence-state.mjs +290 -0
  53. package/src/batch/sequence.mjs +113 -51
  54. package/src/batch/state.mjs +16 -0
  55. package/src/batch/worker-host.mjs +14 -5
  56. package/src/cli/deps.mjs +0 -2
  57. package/src/cli/sequence.mjs +14 -1
  58. package/src/cli/settings-set.mjs +33 -3
  59. package/src/config/contract.mjs +10 -0
  60. package/src/config/model-id.mjs +103 -0
  61. package/src/config/spine-init-constants.mjs +1 -0
  62. package/src/config/spine-preflight-lib.mjs +23 -1
  63. package/src/dashboard/public/dashboard.css +8 -0
  64. package/src/dashboard/public/dashboard.js +36 -9
  65. package/src/dashboard/running-tail-state.mjs +31 -0
  66. package/src/dashboard/server.mjs +4 -0
  67. package/src/dashboard/snapshot.mjs +260 -29
  68. package/src/dashboard/view.mjs +112 -2
  69. package/src/doctor/agent-models.mjs +53 -0
  70. package/src/doctor/batch-size-guidance.mjs +30 -2
  71. package/src/doctor/pi-extension-conflict.mjs +169 -0
  72. package/src/doctor/run-doctor-checks.mjs +6 -0
  73. package/src/planner/scope.mjs +5 -1
  74. package/src/tasks/packet/parse-prompt.mjs +31 -1
  75. package/src/tasks/packet/validate-contract.mjs +108 -0
  76. package/src/tasks/packet/validate-prompt.mjs +0 -1
@@ -0,0 +1,513 @@
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 { execFileSync } from "node:child_process";
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
+ /**
355
+ * Split gitignored paths into index-tracked (removable with git rm --cached)
356
+ * and worktree-only (ephemeral artifacts not in the index).
357
+ *
358
+ * @param {string} worktreePath
359
+ * @param {string[]} gitignoredPaths
360
+ * @returns {{ indexTracked: string[], worktreeOnly: string[] }}
361
+ */
362
+ export function classifyGitignoredPaths(worktreePath, gitignoredPaths) {
363
+ if (!Array.isArray(gitignoredPaths) || gitignoredPaths.length === 0) {
364
+ return { indexTracked: [], worktreeOnly: [] };
365
+ }
366
+
367
+ let indexedOutput = "";
368
+ try {
369
+ indexedOutput = execFileSync(
370
+ "git",
371
+ ["ls-files", "--cached", "--", ...gitignoredPaths],
372
+ {
373
+ cwd: worktreePath,
374
+ encoding: "utf-8",
375
+ stdio: ["ignore", "pipe", "pipe"],
376
+ },
377
+ ).trim();
378
+ } catch {
379
+ // If ls-files fails, treat all as worktree-only (safe fallback).
380
+ return { indexTracked: [], worktreeOnly: [...gitignoredPaths] };
381
+ }
382
+
383
+ const indexedSet = new Set(
384
+ indexedOutput ? indexedOutput.split("\n").map((l) => l.trim()).filter(Boolean) : [],
385
+ );
386
+ const indexTracked = [];
387
+ const worktreeOnly = [];
388
+ for (const p of gitignoredPaths) {
389
+ if (indexedSet.has(p)) {
390
+ indexTracked.push(p);
391
+ } else {
392
+ worktreeOnly.push(p);
393
+ }
394
+ }
395
+ return { indexTracked, worktreeOnly };
396
+ }
397
+
398
+ /**
399
+ * Build a remediation message appropriate for the gitignored path classification.
400
+ *
401
+ * @param {string[]} indexTracked
402
+ * @param {string[]} worktreeOnly
403
+ * @returns {string}
404
+ */
405
+ export function formatGitignoredRemediationMessage(indexTracked, worktreeOnly) {
406
+ const allPaths = [...indexTracked, ...worktreeOnly];
407
+ const preview = allPaths.slice(0, 20).join(", ");
408
+ const suffix = allPaths.length > 20 ? "…" : "";
409
+ const prefix = `Lane worktree has gitignored dirty files only (${preview}${suffix})`;
410
+
411
+ if (indexTracked.length > 0 && worktreeOnly.length > 0) {
412
+ return (
413
+ `${prefix} — ` +
414
+ `remove index-tracked paths with git rm --cached on the task branch, ` +
415
+ `then git clean -fdX to remove worktree-only artifacts before resume`
416
+ );
417
+ }
418
+ if (indexTracked.length > 0) {
419
+ return (
420
+ `${prefix} — ` +
421
+ `remove from the index with git rm --cached on the task branch before resume`
422
+ );
423
+ }
424
+ return (
425
+ `${prefix} — ` +
426
+ `worktree-only artifacts (not in git index); clean with git clean -fdX before resume`
427
+ );
428
+ }
429
+
430
+ export function filterOutOfScopeCoveragePorcelain(porcelain, fileScopePaths, ignorePatterns = []) {
431
+ const afterIgnore = filterPorcelain(porcelain, ignorePatterns);
432
+ if (!afterIgnore?.trim()) return "";
433
+
434
+ const kept = [];
435
+ for (const line of afterIgnore.split("\n")) {
436
+ if (!line.trim()) continue;
437
+ const filePath = extractPorcelainPath(line);
438
+ if (filePath && isCoverageArtifactPath(filePath) && !isPathInFileScope(filePath, fileScopePaths)) {
439
+ continue;
440
+ }
441
+ kept.push(line);
442
+ }
443
+ return kept.length === 0 ? "" : kept.join("\n");
444
+ }
445
+
446
+ /**
447
+ * Resolve porcelain for post-lane-commit validation: restore ephemeral coverage, then filter.
448
+ *
449
+ * @param {string} worktreePath
450
+ * @param {object} [options]
451
+ * @param {string[]} [options.fileScopePaths]
452
+ * @param {string[]} [options.ignorePatterns]
453
+ * @param {string} [options.projectRoot]
454
+ * @param {string} [options.porcelain]
455
+ * @returns {string}
456
+ */
457
+ export function resolvePostLaneCommitPorcelain(
458
+ worktreePath,
459
+ { fileScopePaths, ignorePatterns = [], projectRoot, porcelain, config, batchId, laneNumber } = {},
460
+ ) {
461
+ const rawPorcelain = typeof porcelain === "string" ? porcelain : "";
462
+ const dirtyPaths = listPorcelainPaths(rawPorcelain);
463
+ const { restored } = restoreOutOfScopeCoverageArtifacts(worktreePath, fileScopePaths, {
464
+ projectRoot,
465
+ dirtyPaths,
466
+ porcelain: rawPorcelain,
467
+ });
468
+
469
+ let effectivePorcelain = rawPorcelain;
470
+ if (restored.length > 0) {
471
+ const restoredSet = new Set(restored);
472
+ const kept = [];
473
+ for (const line of rawPorcelain.split("\n")) {
474
+ if (!line.trim()) continue;
475
+ const filePath = extractPorcelainPath(line);
476
+ if (filePath && restoredSet.has(filePath)) continue;
477
+ kept.push(line);
478
+ }
479
+ effectivePorcelain = kept.length === 0 ? "" : kept.join("\n");
480
+ }
481
+
482
+ let filtered = filterOutOfScopeCoveragePorcelain(effectivePorcelain, fileScopePaths, ignorePatterns);
483
+ if (!filtered?.trim()) {
484
+ return "";
485
+ }
486
+
487
+ if (isSymlinkOnlyDriftPorcelain(filtered)) {
488
+ const identityRoot = projectRoot ?? worktreePath;
489
+ const effectiveConfig = config ?? loadSpineConfig(identityRoot).config ?? {};
490
+ if (resolveWorktreeSetupHook(identityRoot, effectiveConfig)) {
491
+ repairSetupHookSymlinkDrift(worktreePath, {
492
+ projectRoot: identityRoot,
493
+ config: effectiveConfig,
494
+ batchId,
495
+ laneNumber,
496
+ });
497
+ const refreshedPorcelain = gitPorcelain(worktreePath);
498
+ filtered = filterOutOfScopeCoveragePorcelain(
499
+ refreshedPorcelain,
500
+ fileScopePaths,
501
+ ignorePatterns,
502
+ );
503
+ if (!filtered?.trim()) {
504
+ return "";
505
+ }
506
+ if (isSymlinkOnlyDriftPorcelain(filtered)) {
507
+ return "";
508
+ }
509
+ }
510
+ }
511
+
512
+ return filtered;
513
+ }
@@ -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;