pi-spine 2.0.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.
Files changed (36) hide show
  1. package/bin/spine-batch.mjs +74 -5
  2. package/bin/spine-cleanup.mjs +89 -0
  3. package/bin/spine-cli/verify.mjs +1 -0
  4. package/bin/spine-doctor.mjs +8 -0
  5. package/bin/spine.mjs +13 -0
  6. package/package.json +4 -1
  7. package/skills/create-spine-tasks/SKILL.md +28 -0
  8. package/skills/create-spine-tasks/references/contract-template.md +11 -0
  9. package/skills/create-spine-tasks/references/prompt-template.md +7 -1
  10. package/skills/spine-autonomous-operator/SKILL.md +19 -3
  11. package/skills/spine-autonomous-operator/references/agent-shell-batch-policy.md +18 -0
  12. package/skills/spine-orchestrate-waves/SKILL.md +9 -2
  13. package/skills/spine-orchestrate-waves/references/outer-loop.md +24 -2
  14. package/skills/spine-release-operator/SKILL.md +25 -2
  15. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +96 -0
  16. package/skills/spine-release-operator/references/release-manifest-template.md +7 -3
  17. package/src/batch/abort.mjs +10 -14
  18. package/src/batch/attached-runner.mjs +12 -1
  19. package/src/batch/diagnosis-merge-failure.mjs +66 -0
  20. package/src/batch/diagnosis-parent-exit.mjs +125 -0
  21. package/src/batch/diagnosis.mjs +26 -73
  22. package/src/batch/engine-lanes/merge.mjs +25 -0
  23. package/src/batch/journal-rebuild.mjs +80 -1
  24. package/src/batch/lane-dirty-check.mjs +10 -0
  25. package/src/batch/lifecycle.mjs +1 -18
  26. package/src/batch/reconcile.mjs +11 -0
  27. package/src/batch/resume-multi-lanes.mjs +38 -1
  28. package/src/batch/review.mjs +20 -0
  29. package/src/batch/salvage-batch.mjs +691 -0
  30. package/src/batch/worktree.mjs +130 -1
  31. package/src/config/preflight/git-batch.mjs +14 -3
  32. package/src/doctor/duplicate-install.mjs +148 -0
  33. package/src/doctor/pi-cli-resolution.mjs +222 -0
  34. package/src/doctor/run-doctor-checks.mjs +4 -0
  35. package/src/doctor/stale-worktrees.mjs +1 -1
  36. package/src/tasks/packet/parse-prompt.mjs +29 -0
@@ -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
+ }