pi-spine 2.3.1 → 2.4.0

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