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,140 +1,7 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Batch reconciliation (FR-BATCH-12, §17.5).
4
- */
5
-
6
- import fs from "node:fs";
7
- import path from "node:path";
8
- import { execFileSync } from "node:child_process";
9
- import { loadSpineConfig } from "../config/spine-config-load.mjs";
10
- import { PACKAGE_ROOT } from "../config/spine-init-constants.mjs";
11
- import { resolveTasksRootPath } from "../config/env-overrides.mjs";
12
- import { resolveCurrentGitBranch } from "../config/spine-preflight-lib.mjs";
13
- import { buildStalePathDoctorCheck } from "../doctor/stale-path.mjs";
14
- import { loadGateRecord } from "./gate-evidence-read.mjs";
15
- import { deriveMacroPhase, macroPhaseLabel } from "./macro-phase.mjs";
16
- import {
17
- buildDiagnosisOutput,
18
- classifyTaskDoneSemantics,
19
- inferLaunchFailureFromWorkerOutputTail,
20
- inferLaunchFailureKind,
21
- inferMergeGitignoredFailure,
22
- } from "./diagnosis.mjs";
23
- import { findLatestReviewHonorSignal } from "./review.mjs";
24
- import { summarizeMergeFailures } from "./diagnosis-merge-failure.mjs";
25
- import { inferWorkerDoneMissingFailure } from "./diagnosis-worker-done-missing.mjs";
26
- import { inferEngineOrphanCause } from "./diagnosis-parent-exit.mjs";
27
- import {
28
- findStubMarkedSucceededTask,
29
- inferStubExitReasonForTask,
30
- } from "./diagnosis-stub.mjs";
31
- import { workerOutputLogPath, workerOutputLogRef } from "./worker-output.mjs";
32
- import { detectOrphanRunning, journalEventsSinceResume } from "./orphan-detect.mjs";
33
- import { isPostMergeLimbo } from "./limbo-detect.mjs";
34
- import { computePendingTasks } from "./resume-multi.mjs";
35
- import { computeStatusProgress } from "./status-json.mjs";
36
- import {
37
- detectBatchStateDrift,
38
- rebuildBatchStateFromJournal,
39
- reconcileBatchStateDrift,
40
- } from "./journal-rebuild.mjs";
41
- import { appendJournalEvent, extractJournalDiagnosisHints, findPlanReviewNestedSpawnBlockedFailure, journalPath, readJournalEvents } from "./journal.mjs";
42
- import { findLatestSalvageInspection } from "./salvage.mjs";
43
- import { countCommitsAhead } from "./lane-commit.mjs";
44
- import { isProcessAlive } from "../process/liveness.mjs";
45
- import {
46
- loadBatchStateFile,
47
- parseBatchState,
48
- readBaseBranchHeadAtStart,
49
- } from "./batch-state-io.mjs";
50
- import {
51
- clearBatchEnginePid,
52
- readBatchEnginePid,
53
- recomputeTaskCounters,
54
- saveSpineBatchState,
55
- updateSegmentForTask,
56
- } from "./state.mjs";
57
-
58
- export { loadBatchStateFile, parseBatchState, resolveBatchStatePath } from "./batch-state-io.mjs";
59
-
60
- const LIMBO_PHASES = new Set(["stopped", "failed", "executing"]);
61
- const RUNNING_PHASES = new Set(["planning", "running", "executing", "merging"]);
62
-
63
- /** @type {{ projectRoot: string|null, batchId: string|null, phase: string|null, git: object|null, diagnosis: string|null }} */
64
- let _lightReconcileCache = {
65
- projectRoot: null,
66
- batchId: null,
67
- phase: null,
68
- git: null,
69
- diagnosis: null,
70
- };
71
-
72
- /**
73
- * Clears light-reconcile git cache (test isolation).
74
- */
75
- export function clearLightReconcileCache() {
76
- _lightReconcileCache = {
77
- projectRoot: null,
78
- batchId: null,
79
- phase: null,
80
- git: null,
81
- diagnosis: null,
82
- };
83
- }
84
-
85
- /**
86
- * @param {string} projectRoot
87
- * @param {string} batchId
88
- * @param {string} phase
89
- */
90
- function lightReconcileCacheMatches(projectRoot, batchId, phase) {
91
- return (
92
- _lightReconcileCache.projectRoot === projectRoot &&
93
- _lightReconcileCache.batchId === batchId &&
94
- _lightReconcileCache.phase === phase &&
95
- _lightReconcileCache.git != null
96
- );
97
- }
98
-
99
- /**
100
- * @param {string} projectRoot
101
- * @param {string} batchId
102
- * @param {string} phase
103
- * @param {object} git
104
- * @param {string|null} diagnosis
105
- */
106
- function updateLightReconcileCache(projectRoot, batchId, phase, git, diagnosis) {
107
- _lightReconcileCache = { projectRoot, batchId, phase, git, diagnosis };
108
- }
109
-
110
- /**
111
- * @typedef {object} NormalizedTask
112
- * @property {string} taskId
113
- * @property {string} status
114
- * @property {string|null} taskFolder
115
- * @property {boolean} doneFileFound
116
- * @property {string} classification
117
- * @property {boolean} doneOnMain
118
- * @property {boolean} doneInLane
119
- */
120
-
121
- /**
122
- * @typedef {object} NormalizedBatchState
123
- * @property {"spine"|"taskplane"} source
124
- * @property {string} batchId
125
- * @property {string} phase
126
- * @property {string} baseBranch
127
- * @property {string|null} orchBranch
128
- * @property {unknown} startedAt
129
- * @property {unknown} endedAt
130
- * @property {number} failedTasks
131
- * @property {number} succeededTasks
132
- * @property {number} totalTasks
133
- * @property {unknown[]} mergeResults
134
- * @property {NormalizedTask[]} tasks
135
- * @property {Array<{ segmentId: string, taskId: string, status: string, classification: string }>} segments
136
- * @property {unknown[]} lanes
137
- * @property {Record<string, unknown>} raw
4
+ * Re-export shim — classify / diagnosis / batch / orphan / light-cache (SP-578/596/606).
138
5
  */
139
6
 
140
7
  /**
@@ -154,1562 +21,21 @@ function updateLightReconcileCache(projectRoot, batchId, phase, git, diagnosis)
154
21
  * @property {number} [waveCount]
155
22
  */
156
23
 
157
- /**
158
- * @param {string} projectRoot
159
- * @param {ReturnType<typeof loadSpineConfig>} [configResult]
160
- */
161
- export function resolveTasksRoot(projectRoot, configResult) {
162
- const loaded = configResult ?? loadSpineConfig(projectRoot);
163
- if (!loaded.config) {
164
- return null;
165
- }
166
- return resolveTasksRootPath(projectRoot, loaded.config);
167
- }
168
-
169
- /**
170
- * Align computed classification with reconciled batch-state status (SP-516 / #166).
171
- * Stale lane `.DONE` markers must not imply terminal-success when cache status is
172
- * failed or pending. Running + done markers stays terminal-success for drift (SP-512).
173
- *
174
- * @param {object} classified
175
- */
176
- export function alignTaskClassificationWithStatus(classified) {
177
- const status = String(classified.status ?? "").toLowerCase();
178
- let classification = classified.classification;
179
-
180
- if (status === "succeeded" || status === "skipped") {
181
- classification = "terminal-success";
182
- } else if (status === "failed") {
183
- classification = "terminal-failure";
184
- } else if (status === "running") {
185
- if (classified.doneOnMain || classified.doneInLane || classified.doneFileFound) {
186
- classification = "terminal-success";
187
- } else {
188
- classification = "running";
189
- }
190
- } else {
191
- classification = "pending";
192
- }
193
-
194
- return { ...classified, classification };
195
- }
196
-
197
- /**
198
- * @param {NormalizedBatchState} batch
199
- * @param {string|null} tasksRoot
200
- * @param {string} [projectRoot]
201
- */
202
- export function classifyTasks(batch, tasksRoot, projectRoot = "") {
203
- return batch.tasks.map((task) =>
204
- alignTaskClassificationWithStatus(
205
- classifyTaskDoneSemantics(task, {
206
- tasksRoot,
207
- projectRoot,
208
- batchId: batch.batchId,
209
- lanes: batch.lanes,
210
- }),
211
- ),
212
- );
213
- }
214
-
215
- /**
216
- * Clear stale persisted task classification fields that contradict reconciled status.
217
- *
218
- * @param {object} params
219
- * @param {string} params.projectRoot
220
- * @param {object} params.state
221
- * @returns {{ changed: boolean }}
222
- */
223
- export function syncPersistedClassifications({ projectRoot, state }) {
224
- if (!state || typeof state !== "object") {
225
- return { changed: false };
226
- }
227
-
228
- const batch = parseBatchState(state, "");
229
- if (!batch) {
230
- return { changed: false };
231
- }
232
-
233
- const tasksRoot = resolveTasksRoot(projectRoot);
234
- const classified = classifyTasks(batch, tasksRoot, projectRoot);
235
- const alignedById = new Map(classified.map((task) => [String(task.taskId), task]));
236
- let changed = false;
237
-
238
- for (const task of state.tasks ?? []) {
239
- if (!task?.taskId) continue;
240
- const aligned = alignedById.get(String(task.taskId));
241
- if (!aligned) continue;
242
-
243
- const status = String(task.status ?? "").toLowerCase();
244
- if (status === "succeeded" || status === "skipped") {
245
- if ("classification" in task) {
246
- delete task.classification;
247
- changed = true;
248
- }
249
- continue;
250
- }
251
-
252
- if (!("classification" in task)) continue;
253
-
254
- const persisted = String(task.classification ?? "");
255
- if (persisted === aligned.classification) continue;
256
-
257
- if (status === "failed" || status === "pending") {
258
- delete task.classification;
259
- changed = true;
260
- }
261
- }
262
-
263
- for (const segment of state.segments ?? []) {
264
- if (!segment?.taskId || !("classification" in segment)) continue;
265
- const aligned = alignedById.get(String(segment.taskId));
266
- if (!aligned) continue;
267
- const segmentStatus = String(segment.status ?? "").toLowerCase();
268
- if (segmentStatus === "failed" || segmentStatus === "pending") {
269
- delete segment.classification;
270
- changed = true;
271
- }
272
- }
273
-
274
- if (changed) {
275
- saveSpineBatchState(projectRoot, state);
276
- }
277
-
278
- return { changed };
279
- }
280
-
281
- /**
282
- * @param {string} projectRoot
283
- */
284
- function isInsideGitRepo(projectRoot) {
285
- try {
286
- execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
287
- cwd: projectRoot,
288
- stdio: ["ignore", "pipe", "pipe"],
289
- timeout: 5000,
290
- });
291
- return true;
292
- } catch {
293
- return false;
294
- }
295
- }
296
-
297
- /**
298
- * @param {string} projectRoot
299
- * @param {string} ref
300
- */
301
- function gitRefExists(projectRoot, ref) {
302
- try {
303
- execFileSync("git", ["rev-parse", "--verify", ref], {
304
- cwd: projectRoot,
305
- stdio: ["ignore", "pipe", "pipe"],
306
- timeout: 5000,
307
- });
308
- return true;
309
- } catch {
310
- return false;
311
- }
312
- }
313
-
314
- /**
315
- * @param {string} projectRoot
316
- * @param {string} ancestor
317
- * @param {string} descendant
318
- */
319
- function gitIsAncestor(projectRoot, ancestor, descendant) {
320
- try {
321
- execFileSync("git", ["merge-base", "--is-ancestor", ancestor, descendant], {
322
- cwd: projectRoot,
323
- stdio: ["ignore", "pipe", "pipe"],
324
- timeout: 5000,
325
- });
326
- return true;
327
- } catch {
328
- return false;
329
- }
330
- }
331
-
332
- /**
333
- * @param {object} result
334
- * @param {unknown} err
335
- * @param {string} context
336
- */
337
- function recordGitInspectionError(result, err, context) {
338
- const message = err instanceof Error ? err.message : String(err);
339
- const detail = `${context}: ${message}`;
340
- result.gitInspectionError = result.gitInspectionError
341
- ? `${result.gitInspectionError}; ${detail}`
342
- : detail;
343
- }
344
-
345
- /**
346
- * @param {string} projectRoot
347
- * @param {string} batchId
348
- */
349
- function listOrchBranches(projectRoot, batchId) {
350
- try {
351
- const output = execFileSync("git", ["branch", "-a", "--list", "*orch*"], {
352
- cwd: projectRoot,
353
- encoding: "utf-8",
354
- timeout: 5000,
355
- });
356
-
357
- return output
358
- .split(/\r?\n/)
359
- .map((line) => line.trim().replace(/^\*?\s+/, "").replace(/^remotes\/[^/]+\//, ""))
360
- .filter(Boolean)
361
- .filter((branch) => branch.includes(batchId));
362
- } catch {
363
- return [];
364
- }
365
- }
366
-
367
- /**
368
- * @param {object} ctx
369
- * @param {string} ctx.projectRoot
370
- * @param {string} ctx.batchId
371
- * @param {string} ctx.baseBranch
372
- * @param {string|null} ctx.orchBranch
373
- */
374
- export function inspectGitState(ctx) {
375
- const { projectRoot, batchId, baseBranch, orchBranch } = ctx;
376
- const result = {
377
- inGitRepo: isInsideGitRepo(projectRoot),
378
- baseBranch,
379
- orchBranch,
380
- orchBranches: [],
381
- orchBranchExists: false,
382
- orchMergedToBase: false,
383
- mergedOrchBranch: null,
384
- orchCommitsAhead: null,
385
- gitInspectionError: null,
386
- };
387
-
388
- if (!result.inGitRepo) return result;
389
-
390
- if (process.env.SPINE_TEST_GIT_INSPECTION_THROW) {
391
- result.gitInspectionError = `simulated: ${process.env.SPINE_TEST_GIT_INSPECTION_THROW}`;
392
- return result;
393
- }
394
-
395
- const candidates = new Set(listOrchBranches(projectRoot, batchId));
396
- if (orchBranch) candidates.add(orchBranch);
397
- candidates.add(`orch/cdelgado-${batchId}`);
398
- candidates.add(`orch/spine-*-${batchId}`.replace("*", "operator"));
399
-
400
- result.orchBranches = [...candidates].filter((branch) => !branch.includes("*"));
401
-
402
- for (const branch of result.orchBranches) {
403
- if (!gitRefExists(projectRoot, branch)) continue;
404
- result.orchBranchExists = true;
405
- if (gitIsAncestor(projectRoot, branch, baseBranch)) {
406
- result.orchMergedToBase = true;
407
- result.mergedOrchBranch = branch;
408
- break;
409
- }
410
- }
411
-
412
- const resolvedOrch = orchBranch && gitRefExists(projectRoot, orchBranch) ? orchBranch : result.mergedOrchBranch;
413
- if (resolvedOrch && gitRefExists(projectRoot, resolvedOrch) && !result.orchMergedToBase) {
414
- try {
415
- result.orchCommitsAhead = countCommitsAhead(projectRoot, baseBranch, resolvedOrch);
416
- } catch (err) {
417
- result.orchCommitsAhead = null;
418
- recordGitInspectionError(result, err, "count_commits_ahead");
419
- }
420
- }
421
-
422
- if (!result.orchMergedToBase) {
423
- try {
424
- const merged = execFileSync("git", ["branch", "--merged", baseBranch], {
425
- cwd: projectRoot,
426
- encoding: "utf-8",
427
- timeout: 5000,
428
- });
429
- const mergedOrch = merged
430
- .split(/\r?\n/)
431
- .map((line) => line.trim().replace(/^\*?\s+/, ""))
432
- .filter((branch) => branch.includes("orch") && branch.includes(batchId));
433
- if (mergedOrch.length > 0) {
434
- result.orchMergedToBase = true;
435
- result.mergedOrchBranch = mergedOrch[0];
436
- result.orchBranchExists = true;
437
- }
438
- } catch (err) {
439
- recordGitInspectionError(result, err, "list_merged_branches");
440
- }
441
- }
442
-
443
- return result;
444
- }
445
-
446
- /**
447
- * @typedef {object} HumanBaseSyncInspection
448
- * @property {"human_base_diverged"|"integrate_isolated_ok"} diagnosis
449
- * @property {string} headline
450
- * @property {string[]} [overlapPaths]
451
- * @property {string} [humanHead]
452
- * @property {string} [baseTip]
453
- * @property {string|null} [orchBranch]
454
- * @property {boolean} [preIntegrate]
455
- */
456
-
457
- /**
458
- * @param {string} projectRoot
459
- * @param {string} refA
460
- * @param {string} refB
461
- * @returns {string[]}
462
- */
463
- export function listGitChangedPaths(projectRoot, refA, refB) {
464
- if (!refA || !refB || refA === refB) return [];
465
- try {
466
- const output = execFileSync("git", ["diff", "--name-only", `${refA}..${refB}`], {
467
- cwd: projectRoot,
468
- encoding: "utf-8",
469
- stdio: ["ignore", "pipe", "pipe"],
470
- timeout: 5000,
471
- });
472
- return output
473
- .split(/\r?\n/)
474
- .map((line) => line.trim())
475
- .filter(Boolean);
476
- } catch {
477
- return [];
478
- }
479
- }
480
-
481
- /**
482
- * Paths touched by human commits on base since batch snapshot, excluding orch ancestry.
483
- *
484
- * @param {string} projectRoot
485
- * @param {string} snapshot
486
- * @param {string} humanHead
487
- * @param {string|null} orchBranch
488
- * @returns {string[]}
489
- */
490
- export function listHumanOnlyPaths(projectRoot, snapshot, humanHead, orchBranch) {
491
- if (!snapshot || !humanHead || snapshot === humanHead) return [];
492
- const args = ["log", "--name-only", "--pretty=format:", `${snapshot}..${humanHead}`];
493
- if (orchBranch && gitRefExists(projectRoot, orchBranch)) {
494
- args.push("--not", orchBranch);
495
- }
496
- try {
497
- const output = execFileSync("git", args, {
498
- cwd: projectRoot,
499
- encoding: "utf-8",
500
- stdio: ["ignore", "pipe", "pipe"],
501
- timeout: 5000,
502
- });
503
- return [...new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean))];
504
- } catch {
505
- return [];
506
- }
507
- }
508
-
509
- /**
510
- * @param {string} projectRoot
511
- * @param {string} ref
512
- * @param {string} filePath
513
- */
514
- function pathExistsAtRef(projectRoot, ref, filePath) {
515
- try {
516
- execFileSync("git", ["cat-file", "-e", `${ref}:${filePath}`], {
517
- cwd: projectRoot,
518
- stdio: ["ignore", "pipe", "pipe"],
519
- timeout: 5000,
520
- });
521
- return true;
522
- } catch {
523
- return false;
524
- }
525
- }
526
-
527
- /**
528
- * @param {string} projectRoot
529
- * @param {string} baseTip
530
- * @param {string} snapshot
531
- * @returns {boolean}
532
- */
533
- function humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot) {
534
- const landPaths = listGitChangedPaths(projectRoot, snapshot, baseTip);
535
- for (const filePath of landPaths) {
536
- if (!pathExistsAtRef(projectRoot, baseTip, filePath)) continue;
537
- if (!fs.existsSync(path.join(projectRoot, filePath))) {
538
- return true;
539
- }
540
- }
541
- return false;
542
- }
543
-
544
- /**
545
- * Detect human/base divergence or post-isolated-integrate sync need (FR-WT-08 / #91).
546
- *
547
- * @param {object} ctx
548
- * @param {string} ctx.projectRoot
549
- * @param {string} ctx.baseBranch
550
- * @param {string} ctx.baseBranchHeadAtStart
551
- * @param {string|null} ctx.orchBranch
552
- * @param {ReturnType<typeof inspectGitState>} ctx.git
553
- * @param {object[]} [ctx.journalEvents]
554
- * @returns {HumanBaseSyncInspection|null}
555
- */
556
- export function inspectHumanBaseSync(ctx) {
557
- const { projectRoot, baseBranch, baseBranchHeadAtStart, orchBranch, git, journalEvents } = ctx;
558
- if (!git?.inGitRepo) return null;
559
-
560
- const snapshot = String(baseBranchHeadAtStart ?? "").trim();
561
- if (!snapshot) return null;
562
-
563
- let baseTip = "";
564
- let humanHead = "";
565
- try {
566
- baseTip = execFileSync("git", ["rev-parse", baseBranch], {
567
- cwd: projectRoot,
568
- encoding: "utf-8",
569
- timeout: 5000,
570
- }).trim();
571
- humanHead = execFileSync("git", ["rev-parse", "HEAD"], {
572
- cwd: projectRoot,
573
- encoding: "utf-8",
574
- timeout: 5000,
575
- }).trim();
576
- } catch {
577
- return null;
578
- }
579
-
580
- const integrateCompleted = Array.isArray(journalEvents)
581
- ? journalEvents.some((event) => event.type === "integrate.completed")
582
- : false;
583
- const landSucceeded =
584
- git.orchMergedToBase ||
585
- integrateCompleted ||
586
- (baseTip !== snapshot && gitIsAncestor(projectRoot, snapshot, baseTip));
587
-
588
- const resolvedOrch =
589
- orchBranch && gitRefExists(projectRoot, orchBranch)
590
- ? orchBranch
591
- : git.mergedOrchBranch && gitRefExists(projectRoot, git.mergedOrchBranch)
592
- ? git.mergedOrchBranch
593
- : null;
594
-
595
- const branchResult = resolveCurrentGitBranch(projectRoot);
596
- const onBaseBranch = branchResult.branch === baseBranch;
597
-
598
- const humanSinceSnapshot =
599
- onBaseBranch &&
600
- gitIsAncestor(projectRoot, snapshot, humanHead) &&
601
- humanHead !== snapshot;
602
- const humanPaths = humanSinceSnapshot
603
- ? listHumanOnlyPaths(projectRoot, snapshot, humanHead, resolvedOrch)
604
- : [];
605
- const landPaths = landSucceeded ? listGitChangedPaths(projectRoot, snapshot, baseTip) : [];
606
- const orchPaths =
607
- resolvedOrch && gitRefExists(projectRoot, resolvedOrch)
608
- ? listGitChangedPaths(projectRoot, snapshot, resolvedOrch)
609
- : landPaths;
610
- const overlapPaths = humanPaths.filter((filePath) => orchPaths.includes(filePath));
611
-
612
- if (overlapPaths.length > 0) {
613
- return {
614
- diagnosis: "human_base_diverged",
615
- headline: onBaseBranch
616
- ? `Human commits on ${baseBranch} overlap orch land (${overlapPaths.length} path(s))`
617
- : `Human commits overlap orch land (${overlapPaths.length} path(s))`,
618
- overlapPaths,
619
- humanHead,
620
- baseTip,
621
- orchBranch: resolvedOrch,
622
- preIntegrate: !landSucceeded,
623
- };
624
- }
625
-
626
- if (!landSucceeded) return null;
627
-
628
- const needsCommitSync =
629
- humanHead !== baseTip && onBaseBranch && gitIsAncestor(projectRoot, humanHead, baseTip);
630
- const needsPathSync =
631
- onBaseBranch && humanHead === baseTip && humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot);
632
-
633
- if (!needsCommitSync && !needsPathSync) {
634
- if (!onBaseBranch) {
635
- const mergeBase = (() => {
636
- try {
637
- return execFileSync("git", ["merge-base", humanHead, baseTip], {
638
- cwd: projectRoot,
639
- encoding: "utf-8",
640
- timeout: 5000,
641
- }).trim();
642
- } catch {
643
- return "";
644
- }
645
- })();
646
- if (mergeBase && mergeBase !== baseTip && gitIsAncestor(projectRoot, mergeBase, baseTip)) {
647
- return {
648
- diagnosis: "integrate_isolated_ok",
649
- headline: `${baseBranch} advanced during batch; feature branch needs sync`,
650
- humanHead,
651
- baseTip,
652
- orchBranch: resolvedOrch,
653
- };
654
- }
655
- }
656
- return null;
657
- }
658
-
659
- return {
660
- diagnosis: "integrate_isolated_ok",
661
- headline: needsPathSync
662
- ? `Isolated integrate landed on ${baseBranch}; working tree needs path sync`
663
- : `Isolated integrate landed on ${baseBranch}; checkout needs sync`,
664
- humanHead,
665
- baseTip,
666
- orchBranch: resolvedOrch,
667
- };
668
- }
669
-
670
- const HUMAN_SYNC_OVERRIDE_DIAGNOSES = new Set([
671
- "completed",
672
- "completed_manual",
673
- "needs_integrate",
674
- "limbo_stale",
675
- "running",
676
- "paused",
677
- ]);
678
-
679
- /**
680
- * @param {unknown} rawTasks
681
- * @param {string|null} failedTaskId
682
- * @returns {string|null}
683
- */
684
- function resolveFailedExitReason(rawTasks, failedTaskId) {
685
- if (!failedTaskId || !Array.isArray(rawTasks)) return null;
686
- const match = rawTasks.find((entry) => {
687
- if (!entry || typeof entry !== "object") return false;
688
- return String(entry.taskId ?? entry.id ?? "") === failedTaskId;
689
- });
690
- if (!match || typeof match !== "object") return null;
691
- const exitReason = /** @type {{ exitReason?: unknown }} */ (match).exitReason;
692
- return typeof exitReason === "string" && exitReason ? exitReason : null;
693
- }
694
-
695
- /**
696
- * @param {string|null} failedTaskId
697
- * @param {object} signals
698
- * @returns {string|null}
699
- */
700
- function resolvePrimaryFailureExitReason(failedTaskId, signals) {
701
- const fromTask = resolveFailedExitReason(signals.raw?.tasks, failedTaskId);
702
- if (fromTask) return fromTask;
703
- if (!failedTaskId) return null;
704
- if (Array.isArray(signals.segments)) {
705
- const segment = signals.segments.find((entry) => entry?.taskId === failedTaskId);
706
- const classification = segment?.classification;
707
- if (
708
- typeof classification === "string" &&
709
- classification &&
710
- classification !== "terminal-failure"
711
- ) {
712
- return classification;
713
- }
714
- }
715
- if (Array.isArray(signals.journalEvents)) {
716
- for (let index = signals.journalEvents.length - 1; index >= 0; index -= 1) {
717
- const event = signals.journalEvents[index];
718
- if (event.type !== "task.failed") continue;
719
- const eventTaskId = event.taskId ?? event.payload?.taskId;
720
- if (eventTaskId !== failedTaskId) continue;
721
- const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
722
- const reason = payload.exitReason ?? payload.classification;
723
- if (typeof reason === "string" && reason) return reason;
724
- }
725
- }
726
- return null;
727
- }
728
-
729
- /**
730
- * @param {string|null} failedTaskId
731
- * @param {string|null} exitReason
732
- * @param {object} signals
733
- * @returns {{ exitReason: string|null, launchFailureKind: string|null }}
734
- */
735
- function deriveFailureContext(failedTaskId, exitReason, signals) {
736
- let resolvedExitReason =
737
- exitReason ?? resolvePrimaryFailureExitReason(failedTaskId, signals);
738
- if (failedTaskId && signals.tasksRoot) {
739
- const taskFolder =
740
- signals.tasks?.find((entry) => entry.taskId === failedTaskId)?.taskFolder ?? null;
741
- const stubReason = inferStubExitReasonForTask(signals.tasksRoot, failedTaskId, taskFolder);
742
- if (stubReason) {
743
- resolvedExitReason = stubReason;
744
- }
745
- }
746
- const launchFailureKind = inferLaunchFailureKind({
747
- exitReason: resolvedExitReason,
748
- journalEvents: signals.journalEvents,
749
- failedTaskId,
750
- });
751
- return { exitReason: resolvedExitReason, launchFailureKind };
752
- }
753
-
754
- const WORKER_OUTPUT_TAIL_LINES = 20;
755
-
756
- /**
757
- * @param {string} filePath
758
- * @param {number} [lineCount]
759
- * @returns {string|null}
760
- */
761
- function readWorkerOutputLogTail(filePath, lineCount = WORKER_OUTPUT_TAIL_LINES) {
762
- if (!fs.existsSync(filePath)) return null;
763
- const content = fs.readFileSync(filePath, "utf-8");
764
- const lines = content.split("\n");
765
- if (lines.at(-1) === "") lines.pop();
766
- if (lines.length === 0) return null;
767
- return lines.slice(-lineCount).join("\n");
768
- }
769
-
770
- /**
771
- * @param {string} projectRoot
772
- * @param {string} batchId
773
- * @param {string|null} failedTaskId
774
- * @param {Array<{ taskId: string, laneNumber?: number|null }>} tasks
775
- * @param {string|null} launchFailureKind
776
- * @returns {string|null}
777
- */
778
- function enrichLaunchFailureFromWorkerOutput(projectRoot, batchId, failedTaskId, tasks, launchFailureKind) {
779
- if (launchFailureKind || !failedTaskId || !batchId) return launchFailureKind;
780
- const task = tasks.find((entry) => entry.taskId === failedTaskId);
781
- if (!task || task.laneNumber == null) return launchFailureKind;
782
- const logPath = workerOutputLogPath(projectRoot, batchId, task.laneNumber, failedTaskId);
783
- const tail = readWorkerOutputLogTail(logPath);
784
- return inferLaunchFailureFromWorkerOutputTail(tail) ?? launchFailureKind;
785
- }
786
-
787
- /**
788
- * @param {string} projectRoot
789
- * @param {string} batchId
790
- * @param {string|null} failedTaskId
791
- * @param {Array<{ taskId: string, laneNumber?: number|null }>} tasks
792
- * @param {object|null} doneMissingHint
793
- * @returns {{ workerOutputLogRef: string|null, workerOutputLogPath: string|null, workerOutputTail: string|null, workerOutputSnippet: string|null, changedFileCount: number|null }}
794
- */
795
- function enrichWorkerDoneMissingContext(
796
- projectRoot,
797
- batchId,
798
- failedTaskId,
799
- tasks,
800
- doneMissingHint,
801
- ) {
802
- const task = tasks.find((entry) => entry.taskId === failedTaskId);
803
- const laneNumber = task?.laneNumber;
804
- const logRef =
805
- doneMissingHint?.workerOutputLogRef ??
806
- (failedTaskId && laneNumber != null
807
- ? workerOutputLogRef(batchId, laneNumber, failedTaskId)
808
- : null);
809
- const logPath =
810
- doneMissingHint?.workerOutputLogPath ??
811
- (failedTaskId && laneNumber != null
812
- ? workerOutputLogPath(projectRoot, batchId, laneNumber, failedTaskId)
813
- : null);
814
- const tailFromDisk = logPath ? readWorkerOutputLogTail(logPath) : null;
815
- const outputText = [doneMissingHint?.output, tailFromDisk].filter(Boolean).join("\n");
816
- const snippet = outputText
817
- ? outputText
818
- .split("\n")
819
- .filter(Boolean)
820
- .slice(-3)
821
- .join(" | ")
822
- : null;
823
-
824
- return {
825
- workerOutputLogRef: logRef,
826
- workerOutputLogPath: logPath,
827
- workerOutputTail: tailFromDisk,
828
- workerOutputSnippet: snippet,
829
- changedFileCount:
830
- doneMissingHint?.changedFileCount != null ? doneMissingHint.changedFileCount : null,
831
- };
832
- }
833
-
834
- /**
835
- * @param {Array<{ taskId: string, classification: string, laneNumber?: number|null }>} tasks
836
- * @param {string|null} failedTaskId
837
- * @returns {boolean}
838
- */
839
- function hasGhostRunningCluster(tasks, failedTaskId) {
840
- if (!failedTaskId) return false;
841
- const task = tasks.find((entry) => entry.taskId === failedTaskId);
842
- if (!task || task.laneNumber == null) return false;
843
- const laneNumber = Number(task.laneNumber);
844
- return (
845
- tasks.filter(
846
- (entry) =>
847
- entry.classification === "running" && Number(entry.laneNumber) === laneNumber,
848
- ).length > 1
849
- );
850
- }
851
-
852
- /**
853
- * @param {object[]} journalEvents
854
- * @param {string|null} failedTaskId
855
- * @returns {string[]}
856
- */
857
- function extractGitignoredPathsFromJournal(journalEvents, failedTaskId) {
858
- if (!Array.isArray(journalEvents)) return [];
859
- for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
860
- const event = journalEvents[index];
861
- if (event.type !== "task.failed") continue;
862
- const eventTaskId = event.taskId ?? event.payload?.taskId;
863
- if (failedTaskId && eventTaskId && eventTaskId !== failedTaskId) continue;
864
- const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
865
- if (Array.isArray(payload.gitignoredPaths)) {
866
- return payload.gitignoredPaths.filter((entry) => typeof entry === "string");
867
- }
868
- }
869
- return [];
870
- }
871
-
872
- /**
873
- * @param {Record<string, unknown>|null|undefined} raw
874
- * @param {string} batchId
875
- * @param {string} taskId
876
- * @returns {string|null}
877
- */
878
- function laneTaskBranchForDiagnosis(raw, batchId, taskId) {
879
- const tasks = raw?.tasks;
880
- if (!Array.isArray(tasks)) return null;
881
- const task = tasks.find((entry) => entry?.taskId === taskId);
882
- if (!task || task.laneNumber == null) return null;
883
- return `task/spine-lane-${task.laneNumber}-${batchId}`;
884
- }
885
-
886
- /**
887
- * @param {string} diagnosis
888
- * @param {string|null} failedTaskId
889
- * @param {object} signals
890
- * @param {string|null} [exitReason]
891
- */
892
- function withFailureContext(diagnosis, failedTaskId, signals, exitReason = null) {
893
- const context = deriveFailureContext(failedTaskId, exitReason, signals);
894
- return {
895
- diagnosis,
896
- failedTaskId,
897
- exitReason: context.exitReason,
898
- launchFailureKind: context.launchFailureKind,
899
- };
900
- }
901
-
902
- /**
903
- * @param {object[]} journalEvents
904
- * @param {Record<string, unknown>|null|undefined} raw
905
- * @param {string|null} taskId
906
- */
907
- function journalIndicatesResumeRulesStall(journalEvents, raw, taskId) {
908
- const scoped = journalEventsSinceResume(journalEvents, raw);
909
- const hasRulesSelected = scoped.some((event) => {
910
- if (event.type !== "worker.rules_selected") return false;
911
- const eventTaskId = event.taskId ?? event.payload?.taskId;
912
- return !taskId || !eventTaskId || eventTaskId === taskId;
913
- });
914
- const hasBatchResumed = scoped.some((event) => event.type === "batch.resumed");
915
- return hasRulesSelected && hasBatchResumed;
916
- }
917
-
918
- /**
919
- * @param {object} signals
920
- */
921
- function findNeedsReplanTask(signals) {
922
- const tasks = signals.raw?.tasks ?? signals.tasks ?? [];
923
- return (
924
- tasks.find(
925
- (task) =>
926
- task?.exitReason === "needs_replan" &&
927
- (task.status === "failed" || task.classification === "terminal-failure"),
928
- ) ?? null
929
- );
930
- }
931
-
932
- /**
933
- * @param {object} signals
934
- */
935
- function hasNeedsReplanBlocker(signals) {
936
- const tasks = signals.raw?.tasks ?? signals.tasks ?? [];
937
- return tasks.some((task) => task?.exitReason === "needs_replan");
938
- }
939
-
940
- /**
941
- * @param {object} signals
942
- */
943
- export function deriveDiagnosis(signals) {
944
- const {
945
- phase,
946
- endedAt,
947
- failedTasks,
948
- allTasksTerminalSuccess,
949
- hasRunningTasks,
950
- hasPendingTasks,
951
- hasFailedTasks,
952
- hasSegmentDrift,
953
- failedTaskId,
954
- mergeResultsEmpty,
955
- git,
956
- orphanRunning,
957
- } = signals;
958
-
959
- if (orphanRunning) {
960
- if (orphanRunning.kind === "lane" && orphanRunning.taskId) {
961
- const enginePid = readBatchEnginePid(signals.raw);
962
- const engineDead = enginePid == null || !isProcessAlive(enginePid);
963
- const resumeRulesStall = journalIndicatesResumeRulesStall(
964
- signals.journalEvents ?? [],
965
- signals.raw,
966
- orphanRunning.taskId,
967
- );
968
- if (engineDead && resumeRulesStall) {
969
- return withFailureContext("engine_orphaned", orphanRunning.taskId, signals);
970
- }
971
- return withFailureContext("worker_orphaned", orphanRunning.taskId, signals);
972
- }
973
- return withFailureContext("engine_orphaned", orphanRunning.taskId ?? null, signals);
974
- }
975
-
976
- if (signals.stateDrift?.drifted) {
977
- const driftTask = signals.stateDrift.entries.find((entry) => entry.taskId !== "*");
978
- return withFailureContext("state_drift", driftTask?.taskId ?? null, signals);
979
- }
980
-
981
- if (
982
- !hasRunningTasks &&
983
- hasPendingTasks &&
984
- Array.isArray(signals.tasks) &&
985
- signals.tasks.some(
986
- (task) =>
987
- task?.doneInLane === true &&
988
- (task.status === "pending" || task.status === "running" || task.classification === "pending" || task.classification === "running"),
989
- )
990
- ) {
991
- const driftTask = signals.tasks.find((task) => task?.doneInLane);
992
- return withFailureContext("needs_retry", driftTask?.taskId ?? null, signals);
993
- }
994
-
995
- if (git?.gitInspectionError) {
996
- return withFailureContext("git_unavailable", null, signals);
997
- }
998
-
999
- if (phase === "aborted") {
1000
- return withFailureContext("aborted", null, signals);
1001
- }
1002
- if (phase === "completed" && endedAt != null) {
1003
- if (git.orchBranchExists && !git.orchMergedToBase) {
1004
- return withFailureContext("needs_integrate", null, signals);
1005
- }
1006
- return withFailureContext("completed", null, signals);
1007
- }
1008
-
1009
- const limboSignals =
1010
- allTasksTerminalSuccess &&
1011
- failedTasks === 0 &&
1012
- LIMBO_PHASES.has(phase) &&
1013
- endedAt == null &&
1014
- mergeResultsEmpty;
1015
-
1016
- if (limboSignals && git.orchMergedToBase) {
1017
- return withFailureContext("completed_manual", null, signals);
1018
- }
1019
-
1020
- if (limboSignals) {
1021
- return withFailureContext("limbo_stale", null, signals);
1022
- }
1023
-
1024
- if (hasFailedTasks || hasSegmentDrift) {
1025
- const replanTask = findNeedsReplanTask(signals);
1026
- if (replanTask) {
1027
- return withFailureContext(
1028
- "needs_replan",
1029
- replanTask.taskId ?? failedTaskId,
1030
- signals,
1031
- "needs_replan",
1032
- );
1033
- }
1034
- const doneMissing = inferWorkerDoneMissingFailure({
1035
- journalEvents: signals.journalEvents,
1036
- failedTaskId,
1037
- });
1038
- if (doneMissing) {
1039
- return withFailureContext("worker_done_missing", failedTaskId, signals);
1040
- }
1041
- return withFailureContext("needs_retry", failedTaskId, signals);
1042
- }
1043
-
1044
- if (hasNeedsReplanBlocker(signals)) {
1045
- const replanTask = findNeedsReplanTask(signals);
1046
- return withFailureContext(
1047
- "needs_replan",
1048
- replanTask?.taskId ?? failedTaskId,
1049
- signals,
1050
- "needs_replan",
1051
- );
1052
- }
1053
-
1054
- const postMergeLimbo = isPostMergeLimbo(signals.raw ?? {}, git);
1055
- signals.postMergeLimbo = postMergeLimbo;
1056
-
1057
- if (postMergeLimbo) {
1058
- return withFailureContext("needs_integrate", null, signals);
1059
- }
1060
-
1061
- if (phase === "merge_blocked") {
1062
- return withFailureContext("failed", null, signals);
1063
- }
1064
-
1065
- if (
1066
- phase === "merging" &&
1067
- endedAt != null &&
1068
- Array.isArray(signals.raw?.mergeResults) &&
1069
- signals.raw.mergeResults.some((entry) => String(entry?.status ?? "").toLowerCase() === "failed")
1070
- ) {
1071
- return withFailureContext("failed", null, signals);
1072
- }
1073
-
1074
- if (phase === "merging" || (allTasksTerminalSuccess && mergeResultsEmpty && git.orchBranchExists && !git.orchMergedToBase)) {
1075
- if (allTasksTerminalSuccess && git.orchBranchExists && !git.orchMergedToBase && !mergeResultsEmpty) {
1076
- return withFailureContext("needs_integrate", null, signals);
1077
- }
1078
- return withFailureContext("needs_merge", null, signals);
1079
- }
1080
-
1081
- if (allTasksTerminalSuccess && git.orchBranchExists && !git.orchMergedToBase && mergeResultsEmpty) {
1082
- return withFailureContext("needs_integrate", null, signals);
1083
- }
1084
-
1085
- if (
1086
- phase === "failed" &&
1087
- !hasFailedTasks &&
1088
- !hasSegmentDrift &&
1089
- hasPendingTasks
1090
- ) {
1091
- return withFailureContext("needs_retry", null, signals);
1092
- }
1093
-
1094
- if (
1095
- phase === "failed" &&
1096
- !hasFailedTasks &&
1097
- !hasSegmentDrift &&
1098
- allTasksTerminalSuccess &&
1099
- mergeResultsEmpty
1100
- ) {
1101
- return withFailureContext("needs_merge", null, signals);
1102
- }
1103
-
1104
- if (phase === "failed" || (failedTasks > 0 && !hasPendingTasks && !hasRunningTasks)) {
1105
- return withFailureContext("failed", failedTaskId, signals);
1106
- }
1107
-
1108
- if (phase === "paused") {
1109
- return withFailureContext("paused", null, signals);
1110
- }
1111
-
1112
- if (RUNNING_PHASES.has(phase) || hasRunningTasks || hasPendingTasks) {
1113
- return withFailureContext("running", null, signals);
1114
- }
1115
-
1116
- return withFailureContext("paused", null, signals);
1117
- }
1118
-
1119
- /**
1120
- * @param {object} ctx
1121
- * @param {string} ctx.projectRoot
1122
- * @param {object|null} [ctx.batchState]
1123
- * @param {string|null} [ctx.batchStatePath]
1124
- * @param {boolean} [ctx.verbose]
1125
- * @param {boolean} [ctx.light] Skip git branch scans when batch phase unchanged since last full reconcile.
1126
- * @param {boolean} [ctx._lightRetry] Internal — full reconcile after light diagnosis transition.
1127
- */
1128
- export function reconcileBatch(ctx, _lightRetry = false) {
1129
- const { projectRoot } = ctx;
1130
- const loaded = ctx.batchState
1131
- ? {
1132
- path: ctx.batchStatePath ?? null,
1133
- raw: ctx.batchState,
1134
- parseError: null,
1135
- }
1136
- : loadBatchStateFile(projectRoot, ctx.batchStatePath ?? null);
1137
-
1138
- if (!loaded.path && !loaded.raw) {
1139
- clearLightReconcileCache();
1140
- return {
1141
- diagnosis: null,
1142
- headline: "No active batch — ready to plan or start",
1143
- suggestedCommand: "spine preflight",
1144
- alternatives: ["spine plan all"],
1145
- batchId: null,
1146
- batchStatePath: null,
1147
- phase: null,
1148
- macroPhase: "idle",
1149
- macroPhaseLabel: macroPhaseLabel("idle"),
1150
- signals: { idle: true, macroPhase: "idle" },
1151
- };
1152
- }
1153
-
1154
- if (loaded.parseError) {
1155
- return {
1156
- diagnosis: "failed",
1157
- headline: `Cannot parse batch state: ${loaded.parseError}`,
1158
- suggestedCommand: "spine status --diagnose",
1159
- alternatives: ["spine doctor"],
1160
- batchId: null,
1161
- batchStatePath: loaded.path,
1162
- phase: null,
1163
- macroPhase: "failed",
1164
- macroPhaseLabel: macroPhaseLabel("failed"),
1165
- signals: { parseError: loaded.parseError, macroPhase: "failed" },
1166
- };
1167
- }
1168
-
1169
- const batch = parseBatchState(loaded.raw ?? ctx.batchState, loaded.path ?? ctx.batchStatePath ?? "");
1170
- if (!batch) {
1171
- return {
1172
- diagnosis: "failed",
1173
- headline: "Batch state is unreadable",
1174
- suggestedCommand: "spine status --diagnose",
1175
- batchId: null,
1176
- batchStatePath: loaded.path,
1177
- phase: null,
1178
- macroPhase: "failed",
1179
- macroPhaseLabel: macroPhaseLabel("failed"),
1180
- signals: { unreadable: true, macroPhase: "failed" },
1181
- };
1182
- }
1183
-
1184
- const tasksRoot = resolveTasksRoot(projectRoot);
1185
- let classifiedTasks = classifyTasks(batch, tasksRoot, projectRoot);
1186
- const useLightGit =
1187
- ctx.light === true &&
1188
- !_lightRetry &&
1189
- lightReconcileCacheMatches(projectRoot, batch.batchId, batch.phase);
1190
- const git = useLightGit
1191
- ? /** @type {ReturnType<typeof inspectGitState>} */ (_lightReconcileCache.git)
1192
- : inspectGitState({
1193
- projectRoot,
1194
- batchId: batch.batchId,
1195
- baseBranch: batch.baseBranch,
1196
- orchBranch: batch.orchBranch,
1197
- });
1198
-
1199
- const hasRunningTasks = classifiedTasks.some((task) => task.classification === "running");
1200
- const hasPendingTasks = classifiedTasks.some((task) => task.classification === "pending");
1201
- const pendingWithFailedSegment = batch.segments.some(
1202
- (segment) => segment.classification === "terminal-failure",
1203
- );
1204
- const driftTask = batch.tasks.find((task) => {
1205
- if (task.classification !== "pending") return false;
1206
- return batch.segments.some(
1207
- (segment) => segment.taskId === task.taskId && segment.classification === "terminal-failure",
1208
- );
1209
- });
1210
- const hasSegmentDrift = pendingWithFailedSegment || Boolean(driftTask);
1211
- const hasFailedTasks =
1212
- classifiedTasks.some((task) => task.classification === "terminal-failure") ||
1213
- hasSegmentDrift ||
1214
- batch.failedTasks > 0;
1215
- const allTasksTerminalSuccess =
1216
- classifiedTasks.length > 0 &&
1217
- classifiedTasks.every((task) => task.classification === "terminal-success");
1218
- const failedTask = classifiedTasks.find((task) => task.classification === "terminal-failure");
1219
-
1220
- const signals = {
1221
- phase: batch.phase,
1222
- endedAt: batch.endedAt,
1223
- failedTasks: hasFailedTasks ? Math.max(batch.failedTasks, 1) : batch.failedTasks,
1224
- allTasksTerminalSuccess,
1225
- hasRunningTasks,
1226
- hasPendingTasks,
1227
- hasFailedTasks,
1228
- hasSegmentDrift,
1229
- failedTaskId: failedTask?.taskId ?? driftTask?.taskId ?? null,
1230
- mergeResultsEmpty: batch.mergeResults.length === 0,
1231
- git,
1232
- tasks: classifiedTasks,
1233
- tasksRoot,
1234
- segments: batch.segments,
1235
- lanes: batch.lanes,
1236
- raw: batch.raw,
1237
- };
1238
-
1239
- const journalFile = journalPath(projectRoot, batch.batchId);
1240
- /** @type {object[]} */
1241
- let journalEvents = [];
1242
- if (fs.existsSync(journalFile)) {
1243
- journalEvents = readJournalEvents(projectRoot, batch.batchId);
1244
- signals.journalHints = extractJournalDiagnosisHints(journalEvents);
1245
- signals.journalEvents = journalEvents;
1246
- }
1247
-
1248
- const engineSessionJournalEvents = journalEventsSinceResume(journalEvents, batch.raw);
1249
-
1250
- if (journalEvents.length > 0 && batch.raw) {
1251
- let rebuilt = rebuildBatchStateFromJournal(batch.raw, journalEvents);
1252
- let drift = detectBatchStateDrift(batch.raw, rebuilt, journalEvents, classifiedTasks);
1253
- const healed = reconcileBatchStateDrift({
1254
- projectRoot,
1255
- state: batch.raw,
1256
- classifiedTasks,
1257
- journalEvents,
1258
- drift,
1259
- });
1260
- if (healed.reconciled) {
1261
- journalEvents = readJournalEvents(projectRoot, batch.batchId);
1262
- const refreshed = parseBatchState(batch.raw, loaded.path ?? ctx.batchStatePath ?? "");
1263
- if (refreshed) {
1264
- batch.tasks = refreshed.tasks;
1265
- batch.segments = refreshed.segments;
1266
- batch.succeededTasks = refreshed.succeededTasks;
1267
- batch.failedTasks = refreshed.failedTasks;
1268
- batch.lanes = refreshed.lanes;
1269
- }
1270
- classifiedTasks = classifyTasks(batch, tasksRoot, projectRoot);
1271
- rebuilt = rebuildBatchStateFromJournal(batch.raw, journalEvents);
1272
- drift = detectBatchStateDrift(batch.raw, rebuilt, journalEvents, classifiedTasks);
1273
- }
1274
- signals.stateDrift = drift;
1275
- signals.rebuiltFromJournal = rebuilt;
1276
- if (healed.reconciled) {
1277
- signals.journalEvents = journalEvents;
1278
- signals.tasks = classifiedTasks;
1279
- signals.hasRunningTasks = classifiedTasks.some((task) => task.classification === "running");
1280
- signals.hasPendingTasks = classifiedTasks.some((task) => task.classification === "pending");
1281
- signals.allTasksTerminalSuccess =
1282
- classifiedTasks.length > 0 &&
1283
- classifiedTasks.every((task) => task.classification === "terminal-success");
1284
- const healedFailedTask = classifiedTasks.find(
1285
- (task) => task.classification === "terminal-failure",
1286
- );
1287
- signals.failedTaskId = healedFailedTask?.taskId ?? signals.failedTaskId;
1288
- }
1289
- }
1290
-
1291
- if (batch.raw) {
1292
- syncPersistedClassifications({ projectRoot, state: batch.raw });
1293
- }
1294
-
1295
- signals.orphanRunning = detectOrphanRunning({
1296
- phase: batch.phase,
1297
- hasRunningTasks: signals.hasRunningTasks,
1298
- tasks: classifiedTasks,
1299
- lanes: batch.lanes,
1300
- raw: batch.raw,
1301
- journalEvents: engineSessionJournalEvents,
1302
- });
1303
-
1304
- const pendingTaskCount = computePendingTasks(batch.raw ?? {}).length;
1305
- signals.pendingTaskCount = pendingTaskCount;
1306
-
1307
- const derived = deriveDiagnosis(signals);
1308
- let { diagnosis, failedTaskId, exitReason } = derived;
1309
- const launchFailureKind = derived.launchFailureKind;
1310
- const stubSucceededTaskId = findStubMarkedSucceededTask(tasksRoot, classifiedTasks);
1311
- if (
1312
- stubSucceededTaskId &&
1313
- (diagnosis === "completed" ||
1314
- diagnosis === "needs_integrate" ||
1315
- diagnosis === "limbo_stale" ||
1316
- diagnosis === "completed_manual")
1317
- ) {
1318
- diagnosis = "needs_retry";
1319
- failedTaskId = stubSucceededTaskId;
1320
- exitReason = "stub";
1321
- }
1322
-
1323
- const humanBaseSync = inspectHumanBaseSync({
1324
- projectRoot,
1325
- baseBranch: batch.baseBranch,
1326
- baseBranchHeadAtStart: readBaseBranchHeadAtStart(batch.raw),
1327
- orchBranch: batch.orchBranch,
1328
- git,
1329
- journalEvents,
1330
- });
1331
- if (humanBaseSync && HUMAN_SYNC_OVERRIDE_DIAGNOSES.has(diagnosis)) {
1332
- diagnosis = humanBaseSync.diagnosis;
1333
- }
1334
-
1335
- const doneMissingHint =
1336
- diagnosis === "worker_done_missing"
1337
- ? inferWorkerDoneMissingFailure({
1338
- journalEvents,
1339
- failedTaskId,
1340
- })
1341
- : null;
1342
- const doneMissingContext =
1343
- diagnosis === "worker_done_missing"
1344
- ? enrichWorkerDoneMissingContext(
1345
- projectRoot,
1346
- batch.batchId,
1347
- failedTaskId,
1348
- classifiedTasks,
1349
- doneMissingHint,
1350
- )
1351
- : null;
1352
- const resolvedLaunchFailureKind =
1353
- diagnosis === "worker_orphaned"
1354
- ? enrichLaunchFailureFromWorkerOutput(
1355
- projectRoot,
1356
- batch.batchId,
1357
- failedTaskId,
1358
- classifiedTasks,
1359
- launchFailureKind,
1360
- )
1361
- : launchFailureKind;
1362
- const ghostRunningCluster =
1363
- diagnosis === "worker_orphaned" && hasGhostRunningCluster(classifiedTasks, failedTaskId);
1364
- const salvagePayload = findLatestSalvageInspection(journalEvents, failedTaskId);
1365
- const salvageChangedFileCount = Number(salvagePayload?.changedFileCount ?? 0) || 0;
1366
- const salvageRetryCommand =
1367
- typeof salvagePayload?.retryCommand === "string"
1368
- ? salvagePayload.retryCommand
1369
- : signals.orphanRunning?.taskId
1370
- ? `spine batch retry ${signals.orphanRunning.taskId}`
1371
- : null;
1372
-
1373
- const gateRecord = batch.batchId ? loadGateRecord(projectRoot, batch.batchId) : null;
1374
- const integrateGateOpen = signals.postMergeLimbo === true && Boolean(gateRecord);
1375
-
1376
- const macroPhase = deriveMacroPhase({
1377
- diagnosis,
1378
- batchPhase: batch.phase,
1379
- gateRecord,
1380
- postMergeLimbo: signals.postMergeLimbo === true,
1381
- journalEvents,
1382
- mergeResults: batch.mergeResults,
1383
- hasActiveWorkerTasks: hasRunningTasks || hasPendingTasks,
1384
- allTasksTerminalSuccess: signals.allTasksTerminalSuccess,
1385
- mergeResultsEmpty: signals.mergeResultsEmpty,
1386
- });
1387
- const resolvedMacroPhaseLabel = macroPhaseLabel(macroPhase);
1388
- if (ctx.verbose) {
1389
- signals.macroPhase = macroPhase;
1390
- signals.reconcileMode = useLightGit ? "light" : "full";
1391
- }
1392
-
1393
- const stalePathCheck = buildStalePathDoctorCheck({
1394
- packageRoot: PACKAGE_ROOT,
1395
- runningSpinePath: path.join(PACKAGE_ROOT, "bin", "spine.mjs"),
1396
- });
1397
- const stalePathSpine = stalePathCheck.warning === true;
1398
- const planReviewNestedSpawnBlocked =
1399
- diagnosis === "worker_orphaned" &&
1400
- findPlanReviewNestedSpawnBlockedFailure(journalEvents, failedTaskId);
1401
-
1402
- const mergeGitignoredFailure = inferMergeGitignoredFailure({
1403
- exitReason,
1404
- failureClass: batch.raw?.mergeResults?.find((entry) => entry?.failureClass)?.failureClass ?? null,
1405
- lastError: batch.raw?.lastError ?? null,
1406
- journalEvents,
1407
- });
1408
- const mergeFailureSummary = summarizeMergeFailures(
1409
- batch.mergeResults,
1410
- batch.raw?.lastError ?? null,
1411
- );
1412
- signals.mergeFailed = mergeFailureSummary.mergeFailed;
1413
- signals.failedMerges = mergeFailureSummary.failedMerges;
1414
- signals.failedWaveIndex = mergeFailureSummary.failedWaveIndex;
1415
- signals.failedLane = mergeFailureSummary.failedLane;
1416
- signals.lastError = mergeFailureSummary.lastError;
1417
- const gitignoredPaths = extractGitignoredPathsFromJournal(journalEvents, failedTaskId);
1418
- const taskBranch =
1419
- failedTaskId != null
1420
- ? laneTaskBranchForDiagnosis(batch.raw, batch.batchId, failedTaskId)
1421
- : null;
1422
- const driftTaskStatus =
1423
- failedTaskId != null
1424
- ? String(
1425
- (batch.raw?.tasks ?? []).find((entry) => entry?.taskId === failedTaskId)?.status ?? "",
1426
- )
1427
- : null;
1428
-
1429
- const activeReviewTaskId =
1430
- failedTaskId ??
1431
- classifiedTasks.find((task) => task.classification === "running")?.taskId ??
1432
- null;
1433
- const reviewHonorSignal = findLatestReviewHonorSignal(journalEvents, activeReviewTaskId);
1434
- if (ctx.verbose) {
1435
- signals.reviewHonor = reviewHonorSignal;
1436
- }
1437
-
1438
- const enginePid = readBatchEnginePid(batch.raw);
1439
- const staleEnginePid =
1440
- enginePid != null && !isProcessAlive(enginePid);
1441
- const engineOrphanCause =
1442
- diagnosis === "engine_orphaned"
1443
- ? inferEngineOrphanCause({ journalEvents, staleEnginePid })
1444
- : null;
1445
-
1446
- const output = buildDiagnosisOutput(diagnosis, {
1447
- batchId: batch.batchId,
1448
- phase: batch.phase,
1449
- failedTasks: signals.failedTasks,
1450
- failedTaskId,
1451
- driftTaskStatus,
1452
- exitReason,
1453
- launchFailureKind: resolvedLaunchFailureKind,
1454
- gitMerged: git.orchMergedToBase,
1455
- pendingTaskCount,
1456
- salvageChangedFileCount,
1457
- salvageRetryCommand,
1458
- ghostRunningCluster,
1459
- postMergeLimbo: signals.postMergeLimbo === true,
1460
- integrateGateOpen,
1461
- stalePathSpine,
1462
- planReviewNestedSpawnBlocked,
1463
- mergeGitignoredFailure,
1464
- mergeFailed: mergeFailureSummary.mergeFailed,
1465
- failedWaveIndex: mergeFailureSummary.failedWaveIndex,
1466
- failedLane: mergeFailureSummary.failedLane,
1467
- lastError: mergeFailureSummary.lastError,
1468
- succeededTasks: batch.succeededTasks,
1469
- totalTasks: batch.totalTasks,
1470
- taskBranch,
1471
- gitignoredPaths,
1472
- hasRunningTasks,
1473
- hasPendingTasks,
1474
- allTasksTerminalSuccess: signals.allTasksTerminalSuccess,
1475
- tasksRoot,
1476
- macroPhase,
1477
- reviewHonorSignal,
1478
- ...(doneMissingContext ?? {}),
1479
- engineOrphanCause,
1480
- staleEnginePid,
1481
- humanBaseSync,
1482
- overlapPaths: humanBaseSync?.overlapPaths ?? [],
1483
- });
1484
-
1485
- if (humanBaseSync && (diagnosis === "human_base_diverged" || diagnosis === "integrate_isolated_ok")) {
1486
- output.headline = humanBaseSync.headline;
1487
- }
1488
-
1489
- if (diagnosis === "git_unavailable") {
1490
- output.headline = `Batch ${batch.batchId} — git inspection failed: ${git.gitInspectionError}`;
1491
- output.suggestedCommand = "spine doctor";
1492
- output.alternatives = ["spine status --diagnose"];
1493
- }
1494
-
1495
- const progress = computeStatusProgress({
1496
- batchRaw: batch.raw,
1497
- succeededTasks: batch.succeededTasks,
1498
- totalTasks: batch.totalTasks,
1499
- pendingTasks: pendingTaskCount,
1500
- });
1501
-
1502
- if (
1503
- ctx.light === true &&
1504
- useLightGit &&
1505
- !_lightRetry &&
1506
- _lightReconcileCache.diagnosis != null &&
1507
- _lightReconcileCache.diagnosis !== diagnosis
1508
- ) {
1509
- return reconcileBatch({ ...ctx, light: false }, true);
1510
- }
1511
-
1512
- if (!useLightGit) {
1513
- updateLightReconcileCache(projectRoot, batch.batchId, batch.phase, git, diagnosis);
1514
- } else {
1515
- _lightReconcileCache.diagnosis = diagnosis;
1516
- }
1517
-
1518
- return {
1519
- ...output,
1520
- batchId: batch.batchId,
1521
- batchStatePath: loaded.path ?? ctx.batchStatePath ?? null,
1522
- phase: batch.phase,
1523
- macroPhase,
1524
- macroPhaseLabel: resolvedMacroPhaseLabel,
1525
- failedTasks: signals.failedTasks,
1526
- succeededTasks: batch.succeededTasks,
1527
- totalTasks: batch.totalTasks,
1528
- pendingTasks: progress?.pendingTasks,
1529
- currentWaveIndex: progress?.currentWaveIndex,
1530
- waveCount: progress?.waveCount,
1531
- mergeFailed: mergeFailureSummary.mergeFailed,
1532
- failedMerges: mergeFailureSummary.failedMerges,
1533
- failedWaveIndex: mergeFailureSummary.failedWaveIndex,
1534
- failedLane: mergeFailureSummary.failedLane,
1535
- lastError: mergeFailureSummary.lastError,
1536
- signals: ctx.verbose ? signals : undefined,
1537
- };
1538
- }
1539
-
1540
- /**
1541
- * @param {object} ctx
1542
- * @param {string} ctx.projectRoot
1543
- * @param {object|null} [ctx.batchState]
1544
- * @param {string|null} [ctx.batchStatePath]
1545
- */
1546
- export function runReconciliationCheck(ctx) {
1547
- return reconcileBatch(ctx);
1548
- }
1549
-
1550
- /**
1551
- * @param {unknown[]} lanes
1552
- * @param {number|null|undefined} laneNumber
1553
- */
1554
- function findLaneForOrphanReconcile(lanes, laneNumber) {
1555
- if (!Array.isArray(lanes)) return null;
1556
- if (laneNumber != null) {
1557
- const match = lanes.find((lane) => Number(lane?.laneNumber) === Number(laneNumber));
1558
- if (match) return match;
1559
- }
1560
- return lanes[0] ?? null;
1561
- }
1562
-
1563
- /**
1564
- * Classify tasks for orphan reconcile (status-only, mirrors resume validation).
1565
- *
1566
- * @param {object[]} tasks
1567
- */
1568
- function classifyTasksForOrphanReconcile(tasks) {
1569
- return (tasks ?? []).map((task) => {
1570
- const status = String(task?.status ?? "").toLowerCase();
1571
- return {
1572
- taskId: task.taskId,
1573
- laneNumber: task.laneNumber,
1574
- classification: status === "running" ? "running" : status,
1575
- };
1576
- });
1577
- }
1578
-
1579
- /**
1580
- * @param {object[]} journalEvents
1581
- * @param {string} taskId
1582
- * @param {string} eventType
1583
- */
1584
- function journalHasTaskEvent(journalEvents, taskId, eventType) {
1585
- return journalEvents.some((event) => {
1586
- if (String(event?.type ?? "") !== eventType) return false;
1587
- const eventTaskId = event.taskId ?? event.payload?.taskId;
1588
- return eventTaskId === taskId;
1589
- });
1590
- }
1591
-
1592
- /**
1593
- * Transition orphan running tasks to failed so retry/resume paths succeed (SP-315 / #20).
1594
- *
1595
- * @param {object} params
1596
- * @param {string} params.projectRoot
1597
- * @param {object} params.state
1598
- * @returns {{ reconciled: boolean, taskId?: string|null, kind?: string, exitReason?: string }}
1599
- */
1600
- export function reconcileOrphanRunningState({ projectRoot, state }) {
1601
- if (!state || typeof state !== "object") {
1602
- return { reconciled: false };
1603
- }
1604
-
1605
- const batchId = String(state.batchId ?? "");
1606
- if (!batchId) {
1607
- return { reconciled: false };
1608
- }
1609
-
1610
- const classifiedTasks = classifyTasksForOrphanReconcile(state.tasks);
1611
- const hasRunningTasks = classifiedTasks.some((task) => task.classification === "running");
1612
- const journalEvents = readJournalEvents(projectRoot, batchId);
1613
- const scopedJournalEvents = journalEventsSinceResume(journalEvents, state);
1614
- const orphanRunning = detectOrphanRunning({
1615
- phase: String(state.phase ?? ""),
1616
- hasRunningTasks,
1617
- tasks: classifiedTasks,
1618
- lanes: state.lanes ?? [],
1619
- raw: state,
1620
- journalEvents: scopedJournalEvents,
1621
- });
1622
-
1623
- if (!orphanRunning) {
1624
- return { reconciled: false };
1625
- }
1626
-
1627
- const exitReason = orphanRunning.kind === "engine" ? "engine_orphaned" : "worker_orphaned";
1628
- /** @type {string[]} */
1629
- const taskIdsToFail =
1630
- orphanRunning.kind === "lane" && orphanRunning.taskId
1631
- ? [orphanRunning.taskId]
1632
- : classifiedTasks
1633
- .filter((task) => task.classification === "running")
1634
- .map((task) => task.taskId)
1635
- .filter(Boolean);
1636
-
1637
- if (taskIdsToFail.length === 0) {
1638
- return { reconciled: false };
1639
- }
1640
-
1641
- const now = Date.now();
1642
- let changed = false;
1643
-
1644
- for (const taskId of taskIdsToFail) {
1645
- const task = (state.tasks ?? []).find((entry) => entry?.taskId === taskId);
1646
- if (!task || task.status !== "running") continue;
1647
-
1648
- task.status = "failed";
1649
- task.endedAt = now;
1650
- task.exitReason = exitReason;
1651
- updateSegmentForTask(state, taskId, "failed");
1652
- changed = true;
1653
-
1654
- if (!journalHasTaskEvent(scopedJournalEvents, taskId, "task.failed")) {
1655
- const lane = findLaneForOrphanReconcile(state.lanes, task.laneNumber);
1656
- appendJournalEvent(projectRoot, batchId, "task.failed", {
1657
- taskId,
1658
- laneNumber: task.laneNumber ?? null,
1659
- laneId: lane?.laneId ?? null,
1660
- reason: exitReason,
1661
- reconciled: true,
1662
- });
1663
- }
1664
-
1665
- if (
1666
- orphanRunning.kind === "lane" &&
1667
- !journalHasTaskEvent(scopedJournalEvents, taskId, "lane.died")
1668
- ) {
1669
- const lane = findLaneForOrphanReconcile(state.lanes, task.laneNumber);
1670
- appendJournalEvent(projectRoot, batchId, "lane.died", {
1671
- taskId,
1672
- laneNumber: task.laneNumber ?? null,
1673
- laneId: lane?.laneId ?? null,
1674
- reason: exitReason,
1675
- reconciled: true,
1676
- });
1677
- }
1678
- }
1679
-
1680
- for (const lane of state.lanes ?? []) {
1681
- if (!lane || typeof lane !== "object") continue;
1682
- const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
1683
- if (Number.isFinite(workerPid) && workerPid > 0 && !isProcessAlive(workerPid)) {
1684
- delete lane.workerPid;
1685
- changed = true;
1686
- }
1687
- }
1688
-
1689
- const enginePid = readBatchEnginePid(state);
1690
- if (enginePid != null && !isProcessAlive(enginePid)) {
1691
- clearBatchEnginePid(state);
1692
- changed = true;
1693
- }
1694
-
1695
- if (!changed) {
1696
- return { reconciled: false };
1697
- }
1698
-
1699
- recomputeTaskCounters(state);
1700
- if (String(state.phase ?? "") === "running") {
1701
- state.phase = "failed";
1702
- state.endedAt = state.endedAt ?? now;
1703
- state.lastError =
1704
- state.lastError ?? `Orphan reconcile: ${exitReason} (task ${taskIdsToFail.join(", ")})`;
1705
- }
1706
-
1707
- saveSpineBatchState(projectRoot, state);
1708
-
1709
- return {
1710
- reconciled: true,
1711
- taskId: orphanRunning.taskId ?? taskIdsToFail[0] ?? null,
1712
- kind: orphanRunning.kind,
1713
- exitReason,
1714
- };
1715
- }
24
+ export { loadBatchStateFile, parseBatchState, resolveBatchStatePath } from "./batch-state-io.mjs";
25
+ export {
26
+ alignTaskClassificationWithStatus,
27
+ classifyTasks,
28
+ inspectGitState,
29
+ inspectHumanBaseSync,
30
+ listGitChangedPaths,
31
+ listHumanOnlyPaths,
32
+ resolveTasksRoot,
33
+ syncPersistedClassifications,
34
+ } from "./reconcile-classify.mjs";
35
+ export { deriveDiagnosis } from "./reconcile-diagnosis.mjs";
36
+ export { clearLightReconcileCache } from "./reconcile-light-cache.mjs";
37
+ export { reconcileBatch } from "./reconcile-batch.mjs";
38
+ export {
39
+ reconcileOrphanRunningState,
40
+ runReconciliationCheck,
41
+ } from "./reconcile-orphan.mjs";