pi-spine 1.0.2 → 1.2.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 (129) hide show
  1. package/README.md +61 -489
  2. package/bin/get-version.mjs +1 -13
  3. package/bin/spine-batch.mjs +162 -51
  4. package/bin/spine-cli/batch.mjs +3 -3
  5. package/bin/spine-cli/lane-logs.mjs +24 -0
  6. package/bin/spine-cli/scenarios.mjs +298 -0
  7. package/bin/spine-cli/wait.mjs +30 -0
  8. package/bin/spine-cli/watch.mjs +27 -0
  9. package/bin/spine-config.mjs +1 -212
  10. package/bin/spine-doctor.mjs +2 -418
  11. package/bin/spine-init.mjs +1 -398
  12. package/bin/spine-issue.mjs +196 -0
  13. package/bin/spine-journal.mjs +1 -0
  14. package/bin/spine-preflight.mjs +1 -700
  15. package/bin/spine-review-step.mjs +6 -4
  16. package/bin/spine-run.mjs +30 -0
  17. package/bin/spine-status.mjs +19 -1
  18. package/bin/spine-tasks.mjs +112 -13
  19. package/bin/spine-worker-runner.mjs +24 -14
  20. package/bin/spine.mjs +52 -2
  21. package/extensions/spine/worker-tools.ts +14 -12
  22. package/package.json +5 -2
  23. package/skills/create-spine-tasks/SKILL.md +135 -6
  24. package/skills/create-spine-tasks/references/clarify-template.md +73 -0
  25. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  26. package/skills/create-spine-tasks/references/prompt-template.md +2 -0
  27. package/skills/create-spine-tasks/references/requirements-checklist-template.md +94 -0
  28. package/src/batch/abort.mjs +3 -12
  29. package/src/batch/agent-session-worker.mjs +45 -5
  30. package/src/batch/attached-engine-handoff.mjs +188 -0
  31. package/src/batch/attached-runner.mjs +312 -0
  32. package/src/batch/contract-prelanded.mjs +180 -0
  33. package/src/batch/contract-verify.mjs +140 -2
  34. package/src/batch/detached-start.mjs +105 -7
  35. package/src/batch/diagnosis-alternatives.mjs +46 -0
  36. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  37. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  38. package/src/batch/diagnosis-stub.mjs +109 -0
  39. package/src/batch/diagnosis-task-done.mjs +110 -0
  40. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  41. package/src/batch/diagnosis.mjs +174 -62
  42. package/src/batch/engine-lanes/merge.mjs +168 -77
  43. package/src/batch/engine-lanes/queue.mjs +4 -1
  44. package/src/batch/engine-lanes/review.mjs +32 -74
  45. package/src/batch/engine-lanes/watch.mjs +29 -0
  46. package/src/batch/engine-lanes.mjs +1 -0
  47. package/src/batch/engine-scope.mjs +42 -5
  48. package/src/batch/engine.mjs +115 -68
  49. package/src/batch/evidence.mjs +81 -17
  50. package/src/batch/gate.mjs +46 -17
  51. package/src/batch/git-helpers.mjs +96 -0
  52. package/src/batch/heartbeat.mjs +73 -7
  53. package/src/batch/integrate.mjs +3 -5
  54. package/src/batch/journal.mjs +25 -0
  55. package/src/batch/lane-commit.mjs +90 -5
  56. package/src/batch/lifecycle.mjs +131 -4
  57. package/src/batch/macro-phase.mjs +226 -0
  58. package/src/batch/merge/adoption-doc-merge.mjs +243 -0
  59. package/src/batch/merge/wave-merge-state.mjs +108 -0
  60. package/src/batch/metrics.mjs +74 -5
  61. package/src/batch/orphan-detect.mjs +74 -0
  62. package/src/batch/pause.mjs +223 -0
  63. package/src/batch/post-merge-limbo.mjs +345 -17
  64. package/src/batch/reconcile.mjs +473 -50
  65. package/src/batch/resume-common.mjs +6 -2
  66. package/src/batch/resume-engine.mjs +58 -1
  67. package/src/batch/resume-lane-reviews.mjs +16 -0
  68. package/src/batch/resume-multi-lanes.mjs +56 -1
  69. package/src/batch/resume-multi-validate.mjs +148 -8
  70. package/src/batch/resume-multi.mjs +45 -44
  71. package/src/batch/resume.mjs +64 -47
  72. package/src/batch/retry.mjs +56 -5
  73. package/src/batch/review-shared.mjs +196 -0
  74. package/src/batch/review-spawn.mjs +326 -0
  75. package/src/batch/review.mjs +178 -212
  76. package/src/batch/rules-manifest-drift.mjs +157 -0
  77. package/src/batch/salvage.mjs +2 -1
  78. package/src/batch/sequence.mjs +454 -0
  79. package/src/batch/state.mjs +18 -3
  80. package/src/batch/status-json.mjs +67 -0
  81. package/src/batch/task-stall-budget.mjs +94 -10
  82. package/src/batch/worker-host.mjs +185 -37
  83. package/src/batch/worker-output.mjs +196 -3
  84. package/src/batch/worktree.mjs +10 -0
  85. package/src/cli/handoff.mjs +1 -1
  86. package/src/cli/issue-draft.mjs +180 -0
  87. package/src/cli/journal-follow.mjs +239 -0
  88. package/src/cli/lane-logs.mjs +291 -0
  89. package/src/cli/rules.mjs +1 -1
  90. package/src/cli/sequence.mjs +108 -0
  91. package/src/cli/settings-set.mjs +3 -22
  92. package/src/cli/settings-slash.mjs +27 -5
  93. package/src/cli/wait.mjs +187 -0
  94. package/src/cli/watch.mjs +160 -0
  95. package/src/config/agent-model-resolve.mjs +48 -0
  96. package/src/config/cursor-rules/discover.mjs +3 -21
  97. package/src/config/defaults.mjs +7 -1
  98. package/src/config/settings-fields.mjs +48 -0
  99. package/src/config/spine-config-load.mjs +221 -0
  100. package/src/config/spine-init-constants.mjs +424 -0
  101. package/src/config/spine-preflight-lib.mjs +1180 -0
  102. package/src/dashboard/lane-throughput.mjs +351 -0
  103. package/src/dashboard/public/dashboard.css +25 -1
  104. package/src/dashboard/public/dashboard.js +224 -40
  105. package/src/dashboard/public/index.html +15 -9
  106. package/src/dashboard/server.mjs +4 -0
  107. package/src/dashboard/snapshot.mjs +387 -6
  108. package/src/dashboard/view.mjs +170 -15
  109. package/src/doctor/agent-model-inherit.mjs +61 -6
  110. package/src/doctor/run-doctor-checks.mjs +483 -0
  111. package/src/doctor/sequence-safety.mjs +57 -0
  112. package/src/doctor/stale-path.mjs +22 -0
  113. package/src/doctor/stale-worktrees.mjs +102 -0
  114. package/src/fixtures/scenario-registry.mjs +194 -0
  115. package/src/fs/atomic-write.mjs +49 -0
  116. package/src/migrate/taskplane-config.mjs +1 -1
  117. package/src/planner/file-scope.mjs +246 -0
  118. package/src/planner/format-plan.mjs +9 -7
  119. package/src/planner/index.mjs +6 -2
  120. package/src/planner/pending.mjs +92 -1
  121. package/src/planner/wave-scope.mjs +136 -0
  122. package/src/planner/waves.mjs +133 -0
  123. package/src/tasks/analyze/index.mjs +453 -0
  124. package/src/tasks/packet/index.mjs +1 -0
  125. package/src/tasks/packet/parse-prompt.mjs +42 -1
  126. package/src/tasks/packet/validate-prompt.mjs +124 -0
  127. package/src/util/command-exists.mjs +19 -0
  128. package/templates/docs/constitution.md +61 -0
  129. package/templates/spine-config.json +9 -2
@@ -8,6 +8,12 @@ import { execFileSync, spawnSync } from "node:child_process";
8
8
  import micromatch from "micromatch";
9
9
  import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
10
10
  import { resolveContractMode } from "../tasks/packet/validate-contract.mjs";
11
+ import {
12
+ isPrelandedFileScopeSatisfied,
13
+ isStubPrelandedFileScopeSatisfied,
14
+ } from "./contract-prelanded.mjs";
15
+
16
+ export { resolvePromptRelPath, isFileScopePatternPrelanded, hasSpineTaskDeliveryChanges } from "./contract-prelanded.mjs";
11
17
 
12
18
  /**
13
19
  * @param {string} taskId
@@ -68,6 +74,122 @@ export function shouldRunContractVerifyForWorker(promptMarkdown, parsedContract,
68
74
  return isExitVerificationTask(promptMarkdown);
69
75
  }
70
76
 
77
+ /**
78
+ * @returns {boolean}
79
+ */
80
+ export function isStubWorkerMode() {
81
+ return process.env.SPINE_WORKER_STUB === "1" || process.env.SPINE_WORKER_STUB === "true";
82
+ }
83
+
84
+ /**
85
+ * Legacy stub workers write "Task: stub" in `.DONE` body.
86
+ *
87
+ * @param {string} doneContent
88
+ */
89
+ export function isLegacyStubDoneMarker(doneContent) {
90
+ return /Task:\s*stub/i.test(String(doneContent ?? ""));
91
+ }
92
+
93
+ /**
94
+ * @param {string} donePath
95
+ */
96
+ export function isLegacyStubDoneFile(donePath) {
97
+ if (!fs.existsSync(donePath)) {
98
+ return false;
99
+ }
100
+ return isLegacyStubDoneMarker(fs.readFileSync(donePath, "utf-8"));
101
+ }
102
+
103
+ /**
104
+ * Lane commit enforces `fileScopeMustChange` when stub mode is active or `.DONE` is legacy stub.
105
+ *
106
+ * @param {string} donePath
107
+ */
108
+ export function shouldEnforceStubContractAtLaneCommit(donePath) {
109
+ if (isStubWorkerMode()) {
110
+ return true;
111
+ }
112
+ return isLegacyStubDoneFile(donePath);
113
+ }
114
+
115
+ /**
116
+ * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
117
+ */
118
+ export function hasReleaseCriticalContract(parsedContract) {
119
+ return (parsedContract?.fileScopeMustChange?.length ?? 0) > 0;
120
+ }
121
+
122
+ /**
123
+ * @param {string} worktreePath
124
+ */
125
+ function listUntrackedFiles(worktreePath) {
126
+ try {
127
+ const output = execFileSync("git", ["ls-files", "-o", "--exclude-standard"], {
128
+ cwd: worktreePath,
129
+ encoding: "utf-8",
130
+ stdio: ["ignore", "pipe", "pipe"],
131
+ timeout: 30_000,
132
+ });
133
+ return output
134
+ .split(/\r?\n/)
135
+ .map((line) => line.trim())
136
+ .filter(Boolean);
137
+ } catch {
138
+ return [];
139
+ }
140
+ }
141
+
142
+ /**
143
+ * @param {string} worktreePath
144
+ * @param {string} baseBranch
145
+ * @param {string[]} [pendingPaths]
146
+ */
147
+ export function listEffectiveChangedFiles(worktreePath, baseBranch = "main", pendingPaths = []) {
148
+ return [
149
+ ...new Set([
150
+ ...listChangedFiles(worktreePath, baseBranch),
151
+ ...pendingPaths,
152
+ ...listUntrackedFiles(worktreePath),
153
+ ]),
154
+ ];
155
+ }
156
+
157
+ /**
158
+ * @param {string} worktreePath
159
+ * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
160
+ * @param {string} [baseBranch]
161
+ * @param {string[]} [pendingPaths] Uncommitted paths about to be lane-committed
162
+ * @param {object} [config]
163
+ * @returns {{ ok: boolean, failures: string[] }}
164
+ */
165
+ export function verifyStubFileScopeMustChange(
166
+ worktreePath,
167
+ parsedContract,
168
+ baseBranch = "main",
169
+ pendingPaths = [],
170
+ config = {},
171
+ ) {
172
+ const patterns = parsedContract?.fileScopeMustChange ?? [];
173
+ if (patterns.length === 0) {
174
+ return { ok: true, failures: [] };
175
+ }
176
+
177
+ const changedFiles = listEffectiveChangedFiles(worktreePath, baseBranch, pendingPaths);
178
+ /** @type {string[]} */
179
+ const failures = [];
180
+ for (const pattern of patterns) {
181
+ const matched = changedFiles.some((file) => matchesContractPattern(file, pattern));
182
+ if (matched) {
183
+ continue;
184
+ }
185
+ if (isStubPrelandedFileScopeSatisfied(worktreePath, pattern, changedFiles, config, baseBranch)) {
186
+ continue;
187
+ }
188
+ failures.push(`Contract fileScopeMustChange: no matching changes for ${pattern}`);
189
+ }
190
+ return { ok: failures.length === 0, failures };
191
+ }
192
+
71
193
  /**
72
194
  * @param {string} worktreePath
73
195
  * @param {string} [baseBranch]
@@ -229,9 +351,11 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
229
351
  const changedFiles = listChangedFiles(worktreePath, baseBranch);
230
352
 
231
353
  let testCommandOutput = "";
354
+ let testCommandOk = true;
232
355
  if (parsedContract.testCommand) {
233
356
  const result = runContractTestCommand(worktreePath, parsedContract.testCommand);
234
357
  testCommandOutput = result.output;
358
+ testCommandOk = result.ok;
235
359
  checks.push({
236
360
  field: "testCommand",
237
361
  ok: result.ok,
@@ -243,12 +367,26 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
243
367
 
244
368
  for (const pattern of parsedContract.fileScopeMustChange ?? []) {
245
369
  const matched = changedFiles.some((file) => matchesContractPattern(file, pattern));
370
+ const prelanded = !matched &&
371
+ isPrelandedFileScopeSatisfied(
372
+ worktreePath,
373
+ pattern,
374
+ changedFiles,
375
+ parsedContract,
376
+ config,
377
+ baseBranch,
378
+ { testCommandOk },
379
+ (worktree, artifactPath) => findArtifactMatch(worktree, artifactPath).ok,
380
+ );
381
+ const ok = matched || prelanded;
246
382
  checks.push({
247
383
  field: "fileScopeMustChange",
248
- ok: matched,
384
+ ok,
249
385
  message: matched
250
386
  ? `fileScopeMustChange matched: ${pattern}`
251
- : `Contract fileScopeMustChange: no matching changes for ${pattern}`,
387
+ : prelanded
388
+ ? `fileScopeMustChange pre-landed on ${baseBranch}: ${pattern}`
389
+ : `Contract fileScopeMustChange: no matching changes for ${pattern}`,
252
390
  });
253
391
  }
254
392
 
@@ -5,13 +5,15 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { spawn } from "node:child_process";
8
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
9
- import { runBatchPreflight } from "../../bin/spine-preflight.mjs";
8
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
+ import { runBatchPreflight } from "../config/spine-preflight-lib.mjs";
10
10
  import { loadGateRecord } from "./gate.mjs";
11
11
  import { reconcileBatch } from "./reconcile.mjs";
12
12
  import { validateResumeBatch } from "./resume.mjs";
13
+ import { assessRunningPhaseResumeEligibility } from "./resume-multi-validate.mjs";
13
14
  import { readLastTaskFailedEvent } from "./journal.mjs";
14
- import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
15
+ import { prepareOrphanResumeHandoff } from "./resume-engine.mjs";
16
+ import { finalizeResumePostMergeLimbo } from "./attached-runner.mjs";
15
17
  import {
16
18
  ACTIVE_PHASES,
17
19
  loadSpineBatchState,
@@ -27,6 +29,7 @@ const RESUME_WAIT_TERMINAL_DIAGNOSES = new Set([
27
29
  "engine_orphaned",
28
30
  "worker_orphaned",
29
31
  "state_drift",
32
+ "needs_integrate",
30
33
  ]);
31
34
 
32
35
  /**
@@ -56,6 +59,20 @@ const TERMINAL_TASK_STATUSES = new Set(["succeeded", "failed", "skipped", "abort
56
59
 
57
60
  const FAILURE_LOG_TAIL_LINES = 20;
58
61
 
62
+ /** Default wait when --wait-terminal blocks on orphan/drift resume (real workers exceed 30s). */
63
+ const DETACHED_WAIT_TERMINAL_TIMEOUT_MS = 2 * 60 * 60 * 1000;
64
+
65
+ /**
66
+ * @param {boolean} waitTerminal
67
+ * @param {number} [explicitTimeoutMs]
68
+ */
69
+ export function resolveDetachedWaitTimeoutMs(waitTerminal, explicitTimeoutMs) {
70
+ if (Number.isFinite(explicitTimeoutMs) && explicitTimeoutMs > 0) {
71
+ return explicitTimeoutMs;
72
+ }
73
+ return waitTerminal ? DETACHED_WAIT_TERMINAL_TIMEOUT_MS : 30_000;
74
+ }
75
+
59
76
  /**
60
77
  * @param {string} filePath
61
78
  * @param {number} [lineCount]
@@ -271,14 +288,23 @@ export function detachedEngineLogPath(projectRoot) {
271
288
  * @param {object} params
272
289
  * @param {string} params.scope
273
290
  * @param {boolean} [params.skipPreflight]
291
+ * @param {boolean} [params.forceSuperseded]
292
+ * @param {number|null} [params.waveFilter]
274
293
  */
275
- export function buildAttachedBatchStartArgv({ scope, skipPreflight = false }) {
294
+ export function buildAttachedBatchStartArgv({
295
+ scope,
296
+ skipPreflight = false,
297
+ forceSuperseded = false,
298
+ waveFilter = null,
299
+ }) {
276
300
  const tokens = String(scope ?? "")
277
301
  .trim()
278
302
  .split(/\s+/)
279
303
  .filter(Boolean);
280
304
  const args = ["batch", "start", ...tokens, "--attached"];
281
305
  if (skipPreflight) args.push("--skip-preflight");
306
+ if (forceSuperseded) args.push("--force-superseded");
307
+ if (waveFilter != null) args.push("--wave", String(waveFilter));
282
308
  return args;
283
309
  }
284
310
 
@@ -335,6 +361,7 @@ function persistDetachedEnginePid(projectRoot, enginePid) {
335
361
  /**
336
362
  * Kill a stale detached engine and persist cleared PID before spawning resume engine (SP-254).
337
363
  * Resume child records its own PID after terminateStaleDetachedEngine runs in-process.
364
+ * Running-phase orphan resume (SP-296) clears a dead engine PID without requiring pause first.
338
365
  *
339
366
  * @param {string} projectRoot
340
367
  */
@@ -347,15 +374,27 @@ export function prepareDetachedResumeEngineHandoff(projectRoot) {
347
374
  const state = loaded.raw;
348
375
  const batchId = String(state.batchId ?? "");
349
376
  const fromPhase = String(state.phase ?? "");
350
- const terminateResult = terminateStaleDetachedEngine({
377
+ const orphanEligibility =
378
+ fromPhase === "running"
379
+ ? assessRunningPhaseResumeEligibility({ projectRoot, state })
380
+ : { engineConfirmedDead: false, allowOrphanResume: false };
381
+ const handoff = prepareOrphanResumeHandoff({
351
382
  projectRoot,
352
383
  state,
353
384
  batchId,
354
385
  fromPhase,
386
+ orphanResume: orphanEligibility.allowOrphanResume,
387
+ engineConfirmedDead: orphanEligibility.engineConfirmedDead,
355
388
  });
356
389
  saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
357
390
 
358
- return { ok: true, batchId, fromPhase, terminateResult };
391
+ return {
392
+ ok: true,
393
+ batchId,
394
+ fromPhase,
395
+ terminateResult: handoff.terminateResult,
396
+ orphanResume: orphanEligibility.allowOrphanResume,
397
+ };
359
398
  }
360
399
 
361
400
  /**
@@ -598,6 +637,8 @@ export function formatDetachedBatchStartOutput(result, json = false) {
598
637
  * @param {string} params.spineBin
599
638
  * @param {string} params.scope
600
639
  * @param {boolean} [params.skipPreflight]
640
+ * @param {boolean} [params.forceSuperseded]
641
+ * @param {number|null} [params.waveFilter]
601
642
  * @param {boolean} [params.waitTerminal]
602
643
  * @param {boolean} [params.json]
603
644
  */
@@ -606,6 +647,8 @@ export async function startBatchDetached({
606
647
  spineBin,
607
648
  scope,
608
649
  skipPreflight = false,
650
+ forceSuperseded = false,
651
+ waveFilter = null,
609
652
  waitTerminal = false,
610
653
  json = false,
611
654
  }) {
@@ -628,7 +671,12 @@ export async function startBatchDetached({
628
671
 
629
672
  const before = loadSpineBatchState(projectRoot);
630
673
  const previousBatchId = before.raw?.batchId ?? null;
631
- const argv = buildAttachedBatchStartArgv({ scope, skipPreflight: true });
674
+ const argv = buildAttachedBatchStartArgv({
675
+ scope,
676
+ skipPreflight: true,
677
+ forceSuperseded,
678
+ waveFilter,
679
+ });
632
680
  const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
633
681
  persistDetachedEnginePid(projectRoot, enginePid);
634
682
  const wait = await waitForDetachedBatchStart({ projectRoot, previousBatchId, waitTerminal });
@@ -719,15 +767,65 @@ export async function resumeBatchDetached({
719
767
  }
720
768
 
721
769
  const { batchId, updatedAt, taskId } = resumeCheck;
770
+
771
+ if (resumeCheck.postMergeLimbo) {
772
+ const loaded = loadSpineBatchState(projectRoot);
773
+ const state = loaded.raw;
774
+ const finalizeResult = finalizeResumePostMergeLimbo({
775
+ projectRoot,
776
+ state,
777
+ batchId,
778
+ orchBranch: state.orchBranch,
779
+ fromPhase: String(state.phase ?? "running"),
780
+ resumeForced: force,
781
+ });
782
+ if (!finalizeResult?.ok) {
783
+ const payload = {
784
+ ok: false,
785
+ detached: true,
786
+ operation: "resume",
787
+ batchId,
788
+ taskId,
789
+ error: "post_merge_limbo_finalize_failed",
790
+ output: finalizeResult?.output ?? "Failed to finalize post-merge limbo.\n",
791
+ };
792
+ return {
793
+ ok: false,
794
+ exitCode: 1,
795
+ output: formatDetachedEngineOutput(payload, json),
796
+ result: payload,
797
+ };
798
+ }
799
+
800
+ const payload = {
801
+ ok: true,
802
+ detached: true,
803
+ operation: "resume",
804
+ status: "resume_completed",
805
+ batchId,
806
+ taskId,
807
+ phase: "completed",
808
+ output: finalizeResult.output,
809
+ };
810
+ return {
811
+ ok: true,
812
+ exitCode: 0,
813
+ output: formatDetachedEngineOutput(payload, json),
814
+ result: payload,
815
+ };
816
+ }
817
+
722
818
  prepareDetachedResumeEngineHandoff(projectRoot);
723
819
  const argv = buildAttachedBatchResumeArgv({ force });
724
820
  const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
821
+ const waitTimeoutMs = resolveDetachedWaitTimeoutMs(waitTerminal);
725
822
  const wait = await waitForDetachedBatchResume({
726
823
  projectRoot,
727
824
  batchId,
728
825
  updatedAtBefore: updatedAt,
729
826
  taskId,
730
827
  waitTerminal,
828
+ timeoutMs: waitTimeoutMs,
731
829
  });
732
830
 
733
831
  if (!wait.ok) {
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Alternative operator commands per diagnosis (extracted for module size budget).
3
+ */
4
+ import { buildWorkerDoneMissingAlternatives } from "./diagnosis-worker-done-missing.mjs";
5
+
6
+ /**
7
+ * @param {string} diagnosis
8
+ * @param {object} [ctx]
9
+ * @param {string|null} [ctx.failedTaskId]
10
+ */
11
+ export function buildAlternatives(diagnosis, ctx = {}) {
12
+ const common = ["spine status --diagnose"];
13
+
14
+ switch (diagnosis) {
15
+ case "limbo_stale":
16
+ return ["spine batch complete --detect-manual-merge", ...common];
17
+ case "completed_manual":
18
+ return ["spine batch complete --detect-manual-merge", "spine batch dismiss", ...common];
19
+ case "needs_retry":
20
+ return ["spine batch abort", "/spine-skip-task", "/spine-resume --force", ...common];
21
+ case "worker_orphaned":
22
+ return ["spine batch abort", "spine batch resume --force", ...common];
23
+ case "worker_done_missing":
24
+ return buildWorkerDoneMissingAlternatives(ctx, common);
25
+ case "engine_orphaned":
26
+ return ctx.failedTaskId
27
+ ? [`spine batch retry ${ctx.failedTaskId}`, "spine batch abort", ...common]
28
+ : ["spine batch abort", "spine batch resume --force", ...common];
29
+ case "needs_merge":
30
+ return ["/spine-status --diagnose", ...common];
31
+ case "needs_integrate":
32
+ return ["/spine-integrate", "/spine-gate", ...common];
33
+ case "needs_replan":
34
+ return ctx.failedTaskId
35
+ ? [`spine batch skip ${ctx.failedTaskId}`, "spine handoff", ...common]
36
+ : ["spine handoff", ...common];
37
+ case "running":
38
+ return ["/spine-pause", "/spine-abort", ...common];
39
+ case "paused":
40
+ return ["spine batch resume --force", "spine status --diagnose", ...common];
41
+ case "failed":
42
+ return ["/spine-retry-task", ...common];
43
+ default:
44
+ return common;
45
+ }
46
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Wave merge failure diagnosis helpers (SP-338 / GitHub #29).
3
+ */
4
+
5
+ /**
6
+ * @param {unknown[]} mergeResults
7
+ * @param {string|null|undefined} lastError
8
+ * @returns {{
9
+ * mergeFailed: boolean,
10
+ * failedMerges: number,
11
+ * failedWaveIndex: number | null,
12
+ * failedLane: number | null,
13
+ * lastError: string | null,
14
+ * }}
15
+ */
16
+ export function summarizeMergeFailures(mergeResults, lastError = null) {
17
+ const results = Array.isArray(mergeResults) ? mergeResults : [];
18
+ const failedEntries = results.filter(
19
+ (entry) => String(entry?.status ?? "").toLowerCase() === "failed",
20
+ );
21
+ if (failedEntries.length === 0) {
22
+ return {
23
+ mergeFailed: false,
24
+ failedMerges: 0,
25
+ failedWaveIndex: null,
26
+ failedLane: null,
27
+ lastError: lastError ? String(lastError) : null,
28
+ };
29
+ }
30
+
31
+ const latestFailed = failedEntries.reduce((latest, entry) => {
32
+ const waveIndex = Number(entry?.waveIndex);
33
+ if (!Number.isFinite(waveIndex)) return latest;
34
+ if (!latest) return entry;
35
+ return Number(latest.waveIndex) > waveIndex ? latest : entry;
36
+ }, null);
37
+
38
+ const failedWaveIndex = Number(latestFailed?.waveIndex);
39
+ const failedLaneRaw = latestFailed?.failedLane;
40
+ const failedLane =
41
+ failedLaneRaw == null || failedLaneRaw === ""
42
+ ? null
43
+ : Number(failedLaneRaw);
44
+ const resolvedLastError =
45
+ lastError ??
46
+ latestFailed?.failureReason ??
47
+ latestFailed?.error ??
48
+ null;
49
+
50
+ return {
51
+ mergeFailed: true,
52
+ failedMerges: failedEntries.length,
53
+ failedWaveIndex: Number.isFinite(failedWaveIndex) ? failedWaveIndex : null,
54
+ failedLane: Number.isFinite(failedLane) ? failedLane : null,
55
+ lastError: resolvedLastError ? String(resolvedLastError) : null,
56
+ };
57
+ }
58
+
59
+ /**
60
+ * @param {string} batchLabel
61
+ * @param {object} ctx
62
+ * @param {number|null} [ctx.failedWaveIndex]
63
+ * @param {number|null} [ctx.failedLane]
64
+ * @param {string|null} [ctx.lastError]
65
+ * @param {number} [ctx.succeededTasks]
66
+ * @param {number} [ctx.totalTasks]
67
+ */
68
+ export function buildMergeFailureHeadline(batchLabel, ctx = {}) {
69
+ const waveNumber =
70
+ ctx.failedWaveIndex == null ? "?" : String(Number(ctx.failedWaveIndex) + 1);
71
+ const laneLabel =
72
+ ctx.failedLane == null ? "unknown lane" : `lane-${ctx.failedLane}`;
73
+ const progress =
74
+ ctx.totalTasks != null && ctx.succeededTasks != null
75
+ ? ` (${ctx.succeededTasks}/${ctx.totalTasks} tasks succeeded)`
76
+ : "";
77
+ const errorSuffix = ctx.lastError ? `: ${ctx.lastError}` : "";
78
+ return `${batchLabel} failed: wave ${waveNumber} merge conflict on ${laneLabel}${progress}${errorSuffix}`;
79
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Failed-phase limbo after retry clears failed tasks but phase stays failed (GitHub #25).
3
+ */
4
+
5
+ /**
6
+ * @param {object} ctx
7
+ * @param {string|null} [ctx.failedTaskId]
8
+ * @param {number} [ctx.failedTasks]
9
+ * @param {number} [ctx.pendingTaskCount]
10
+ * @param {string|null} [ctx.phase]
11
+ */
12
+ export function isFailedPhasePendingOnlyLimbo(ctx = {}) {
13
+ return (
14
+ String(ctx.phase ?? "") === "failed" &&
15
+ (ctx.failedTasks ?? 0) === 0 &&
16
+ (ctx.pendingTaskCount ?? 0) > 0 &&
17
+ !ctx.failedTaskId
18
+ );
19
+ }
20
+
21
+ /**
22
+ * @param {string} batchLabel
23
+ * @param {object} ctx
24
+ */
25
+ export function buildFailedPhasePendingOnlyHeadline(batchLabel, ctx = {}) {
26
+ return `${batchLabel} failed with pending task(s) and no failed tasks — resume to continue`;
27
+ }
28
+
29
+ /**
30
+ * @param {object} ctx
31
+ */
32
+ export function buildFailedPhasePendingOnlySuggestedCommand(_ctx = {}) {
33
+ return "spine batch resume --force";
34
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Stub worker completion diagnosis helpers (SP-349 / GitHub #33, #40).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { isLegacyStubDoneMarker } from "./contract-verify.mjs";
8
+ import { parsePrompt } from "../tasks/packet/parse-prompt.mjs";
9
+
10
+ export const STUB_EXIT_REASONS = new Set(["stub"]);
11
+
12
+ /**
13
+ * Surface `exitReason: stub` when legacy `.DONE` contains `Task: stub` on M/L implementation tasks.
14
+ *
15
+ * @param {string} promptMarkdown
16
+ * @param {string} doneContent
17
+ * @returns {string|null}
18
+ */
19
+ export function inferStubExitReasonFromDoneMarker(promptMarkdown, doneContent) {
20
+ if (!isLegacyStubDoneMarker(doneContent)) {
21
+ return null;
22
+ }
23
+ const parsed = parsePrompt(promptMarkdown);
24
+ if (parsed.size !== "M" && parsed.size !== "L") {
25
+ return null;
26
+ }
27
+ return "stub";
28
+ }
29
+
30
+ /**
31
+ * @param {string} tasksRoot
32
+ * @param {string} taskId
33
+ * @param {string|null} [taskFolder]
34
+ * @returns {string|null}
35
+ */
36
+ function resolveTaskFolder(tasksRoot, taskId, taskFolder = null) {
37
+ if (taskFolder) {
38
+ const direct = path.join(tasksRoot, taskFolder);
39
+ if (fs.existsSync(direct)) return direct;
40
+ }
41
+ if (!tasksRoot || !fs.existsSync(tasksRoot)) return null;
42
+ const match = fs
43
+ .readdirSync(tasksRoot, { withFileTypes: true })
44
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith(`${taskId}-`))
45
+ .map((entry) => path.join(tasksRoot, entry.name))[0];
46
+ return match ?? null;
47
+ }
48
+
49
+ /**
50
+ * Read on-disk PROMPT/.DONE for a task and infer stub exitReason when applicable.
51
+ *
52
+ * @param {string} tasksRoot
53
+ * @param {string} taskId
54
+ * @param {string|null} [taskFolder]
55
+ * @returns {string|null}
56
+ */
57
+ export function inferStubExitReasonForTask(tasksRoot, taskId, taskFolder = null) {
58
+ const folderPath = resolveTaskFolder(tasksRoot, taskId, taskFolder);
59
+ if (!folderPath) return null;
60
+ const donePath = path.join(folderPath, ".DONE");
61
+ const promptPath = path.join(folderPath, "PROMPT.md");
62
+ if (!fs.existsSync(donePath) || !fs.existsSync(promptPath)) return null;
63
+ return inferStubExitReasonFromDoneMarker(
64
+ fs.readFileSync(promptPath, "utf-8"),
65
+ fs.readFileSync(donePath, "utf-8"),
66
+ );
67
+ }
68
+
69
+ /**
70
+ * Find a succeeded task whose legacy `.DONE` marks stub completion on M/L work.
71
+ *
72
+ * @param {string|null} tasksRoot
73
+ * @param {Array<{ taskId: string, classification?: string, taskFolder?: string|null }>} tasks
74
+ * @returns {string|null}
75
+ */
76
+ export function findStubMarkedSucceededTask(tasksRoot, tasks) {
77
+ if (!tasksRoot || !Array.isArray(tasks)) return null;
78
+ for (const task of tasks) {
79
+ if (task.classification !== "terminal-success") continue;
80
+ const stubReason = inferStubExitReasonForTask(
81
+ tasksRoot,
82
+ task.taskId,
83
+ task.taskFolder ?? null,
84
+ );
85
+ if (stubReason) return task.taskId;
86
+ }
87
+ return null;
88
+ }
89
+
90
+ /**
91
+ * @param {string} batchLabel
92
+ * @param {object} ctx
93
+ * @param {string|null} [ctx.failedTaskId]
94
+ */
95
+ export function buildStubFailureHeadline(batchLabel, ctx = {}) {
96
+ return ctx.failedTaskId
97
+ ? `${batchLabel} task ${ctx.failedTaskId} stub-completed without file-scope changes`
98
+ : `${batchLabel} stub worker completed without file-scope changes`;
99
+ }
100
+
101
+ /**
102
+ * @param {object} ctx
103
+ * @param {string|null} [ctx.failedTaskId]
104
+ */
105
+ export function buildStubFailureSuggestedCommand(ctx = {}) {
106
+ return ctx.failedTaskId
107
+ ? `unset SPINE_WORKER_STUB && spine batch retry ${ctx.failedTaskId}`
108
+ : "unset SPINE_WORKER_STUB && spine batch resume";
109
+ }