pi-spine 2.1.0 → 2.2.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.
@@ -21,6 +21,7 @@ import {
21
21
  runAttachedBatchEngine,
22
22
  } from "../src/batch/attached-runner.mjs";
23
23
  import { enforceAttachedOrphanRiskGuard } from "../src/doctor/attached-orphan-risk.mjs";
24
+ import { formatSalvageIntegrateOutput, formatSalvageListOutput, integrateSalvageableLane, listSalvageableLanes } from "../src/batch/salvage-batch.mjs";
24
25
 
25
26
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
26
27
 
@@ -29,6 +30,7 @@ const BATCH_FLAG_VALUE_TAKERS = new Set([
29
30
  "--through-wave",
30
31
  "--batch",
31
32
  "--reason",
33
+ "--lane",
32
34
  ]);
33
35
 
34
36
  /**
@@ -36,7 +38,7 @@ const BATCH_FLAG_VALUE_TAKERS = new Set([
36
38
  */
37
39
  export function printBatchHelp() {
38
40
  return (
39
- "Usage: spine batch start <scope>|pause|resume|retry <taskId>|skip <taskId>|force-merge [--wave N]|abort|dismiss|complete [--batch ID] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n"
41
+ "Usage: spine batch start <scope>|pause|resume|retry <taskId>|skip <taskId>|force-merge [--wave N]|salvage|abort|dismiss|complete [--batch ID] [--lane N] [--integrate] [--yes] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n"
40
42
  );
41
43
  }
42
44
 
@@ -51,9 +53,18 @@ export function isBatchHelpRequest(args) {
51
53
  return true;
52
54
  }
53
55
  const subcommand = args.find((token) =>
54
- ["dismiss", "complete", "abort", "start", "pause", "resume", "retry", "skip", "force-merge"].includes(
55
- token,
56
- ),
56
+ [
57
+ "dismiss",
58
+ "complete",
59
+ "abort",
60
+ "start",
61
+ "pause",
62
+ "resume",
63
+ "retry",
64
+ "skip",
65
+ "force-merge",
66
+ "salvage",
67
+ ].includes(token),
57
68
  );
58
69
  if (subcommand && args.includes("help")) {
59
70
  const helpIdx = args.indexOf("help");
@@ -143,6 +154,12 @@ export function parseBatchArgs(args) {
143
154
  waveIndex = Number(args[waveIdx + 1]);
144
155
  }
145
156
 
157
+ let laneNumber = null;
158
+ const laneIdx = args.indexOf("--lane");
159
+ if (laneIdx >= 0 && args[laneIdx + 1]) {
160
+ laneNumber = Number(args[laneIdx + 1]);
161
+ }
162
+
146
163
  const subcommand =
147
164
  args.find(
148
165
  (t) =>
@@ -154,7 +171,8 @@ export function parseBatchArgs(args) {
154
171
  t === "resume" ||
155
172
  t === "retry" ||
156
173
  t === "skip" ||
157
- t === "force-merge",
174
+ t === "force-merge" ||
175
+ t === "salvage",
158
176
  ) ?? null;
159
177
 
160
178
  let waveFilter = null;
@@ -175,6 +193,8 @@ export function parseBatchArgs(args) {
175
193
  const dryRun = flags.has("--dry-run");
176
194
  const skipPreflight = flags.has("--skip-preflight");
177
195
  const forceSuperseded = flags.has("--force-superseded");
196
+ const integrate = flags.has("--integrate");
197
+ const yes = flags.has("--yes");
178
198
 
179
199
  return {
180
200
  json: flags.has("--json"),
@@ -187,9 +207,12 @@ export function parseBatchArgs(args) {
187
207
  dryRun,
188
208
  skipPreflight,
189
209
  forceSuperseded,
210
+ integrate,
211
+ yes,
190
212
  batchId,
191
213
  reason,
192
214
  waveIndex,
215
+ laneNumber,
193
216
  waveFilter,
194
217
  waveFilterError,
195
218
  subcommand,
@@ -225,6 +248,52 @@ export async function runSpineBatch(options) {
225
248
  };
226
249
  }
227
250
 
251
+ if (parsed.subcommand === "salvage") {
252
+ if (!parsed.batchId) {
253
+ return {
254
+ exitCode: 1,
255
+ output:
256
+ "Usage: spine batch salvage --batch <batchId> --dry-run [--json]\n" +
257
+ " spine batch salvage --batch <batchId> --lane <n> --integrate [--yes] [--json]\n",
258
+ };
259
+ }
260
+
261
+ if (parsed.integrate) {
262
+ if (!Number.isFinite(parsed.laneNumber) || parsed.laneNumber <= 0) {
263
+ return {
264
+ exitCode: 1,
265
+ output: "Usage: spine batch salvage --batch <batchId> --lane <n> --integrate [--yes] [--json]\n",
266
+ };
267
+ }
268
+
269
+ const result = await integrateSalvageableLane(projectRoot, parsed.batchId, parsed.laneNumber, {
270
+ yes: parsed.yes,
271
+ forceIntegrate: parsed.force,
272
+ });
273
+ return {
274
+ exitCode: result.exitCode ?? (result.ok ? 0 : 1),
275
+ output: formatSalvageIntegrateOutput(result, { json: parsed.json }),
276
+ result,
277
+ };
278
+ }
279
+
280
+ if (!parsed.dryRun) {
281
+ return {
282
+ exitCode: 1,
283
+ output:
284
+ "Usage: spine batch salvage --batch <batchId> --dry-run [--json]\n" +
285
+ " spine batch salvage --batch <batchId> --lane <n> --integrate [--yes] [--json]\n",
286
+ };
287
+ }
288
+
289
+ const result = listSalvageableLanes(projectRoot, parsed.batchId);
290
+ return {
291
+ exitCode: result.exitCode ?? (result.ok ? 0 : 1),
292
+ output: formatSalvageListOutput(result, { json: parsed.json }),
293
+ result,
294
+ };
295
+ }
296
+
228
297
  if (parsed.subcommand === "abort") {
229
298
  const result = abortBatch({
230
299
  projectRoot,
@@ -28,6 +28,7 @@ export const PHASE23_GRANDFATHERED_OVER_500 = [
28
28
  "src/batch/lane-dirty-check.mjs",
29
29
  "src/batch/attached-runner.mjs",
30
30
  "src/batch/lifecycle.mjs",
31
+ "src/batch/salvage-batch.mjs",
31
32
  ];
32
33
 
33
34
  const PHASE23_ENGINE_LANES_MAX = 500;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -32,6 +32,7 @@ import {
32
32
  journalIndicatesPausedForceResume,
33
33
  } from "./orphan-detect.mjs";
34
34
  import { classifyTaskDoneSemantics } from "./diagnosis-task-done.mjs";
35
+ import { laneDoneMarkerReadyForPromote } from "./journal-rebuild.mjs";
35
36
  import { resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
36
37
  import { journalHasTaskCompleted } from "./resume-common.mjs";
37
38
  import { startParentSessionMonitor } from "./parent-session-monitor.mjs";
@@ -393,7 +394,17 @@ export function reconcilePausedResumeDoneInLane({ projectRoot, state, batchId })
393
394
  batchId,
394
395
  lanes,
395
396
  });
396
- if (classified.doneInLane !== true) continue;
397
+ if (
398
+ !laneDoneMarkerReadyForPromote({
399
+ projectRoot,
400
+ batchId,
401
+ task,
402
+ lanes,
403
+ classified,
404
+ })
405
+ ) {
406
+ continue;
407
+ }
397
408
  if (!journalHasContractVerified(journalEvents, task.taskId)) continue;
398
409
 
399
410
  task.status = "succeeded";
@@ -31,6 +31,7 @@ import { maybeFinalizeAfterWaveMerge } from "../post-merge-limbo.mjs";
31
31
  import { saveSpineBatchState } from "../state.mjs";
32
32
  import { loadTaskFileScopePaths } from "./queue.mjs";
33
33
  import { laneTaskBranch } from "../worktree.mjs";
34
+ import { laneDoneMarkerCommittedOnBranch, normalizeTaskFolderRel } from "../journal-rebuild.mjs";
34
35
 
35
36
  /**
36
37
  * @param {string} projectRoot
@@ -486,6 +487,7 @@ export function mergeLaneToOrch({
486
487
  batchId,
487
488
  requireLaneCommits = false,
488
489
  laneFileScopePaths = [],
490
+ laneTaskFolders = [],
489
491
  waveIndex,
490
492
  }) {
491
493
  const previous = gitStrict(projectRoot, ["rev-parse", "--abbrev-ref", "HEAD"]);
@@ -503,6 +505,21 @@ export function mergeLaneToOrch({
503
505
  const orchHeadBefore = gitStrict(projectRoot, ["rev-parse", orchBranch]);
504
506
  const commitsAhead = countCommitsAhead(projectRoot, orchBranch, taskBranch);
505
507
 
508
+ if (Array.isArray(laneTaskFolders) && laneTaskFolders.length > 0) {
509
+ for (const taskFolderRel of laneTaskFolders) {
510
+ if (laneDoneMarkerCommittedOnBranch(projectRoot, taskBranch, taskFolderRel)) {
511
+ continue;
512
+ }
513
+ return {
514
+ ok: false,
515
+ failureClass: "DoneMarkerMissing",
516
+ error:
517
+ `Task branch ${taskBranch} lacks committed ${normalizeTaskFolderRel(projectRoot, taskFolderRel) ?? taskFolderRel}/.DONE. ` +
518
+ "Worker must create .DONE on the lane branch before merge.",
519
+ };
520
+ }
521
+ }
522
+
506
523
  if (requireLaneCommits && commitsAhead === 0) {
507
524
  return {
508
525
  ok: false,
@@ -628,6 +645,13 @@ export async function mergeWaveLanesToOrch({
628
645
 
629
646
  const taskBranch = lane.branch ?? laneTaskBranch(batchId, laneNumber);
630
647
  const laneFileScopePaths = collectLaneWaveFileScope(state, laneNumber, waveTaskIds);
648
+ const laneTaskFolders = waveTaskIds
649
+ .map((taskId) => {
650
+ const task = (state.tasks ?? []).find((entry) => entry?.taskId === taskId);
651
+ if (!task || task.laneNumber !== laneNumber || !task.taskFolder) return null;
652
+ return task.taskFolder;
653
+ })
654
+ .filter(Boolean);
631
655
  appendJournalEvent(projectRoot, batchId, "batch.merge_started", {
632
656
  taskBranch,
633
657
  orchBranch,
@@ -644,6 +668,7 @@ export async function mergeWaveLanesToOrch({
644
668
  batchId,
645
669
  requireLaneCommits: false,
646
670
  laneFileScopePaths,
671
+ laneTaskFolders,
647
672
  waveIndex,
648
673
  });
649
674
  if (!merge.ok) {
@@ -4,7 +4,10 @@
4
4
  */
5
5
 
6
6
  import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { execFileSync } from "node:child_process";
7
9
  import { appendJournalEvent, readJournalEvents, STRUCTURAL_JOURNAL_EVENT_TYPES } from "./journal.mjs";
10
+ import { laneTaskBranch } from "./worktree.mjs";
8
11
  import { parseReviewVerdict } from "./review-shared.mjs";
9
12
  import { journalHasTaskCompleted } from "./resume-common.mjs";
10
13
  import {
@@ -390,6 +393,72 @@ function classifiedShowsDoneInLaneDrift(classified) {
390
393
  );
391
394
  }
392
395
 
396
+ export function normalizeTaskFolderRel(projectRoot, taskFolder) {
397
+ if (!taskFolder) return null;
398
+ if (path.isAbsolute(taskFolder)) {
399
+ return path.relative(projectRoot, taskFolder).replace(/\\/g, "/");
400
+ }
401
+ return String(taskFolder).replace(/\\/g, "/");
402
+ }
403
+
404
+ /**
405
+ * True when `.DONE` is committed on the lane task branch (fail-closed / #190).
406
+ *
407
+ * @param {string} projectRoot
408
+ * @param {string} taskBranch
409
+ * @param {string} taskFolderRel
410
+ */
411
+ export function laneDoneMarkerCommittedOnBranch(projectRoot, taskBranch, taskFolderRel) {
412
+ const folderRel = normalizeTaskFolderRel(projectRoot, taskFolderRel);
413
+ if (!projectRoot || !taskBranch || !folderRel) return false;
414
+ const donePath = `${folderRel.replace(/\/+$/, "")}/.DONE`;
415
+ try {
416
+ execFileSync("git", ["cat-file", "-e", `${taskBranch}:${donePath}`], {
417
+ cwd: projectRoot,
418
+ stdio: ["ignore", "pipe", "pipe"],
419
+ timeout: 5000,
420
+ });
421
+ return true;
422
+ } catch {
423
+ return false;
424
+ }
425
+ }
426
+
427
+ /**
428
+ * @param {object} task
429
+ * @param {string} batchId
430
+ * @param {unknown[]} lanes
431
+ * @param {string} projectRoot
432
+ */
433
+ function laneTaskBranchForTask(task, batchId, lanes) {
434
+ const laneNumber = Number(task.laneNumber ?? 1);
435
+ const lane = Array.isArray(lanes)
436
+ ? lanes.find((entry) => Number(entry?.laneNumber) === laneNumber)
437
+ : null;
438
+ if (lane && typeof lane.branch === "string" && lane.branch) {
439
+ return lane.branch;
440
+ }
441
+ return laneTaskBranch(batchId, laneNumber);
442
+ }
443
+
444
+ /**
445
+ * Fail-closed gate: filesystem `.DONE` in lane worktree and committed on lane branch.
446
+ *
447
+ * @param {object} params
448
+ * @param {string} params.projectRoot
449
+ * @param {string} params.batchId
450
+ * @param {object} params.task
451
+ * @param {unknown[]} [params.lanes]
452
+ * @param {object|null|undefined} params.classified
453
+ */
454
+ export function laneDoneMarkerReadyForPromote({ projectRoot, batchId, task, lanes = [], classified }) {
455
+ if (classified?.doneInLane !== true) return false;
456
+ const taskFolder = normalizeTaskFolderRel(projectRoot, task?.taskFolder);
457
+ if (!taskFolder) return false;
458
+ const taskBranch = laneTaskBranchForTask(task, batchId, lanes);
459
+ return laneDoneMarkerCommittedOnBranch(projectRoot, taskBranch, taskFolder);
460
+ }
461
+
393
462
  /**
394
463
  * Detect review.started events that have no matching review.completed for the same
395
464
  * taskId + reviewType. These represent engine crashes mid-review where the artifact
@@ -634,7 +703,17 @@ export function reconcileBatchStateDrift({
634
703
 
635
704
  const classified = classifiedById.get(taskId);
636
705
  if (!classifiedShowsDoneInLaneDrift(classified)) continue;
637
- if (classified?.doneInLane !== true) continue;
706
+ if (
707
+ !laneDoneMarkerReadyForPromote({
708
+ projectRoot,
709
+ batchId,
710
+ task,
711
+ lanes: state.lanes ?? [],
712
+ classified,
713
+ })
714
+ ) {
715
+ continue;
716
+ }
638
717
  if (journalHasTaskCompleted(journalEvents, taskId)) continue;
639
718
  if (!journalShowsDoneInLaneTerminalArtifacts(journalEvents, taskId)) continue;
640
719
  if (String(task.status ?? "") === "succeeded") continue;
@@ -5,6 +5,7 @@
5
5
 
6
6
  import path from "node:path";
7
7
  import crypto from "node:crypto";
8
+ import fs from "node:fs";
8
9
  import {
9
10
  journalHasTaskCompleted,
10
11
  loadResumeFileScopePaths,
@@ -18,6 +19,7 @@ import { commitLaneWorktree, filterPorcelain, gitPorcelain } from "./lane-commit
18
19
  import { recordTaskFailureSalvage } from "./salvage.mjs";
19
20
  import { saveSpineBatchState, updateSegmentForTask } from "./state.mjs";
20
21
  import { laneTaskBranch } from "./worktree.mjs";
22
+ import { laneDoneMarkerCommittedOnBranch } from "./journal-rebuild.mjs";
21
23
  import { runWorker } from "./worker-host.mjs";
22
24
  import { isTaskResumable } from "./resume-multi-validate.mjs";
23
25
  import { runLaneReviewPhasesBeforeCommit } from "./resume-lane-reviews.mjs";
@@ -161,6 +163,41 @@ async function markTaskCompleteFromDisk({
161
163
  };
162
164
  }
163
165
 
166
+ const taskFolderRel = task.taskFolder;
167
+ const doneOnDisk = fs.existsSync(path.join(taskFolderInWorktree, ".DONE"));
168
+ if (
169
+ doneOnDisk &&
170
+ (!taskFolderRel ||
171
+ !laneDoneMarkerCommittedOnBranch(projectRoot, taskBranchResolved, taskFolderRel))
172
+ ) {
173
+ const output =
174
+ `Lane task branch ${taskBranchResolved} lacks committed ${taskFolderRel ?? "<unknown>"}/.DONE — ` +
175
+ "worker must create and commit .DONE before resume can promote";
176
+ task.status = "failed";
177
+ task.endedAt = Date.now();
178
+ task.exitReason = "done_marker_missing";
179
+ updateSegmentForTask(state, taskId, "failed");
180
+ recomputeTaskCounters(state);
181
+ saveSpineBatchState(projectRoot, state);
182
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
183
+ taskId,
184
+ laneNumber,
185
+ laneId: lane.laneId,
186
+ correlationId: laneCorrelationId,
187
+ classification: "done_marker_missing",
188
+ exitCode: 1,
189
+ output,
190
+ resumed: true,
191
+ });
192
+ return {
193
+ ok: false,
194
+ error: "done_marker_missing",
195
+ output,
196
+ taskId,
197
+ laneNumber,
198
+ };
199
+ }
200
+
164
201
  task.status = "succeeded";
165
202
  task.doneFileFound = true;
166
203
  task.exitReason = task.exitReason ?? "done";
@@ -176,7 +213,7 @@ async function markTaskCompleteFromDisk({
176
213
  laneId: lane.laneId,
177
214
  correlationId: laneCorrelationId,
178
215
  resumed: true,
179
- skippedDoneOnDisk: true,
216
+ ...(doneOnDisk ? { skippedDoneOnDisk: true } : {}),
180
217
  taskFolder: taskFolderInWorktree,
181
218
  });
182
219
  }
@@ -0,0 +1,691 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Operator salvage after batch abort/dismiss (FR-REL220-03, #158).
4
+ * List mode only in SP-570; integrate mode is SP-571.
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import readline from "node:readline/promises";
9
+ import { execFileSync } from "node:child_process";
10
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
11
+ import { archiveBatchStatePath } from "./lifecycle.mjs";
12
+ import { countCommitsAhead } from "./lane-commit.mjs";
13
+ import { checkIntegrateGate } from "./gate.mjs";
14
+ import { gitExec } from "./git-exec.mjs";
15
+ import { mergeOrchIntoBaseIsolated, syncPlumbingMergePathsToWorktree } from "./integrate-worktree.mjs";
16
+ import { journalPath, readJournalEvents, appendJournalEvent } from "./journal.mjs";
17
+ import { rebuildBatchStateFromJournal } from "./journal-rebuild.mjs";
18
+ import { loadBatchStateFile } from "./reconcile.mjs";
19
+ import { resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
20
+ import { laneTaskBranch } from "./worktree.mjs";
21
+
22
+ /** Exit reasons that block salvage even when a lane commit exists. */
23
+ export const NON_SALVAGEABLE_EXIT_REASONS = new Set([
24
+ "contract_failed",
25
+ "review_exhausted",
26
+ "review_failed",
27
+ "code_review_invalid_verdict",
28
+ "final_review_invalid_verdict",
29
+ "CONTRACT_FAIL",
30
+ ]);
31
+
32
+ /**
33
+ * @param {string|null|undefined} exitReason
34
+ */
35
+ export function isNonSalvageableExitReason(exitReason) {
36
+ if (!exitReason) return false;
37
+ return NON_SALVAGEABLE_EXIT_REASONS.has(String(exitReason));
38
+ }
39
+
40
+ /**
41
+ * @param {string} projectRoot
42
+ * @param {string} baseBranch
43
+ * @param {string} headRef
44
+ */
45
+ function collectDiffStat(projectRoot, baseBranch, headRef) {
46
+ try {
47
+ return execFileSync("git", ["diff", "--stat", `${baseBranch}..${headRef}`], {
48
+ cwd: projectRoot,
49
+ encoding: "utf-8",
50
+ stdio: ["ignore", "pipe", "pipe"],
51
+ }).trim();
52
+ } catch (err) {
53
+ const message = err instanceof Error ? err.message : String(err);
54
+ return `(git diff --stat failed: ${message})`;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * @param {string} projectRoot
60
+ * @param {string} ref
61
+ */
62
+ function branchExists(projectRoot, ref) {
63
+ try {
64
+ execFileSync("git", ["rev-parse", "--verify", ref], {
65
+ cwd: projectRoot,
66
+ encoding: "utf-8",
67
+ stdio: ["ignore", "pipe", "pipe"],
68
+ });
69
+ return true;
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * @param {object[]} journalEvents
77
+ */
78
+ function laneCommittedTaskIds(journalEvents) {
79
+ /** @type {Set<string>} */
80
+ const committed = new Set();
81
+ for (const event of journalEvents) {
82
+ if (String(event?.type ?? "") !== "lane.committed") continue;
83
+ const taskId = typeof event.taskId === "string" ? event.taskId : event.payload?.taskId;
84
+ if (taskId) committed.add(String(taskId));
85
+ }
86
+ return committed;
87
+ }
88
+
89
+ /**
90
+ * @param {string} projectRoot
91
+ * @param {string} batchId
92
+ */
93
+ function loadSalvageBatchSeed(projectRoot, batchId) {
94
+ const archivePath = archiveBatchStatePath(projectRoot, batchId);
95
+ if (fs.existsSync(archivePath)) {
96
+ try {
97
+ return JSON.parse(fs.readFileSync(archivePath, "utf-8"));
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+
103
+ const loaded = loadBatchStateFile(projectRoot);
104
+ if (loaded.raw && String(loaded.raw.batchId ?? loaded.raw.id ?? "") === batchId) {
105
+ return loaded.raw;
106
+ }
107
+
108
+ return null;
109
+ }
110
+
111
+ /**
112
+ * @param {object[]} tasks
113
+ */
114
+ function laneNumbersFromTasks(tasks) {
115
+ /** @type {Set<number>} */
116
+ const lanes = new Set();
117
+ for (const task of tasks ?? []) {
118
+ const laneNumber = Number(task?.laneNumber);
119
+ if (Number.isFinite(laneNumber) && laneNumber > 0) lanes.add(laneNumber);
120
+ }
121
+ return lanes;
122
+ }
123
+
124
+ /**
125
+ * @param {object} task
126
+ * @param {Set<string>} committedTaskIds
127
+ */
128
+ function isSalvageableTask(task, committedTaskIds) {
129
+ const taskId = String(task?.taskId ?? "");
130
+ if (!taskId) return false;
131
+ if (!committedTaskIds.has(taskId)) return false;
132
+
133
+ const status = String(task?.status ?? "").toLowerCase();
134
+ if (status !== "succeeded" && status !== "skipped") return false;
135
+ if (isNonSalvageableExitReason(task?.exitReason)) return false;
136
+ return true;
137
+ }
138
+
139
+ /**
140
+ * List lanes with salvageable commits after abort/dismiss (read-only).
141
+ *
142
+ * @param {string} projectRoot
143
+ * @param {string} batchId
144
+ */
145
+ export function listSalvageableLanes(projectRoot, batchId) {
146
+ const resolvedBatchId = String(batchId ?? "").trim();
147
+ if (!resolvedBatchId) {
148
+ return {
149
+ ok: false,
150
+ exitCode: 1,
151
+ error: "batch_id_required",
152
+ headline: "Batch id is required",
153
+ suggestedCommand: "spine batch salvage --batch <batchId> --dry-run",
154
+ };
155
+ }
156
+
157
+ const journalFile = journalPath(projectRoot, resolvedBatchId);
158
+ if (!fs.existsSync(journalFile)) {
159
+ return {
160
+ ok: false,
161
+ exitCode: 1,
162
+ error: "journal_missing",
163
+ headline: `No journal found for batch ${resolvedBatchId}`,
164
+ suggestedCommand: "spine status --diagnose",
165
+ batchId: resolvedBatchId,
166
+ };
167
+ }
168
+
169
+ const journalEvents = readJournalEvents(projectRoot, resolvedBatchId);
170
+ const seedState = loadSalvageBatchSeed(projectRoot, resolvedBatchId);
171
+ const rebuilt = rebuildBatchStateFromJournal(seedState, journalEvents);
172
+ const baseBranch = String(rebuilt.baseBranch ?? seedState?.baseBranch ?? "main");
173
+ const committedTaskIds = laneCommittedTaskIds(journalEvents);
174
+
175
+ /** @type {Map<number, { laneNumber: number, salvageableTasks: string[], excludedTasks: string[] }>} */
176
+ const laneMap = new Map();
177
+
178
+ for (const task of rebuilt.tasks ?? []) {
179
+ const laneNumber = Number(task?.laneNumber);
180
+ if (!Number.isFinite(laneNumber) || laneNumber <= 0) continue;
181
+
182
+ if (!laneMap.has(laneNumber)) {
183
+ laneMap.set(laneNumber, { laneNumber, salvageableTasks: [], excludedTasks: [] });
184
+ }
185
+ const laneEntry = laneMap.get(laneNumber);
186
+
187
+ const taskId = String(task.taskId ?? "");
188
+ const status = String(task.status ?? "").toLowerCase();
189
+ const hasLaneCommit = committedTaskIds.has(taskId);
190
+
191
+ if (hasLaneCommit && isNonSalvageableExitReason(task.exitReason)) {
192
+ laneEntry.excludedTasks.push(taskId);
193
+ continue;
194
+ }
195
+
196
+ if (isSalvageableTask(task, committedTaskIds)) {
197
+ laneEntry.salvageableTasks.push(taskId);
198
+ } else if (
199
+ hasLaneCommit &&
200
+ (status === "failed" || isNonSalvageableExitReason(task.exitReason))
201
+ ) {
202
+ laneEntry.excludedTasks.push(taskId);
203
+ }
204
+ }
205
+
206
+ for (const laneNumber of laneNumbersFromTasks(rebuilt.tasks)) {
207
+ if (!laneMap.has(laneNumber)) {
208
+ laneMap.set(laneNumber, { laneNumber, salvageableTasks: [], excludedTasks: [] });
209
+ }
210
+ }
211
+
212
+ /** @type {object[]} */
213
+ const lanes = [];
214
+ for (const laneNumber of [...laneMap.keys()].sort((a, b) => a - b)) {
215
+ const entry = laneMap.get(laneNumber);
216
+ if (entry.salvageableTasks.length === 0) continue;
217
+
218
+ const taskBranch = laneTaskBranch(resolvedBatchId, laneNumber);
219
+ if (!branchExists(projectRoot, taskBranch)) continue;
220
+
221
+ const commitsAhead = countCommitsAhead(projectRoot, baseBranch, taskBranch);
222
+ if (commitsAhead <= 0) continue;
223
+
224
+ lanes.push({
225
+ laneNumber,
226
+ taskBranch,
227
+ commitsAhead,
228
+ diffStat: collectDiffStat(projectRoot, baseBranch, taskBranch),
229
+ salvageableTasks: [...entry.salvageableTasks],
230
+ excludedTasks: [...entry.excludedTasks],
231
+ });
232
+ }
233
+
234
+ return {
235
+ ok: true,
236
+ exitCode: 0,
237
+ dryRun: true,
238
+ batchId: resolvedBatchId,
239
+ baseBranch,
240
+ lanes,
241
+ headline:
242
+ lanes.length === 0
243
+ ? `No salvageable lane commits for batch ${resolvedBatchId}`
244
+ : `${lanes.length} salvageable lane(s) for batch ${resolvedBatchId}`,
245
+ suggestedCommand:
246
+ lanes.length === 0
247
+ ? "spine status --diagnose"
248
+ : "spine batch salvage --batch <batchId> --lane <n> --integrate",
249
+ };
250
+ }
251
+
252
+ /**
253
+ * @param {ReturnType<typeof listSalvageableLanes>} result
254
+ * @param {{ json?: boolean }} [options]
255
+ */
256
+ export function formatSalvageListOutput(result, options = {}) {
257
+ if (options.json) {
258
+ return `${JSON.stringify(result, null, 2)}\n`;
259
+ }
260
+
261
+ const lines = ["", result.ok ? "Salvage list (dry-run)" : "Salvage list failed", "", ` ${result.headline}`];
262
+
263
+ if (result.error) {
264
+ lines.push("", ` Error: ${result.error}`);
265
+ }
266
+ if (result.batchId) {
267
+ lines.push("", ` Batch: ${result.batchId}`);
268
+ }
269
+ if (result.baseBranch) {
270
+ lines.push(` Base: ${result.baseBranch}`);
271
+ }
272
+
273
+ if (result.ok && Array.isArray(result.lanes)) {
274
+ for (const lane of result.lanes) {
275
+ lines.push(
276
+ "",
277
+ ` Lane ${lane.laneNumber}: ${lane.taskBranch} (${lane.commitsAhead} commit(s) ahead)`,
278
+ ` Tasks: ${lane.salvageableTasks.join(", ")}`,
279
+ );
280
+ if (lane.excludedTasks?.length) {
281
+ lines.push(` Excluded: ${lane.excludedTasks.join(", ")}`);
282
+ }
283
+ if (lane.diffStat) {
284
+ for (const statLine of String(lane.diffStat).split("\n")) {
285
+ lines.push(` ${statLine}`);
286
+ }
287
+ }
288
+ }
289
+ }
290
+
291
+ if (result.suggestedCommand) {
292
+ lines.push("", ` → ${result.suggestedCommand}`);
293
+ }
294
+
295
+ lines.push("");
296
+ return lines.join("\n");
297
+ }
298
+
299
+ /**
300
+ * @param {string} projectRoot
301
+ * @param {string[]} args
302
+ */
303
+ function git(projectRoot, args) {
304
+ return gitExec(projectRoot, args, { projectRoot });
305
+ }
306
+
307
+ /**
308
+ * Default interactive confirmation for salvage integrate.
309
+ *
310
+ * @param {object} summary
311
+ */
312
+ export async function confirmSalvageIntegrate(summary) {
313
+ if (process.stdin.isTTY !== true) {
314
+ return false;
315
+ }
316
+
317
+ const lines = [
318
+ "",
319
+ `Salvage integrate lane ${summary.laneNumber}: ${summary.taskBranch} → ${summary.baseBranch}`,
320
+ ` Commits ahead: ${summary.commitsAhead}`,
321
+ ` Salvageable tasks: ${summary.salvageableTasks.join(", ") || "(none)"}`,
322
+ ];
323
+ if (summary.excludedTasks?.length) {
324
+ lines.push(` Excluded tasks: ${summary.excludedTasks.join(", ")}`);
325
+ }
326
+ if (summary.diffStat) {
327
+ lines.push(" Diff:");
328
+ for (const statLine of String(summary.diffStat).split("\n")) {
329
+ lines.push(` ${statLine}`);
330
+ }
331
+ }
332
+ lines.push("", "Proceed with salvage integrate? [y/N] ");
333
+ process.stdout.write(lines.join("\n"));
334
+
335
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
336
+ try {
337
+ const answer = String(await rl.question("")).trim().toLowerCase();
338
+ return answer === "y" || answer === "yes";
339
+ } finally {
340
+ rl.close();
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Integrate salvageable lane commits into base after batch abort/dismiss (FR-REL220-04, #158).
346
+ *
347
+ * @param {string} projectRoot
348
+ * @param {string} batchId
349
+ * @param {number|string} laneNumber
350
+ * @param {object} [options]
351
+ * @param {boolean} [options.yes]
352
+ * @param {boolean} [options.forceIntegrate]
353
+ * @param {(summary: object) => Promise<boolean>} [options.confirmFn]
354
+ */
355
+ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber, options = {}) {
356
+ const resolvedBatchId = String(batchId ?? "").trim();
357
+ const laneNum = Number(laneNumber);
358
+ const yes = Boolean(options.yes);
359
+ const forceIntegrate = Boolean(options.forceIntegrate);
360
+ const confirmFn = options.confirmFn ?? confirmSalvageIntegrate;
361
+
362
+ if (!resolvedBatchId) {
363
+ return {
364
+ ok: false,
365
+ exitCode: 1,
366
+ error: "batch_id_required",
367
+ headline: "Batch id is required",
368
+ suggestedCommand: "spine batch salvage --batch <batchId> --lane <n> --integrate",
369
+ };
370
+ }
371
+
372
+ if (!Number.isFinite(laneNum) || laneNum <= 0) {
373
+ return {
374
+ ok: false,
375
+ exitCode: 1,
376
+ error: "lane_number_invalid",
377
+ headline: "Lane number must be a positive integer",
378
+ suggestedCommand: `spine batch salvage --batch ${resolvedBatchId} --dry-run`,
379
+ batchId: resolvedBatchId,
380
+ };
381
+ }
382
+
383
+ const listResult = listSalvageableLanes(projectRoot, resolvedBatchId);
384
+ if (!listResult.ok) {
385
+ return { ...listResult, integrate: true };
386
+ }
387
+
388
+ const lane = (listResult.lanes ?? []).find((entry) => entry.laneNumber === laneNum);
389
+ if (!lane) {
390
+ return {
391
+ ok: false,
392
+ exitCode: 1,
393
+ error: "lane_not_salvageable",
394
+ headline: `Lane ${laneNum} has no salvageable commits for batch ${resolvedBatchId}`,
395
+ suggestedCommand: `spine batch salvage --batch ${resolvedBatchId} --dry-run`,
396
+ batchId: resolvedBatchId,
397
+ laneNumber: laneNum,
398
+ };
399
+ }
400
+
401
+ const baseBranch = String(listResult.baseBranch ?? "main");
402
+ const taskBranch = String(lane.taskBranch ?? laneTaskBranch(resolvedBatchId, laneNum));
403
+
404
+ let commitsAhead = lane.commitsAhead;
405
+ try {
406
+ commitsAhead = countCommitsAhead(projectRoot, baseBranch, taskBranch);
407
+ } catch (err) {
408
+ const message = err instanceof Error ? err.message : String(err);
409
+ return {
410
+ ok: false,
411
+ exitCode: 1,
412
+ error: message,
413
+ headline: `Cannot salvage integrate — ${message}`,
414
+ suggestedCommand: "spine status --diagnose",
415
+ batchId: resolvedBatchId,
416
+ laneNumber: laneNum,
417
+ };
418
+ }
419
+
420
+ if (commitsAhead <= 0) {
421
+ return {
422
+ ok: true,
423
+ exitCode: 0,
424
+ alreadyMerged: true,
425
+ batchId: resolvedBatchId,
426
+ laneNumber: laneNum,
427
+ baseBranch,
428
+ taskBranch,
429
+ salvageableTasks: lane.salvageableTasks,
430
+ excludedTasks: lane.excludedTasks,
431
+ headline: `Lane ${laneNum} already merged into ${baseBranch}`,
432
+ suggestedCommand: "spine status --diagnose",
433
+ };
434
+ }
435
+
436
+ const configResult = loadSpineConfig(projectRoot);
437
+ const gateCheck = checkIntegrateGate({
438
+ projectRoot,
439
+ batchId: resolvedBatchId,
440
+ config: configResult.config ?? null,
441
+ forceIntegrate,
442
+ });
443
+
444
+ if (!gateCheck.ok) {
445
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
446
+ laneNumber: laneNum,
447
+ taskBranch,
448
+ baseBranch,
449
+ gateBlocked: true,
450
+ gateStatus: gateCheck.gate?.status ?? "missing",
451
+ error: gateCheck.error ?? gateCheck.headline,
452
+ });
453
+
454
+ return {
455
+ ok: false,
456
+ exitCode: gateCheck.exitCode ?? 2,
457
+ failureClass: gateCheck.failureClass ?? "GateBlocked",
458
+ error: gateCheck.error,
459
+ headline: gateCheck.headline ?? "Salvage integrate blocked by gate",
460
+ suggestedCommand: gateCheck.suggestedCommand ?? "spine gate approve",
461
+ alternatives: gateCheck.alternatives ?? ["/spine-gate approve"],
462
+ batchId: resolvedBatchId,
463
+ laneNumber: laneNum,
464
+ gate: gateCheck.gate ?? null,
465
+ };
466
+ }
467
+
468
+ if (!yes) {
469
+ if (process.stdin.isTTY !== true) {
470
+ return {
471
+ ok: false,
472
+ exitCode: 1,
473
+ error: "confirmation_required",
474
+ headline: "Non-interactive mode requires --yes to salvage integrate",
475
+ suggestedCommand: `spine batch salvage --batch ${resolvedBatchId} --lane ${laneNum} --integrate --yes`,
476
+ batchId: resolvedBatchId,
477
+ laneNumber: laneNum,
478
+ baseBranch,
479
+ taskBranch,
480
+ commitsAhead,
481
+ salvageableTasks: lane.salvageableTasks,
482
+ excludedTasks: lane.excludedTasks,
483
+ };
484
+ }
485
+
486
+ const confirmed = await confirmFn({
487
+ laneNumber: laneNum,
488
+ taskBranch,
489
+ baseBranch,
490
+ commitsAhead,
491
+ salvageableTasks: lane.salvageableTasks,
492
+ excludedTasks: lane.excludedTasks,
493
+ diffStat: lane.diffStat,
494
+ });
495
+
496
+ if (!confirmed) {
497
+ return {
498
+ ok: false,
499
+ exitCode: 1,
500
+ error: "confirmation_declined",
501
+ cancelled: true,
502
+ headline: "Salvage integrate cancelled",
503
+ suggestedCommand: `spine batch salvage --batch ${resolvedBatchId} --lane ${laneNum} --integrate --yes`,
504
+ batchId: resolvedBatchId,
505
+ laneNumber: laneNum,
506
+ };
507
+ }
508
+ }
509
+
510
+ const drift = resolveRulesManifestIntegrateDrift({
511
+ projectRoot,
512
+ baseBranch,
513
+ orchBranch: taskBranch,
514
+ isolatedMerge: true,
515
+ });
516
+ if (!drift.ok) {
517
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
518
+ laneNumber: laneNum,
519
+ taskBranch,
520
+ baseBranch,
521
+ error: drift.error,
522
+ failureClass: drift.failureClass ?? "DirtyWorktree",
523
+ });
524
+ return {
525
+ ok: false,
526
+ exitCode: 1,
527
+ error: drift.error,
528
+ failureClass: drift.failureClass ?? "DirtyWorktree",
529
+ headline: drift.error ?? "Salvage integrate refused — dirty rules-manifest",
530
+ suggestedCommand: "spine status --diagnose",
531
+ batchId: resolvedBatchId,
532
+ laneNumber: laneNum,
533
+ };
534
+ }
535
+
536
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_started", {
537
+ laneNumber: laneNum,
538
+ taskBranch,
539
+ baseBranch,
540
+ commitsAhead,
541
+ salvageableTasks: lane.salvageableTasks,
542
+ excludedTasks: lane.excludedTasks,
543
+ gateRequired: gateCheck.required ?? false,
544
+ gateForced: gateCheck.forced ?? false,
545
+ });
546
+
547
+ const mergeResult = mergeOrchIntoBaseIsolated({
548
+ projectRoot,
549
+ baseBranch,
550
+ orchBranch: taskBranch,
551
+ batchId: resolvedBatchId,
552
+ });
553
+
554
+ if (!mergeResult.ok) {
555
+ const conflict = mergeResult.failureClass === "MergeConflict";
556
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
557
+ laneNumber: laneNum,
558
+ taskBranch,
559
+ baseBranch,
560
+ error: String(mergeResult.error ?? "merge failed").slice(0, 500),
561
+ conflict,
562
+ failureClass: mergeResult.failureClass ?? "IntegrateFailed",
563
+ });
564
+
565
+ return {
566
+ ok: false,
567
+ exitCode: 1,
568
+ error: mergeResult.error,
569
+ failureClass: mergeResult.failureClass ?? (conflict ? "MergeConflict" : "IntegrateFailed"),
570
+ headline: conflict
571
+ ? `Merge conflict salvaging ${taskBranch} into ${baseBranch} — resolve manually`
572
+ : `Salvage integrate failed: ${mergeResult.error ?? "merge failed"}`,
573
+ suggestedCommand: "spine status --diagnose",
574
+ batchId: resolvedBatchId,
575
+ laneNumber: laneNum,
576
+ alternatives: ["/spine-gate"],
577
+ };
578
+ }
579
+
580
+ const mergeCommit = mergeResult.mergeCommit;
581
+ /** @type {{ ok: boolean, timedOut?: boolean, error?: string } | null} */
582
+ let syncResult = null;
583
+ if (mergeResult.mode === "plumbing") {
584
+ const baseSha = git(projectRoot, ["rev-parse", `${mergeCommit}^1`]);
585
+ syncResult = syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit);
586
+ }
587
+
588
+ if (syncResult && !syncResult.ok) {
589
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
590
+ laneNumber: laneNum,
591
+ taskBranch,
592
+ baseBranch,
593
+ timeout: Boolean(syncResult.timedOut),
594
+ error: (syncResult.error ?? "sync failed").slice(0, 500),
595
+ mergeCommitLanded: true,
596
+ mergeCommit,
597
+ });
598
+
599
+ return {
600
+ ok: false,
601
+ exitCode: 1,
602
+ error: syncResult.error ?? "post-merge sync failed",
603
+ failureClass: syncResult.timedOut ? "IntegrateTimeout" : "IntegrateFailed",
604
+ headline: syncResult.timedOut
605
+ ? `Salvage integrate sync timed out after merge landed — ${taskBranch} into ${baseBranch}`
606
+ : `Salvage integrate post-merge sync failed — ${syncResult.error}`,
607
+ suggestedCommand: "spine status --diagnose",
608
+ batchId: resolvedBatchId,
609
+ laneNumber: laneNum,
610
+ mergeCommitLanded: true,
611
+ };
612
+ }
613
+
614
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrated", {
615
+ laneNumber: laneNum,
616
+ taskBranch,
617
+ baseBranch,
618
+ mergeCommit,
619
+ commitsAhead,
620
+ salvageableTasks: lane.salvageableTasks,
621
+ excludedTasks: lane.excludedTasks,
622
+ });
623
+
624
+ return {
625
+ ok: true,
626
+ exitCode: 0,
627
+ batchId: resolvedBatchId,
628
+ laneNumber: laneNum,
629
+ baseBranch,
630
+ taskBranch,
631
+ mergeCommit,
632
+ commitsAhead,
633
+ salvageableTasks: lane.salvageableTasks,
634
+ excludedTasks: lane.excludedTasks,
635
+ headline: `Salvaged lane ${laneNum} (${taskBranch}) into ${baseBranch}`,
636
+ suggestedCommand: "spine status --diagnose",
637
+ };
638
+ }
639
+
640
+ /**
641
+ * @param {Awaited<ReturnType<typeof integrateSalvageableLane>>} result
642
+ * @param {{ json?: boolean }} [options]
643
+ */
644
+ export function formatSalvageIntegrateOutput(result, options = {}) {
645
+ if (options.json) {
646
+ return `${JSON.stringify(result, null, 2)}\n`;
647
+ }
648
+
649
+ const lines = [
650
+ "",
651
+ result.ok ? "Salvage integrate" : result.cancelled ? "Salvage integrate cancelled" : "Salvage integrate failed",
652
+ "",
653
+ ` ${result.headline}`,
654
+ ];
655
+
656
+ if (result.error) {
657
+ lines.push("", ` Error: ${result.error}`);
658
+ }
659
+ if (result.batchId) {
660
+ lines.push("", ` Batch: ${result.batchId}`);
661
+ }
662
+ if (result.laneNumber != null) {
663
+ lines.push(` Lane: ${result.laneNumber}`);
664
+ }
665
+ if (result.baseBranch && result.taskBranch) {
666
+ lines.push(` Merge: ${result.taskBranch} → ${result.baseBranch}`);
667
+ }
668
+ if (result.salvageableTasks?.length) {
669
+ lines.push(` Tasks: ${result.salvageableTasks.join(", ")}`);
670
+ }
671
+ if (result.excludedTasks?.length) {
672
+ lines.push(` Excluded: ${result.excludedTasks.join(", ")}`);
673
+ }
674
+ if (result.mergeCommit) {
675
+ lines.push(` Merge commit: ${result.mergeCommit}`);
676
+ }
677
+
678
+ if (result.suggestedCommand) {
679
+ lines.push("", ` → ${result.suggestedCommand}`);
680
+ }
681
+
682
+ if (result.alternatives?.length) {
683
+ lines.push("", " Alternatives:");
684
+ for (const alt of result.alternatives) {
685
+ lines.push(` • ${alt}`);
686
+ }
687
+ }
688
+
689
+ lines.push("");
690
+ return lines.join("\n");
691
+ }