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,346 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Detached batch wait/poll helpers — state polling after spawn (SP-598).
4
+ */
5
+
6
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
7
+ import { runBatchPreflight } from "../config/spine-preflight-lib.mjs";
8
+ import { loadGateRecord } from "./gate.mjs";
9
+ import { reconcileBatch } from "./reconcile.mjs";
10
+ import { assessRunningPhaseResumeEligibility } from "./resume-multi-validate.mjs";
11
+ import { prepareOrphanResumeHandoff } from "./resume-engine.mjs";
12
+ import {
13
+ ACTIVE_PHASES,
14
+ loadSpineBatchState,
15
+ recordBatchEnginePid,
16
+ saveSpineBatchState,
17
+ TERMINAL_BATCH_PHASES,
18
+ } from "./state.mjs";
19
+
20
+ /** Diagnoses that benefit from blocking until resume engine reaches terminal phase. */
21
+ const RESUME_WAIT_TERMINAL_DIAGNOSES = new Set([
22
+ "engine_orphaned",
23
+ "worker_orphaned",
24
+ "state_drift",
25
+ "needs_integrate",
26
+ ]);
27
+
28
+ /**
29
+ * Default detached resume to --wait-terminal after orphan/drift diagnoses.
30
+ *
31
+ * @param {string} projectRoot
32
+ * @param {boolean} explicitWaitTerminal
33
+ * @param {boolean} noWaitTerminal
34
+ */
35
+ export function resolveDefaultResumeWaitTerminal(
36
+ projectRoot,
37
+ explicitWaitTerminal,
38
+ noWaitTerminal = false,
39
+ ) {
40
+ if (explicitWaitTerminal) return true;
41
+ if (noWaitTerminal) return false;
42
+ const reconciliation = reconcileBatch({ projectRoot });
43
+ const diagnosis = reconciliation.diagnosis;
44
+ if (diagnosis && RESUME_WAIT_TERMINAL_DIAGNOSES.has(diagnosis)) {
45
+ return true;
46
+ }
47
+ return false;
48
+ }
49
+
50
+ /** @type {ReadonlySet<string>} */
51
+ const TERMINAL_TASK_STATUSES = new Set(["succeeded", "failed", "skipped", "aborted"]);
52
+
53
+ /** Default wait when --wait-terminal blocks on orphan/drift resume (real workers exceed 30s). */
54
+ const DETACHED_WAIT_TERMINAL_TIMEOUT_MS = 2 * 60 * 60 * 1000;
55
+
56
+ /**
57
+ * @param {boolean} waitTerminal
58
+ * @param {number} [explicitTimeoutMs]
59
+ */
60
+ export function resolveDetachedWaitTimeoutMs(waitTerminal, explicitTimeoutMs) {
61
+ if (Number.isFinite(explicitTimeoutMs) && explicitTimeoutMs > 0) {
62
+ return explicitTimeoutMs;
63
+ }
64
+ return waitTerminal ? DETACHED_WAIT_TERMINAL_TIMEOUT_MS : 30_000;
65
+ }
66
+
67
+ /**
68
+ * @param {number} ms
69
+ */
70
+ function sleep(ms) {
71
+ return new Promise((resolve) => setTimeout(resolve, ms));
72
+ }
73
+
74
+ /**
75
+ * @param {object|null|undefined} raw
76
+ * @param {string|null|undefined} taskId
77
+ */
78
+ function resumedTaskReachedTerminal(raw, taskId) {
79
+ if (!taskId || !raw || !Array.isArray(raw.tasks)) return false;
80
+ const task = raw.tasks.find((entry) => entry?.taskId === taskId);
81
+ return Boolean(task && TERMINAL_TASK_STATUSES.has(String(task.status ?? "")));
82
+ }
83
+
84
+ /**
85
+ * @param {string} projectRoot
86
+ * @param {object|null|undefined} raw
87
+ */
88
+ function detachedResumeRequiresIntegrateGate(projectRoot, raw) {
89
+ if (!raw?.batchId || String(raw.phase ?? "") !== "completed") {
90
+ return false;
91
+ }
92
+ if (!raw.orchBranch) {
93
+ return false;
94
+ }
95
+ const config = loadSpineConfig(projectRoot).config ?? {};
96
+ return config.gates?.requireBeforeIntegrate === true;
97
+ }
98
+
99
+ /**
100
+ * @param {string} projectRoot
101
+ * @param {object|null|undefined} raw
102
+ */
103
+ function detachedResumeIntegrateGateReady(projectRoot, raw) {
104
+ if (!detachedResumeRequiresIntegrateGate(projectRoot, raw)) {
105
+ return true;
106
+ }
107
+ return Boolean(loadGateRecord(projectRoot, String(raw.batchId)));
108
+ }
109
+
110
+ /**
111
+ * @param {object|null|undefined} raw
112
+ * @param {string|null|undefined} taskId
113
+ * @param {number} updatedAtBefore
114
+ */
115
+ function evaluateDetachedResumeWait(raw, taskId, updatedAtBefore) {
116
+ if (!raw?.batchId) return null;
117
+ const updatedAt = Number(raw.updatedAt ?? 0);
118
+ if (updatedAt <= updatedAtBefore) return null;
119
+
120
+ if (TERMINAL_BATCH_PHASES.has(String(raw.phase ?? ""))) {
121
+ return {
122
+ ok: true,
123
+ status: "resume_completed",
124
+ batchId: raw.batchId,
125
+ phase: raw.phase,
126
+ };
127
+ }
128
+
129
+ if (resumedTaskReachedTerminal(raw, taskId)) {
130
+ return {
131
+ ok: true,
132
+ status: "resume_completed",
133
+ batchId: raw.batchId,
134
+ phase: raw.phase,
135
+ };
136
+ }
137
+
138
+ return null;
139
+ }
140
+
141
+ /**
142
+ * @param {string} projectRoot
143
+ * @param {number|null} enginePid
144
+ */
145
+ export function persistDetachedEnginePid(projectRoot, enginePid) {
146
+ const pid = Number(enginePid);
147
+ if (!Number.isFinite(pid) || pid <= 0) return;
148
+ const { raw } = loadSpineBatchState(projectRoot);
149
+ if (!raw) return;
150
+ recordBatchEnginePid(raw, pid);
151
+ saveSpineBatchState(projectRoot, raw);
152
+ }
153
+
154
+ /**
155
+ * Kill a stale detached engine and persist cleared PID before spawning resume engine (SP-254).
156
+ * Resume child records its own PID after terminateStaleDetachedEngine runs in-process.
157
+ * Running-phase orphan resume (SP-296) clears a dead engine PID without requiring pause first.
158
+ *
159
+ * @param {string} projectRoot
160
+ */
161
+ export function prepareDetachedResumeEngineHandoff(projectRoot) {
162
+ const loaded = loadSpineBatchState(projectRoot);
163
+ if (!loaded.raw) {
164
+ return { ok: false, reason: "no_active_batch" };
165
+ }
166
+
167
+ const state = loaded.raw;
168
+ const batchId = String(state.batchId ?? "");
169
+ const fromPhase = String(state.phase ?? "");
170
+ const orphanEligibility =
171
+ fromPhase === "running"
172
+ ? assessRunningPhaseResumeEligibility({ projectRoot, state })
173
+ : { engineConfirmedDead: false, allowOrphanResume: false };
174
+ const handoff = prepareOrphanResumeHandoff({
175
+ projectRoot,
176
+ state,
177
+ batchId,
178
+ fromPhase,
179
+ orphanResume: orphanEligibility.allowOrphanResume,
180
+ engineConfirmedDead: orphanEligibility.engineConfirmedDead,
181
+ });
182
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
183
+
184
+ return {
185
+ ok: true,
186
+ batchId,
187
+ fromPhase,
188
+ terminateResult: handoff.terminateResult,
189
+ orphanResume: orphanEligibility.allowOrphanResume,
190
+ };
191
+ }
192
+
193
+ /**
194
+ * @param {object} params
195
+ * @param {string} params.projectRoot
196
+ * @param {boolean} [params.skipPreflight]
197
+ */
198
+ export function runDetachedStartPreflight({ projectRoot, skipPreflight = false }) {
199
+ if (skipPreflight) {
200
+ return { ok: true };
201
+ }
202
+ const preflight = runBatchPreflight({ projectRoot, skipDoctor: false });
203
+ if (!preflight.ok) {
204
+ return {
205
+ ok: false,
206
+ exitCode: preflight.exitCode ?? 1,
207
+ error: "preflight_failed",
208
+ output: preflight.output,
209
+ };
210
+ }
211
+ return { ok: true };
212
+ }
213
+
214
+ /**
215
+ * @param {object} params
216
+ * @param {string} params.projectRoot
217
+ * @param {string | null} [params.previousBatchId]
218
+ * @param {number} [params.timeoutMs]
219
+ * @param {boolean} [params.waitTerminal]
220
+ */
221
+ export async function waitForDetachedBatchStart({
222
+ projectRoot,
223
+ previousBatchId = null,
224
+ timeoutMs = 30_000,
225
+ waitTerminal = false,
226
+ }) {
227
+ const deadline = Date.now() + timeoutMs;
228
+ /** @type {string|null} */
229
+ let startedBatchId = null;
230
+
231
+ while (Date.now() < deadline) {
232
+ const { raw } = loadSpineBatchState(projectRoot);
233
+ const batchId = raw?.batchId ?? null;
234
+ if (batchId && batchId !== previousBatchId) {
235
+ if (raw.phase === "failed" || raw.phase === "aborted") {
236
+ return {
237
+ ok: false,
238
+ error: "batch_engine_failed",
239
+ batchId,
240
+ phase: raw.phase,
241
+ lastError: raw.lastError ?? null,
242
+ };
243
+ }
244
+
245
+ if (TERMINAL_BATCH_PHASES.has(String(raw.phase ?? "")) || raw.phase === "paused") {
246
+ return {
247
+ ok: true,
248
+ status: "start_completed",
249
+ batchId,
250
+ phase: raw.phase,
251
+ };
252
+ }
253
+
254
+ if (ACTIVE_PHASES.has(raw.phase)) {
255
+ startedBatchId = batchId;
256
+ if (!waitTerminal) {
257
+ return {
258
+ ok: true,
259
+ status: "engine_started",
260
+ batchId,
261
+ phase: raw.phase,
262
+ };
263
+ }
264
+ }
265
+ }
266
+ await sleep(200);
267
+ }
268
+
269
+ if (startedBatchId) {
270
+ return {
271
+ ok: false,
272
+ error: "timeout_waiting_for_batch",
273
+ batchId: startedBatchId,
274
+ status: "engine_started",
275
+ };
276
+ }
277
+
278
+ return { ok: false, error: "timeout_waiting_for_batch" };
279
+ }
280
+
281
+ /**
282
+ * @param {object} params
283
+ * @param {string} params.projectRoot
284
+ * @param {string} params.batchId
285
+ * @param {number} params.updatedAtBefore
286
+ * @param {string|null|undefined} [params.taskId]
287
+ * @param {number} [params.timeoutMs]
288
+ * @param {boolean} [params.waitTerminal]
289
+ */
290
+ export async function waitForDetachedBatchResume({
291
+ projectRoot,
292
+ batchId,
293
+ updatedAtBefore,
294
+ taskId = null,
295
+ timeoutMs = 30_000,
296
+ waitTerminal = false,
297
+ }) {
298
+ const deadline = Date.now() + timeoutMs;
299
+ /** @type {boolean} */
300
+ let engineStarted = false;
301
+
302
+ while (Date.now() < deadline) {
303
+ const { raw } = loadSpineBatchState(projectRoot);
304
+ if (raw?.batchId !== batchId) {
305
+ await sleep(200);
306
+ continue;
307
+ }
308
+
309
+ if (raw.phase === "failed" || raw.phase === "aborted") {
310
+ return {
311
+ ok: false,
312
+ error: "batch_engine_failed",
313
+ batchId,
314
+ phase: raw.phase,
315
+ lastError: raw.lastError ?? null,
316
+ };
317
+ }
318
+
319
+ const updatedAt = Number(raw.updatedAt ?? 0);
320
+ if (raw.phase === "running" && updatedAt > updatedAtBefore) {
321
+ engineStarted = true;
322
+ if (!waitTerminal) {
323
+ return {
324
+ ok: true,
325
+ status: "engine_started",
326
+ batchId,
327
+ phase: raw.phase,
328
+ };
329
+ }
330
+ }
331
+
332
+ const completed = evaluateDetachedResumeWait(raw, taskId, updatedAtBefore);
333
+ if (completed && detachedResumeIntegrateGateReady(projectRoot, raw)) {
334
+ return completed;
335
+ }
336
+
337
+ await sleep(200);
338
+ }
339
+
340
+ return {
341
+ ok: false,
342
+ error: "timeout_waiting_for_resume",
343
+ batchId,
344
+ engineStarted,
345
+ };
346
+ }
@@ -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) {
@@ -45,6 +45,7 @@ import {
45
45
  skipTaskDoneOnDisk,
46
46
  transitionPhase,
47
47
  } from "./engine-lanes.mjs";
48
+ import { rejectNestedBatchStart } from "./batch-guards.mjs";
48
49
 
49
50
  /**
50
51
  * @param {string} batchId
@@ -71,55 +72,13 @@ export {
71
72
  resolveBatchStartScope,
72
73
  } from "./engine-scope.mjs";
73
74
  export { loadTaskFileScopePaths, mergeLaneToOrch } from "./engine-lanes.mjs";
75
+ export { detectNestedWorkerContext } from "./batch-guards.mjs";
74
76
 
75
- /**
76
- * Mutable batch-state fields are widened from createInitialBatchState literals so
77
- * terminal transitions can assign endedAt/lastError without any casts.
78
- *
79
- * @typedef {Omit<ReturnType<typeof createInitialBatchState>, "endedAt" | "lastError"> & {
80
- * endedAt: number | null;
81
- * lastError: string | null;
82
- * }} SpineBatchState
83
- */
84
-
85
- const WORKTREE_SPINE_PATTERN = /[/\\]\.worktrees[/\\]spine-/;
86
-
87
- /**
88
- * Detect whether the current process is running inside a spine worker context.
89
- * Returns a human-readable reason string if nested, or null if safe to proceed.
90
- *
91
- * Two guards: (1) SPINE_IS_WORKER env set by worker-host, and
92
- * (2) projectRoot inside a .worktrees/spine-* directory (catches cases where
93
- * the env was not inherited but the target is clearly a lane worktree).
94
- *
95
- * @param {string} projectRoot — the directory where the batch would run
96
- * @returns {string | null}
97
- */
98
- export function detectNestedWorkerContext(projectRoot) {
99
- if (process.env.SPINE_IS_WORKER === "1") {
100
- return "SPINE_IS_WORKER=1 is set (running inside a worker process)";
101
- }
102
- const parentBatchId = process.env.SPINE_PARENT_BATCH_ID ?? process.env.SPINE_BATCH_ID;
103
- if (parentBatchId && WORKTREE_SPINE_PATTERN.test(projectRoot)) {
104
- return (
105
- `parent batch ${parentBatchId} is active and projectRoot is inside a ` +
106
- `.worktrees/spine-* lane directory`
107
- );
108
- }
109
- if (WORKTREE_SPINE_PATTERN.test(projectRoot)) {
110
- return "projectRoot is inside a .worktrees/spine-* lane directory";
111
- }
112
- return null;
113
- }
77
+ /** Widened so terminal transitions can assign endedAt/lastError without casts. */
78
+ /** @typedef {Omit<ReturnType<typeof createInitialBatchState>, "endedAt" | "lastError"> & { endedAt: number | null; lastError: string | null }} SpineBatchState */
114
79
 
115
80
  /**
116
- * @param {object} options
117
- * @param {string} options.projectRoot
118
- * @param {string} [options.scope]
119
- * @param {boolean} [options.dryRun]
120
- * @param {boolean} [options.skipPreflight]
121
- * @param {boolean} [options.forceSuperseded]
122
- * @param {number|null} [options.waveFilter]
81
+ * @param {{ projectRoot: string, scope?: string, dryRun?: boolean, skipPreflight?: boolean, forceSuperseded?: boolean, waveFilter?: number|null }} options
123
82
  */
124
83
  export async function startBatch({
125
84
  projectRoot,
@@ -129,27 +88,9 @@ export async function startBatch({
129
88
  forceSuperseded = false,
130
89
  waveFilter = null,
131
90
  }) {
132
- const nestedReason = detectNestedWorkerContext(projectRoot);
133
- if (nestedReason) {
134
- const parentBatchId = process.env.SPINE_PARENT_BATCH_ID ?? process.env.SPINE_BATCH_ID ?? "unknown";
135
- try {
136
- appendJournalEvent(projectRoot, parentBatchId, "engine.nested_spawn_blocked", {
137
- projectRoot,
138
- parentBatchId,
139
- reason: nestedReason,
140
- });
141
- } catch {
142
- // Journal may not be writable from a worker worktree; best-effort.
143
- }
144
- return {
145
- ok: false,
146
- exitCode: 1,
147
- error: "nested_batch_spawn_blocked",
148
- output:
149
- `Nested batch start blocked: ${nestedReason}. ` +
150
- `Workers must not spawn batch engines. ` +
151
- `Parent batch: ${parentBatchId}, projectRoot: ${projectRoot}\n`,
152
- };
91
+ const nestedBlock = rejectNestedBatchStart(projectRoot);
92
+ if (nestedBlock) {
93
+ return nestedBlock;
153
94
  }
154
95
 
155
96
  if (!skipPreflight) {
@@ -0,0 +1,21 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Git helpers for orch→base integrate recovery (FR-SHIP-02 / #116).
4
+ */
5
+
6
+ import { gitExec } from "./git-exec.mjs";
7
+
8
+ /**
9
+ * Best-effort checkout restore after integrate failure.
10
+ * Leaves the operator on the current branch when checkout fails (dirty tree / lock).
11
+ *
12
+ * @param {string} projectRoot
13
+ * @param {string} branch Target branch (typically previous HEAD or baseBranch)
14
+ */
15
+ export function tryRestoreBranch(projectRoot, branch) {
16
+ try {
17
+ gitExec(projectRoot, ["checkout", branch], { projectRoot });
18
+ } catch {
19
+ // Leave operator on current branch for manual recovery.
20
+ }
21
+ }
@@ -13,6 +13,8 @@ import {
13
13
  } from "./rules-manifest-drift.mjs";
14
14
  import { assertOrchIntegratable } from "./integrate-assert.mjs";
15
15
  export { assertOrchIntegratable } from "./integrate-assert.mjs";
16
+ import { tryRestoreBranch } from "./integrate-git.mjs";
17
+ export { tryRestoreBranch } from "./integrate-git.mjs";
16
18
  import { checkIntegrateGate } from "./gate.mjs";
17
19
  import { appendJournalEvent } from "./journal.mjs";
18
20
  import { countCommitsAhead } from "./lane-commit.mjs";
@@ -379,11 +381,7 @@ export function integrateOrchToBase(ctx) {
379
381
  error: message.slice(0, 500),
380
382
  conflict,
381
383
  });
382
- try {
383
- git(projectRoot, ["checkout", previous || baseBranch]);
384
- } catch {
385
- // leave operator on current branch for manual recovery
386
- }
384
+ tryRestoreBranch(projectRoot, previous || baseBranch);
387
385
  return {
388
386
  ok: false,
389
387
  exitCode: 1,
@@ -430,11 +428,7 @@ export function integrateOrchToBase(ctx) {
430
428
  mergeCommit,
431
429
  });
432
430
 
433
- try {
434
- git(projectRoot, ["checkout", previous || baseBranch]);
435
- } catch {
436
- // Leave operator on current branch for manual recovery.
437
- }
431
+ tryRestoreBranch(projectRoot, previous || baseBranch);
438
432
 
439
433
  return {
440
434
  ok: false,
@@ -484,11 +478,7 @@ export function integrateOrchToBase(ctx) {
484
478
  conflict,
485
479
  });
486
480
 
487
- try {
488
- git(projectRoot, ["checkout", previous || baseBranch]);
489
- } catch {
490
- // leave operator on current branch for manual recovery
491
- }
481
+ tryRestoreBranch(projectRoot, previous || baseBranch);
492
482
 
493
483
  return {
494
484
  ok: false,