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
@@ -1,636 +1,26 @@
1
1
  // @ts-nocheck
2
2
  /**
3
- * Attached batch foreground runner — milestones, integrate handoff, CLI exit (SP-343, GitHub #34).
4
- * Post-merge limbo resume fast path (SP-348, GitHub #39).
5
- */
6
-
7
- import fs from "node:fs";
8
- import path from "node:path";
9
- import {
10
- finalizeAttachedLandLoopBeforeExit,
11
- finalizeResumedBatchForIntegrate,
12
- isPostMergeLimbo,
13
- } from "./post-merge-limbo.mjs";
14
- import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
15
- import { isProcessAlive } from "../process/liveness.mjs";
16
- import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
17
- import { reconcileBatch } from "./reconcile.mjs";
18
- import { readJournalEventsCached, readJournalEvents, appendJournalEvent } from "./journal.mjs";
19
- import { enforceOperatorPauseOnDisk } from "./pause.mjs";
20
- import {
21
- loadSpineBatchState,
22
- readBatchEnginePid,
23
- saveSpineBatchState,
24
- updateSegmentForTask,
25
- recomputeTaskCounters,
26
- clearBatchEnginePid,
27
- } from "./state.mjs";
28
- import { loadSpineConfig } from "../config/spine-config-load.mjs";
29
- import { resolveAttachedMilestonePollMs } from "../config/spine-config-schema.mjs";
30
- import {
31
- journalHasContractVerified,
32
- journalIndicatesPausedForceResume,
33
- } from "./orphan-detect.mjs";
34
- import { classifyTaskDoneSemantics } from "./diagnosis-task-done.mjs";
35
- import { resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
36
- import { journalHasTaskCompleted } from "./resume-common.mjs";
37
- import { startParentSessionMonitor } from "./parent-session-monitor.mjs";
38
-
39
- export { DEFAULT_ATTACHED_MILESTONE_POLL_MS } from "../config/spine-config-schema.mjs";
40
-
41
- /** @type {boolean} */
42
- let attachedExitHandlersInstalled = false;
43
-
44
- /** Journal types surfaced on attached stdout during the land loop. */
45
- export const ATTACHED_LAND_LOOP_MILESTONE_TYPES = new Set([
46
- "batch.started",
47
- "task.started",
48
- "task.completed",
49
- "task.failed",
50
- "batch.merge_started",
51
- "batch.merge_completed",
52
- "batch.merge_blocked",
53
- "gate.opened",
54
- "gate.evidence_collecting",
55
- "gate.evidence_completed",
56
- "gate.evidence_failed",
57
- "batch.land_loop_finalized",
58
- "batch.completed",
59
- ]);
60
-
61
- /**
62
- * Install journal-aware SIGTERM/SIGINT handlers before attached engine exit (SP-378).
63
- *
64
- * @param {object} params
65
- * @param {string} params.projectRoot
66
- * @param {string} [params.spineBin]
67
- */
68
- export function installAttachedExitFinalizeHandlers({ projectRoot, spineBin }) {
69
- if (attachedExitHandlersInstalled) return;
70
- attachedExitHandlersInstalled = true;
71
-
72
- const onShutdown = (signal) => {
73
- const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal });
74
- if (handoff.handled) {
75
- process.exit(0);
76
- }
77
- };
78
-
79
- process.once("SIGTERM", () => onShutdown("SIGTERM"));
80
- process.once("SIGINT", () => onShutdown("SIGINT"));
81
- }
82
-
83
- /**
84
- * @param {number} ms
85
- */
86
- function sleep(ms) {
87
- return new Promise((resolve) => setTimeout(resolve, ms));
88
- }
89
-
90
- /**
91
- * @param {object} event
92
- */
93
- function milestoneEventKey(event) {
94
- if (typeof event.eventId === "string" && event.eventId) {
95
- return event.eventId;
96
- }
97
- const taskId = typeof event.taskId === "string" ? event.taskId : "";
98
- const timestamp = typeof event.timestamp === "string" ? event.timestamp : String(event.timestamp ?? "");
99
- return `${event.type ?? "unknown"}:${timestamp}:${taskId}`;
100
- }
101
-
102
- /**
103
- * @param {object} event
104
- * @returns {string}
105
- */
106
- export function formatAttachedMilestoneLine(event) {
107
- const type = String(event.type ?? "unknown");
108
- const taskId = typeof event.taskId === "string" && event.taskId ? ` ${event.taskId}` : "";
109
- const payload =
110
- event.payload && typeof event.payload === "object" ? /** @type {Record<string, unknown>} */ (event.payload) : {};
111
- const waveIndex = payload.waveIndex;
112
- const waveSuffix =
113
- typeof waveIndex === "number" &&
114
- (type === "batch.merge_started" || type === "batch.merge_completed" || type === "batch.merge_blocked")
115
- ? ` wave=${waveIndex}`
116
- : "";
117
- return `[spine] ${type}${taskId}${waveSuffix}\n`;
118
- }
119
-
120
- /**
121
- * @param {object} params
122
- * @param {string} params.projectRoot
123
- * @param {(line: string) => void} [params.write]
124
- * @param {number} [params.pollIntervalMs]
125
- * @returns {Promise<{ stop: () => Promise<void> }>}
126
- */
127
- export async function startAttachedMilestoneReporter({
128
- projectRoot,
129
- write = (line) => process.stdout.write(line),
130
- pollIntervalMs,
131
- }) {
132
- const configResult = loadSpineConfig(projectRoot);
133
- const resolvedPollMs =
134
- pollIntervalMs ??
135
- resolveAttachedMilestonePollMs({ config: configResult.config ?? {} });
136
- /** @type {Set<string>} */
137
- const printed = new Set();
138
- let batchId = null;
139
- let stopped = false;
140
-
141
- const loop = async () => {
142
- while (!stopped) {
143
- enforceOperatorPauseOnDisk(projectRoot);
144
- if (!batchId) {
145
- const loaded = loadSpineBatchState(projectRoot);
146
- batchId = loaded.raw?.batchId ? String(loaded.raw.batchId) : null;
147
- }
148
- if (batchId) {
149
- const events = readJournalEventsCached(projectRoot, batchId);
150
- for (const event of events) {
151
- const key = milestoneEventKey(event);
152
- if (printed.has(key)) continue;
153
- if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
154
- printed.add(key);
155
- write(formatAttachedMilestoneLine(event));
156
- }
157
- }
158
- await sleep(resolvedPollMs);
159
- }
160
- };
161
-
162
- const loopPromise = loop();
163
-
164
- return {
165
- stop: async () => {
166
- stopped = true;
167
- await loopPromise;
168
- if (batchId) {
169
- const events = readJournalEventsCached(projectRoot, batchId);
170
- for (const event of events) {
171
- const key = milestoneEventKey(event);
172
- if (printed.has(key)) continue;
173
- if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
174
- printed.add(key);
175
- write(formatAttachedMilestoneLine(event));
176
- }
177
- }
178
- },
179
- };
180
- }
181
-
182
- /**
183
- * @param {string} projectRoot
184
- * @param {string} batchId
185
- */
186
- export function resumeHandoffLockPath(projectRoot, batchId) {
187
- return path.join(projectRoot, ".spine", "runtime", batchId, "resume-handoff.lock");
188
- }
189
-
190
- /**
191
- * Exclusive lock for forced resume handoff (SP-533 / #167).
192
- *
193
- * @param {string} projectRoot
194
- * @param {string} batchId
195
- * @param {boolean} [allowRetry]
196
- * @returns {{ ok: true, release: () => void } | { ok: false, holderPid?: number|null, startedAt?: number }}
197
- */
198
- export function tryAcquireResumeHandoffLock(projectRoot, batchId, allowRetry = true) {
199
- const lockPath = resumeHandoffLockPath(projectRoot, batchId);
200
- fs.mkdirSync(path.dirname(lockPath), { recursive: true });
201
- const payload = JSON.stringify({ pid: process.pid, startedAt: Date.now() });
202
-
203
- try {
204
- fs.writeFileSync(lockPath, payload, { encoding: "utf-8", flag: "wx" });
205
- return {
206
- ok: true,
207
- release: () => releaseResumeHandoffLock(projectRoot, batchId),
208
- };
209
- } catch (err) {
210
- if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EEXIST") {
211
- throw err;
212
- }
213
- }
214
-
215
- /** @type {{ pid?: number, startedAt?: number } | null} */
216
- let holder = null;
217
- try {
218
- holder = JSON.parse(fs.readFileSync(lockPath, "utf-8"));
219
- } catch {
220
- try {
221
- fs.unlinkSync(lockPath);
222
- } catch {
223
- /* ignore stale corrupt lock cleanup */
224
- }
225
- if (allowRetry) {
226
- return tryAcquireResumeHandoffLock(projectRoot, batchId, false);
227
- }
228
- return { ok: false, holderPid: null };
229
- }
230
-
231
- const holderPid = Number(holder?.pid);
232
- if (Number.isFinite(holderPid) && holderPid > 0 && isProcessAlive(holderPid)) {
233
- return {
234
- ok: false,
235
- holderPid,
236
- startedAt: Number(holder?.startedAt) || undefined,
237
- };
238
- }
239
-
240
- try {
241
- fs.unlinkSync(lockPath);
242
- } catch {
243
- /* ignore stale lock cleanup */
244
- }
245
-
246
- try {
247
- fs.writeFileSync(lockPath, payload, { encoding: "utf-8", flag: "wx" });
248
- return {
249
- ok: true,
250
- release: () => releaseResumeHandoffLock(projectRoot, batchId),
251
- };
252
- } catch (err) {
253
- if (/** @type {NodeJS.ErrnoException} */ (err).code === "EEXIST") {
254
- return { ok: false, holderPid: Number.isFinite(holderPid) ? holderPid : null };
255
- }
256
- throw err;
257
- }
258
- }
259
-
260
- /**
261
- * @param {string} projectRoot
262
- * @param {string} batchId
263
- */
264
- export function releaseResumeHandoffLock(projectRoot, batchId) {
265
- const lockPath = resumeHandoffLockPath(projectRoot, batchId);
266
- try {
267
- if (!fs.existsSync(lockPath)) return;
268
- const holder = JSON.parse(fs.readFileSync(lockPath, "utf-8"));
269
- if (Number(holder?.pid) === process.pid) {
270
- fs.unlinkSync(lockPath);
271
- }
272
- } catch {
273
- /* ignore release races */
274
- }
275
- }
276
-
277
- /**
278
- * Reject a second attached engine when resilience.enginePid is alive (SP-434, GitHub #89).
279
- * Serialized forced resume handoff when another resume --force is in flight (SP-533, #167).
280
- *
281
- * @param {object} params
282
- * @param {string} params.projectRoot
283
- * @param {boolean} [params.force] Orphan-terminate prior engine before handoff
284
- * @param {"start"|"resume"} [params.operation]
285
- */
286
- export function enforceAttachedEngineSingleOwner({ projectRoot, force = false, operation = "resume" }) {
287
- const loaded = loadSpineBatchState(projectRoot);
288
- const state = loaded.raw;
289
- if (!state) {
290
- return { ok: true };
291
- }
292
-
293
- const batchId = String(state.batchId ?? "");
294
- /** @type {(() => void) | undefined} */
295
- let releaseResumeLock;
296
-
297
- if (force && operation === "resume") {
298
- const lock = tryAcquireResumeHandoffLock(projectRoot, batchId);
299
- if (!lock.ok) {
300
- const enginePid = readBatchEnginePid(state);
301
- const holderPid = lock.holderPid ?? null;
302
- const output =
303
- `Another batch resume --force is already in progress (batch ${batchId}` +
304
- `${holderPid ? `, holder PID ${holderPid}` : ""}).\n` +
305
- `Wait for the in-flight forced resume to finish before starting another.\n`;
306
- return {
307
- ok: false,
308
- exitCode: 1,
309
- error: "concurrent_resume_blocked",
310
- output,
311
- batchId,
312
- enginePid,
313
- holderPid,
314
- };
315
- }
316
- releaseResumeLock = lock.release;
317
- appendJournalEvent(projectRoot, batchId, "batch.resume_handoff_started", {
318
- pid: process.pid,
319
- });
320
- }
321
-
322
- const enginePid = readBatchEnginePid(state);
323
- if (enginePid == null || enginePid === process.pid || !isProcessAlive(enginePid)) {
324
- return releaseResumeLock ? { ok: true, releaseResumeLock } : { ok: true };
325
- }
326
-
327
- const fromPhase = String(state.phase ?? "");
328
- if (force) {
329
- const terminateResult = terminateStaleDetachedEngine({
330
- projectRoot,
331
- state,
332
- batchId,
333
- fromPhase,
334
- allowRunningOrphanTerminate: true,
335
- });
336
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
337
- return {
338
- ok: true,
339
- handoff: true,
340
- terminated: terminateResult.terminated,
341
- stalePid: terminateResult.stalePid ?? enginePid,
342
- releaseResumeLock,
343
- };
344
- }
345
-
346
- const operationLabel = operation === "start" ? "start" : "resume";
347
- const output =
348
- `Attached batch engine already running (PID ${enginePid}, batch ${batchId}).\n` +
349
- `Stop the existing engine or run spine batch ${operationLabel} --attached --force to orphan it first.\n`;
350
- return {
351
- ok: false,
352
- exitCode: 1,
353
- error: "attached_engine_already_running",
354
- output,
355
- batchId,
356
- enginePid,
357
- };
358
- }
359
-
360
- /**
361
- * Promote running cache tasks with lane `.DONE` and contract verify after paused force resume (SP-513 / #184).
362
- *
363
- * @param {object} params
364
- * @param {string} params.projectRoot
365
- * @param {object} params.state
366
- * @param {string} params.batchId
367
- * @returns {{ reconciled: boolean, taskIds?: string[] }}
368
- */
369
- export function reconcilePausedResumeDoneInLane({ projectRoot, state, batchId }) {
370
- if (!state || typeof state !== "object" || !batchId) {
371
- return { reconciled: false };
372
- }
373
-
374
- const journalEvents = readJournalEvents(projectRoot, batchId);
375
- if (!journalIndicatesPausedForceResume(journalEvents)) {
376
- return { reconciled: false };
377
- }
378
-
379
- const configResult = loadSpineConfig(projectRoot);
380
- const tasksRoot = resolveTasksRoot(projectRoot, configResult);
381
- const lanes = state.lanes ?? [];
382
- /** @type {string[]} */
383
- const promotedTaskIds = [];
384
- let changed = false;
385
-
386
- for (const task of state.tasks ?? []) {
387
- const status = String(task?.status ?? "").toLowerCase();
388
- if (status !== "running" && status !== "pending") continue;
389
-
390
- const classified = classifyTaskDoneSemantics(task, {
391
- tasksRoot,
392
- projectRoot,
393
- batchId,
394
- lanes,
395
- });
396
- if (classified.doneInLane !== true) continue;
397
- if (!journalHasContractVerified(journalEvents, task.taskId)) continue;
398
-
399
- task.status = "succeeded";
400
- task.doneFileFound = true;
401
- task.exitReason = task.exitReason ?? "done";
402
- if (!task.endedAt) task.endedAt = Date.now();
403
- updateSegmentForTask(state, task.taskId, "succeeded");
404
- promotedTaskIds.push(task.taskId);
405
- changed = true;
406
-
407
- if (!journalHasTaskCompleted(journalEvents, task.taskId)) {
408
- const laneNumber = Number(task.laneNumber ?? 1);
409
- const lane = lanes.find((entry) => Number(entry?.laneNumber) === laneNumber);
410
- appendJournalEvent(projectRoot, batchId, "task.completed", {
411
- taskId: task.taskId,
412
- laneNumber,
413
- laneId: lane?.laneId ?? `lane-${laneNumber}`,
414
- resumed: true,
415
- skippedDoneOnDisk: true,
416
- reconciled: true,
417
- });
418
- }
419
- }
420
-
421
- if (!changed) {
422
- return { reconciled: false };
423
- }
424
-
425
- const enginePid = readBatchEnginePid(state);
426
- if (enginePid != null && !isProcessAlive(enginePid)) {
427
- clearBatchEnginePid(state);
428
- }
429
-
430
- recomputeTaskCounters(state);
431
- saveSpineBatchState(projectRoot, state);
432
- return { reconciled: true, taskIds: promotedTaskIds };
433
- }
434
-
435
- /**
436
- * Run an attached foreground engine while streaming land-loop journal milestones to stdout.
437
- *
438
- * @param {object} params
439
- * @param {string} params.projectRoot
440
- * @param {() => Promise<object>} params.runEngine
441
- * @param {(line: string) => void} [params.write]
442
- * @param {boolean} [params.force]
443
- * @param {"start"|"resume"} [params.operation]
444
- */
445
- export async function runAttachedBatchEngine({
446
- projectRoot,
447
- runEngine,
448
- write,
449
- spineBin,
450
- _force = false,
451
- operation = "resume",
452
- }) {
453
- if (operation === "start") {
454
- const lock = enforceAttachedEngineSingleOwner({ projectRoot, force: false, operation: "start" });
455
- if (!lock.ok) {
456
- return {
457
- ok: false,
458
- exitCode: lock.exitCode ?? 1,
459
- error: lock.error,
460
- output: lock.output,
461
- batchId: lock.batchId,
462
- };
463
- }
464
- }
465
-
466
- installAttachedExitFinalizeHandlers({ projectRoot, spineBin });
467
- const reporter = await startAttachedMilestoneReporter({ projectRoot, write });
468
- /** @type {{ stop: () => Promise<void> }} */
469
- let parentMonitor = { stop: async () => {} };
470
- if (process.env.SPINE_ALLOW_ATTACHED_HARNESS !== "1") {
471
- parentMonitor = await startParentSessionMonitor({
472
- projectRoot,
473
- onParentDied: () => {
474
- process.exit(1);
475
- },
476
- });
477
- }
478
- try {
479
- const result = await runEngine();
480
- const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "exit" });
481
- if (handoff.handled && handoff.action === "finalized_in_process" && handoff.result) {
482
- return handoff.result;
483
- }
484
- return result;
485
- } finally {
486
- await parentMonitor.stop();
487
- await reporter.stop();
488
- }
489
- }
490
-
491
- /**
492
- * @param {object} result
493
- * @param {import("./reconcile.mjs").ReconciliationResult} reconciliation
494
- */
495
- function resolveAttachedBatchExitCode(result, reconciliation) {
496
- if (reconciliation.phase === "merge_blocked") {
497
- return result.exitCode ?? 1;
498
- }
499
- return result.exitCode ?? (result.ok ? 0 : 1);
500
- }
501
-
502
- /**
503
- * @param {object} params
504
- * @param {string} params.projectRoot
505
- * @param {"start"|"resume"} params.operation
506
- * @param {object} params.result
507
- * @param {boolean} [params.json]
508
- */
509
- export function formatAttachedBatchCliResult({ projectRoot, operation, result, json = false }) {
510
- const loaded = loadSpineBatchState(projectRoot);
511
- if (loaded.raw?.batchId) {
512
- reconcilePausedResumeDoneInLane({
513
- projectRoot,
514
- state: loaded.raw,
515
- batchId: String(loaded.raw.batchId),
516
- });
517
- }
518
- const reconciliation = reconcileBatch({ projectRoot });
519
- const mergeBlocked = reconciliation.phase === "merge_blocked";
520
-
521
- if (json) {
522
- return {
523
- exitCode: resolveAttachedBatchExitCode(result, reconciliation),
524
- output: `${JSON.stringify({ ...result, reconciliation }, null, 2)}\n`,
525
- };
526
- }
527
-
528
- const operationLabel = operation === "resume" ? "resumed" : "started";
529
- const headline = result.ok
530
- ? `Batch ${operationLabel}`
531
- : mergeBlocked && reconciliation.headline
532
- ? reconciliation.headline
533
- : operation === "resume"
534
- ? "Batch resume failed"
535
- : "Batch start failed";
536
-
537
- /** @type {string[]} */
538
- const lines = ["", headline, ""];
539
-
540
- if (result.output) {
541
- lines.push(result.output.trimEnd());
542
- } else if (result.error && !mergeBlocked) {
543
- lines.push(String(result.error));
544
- }
545
-
546
- if (reconciliation.headline && reconciliation.headline !== headline) {
547
- lines.push("", reconciliation.headline);
548
- }
549
- if (reconciliation.suggestedCommand) {
550
- lines.push("", ` → ${reconciliation.suggestedCommand}`);
551
- }
552
- if (reconciliation.alternatives?.length) {
553
- lines.push("", " Alternatives:");
554
- for (const alt of reconciliation.alternatives) {
555
- lines.push(` • ${alt}`);
556
- }
557
- }
558
-
559
- if (result.batchId) {
560
- lines.push("", ` Batch: ${result.batchId}`);
561
- }
562
- if (result.taskId) {
563
- lines.push(` Task: ${result.taskId}`);
564
- }
565
-
566
- lines.push("");
567
- return {
568
- exitCode: resolveAttachedBatchExitCode(result, reconciliation),
569
- output: lines.join("\n"),
570
- };
571
- }
572
-
573
- /**
574
- * Write attached CLI output and exit so the foreground process does not linger after batch.completed.
575
- *
576
- * @param {{ exitCode?: number, output?: string }} cli
577
- * @param {object} [options]
578
- * @param {boolean} [options.deferExit]
579
- */
580
- export function finishAttachedBatchCli(cli, { deferExit = false, projectRoot, spineBin } = {}) {
581
- const exitCode = cli.exitCode ?? 1;
582
- if (cli.output) {
583
- process.stdout.write(cli.output);
584
- }
585
- if (deferExit) {
586
- return;
587
- }
588
- if (projectRoot) {
589
- finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "cli_exit" });
590
- }
591
- process.exit(exitCode);
592
- }
593
-
594
- /**
595
- * Finalize post-merge limbo during resume without re-running workers.
596
- *
597
- * @param {object} params
598
- * @param {string} params.projectRoot
599
- * @param {object} params.state
600
- * @param {string} params.batchId
601
- * @param {string} params.orchBranch
602
- * @param {string} [params.fromPhase]
603
- * @param {boolean} [params.resumeForced]
604
- * @returns {ReturnType<typeof finalizeResumedBatchForIntegrate>|null}
605
- */
606
- export function finalizeResumePostMergeLimbo({
607
- projectRoot,
608
- state,
609
- batchId,
610
- orchBranch,
611
- fromPhase = "running",
612
- resumeForced = false,
613
- }) {
614
- if (String(state.phase ?? "") === "completed") {
615
- return null;
616
- }
617
- if (!detectPostMergeLimboForResume({ projectRoot, state }) && !isPostMergeLimbo(state)) {
618
- return null;
619
- }
620
-
621
- terminateStaleDetachedEngine({
622
- projectRoot,
623
- state,
624
- batchId,
625
- fromPhase,
626
- });
627
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
628
-
629
- return finalizeResumedBatchForIntegrate({
630
- projectRoot,
631
- state,
632
- batchId,
633
- orchBranch,
634
- resumeForced,
635
- });
636
- }
3
+ * Attached batch foreground runner — public facade (SP-343 / #34, SP-348 / #39).
4
+ * Promote/exit: attached-runner-promote.mjs (SP-586).
5
+ * Pause/resume reconcile: attached-runner-reconcile.mjs (SP-604).
6
+ */
7
+
8
+ export {
9
+ resumeHandoffLockPath,
10
+ tryAcquireResumeHandoffLock,
11
+ releaseResumeHandoffLock,
12
+ enforceAttachedEngineSingleOwner,
13
+ reconcilePausedResumeDoneInLane,
14
+ } from "./attached-runner-reconcile.mjs";
15
+
16
+ export {
17
+ DEFAULT_ATTACHED_MILESTONE_POLL_MS,
18
+ ATTACHED_LAND_LOOP_MILESTONE_TYPES,
19
+ installAttachedExitFinalizeHandlers,
20
+ formatAttachedMilestoneLine,
21
+ startAttachedMilestoneReporter,
22
+ runAttachedBatchEngine,
23
+ formatAttachedBatchCliResult,
24
+ finishAttachedBatchCli,
25
+ finalizeResumePostMergeLimbo,
26
+ } from "./attached-runner-promote.mjs";