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,291 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Salvage list (dry-run) after batch abort/dismiss (FR-REL220-03, #158).
4
+ * Extracted from salvage-batch.mjs (SP-591); integrate remains in salvage-batch.mjs until SP-605.
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import { execFileSync } from "node:child_process";
9
+ import { archiveBatchStatePath } from "./lifecycle.mjs";
10
+ import { countCommitsAhead } from "./lane-commit.mjs";
11
+ import { journalPath, readJournalEvents } from "./journal.mjs";
12
+ import { rebuildBatchStateFromJournal } from "./journal-rebuild.mjs";
13
+ import { loadBatchStateFile } from "./reconcile.mjs";
14
+ import { laneTaskBranch } from "./worktree.mjs";
15
+
16
+ /** Exit reasons that block salvage even when a lane commit exists. */
17
+ export const NON_SALVAGEABLE_EXIT_REASONS = new Set([
18
+ "contract_failed",
19
+ "review_exhausted",
20
+ "review_failed",
21
+ "code_review_invalid_verdict",
22
+ "final_review_invalid_verdict",
23
+ "CONTRACT_FAIL",
24
+ ]);
25
+
26
+ /**
27
+ * @param {string|null|undefined} exitReason
28
+ */
29
+ export function isNonSalvageableExitReason(exitReason) {
30
+ if (!exitReason) return false;
31
+ return NON_SALVAGEABLE_EXIT_REASONS.has(String(exitReason));
32
+ }
33
+
34
+ /**
35
+ * @param {string} projectRoot
36
+ * @param {string} baseBranch
37
+ * @param {string} headRef
38
+ */
39
+ function collectDiffStat(projectRoot, baseBranch, headRef) {
40
+ try {
41
+ return execFileSync("git", ["diff", "--stat", `${baseBranch}..${headRef}`], {
42
+ cwd: projectRoot,
43
+ encoding: "utf-8",
44
+ stdio: ["ignore", "pipe", "pipe"],
45
+ }).trim();
46
+ } catch (err) {
47
+ const message = err instanceof Error ? err.message : String(err);
48
+ return `(git diff --stat failed: ${message})`;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * @param {string} projectRoot
54
+ * @param {string} ref
55
+ */
56
+ function branchExists(projectRoot, ref) {
57
+ try {
58
+ execFileSync("git", ["rev-parse", "--verify", ref], {
59
+ cwd: projectRoot,
60
+ encoding: "utf-8",
61
+ stdio: ["ignore", "pipe", "pipe"],
62
+ });
63
+ return true;
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * @param {object[]} journalEvents
71
+ */
72
+ function laneCommittedTaskIds(journalEvents) {
73
+ /** @type {Set<string>} */
74
+ const committed = new Set();
75
+ for (const event of journalEvents) {
76
+ if (String(event?.type ?? "") !== "lane.committed") continue;
77
+ const taskId = typeof event.taskId === "string" ? event.taskId : event.payload?.taskId;
78
+ if (taskId) committed.add(String(taskId));
79
+ }
80
+ return committed;
81
+ }
82
+
83
+ /**
84
+ * @param {string} projectRoot
85
+ * @param {string} batchId
86
+ */
87
+ function loadSalvageBatchSeed(projectRoot, batchId) {
88
+ const archivePath = archiveBatchStatePath(projectRoot, batchId);
89
+ if (fs.existsSync(archivePath)) {
90
+ try {
91
+ return JSON.parse(fs.readFileSync(archivePath, "utf-8"));
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+
97
+ const loaded = loadBatchStateFile(projectRoot);
98
+ if (loaded.raw && String(loaded.raw.batchId ?? loaded.raw.id ?? "") === batchId) {
99
+ return loaded.raw;
100
+ }
101
+
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * @param {object[]} tasks
107
+ */
108
+ function laneNumbersFromTasks(tasks) {
109
+ /** @type {Set<number>} */
110
+ const lanes = new Set();
111
+ for (const task of tasks ?? []) {
112
+ const laneNumber = Number(task?.laneNumber);
113
+ if (Number.isFinite(laneNumber) && laneNumber > 0) lanes.add(laneNumber);
114
+ }
115
+ return lanes;
116
+ }
117
+
118
+ /**
119
+ * @param {object} task
120
+ * @param {Set<string>} committedTaskIds
121
+ */
122
+ function isSalvageableTask(task, committedTaskIds) {
123
+ const taskId = String(task?.taskId ?? "");
124
+ if (!taskId) return false;
125
+ if (!committedTaskIds.has(taskId)) return false;
126
+
127
+ const status = String(task?.status ?? "").toLowerCase();
128
+ if (status !== "succeeded" && status !== "skipped") return false;
129
+ if (isNonSalvageableExitReason(task?.exitReason)) return false;
130
+ return true;
131
+ }
132
+
133
+ /**
134
+ * List lanes with salvageable commits after abort/dismiss (read-only).
135
+ *
136
+ * @param {string} projectRoot
137
+ * @param {string} batchId
138
+ */
139
+ export function listSalvageableLanes(projectRoot, batchId) {
140
+ const resolvedBatchId = String(batchId ?? "").trim();
141
+ if (!resolvedBatchId) {
142
+ return {
143
+ ok: false,
144
+ exitCode: 1,
145
+ error: "batch_id_required",
146
+ headline: "Batch id is required",
147
+ suggestedCommand: "spine batch salvage --batch <batchId> --dry-run",
148
+ };
149
+ }
150
+
151
+ const journalFile = journalPath(projectRoot, resolvedBatchId);
152
+ if (!fs.existsSync(journalFile)) {
153
+ return {
154
+ ok: false,
155
+ exitCode: 1,
156
+ error: "journal_missing",
157
+ headline: `No journal found for batch ${resolvedBatchId}`,
158
+ suggestedCommand: "spine status --diagnose",
159
+ batchId: resolvedBatchId,
160
+ };
161
+ }
162
+
163
+ const journalEvents = readJournalEvents(projectRoot, resolvedBatchId);
164
+ const seedState = loadSalvageBatchSeed(projectRoot, resolvedBatchId);
165
+ const rebuilt = rebuildBatchStateFromJournal(seedState, journalEvents);
166
+ const baseBranch = String(rebuilt.baseBranch ?? seedState?.baseBranch ?? "main");
167
+ const committedTaskIds = laneCommittedTaskIds(journalEvents);
168
+
169
+ /** @type {Map<number, { laneNumber: number, salvageableTasks: string[], excludedTasks: string[] }>} */
170
+ const laneMap = new Map();
171
+
172
+ for (const task of rebuilt.tasks ?? []) {
173
+ const laneNumber = Number(task?.laneNumber);
174
+ if (!Number.isFinite(laneNumber) || laneNumber <= 0) continue;
175
+
176
+ if (!laneMap.has(laneNumber)) {
177
+ laneMap.set(laneNumber, { laneNumber, salvageableTasks: [], excludedTasks: [] });
178
+ }
179
+ const laneEntry = laneMap.get(laneNumber);
180
+
181
+ const taskId = String(task.taskId ?? "");
182
+ const status = String(task.status ?? "").toLowerCase();
183
+ const hasLaneCommit = committedTaskIds.has(taskId);
184
+
185
+ if (hasLaneCommit && isNonSalvageableExitReason(task.exitReason)) {
186
+ laneEntry.excludedTasks.push(taskId);
187
+ continue;
188
+ }
189
+
190
+ if (isSalvageableTask(task, committedTaskIds)) {
191
+ laneEntry.salvageableTasks.push(taskId);
192
+ } else if (
193
+ hasLaneCommit &&
194
+ (status === "failed" || isNonSalvageableExitReason(task.exitReason))
195
+ ) {
196
+ laneEntry.excludedTasks.push(taskId);
197
+ }
198
+ }
199
+
200
+ for (const laneNumber of laneNumbersFromTasks(rebuilt.tasks)) {
201
+ if (!laneMap.has(laneNumber)) {
202
+ laneMap.set(laneNumber, { laneNumber, salvageableTasks: [], excludedTasks: [] });
203
+ }
204
+ }
205
+
206
+ /** @type {object[]} */
207
+ const lanes = [];
208
+ for (const laneNumber of [...laneMap.keys()].sort((a, b) => a - b)) {
209
+ const entry = laneMap.get(laneNumber);
210
+ if (entry.salvageableTasks.length === 0) continue;
211
+
212
+ const taskBranch = laneTaskBranch(resolvedBatchId, laneNumber);
213
+ if (!branchExists(projectRoot, taskBranch)) continue;
214
+
215
+ const commitsAhead = countCommitsAhead(projectRoot, baseBranch, taskBranch);
216
+ if (commitsAhead <= 0) continue;
217
+
218
+ lanes.push({
219
+ laneNumber,
220
+ taskBranch,
221
+ commitsAhead,
222
+ diffStat: collectDiffStat(projectRoot, baseBranch, taskBranch),
223
+ salvageableTasks: [...entry.salvageableTasks],
224
+ excludedTasks: [...entry.excludedTasks],
225
+ });
226
+ }
227
+
228
+ return {
229
+ ok: true,
230
+ exitCode: 0,
231
+ dryRun: true,
232
+ batchId: resolvedBatchId,
233
+ baseBranch,
234
+ lanes,
235
+ headline:
236
+ lanes.length === 0
237
+ ? `No salvageable lane commits for batch ${resolvedBatchId}`
238
+ : `${lanes.length} salvageable lane(s) for batch ${resolvedBatchId}`,
239
+ suggestedCommand:
240
+ lanes.length === 0
241
+ ? "spine status --diagnose"
242
+ : "spine batch salvage --batch <batchId> --lane <n> --integrate",
243
+ };
244
+ }
245
+
246
+ /**
247
+ * @param {ReturnType<typeof listSalvageableLanes>} result
248
+ * @param {{ json?: boolean }} [options]
249
+ */
250
+ export function formatSalvageListOutput(result, options = {}) {
251
+ if (options.json) {
252
+ return `${JSON.stringify(result, null, 2)}\n`;
253
+ }
254
+
255
+ const lines = ["", result.ok ? "Salvage list (dry-run)" : "Salvage list failed", "", ` ${result.headline}`];
256
+
257
+ if (result.error) {
258
+ lines.push("", ` Error: ${result.error}`);
259
+ }
260
+ if (result.batchId) {
261
+ lines.push("", ` Batch: ${result.batchId}`);
262
+ }
263
+ if (result.baseBranch) {
264
+ lines.push(` Base: ${result.baseBranch}`);
265
+ }
266
+
267
+ if (result.ok && Array.isArray(result.lanes)) {
268
+ for (const lane of result.lanes) {
269
+ lines.push(
270
+ "",
271
+ ` Lane ${lane.laneNumber}: ${lane.taskBranch} (${lane.commitsAhead} commit(s) ahead)`,
272
+ ` Tasks: ${lane.salvageableTasks.join(", ")}`,
273
+ );
274
+ if (lane.excludedTasks?.length) {
275
+ lines.push(` Excluded: ${lane.excludedTasks.join(", ")}`);
276
+ }
277
+ if (lane.diffStat) {
278
+ for (const statLine of String(lane.diffStat).split("\n")) {
279
+ lines.push(` ${statLine}`);
280
+ }
281
+ }
282
+ }
283
+ }
284
+
285
+ if (result.suggestedCommand) {
286
+ lines.push("", ` → ${result.suggestedCommand}`);
287
+ }
288
+
289
+ lines.push("");
290
+ return lines.join("\n");
291
+ }
@@ -0,0 +1,417 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Operator salvage after batch abort/dismiss (FR-REL220-03, #158).
4
+ * List API → salvage-batch-list.mjs (SP-591); integrate remains here until SP-605.
5
+ */
6
+
7
+ import readline from "node:readline/promises";
8
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
+ import { countCommitsAhead } from "./lane-commit.mjs";
10
+ import { checkIntegrateGate } from "./gate.mjs";
11
+ import { gitExec } from "./git-exec.mjs";
12
+ import { mergeOrchIntoBaseIsolated, syncPlumbingMergePathsToWorktree } from "./integrate-worktree.mjs";
13
+ import { appendJournalEvent } from "./journal.mjs";
14
+ import { resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
15
+ import { laneTaskBranch } from "./worktree.mjs";
16
+ import { listSalvageableLanes } from "./salvage-batch-list.mjs";
17
+
18
+ export {
19
+ NON_SALVAGEABLE_EXIT_REASONS,
20
+ formatSalvageListOutput,
21
+ isNonSalvageableExitReason,
22
+ listSalvageableLanes,
23
+ } from "./salvage-batch-list.mjs";
24
+
25
+ /**
26
+ * @param {string} projectRoot
27
+ * @param {string[]} args
28
+ */
29
+ function git(projectRoot, args) {
30
+ return gitExec(projectRoot, args, { projectRoot });
31
+ }
32
+
33
+ /**
34
+ * Default interactive confirmation for salvage integrate.
35
+ *
36
+ * @param {object} summary
37
+ */
38
+ export async function confirmSalvageIntegrate(summary) {
39
+ if (process.stdin.isTTY !== true) {
40
+ return false;
41
+ }
42
+
43
+ const lines = [
44
+ "",
45
+ `Salvage integrate lane ${summary.laneNumber}: ${summary.taskBranch} → ${summary.baseBranch}`,
46
+ ` Commits ahead: ${summary.commitsAhead}`,
47
+ ` Salvageable tasks: ${summary.salvageableTasks.join(", ") || "(none)"}`,
48
+ ];
49
+ if (summary.excludedTasks?.length) {
50
+ lines.push(` Excluded tasks: ${summary.excludedTasks.join(", ")}`);
51
+ }
52
+ if (summary.diffStat) {
53
+ lines.push(" Diff:");
54
+ for (const statLine of String(summary.diffStat).split("\n")) {
55
+ lines.push(` ${statLine}`);
56
+ }
57
+ }
58
+ lines.push("", "Proceed with salvage integrate? [y/N] ");
59
+ process.stdout.write(lines.join("\n"));
60
+
61
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
62
+ try {
63
+ const answer = String(await rl.question("")).trim().toLowerCase();
64
+ return answer === "y" || answer === "yes";
65
+ } finally {
66
+ rl.close();
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Integrate salvageable lane commits into base after batch abort/dismiss (FR-REL220-04, #158).
72
+ *
73
+ * @param {string} projectRoot
74
+ * @param {string} batchId
75
+ * @param {number|string} laneNumber
76
+ * @param {object} [options]
77
+ * @param {boolean} [options.yes]
78
+ * @param {boolean} [options.forceIntegrate]
79
+ * @param {(summary: object) => Promise<boolean>} [options.confirmFn]
80
+ */
81
+ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber, options = {}) {
82
+ const resolvedBatchId = String(batchId ?? "").trim();
83
+ const laneNum = Number(laneNumber);
84
+ const yes = Boolean(options.yes);
85
+ const forceIntegrate = Boolean(options.forceIntegrate);
86
+ const confirmFn = options.confirmFn ?? confirmSalvageIntegrate;
87
+
88
+ if (!resolvedBatchId) {
89
+ return {
90
+ ok: false,
91
+ exitCode: 1,
92
+ error: "batch_id_required",
93
+ headline: "Batch id is required",
94
+ suggestedCommand: "spine batch salvage --batch <batchId> --lane <n> --integrate",
95
+ };
96
+ }
97
+
98
+ if (!Number.isFinite(laneNum) || laneNum <= 0) {
99
+ return {
100
+ ok: false,
101
+ exitCode: 1,
102
+ error: "lane_number_invalid",
103
+ headline: "Lane number must be a positive integer",
104
+ suggestedCommand: `spine batch salvage --batch ${resolvedBatchId} --dry-run`,
105
+ batchId: resolvedBatchId,
106
+ };
107
+ }
108
+
109
+ const listResult = listSalvageableLanes(projectRoot, resolvedBatchId);
110
+ if (!listResult.ok) {
111
+ return { ...listResult, integrate: true };
112
+ }
113
+
114
+ const lane = (listResult.lanes ?? []).find((entry) => entry.laneNumber === laneNum);
115
+ if (!lane) {
116
+ return {
117
+ ok: false,
118
+ exitCode: 1,
119
+ error: "lane_not_salvageable",
120
+ headline: `Lane ${laneNum} has no salvageable commits for batch ${resolvedBatchId}`,
121
+ suggestedCommand: `spine batch salvage --batch ${resolvedBatchId} --dry-run`,
122
+ batchId: resolvedBatchId,
123
+ laneNumber: laneNum,
124
+ };
125
+ }
126
+
127
+ const baseBranch = String(listResult.baseBranch ?? "main");
128
+ const taskBranch = String(lane.taskBranch ?? laneTaskBranch(resolvedBatchId, laneNum));
129
+
130
+ let commitsAhead = lane.commitsAhead;
131
+ try {
132
+ commitsAhead = countCommitsAhead(projectRoot, baseBranch, taskBranch);
133
+ } catch (err) {
134
+ const message = err instanceof Error ? err.message : String(err);
135
+ return {
136
+ ok: false,
137
+ exitCode: 1,
138
+ error: message,
139
+ headline: `Cannot salvage integrate — ${message}`,
140
+ suggestedCommand: "spine status --diagnose",
141
+ batchId: resolvedBatchId,
142
+ laneNumber: laneNum,
143
+ };
144
+ }
145
+
146
+ if (commitsAhead <= 0) {
147
+ return {
148
+ ok: true,
149
+ exitCode: 0,
150
+ alreadyMerged: true,
151
+ batchId: resolvedBatchId,
152
+ laneNumber: laneNum,
153
+ baseBranch,
154
+ taskBranch,
155
+ salvageableTasks: lane.salvageableTasks,
156
+ excludedTasks: lane.excludedTasks,
157
+ headline: `Lane ${laneNum} already merged into ${baseBranch}`,
158
+ suggestedCommand: "spine status --diagnose",
159
+ };
160
+ }
161
+
162
+ const configResult = loadSpineConfig(projectRoot);
163
+ const gateCheck = checkIntegrateGate({
164
+ projectRoot,
165
+ batchId: resolvedBatchId,
166
+ config: configResult.config ?? null,
167
+ forceIntegrate,
168
+ });
169
+
170
+ if (!gateCheck.ok) {
171
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
172
+ laneNumber: laneNum,
173
+ taskBranch,
174
+ baseBranch,
175
+ gateBlocked: true,
176
+ gateStatus: gateCheck.gate?.status ?? "missing",
177
+ error: gateCheck.error ?? gateCheck.headline,
178
+ });
179
+
180
+ return {
181
+ ok: false,
182
+ exitCode: gateCheck.exitCode ?? 2,
183
+ failureClass: gateCheck.failureClass ?? "GateBlocked",
184
+ error: gateCheck.error,
185
+ headline: gateCheck.headline ?? "Salvage integrate blocked by gate",
186
+ suggestedCommand: gateCheck.suggestedCommand ?? "spine gate approve",
187
+ alternatives: gateCheck.alternatives ?? ["/spine-gate approve"],
188
+ batchId: resolvedBatchId,
189
+ laneNumber: laneNum,
190
+ gate: gateCheck.gate ?? null,
191
+ };
192
+ }
193
+
194
+ if (!yes) {
195
+ if (process.stdin.isTTY !== true) {
196
+ return {
197
+ ok: false,
198
+ exitCode: 1,
199
+ error: "confirmation_required",
200
+ headline: "Non-interactive mode requires --yes to salvage integrate",
201
+ suggestedCommand: `spine batch salvage --batch ${resolvedBatchId} --lane ${laneNum} --integrate --yes`,
202
+ batchId: resolvedBatchId,
203
+ laneNumber: laneNum,
204
+ baseBranch,
205
+ taskBranch,
206
+ commitsAhead,
207
+ salvageableTasks: lane.salvageableTasks,
208
+ excludedTasks: lane.excludedTasks,
209
+ };
210
+ }
211
+
212
+ const confirmed = await confirmFn({
213
+ laneNumber: laneNum,
214
+ taskBranch,
215
+ baseBranch,
216
+ commitsAhead,
217
+ salvageableTasks: lane.salvageableTasks,
218
+ excludedTasks: lane.excludedTasks,
219
+ diffStat: lane.diffStat,
220
+ });
221
+
222
+ if (!confirmed) {
223
+ return {
224
+ ok: false,
225
+ exitCode: 1,
226
+ error: "confirmation_declined",
227
+ cancelled: true,
228
+ headline: "Salvage integrate cancelled",
229
+ suggestedCommand: `spine batch salvage --batch ${resolvedBatchId} --lane ${laneNum} --integrate --yes`,
230
+ batchId: resolvedBatchId,
231
+ laneNumber: laneNum,
232
+ };
233
+ }
234
+ }
235
+
236
+ const drift = resolveRulesManifestIntegrateDrift({
237
+ projectRoot,
238
+ baseBranch,
239
+ orchBranch: taskBranch,
240
+ isolatedMerge: true,
241
+ });
242
+ if (!drift.ok) {
243
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
244
+ laneNumber: laneNum,
245
+ taskBranch,
246
+ baseBranch,
247
+ error: drift.error,
248
+ failureClass: drift.failureClass ?? "DirtyWorktree",
249
+ });
250
+ return {
251
+ ok: false,
252
+ exitCode: 1,
253
+ error: drift.error,
254
+ failureClass: drift.failureClass ?? "DirtyWorktree",
255
+ headline: drift.error ?? "Salvage integrate refused — dirty rules-manifest",
256
+ suggestedCommand: "spine status --diagnose",
257
+ batchId: resolvedBatchId,
258
+ laneNumber: laneNum,
259
+ };
260
+ }
261
+
262
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_started", {
263
+ laneNumber: laneNum,
264
+ taskBranch,
265
+ baseBranch,
266
+ commitsAhead,
267
+ salvageableTasks: lane.salvageableTasks,
268
+ excludedTasks: lane.excludedTasks,
269
+ gateRequired: gateCheck.required ?? false,
270
+ gateForced: gateCheck.forced ?? false,
271
+ });
272
+
273
+ const mergeResult = mergeOrchIntoBaseIsolated({
274
+ projectRoot,
275
+ baseBranch,
276
+ orchBranch: taskBranch,
277
+ batchId: resolvedBatchId,
278
+ });
279
+
280
+ if (!mergeResult.ok) {
281
+ const conflict = mergeResult.failureClass === "MergeConflict";
282
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
283
+ laneNumber: laneNum,
284
+ taskBranch,
285
+ baseBranch,
286
+ error: String(mergeResult.error ?? "merge failed").slice(0, 500),
287
+ conflict,
288
+ failureClass: mergeResult.failureClass ?? "IntegrateFailed",
289
+ });
290
+
291
+ return {
292
+ ok: false,
293
+ exitCode: 1,
294
+ error: mergeResult.error,
295
+ failureClass: mergeResult.failureClass ?? (conflict ? "MergeConflict" : "IntegrateFailed"),
296
+ headline: conflict
297
+ ? `Merge conflict salvaging ${taskBranch} into ${baseBranch} — resolve manually`
298
+ : `Salvage integrate failed: ${mergeResult.error ?? "merge failed"}`,
299
+ suggestedCommand: "spine status --diagnose",
300
+ batchId: resolvedBatchId,
301
+ laneNumber: laneNum,
302
+ alternatives: ["/spine-gate"],
303
+ };
304
+ }
305
+
306
+ const mergeCommit = mergeResult.mergeCommit;
307
+ /** @type {{ ok: boolean, timedOut?: boolean, error?: string } | null} */
308
+ let syncResult = null;
309
+ if (mergeResult.mode === "plumbing") {
310
+ const baseSha = git(projectRoot, ["rev-parse", `${mergeCommit}^1`]);
311
+ syncResult = syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit);
312
+ }
313
+
314
+ if (syncResult && !syncResult.ok) {
315
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
316
+ laneNumber: laneNum,
317
+ taskBranch,
318
+ baseBranch,
319
+ timeout: Boolean(syncResult.timedOut),
320
+ error: (syncResult.error ?? "sync failed").slice(0, 500),
321
+ mergeCommitLanded: true,
322
+ mergeCommit,
323
+ });
324
+
325
+ return {
326
+ ok: false,
327
+ exitCode: 1,
328
+ error: syncResult.error ?? "post-merge sync failed",
329
+ failureClass: syncResult.timedOut ? "IntegrateTimeout" : "IntegrateFailed",
330
+ headline: syncResult.timedOut
331
+ ? `Salvage integrate sync timed out after merge landed — ${taskBranch} into ${baseBranch}`
332
+ : `Salvage integrate post-merge sync failed — ${syncResult.error}`,
333
+ suggestedCommand: "spine status --diagnose",
334
+ batchId: resolvedBatchId,
335
+ laneNumber: laneNum,
336
+ mergeCommitLanded: true,
337
+ };
338
+ }
339
+
340
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrated", {
341
+ laneNumber: laneNum,
342
+ taskBranch,
343
+ baseBranch,
344
+ mergeCommit,
345
+ commitsAhead,
346
+ salvageableTasks: lane.salvageableTasks,
347
+ excludedTasks: lane.excludedTasks,
348
+ });
349
+
350
+ return {
351
+ ok: true,
352
+ exitCode: 0,
353
+ batchId: resolvedBatchId,
354
+ laneNumber: laneNum,
355
+ baseBranch,
356
+ taskBranch,
357
+ mergeCommit,
358
+ commitsAhead,
359
+ salvageableTasks: lane.salvageableTasks,
360
+ excludedTasks: lane.excludedTasks,
361
+ headline: `Salvaged lane ${laneNum} (${taskBranch}) into ${baseBranch}`,
362
+ suggestedCommand: "spine status --diagnose",
363
+ };
364
+ }
365
+
366
+ /**
367
+ * @param {Awaited<ReturnType<typeof integrateSalvageableLane>>} result
368
+ * @param {{ json?: boolean }} [options]
369
+ */
370
+ export function formatSalvageIntegrateOutput(result, options = {}) {
371
+ if (options.json) {
372
+ return `${JSON.stringify(result, null, 2)}\n`;
373
+ }
374
+
375
+ const lines = [
376
+ "",
377
+ result.ok ? "Salvage integrate" : result.cancelled ? "Salvage integrate cancelled" : "Salvage integrate failed",
378
+ "",
379
+ ` ${result.headline}`,
380
+ ];
381
+
382
+ if (result.error) {
383
+ lines.push("", ` Error: ${result.error}`);
384
+ }
385
+ if (result.batchId) {
386
+ lines.push("", ` Batch: ${result.batchId}`);
387
+ }
388
+ if (result.laneNumber != null) {
389
+ lines.push(` Lane: ${result.laneNumber}`);
390
+ }
391
+ if (result.baseBranch && result.taskBranch) {
392
+ lines.push(` Merge: ${result.taskBranch} → ${result.baseBranch}`);
393
+ }
394
+ if (result.salvageableTasks?.length) {
395
+ lines.push(` Tasks: ${result.salvageableTasks.join(", ")}`);
396
+ }
397
+ if (result.excludedTasks?.length) {
398
+ lines.push(` Excluded: ${result.excludedTasks.join(", ")}`);
399
+ }
400
+ if (result.mergeCommit) {
401
+ lines.push(` Merge commit: ${result.mergeCommit}`);
402
+ }
403
+
404
+ if (result.suggestedCommand) {
405
+ lines.push("", ` → ${result.suggestedCommand}`);
406
+ }
407
+
408
+ if (result.alternatives?.length) {
409
+ lines.push("", " Alternatives:");
410
+ for (const alt of result.alternatives) {
411
+ lines.push(` • ${alt}`);
412
+ }
413
+ }
414
+
415
+ lines.push("");
416
+ return lines.join("\n");
417
+ }