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
@@ -0,0 +1,459 @@
1
+ // @ts-nocheck
2
+ /** Diagnosis derivation (SP-596/SP-606 / #192). */
3
+
4
+ import fs from "node:fs";
5
+ import {
6
+ inferLaunchFailureFromWorkerOutputTail,
7
+ inferLaunchFailureKind,
8
+ } from "./diagnosis.mjs";
9
+ import { inferWorkerDoneMissingFailure } from "./diagnosis-worker-done-missing.mjs";
10
+ import { inferStubExitReasonForTask } from "./diagnosis-stub.mjs";
11
+ import { workerOutputLogPath, workerOutputLogRef } from "./worker-output.mjs";
12
+ import { journalEventsSinceResume } from "./orphan-detect.mjs";
13
+ import { isPostMergeLimbo } from "./limbo-detect.mjs";
14
+ import { isProcessAlive } from "../process/liveness.mjs";
15
+ import { readBatchEnginePid } from "./state.mjs";
16
+ import {
17
+ LIMBO_PHASES,
18
+ RUNNING_PHASES,
19
+ } from "./reconcile-light-cache.mjs";
20
+
21
+ /**
22
+ * @param {unknown} rawTasks
23
+ * @param {string|null} failedTaskId
24
+ * @returns {string|null}
25
+ */
26
+ function resolveFailedExitReason(rawTasks, failedTaskId) {
27
+ if (!failedTaskId || !Array.isArray(rawTasks)) return null;
28
+ const match = rawTasks.find((entry) => {
29
+ if (!entry || typeof entry !== "object") return false;
30
+ return String(entry.taskId ?? entry.id ?? "") === failedTaskId;
31
+ });
32
+ if (!match || typeof match !== "object") return null;
33
+ const exitReason = /** @type {{ exitReason?: unknown }} */ (match).exitReason;
34
+ return typeof exitReason === "string" && exitReason ? exitReason : null;
35
+ }
36
+
37
+ /**
38
+ * @param {string|null} failedTaskId
39
+ * @param {object} signals
40
+ * @returns {string|null}
41
+ */
42
+ function resolvePrimaryFailureExitReason(failedTaskId, signals) {
43
+ const fromTask = resolveFailedExitReason(signals.raw?.tasks, failedTaskId);
44
+ if (fromTask) return fromTask;
45
+ if (!failedTaskId) return null;
46
+ if (Array.isArray(signals.segments)) {
47
+ const segment = signals.segments.find((entry) => entry?.taskId === failedTaskId);
48
+ const classification = segment?.classification;
49
+ if (
50
+ typeof classification === "string" &&
51
+ classification &&
52
+ classification !== "terminal-failure"
53
+ ) {
54
+ return classification;
55
+ }
56
+ }
57
+ if (Array.isArray(signals.journalEvents)) {
58
+ for (let index = signals.journalEvents.length - 1; index >= 0; index -= 1) {
59
+ const event = signals.journalEvents[index];
60
+ if (event.type !== "task.failed") continue;
61
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
62
+ if (eventTaskId !== failedTaskId) continue;
63
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
64
+ const reason = payload.exitReason ?? payload.classification;
65
+ if (typeof reason === "string" && reason) return reason;
66
+ }
67
+ }
68
+ return null;
69
+ }
70
+
71
+ /**
72
+ * @param {string|null} failedTaskId
73
+ * @param {string|null} exitReason
74
+ * @param {object} signals
75
+ * @returns {{ exitReason: string|null, launchFailureKind: string|null }}
76
+ */
77
+ function deriveFailureContext(failedTaskId, exitReason, signals) {
78
+ let resolvedExitReason =
79
+ exitReason ?? resolvePrimaryFailureExitReason(failedTaskId, signals);
80
+ if (failedTaskId && signals.tasksRoot) {
81
+ const taskFolder =
82
+ signals.tasks?.find((entry) => entry.taskId === failedTaskId)?.taskFolder ?? null;
83
+ const stubReason = inferStubExitReasonForTask(signals.tasksRoot, failedTaskId, taskFolder);
84
+ if (stubReason) {
85
+ resolvedExitReason = stubReason;
86
+ }
87
+ }
88
+ const launchFailureKind = inferLaunchFailureKind({
89
+ exitReason: resolvedExitReason,
90
+ journalEvents: signals.journalEvents,
91
+ failedTaskId,
92
+ });
93
+ return { exitReason: resolvedExitReason, launchFailureKind };
94
+ }
95
+
96
+ const WORKER_OUTPUT_TAIL_LINES = 20;
97
+
98
+ /**
99
+ * @param {string} filePath
100
+ * @param {number} [lineCount]
101
+ * @returns {string|null}
102
+ */
103
+ function readWorkerOutputLogTail(filePath, lineCount = WORKER_OUTPUT_TAIL_LINES) {
104
+ if (!fs.existsSync(filePath)) return null;
105
+ const content = fs.readFileSync(filePath, "utf-8");
106
+ const lines = content.split("\n");
107
+ if (lines.at(-1) === "") lines.pop();
108
+ if (lines.length === 0) return null;
109
+ return lines.slice(-lineCount).join("\n");
110
+ }
111
+
112
+ /**
113
+ * @param {string} projectRoot
114
+ * @param {string} batchId
115
+ * @param {string|null} failedTaskId
116
+ * @param {Array<{ taskId: string, laneNumber?: number|null }>} tasks
117
+ * @param {string|null} launchFailureKind
118
+ * @returns {string|null}
119
+ */
120
+ export function enrichLaunchFailureFromWorkerOutput(projectRoot, batchId, failedTaskId, tasks, launchFailureKind) {
121
+ if (launchFailureKind || !failedTaskId || !batchId) return launchFailureKind;
122
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
123
+ if (!task || task.laneNumber == null) return launchFailureKind;
124
+ const logPath = workerOutputLogPath(projectRoot, batchId, task.laneNumber, failedTaskId);
125
+ const tail = readWorkerOutputLogTail(logPath);
126
+ return inferLaunchFailureFromWorkerOutputTail(tail) ?? launchFailureKind;
127
+ }
128
+
129
+ /**
130
+ * @param {string} projectRoot
131
+ * @param {string} batchId
132
+ * @param {string|null} failedTaskId
133
+ * @param {Array<{ taskId: string, laneNumber?: number|null }>} tasks
134
+ * @param {object|null} doneMissingHint
135
+ * @returns {{ workerOutputLogRef: string|null, workerOutputLogPath: string|null, workerOutputTail: string|null, workerOutputSnippet: string|null, changedFileCount: number|null }}
136
+ */
137
+ export function enrichWorkerDoneMissingContext(
138
+ projectRoot,
139
+ batchId,
140
+ failedTaskId,
141
+ tasks,
142
+ doneMissingHint,
143
+ ) {
144
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
145
+ const laneNumber = task?.laneNumber;
146
+ const logRef =
147
+ doneMissingHint?.workerOutputLogRef ??
148
+ (failedTaskId && laneNumber != null
149
+ ? workerOutputLogRef(batchId, laneNumber, failedTaskId)
150
+ : null);
151
+ const logPath =
152
+ doneMissingHint?.workerOutputLogPath ??
153
+ (failedTaskId && laneNumber != null
154
+ ? workerOutputLogPath(projectRoot, batchId, laneNumber, failedTaskId)
155
+ : null);
156
+ const tailFromDisk = logPath ? readWorkerOutputLogTail(logPath) : null;
157
+ const outputText = [doneMissingHint?.output, tailFromDisk].filter(Boolean).join("\n");
158
+ const snippet = outputText
159
+ ? outputText
160
+ .split("\n")
161
+ .filter(Boolean)
162
+ .slice(-3)
163
+ .join(" | ")
164
+ : null;
165
+
166
+ return {
167
+ workerOutputLogRef: logRef,
168
+ workerOutputLogPath: logPath,
169
+ workerOutputTail: tailFromDisk,
170
+ workerOutputSnippet: snippet,
171
+ changedFileCount:
172
+ doneMissingHint?.changedFileCount != null ? doneMissingHint.changedFileCount : null,
173
+ };
174
+ }
175
+
176
+ /**
177
+ * @param {Array<{ taskId: string, classification: string, laneNumber?: number|null }>} tasks
178
+ * @param {string|null} failedTaskId
179
+ * @returns {boolean}
180
+ */
181
+ export function hasGhostRunningCluster(tasks, failedTaskId) {
182
+ if (!failedTaskId) return false;
183
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
184
+ if (!task || task.laneNumber == null) return false;
185
+ const laneNumber = Number(task.laneNumber);
186
+ return (
187
+ tasks.filter(
188
+ (entry) =>
189
+ entry.classification === "running" && Number(entry.laneNumber) === laneNumber,
190
+ ).length > 1
191
+ );
192
+ }
193
+
194
+ /**
195
+ * @param {object[]} journalEvents
196
+ * @param {string|null} failedTaskId
197
+ * @returns {string[]}
198
+ */
199
+ export function extractGitignoredPathsFromJournal(journalEvents, failedTaskId) {
200
+ if (!Array.isArray(journalEvents)) return [];
201
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
202
+ const event = journalEvents[index];
203
+ if (event.type !== "task.failed") continue;
204
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
205
+ if (failedTaskId && eventTaskId && eventTaskId !== failedTaskId) continue;
206
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
207
+ if (Array.isArray(payload.gitignoredPaths)) {
208
+ return payload.gitignoredPaths.filter((entry) => typeof entry === "string");
209
+ }
210
+ }
211
+ return [];
212
+ }
213
+
214
+ /**
215
+ * @param {Record<string, unknown>|null|undefined} raw
216
+ * @param {string} batchId
217
+ * @param {string} taskId
218
+ * @returns {string|null}
219
+ */
220
+ export function laneTaskBranchForDiagnosis(raw, batchId, taskId) {
221
+ const tasks = raw?.tasks;
222
+ if (!Array.isArray(tasks)) return null;
223
+ const task = tasks.find((entry) => entry?.taskId === taskId);
224
+ if (!task || task.laneNumber == null) return null;
225
+ return `task/spine-lane-${task.laneNumber}-${batchId}`;
226
+ }
227
+
228
+ /**
229
+ * @param {string} diagnosis
230
+ * @param {string|null} failedTaskId
231
+ * @param {object} signals
232
+ * @param {string|null} [exitReason]
233
+ */
234
+ function withFailureContext(diagnosis, failedTaskId, signals, exitReason = null) {
235
+ const context = deriveFailureContext(failedTaskId, exitReason, signals);
236
+ return {
237
+ diagnosis,
238
+ failedTaskId,
239
+ exitReason: context.exitReason,
240
+ launchFailureKind: context.launchFailureKind,
241
+ };
242
+ }
243
+
244
+ /**
245
+ * @param {object[]} journalEvents
246
+ * @param {Record<string, unknown>|null|undefined} raw
247
+ * @param {string|null} taskId
248
+ */
249
+ function journalIndicatesResumeRulesStall(journalEvents, raw, taskId) {
250
+ const scoped = journalEventsSinceResume(journalEvents, raw);
251
+ const hasRulesSelected = scoped.some((event) => {
252
+ if (event.type !== "worker.rules_selected") return false;
253
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
254
+ return !taskId || !eventTaskId || eventTaskId === taskId;
255
+ });
256
+ const hasBatchResumed = scoped.some((event) => event.type === "batch.resumed");
257
+ return hasRulesSelected && hasBatchResumed;
258
+ }
259
+
260
+ /**
261
+ * @param {object} signals
262
+ */
263
+ function findNeedsReplanTask(signals) {
264
+ const tasks = signals.raw?.tasks ?? signals.tasks ?? [];
265
+ return (
266
+ tasks.find(
267
+ (task) =>
268
+ task?.exitReason === "needs_replan" &&
269
+ (task.status === "failed" || task.classification === "terminal-failure"),
270
+ ) ?? null
271
+ );
272
+ }
273
+
274
+ /**
275
+ * @param {object} signals
276
+ */
277
+ function hasNeedsReplanBlocker(signals) {
278
+ const tasks = signals.raw?.tasks ?? signals.tasks ?? [];
279
+ return tasks.some((task) => task?.exitReason === "needs_replan");
280
+ }
281
+
282
+ /**
283
+ * @param {object} signals
284
+ */
285
+ export function deriveDiagnosis(signals) {
286
+ const {
287
+ phase,
288
+ endedAt,
289
+ failedTasks,
290
+ allTasksTerminalSuccess,
291
+ hasRunningTasks,
292
+ hasPendingTasks,
293
+ hasFailedTasks,
294
+ hasSegmentDrift,
295
+ failedTaskId,
296
+ mergeResultsEmpty,
297
+ git,
298
+ orphanRunning,
299
+ } = signals;
300
+
301
+ if (orphanRunning) {
302
+ if (orphanRunning.kind === "lane" && orphanRunning.taskId) {
303
+ const enginePid = readBatchEnginePid(signals.raw);
304
+ const engineDead = enginePid == null || !isProcessAlive(enginePid);
305
+ const resumeRulesStall = journalIndicatesResumeRulesStall(
306
+ signals.journalEvents ?? [],
307
+ signals.raw,
308
+ orphanRunning.taskId,
309
+ );
310
+ if (engineDead && resumeRulesStall) {
311
+ return withFailureContext("engine_orphaned", orphanRunning.taskId, signals);
312
+ }
313
+ return withFailureContext("worker_orphaned", orphanRunning.taskId, signals);
314
+ }
315
+ return withFailureContext("engine_orphaned", orphanRunning.taskId ?? null, signals);
316
+ }
317
+
318
+ if (signals.stateDrift?.drifted) {
319
+ const driftTask = signals.stateDrift.entries.find((entry) => entry.taskId !== "*");
320
+ return withFailureContext("state_drift", driftTask?.taskId ?? null, signals);
321
+ }
322
+
323
+ if (
324
+ !hasRunningTasks &&
325
+ hasPendingTasks &&
326
+ Array.isArray(signals.tasks) &&
327
+ signals.tasks.some(
328
+ (task) =>
329
+ task?.doneInLane === true &&
330
+ (task.status === "pending" || task.status === "running" || task.classification === "pending" || task.classification === "running"),
331
+ )
332
+ ) {
333
+ const driftTask = signals.tasks.find((task) => task?.doneInLane);
334
+ return withFailureContext("needs_retry", driftTask?.taskId ?? null, signals);
335
+ }
336
+
337
+ if (git?.gitInspectionError) {
338
+ return withFailureContext("git_unavailable", null, signals);
339
+ }
340
+
341
+ if (phase === "aborted") {
342
+ return withFailureContext("aborted", null, signals);
343
+ }
344
+ if (phase === "completed" && endedAt != null) {
345
+ if (git.orchBranchExists && !git.orchMergedToBase) {
346
+ return withFailureContext("needs_integrate", null, signals);
347
+ }
348
+ return withFailureContext("completed", null, signals);
349
+ }
350
+
351
+ const limboSignals =
352
+ allTasksTerminalSuccess &&
353
+ failedTasks === 0 &&
354
+ LIMBO_PHASES.has(phase) &&
355
+ endedAt == null &&
356
+ mergeResultsEmpty;
357
+
358
+ if (limboSignals && git.orchMergedToBase) {
359
+ return withFailureContext("completed_manual", null, signals);
360
+ }
361
+
362
+ if (limboSignals) {
363
+ return withFailureContext("limbo_stale", null, signals);
364
+ }
365
+
366
+ if (hasFailedTasks || hasSegmentDrift) {
367
+ const replanTask = findNeedsReplanTask(signals);
368
+ if (replanTask) {
369
+ return withFailureContext(
370
+ "needs_replan",
371
+ replanTask.taskId ?? failedTaskId,
372
+ signals,
373
+ "needs_replan",
374
+ );
375
+ }
376
+ const doneMissing = inferWorkerDoneMissingFailure({
377
+ journalEvents: signals.journalEvents,
378
+ failedTaskId,
379
+ });
380
+ if (doneMissing) {
381
+ return withFailureContext("worker_done_missing", failedTaskId, signals);
382
+ }
383
+ return withFailureContext("needs_retry", failedTaskId, signals);
384
+ }
385
+
386
+ if (hasNeedsReplanBlocker(signals)) {
387
+ const replanTask = findNeedsReplanTask(signals);
388
+ return withFailureContext(
389
+ "needs_replan",
390
+ replanTask?.taskId ?? failedTaskId,
391
+ signals,
392
+ "needs_replan",
393
+ );
394
+ }
395
+
396
+ const postMergeLimbo = isPostMergeLimbo(signals.raw ?? {}, git);
397
+ signals.postMergeLimbo = postMergeLimbo;
398
+
399
+ if (postMergeLimbo) {
400
+ return withFailureContext("needs_integrate", null, signals);
401
+ }
402
+
403
+ if (phase === "merge_blocked") {
404
+ return withFailureContext("failed", null, signals);
405
+ }
406
+
407
+ if (
408
+ phase === "merging" &&
409
+ endedAt != null &&
410
+ Array.isArray(signals.raw?.mergeResults) &&
411
+ signals.raw.mergeResults.some((entry) => String(entry?.status ?? "").toLowerCase() === "failed")
412
+ ) {
413
+ return withFailureContext("failed", null, signals);
414
+ }
415
+
416
+ if (phase === "merging" || (allTasksTerminalSuccess && mergeResultsEmpty && git.orchBranchExists && !git.orchMergedToBase)) {
417
+ if (allTasksTerminalSuccess && git.orchBranchExists && !git.orchMergedToBase && !mergeResultsEmpty) {
418
+ return withFailureContext("needs_integrate", null, signals);
419
+ }
420
+ return withFailureContext("needs_merge", null, signals);
421
+ }
422
+
423
+ if (allTasksTerminalSuccess && git.orchBranchExists && !git.orchMergedToBase && mergeResultsEmpty) {
424
+ return withFailureContext("needs_integrate", null, signals);
425
+ }
426
+
427
+ if (
428
+ phase === "failed" &&
429
+ !hasFailedTasks &&
430
+ !hasSegmentDrift &&
431
+ hasPendingTasks
432
+ ) {
433
+ return withFailureContext("needs_retry", null, signals);
434
+ }
435
+
436
+ if (
437
+ phase === "failed" &&
438
+ !hasFailedTasks &&
439
+ !hasSegmentDrift &&
440
+ allTasksTerminalSuccess &&
441
+ mergeResultsEmpty
442
+ ) {
443
+ return withFailureContext("needs_merge", null, signals);
444
+ }
445
+
446
+ if (phase === "failed" || (failedTasks > 0 && !hasPendingTasks && !hasRunningTasks)) {
447
+ return withFailureContext("failed", failedTaskId, signals);
448
+ }
449
+
450
+ if (phase === "paused") {
451
+ return withFailureContext("paused", null, signals);
452
+ }
453
+
454
+ if (RUNNING_PHASES.has(phase) || hasRunningTasks || hasPendingTasks) {
455
+ return withFailureContext("running", null, signals);
456
+ }
457
+
458
+ return withFailureContext("paused", null, signals);
459
+ }
@@ -0,0 +1,61 @@
1
+ // @ts-nocheck
2
+ /** Light-reconcile git cache and phase sets (SP-606 / #192). */
3
+
4
+ export const LIMBO_PHASES = new Set(["stopped", "failed", "executing"]);
5
+ export const RUNNING_PHASES = new Set(["planning", "running", "executing", "merging"]);
6
+
7
+ /** @type {{ projectRoot: string|null, batchId: string|null, phase: string|null, git: object|null, diagnosis: string|null }} */
8
+ export let _lightReconcileCache = {
9
+ projectRoot: null,
10
+ batchId: null,
11
+ phase: null,
12
+ git: null,
13
+ diagnosis: null,
14
+ };
15
+
16
+ /**
17
+ * Clears light-reconcile git cache (test isolation).
18
+ */
19
+ export function clearLightReconcileCache() {
20
+ _lightReconcileCache = {
21
+ projectRoot: null,
22
+ batchId: null,
23
+ phase: null,
24
+ git: null,
25
+ diagnosis: null,
26
+ };
27
+ }
28
+
29
+ /**
30
+ * @param {string} projectRoot
31
+ * @param {string} batchId
32
+ * @param {string} phase
33
+ */
34
+ export function lightReconcileCacheMatches(projectRoot, batchId, phase) {
35
+ return (
36
+ _lightReconcileCache.projectRoot === projectRoot &&
37
+ _lightReconcileCache.batchId === batchId &&
38
+ _lightReconcileCache.phase === phase &&
39
+ _lightReconcileCache.git != null
40
+ );
41
+ }
42
+
43
+ /**
44
+ * @param {string} projectRoot
45
+ * @param {string} batchId
46
+ * @param {string} phase
47
+ * @param {object} git
48
+ * @param {string|null} diagnosis
49
+ */
50
+ export function updateLightReconcileCache(projectRoot, batchId, phase, git, diagnosis) {
51
+ _lightReconcileCache = { projectRoot, batchId, phase, git, diagnosis };
52
+ }
53
+
54
+ export const HUMAN_SYNC_OVERRIDE_DIAGNOSES = new Set([
55
+ "completed",
56
+ "completed_manual",
57
+ "needs_integrate",
58
+ "limbo_stale",
59
+ "running",
60
+ "paused",
61
+ ]);
@@ -0,0 +1,198 @@
1
+ // @ts-nocheck
2
+ /** Orphan reconcile helpers (SP-606 / #192). */
3
+
4
+ import {
5
+ appendJournalEvent,
6
+ readJournalEvents,
7
+ } from "./journal.mjs";
8
+ import {
9
+ detectOrphanRunning,
10
+ journalEventsSinceResume,
11
+ } from "./orphan-detect.mjs";
12
+ import { isProcessAlive } from "../process/liveness.mjs";
13
+ import {
14
+ clearBatchEnginePid,
15
+ readBatchEnginePid,
16
+ recomputeTaskCounters,
17
+ saveSpineBatchState,
18
+ updateSegmentForTask,
19
+ } from "./state.mjs";
20
+ import { reconcileBatch } from "./reconcile-batch.mjs";
21
+
22
+ /**
23
+ * @param {object} ctx
24
+ * @param {string} ctx.projectRoot
25
+ * @param {object|null} [ctx.batchState]
26
+ * @param {string|null} [ctx.batchStatePath]
27
+ */
28
+ export function runReconciliationCheck(ctx) {
29
+ return reconcileBatch(ctx);
30
+ }
31
+
32
+ /**
33
+ * @param {unknown[]} lanes
34
+ * @param {number|null|undefined} laneNumber
35
+ */
36
+ function findLaneForOrphanReconcile(lanes, laneNumber) {
37
+ if (!Array.isArray(lanes)) return null;
38
+ if (laneNumber != null) {
39
+ const match = lanes.find((lane) => Number(lane?.laneNumber) === Number(laneNumber));
40
+ if (match) return match;
41
+ }
42
+ return lanes[0] ?? null;
43
+ }
44
+
45
+ /**
46
+ * Classify tasks for orphan reconcile (status-only, mirrors resume validation).
47
+ *
48
+ * @param {object[]} tasks
49
+ */
50
+ function classifyTasksForOrphanReconcile(tasks) {
51
+ return (tasks ?? []).map((task) => {
52
+ const status = String(task?.status ?? "").toLowerCase();
53
+ return {
54
+ taskId: task.taskId,
55
+ laneNumber: task.laneNumber,
56
+ classification: status === "running" ? "running" : status,
57
+ };
58
+ });
59
+ }
60
+
61
+ /**
62
+ * @param {object[]} journalEvents
63
+ * @param {string} taskId
64
+ * @param {string} eventType
65
+ */
66
+ function journalHasTaskEvent(journalEvents, taskId, eventType) {
67
+ return journalEvents.some((event) => {
68
+ if (String(event?.type ?? "") !== eventType) return false;
69
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
70
+ return eventTaskId === taskId;
71
+ });
72
+ }
73
+
74
+ /**
75
+ * Transition orphan running tasks to failed so retry/resume paths succeed (SP-315 / #20).
76
+ *
77
+ * @param {object} params
78
+ * @param {string} params.projectRoot
79
+ * @param {object} params.state
80
+ * @returns {{ reconciled: boolean, taskId?: string|null, kind?: string, exitReason?: string }}
81
+ */
82
+ export function reconcileOrphanRunningState({ projectRoot, state }) {
83
+ if (!state || typeof state !== "object") {
84
+ return { reconciled: false };
85
+ }
86
+
87
+ const batchId = String(state.batchId ?? "");
88
+ if (!batchId) {
89
+ return { reconciled: false };
90
+ }
91
+
92
+ const classifiedTasks = classifyTasksForOrphanReconcile(state.tasks);
93
+ const hasRunningTasks = classifiedTasks.some((task) => task.classification === "running");
94
+ const journalEvents = readJournalEvents(projectRoot, batchId);
95
+ const scopedJournalEvents = journalEventsSinceResume(journalEvents, state);
96
+ const orphanRunning = detectOrphanRunning({
97
+ phase: String(state.phase ?? ""),
98
+ hasRunningTasks,
99
+ tasks: classifiedTasks,
100
+ lanes: state.lanes ?? [],
101
+ raw: state,
102
+ journalEvents: scopedJournalEvents,
103
+ });
104
+
105
+ if (!orphanRunning) {
106
+ return { reconciled: false };
107
+ }
108
+
109
+ const exitReason = orphanRunning.kind === "engine" ? "engine_orphaned" : "worker_orphaned";
110
+ /** @type {string[]} */
111
+ const taskIdsToFail =
112
+ orphanRunning.kind === "lane" && orphanRunning.taskId
113
+ ? [orphanRunning.taskId]
114
+ : classifiedTasks
115
+ .filter((task) => task.classification === "running")
116
+ .map((task) => task.taskId)
117
+ .filter(Boolean);
118
+
119
+ if (taskIdsToFail.length === 0) {
120
+ return { reconciled: false };
121
+ }
122
+
123
+ const now = Date.now();
124
+ let changed = false;
125
+
126
+ for (const taskId of taskIdsToFail) {
127
+ const task = (state.tasks ?? []).find((entry) => entry?.taskId === taskId);
128
+ if (!task || task.status !== "running") continue;
129
+
130
+ task.status = "failed";
131
+ task.endedAt = now;
132
+ task.exitReason = exitReason;
133
+ updateSegmentForTask(state, taskId, "failed");
134
+ changed = true;
135
+
136
+ if (!journalHasTaskEvent(scopedJournalEvents, taskId, "task.failed")) {
137
+ const lane = findLaneForOrphanReconcile(state.lanes, task.laneNumber);
138
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
139
+ taskId,
140
+ laneNumber: task.laneNumber ?? null,
141
+ laneId: lane?.laneId ?? null,
142
+ reason: exitReason,
143
+ reconciled: true,
144
+ });
145
+ }
146
+
147
+ if (
148
+ orphanRunning.kind === "lane" &&
149
+ !journalHasTaskEvent(scopedJournalEvents, taskId, "lane.died")
150
+ ) {
151
+ const lane = findLaneForOrphanReconcile(state.lanes, task.laneNumber);
152
+ appendJournalEvent(projectRoot, batchId, "lane.died", {
153
+ taskId,
154
+ laneNumber: task.laneNumber ?? null,
155
+ laneId: lane?.laneId ?? null,
156
+ reason: exitReason,
157
+ reconciled: true,
158
+ });
159
+ }
160
+ }
161
+
162
+ for (const lane of state.lanes ?? []) {
163
+ if (!lane || typeof lane !== "object") continue;
164
+ const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
165
+ if (Number.isFinite(workerPid) && workerPid > 0 && !isProcessAlive(workerPid)) {
166
+ delete lane.workerPid;
167
+ changed = true;
168
+ }
169
+ }
170
+
171
+ const enginePid = readBatchEnginePid(state);
172
+ if (enginePid != null && !isProcessAlive(enginePid)) {
173
+ clearBatchEnginePid(state);
174
+ changed = true;
175
+ }
176
+
177
+ if (!changed) {
178
+ return { reconciled: false };
179
+ }
180
+
181
+ recomputeTaskCounters(state);
182
+ if (String(state.phase ?? "") === "running") {
183
+ state.phase = "failed";
184
+ state.endedAt = state.endedAt ?? now;
185
+ state.lastError =
186
+ state.lastError ?? `Orphan reconcile: ${exitReason} (task ${taskIdsToFail.join(", ")})`;
187
+ }
188
+
189
+ saveSpineBatchState(projectRoot, state);
190
+
191
+ return {
192
+ reconciled: true,
193
+ taskId: orphanRunning.taskId ?? taskIdsToFail[0] ?? null,
194
+ kind: orphanRunning.kind,
195
+ exitReason,
196
+ };
197
+ }
198
+