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