pi-spine 2.1.0 → 2.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 (49) hide show
  1. package/bin/spine-batch.mjs +74 -5
  2. package/bin/spine-cli/verify.mjs +2 -18
  3. package/package.json +1 -1
  4. package/src/batch/attached-runner-promote.mjs +370 -0
  5. package/src/batch/attached-runner-reconcile.mjs +291 -0
  6. package/src/batch/attached-runner.mjs +24 -634
  7. package/src/batch/batch-guards.mjs +69 -0
  8. package/src/batch/contract-exec.mjs +483 -0
  9. package/src/batch/contract-parse.mjs +243 -0
  10. package/src/batch/contract-verify.mjs +32 -707
  11. package/src/batch/detached-diagnostics.mjs +255 -0
  12. package/src/batch/detached-run.mjs +326 -0
  13. package/src/batch/detached-start.mjs +18 -894
  14. package/src/batch/detached-wait.mjs +346 -0
  15. package/src/batch/engine-lanes/merge.mjs +25 -0
  16. package/src/batch/engine.mjs +8 -67
  17. package/src/batch/integrate-git.mjs +21 -0
  18. package/src/batch/integrate.mjs +5 -15
  19. package/src/batch/journal-rebuild-structural.mjs +352 -0
  20. package/src/batch/journal-rebuild.mjs +94 -347
  21. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  22. package/src/batch/lane-dirty-check-git.mjs +298 -0
  23. package/src/batch/lane-dirty-check.mjs +31 -297
  24. package/src/batch/reconcile-batch.mjs +483 -0
  25. package/src/batch/reconcile-classify.mjs +433 -0
  26. package/src/batch/reconcile-diagnosis.mjs +459 -0
  27. package/src/batch/reconcile-light-cache.mjs +61 -0
  28. package/src/batch/reconcile-orphan.mjs +198 -0
  29. package/src/batch/reconcile.mjs +19 -1693
  30. package/src/batch/resume-multi-lanes.mjs +44 -149
  31. package/src/batch/resume-multi-queue.mjs +159 -0
  32. package/src/batch/resume-single-validate.mjs +25 -0
  33. package/src/batch/resume.mjs +3 -20
  34. package/src/batch/review-artifacts.mjs +419 -0
  35. package/src/batch/review-step-run.mjs +383 -0
  36. package/src/batch/review-step.mjs +451 -0
  37. package/src/batch/review.mjs +32 -1199
  38. package/src/batch/salvage-batch-list.mjs +291 -0
  39. package/src/batch/salvage-batch.mjs +417 -0
  40. package/src/batch/sequence-plan.mjs +234 -0
  41. package/src/batch/sequence-run.mjs +418 -0
  42. package/src/batch/sequence-wait.mjs +167 -0
  43. package/src/batch/sequence.mjs +22 -783
  44. package/src/batch/state-guards.mjs +284 -0
  45. package/src/batch/state-io.mjs +135 -0
  46. package/src/batch/state.mjs +27 -396
  47. package/src/batch/worker-heartbeat.mjs +375 -0
  48. package/src/batch/worker-host.mjs +50 -541
  49. package/src/batch/worker-spawn.mjs +315 -0
@@ -0,0 +1,361 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Lane-commit dirty hygiene: coverage restore/clean, gitignored artifact
4
+ * sanitization, and post-lane-commit porcelain resolution (SP-601 / #117).
5
+ */
6
+
7
+ import { execFileSync } from "node:child_process";
8
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
+ import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
10
+ import { gitPorcelain } from "./lane-commit.mjs";
11
+ import { gitExec } from "./git-exec.mjs";
12
+ import {
13
+ extractPorcelainPath,
14
+ filterOutOfScopeCoveragePorcelain,
15
+ isSymlinkOnlyDriftPorcelain,
16
+ listOutOfScopeCoveragePaths,
17
+ listOutOfScopeCoverageRoots,
18
+ listPorcelainPaths,
19
+ listTrackedPorcelainPaths,
20
+ repairSetupHookSymlinkDrift,
21
+ } from "./lane-dirty-check-git.mjs";
22
+
23
+ /**
24
+ * Path segments for gitignored build artifacts that npm test and similar tools
25
+ * regenerate in lane worktrees (SP-471 / #95).
26
+ */
27
+ export const GITIGNORED_ARTIFACT_MARKERS = [
28
+ "/node_modules/",
29
+ "node_modules/",
30
+ "/coverage/",
31
+ "coverage/",
32
+ "/__pycache__/",
33
+ "__pycache__/",
34
+ "/graphify-out/",
35
+ "graphify-out/",
36
+ "/.review/",
37
+ ".review/",
38
+ "/.spine/runtime/",
39
+ ".spine/runtime/",
40
+ ];
41
+
42
+ /**
43
+ * Restore tracked and remove untracked out-of-scope coverage before lane commit.
44
+ *
45
+ * @param {string} worktreePath
46
+ * @param {string[]} [fileScopePaths]
47
+ * @param {{ projectRoot?: string, porcelain?: string }} [options]
48
+ * @returns {{ restored: string[], cleanedRoots: string[] }}
49
+ */
50
+ export function sanitizeOutOfScopeCoverageBeforeLaneCommit(
51
+ worktreePath,
52
+ fileScopePaths,
53
+ { projectRoot, porcelain } = {},
54
+ ) {
55
+ const identityRoot = projectRoot ?? worktreePath;
56
+ const rawPorcelain = porcelain ?? "";
57
+ const dirtyPaths = listPorcelainPaths(rawPorcelain);
58
+ const { restored } = restoreOutOfScopeCoverageArtifacts(worktreePath, fileScopePaths, {
59
+ projectRoot: identityRoot,
60
+ dirtyPaths,
61
+ porcelain: rawPorcelain,
62
+ });
63
+
64
+ const cleanedRoots = listOutOfScopeCoverageRoots(dirtyPaths, fileScopePaths);
65
+ for (const root of cleanedRoots) {
66
+ gitExec(worktreePath, ["clean", "-fd", "--", root], {
67
+ projectRoot: identityRoot,
68
+ throwOnError: false,
69
+ });
70
+ }
71
+
72
+ return { restored, cleanedRoots };
73
+ }
74
+
75
+ /**
76
+ * Restore tracked coverage artifacts that are outside task file scope.
77
+ *
78
+ * @param {string} worktreePath
79
+ * @param {string[]} [fileScopePaths]
80
+ * @param {{ projectRoot?: string, dirtyPaths?: string[], porcelain?: string }} [options]
81
+ * @returns {{ restored: string[] }}
82
+ */
83
+ export function restoreOutOfScopeCoverageArtifacts(
84
+ worktreePath,
85
+ fileScopePaths,
86
+ { projectRoot, dirtyPaths, porcelain } = {},
87
+ ) {
88
+ const identityRoot = projectRoot ?? worktreePath;
89
+ const candidates = Array.isArray(dirtyPaths) ? dirtyPaths : [];
90
+ const outOfScope = listOutOfScopeCoveragePaths(candidates, fileScopePaths);
91
+ if (outOfScope.length === 0) {
92
+ return { restored: [] };
93
+ }
94
+
95
+ const trackedPaths = listTrackedPorcelainPaths(porcelain ?? "");
96
+ const toRestore = trackedPaths.size > 0
97
+ ? outOfScope.filter((filePath) => trackedPaths.has(filePath))
98
+ : outOfScope;
99
+ if (toRestore.length === 0) {
100
+ return { restored: [] };
101
+ }
102
+
103
+ gitExec(
104
+ worktreePath,
105
+ ["restore", "--source=HEAD", "--worktree", "--", ...toRestore],
106
+ { projectRoot: identityRoot },
107
+ );
108
+ return { restored: toRestore };
109
+ }
110
+
111
+ /**
112
+ * @param {string} filePath
113
+ * @returns {boolean}
114
+ */
115
+ export function isGitignoredArtifactPath(filePath) {
116
+ if (!filePath || typeof filePath !== "string") return false;
117
+ const normalized = filePath.replace(/\\/g, "/");
118
+ return GITIGNORED_ARTIFACT_MARKERS.some(
119
+ (marker) =>
120
+ normalized === marker.slice(0, -1) ||
121
+ normalized.startsWith(marker) ||
122
+ normalized.includes(marker),
123
+ );
124
+ }
125
+
126
+ /**
127
+ * @param {string} filePath
128
+ * @returns {string | null}
129
+ */
130
+ function gitignoredArtifactRootForPath(filePath) {
131
+ const normalized = filePath.replace(/\\/g, "/");
132
+ for (const marker of ["/node_modules/", "/coverage/", "/__pycache__/", "/graphify-out/"]) {
133
+ const markerIdx = normalized.indexOf(marker);
134
+ if (markerIdx >= 0) {
135
+ return normalized.slice(0, markerIdx + marker.length - 1);
136
+ }
137
+ }
138
+ if (normalized === "node_modules" || normalized.startsWith("node_modules/")) {
139
+ return "node_modules";
140
+ }
141
+ if (normalized === "coverage" || normalized.startsWith("coverage/")) {
142
+ return "coverage";
143
+ }
144
+ if (normalized === "__pycache__" || normalized.startsWith("__pycache__/")) {
145
+ return "__pycache__";
146
+ }
147
+ if (normalized === "graphify-out" || normalized.startsWith("graphify-out/")) {
148
+ return "graphify-out";
149
+ }
150
+ if (normalized === ".review" || normalized.startsWith(".review/")) {
151
+ return ".review";
152
+ }
153
+ if (normalized === ".spine/runtime" || normalized.startsWith(".spine/runtime/")) {
154
+ return ".spine/runtime";
155
+ }
156
+ return null;
157
+ }
158
+
159
+ /**
160
+ * @param {string[]} filePaths
161
+ * @returns {string[]}
162
+ */
163
+ export function listGitignoredArtifactRoots(filePaths) {
164
+ const roots = new Set();
165
+ for (const filePath of filePaths) {
166
+ if (!isGitignoredArtifactPath(filePath)) continue;
167
+ const root = gitignoredArtifactRootForPath(filePath);
168
+ if (root) roots.add(root);
169
+ }
170
+ return [...roots].sort();
171
+ }
172
+
173
+ /**
174
+ * @param {string} worktreePath
175
+ * @returns {string[]}
176
+ */
177
+ function listIgnoredUntrackedPaths(worktreePath) {
178
+ let output = "";
179
+ try {
180
+ output = execFileSync("git", ["ls-files", "-o", "-i", "--exclude-standard"], {
181
+ cwd: worktreePath,
182
+ encoding: "utf-8",
183
+ stdio: ["ignore", "pipe", "pipe"],
184
+ }).trim();
185
+ } catch {
186
+ return [];
187
+ }
188
+ if (!output) return [];
189
+ return output.split("\n").map((line) => line.trim()).filter(Boolean);
190
+ }
191
+
192
+ /**
193
+ * Auto-clean worktree-only gitignored artifacts under known dirs before lane dirty gate.
194
+ *
195
+ * @param {string} worktreePath
196
+ * @param {{ projectRoot?: string, porcelain?: string, enabled?: boolean }} [options]
197
+ * @returns {{ cleanedRoots: string[] }}
198
+ */
199
+ export function sanitizeGitignoredArtifactsBeforeLaneCommit(
200
+ worktreePath,
201
+ { projectRoot, porcelain, enabled = true } = {},
202
+ ) {
203
+ if (!enabled) return { cleanedRoots: [] };
204
+
205
+ const identityRoot = projectRoot ?? worktreePath;
206
+ const rawPorcelain = typeof porcelain === "string" ? porcelain : "";
207
+ const dirtyPaths = listPorcelainPaths(rawPorcelain);
208
+ const ignoredUntrackedPaths = listIgnoredUntrackedPaths(worktreePath);
209
+ const gitignoredCandidates = [...new Set([...dirtyPaths, ...ignoredUntrackedPaths])];
210
+ if (gitignoredCandidates.length === 0) {
211
+ return { cleanedRoots: [] };
212
+ }
213
+
214
+ const { worktreeOnly } = classifyGitignoredPaths(worktreePath, gitignoredCandidates);
215
+ const artifactRoots = listGitignoredArtifactRoots(worktreeOnly);
216
+ for (const root of artifactRoots) {
217
+ gitExec(worktreePath, ["clean", "-fdX", "--", root], {
218
+ projectRoot: identityRoot,
219
+ throwOnError: false,
220
+ });
221
+ }
222
+
223
+ return { cleanedRoots: artifactRoots };
224
+ }
225
+
226
+ export function classifyGitignoredPaths(worktreePath, gitignoredPaths) {
227
+ if (!Array.isArray(gitignoredPaths) || gitignoredPaths.length === 0) {
228
+ return { indexTracked: [], worktreeOnly: [] };
229
+ }
230
+
231
+ let indexedOutput = "";
232
+ try {
233
+ indexedOutput = execFileSync(
234
+ "git",
235
+ ["ls-files", "--cached", "--", ...gitignoredPaths],
236
+ {
237
+ cwd: worktreePath,
238
+ encoding: "utf-8",
239
+ stdio: ["ignore", "pipe", "pipe"],
240
+ },
241
+ ).trim();
242
+ } catch {
243
+ // If ls-files fails, treat all as worktree-only (safe fallback).
244
+ return { indexTracked: [], worktreeOnly: [...gitignoredPaths] };
245
+ }
246
+
247
+ const indexedSet = new Set(
248
+ indexedOutput ? indexedOutput.split("\n").map((l) => l.trim()).filter(Boolean) : [],
249
+ );
250
+ const indexTracked = [];
251
+ const worktreeOnly = [];
252
+ for (const p of gitignoredPaths) {
253
+ if (indexedSet.has(p)) {
254
+ indexTracked.push(p);
255
+ } else {
256
+ worktreeOnly.push(p);
257
+ }
258
+ }
259
+ return { indexTracked, worktreeOnly };
260
+ }
261
+
262
+ /**
263
+ * Build a remediation message appropriate for the gitignored path classification.
264
+ *
265
+ * @param {string[]} indexTracked
266
+ * @param {string[]} worktreeOnly
267
+ * @returns {string}
268
+ */
269
+ export function formatGitignoredRemediationMessage(indexTracked, worktreeOnly) {
270
+ const allPaths = [...indexTracked, ...worktreeOnly];
271
+ const preview = allPaths.slice(0, 20).join(", ");
272
+ const suffix = allPaths.length > 20 ? "…" : "";
273
+ const prefix = `Lane worktree has gitignored dirty files only (${preview}${suffix})`;
274
+
275
+ if (indexTracked.length > 0 && worktreeOnly.length > 0) {
276
+ return (
277
+ `${prefix} — ` +
278
+ `remove index-tracked paths with git rm --cached on the task branch, ` +
279
+ `then git clean -fdX to remove worktree-only artifacts before resume`
280
+ );
281
+ }
282
+ if (indexTracked.length > 0) {
283
+ return (
284
+ `${prefix} — ` +
285
+ `remove from the index with git rm --cached on the task branch before resume`
286
+ );
287
+ }
288
+ return (
289
+ `${prefix} — ` +
290
+ `worktree-only artifacts (not in git index); clean with git clean -fdX before resume`
291
+ );
292
+ }
293
+
294
+ /**
295
+ * Resolve porcelain for post-lane-commit validation: restore ephemeral coverage, then filter.
296
+ *
297
+ * @param {string} worktreePath
298
+ * @param {object} [options]
299
+ * @param {string[]} [options.fileScopePaths]
300
+ * @param {string[]} [options.ignorePatterns]
301
+ * @param {string} [options.projectRoot]
302
+ * @param {string} [options.porcelain]
303
+ * @returns {string}
304
+ */
305
+ export function resolvePostLaneCommitPorcelain(
306
+ worktreePath,
307
+ { fileScopePaths, ignorePatterns = [], projectRoot, porcelain, config, batchId, laneNumber } = {},
308
+ ) {
309
+ const rawPorcelain = typeof porcelain === "string" ? porcelain : "";
310
+ const dirtyPaths = listPorcelainPaths(rawPorcelain);
311
+ const { restored } = restoreOutOfScopeCoverageArtifacts(worktreePath, fileScopePaths, {
312
+ projectRoot,
313
+ dirtyPaths,
314
+ porcelain: rawPorcelain,
315
+ });
316
+
317
+ let effectivePorcelain = rawPorcelain;
318
+ if (restored.length > 0) {
319
+ const restoredSet = new Set(restored);
320
+ const kept = [];
321
+ for (const line of rawPorcelain.split("\n")) {
322
+ if (!line.trim()) continue;
323
+ const filePath = extractPorcelainPath(line);
324
+ if (filePath && restoredSet.has(filePath)) continue;
325
+ kept.push(line);
326
+ }
327
+ effectivePorcelain = kept.length === 0 ? "" : kept.join("\n");
328
+ }
329
+
330
+ let filtered = filterOutOfScopeCoveragePorcelain(effectivePorcelain, fileScopePaths, ignorePatterns);
331
+ if (!filtered?.trim()) {
332
+ return "";
333
+ }
334
+
335
+ if (isSymlinkOnlyDriftPorcelain(filtered)) {
336
+ const identityRoot = projectRoot ?? worktreePath;
337
+ const effectiveConfig = config ?? loadSpineConfig(identityRoot).config ?? {};
338
+ if (resolveWorktreeSetupHook(identityRoot, effectiveConfig)) {
339
+ repairSetupHookSymlinkDrift(worktreePath, {
340
+ projectRoot: identityRoot,
341
+ config: effectiveConfig,
342
+ batchId,
343
+ laneNumber,
344
+ });
345
+ const refreshedPorcelain = gitPorcelain(worktreePath);
346
+ filtered = filterOutOfScopeCoveragePorcelain(
347
+ refreshedPorcelain,
348
+ fileScopePaths,
349
+ ignorePatterns,
350
+ );
351
+ if (!filtered?.trim()) {
352
+ return "";
353
+ }
354
+ if (isSymlinkOnlyDriftPorcelain(filtered)) {
355
+ return "";
356
+ }
357
+ }
358
+ }
359
+
360
+ return filtered;
361
+ }
@@ -0,0 +1,298 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Lane dirty-check git porcelain parsing, symlink drift, and path-in-scope helpers.
4
+ * SP-583 extraction from lane-dirty-check.mjs; gitignored remediation stays in parent (SP-601).
5
+ */
6
+
7
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
8
+ import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
9
+ import { filterPorcelain } from "./lane-commit.mjs";
10
+ import { runWorktreeSetupHook } from "./worktree.mjs";
11
+
12
+ /**
13
+ * Path segments that identify generated coverage report artifacts.
14
+ * Matches extension/coverage, root coverage dirs, and nested coverage paths.
15
+ */
16
+ export const COVERAGE_ARTIFACT_MARKERS = ["/coverage/", "coverage/"];
17
+
18
+ /**
19
+ * @param {string} filePath
20
+ * @returns {boolean}
21
+ */
22
+ export function isCoverageArtifactPath(filePath) {
23
+ if (!filePath || typeof filePath !== "string") return false;
24
+ const normalized = filePath.replace(/\\/g, "/");
25
+ return COVERAGE_ARTIFACT_MARKERS.some(
26
+ (marker) =>
27
+ normalized === marker.slice(0, -1) ||
28
+ normalized.startsWith(marker) ||
29
+ normalized.includes(marker),
30
+ );
31
+ }
32
+
33
+ /**
34
+ * @param {string} filePath
35
+ * @param {string[]} [fileScopePaths]
36
+ * @returns {boolean}
37
+ */
38
+ export function isPathInFileScope(filePath, fileScopePaths) {
39
+ if (!filePath || !Array.isArray(fileScopePaths) || fileScopePaths.length === 0) {
40
+ return false;
41
+ }
42
+
43
+ const normalizedPath = filePath.replace(/\\/g, "/");
44
+ const scopePrefixes = [];
45
+ for (const rel of fileScopePaths) {
46
+ if (!rel || typeof rel !== "string") continue;
47
+ const normalized = rel.replace(/\\/g, "/");
48
+ scopePrefixes.push(normalized.endsWith("/") ? normalized : `${normalized}/`);
49
+ scopePrefixes.push(normalized);
50
+ }
51
+
52
+ return scopePrefixes.some(
53
+ (prefix) => normalizedPath === prefix || normalizedPath.startsWith(prefix),
54
+ );
55
+ }
56
+
57
+ /**
58
+ * @param {string} line
59
+ * @returns {string | null}
60
+ */
61
+ export function extractPorcelainPath(line) {
62
+ if (!line.trim()) return null;
63
+ let filePath = line.length > 2 && line[2] === " " ? line.slice(3) : line.slice(2);
64
+ filePath = filePath.trim();
65
+ if (!filePath) return null;
66
+ if (filePath.includes(" -> ")) {
67
+ return filePath.split(" -> ").pop()?.trim() ?? null;
68
+ }
69
+ return filePath;
70
+ }
71
+
72
+ /**
73
+ * @param {string} porcelain
74
+ * @returns {string[]}
75
+ */
76
+ export function listPorcelainPaths(porcelain) {
77
+ if (!porcelain?.trim()) return [];
78
+ return porcelain
79
+ .split("\n")
80
+ .map((line) => extractPorcelainPath(line))
81
+ .filter((entry) => Boolean(entry));
82
+ }
83
+
84
+ /**
85
+ * @param {string[]} dirtyPaths
86
+ * @param {string[]} [fileScopePaths]
87
+ * @returns {string[]}
88
+ */
89
+ export function listOutOfScopeCoveragePaths(dirtyPaths, fileScopePaths) {
90
+ if (!Array.isArray(dirtyPaths) || dirtyPaths.length === 0) return [];
91
+ return dirtyPaths.filter(
92
+ (filePath) => isCoverageArtifactPath(filePath) && !isPathInFileScope(filePath, fileScopePaths),
93
+ );
94
+ }
95
+
96
+ /**
97
+ * @param {string} filePath
98
+ * @returns {string | null}
99
+ */
100
+ function coverageRootForPath(filePath) {
101
+ const normalized = filePath.replace(/\\/g, "/");
102
+ const markerIdx = normalized.indexOf("/coverage/");
103
+ if (markerIdx >= 0) {
104
+ return normalized.slice(0, markerIdx + "/coverage".length);
105
+ }
106
+ if (normalized === "coverage" || normalized.startsWith("coverage/")) {
107
+ return "coverage";
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /**
113
+ * @param {string[]} filePaths
114
+ * @param {string[]} [fileScopePaths]
115
+ * @returns {string[]}
116
+ */
117
+ export function listOutOfScopeCoverageRoots(filePaths, fileScopePaths) {
118
+ const roots = new Set();
119
+ for (const filePath of filePaths) {
120
+ if (!isCoverageArtifactPath(filePath) || isPathInFileScope(filePath, fileScopePaths)) {
121
+ continue;
122
+ }
123
+ const root = coverageRootForPath(filePath);
124
+ if (root && !isPathInFileScope(root, fileScopePaths)) {
125
+ roots.add(root);
126
+ }
127
+ }
128
+ return [...roots].sort();
129
+ }
130
+
131
+ /**
132
+ * @param {string} porcelain
133
+ * @returns {Set<string>}
134
+ */
135
+ export function listTrackedPorcelainPaths(porcelain) {
136
+ const tracked = new Set();
137
+ if (!porcelain?.trim()) return tracked;
138
+ for (const line of porcelain.split("\n")) {
139
+ if (!line.trim()) continue;
140
+ const status = line.slice(0, 2);
141
+ if (status === "??" || status === "!!") continue;
142
+ const filePath = extractPorcelainPath(line);
143
+ if (filePath) tracked.add(filePath);
144
+ }
145
+ return tracked;
146
+ }
147
+
148
+ /**
149
+ * @param {string} line
150
+ * @returns {boolean}
151
+ */
152
+ export function isSymlinkDeletionPorcelainLine(line) {
153
+ if (!line?.trim() || line.length < 3) return false;
154
+ const indexStatus = line[0];
155
+ const worktreeStatus = line[1];
156
+ const disallowed = new Set(["M", "A", "R", "C", "U"]);
157
+ if (disallowed.has(indexStatus) || disallowed.has(worktreeStatus)) {
158
+ return false;
159
+ }
160
+ return indexStatus === "D" || worktreeStatus === "D";
161
+ }
162
+
163
+ /**
164
+ * @param {string} line
165
+ * @returns {boolean}
166
+ */
167
+ export function isWorktreeDeletionPorcelainLine(line) {
168
+ return isSymlinkDeletionPorcelainLine(line) && line[1] === "D";
169
+ }
170
+
171
+ /**
172
+ * True when every porcelain line is a symlink/hook deletion (` D`, `D `, or `DD`).
173
+ *
174
+ * @param {string} porcelain
175
+ * @returns {boolean}
176
+ */
177
+ export function isSymlinkOnlyDriftPorcelain(porcelain) {
178
+ if (!porcelain?.trim()) return false;
179
+ for (const line of porcelain.split("\n")) {
180
+ if (!line.trim()) continue;
181
+ if (!isSymlinkDeletionPorcelainLine(line)) return false;
182
+ }
183
+ return true;
184
+ }
185
+
186
+ /**
187
+ * @param {string} worktreePath
188
+ * @returns {{ batchId: string, laneNumber: number } | null}
189
+ */
190
+ export function parseLaneWorktreeIdentity(worktreePath) {
191
+ const normalized = worktreePath.replace(/\\/g, "/");
192
+ const match = normalized.match(/\/\.worktrees\/spine-([^/]+)\/lane-(\d+)\/?$/);
193
+ if (!match) return null;
194
+ return { batchId: match[1], laneNumber: Number(match[2]) };
195
+ }
196
+
197
+ /**
198
+ * @param {string} porcelain
199
+ * @returns {string}
200
+ */
201
+ export function filterSetupHookSymlinkDriftPorcelain(porcelain) {
202
+ if (!porcelain?.trim() || !isSymlinkOnlyDriftPorcelain(porcelain)) {
203
+ return porcelain ?? "";
204
+ }
205
+ return "";
206
+ }
207
+
208
+ /**
209
+ * Re-run worktreeSetupHook to recreate hook-managed symlinks after drift.
210
+ *
211
+ * @param {string} worktreePath
212
+ * @param {{ projectRoot: string, config?: object, batchId?: string, laneNumber?: number }} options
213
+ * @returns {{ repaired: boolean, reason?: string }}
214
+ */
215
+ export function repairSetupHookSymlinkDrift(worktreePath, { projectRoot, config, batchId, laneNumber }) {
216
+ const effectiveConfig = config ?? loadSpineConfig(projectRoot).config ?? {};
217
+ const hookPath = resolveWorktreeSetupHook(projectRoot, effectiveConfig);
218
+ if (!hookPath) {
219
+ return { repaired: false, reason: "no_hook" };
220
+ }
221
+
222
+ const identity = parseLaneWorktreeIdentity(worktreePath);
223
+ const effectiveBatchId = batchId ?? identity?.batchId ?? "unknown";
224
+ const effectiveLaneNumber = laneNumber ?? identity?.laneNumber ?? 1;
225
+
226
+ try {
227
+ runWorktreeSetupHook({
228
+ projectRoot,
229
+ worktreePath,
230
+ batchId: effectiveBatchId,
231
+ laneNumber: effectiveLaneNumber,
232
+ config: effectiveConfig,
233
+ });
234
+ return { repaired: true };
235
+ } catch {
236
+ return { repaired: false, reason: "hook_failed" };
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Repair or ignore symlink-only deletions from worktreeSetupHook paths (#87 / SP-429).
242
+ *
243
+ * @param {string} worktreePath
244
+ * @param {string} porcelain
245
+ * @param {{ projectRoot?: string, config?: object, batchId?: string, laneNumber?: number }} [options]
246
+ * @returns {string}
247
+ */
248
+ export function resolveSetupHookSymlinkDriftPorcelain(
249
+ worktreePath,
250
+ porcelain,
251
+ { projectRoot, config, batchId, laneNumber } = {},
252
+ ) {
253
+ if (!porcelain?.trim() || !isSymlinkOnlyDriftPorcelain(porcelain)) {
254
+ return porcelain ?? "";
255
+ }
256
+
257
+ const identityRoot = projectRoot ?? worktreePath;
258
+ const effectiveConfig = config ?? loadSpineConfig(identityRoot).config ?? {};
259
+ if (!resolveWorktreeSetupHook(identityRoot, effectiveConfig)) {
260
+ return porcelain;
261
+ }
262
+
263
+ const repair = repairSetupHookSymlinkDrift(worktreePath, {
264
+ projectRoot: identityRoot,
265
+ config: effectiveConfig,
266
+ batchId,
267
+ laneNumber,
268
+ });
269
+ if (repair.repaired) {
270
+ return porcelain;
271
+ }
272
+
273
+ return filterSetupHookSymlinkDriftPorcelain(porcelain);
274
+ }
275
+
276
+ /**
277
+ * Drop out-of-scope coverage artifact lines from porcelain after ignore patterns.
278
+ *
279
+ * @param {string} porcelain
280
+ * @param {string[]} [fileScopePaths]
281
+ * @param {string[]} [ignorePatterns]
282
+ * @returns {string}
283
+ */
284
+ export function filterOutOfScopeCoveragePorcelain(porcelain, fileScopePaths, ignorePatterns = []) {
285
+ const afterIgnore = filterPorcelain(porcelain, ignorePatterns);
286
+ if (!afterIgnore?.trim()) return "";
287
+
288
+ const kept = [];
289
+ for (const line of afterIgnore.split("\n")) {
290
+ if (!line.trim()) continue;
291
+ const filePath = extractPorcelainPath(line);
292
+ if (filePath && isCoverageArtifactPath(filePath) && !isPathInFileScope(filePath, fileScopePaths)) {
293
+ continue;
294
+ }
295
+ kept.push(line);
296
+ }
297
+ return kept.length === 0 ? "" : kept.join("\n");
298
+ }