pi-spine 1.5.0 → 1.7.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 (57) hide show
  1. package/bin/spine-batch.mjs +3 -2
  2. package/bin/spine-wait.mjs +12 -0
  3. package/bin/spine.mjs +12 -0
  4. package/extensions/spine/slash-commands.ts +170 -1
  5. package/package.json +7 -4
  6. package/skills/spine-orchestrate-waves/SKILL.md +200 -0
  7. package/skills/spine-orchestrate-waves/references/outer-loop.md +165 -0
  8. package/skills/spine-release-operator/SKILL.md +371 -0
  9. package/skills/spine-release-operator/references/issue-intake-checklist.md +107 -0
  10. package/skills/spine-release-operator/references/issue-template.md +51 -0
  11. package/skills/spine-release-operator/references/release-manifest-template.md +76 -0
  12. package/skills/spine-release-operator/references/release-profiles.md +100 -0
  13. package/src/batch/attached-runner.mjs +18 -7
  14. package/src/batch/batch-state-io.mjs +137 -0
  15. package/src/batch/contract-prelanded.mjs +116 -14
  16. package/src/batch/contract-task-start.mjs +12 -7
  17. package/src/batch/contract-verify.mjs +51 -3
  18. package/src/batch/detached-spawn.mjs +78 -0
  19. package/src/batch/detached-start.mjs +25 -71
  20. package/src/batch/diagnosis-alternatives.mjs +8 -0
  21. package/src/batch/diagnosis.mjs +53 -4
  22. package/src/batch/engine.mjs +10 -1
  23. package/src/batch/evidence.mjs +30 -250
  24. package/src/batch/gate-evidence-collect.mjs +172 -0
  25. package/src/batch/gate-evidence-read.mjs +145 -0
  26. package/src/batch/gate.mjs +28 -38
  27. package/src/batch/integrate-worktree.mjs +65 -15
  28. package/src/batch/lane-dirty-check.mjs +108 -1
  29. package/src/batch/lifecycle.mjs +16 -11
  30. package/src/batch/post-merge-limbo.mjs +1 -1
  31. package/src/batch/postmortem.mjs +1 -2
  32. package/src/batch/reconcile.mjs +255 -1
  33. package/src/batch/resume-common.mjs +7 -1
  34. package/src/batch/resume-multi-validate.mjs +25 -101
  35. package/src/batch/resume-validation.mjs +120 -0
  36. package/src/batch/sequence.mjs +11 -2
  37. package/src/batch/state.mjs +18 -1
  38. package/src/batch/supervisor-spawn.mjs +379 -0
  39. package/src/cli/batch-complete.mjs +16 -0
  40. package/src/cli/spine-wait.mjs +114 -0
  41. package/src/cli/sync-base.mjs +354 -0
  42. package/src/cli/wait.mjs +7 -43
  43. package/src/config/defaults.mjs +11 -1
  44. package/src/config/settings-fields.mjs +23 -0
  45. package/src/config/spine-config-load.mjs +6 -0
  46. package/src/config/spine-config-schema.mjs +121 -0
  47. package/src/config/spine-init-constants.mjs +19 -1
  48. package/src/config/spine-preflight-lib.mjs +146 -2
  49. package/src/config/worktree-setup-hook.mjs +221 -0
  50. package/src/doctor/agent-models.mjs +1 -0
  51. package/src/doctor/agents-model-inherit.mjs +318 -0
  52. package/src/doctor/run-doctor-checks.mjs +28 -0
  53. package/src/doctor/supervisor.mjs +66 -0
  54. package/src/doctor/worktree-health.mjs +1 -1
  55. package/templates/agents/supervisor.md +27 -18
  56. package/templates/spine-config.json +20 -1
  57. package/templates/spine-worktree-setup-flutter.sh +44 -0
@@ -8,8 +8,9 @@ import { execFileSync } from "node:child_process";
8
8
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
9
  import { PACKAGE_ROOT } from "../config/spine-init-constants.mjs";
10
10
  import { resolveTasksRootPath } from "../config/env-overrides.mjs";
11
+ import { resolveCurrentGitBranch } from "../config/spine-preflight-lib.mjs";
11
12
  import { buildStalePathDoctorCheck } from "../doctor/stale-path.mjs";
12
- import { loadGateRecord } from "./gate.mjs";
13
+ import { loadGateRecord } from "./gate-evidence-read.mjs";
13
14
  import { deriveMacroPhase, macroPhaseLabel } from "./macro-phase.mjs";
14
15
  import {
15
16
  buildDiagnosisOutput,
@@ -40,6 +41,7 @@ import { isProcessAlive } from "../process/liveness.mjs";
40
41
  import {
41
42
  loadBatchStateFile,
42
43
  parseBatchState,
44
+ readBaseBranchHeadAtStart,
43
45
  } from "./batch-state-io.mjs";
44
46
  import {
45
47
  clearBatchEnginePid,
@@ -294,6 +296,239 @@ export function inspectGitState(ctx) {
294
296
  return result;
295
297
  }
296
298
 
299
+ /**
300
+ * @typedef {object} HumanBaseSyncInspection
301
+ * @property {"human_base_diverged"|"integrate_isolated_ok"} diagnosis
302
+ * @property {string} headline
303
+ * @property {string[]} [overlapPaths]
304
+ * @property {string} [humanHead]
305
+ * @property {string} [baseTip]
306
+ * @property {string|null} [orchBranch]
307
+ * @property {boolean} [preIntegrate]
308
+ */
309
+
310
+ /**
311
+ * @param {string} projectRoot
312
+ * @param {string} refA
313
+ * @param {string} refB
314
+ * @returns {string[]}
315
+ */
316
+ export function listGitChangedPaths(projectRoot, refA, refB) {
317
+ if (!refA || !refB || refA === refB) return [];
318
+ try {
319
+ const output = execFileSync("git", ["diff", "--name-only", `${refA}..${refB}`], {
320
+ cwd: projectRoot,
321
+ encoding: "utf-8",
322
+ stdio: ["ignore", "pipe", "pipe"],
323
+ timeout: 5000,
324
+ });
325
+ return output
326
+ .split(/\r?\n/)
327
+ .map((line) => line.trim())
328
+ .filter(Boolean);
329
+ } catch {
330
+ return [];
331
+ }
332
+ }
333
+
334
+ /**
335
+ * Paths touched by human commits on base since batch snapshot, excluding orch ancestry.
336
+ *
337
+ * @param {string} projectRoot
338
+ * @param {string} snapshot
339
+ * @param {string} humanHead
340
+ * @param {string|null} orchBranch
341
+ * @returns {string[]}
342
+ */
343
+ export function listHumanOnlyPaths(projectRoot, snapshot, humanHead, orchBranch) {
344
+ if (!snapshot || !humanHead || snapshot === humanHead) return [];
345
+ const args = ["log", "--name-only", "--pretty=format:", `${snapshot}..${humanHead}`];
346
+ if (orchBranch && gitRefExists(projectRoot, orchBranch)) {
347
+ args.push("--not", orchBranch);
348
+ }
349
+ try {
350
+ const output = execFileSync("git", args, {
351
+ cwd: projectRoot,
352
+ encoding: "utf-8",
353
+ stdio: ["ignore", "pipe", "pipe"],
354
+ timeout: 5000,
355
+ });
356
+ return [...new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean))];
357
+ } catch {
358
+ return [];
359
+ }
360
+ }
361
+
362
+ /**
363
+ * @param {string} projectRoot
364
+ * @param {string} ref
365
+ * @param {string} filePath
366
+ */
367
+ function pathExistsAtRef(projectRoot, ref, filePath) {
368
+ try {
369
+ execFileSync("git", ["cat-file", "-e", `${ref}:${filePath}`], {
370
+ cwd: projectRoot,
371
+ stdio: ["ignore", "pipe", "pipe"],
372
+ timeout: 5000,
373
+ });
374
+ return true;
375
+ } catch {
376
+ return false;
377
+ }
378
+ }
379
+
380
+ /**
381
+ * @param {string} projectRoot
382
+ * @param {string} baseTip
383
+ * @param {string} snapshot
384
+ * @returns {boolean}
385
+ */
386
+ function humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot) {
387
+ const landPaths = listGitChangedPaths(projectRoot, snapshot, baseTip);
388
+ for (const filePath of landPaths) {
389
+ if (!pathExistsAtRef(projectRoot, baseTip, filePath)) continue;
390
+ if (!fs.existsSync(path.join(projectRoot, filePath))) {
391
+ return true;
392
+ }
393
+ }
394
+ return false;
395
+ }
396
+
397
+ /**
398
+ * Detect human/base divergence or post-isolated-integrate sync need (FR-WT-08 / #91).
399
+ *
400
+ * @param {object} ctx
401
+ * @param {string} ctx.projectRoot
402
+ * @param {string} ctx.baseBranch
403
+ * @param {string} ctx.baseBranchHeadAtStart
404
+ * @param {string|null} ctx.orchBranch
405
+ * @param {ReturnType<typeof inspectGitState>} ctx.git
406
+ * @param {object[]} [ctx.journalEvents]
407
+ * @returns {HumanBaseSyncInspection|null}
408
+ */
409
+ export function inspectHumanBaseSync(ctx) {
410
+ const { projectRoot, baseBranch, baseBranchHeadAtStart, orchBranch, git, journalEvents } = ctx;
411
+ if (!git?.inGitRepo) return null;
412
+
413
+ const snapshot = String(baseBranchHeadAtStart ?? "").trim();
414
+ if (!snapshot) return null;
415
+
416
+ let baseTip = "";
417
+ let humanHead = "";
418
+ try {
419
+ baseTip = execFileSync("git", ["rev-parse", baseBranch], {
420
+ cwd: projectRoot,
421
+ encoding: "utf-8",
422
+ timeout: 5000,
423
+ }).trim();
424
+ humanHead = execFileSync("git", ["rev-parse", "HEAD"], {
425
+ cwd: projectRoot,
426
+ encoding: "utf-8",
427
+ timeout: 5000,
428
+ }).trim();
429
+ } catch {
430
+ return null;
431
+ }
432
+
433
+ const integrateCompleted = Array.isArray(journalEvents)
434
+ ? journalEvents.some((event) => event.type === "integrate.completed")
435
+ : false;
436
+ const landSucceeded =
437
+ git.orchMergedToBase ||
438
+ integrateCompleted ||
439
+ (baseTip !== snapshot && gitIsAncestor(projectRoot, snapshot, baseTip));
440
+
441
+ const resolvedOrch =
442
+ orchBranch && gitRefExists(projectRoot, orchBranch)
443
+ ? orchBranch
444
+ : git.mergedOrchBranch && gitRefExists(projectRoot, git.mergedOrchBranch)
445
+ ? git.mergedOrchBranch
446
+ : null;
447
+
448
+ const branchResult = resolveCurrentGitBranch(projectRoot);
449
+ const onBaseBranch = branchResult.branch === baseBranch;
450
+
451
+ const humanSinceSnapshot =
452
+ onBaseBranch &&
453
+ gitIsAncestor(projectRoot, snapshot, humanHead) &&
454
+ humanHead !== snapshot;
455
+ const humanPaths = humanSinceSnapshot
456
+ ? listHumanOnlyPaths(projectRoot, snapshot, humanHead, resolvedOrch)
457
+ : [];
458
+ const landPaths = landSucceeded ? listGitChangedPaths(projectRoot, snapshot, baseTip) : [];
459
+ const orchPaths =
460
+ resolvedOrch && gitRefExists(projectRoot, resolvedOrch)
461
+ ? listGitChangedPaths(projectRoot, snapshot, resolvedOrch)
462
+ : landPaths;
463
+ const overlapPaths = humanPaths.filter((filePath) => orchPaths.includes(filePath));
464
+
465
+ if (overlapPaths.length > 0) {
466
+ return {
467
+ diagnosis: "human_base_diverged",
468
+ headline: onBaseBranch
469
+ ? `Human commits on ${baseBranch} overlap orch land (${overlapPaths.length} path(s))`
470
+ : `Human commits overlap orch land (${overlapPaths.length} path(s))`,
471
+ overlapPaths,
472
+ humanHead,
473
+ baseTip,
474
+ orchBranch: resolvedOrch,
475
+ preIntegrate: !landSucceeded,
476
+ };
477
+ }
478
+
479
+ if (!landSucceeded) return null;
480
+
481
+ const needsCommitSync =
482
+ humanHead !== baseTip && onBaseBranch && gitIsAncestor(projectRoot, humanHead, baseTip);
483
+ const needsPathSync =
484
+ onBaseBranch && humanHead === baseTip && humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot);
485
+
486
+ if (!needsCommitSync && !needsPathSync) {
487
+ if (!onBaseBranch) {
488
+ const mergeBase = (() => {
489
+ try {
490
+ return execFileSync("git", ["merge-base", humanHead, baseTip], {
491
+ cwd: projectRoot,
492
+ encoding: "utf-8",
493
+ timeout: 5000,
494
+ }).trim();
495
+ } catch {
496
+ return "";
497
+ }
498
+ })();
499
+ if (mergeBase && mergeBase !== baseTip && gitIsAncestor(projectRoot, mergeBase, baseTip)) {
500
+ return {
501
+ diagnosis: "integrate_isolated_ok",
502
+ headline: `${baseBranch} advanced during batch; feature branch needs sync`,
503
+ humanHead,
504
+ baseTip,
505
+ orchBranch: resolvedOrch,
506
+ };
507
+ }
508
+ }
509
+ return null;
510
+ }
511
+
512
+ return {
513
+ diagnosis: "integrate_isolated_ok",
514
+ headline: needsPathSync
515
+ ? `Isolated integrate landed on ${baseBranch}; working tree needs path sync`
516
+ : `Isolated integrate landed on ${baseBranch}; checkout needs sync`,
517
+ humanHead,
518
+ baseTip,
519
+ orchBranch: resolvedOrch,
520
+ };
521
+ }
522
+
523
+ const HUMAN_SYNC_OVERRIDE_DIAGNOSES = new Set([
524
+ "completed",
525
+ "completed_manual",
526
+ "needs_integrate",
527
+ "limbo_stale",
528
+ "running",
529
+ "paused",
530
+ ]);
531
+
297
532
  /**
298
533
  * @param {unknown} rawTasks
299
534
  * @param {string|null} failedTaskId
@@ -888,6 +1123,19 @@ export function reconcileBatch(ctx) {
888
1123
  failedTaskId = stubSucceededTaskId;
889
1124
  exitReason = "stub";
890
1125
  }
1126
+
1127
+ const humanBaseSync = inspectHumanBaseSync({
1128
+ projectRoot,
1129
+ baseBranch: batch.baseBranch,
1130
+ baseBranchHeadAtStart: readBaseBranchHeadAtStart(batch.raw),
1131
+ orchBranch: batch.orchBranch,
1132
+ git,
1133
+ journalEvents,
1134
+ });
1135
+ if (humanBaseSync && HUMAN_SYNC_OVERRIDE_DIAGNOSES.has(diagnosis)) {
1136
+ diagnosis = humanBaseSync.diagnosis;
1137
+ }
1138
+
891
1139
  const doneMissingHint =
892
1140
  diagnosis === "worker_done_missing"
893
1141
  ? inferWorkerDoneMissingFailure({
@@ -1006,8 +1254,14 @@ export function reconcileBatch(ctx) {
1006
1254
  tasksRoot,
1007
1255
  macroPhase,
1008
1256
  ...(doneMissingContext ?? {}),
1257
+ humanBaseSync,
1258
+ overlapPaths: humanBaseSync?.overlapPaths ?? [],
1009
1259
  });
1010
1260
 
1261
+ if (humanBaseSync && (diagnosis === "human_base_diverged" || diagnosis === "integrate_isolated_ok")) {
1262
+ output.headline = humanBaseSync.headline;
1263
+ }
1264
+
1011
1265
  if (diagnosis === "git_unavailable") {
1012
1266
  output.headline = `Batch ${batch.batchId} — git inspection failed: ${git.gitInspectionError}`;
1013
1267
  output.suggestedCommand = "spine doctor";
@@ -55,10 +55,16 @@ export function taskTerminalSuccessInBatch({ events, task, taskFolder }) {
55
55
  */
56
56
  export function taskAlreadyComplete({ taskFolder, events, task }) {
57
57
  const status = String(task?.status ?? "");
58
- if (status === "pending" || status === "failed" || status === "running") {
58
+ if (status === "failed") {
59
59
  return false;
60
60
  }
61
61
  const doneOnDisk = fs.existsSync(path.join(taskFolder, ".DONE"));
62
+ if (doneOnDisk && (status === "running" || status === "pending")) {
63
+ return true;
64
+ }
65
+ if (status === "pending" || status === "running") {
66
+ return false;
67
+ }
62
68
  return (
63
69
  doneOnDisk ||
64
70
  task.doneFileFound ||
@@ -4,18 +4,18 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import { isProcessAlive } from "../process/liveness.mjs";
7
- import {
8
- findFirstWaveNeedingMerge,
9
- hasPendingWaveMerge,
10
- succeededWaveMergeIndices,
11
- waveTasksAllTerminal,
12
- } from "./merge/wave-merge-state.mjs";
7
+ import { hasPendingWaveMerge } from "./merge/wave-merge-state.mjs";
13
8
  import { loadGateRecord } from "./gate.mjs";
14
9
  import { readJournalEvents } from "./journal.mjs";
15
10
  import { detectOrphanRunning, journalEventsSinceResume } from "./orphan-detect.mjs";
16
- import { isPostMergeLimbo } from "./post-merge-limbo.mjs";
17
11
  import { inspectGitState } from "./reconcile.mjs";
18
12
  import { detectSegmentDrift } from "./retry.mjs";
13
+ import {
14
+ classifyTasksForOrphanDetect,
15
+ computePendingTasks,
16
+ detectPostMergeLimboFromResumeSignals,
17
+ findResumableWave,
18
+ } from "./resume-validation.mjs";
19
19
  import { loadSpineBatchState, readBatchEnginePid, validateBatchState } from "./state.mjs";
20
20
  import {
21
21
  assertLaneWorktreeGitHealthy,
@@ -23,6 +23,13 @@ import {
23
23
  repairLaneWorktreeGitMetadata,
24
24
  } from "./worktree.mjs";
25
25
 
26
+ export {
27
+ classifyTasksForOrphanDetect,
28
+ computePendingTasks,
29
+ findResumableWave,
30
+ isTaskResumable,
31
+ } from "./resume-validation.mjs";
32
+
26
33
  /**
27
34
  * Resume-time limbo detection — state file, git signals, and journal merge events (SP-358, GitHub #41).
28
35
  *
@@ -31,109 +38,26 @@ import {
31
38
  * @param {object} params.state
32
39
  */
33
40
  export function detectPostMergeLimboForResume({ projectRoot, state }) {
34
- if (!state || typeof state !== "object") return false;
35
- if (String(state.phase ?? "") === "completed") return false;
36
-
37
- if (isPostMergeLimbo(state)) return true;
38
-
39
- const batchId = String(state.batchId ?? "");
41
+ const batchId = String(state?.batchId ?? "");
40
42
  const git = inspectGitState({
41
43
  projectRoot,
42
44
  batchId,
43
- baseBranch: state.baseBranch ?? "main",
44
- orchBranch: state.orchBranch ?? null,
45
+ baseBranch: state?.baseBranch ?? "main",
46
+ orchBranch: state?.orchBranch ?? null,
45
47
  });
46
- if (isPostMergeLimbo(state, git)) return true;
47
-
48
- const phase = String(state.phase ?? "");
49
- if (phase !== "running" && phase !== "merging") return false;
50
- if (state.endedAt != null) return false;
51
- if (!git.orchBranchExists || git.orchMergedToBase) return false;
52
- if (!batchId || loadGateRecord(projectRoot, batchId)) return false;
53
-
54
- const tasks = state.tasks ?? [];
55
- if (tasks.length === 0) return false;
56
- const allSucceeded = tasks.every((task) => String(task?.status ?? "") === "succeeded");
57
- if (!allSucceeded) return false;
58
-
59
- const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
60
- if (!Number.isFinite(totalWaves) || totalWaves <= 0) return false;
61
-
62
- const events = readJournalEvents(projectRoot, batchId);
63
- const mergeCompleted = events.filter((event) => event.type === "batch.merge_completed");
64
- if (mergeCompleted.length < 1) return false;
65
-
66
- const lastWaveIndex = totalWaves - 1;
67
- return mergeCompleted.some((event) => Number(event.payload?.waveIndex ?? -1) === lastWaveIndex);
68
- }
69
-
70
- /**
71
- * @param {object} state
72
- * @param {object} task
73
- */
74
- export function isTaskResumable(state, task) {
75
- const status = String(task.status ?? "").toLowerCase();
76
- if (status === "pending" || status === "running") return true;
77
-
78
- return (state.segments ?? []).some((segment) => {
79
- if (!segment || segment.taskId !== task.taskId) return false;
80
- const segmentStatus = String(segment.status ?? "").toLowerCase();
81
- return segmentStatus === "pending" || segmentStatus === "running";
48
+ const journalEvents = batchId ? readJournalEvents(projectRoot, batchId) : [];
49
+ const gateRecordExists = batchId ? loadGateRecord(projectRoot, batchId) != null : false;
50
+
51
+ return detectPostMergeLimboFromResumeSignals({
52
+ state,
53
+ git,
54
+ journalEvents,
55
+ gateRecordExists,
82
56
  });
83
57
  }
84
58
 
85
- /**
86
- * @param {object} state
87
- */
88
- export function computePendingTasks(state) {
89
- return (state.tasks ?? []).filter((task) => task && isTaskResumable(state, task));
90
- }
91
-
92
59
  export { hasPendingWaveMerge } from "./merge/wave-merge-state.mjs";
93
60
 
94
- /**
95
- * @param {object} state
96
- * @param {object[]} pendingTasks
97
- */
98
- export function findResumableWave(state, pendingTasks) {
99
- const pendingIds = new Set(pendingTasks.map((task) => task.taskId));
100
- const wavePlan = state.wavePlan ?? [];
101
- const succeededMerges = succeededWaveMergeIndices(state);
102
-
103
- for (let waveIndex = 0; waveIndex < wavePlan.length; waveIndex++) {
104
- if (succeededMerges.has(waveIndex) && waveTasksAllTerminal(state, waveIndex)) {
105
- continue;
106
- }
107
- const waveTaskIds = wavePlan[waveIndex] ?? [];
108
- if (waveTaskIds.some((taskId) => pendingIds.has(taskId))) {
109
- return waveIndex;
110
- }
111
- }
112
-
113
- const pendingMergeWave = findFirstWaveNeedingMerge(state);
114
- if (pendingMergeWave != null) {
115
- return pendingMergeWave;
116
- }
117
-
118
- return Number(state.currentWaveIndex ?? 0);
119
- }
120
-
121
- /**
122
- * Classify tasks for orphan detection during resume validation (status-only).
123
- *
124
- * @param {object[]} tasks
125
- */
126
- function classifyTasksForOrphanDetect(tasks) {
127
- return (tasks ?? []).map((task) => {
128
- const status = String(task?.status ?? "").toLowerCase();
129
- return {
130
- taskId: task.taskId,
131
- laneNumber: task.laneNumber,
132
- classification: status === "running" ? "running" : status,
133
- };
134
- });
135
- }
136
-
137
61
  /**
138
62
  * Assess whether a running-phase batch may resume after a dead detached engine (SP-296).
139
63
  *
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Pure resume validation helpers — leaf module (SP-468 / #83-B).
3
+ * No reconcile import; I/O wrappers live in resume-multi-validate.mjs.
4
+ */
5
+
6
+ import { isPostMergeLimbo } from "./limbo-detect.mjs";
7
+ import {
8
+ findFirstWaveNeedingMerge,
9
+ succeededWaveMergeIndices,
10
+ waveTasksAllTerminal,
11
+ } from "./merge/wave-merge-state.mjs";
12
+
13
+ /**
14
+ * Resume-time post-merge limbo from state, git, journal, and gate signals (pure).
15
+ *
16
+ * @param {object} params
17
+ * @param {object|null|undefined} params.state
18
+ * @param {object} [params.git]
19
+ * @param {object[]} [params.journalEvents]
20
+ * @param {boolean} [params.gateRecordExists]
21
+ */
22
+ export function detectPostMergeLimboFromResumeSignals({
23
+ state,
24
+ git = {},
25
+ journalEvents = [],
26
+ gateRecordExists = false,
27
+ }) {
28
+ if (!state || typeof state !== "object") return false;
29
+ if (String(state.phase ?? "") === "completed") return false;
30
+
31
+ if (isPostMergeLimbo(state)) return true;
32
+ if (isPostMergeLimbo(state, git)) return true;
33
+
34
+ const phase = String(state.phase ?? "");
35
+ if (phase !== "running" && phase !== "merging") return false;
36
+ if (state.endedAt != null) return false;
37
+ if (!git.orchBranchExists || git.orchMergedToBase) return false;
38
+
39
+ const batchId = String(state.batchId ?? "");
40
+ if (!batchId || gateRecordExists) return false;
41
+
42
+ const tasks = state.tasks ?? [];
43
+ if (tasks.length === 0) return false;
44
+ const allSucceeded = tasks.every((task) => String(task?.status ?? "") === "succeeded");
45
+ if (!allSucceeded) return false;
46
+
47
+ const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
48
+ if (!Number.isFinite(totalWaves) || totalWaves <= 0) return false;
49
+
50
+ const mergeCompleted = (journalEvents ?? []).filter((event) => event.type === "batch.merge_completed");
51
+ if (mergeCompleted.length < 1) return false;
52
+
53
+ const lastWaveIndex = totalWaves - 1;
54
+ return mergeCompleted.some((event) => Number(event.payload?.waveIndex ?? -1) === lastWaveIndex);
55
+ }
56
+
57
+ /**
58
+ * @param {object} state
59
+ * @param {object} task
60
+ */
61
+ export function isTaskResumable(state, task) {
62
+ const status = String(task.status ?? "").toLowerCase();
63
+ if (status === "pending" || status === "running") return true;
64
+
65
+ return (state.segments ?? []).some((segment) => {
66
+ if (!segment || segment.taskId !== task.taskId) return false;
67
+ const segmentStatus = String(segment.status ?? "").toLowerCase();
68
+ return segmentStatus === "pending" || segmentStatus === "running";
69
+ });
70
+ }
71
+
72
+ /**
73
+ * @param {object} state
74
+ */
75
+ export function computePendingTasks(state) {
76
+ return (state.tasks ?? []).filter((task) => task && isTaskResumable(state, task));
77
+ }
78
+
79
+ /**
80
+ * @param {object} state
81
+ * @param {object[]} pendingTasks
82
+ */
83
+ export function findResumableWave(state, pendingTasks) {
84
+ const pendingIds = new Set(pendingTasks.map((task) => task.taskId));
85
+ const wavePlan = state.wavePlan ?? [];
86
+ const succeededMerges = succeededWaveMergeIndices(state);
87
+
88
+ for (let waveIndex = 0; waveIndex < wavePlan.length; waveIndex++) {
89
+ if (succeededMerges.has(waveIndex) && waveTasksAllTerminal(state, waveIndex)) {
90
+ continue;
91
+ }
92
+ const waveTaskIds = wavePlan[waveIndex] ?? [];
93
+ if (waveTaskIds.some((taskId) => pendingIds.has(taskId))) {
94
+ return waveIndex;
95
+ }
96
+ }
97
+
98
+ const pendingMergeWave = findFirstWaveNeedingMerge(state);
99
+ if (pendingMergeWave != null) {
100
+ return pendingMergeWave;
101
+ }
102
+
103
+ return Number(state.currentWaveIndex ?? 0);
104
+ }
105
+
106
+ /**
107
+ * Classify tasks for orphan detection during resume validation (status-only).
108
+ *
109
+ * @param {object[]} tasks
110
+ */
111
+ export function classifyTasksForOrphanDetect(tasks) {
112
+ return (tasks ?? []).map((task) => {
113
+ const status = String(task?.status ?? "").toLowerCase();
114
+ return {
115
+ taskId: task.taskId,
116
+ laneNumber: task.laneNumber,
117
+ classification: status === "running" ? "running" : status,
118
+ };
119
+ });
120
+ }
@@ -4,6 +4,10 @@
4
4
  */
5
5
 
6
6
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
7
+ import {
8
+ DEFAULT_SEQUENCE_POLL_MS,
9
+ resolveSequencePollMs,
10
+ } from "../config/spine-config-schema.mjs";
7
11
  import {
8
12
  formatPreflightHuman,
9
13
  runBatchPreflight,
@@ -75,7 +79,7 @@ export function isSequenceBatchWaiting(diagnosis) {
75
79
 
76
80
  export async function waitForSequenceBatchTerminal({
77
81
  projectRoot,
78
- pollIntervalMs = 250,
82
+ pollIntervalMs = DEFAULT_SEQUENCE_POLL_MS,
79
83
  timeoutMs = 120_000,
80
84
  enginePid = null,
81
85
  }) {
@@ -316,12 +320,17 @@ export async function runSequence(ctx) {
316
320
  stopOnFailure = true,
317
321
  dryRun = false,
318
322
  skipPreflight = false,
319
- pollIntervalMs = 250,
323
+ pollIntervalMs: pollIntervalMsOverride,
320
324
  timeoutMs = 120_000,
321
325
  spineBin = null,
322
326
  startBatchFn = startBatch,
323
327
  } = ctx;
324
328
 
329
+ const configResult = loadSpineConfig(projectRoot);
330
+ const pollIntervalMs =
331
+ pollIntervalMsOverride ??
332
+ resolveSequencePollMs({ config: configResult.config ?? {} });
333
+
325
334
  let sequenceState = null;
326
335
  let effectiveFromWave = fromWave;
327
336
  /** @type {Array<{ waveIndex: number, batchId: string|null, diagnosis: string|null }>} */
@@ -6,7 +6,10 @@ import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
8
8
  import { appendJournalEvent } from "./journal.mjs";
9
- import { loadBatchStateFile } from "./batch-state-io.mjs";
9
+ import {
10
+ clearStaleTerminalBatchStateForStart,
11
+ loadBatchStateFile,
12
+ } from "./batch-state-io.mjs";
10
13
  import { isProcessAlive } from "../process/liveness.mjs";
11
14
 
12
15
  export const SPINE_BATCH_STATE_REL = path.join(".spine", "batch-state.json");
@@ -85,7 +88,19 @@ export function evaluateBatchStateWriteGuard(projectRoot, state) {
85
88
  if (fs.existsSync(filePath)) {
86
89
  try {
87
90
  const onDisk = JSON.parse(fs.readFileSync(filePath, "utf-8"));
91
+ const onDiskBatchId = String(onDisk.batchId ?? "");
92
+ const incomingBatchId = String(state.batchId ?? "");
93
+ const onDiskPhase = String(onDisk.phase ?? "");
88
94
  const ownerPid = readBatchEnginePid(onDisk);
95
+ if (
96
+ incomingBatchId &&
97
+ onDiskBatchId &&
98
+ incomingBatchId !== onDiskBatchId &&
99
+ TERMINAL_BATCH_PHASES.has(onDiskPhase) &&
100
+ (!ownerPid || !isProcessAlive(ownerPid))
101
+ ) {
102
+ return { allowed: true };
103
+ }
89
104
  if (ownerPid && ownerPid !== process.pid && isProcessAlive(ownerPid)) {
90
105
  return { allowed: false, reason: "stale_engine_pid" };
91
106
  }
@@ -251,6 +266,8 @@ export function failBatchFromEngineError({
251
266
  * @param {string} projectRoot
252
267
  */
253
268
  export function assertNoActiveBatch(projectRoot) {
269
+ clearStaleTerminalBatchStateForStart(projectRoot);
270
+
254
271
  const spine = loadSpineBatchState(projectRoot);
255
272
  if (spine.path && spine.raw) {
256
273
  const phase = String(spine.raw.phase ?? "");