pi-spine 1.1.0 → 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 (102) hide show
  1. package/bin/spine-batch.mjs +160 -53
  2. package/bin/spine-cli/batch.mjs +3 -3
  3. package/bin/spine-cli/lane-logs.mjs +24 -0
  4. package/bin/spine-cli/scenarios.mjs +298 -0
  5. package/bin/spine-cli/wait.mjs +30 -0
  6. package/bin/spine-cli/watch.mjs +27 -0
  7. package/bin/spine-issue.mjs +196 -0
  8. package/bin/spine-journal.mjs +1 -0
  9. package/bin/spine-run.mjs +30 -0
  10. package/bin/spine-status.mjs +19 -1
  11. package/bin/spine-tasks.mjs +16 -2
  12. package/bin/spine-worker-runner.mjs +10 -10
  13. package/bin/spine.mjs +49 -1
  14. package/package.json +1 -1
  15. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  16. package/src/batch/abort.mjs +2 -11
  17. package/src/batch/agent-session-worker.mjs +45 -5
  18. package/src/batch/attached-engine-handoff.mjs +188 -0
  19. package/src/batch/attached-runner.mjs +312 -0
  20. package/src/batch/contract-prelanded.mjs +180 -0
  21. package/src/batch/contract-verify.mjs +140 -2
  22. package/src/batch/detached-start.mjs +66 -2
  23. package/src/batch/diagnosis-alternatives.mjs +46 -0
  24. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  25. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  26. package/src/batch/diagnosis-stub.mjs +109 -0
  27. package/src/batch/diagnosis-task-done.mjs +110 -0
  28. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  29. package/src/batch/diagnosis.mjs +135 -68
  30. package/src/batch/engine-lanes/merge.mjs +110 -82
  31. package/src/batch/engine-lanes/queue.mjs +4 -1
  32. package/src/batch/engine-lanes/watch.mjs +29 -0
  33. package/src/batch/engine-lanes.mjs +1 -0
  34. package/src/batch/engine-scope.mjs +11 -1
  35. package/src/batch/engine.mjs +79 -24
  36. package/src/batch/evidence.mjs +78 -15
  37. package/src/batch/gate.mjs +43 -14
  38. package/src/batch/git-helpers.mjs +96 -0
  39. package/src/batch/heartbeat.mjs +73 -7
  40. package/src/batch/integrate.mjs +2 -4
  41. package/src/batch/journal.mjs +3 -0
  42. package/src/batch/lane-commit.mjs +90 -5
  43. package/src/batch/lifecycle.mjs +130 -3
  44. package/src/batch/macro-phase.mjs +226 -0
  45. package/src/batch/merge/adoption-doc-merge.mjs +93 -10
  46. package/src/batch/merge/wave-merge-state.mjs +3 -0
  47. package/src/batch/metrics.mjs +74 -5
  48. package/src/batch/orphan-detect.mjs +74 -0
  49. package/src/batch/pause.mjs +223 -0
  50. package/src/batch/post-merge-limbo.mjs +264 -8
  51. package/src/batch/reconcile.mjs +429 -54
  52. package/src/batch/resume-common.mjs +5 -1
  53. package/src/batch/resume-lane-reviews.mjs +16 -0
  54. package/src/batch/resume-multi-lanes.mjs +56 -1
  55. package/src/batch/resume-multi-validate.mjs +67 -6
  56. package/src/batch/resume-multi.mjs +9 -4
  57. package/src/batch/resume.mjs +52 -45
  58. package/src/batch/retry.mjs +56 -5
  59. package/src/batch/review-spawn.mjs +8 -2
  60. package/src/batch/rules-manifest-drift.mjs +157 -0
  61. package/src/batch/salvage.mjs +2 -1
  62. package/src/batch/sequence.mjs +454 -0
  63. package/src/batch/state.mjs +18 -3
  64. package/src/batch/status-json.mjs +67 -0
  65. package/src/batch/task-stall-budget.mjs +22 -10
  66. package/src/batch/worker-host.mjs +95 -7
  67. package/src/batch/worker-output.mjs +196 -3
  68. package/src/cli/issue-draft.mjs +180 -0
  69. package/src/cli/journal-follow.mjs +239 -0
  70. package/src/cli/lane-logs.mjs +291 -0
  71. package/src/cli/sequence.mjs +108 -0
  72. package/src/cli/settings-set.mjs +2 -21
  73. package/src/cli/wait.mjs +187 -0
  74. package/src/cli/watch.mjs +160 -0
  75. package/src/config/agent-model-resolve.mjs +48 -0
  76. package/src/config/cursor-rules/discover.mjs +3 -21
  77. package/src/config/defaults.mjs +7 -1
  78. package/src/config/settings-fields.mjs +48 -0
  79. package/src/config/spine-init-constants.mjs +1 -0
  80. package/src/config/spine-preflight-lib.mjs +471 -16
  81. package/src/dashboard/lane-throughput.mjs +351 -0
  82. package/src/dashboard/public/dashboard.css +25 -1
  83. package/src/dashboard/public/dashboard.js +223 -18
  84. package/src/dashboard/public/index.html +14 -2
  85. package/src/dashboard/server.mjs +4 -0
  86. package/src/dashboard/snapshot.mjs +215 -1
  87. package/src/dashboard/view.mjs +170 -17
  88. package/src/doctor/agent-model-inherit.mjs +61 -6
  89. package/src/doctor/run-doctor-checks.mjs +26 -1
  90. package/src/doctor/sequence-safety.mjs +57 -0
  91. package/src/doctor/stale-worktrees.mjs +102 -0
  92. package/src/fixtures/scenario-registry.mjs +194 -0
  93. package/src/fs/atomic-write.mjs +49 -0
  94. package/src/planner/file-scope.mjs +246 -0
  95. package/src/planner/format-plan.mjs +9 -7
  96. package/src/planner/index.mjs +6 -2
  97. package/src/planner/wave-scope.mjs +136 -0
  98. package/src/planner/waves.mjs +133 -0
  99. package/src/tasks/packet/index.mjs +1 -0
  100. package/src/tasks/packet/parse-prompt.mjs +42 -1
  101. package/src/tasks/packet/validate-prompt.mjs +124 -0
  102. package/templates/spine-config.json +8 -1
@@ -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
 
@@ -13,6 +13,7 @@ import { validateResumeBatch } from "./resume.mjs";
13
13
  import { assessRunningPhaseResumeEligibility } from "./resume-multi-validate.mjs";
14
14
  import { readLastTaskFailedEvent } from "./journal.mjs";
15
15
  import { prepareOrphanResumeHandoff } from "./resume-engine.mjs";
16
+ import { finalizeResumePostMergeLimbo } from "./attached-runner.mjs";
16
17
  import {
17
18
  ACTIVE_PHASES,
18
19
  loadSpineBatchState,
@@ -28,6 +29,7 @@ const RESUME_WAIT_TERMINAL_DIAGNOSES = new Set([
28
29
  "engine_orphaned",
29
30
  "worker_orphaned",
30
31
  "state_drift",
32
+ "needs_integrate",
31
33
  ]);
32
34
 
33
35
  /**
@@ -287,8 +289,14 @@ export function detachedEngineLogPath(projectRoot) {
287
289
  * @param {string} params.scope
288
290
  * @param {boolean} [params.skipPreflight]
289
291
  * @param {boolean} [params.forceSuperseded]
292
+ * @param {number|null} [params.waveFilter]
290
293
  */
291
- export function buildAttachedBatchStartArgv({ scope, skipPreflight = false, forceSuperseded = false }) {
294
+ export function buildAttachedBatchStartArgv({
295
+ scope,
296
+ skipPreflight = false,
297
+ forceSuperseded = false,
298
+ waveFilter = null,
299
+ }) {
292
300
  const tokens = String(scope ?? "")
293
301
  .trim()
294
302
  .split(/\s+/)
@@ -296,6 +304,7 @@ export function buildAttachedBatchStartArgv({ scope, skipPreflight = false, forc
296
304
  const args = ["batch", "start", ...tokens, "--attached"];
297
305
  if (skipPreflight) args.push("--skip-preflight");
298
306
  if (forceSuperseded) args.push("--force-superseded");
307
+ if (waveFilter != null) args.push("--wave", String(waveFilter));
299
308
  return args;
300
309
  }
301
310
 
@@ -629,6 +638,7 @@ export function formatDetachedBatchStartOutput(result, json = false) {
629
638
  * @param {string} params.scope
630
639
  * @param {boolean} [params.skipPreflight]
631
640
  * @param {boolean} [params.forceSuperseded]
641
+ * @param {number|null} [params.waveFilter]
632
642
  * @param {boolean} [params.waitTerminal]
633
643
  * @param {boolean} [params.json]
634
644
  */
@@ -638,6 +648,7 @@ export async function startBatchDetached({
638
648
  scope,
639
649
  skipPreflight = false,
640
650
  forceSuperseded = false,
651
+ waveFilter = null,
641
652
  waitTerminal = false,
642
653
  json = false,
643
654
  }) {
@@ -660,7 +671,12 @@ export async function startBatchDetached({
660
671
 
661
672
  const before = loadSpineBatchState(projectRoot);
662
673
  const previousBatchId = before.raw?.batchId ?? null;
663
- const argv = buildAttachedBatchStartArgv({ scope, skipPreflight: true, forceSuperseded });
674
+ const argv = buildAttachedBatchStartArgv({
675
+ scope,
676
+ skipPreflight: true,
677
+ forceSuperseded,
678
+ waveFilter,
679
+ });
664
680
  const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
665
681
  persistDetachedEnginePid(projectRoot, enginePid);
666
682
  const wait = await waitForDetachedBatchStart({ projectRoot, previousBatchId, waitTerminal });
@@ -751,6 +767,54 @@ export async function resumeBatchDetached({
751
767
  }
752
768
 
753
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
+
754
818
  prepareDetachedResumeEngineHandoff(projectRoot);
755
819
  const argv = buildAttachedBatchResumeArgv({ force });
756
820
  const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
@@ -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
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Per-task done-marker semantics for reconcile / status JSON (SP-344 / GitHub #35).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { laneWorktreePath } from "./worktree.mjs";
8
+
9
+ /** Documented task done-flag field names for status JSON. */
10
+ export const TASK_DONE_FLAG_FIELD_NAMES = ["doneFileFound", "doneOnMain", "doneInLane"];
11
+
12
+ /**
13
+ * @param {string} tasksRoot
14
+ * @param {string} taskId
15
+ * @param {string|null|undefined} taskFolder
16
+ * @returns {string|null}
17
+ */
18
+ export function resolveTaskFolderPath(tasksRoot, taskId, taskFolder) {
19
+ if (taskFolder) {
20
+ const direct = path.join(tasksRoot, taskFolder);
21
+ if (fs.existsSync(direct)) return direct;
22
+ }
23
+
24
+ if (!tasksRoot || !fs.existsSync(tasksRoot)) return null;
25
+
26
+ const match = fs
27
+ .readdirSync(tasksRoot, { withFileTypes: true })
28
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith(`${taskId}-`))
29
+ .map((entry) => path.join(tasksRoot, entry.name))[0];
30
+
31
+ return match ?? null;
32
+ }
33
+
34
+ /**
35
+ * @param {string} projectRoot
36
+ * @param {string} batchId
37
+ * @param {unknown[]} lanes
38
+ * @param {object} task
39
+ * @returns {string}
40
+ */
41
+ export function resolveTaskLaneWorktreePath(projectRoot, batchId, lanes, task) {
42
+ const laneNumber = Number(task.laneNumber ?? 1);
43
+ const lane = Array.isArray(lanes)
44
+ ? lanes.find((entry) => Number(entry.laneNumber) === laneNumber)
45
+ : null;
46
+ if (lane && typeof lane.worktreePath === "string" && lane.worktreePath) {
47
+ return path.isAbsolute(lane.worktreePath)
48
+ ? lane.worktreePath
49
+ : path.join(projectRoot, lane.worktreePath);
50
+ }
51
+ return laneWorktreePath(projectRoot, batchId, laneNumber);
52
+ }
53
+
54
+ /**
55
+ * @param {string|null} folderPath
56
+ * @returns {boolean}
57
+ */
58
+ function doneMarkerExists(folderPath) {
59
+ return Boolean(folderPath && fs.existsSync(path.join(folderPath, ".DONE")));
60
+ }
61
+
62
+ /**
63
+ * Classify per-task done semantics for reconcile / status JSON.
64
+ *
65
+ * - `doneFileFound`: batch-state / journal records worker completion.
66
+ * - `doneOnMain`: `.DONE` exists under the integration checkout tasks root.
67
+ * - `doneInLane`: `.DONE` exists in the lane worktree copy (pre-merge).
68
+ *
69
+ * @param {object} task
70
+ * @param {object} ctx
71
+ * @param {string|null} [ctx.tasksRoot]
72
+ * @param {string} [ctx.projectRoot]
73
+ * @param {string} [ctx.batchId]
74
+ * @param {unknown[]} [ctx.lanes]
75
+ */
76
+ export function classifyTaskDoneSemantics(task, ctx = {}) {
77
+ const { tasksRoot, projectRoot, batchId, lanes = [] } = ctx;
78
+ const mainFolderPath =
79
+ tasksRoot && task.taskId
80
+ ? resolveTaskFolderPath(tasksRoot, task.taskId, task.taskFolder ?? null)
81
+ : null;
82
+ const doneOnMain = doneMarkerExists(mainFolderPath);
83
+ const doneFileFound = Boolean(task.doneFileFound);
84
+
85
+ let doneInLane = false;
86
+ if (projectRoot && batchId && tasksRoot && task.taskId) {
87
+ const laneWorktree = resolveTaskLaneWorktreePath(projectRoot, batchId, lanes, task);
88
+ const tasksRootRel = path.relative(projectRoot, tasksRoot);
89
+ const laneTasksRoot = path.join(laneWorktree, tasksRootRel);
90
+ const laneFolderPath = resolveTaskFolderPath(
91
+ laneTasksRoot,
92
+ task.taskId,
93
+ task.taskFolder ?? null,
94
+ );
95
+ doneInLane = doneMarkerExists(laneFolderPath);
96
+ }
97
+
98
+ let classification = task.classification;
99
+ if (doneOnMain || doneInLane || doneFileFound) {
100
+ classification = "terminal-success";
101
+ }
102
+
103
+ return {
104
+ ...task,
105
+ doneFileFound,
106
+ doneOnMain,
107
+ doneInLane,
108
+ classification,
109
+ };
110
+ }