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
@@ -11,25 +11,8 @@ import { c, FAIL, OK } from "./shared.mjs";
11
11
 
12
12
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
13
 
14
- /** Modules >500 LOC grandfathered until v2.3 split (FR-SHIP-02 partial — engine-lanes split done). */
15
- export const PHASE23_GRANDFATHERED_OVER_500 = [
16
- "src/batch/engine.mjs",
17
- "src/batch/integrate.mjs",
18
- "src/batch/state.mjs",
19
- "src/batch/worker-host.mjs",
20
- "src/batch/reconcile.mjs",
21
- "src/batch/detached-start.mjs",
22
- "src/batch/review.mjs",
23
- "src/batch/resume-multi-lanes.mjs",
24
- "src/batch/resume.mjs",
25
- "src/batch/sequence.mjs",
26
- "src/batch/contract-verify.mjs",
27
- "src/batch/journal-rebuild.mjs",
28
- "src/batch/lane-dirty-check.mjs",
29
- "src/batch/attached-runner.mjs",
30
- "src/batch/lifecycle.mjs",
31
- "src/batch/salvage-batch.mjs",
32
- ];
14
+ /** Modules >500 LOC grandfathered until v2.3 split — emptied after SP-578–592 (issue #117). */
15
+ export const PHASE23_GRANDFATHERED_OVER_500 = [];
33
16
 
34
17
  const PHASE23_ENGINE_LANES_MAX = 500;
35
18
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -0,0 +1,370 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Attached batch promote/exit paths — milestones, land-loop CLI, post-merge limbo (SP-586).
4
+ * Pause/resume reconcile lives in attached-runner-reconcile.mjs (SP-604).
5
+ */
6
+
7
+ import {
8
+ finalizeAttachedLandLoopBeforeExit,
9
+ finalizeResumedBatchForIntegrate,
10
+ isPostMergeLimbo,
11
+ } from "./post-merge-limbo.mjs";
12
+ import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
13
+ import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
14
+ import { reconcileBatch } from "./reconcile.mjs";
15
+ import { readJournalEventsCached } from "./journal.mjs";
16
+ import { enforceOperatorPauseOnDisk } from "./pause.mjs";
17
+ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
18
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
19
+ import { resolveAttachedMilestonePollMs } from "../config/spine-config-schema.mjs";
20
+ import { startParentSessionMonitor } from "./parent-session-monitor.mjs";
21
+ import {
22
+ enforceAttachedEngineSingleOwner,
23
+ reconcilePausedResumeDoneInLane,
24
+ } from "./attached-runner-reconcile.mjs";
25
+
26
+ export { DEFAULT_ATTACHED_MILESTONE_POLL_MS } from "../config/spine-config-schema.mjs";
27
+
28
+ /** @type {boolean} */
29
+ let attachedExitHandlersInstalled = false;
30
+
31
+ /** Journal types surfaced on attached stdout during the land loop. */
32
+ export const ATTACHED_LAND_LOOP_MILESTONE_TYPES = new Set([
33
+ "batch.started",
34
+ "task.started",
35
+ "task.completed",
36
+ "task.failed",
37
+ "batch.merge_started",
38
+ "batch.merge_completed",
39
+ "batch.merge_blocked",
40
+ "gate.opened",
41
+ "gate.evidence_collecting",
42
+ "gate.evidence_completed",
43
+ "gate.evidence_failed",
44
+ "batch.land_loop_finalized",
45
+ "batch.completed",
46
+ ]);
47
+
48
+ /**
49
+ * Install journal-aware SIGTERM/SIGINT handlers before attached engine exit (SP-378).
50
+ *
51
+ * @param {object} params
52
+ * @param {string} params.projectRoot
53
+ * @param {string} [params.spineBin]
54
+ */
55
+ export function installAttachedExitFinalizeHandlers({ projectRoot, spineBin }) {
56
+ if (attachedExitHandlersInstalled) return;
57
+ attachedExitHandlersInstalled = true;
58
+
59
+ const onShutdown = (signal) => {
60
+ const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal });
61
+ if (handoff.handled) {
62
+ process.exit(0);
63
+ }
64
+ };
65
+
66
+ process.once("SIGTERM", () => onShutdown("SIGTERM"));
67
+ process.once("SIGINT", () => onShutdown("SIGINT"));
68
+ }
69
+
70
+ /**
71
+ * @param {number} ms
72
+ */
73
+ function sleep(ms) {
74
+ return new Promise((resolve) => setTimeout(resolve, ms));
75
+ }
76
+
77
+ /**
78
+ * @param {object} event
79
+ */
80
+ function milestoneEventKey(event) {
81
+ if (typeof event.eventId === "string" && event.eventId) {
82
+ return event.eventId;
83
+ }
84
+ const taskId = typeof event.taskId === "string" ? event.taskId : "";
85
+ const timestamp = typeof event.timestamp === "string" ? event.timestamp : String(event.timestamp ?? "");
86
+ return `${event.type ?? "unknown"}:${timestamp}:${taskId}`;
87
+ }
88
+
89
+ /**
90
+ * @param {object} event
91
+ * @returns {string}
92
+ */
93
+ export function formatAttachedMilestoneLine(event) {
94
+ const type = String(event.type ?? "unknown");
95
+ const taskId = typeof event.taskId === "string" && event.taskId ? ` ${event.taskId}` : "";
96
+ const payload =
97
+ event.payload && typeof event.payload === "object" ? /** @type {Record<string, unknown>} */ (event.payload) : {};
98
+ const waveIndex = payload.waveIndex;
99
+ const waveSuffix =
100
+ typeof waveIndex === "number" &&
101
+ (type === "batch.merge_started" || type === "batch.merge_completed" || type === "batch.merge_blocked")
102
+ ? ` wave=${waveIndex}`
103
+ : "";
104
+ return `[spine] ${type}${taskId}${waveSuffix}\n`;
105
+ }
106
+
107
+ /**
108
+ * @param {object} params
109
+ * @param {string} params.projectRoot
110
+ * @param {(line: string) => void} [params.write]
111
+ * @param {number} [params.pollIntervalMs]
112
+ * @returns {Promise<{ stop: () => Promise<void> }>}
113
+ */
114
+ export async function startAttachedMilestoneReporter({
115
+ projectRoot,
116
+ write = (line) => process.stdout.write(line),
117
+ pollIntervalMs,
118
+ }) {
119
+ const configResult = loadSpineConfig(projectRoot);
120
+ const resolvedPollMs =
121
+ pollIntervalMs ??
122
+ resolveAttachedMilestonePollMs({ config: configResult.config ?? {} });
123
+ /** @type {Set<string>} */
124
+ const printed = new Set();
125
+ let batchId = null;
126
+ let stopped = false;
127
+
128
+ const loop = async () => {
129
+ while (!stopped) {
130
+ enforceOperatorPauseOnDisk(projectRoot);
131
+ if (!batchId) {
132
+ const loaded = loadSpineBatchState(projectRoot);
133
+ batchId = loaded.raw?.batchId ? String(loaded.raw.batchId) : null;
134
+ }
135
+ if (batchId) {
136
+ const events = readJournalEventsCached(projectRoot, batchId);
137
+ for (const event of events) {
138
+ const key = milestoneEventKey(event);
139
+ if (printed.has(key)) continue;
140
+ if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
141
+ printed.add(key);
142
+ write(formatAttachedMilestoneLine(event));
143
+ }
144
+ }
145
+ await sleep(resolvedPollMs);
146
+ }
147
+ };
148
+
149
+ const loopPromise = loop();
150
+
151
+ return {
152
+ stop: async () => {
153
+ stopped = true;
154
+ await loopPromise;
155
+ if (batchId) {
156
+ const events = readJournalEventsCached(projectRoot, batchId);
157
+ for (const event of events) {
158
+ const key = milestoneEventKey(event);
159
+ if (printed.has(key)) continue;
160
+ if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
161
+ printed.add(key);
162
+ write(formatAttachedMilestoneLine(event));
163
+ }
164
+ }
165
+ },
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Run an attached foreground engine while streaming land-loop journal milestones to stdout.
171
+ *
172
+ * @param {object} params
173
+ * @param {string} params.projectRoot
174
+ * @param {() => Promise<object>} params.runEngine
175
+ * @param {(line: string) => void} [params.write]
176
+ * @param {boolean} [params.force]
177
+ * @param {"start"|"resume"} [params.operation]
178
+ */
179
+ export async function runAttachedBatchEngine({
180
+ projectRoot,
181
+ runEngine,
182
+ write,
183
+ spineBin,
184
+ _force = false,
185
+ operation = "resume",
186
+ }) {
187
+ if (operation === "start") {
188
+ const lock = enforceAttachedEngineSingleOwner({ projectRoot, force: false, operation: "start" });
189
+ if (!lock.ok) {
190
+ return {
191
+ ok: false,
192
+ exitCode: lock.exitCode ?? 1,
193
+ error: lock.error,
194
+ output: lock.output,
195
+ batchId: lock.batchId,
196
+ };
197
+ }
198
+ }
199
+
200
+ installAttachedExitFinalizeHandlers({ projectRoot, spineBin });
201
+ const reporter = await startAttachedMilestoneReporter({ projectRoot, write });
202
+ /** @type {{ stop: () => Promise<void> }} */
203
+ let parentMonitor = { stop: async () => {} };
204
+ if (process.env.SPINE_ALLOW_ATTACHED_HARNESS !== "1") {
205
+ parentMonitor = await startParentSessionMonitor({
206
+ projectRoot,
207
+ onParentDied: () => {
208
+ process.exit(1);
209
+ },
210
+ });
211
+ }
212
+ try {
213
+ const result = await runEngine();
214
+ const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "exit" });
215
+ if (handoff.handled && handoff.action === "finalized_in_process" && handoff.result) {
216
+ return handoff.result;
217
+ }
218
+ return result;
219
+ } finally {
220
+ await parentMonitor.stop();
221
+ await reporter.stop();
222
+ }
223
+ }
224
+
225
+ /**
226
+ * @param {object} result
227
+ * @param {import("./reconcile.mjs").ReconciliationResult} reconciliation
228
+ */
229
+ function resolveAttachedBatchExitCode(result, reconciliation) {
230
+ if (reconciliation.phase === "merge_blocked") {
231
+ return result.exitCode ?? 1;
232
+ }
233
+ return result.exitCode ?? (result.ok ? 0 : 1);
234
+ }
235
+
236
+ /**
237
+ * @param {object} params
238
+ * @param {string} params.projectRoot
239
+ * @param {"start"|"resume"} params.operation
240
+ * @param {object} params.result
241
+ * @param {boolean} [params.json]
242
+ */
243
+ export function formatAttachedBatchCliResult({ projectRoot, operation, result, json = false }) {
244
+ const loaded = loadSpineBatchState(projectRoot);
245
+ if (loaded.raw?.batchId) {
246
+ reconcilePausedResumeDoneInLane({
247
+ projectRoot,
248
+ state: loaded.raw,
249
+ batchId: String(loaded.raw.batchId),
250
+ });
251
+ }
252
+ const reconciliation = reconcileBatch({ projectRoot });
253
+ const mergeBlocked = reconciliation.phase === "merge_blocked";
254
+
255
+ if (json) {
256
+ return {
257
+ exitCode: resolveAttachedBatchExitCode(result, reconciliation),
258
+ output: `${JSON.stringify({ ...result, reconciliation }, null, 2)}\n`,
259
+ };
260
+ }
261
+
262
+ const operationLabel = operation === "resume" ? "resumed" : "started";
263
+ const headline = result.ok
264
+ ? `Batch ${operationLabel}`
265
+ : mergeBlocked && reconciliation.headline
266
+ ? reconciliation.headline
267
+ : operation === "resume"
268
+ ? "Batch resume failed"
269
+ : "Batch start failed";
270
+
271
+ /** @type {string[]} */
272
+ const lines = ["", headline, ""];
273
+
274
+ if (result.output) {
275
+ lines.push(result.output.trimEnd());
276
+ } else if (result.error && !mergeBlocked) {
277
+ lines.push(String(result.error));
278
+ }
279
+
280
+ if (reconciliation.headline && reconciliation.headline !== headline) {
281
+ lines.push("", reconciliation.headline);
282
+ }
283
+ if (reconciliation.suggestedCommand) {
284
+ lines.push("", ` → ${reconciliation.suggestedCommand}`);
285
+ }
286
+ if (reconciliation.alternatives?.length) {
287
+ lines.push("", " Alternatives:");
288
+ for (const alt of reconciliation.alternatives) {
289
+ lines.push(` • ${alt}`);
290
+ }
291
+ }
292
+
293
+ if (result.batchId) {
294
+ lines.push("", ` Batch: ${result.batchId}`);
295
+ }
296
+ if (result.taskId) {
297
+ lines.push(` Task: ${result.taskId}`);
298
+ }
299
+
300
+ lines.push("");
301
+ return {
302
+ exitCode: resolveAttachedBatchExitCode(result, reconciliation),
303
+ output: lines.join("\n"),
304
+ };
305
+ }
306
+
307
+ /**
308
+ * Write attached CLI output and exit so the foreground process does not linger after batch.completed.
309
+ *
310
+ * @param {{ exitCode?: number, output?: string }} cli
311
+ * @param {object} [options]
312
+ * @param {boolean} [options.deferExit]
313
+ */
314
+ export function finishAttachedBatchCli(cli, { deferExit = false, projectRoot, spineBin } = {}) {
315
+ const exitCode = cli.exitCode ?? 1;
316
+ if (cli.output) {
317
+ process.stdout.write(cli.output);
318
+ }
319
+ if (deferExit) {
320
+ return;
321
+ }
322
+ if (projectRoot) {
323
+ finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "cli_exit" });
324
+ }
325
+ process.exit(exitCode);
326
+ }
327
+
328
+ /**
329
+ * Finalize post-merge limbo during resume without re-running workers.
330
+ *
331
+ * @param {object} params
332
+ * @param {string} params.projectRoot
333
+ * @param {object} params.state
334
+ * @param {string} params.batchId
335
+ * @param {string} params.orchBranch
336
+ * @param {string} [params.fromPhase]
337
+ * @param {boolean} [params.resumeForced]
338
+ * @returns {ReturnType<typeof finalizeResumedBatchForIntegrate>|null}
339
+ */
340
+ export function finalizeResumePostMergeLimbo({
341
+ projectRoot,
342
+ state,
343
+ batchId,
344
+ orchBranch,
345
+ fromPhase = "running",
346
+ resumeForced = false,
347
+ }) {
348
+ if (String(state.phase ?? "") === "completed") {
349
+ return null;
350
+ }
351
+ if (!detectPostMergeLimboForResume({ projectRoot, state }) && !isPostMergeLimbo(state)) {
352
+ return null;
353
+ }
354
+
355
+ terminateStaleDetachedEngine({
356
+ projectRoot,
357
+ state,
358
+ batchId,
359
+ fromPhase,
360
+ });
361
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
362
+
363
+ return finalizeResumedBatchForIntegrate({
364
+ projectRoot,
365
+ state,
366
+ batchId,
367
+ orchBranch,
368
+ resumeForced,
369
+ });
370
+ }
@@ -0,0 +1,291 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Attached pause/resume reconcile paths — handoff locks, single-owner enforce,
4
+ * and paused-resume `.DONE` promotion (SP-604).
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { isProcessAlive } from "../process/liveness.mjs";
10
+ import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
11
+ import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
12
+ import {
13
+ loadSpineBatchState,
14
+ readBatchEnginePid,
15
+ saveSpineBatchState,
16
+ updateSegmentForTask,
17
+ recomputeTaskCounters,
18
+ clearBatchEnginePid,
19
+ } from "./state.mjs";
20
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
21
+ import {
22
+ journalHasContractVerified,
23
+ journalIndicatesPausedForceResume,
24
+ } from "./orphan-detect.mjs";
25
+ import { classifyTaskDoneSemantics } from "./diagnosis-task-done.mjs";
26
+ import { laneDoneMarkerReadyForPromote } from "./journal-rebuild.mjs";
27
+ import { resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
28
+ import { journalHasTaskCompleted } from "./resume-common.mjs";
29
+
30
+ /**
31
+ * @param {string} projectRoot
32
+ * @param {string} batchId
33
+ */
34
+ export function resumeHandoffLockPath(projectRoot, batchId) {
35
+ return path.join(projectRoot, ".spine", "runtime", batchId, "resume-handoff.lock");
36
+ }
37
+
38
+ /**
39
+ * Exclusive lock for forced resume handoff (SP-533 / #167).
40
+ *
41
+ * @param {string} projectRoot
42
+ * @param {string} batchId
43
+ * @param {boolean} [allowRetry]
44
+ * @returns {{ ok: true, release: () => void } | { ok: false, holderPid?: number|null, startedAt?: number }}
45
+ */
46
+ export function tryAcquireResumeHandoffLock(projectRoot, batchId, allowRetry = true) {
47
+ const lockPath = resumeHandoffLockPath(projectRoot, batchId);
48
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
49
+ const payload = JSON.stringify({ pid: process.pid, startedAt: Date.now() });
50
+
51
+ try {
52
+ fs.writeFileSync(lockPath, payload, { encoding: "utf-8", flag: "wx" });
53
+ return {
54
+ ok: true,
55
+ release: () => releaseResumeHandoffLock(projectRoot, batchId),
56
+ };
57
+ } catch (err) {
58
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EEXIST") {
59
+ throw err;
60
+ }
61
+ }
62
+
63
+ /** @type {{ pid?: number, startedAt?: number } | null} */
64
+ let holder = null;
65
+ try {
66
+ holder = JSON.parse(fs.readFileSync(lockPath, "utf-8"));
67
+ } catch {
68
+ try {
69
+ fs.unlinkSync(lockPath);
70
+ } catch {
71
+ /* ignore stale corrupt lock cleanup */
72
+ }
73
+ if (allowRetry) {
74
+ return tryAcquireResumeHandoffLock(projectRoot, batchId, false);
75
+ }
76
+ return { ok: false, holderPid: null };
77
+ }
78
+
79
+ const holderPid = Number(holder?.pid);
80
+ if (Number.isFinite(holderPid) && holderPid > 0 && isProcessAlive(holderPid)) {
81
+ return {
82
+ ok: false,
83
+ holderPid,
84
+ startedAt: Number(holder?.startedAt) || undefined,
85
+ };
86
+ }
87
+
88
+ try {
89
+ fs.unlinkSync(lockPath);
90
+ } catch {
91
+ /* ignore stale lock cleanup */
92
+ }
93
+
94
+ try {
95
+ fs.writeFileSync(lockPath, payload, { encoding: "utf-8", flag: "wx" });
96
+ return {
97
+ ok: true,
98
+ release: () => releaseResumeHandoffLock(projectRoot, batchId),
99
+ };
100
+ } catch (err) {
101
+ if (/** @type {NodeJS.ErrnoException} */ (err).code === "EEXIST") {
102
+ return { ok: false, holderPid: Number.isFinite(holderPid) ? holderPid : null };
103
+ }
104
+ throw err;
105
+ }
106
+ }
107
+
108
+ /**
109
+ * @param {string} projectRoot
110
+ * @param {string} batchId
111
+ */
112
+ export function releaseResumeHandoffLock(projectRoot, batchId) {
113
+ const lockPath = resumeHandoffLockPath(projectRoot, batchId);
114
+ try {
115
+ if (!fs.existsSync(lockPath)) return;
116
+ const holder = JSON.parse(fs.readFileSync(lockPath, "utf-8"));
117
+ if (Number(holder?.pid) === process.pid) {
118
+ fs.unlinkSync(lockPath);
119
+ }
120
+ } catch {
121
+ /* ignore release races */
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Reject a second attached engine when resilience.enginePid is alive (SP-434, GitHub #89).
127
+ * Serialized forced resume handoff when another resume --force is in flight (SP-533, #167).
128
+ *
129
+ * @param {object} params
130
+ * @param {string} params.projectRoot
131
+ * @param {boolean} [params.force] Orphan-terminate prior engine before handoff
132
+ * @param {"start"|"resume"} [params.operation]
133
+ */
134
+ export function enforceAttachedEngineSingleOwner({ projectRoot, force = false, operation = "resume" }) {
135
+ const loaded = loadSpineBatchState(projectRoot);
136
+ const state = loaded.raw;
137
+ if (!state) {
138
+ return { ok: true };
139
+ }
140
+
141
+ const batchId = String(state.batchId ?? "");
142
+ /** @type {(() => void) | undefined} */
143
+ let releaseResumeLock;
144
+
145
+ if (force && operation === "resume") {
146
+ const lock = tryAcquireResumeHandoffLock(projectRoot, batchId);
147
+ if (!lock.ok) {
148
+ const enginePid = readBatchEnginePid(state);
149
+ const holderPid = lock.holderPid ?? null;
150
+ const output =
151
+ `Another batch resume --force is already in progress (batch ${batchId}` +
152
+ `${holderPid ? `, holder PID ${holderPid}` : ""}).\n` +
153
+ `Wait for the in-flight forced resume to finish before starting another.\n`;
154
+ return {
155
+ ok: false,
156
+ exitCode: 1,
157
+ error: "concurrent_resume_blocked",
158
+ output,
159
+ batchId,
160
+ enginePid,
161
+ holderPid,
162
+ };
163
+ }
164
+ releaseResumeLock = lock.release;
165
+ appendJournalEvent(projectRoot, batchId, "batch.resume_handoff_started", {
166
+ pid: process.pid,
167
+ });
168
+ }
169
+
170
+ const enginePid = readBatchEnginePid(state);
171
+ if (enginePid == null || enginePid === process.pid || !isProcessAlive(enginePid)) {
172
+ return releaseResumeLock ? { ok: true, releaseResumeLock } : { ok: true };
173
+ }
174
+
175
+ const fromPhase = String(state.phase ?? "");
176
+ if (force) {
177
+ const terminateResult = terminateStaleDetachedEngine({
178
+ projectRoot,
179
+ state,
180
+ batchId,
181
+ fromPhase,
182
+ allowRunningOrphanTerminate: true,
183
+ });
184
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
185
+ return {
186
+ ok: true,
187
+ handoff: true,
188
+ terminated: terminateResult.terminated,
189
+ stalePid: terminateResult.stalePid ?? enginePid,
190
+ releaseResumeLock,
191
+ };
192
+ }
193
+
194
+ const operationLabel = operation === "start" ? "start" : "resume";
195
+ const output =
196
+ `Attached batch engine already running (PID ${enginePid}, batch ${batchId}).\n` +
197
+ `Stop the existing engine or run spine batch ${operationLabel} --attached --force to orphan it first.\n`;
198
+ return {
199
+ ok: false,
200
+ exitCode: 1,
201
+ error: "attached_engine_already_running",
202
+ output,
203
+ batchId,
204
+ enginePid,
205
+ };
206
+ }
207
+
208
+ /**
209
+ * Promote running cache tasks with lane `.DONE` and contract verify after paused force resume (SP-513 / #184).
210
+ *
211
+ * @param {object} params
212
+ * @param {string} params.projectRoot
213
+ * @param {object} params.state
214
+ * @param {string} params.batchId
215
+ * @returns {{ reconciled: boolean, taskIds?: string[] }}
216
+ */
217
+ export function reconcilePausedResumeDoneInLane({ projectRoot, state, batchId }) {
218
+ if (!state || typeof state !== "object" || !batchId) {
219
+ return { reconciled: false };
220
+ }
221
+
222
+ const journalEvents = readJournalEvents(projectRoot, batchId);
223
+ if (!journalIndicatesPausedForceResume(journalEvents)) {
224
+ return { reconciled: false };
225
+ }
226
+
227
+ const configResult = loadSpineConfig(projectRoot);
228
+ const tasksRoot = resolveTasksRoot(projectRoot, configResult);
229
+ const lanes = state.lanes ?? [];
230
+ /** @type {string[]} */
231
+ const promotedTaskIds = [];
232
+ let changed = false;
233
+
234
+ for (const task of state.tasks ?? []) {
235
+ const status = String(task?.status ?? "").toLowerCase();
236
+ if (status !== "running" && status !== "pending") continue;
237
+
238
+ const classified = classifyTaskDoneSemantics(task, {
239
+ tasksRoot,
240
+ projectRoot,
241
+ batchId,
242
+ lanes,
243
+ });
244
+ if (
245
+ !laneDoneMarkerReadyForPromote({
246
+ projectRoot,
247
+ batchId,
248
+ task,
249
+ lanes,
250
+ classified,
251
+ })
252
+ ) {
253
+ continue;
254
+ }
255
+ if (!journalHasContractVerified(journalEvents, task.taskId)) continue;
256
+
257
+ task.status = "succeeded";
258
+ task.doneFileFound = true;
259
+ task.exitReason = task.exitReason ?? "done";
260
+ if (!task.endedAt) task.endedAt = Date.now();
261
+ updateSegmentForTask(state, task.taskId, "succeeded");
262
+ promotedTaskIds.push(task.taskId);
263
+ changed = true;
264
+
265
+ if (!journalHasTaskCompleted(journalEvents, task.taskId)) {
266
+ const laneNumber = Number(task.laneNumber ?? 1);
267
+ const lane = lanes.find((entry) => Number(entry?.laneNumber) === laneNumber);
268
+ appendJournalEvent(projectRoot, batchId, "task.completed", {
269
+ taskId: task.taskId,
270
+ laneNumber,
271
+ laneId: lane?.laneId ?? `lane-${laneNumber}`,
272
+ resumed: true,
273
+ skippedDoneOnDisk: true,
274
+ reconciled: true,
275
+ });
276
+ }
277
+ }
278
+
279
+ if (!changed) {
280
+ return { reconciled: false };
281
+ }
282
+
283
+ const enginePid = readBatchEnginePid(state);
284
+ if (enginePid != null && !isProcessAlive(enginePid)) {
285
+ clearBatchEnginePid(state);
286
+ }
287
+
288
+ recomputeTaskCounters(state);
289
+ saveSpineBatchState(projectRoot, state);
290
+ return { reconciled: true, taskIds: promotedTaskIds };
291
+ }