pi-spine 1.0.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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +563 -0
  3. package/bin/get-version.mjs +35 -0
  4. package/bin/spine-batch.mjs +425 -0
  5. package/bin/spine-cli/batch.mjs +47 -0
  6. package/bin/spine-cli/gate.mjs +10 -0
  7. package/bin/spine-cli/integrate.mjs +10 -0
  8. package/bin/spine-cli/plan.mjs +12 -0
  9. package/bin/spine-cli/shared.mjs +73 -0
  10. package/bin/spine-cli/status.mjs +18 -0
  11. package/bin/spine-cli/verify.mjs +199 -0
  12. package/bin/spine-config.mjs +212 -0
  13. package/bin/spine-dashboard.mjs +178 -0
  14. package/bin/spine-deps.mjs +69 -0
  15. package/bin/spine-doctor.mjs +468 -0
  16. package/bin/spine-gate.mjs +137 -0
  17. package/bin/spine-init.mjs +398 -0
  18. package/bin/spine-integrate.mjs +77 -0
  19. package/bin/spine-journal.mjs +198 -0
  20. package/bin/spine-migrate-from-taskplane.mjs +136 -0
  21. package/bin/spine-plan.mjs +83 -0
  22. package/bin/spine-preflight.mjs +700 -0
  23. package/bin/spine-report-progress.d.mts +28 -0
  24. package/bin/spine-report-progress.mjs +126 -0
  25. package/bin/spine-review-step.d.mts +24 -0
  26. package/bin/spine-review-step.mjs +124 -0
  27. package/bin/spine-rules.mjs +35 -0
  28. package/bin/spine-settings.mjs +186 -0
  29. package/bin/spine-state.mjs +110 -0
  30. package/bin/spine-status.mjs +79 -0
  31. package/bin/spine-tasks.mjs +293 -0
  32. package/bin/spine-worker-runner.mjs +314 -0
  33. package/bin/spine.mjs +404 -0
  34. package/extensions/spine/settings-slash.ts +20 -0
  35. package/extensions/spine/slash-commands.ts +806 -0
  36. package/extensions/spine/worker-tools.ts +279 -0
  37. package/extensions/spine-orchestrator.ts +12 -0
  38. package/package.json +72 -0
  39. package/skills/.gitkeep +0 -0
  40. package/skills/create-spine-tasks/SKILL.md +375 -0
  41. package/skills/create-spine-tasks/references/context-template.md +25 -0
  42. package/skills/create-spine-tasks/references/contract-template.md +98 -0
  43. package/skills/create-spine-tasks/references/explore-template.md +63 -0
  44. package/skills/create-spine-tasks/references/prompt-template.md +276 -0
  45. package/src/batch/abort.mjs +272 -0
  46. package/src/batch/agent-session-worker.mjs +297 -0
  47. package/src/batch/batch-state-io.mjs +53 -0
  48. package/src/batch/contract-verify.mjs +310 -0
  49. package/src/batch/detached-start.mjs +778 -0
  50. package/src/batch/diagnosis.mjs +378 -0
  51. package/src/batch/engine-lanes/merge.mjs +632 -0
  52. package/src/batch/engine-lanes/queue.mjs +208 -0
  53. package/src/batch/engine-lanes/review.mjs +970 -0
  54. package/src/batch/engine-lanes.mjs +388 -0
  55. package/src/batch/engine-scope.mjs +251 -0
  56. package/src/batch/engine.mjs +445 -0
  57. package/src/batch/evidence-command.mjs +157 -0
  58. package/src/batch/evidence.mjs +203 -0
  59. package/src/batch/gate.mjs +359 -0
  60. package/src/batch/git-commit-env.mjs +46 -0
  61. package/src/batch/git-exec.mjs +26 -0
  62. package/src/batch/heartbeat.mjs +430 -0
  63. package/src/batch/integrate.mjs +414 -0
  64. package/src/batch/journal-rebuild.mjs +388 -0
  65. package/src/batch/journal.mjs +373 -0
  66. package/src/batch/lane-commit.mjs +153 -0
  67. package/src/batch/lifecycle.mjs +364 -0
  68. package/src/batch/metrics.mjs +265 -0
  69. package/src/batch/orphan-detect.mjs +210 -0
  70. package/src/batch/post-merge-limbo.mjs +80 -0
  71. package/src/batch/postmortem.mjs +296 -0
  72. package/src/batch/readers/spine-state.mjs +95 -0
  73. package/src/batch/readers/taskplane-state.mjs +136 -0
  74. package/src/batch/reconcile.mjs +729 -0
  75. package/src/batch/resume-common.mjs +104 -0
  76. package/src/batch/resume-engine.mjs +66 -0
  77. package/src/batch/resume-multi-lanes.mjs +479 -0
  78. package/src/batch/resume-multi-validate.mjs +187 -0
  79. package/src/batch/resume-multi.mjs +254 -0
  80. package/src/batch/resume.mjs +475 -0
  81. package/src/batch/retry.mjs +257 -0
  82. package/src/batch/review-scope.mjs +136 -0
  83. package/src/batch/review.mjs +1045 -0
  84. package/src/batch/salvage.mjs +332 -0
  85. package/src/batch/state.mjs +680 -0
  86. package/src/batch/task-stall-budget.mjs +88 -0
  87. package/src/batch/worker-host.mjs +683 -0
  88. package/src/batch/worker-output.mjs +253 -0
  89. package/src/batch/worker-prompt.mjs +84 -0
  90. package/src/batch/worktree.mjs +290 -0
  91. package/src/cli/deps.mjs +141 -0
  92. package/src/cli/handoff.mjs +364 -0
  93. package/src/cli/rules.mjs +429 -0
  94. package/src/cli/settings-set.mjs +171 -0
  95. package/src/cli/settings-show.mjs +140 -0
  96. package/src/cli/settings-slash.mjs +107 -0
  97. package/src/config/contract.mjs +56 -0
  98. package/src/config/cursor-rules/discover.mjs +416 -0
  99. package/src/config/cursor-rules/index.mjs +39 -0
  100. package/src/config/cursor-rules/match-globs.mjs +132 -0
  101. package/src/config/cursor-rules/parse-frontmatter.mjs +222 -0
  102. package/src/config/cursor-rules/priority.mjs +26 -0
  103. package/src/config/cursor-rules/profile.mjs +403 -0
  104. package/src/config/cursor-rules/select.mjs +259 -0
  105. package/src/config/defaults.mjs +36 -0
  106. package/src/config/env-overrides.mjs +207 -0
  107. package/src/config/merge-defaults.mjs +47 -0
  108. package/src/config/pi-spine-root.mjs +93 -0
  109. package/src/config/reviewer-context.mjs +243 -0
  110. package/src/config/settings-fields.mjs +265 -0
  111. package/src/config/worker-backend.mjs +116 -0
  112. package/src/config/worker-context.mjs +402 -0
  113. package/src/config/worker-launch-script.mjs +130 -0
  114. package/src/config/worktree-setup-hook.mjs +122 -0
  115. package/src/dashboard/public/dashboard.css +77 -0
  116. package/src/dashboard/public/dashboard.js +349 -0
  117. package/src/dashboard/public/index.html +80 -0
  118. package/src/dashboard/server.mjs +155 -0
  119. package/src/dashboard/snapshot.mjs +414 -0
  120. package/src/dashboard/sse.mjs +15 -0
  121. package/src/dashboard/view.mjs +292 -0
  122. package/src/doctor/agent-model-inherit.mjs +101 -0
  123. package/src/doctor/batch-size-guidance.mjs +72 -0
  124. package/src/doctor/coexistence.mjs +312 -0
  125. package/src/doctor/rules-manifest.mjs +133 -0
  126. package/src/doctor/stale-path.mjs +156 -0
  127. package/src/doctor/stall-config.mjs +108 -0
  128. package/src/doctor/suggest-max-parallel.mjs +53 -0
  129. package/src/doctor/task-packet-size.mjs +110 -0
  130. package/src/doctor/worktree-health.mjs +71 -0
  131. package/src/migrate/taskplane-config.mjs +116 -0
  132. package/src/planner/cycles.mjs +63 -0
  133. package/src/planner/format-plan.mjs +132 -0
  134. package/src/planner/graph.mjs +99 -0
  135. package/src/planner/index.mjs +125 -0
  136. package/src/planner/lanes.mjs +111 -0
  137. package/src/planner/pending.mjs +39 -0
  138. package/src/planner/scope.mjs +142 -0
  139. package/src/process/liveness.mjs +21 -0
  140. package/src/tasks/packet/discover.mjs +40 -0
  141. package/src/tasks/packet/index.mjs +81 -0
  142. package/src/tasks/packet/merge-deps.mjs +79 -0
  143. package/src/tasks/packet/parse-prompt.mjs +445 -0
  144. package/src/tasks/packet/parse-status.mjs +118 -0
  145. package/src/tasks/packet/validate-contract.mjs +115 -0
  146. package/src/tasks/packet/validate-prompt.mjs +99 -0
  147. package/src/worker-tools/report-progress.d.mts +18 -0
  148. package/src/worker-tools/report-progress.mjs +59 -0
  149. package/src/worker-tools/request-gate.d.mts +17 -0
  150. package/src/worker-tools/request-gate.mjs +54 -0
  151. package/templates/agents/reviewer.md +123 -0
  152. package/templates/agents/supervisor.md +59 -0
  153. package/templates/agents/worker.md +122 -0
  154. package/templates/rules-profile.json +27 -0
  155. package/templates/spine-config.json +64 -0
  156. package/templates/tasks/CONTEXT.md +30 -0
@@ -0,0 +1,276 @@
1
+ # PROMPT.md Template (spine)
2
+
3
+ Copy this template when creating a new task. Replace all `[bracketed]` fields.
4
+
5
+ **Before creating:** Verify you have scored complexity and assigned Review Level.
6
+ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
7
+
8
+ ---
9
+
10
+ ````markdown
11
+ # Task: [PREFIX-###] — [Name]
12
+
13
+ **Created:** [YYYY-MM-DD]
14
+ **Size:** [S | M | L]
15
+
16
+ ## Review Level: [0-3] ([None | Plan Only | Plan and Code | Full])
17
+
18
+ **Assessment:** [1-2 sentences explaining the score]
19
+ **Score:** [N]/8 — Blast radius: [N], Pattern novelty: [N], Security: [N], Reversibility: [N]
20
+
21
+ ## Canonical Task Folder
22
+
23
+ ```
24
+ [FULL_PATH_TO_TASK_FOLDER]/
25
+ ├── PROMPT.md ← This file (immutable above --- divider)
26
+ ├── STATUS.md ← Execution state (worker updates this)
27
+ ├── .reviews/ ← Reviewer output (created by the orchestrator runtime)
28
+ └── .DONE ← Created when complete
29
+ ```
30
+
31
+ ## Mission
32
+
33
+ [One paragraph: what you're building and why it matters]
34
+
35
+ ## Dependencies
36
+
37
+ [Choose one:]
38
+
39
+ - **None**
40
+
41
+ [OR:]
42
+
43
+ - **Task:** [PREFIX-###] ([what must be complete])
44
+ - **Task:** [area-name/PREFIX-###] ([use area-qualified form if cross-area ID may be ambiguous])
45
+ - **External:** [what must be true]
46
+
47
+ ## Context to Read First
48
+
49
+ > Only list docs the worker actually needs. Less is better.
50
+
51
+ **Tier 2 (area context):**
52
+ - `[path/to/CONTEXT.md]`
53
+
54
+ **Tier 3 (load only if needed):**
55
+ - `[path/to/specific-doc.md]` — [why needed]
56
+
57
+ ## Environment
58
+
59
+ - **Workspace:** [primary folder/service being modified]
60
+ - **Services required:** [list, or "None"]
61
+
62
+ ## File Scope
63
+
64
+ > The orchestrator uses this to avoid merge conflicts: tasks with overlapping
65
+ > file scope run on the same lane (serial), not in parallel. List the files and
66
+ > directories this task will create or modify. Use wildcards for directories.
67
+
68
+ - `[path/to/file.ext]`
69
+ - `[path/to/directory/*]`
70
+
71
+ ## Contract
72
+
73
+ > **Required for new `SP-*` tasks** when `contract.mode` is `required` (pi-spine default).
74
+ > Defines machine-verifiable proof checked at final review. See
75
+ > [references/contract-template.md](contract-template.md) for field guidance and examples.
76
+ > Taskplane legacy `TP-*` tasks may omit this section when listed in `contract.legacyTaskIdPrefixes`.
77
+
78
+ | Field | Value |
79
+ |-------|-------|
80
+ | testCommand | `[shell command in backticks, or \`true\` for docs-only S tasks]` |
81
+ | fileScopeMustChange | `[optional: comma-separated paths/globs that must change]` |
82
+ | fileScopeMustNotChange | `[optional: comma-separated paths/globs that must not change]` |
83
+ | minLineCoverage | `[optional: integer 0–100; use 77 for code tasks]` |
84
+ | artifactsMustExist | `[optional: comma-separated file paths that must exist]` |
85
+
86
+ > **Code tasks:** include `testCommand` and usually `minLineCoverage` (≥77%). **Docs-only**
87
+ > Review Level 0 + Size S may set `testCommand` to `` `true` ``.
88
+
89
+ ## Steps
90
+
91
+ > **Section order:** All steps — including `Testing & Verification` and
92
+ > `Documentation & Delivery` — belong **inside** `## Steps`, **before**
93
+ > `## Completion Criteria`. Never end `## Steps` at implementation work and
94
+ > jump straight to Completion Criteria; missing a Testing step fails batch launch
95
+ > (`prompt_parse_failed`, SP-075).
96
+ >
97
+ > **Hydration:** STATUS.md tracks outcomes, not individual code changes. Workers
98
+ > expand steps when runtime discoveries warrant it. See `.spine/agents/worker.md` for rules.
99
+
100
+ ### Step 0: Preflight
101
+
102
+ - [ ] Required files and paths exist
103
+ - [ ] Dependencies satisfied
104
+
105
+ ### Step 1: [Name]
106
+
107
+ - [ ] [Specific, verifiable task]
108
+ - [ ] [Specific, verifiable task]
109
+ - [ ] [Specific, verifiable task]
110
+ - [ ] Run targeted tests: `[test command] --changed` or specific test files
111
+
112
+ **Artifacts:**
113
+ - `path/to/file` (new | modified)
114
+
115
+ ### Step [N-1]: Testing & Verification
116
+
117
+ > **Required for every task** — including docs-only and Review Level 0 packets.
118
+ > ZERO test failures allowed. This step runs the FULL test suite as a quality gate.
119
+ > (Earlier steps should use targeted tests for fast feedback — see worker prompt.)
120
+ >
121
+ > **Docs-only tasks:** keep this step; run the full test suite. Omit the coverage-gate
122
+ > checkbox below when the task does not change application code.
123
+
124
+ - [ ] Run FULL test suite: `[test command from project config]`
125
+ - [ ] Run coverage gate: `[testWithCoverage command, e.g. npm run coverage:check]` — **≥77% line coverage** on in-scope changed code (code-related tasks only; omit for docs-only)
126
+ - [ ] Run integration tests (if applicable)
127
+ - [ ] Fix all failures
128
+ - [ ] Build passes: `[build command]`
129
+
130
+ ### Step [N]: Documentation & Delivery
131
+
132
+ - [ ] "Must Update" docs modified
133
+ - [ ] "Check If Affected" docs reviewed
134
+ - [ ] Discoveries logged in STATUS.md
135
+
136
+ ## Documentation Requirements
137
+
138
+ **Must Update:**
139
+ - `[path/to/doc.md]` — [what to add/change]
140
+
141
+ **Check If Affected:**
142
+ - `[path/to/doc.md]` — [update if relevant]
143
+
144
+ ## Completion Criteria
145
+
146
+ - [ ] All steps complete
147
+ - [ ] All tests passing
148
+ - [ ] Documentation updated
149
+
150
+ ## Git Commit Convention
151
+
152
+ Commits happen at **step boundaries** (not after every checkbox). All commits
153
+ for this task MUST include the task ID for traceability:
154
+
155
+ - **Step completion:** `feat([PREFIX-###]): complete Step N — description`
156
+ - **Bug fixes:** `fix([PREFIX-###]): description`
157
+ - **Tests:** `test([PREFIX-###]): description`
158
+ - **Hydration:** `hydrate: [PREFIX-###] expand Step N checkboxes`
159
+
160
+ ## Do NOT
161
+
162
+ - Expand task scope — add tech debt to CONTEXT.md instead
163
+ - Skip tests
164
+ - Modify framework/standards docs without explicit user approval
165
+ - Load docs not listed in "Context to Read First"
166
+ - Commit without the task ID prefix in the commit message
167
+
168
+ ---
169
+
170
+ ## Amendments (Added During Execution)
171
+
172
+ <!-- Workers add amendments here if issues discovered during execution.
173
+ Format:
174
+ ### Amendment N — YYYY-MM-DD HH:MM
175
+ **Issue:** [what was wrong]
176
+ **Resolution:** [what was changed] -->
177
+ ````
178
+
179
+ ---
180
+
181
+ # STATUS.md Template
182
+
183
+ Create alongside PROMPT.md. If omitted, the execution engine may auto-generate
184
+ this from PROMPT.md.
185
+
186
+ ````markdown
187
+ # [PREFIX-###]: [Name] — Status
188
+
189
+ **Current Step:** Not Started
190
+ **Status:** 🔵 Ready for Execution
191
+ **Last Updated:** [YYYY-MM-DD]
192
+ **Review Level:** [0-3]
193
+ **Review Counter:** 0
194
+ **Iteration:** 0
195
+ **Size:** [S | M | L]
196
+
197
+ > **Hydration:** Checkboxes represent meaningful outcomes, not individual code
198
+ > changes. Workers expand steps when runtime discoveries warrant it — aim for
199
+ > 2-5 outcome-level items per step, not exhaustive implementation scripts.
200
+
201
+ ---
202
+
203
+ ### Step 0: Preflight
204
+ **Status:** ⬜ Not Started
205
+
206
+ - [ ] Required files and paths exist
207
+ - [ ] Dependencies satisfied
208
+
209
+ ---
210
+
211
+ ### Step 1: [Name]
212
+ **Status:** ⬜ Not Started
213
+
214
+ [If items are known at creation time, list each one:]
215
+ - [ ] [Specific item from PROMPT.md]
216
+ - [ ] [Specific item from PROMPT.md]
217
+
218
+ [If items depend on runtime discovery:]
219
+ > ⚠️ Hydrate: Expand checkboxes when entering this step based on [what]
220
+
221
+ - [ ] [High-level placeholder — worker will expand]
222
+
223
+ ---
224
+
225
+ ### Step [N-1]: Testing & Verification
226
+ **Status:** ⬜ Not Started
227
+
228
+ - [ ] FULL test suite passing
229
+ - [ ] Coverage gate passes (≥77% line coverage on in-scope code, when applicable)
230
+ - [ ] Integration tests (if applicable)
231
+ - [ ] All failures fixed
232
+ - [ ] Build passes
233
+
234
+ ---
235
+
236
+ ### Step [N]: Documentation & Delivery
237
+ **Status:** ⬜ Not Started
238
+
239
+ - [ ] "Must Update" docs modified
240
+ - [ ] "Check If Affected" docs reviewed
241
+ - [ ] Discoveries logged
242
+
243
+ ---
244
+
245
+ ## Reviews
246
+
247
+ | # | Type | Step | Verdict | File |
248
+ |---|------|------|---------|------|
249
+
250
+ ---
251
+
252
+ ## Discoveries
253
+
254
+ | Discovery | Disposition | Location |
255
+ |-----------|-------------|----------|
256
+
257
+ ---
258
+
259
+ ## Execution Log
260
+
261
+ | Timestamp | Action | Outcome |
262
+ |-----------|--------|---------|
263
+ | [YYYY-MM-DD] | Task staged | PROMPT.md and STATUS.md created |
264
+
265
+ ---
266
+
267
+ ## Blockers
268
+
269
+ *None*
270
+
271
+ ---
272
+
273
+ ## Notes
274
+
275
+ *Reserved for execution notes*
276
+ ````
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Archive-first batch abort (FR-BATCH-06, §18.6).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { loadSpineConfig } from "../../bin/spine-config.mjs";
8
+ import { archiveBatchStatePath } from "./lifecycle.mjs";
9
+ import { appendJournalEvent, journalPath, readJournalEvents, readJournalTail } from "./journal.mjs";
10
+ import { loadBatchStateFile } from "./reconcile.mjs";
11
+ import { appendBatchHistoryEntry } from "./state.mjs";
12
+ import { removeLaneWorktree } from "./worktree.mjs";
13
+
14
+ /**
15
+ * @param {string} projectRoot
16
+ * @param {string} batchId
17
+ */
18
+ export function abortSignalPath(projectRoot, batchId) {
19
+ return path.join(projectRoot, ".spine", "runtime", batchId, "abort-signal.json");
20
+ }
21
+
22
+ /**
23
+ * @param {string} projectRoot
24
+ * @param {string} batchId
25
+ */
26
+ export function readAbortSignal(projectRoot, batchId) {
27
+ const signalPath = abortSignalPath(projectRoot, batchId);
28
+ if (!fs.existsSync(signalPath)) return null;
29
+ try {
30
+ return JSON.parse(fs.readFileSync(signalPath, "utf-8"));
31
+ } catch {
32
+ return { hard: true, reason: null };
33
+ }
34
+ }
35
+
36
+ /**
37
+ * @param {string} projectRoot
38
+ * @param {string} batchId
39
+ * @param {object} payload
40
+ */
41
+ export function writeAbortSignal(projectRoot, batchId, payload) {
42
+ const signalPath = abortSignalPath(projectRoot, batchId);
43
+ fs.mkdirSync(path.dirname(signalPath), { recursive: true });
44
+ fs.writeFileSync(signalPath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
45
+ return signalPath;
46
+ }
47
+
48
+ /**
49
+ * @param {string} projectRoot
50
+ * @param {string} batchId
51
+ * @param {unknown} raw
52
+ */
53
+ function writeBatchArchive(projectRoot, batchId, raw) {
54
+ const archivePath = archiveBatchStatePath(projectRoot, batchId);
55
+ fs.mkdirSync(path.dirname(archivePath), { recursive: true });
56
+ fs.writeFileSync(archivePath, `${JSON.stringify(raw, null, 2)}\n`, "utf-8");
57
+
58
+ const fd = fs.openSync(archivePath, "r");
59
+ try {
60
+ fs.fsyncSync(fd);
61
+ } finally {
62
+ fs.closeSync(fd);
63
+ }
64
+
65
+ return archivePath;
66
+ }
67
+
68
+ /**
69
+ * @param {string|null} batchStatePath
70
+ */
71
+ function clearActiveBatchState(batchStatePath) {
72
+ if (batchStatePath && fs.existsSync(batchStatePath)) {
73
+ fs.unlinkSync(batchStatePath);
74
+ }
75
+ }
76
+
77
+ /**
78
+ * @param {unknown[]} lanes
79
+ * @param {boolean} hard
80
+ */
81
+ function killLaneWorkers(lanes, hard) {
82
+ const signal = hard ? "SIGKILL" : "SIGTERM";
83
+ for (const lane of lanes ?? []) {
84
+ if (!lane || typeof lane !== "object") continue;
85
+ const pid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
86
+ if (!Number.isFinite(pid) || pid <= 0) continue;
87
+ try {
88
+ process.kill(pid, signal);
89
+ } catch {
90
+ // process may already be gone
91
+ }
92
+ }
93
+ }
94
+
95
+ /**
96
+ * @param {object|null|undefined} config
97
+ */
98
+ function shouldCleanupWorktreesOnHardAbort(config) {
99
+ if (config?.worktrees?.cleanupOnHardAbort === false) return false;
100
+ if (config?.lanes?.cleanupWorktreesOnHardAbort === false) return false;
101
+ return true;
102
+ }
103
+
104
+ /**
105
+ * @param {unknown} raw
106
+ * @param {string|null} reason
107
+ */
108
+ function buildAbortedSnapshot(raw, reason) {
109
+ const snapshot = structuredClone(raw);
110
+ const endedAt = Date.now();
111
+ snapshot.phase = "aborted";
112
+ snapshot.endedAt = endedAt;
113
+ snapshot.updatedAt = endedAt;
114
+ if (reason) snapshot.lastError = reason;
115
+
116
+ for (const task of snapshot.tasks ?? []) {
117
+ if (!task || typeof task !== "object") continue;
118
+ const status = String(/** @type {{ status?: string }} */ (task).status ?? "");
119
+ if (status === "running" || status === "pending") {
120
+ /** @type {{ status: string, endedAt: number, exitReason: string }} */ (task).status = "aborted";
121
+ /** @type {{ endedAt?: number }} */ (task).endedAt =
122
+ /** @type {{ endedAt?: number }} */ (task).endedAt ?? endedAt;
123
+ /** @type {{ exitReason?: string }} */ (task).exitReason = "aborted";
124
+ }
125
+ }
126
+
127
+ for (const segment of snapshot.segments ?? []) {
128
+ if (!segment || typeof segment !== "object") continue;
129
+ const status = String(/** @type {{ status?: string }} */ (segment).status ?? "");
130
+ if (status === "running" || status === "pending") {
131
+ /** @type {{ status: string }} */ (segment).status = "aborted";
132
+ }
133
+ }
134
+
135
+ return snapshot;
136
+ }
137
+
138
+ /**
139
+ * @param {object} ctx
140
+ * @param {string} ctx.projectRoot
141
+ * @param {boolean} [ctx.hard]
142
+ * @param {string|null} [ctx.reason]
143
+ * @param {string|null} [ctx.batchId]
144
+ * @param {string|null} [ctx.batchStatePath]
145
+ */
146
+ export function abortBatch(ctx) {
147
+ const { projectRoot, hard = false, reason = null } = ctx;
148
+ const loaded = loadBatchStateFile(projectRoot, ctx.batchStatePath ?? null);
149
+
150
+ if (!loaded.path || !loaded.raw) {
151
+ return {
152
+ ok: false,
153
+ exitCode: 1,
154
+ headline: "No active batch to abort",
155
+ suggestedCommand: "spine preflight",
156
+ alternatives: ["spine status --diagnose"],
157
+ batchId: null,
158
+ };
159
+ }
160
+
161
+ if (loaded.parseError) {
162
+ return {
163
+ ok: false,
164
+ exitCode: 1,
165
+ error: loaded.parseError,
166
+ headline: `Cannot parse batch state: ${loaded.parseError}`,
167
+ suggestedCommand: "spine status --diagnose",
168
+ batchId: null,
169
+ };
170
+ }
171
+
172
+ const batchId = String(loaded.raw.batchId ?? loaded.raw.id ?? "").trim();
173
+ if (!batchId) {
174
+ return {
175
+ ok: false,
176
+ exitCode: 1,
177
+ error: "batch_id_missing",
178
+ headline: "Active batch state has no batchId",
179
+ suggestedCommand: "spine status --diagnose",
180
+ batchId: null,
181
+ };
182
+ }
183
+
184
+ if (ctx.batchId && ctx.batchId !== batchId) {
185
+ return {
186
+ ok: false,
187
+ exitCode: 1,
188
+ error: `Active batch is ${batchId}, not ${ctx.batchId}`,
189
+ headline: `Batch ID mismatch — active batch is ${batchId}`,
190
+ suggestedCommand: "spine status --diagnose",
191
+ batchId,
192
+ };
193
+ }
194
+
195
+ const snapshot = buildAbortedSnapshot(loaded.raw, reason);
196
+ writeAbortSignal(projectRoot, batchId, {
197
+ hard,
198
+ reason: reason ?? null,
199
+ requestedAt: new Date().toISOString(),
200
+ });
201
+
202
+ if (hard) {
203
+ killLaneWorkers(snapshot.lanes, true);
204
+ }
205
+
206
+ const archivePath = writeBatchArchive(projectRoot, batchId, snapshot);
207
+
208
+ const eventsBefore = readJournalEvents(projectRoot, batchId);
209
+ const journalTail = readJournalTail(eventsBefore);
210
+ appendJournalEvent(projectRoot, batchId, "batch.aborted", {
211
+ reason: reason ?? null,
212
+ hard,
213
+ archivePath: path.relative(projectRoot, archivePath),
214
+ journalEventsBeforeAbort: eventsBefore.length,
215
+ journalTailEventTypes: journalTail.map((event) => event.type),
216
+ });
217
+
218
+ const journalFile = journalPath(projectRoot, batchId);
219
+ if (!fs.existsSync(journalFile)) {
220
+ return {
221
+ ok: false,
222
+ exitCode: 1,
223
+ error: "journal_missing_after_abort",
224
+ headline: "Abort archived state but journal file is missing",
225
+ suggestedCommand: "spine status --diagnose",
226
+ batchId,
227
+ };
228
+ }
229
+
230
+ appendBatchHistoryEntry(projectRoot, {
231
+ batchId,
232
+ action: "aborted",
233
+ endedAt: snapshot.endedAt,
234
+ hard,
235
+ reason: reason ?? null,
236
+ archivePath: path.relative(projectRoot, archivePath),
237
+ });
238
+
239
+ if (hard) {
240
+ const configResult = loadSpineConfig(projectRoot);
241
+ if (shouldCleanupWorktreesOnHardAbort(configResult.config ?? {})) {
242
+ for (const lane of snapshot.lanes ?? []) {
243
+ const laneNumber = Number(
244
+ lane && typeof lane === "object"
245
+ ? /** @type {{ laneNumber?: number }} */ (lane).laneNumber
246
+ : 1,
247
+ );
248
+ try {
249
+ removeLaneWorktree(projectRoot, batchId, laneNumber || 1);
250
+ } catch {
251
+ // best-effort cleanup
252
+ }
253
+ }
254
+ }
255
+ }
256
+
257
+ clearActiveBatchState(loaded.path);
258
+
259
+ return {
260
+ ok: true,
261
+ exitCode: 0,
262
+ batchId,
263
+ diagnosis: "aborted",
264
+ hard,
265
+ headline: hard
266
+ ? `Batch ${batchId} hard-aborted and archived`
267
+ : `Batch ${batchId} aborted and archived`,
268
+ suggestedCommand: "spine preflight",
269
+ alternatives: ["spine batch dismiss", "spine status --diagnose"],
270
+ archivePath,
271
+ };
272
+ }