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,210 @@
1
+ /**
2
+ * Orphan running batch detection (SP-082, FR-BATCH-12 extension).
3
+ */
4
+
5
+ import { isProcessAlive } from "../process/liveness.mjs";
6
+ import { readBatchEnginePid } from "./state.mjs";
7
+
8
+ /** @type {ReadonlySet<string>} */
9
+ export const TERMINAL_JOURNAL_TYPES = new Set([
10
+ "batch.completed",
11
+ "batch.failed",
12
+ "batch.aborted",
13
+ "task.failed",
14
+ "lane.died",
15
+ "lane.stall_killed",
16
+ ]);
17
+
18
+ /** Session-start events in the scoped post-resume window (SP-095, SP-111). */
19
+ /** @type {ReadonlySet<string>} */
20
+ export const SESSION_START_JOURNAL_TYPES = new Set(["batch.resumed", "task.started"]);
21
+
22
+ /**
23
+ * @param {object[]} events
24
+ */
25
+ export function journalHasTerminalBatchEvent(events) {
26
+ if (!Array.isArray(events) || events.length === 0) return false;
27
+ return events.some((event) => TERMINAL_JOURNAL_TYPES.has(String(event?.type ?? "")));
28
+ }
29
+
30
+ /**
31
+ * Scoped journal shows a resumed/started session with no terminal closure (SP-111).
32
+ *
33
+ * @param {object[]} events
34
+ */
35
+ export function journalIndicatesStalledSession(events) {
36
+ if (!Array.isArray(events) || events.length === 0) return false;
37
+ if (journalHasTerminalBatchEvent(events)) return false;
38
+ return events.some((event) => SESSION_START_JOURNAL_TYPES.has(String(event?.type ?? "")));
39
+ }
40
+
41
+ /**
42
+ * @param {unknown} event
43
+ * @returns {number|null}
44
+ */
45
+ function eventTimestampMs(event) {
46
+ if (!event || typeof event !== "object") return null;
47
+ const ts = /** @type {{ timestamp?: unknown }} */ (event).timestamp;
48
+ if (typeof ts === "number" && Number.isFinite(ts)) return ts;
49
+ if (typeof ts === "string") {
50
+ const parsed = Date.parse(ts);
51
+ return Number.isFinite(parsed) ? parsed : null;
52
+ }
53
+ return null;
54
+ }
55
+
56
+ /**
57
+ * @param {Record<string, unknown>|null|undefined} raw
58
+ * @returns {number|null}
59
+ */
60
+ function readEngineStartedAt(raw) {
61
+ if (!raw || typeof raw !== "object") return null;
62
+ const resilience = /** @type {Record<string, unknown>} */ (raw).resilience;
63
+ if (!resilience || typeof resilience !== "object") return null;
64
+ const startedAt = Number(/** @type {Record<string, unknown>} */ (resilience).engineStartedAt);
65
+ return Number.isFinite(startedAt) && startedAt > 0 ? startedAt : null;
66
+ }
67
+
68
+ /**
69
+ * Journal events for the current detached engine session only.
70
+ * Prefers the latest `batch.resumed`; otherwise filters from `engineStartedAt`.
71
+ *
72
+ * @param {object[]} events
73
+ * @param {Record<string, unknown>|null|undefined} [raw]
74
+ */
75
+ export function journalEventsSinceResume(events, raw) {
76
+ if (!Array.isArray(events) || events.length === 0) return [];
77
+
78
+ let resumeIndex = -1;
79
+ for (let i = events.length - 1; i >= 0; i--) {
80
+ if (String(events[i]?.type ?? "") === "batch.resumed") {
81
+ resumeIndex = i;
82
+ break;
83
+ }
84
+ }
85
+ if (resumeIndex >= 0) {
86
+ return events.slice(resumeIndex);
87
+ }
88
+
89
+ const engineStartedAt = readEngineStartedAt(raw);
90
+ if (engineStartedAt != null) {
91
+ return events.filter((event) => {
92
+ const ts = eventTimestampMs(event);
93
+ return ts == null || ts >= engineStartedAt;
94
+ });
95
+ }
96
+
97
+ return events;
98
+ }
99
+
100
+ /**
101
+ * Worker exited (post-done grace or natural exit) but engine still owns code/final review.
102
+ *
103
+ * @param {object[]} journalEvents
104
+ * @param {string} taskId
105
+ */
106
+ export function journalIndicatesEngineOwnedContinuation(journalEvents, taskId) {
107
+ if (!Array.isArray(journalEvents) || !taskId) return false;
108
+ return journalEvents.some(
109
+ (event) =>
110
+ String(event?.taskId ?? "") === taskId &&
111
+ String(event?.type ?? "") === "lane.completed",
112
+ );
113
+ }
114
+
115
+ /**
116
+ * @param {unknown[]} lanes
117
+ * @param {Array<{ laneNumber?: number|null }>} runningTasks
118
+ */
119
+ function hasFiniteWorkerPidForRunningTasks(lanes, runningTasks) {
120
+ for (const task of runningTasks) {
121
+ const lane = findLane(lanes, task.laneNumber);
122
+ const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane)?.workerPid);
123
+ if (Number.isFinite(workerPid) && workerPid > 0) return true;
124
+ }
125
+ return false;
126
+ }
127
+
128
+ /**
129
+ * @param {unknown[]} lanes
130
+ * @param {number|null|undefined} laneNumber
131
+ */
132
+ function findLane(lanes, laneNumber) {
133
+ if (!Array.isArray(lanes)) return null;
134
+ if (laneNumber != null) {
135
+ const match = lanes.find((lane) => Number(lane?.laneNumber) === Number(laneNumber));
136
+ if (match) return match;
137
+ }
138
+ return lanes[0] ?? null;
139
+ }
140
+
141
+ /**
142
+ * @typedef {object} OrphanRunningSignal
143
+ * @property {"lane"|"engine"} kind
144
+ * @property {string|null} taskId
145
+ * @property {number|null} [workerPid]
146
+ * @property {number|null} [enginePid]
147
+ */
148
+
149
+ /**
150
+ * @param {object} ctx
151
+ * @param {string} ctx.phase
152
+ * @param {boolean} ctx.hasRunningTasks
153
+ * @param {Array<{ taskId: string, classification: string, laneNumber?: number|null }>} ctx.tasks
154
+ * @param {unknown[]} ctx.lanes
155
+ * @param {Record<string, unknown>|null|undefined} ctx.raw
156
+ * @param {object[]} [ctx.journalEvents]
157
+ */
158
+ export function detectOrphanRunning(ctx) {
159
+ const runningTasks = (ctx.tasks ?? []).filter((task) => task.classification === "running");
160
+ if (ctx.phase !== "running" && !ctx.hasRunningTasks && runningTasks.length === 0) {
161
+ return null;
162
+ }
163
+
164
+ const scopedJournalEvents = journalEventsSinceResume(ctx.journalEvents ?? [], ctx.raw);
165
+
166
+ for (const task of runningTasks) {
167
+ const lane = findLane(ctx.lanes, task.laneNumber);
168
+ const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane)?.workerPid);
169
+ if (Number.isFinite(workerPid) && workerPid > 0 && !isProcessAlive(workerPid)) {
170
+ if (journalIndicatesEngineOwnedContinuation(scopedJournalEvents, task.taskId)) {
171
+ continue;
172
+ }
173
+ /** @type {OrphanRunningSignal} */
174
+ return {
175
+ kind: "lane",
176
+ taskId: task.taskId,
177
+ workerPid,
178
+ };
179
+ }
180
+ }
181
+
182
+ const enginePid = readBatchEnginePid(ctx.raw);
183
+ if (enginePid && !isProcessAlive(enginePid) && !journalHasTerminalBatchEvent(scopedJournalEvents)) {
184
+ /** @type {OrphanRunningSignal} */
185
+ return {
186
+ kind: "engine",
187
+ taskId: runningTasks[0]?.taskId ?? null,
188
+ enginePid,
189
+ };
190
+ }
191
+
192
+ const engineStartedAt = readEngineStartedAt(ctx.raw);
193
+ if (
194
+ ctx.phase === "running" &&
195
+ runningTasks.length > 0 &&
196
+ enginePid == null &&
197
+ !hasFiniteWorkerPidForRunningTasks(ctx.lanes, runningTasks) &&
198
+ engineStartedAt != null &&
199
+ journalIndicatesStalledSession(scopedJournalEvents)
200
+ ) {
201
+ /** @type {OrphanRunningSignal} */
202
+ return {
203
+ kind: "engine",
204
+ taskId: runningTasks[0]?.taskId ?? null,
205
+ enginePid: null,
206
+ };
207
+ }
208
+
209
+ return null;
210
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Post-merge limbo detection — merges done, tasks succeeded, phase still running (SP-204).
3
+ */
4
+
5
+ import { openIntegrateGateAfterBatchComplete } from "./gate.mjs";
6
+ import { appendJournalEvent } from "./journal.mjs";
7
+ import { saveSpineBatchState } from "./state.mjs";
8
+
9
+ /**
10
+ * @param {object|null|undefined} state
11
+ * @param {object} [git]
12
+ */
13
+ export function isPostMergeLimbo(state, git = {}) {
14
+ if (!state || typeof state !== "object") return false;
15
+ const phase = String(state.phase ?? "");
16
+ if (phase !== "running" || state.endedAt != null) return false;
17
+
18
+ const tasks = state.tasks ?? [];
19
+ if (tasks.length === 0) return false;
20
+ const allSucceeded = tasks.every((task) => String(task?.status ?? "") === "succeeded");
21
+ if (!allSucceeded) return false;
22
+
23
+ const mergeResults = state.mergeResults ?? [];
24
+ if (
25
+ mergeResults.length === 0 ||
26
+ !mergeResults.every((entry) => String(entry?.status ?? "") === "succeeded")
27
+ ) {
28
+ return false;
29
+ }
30
+
31
+ if (git.orchMergedToBase) return false;
32
+ if (git.orchBranchExists === false) return false;
33
+
34
+ return true;
35
+ }
36
+
37
+ /**
38
+ * Open integrate gate and mark batch completed (idempotent gate open).
39
+ *
40
+ * @param {object} params
41
+ */
42
+ export function finalizeResumedBatchForIntegrate({
43
+ projectRoot,
44
+ state,
45
+ batchId,
46
+ orchBranch,
47
+ resumeForced = false,
48
+ }) {
49
+ state.endedAt = Date.now();
50
+ openIntegrateGateAfterBatchComplete({
51
+ projectRoot,
52
+ batchId,
53
+ batchState: { ...state, phase: "completed" },
54
+ });
55
+ state.phase = "completed";
56
+ saveSpineBatchState(projectRoot, state);
57
+ appendJournalEvent(projectRoot, batchId, "batch.completed", {
58
+ taskIds: (state.tasks ?? []).map((task) => task.taskId),
59
+ mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
60
+ resumed: true,
61
+ postMergeLimbo: true,
62
+ resumeForced,
63
+ });
64
+
65
+ const taskIds = (state.tasks ?? []).map((task) => task.taskId);
66
+ const summaryTask =
67
+ taskIds.length === 1 ? taskIds[0] : `${taskIds.length} tasks (${taskIds.join(", ")})`;
68
+
69
+ return {
70
+ ok: true,
71
+ exitCode: 0,
72
+ batchId,
73
+ taskIds,
74
+ taskId: taskIds.length === 1 ? taskIds[0] : undefined,
75
+ mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
76
+ output:
77
+ `Batch ${batchId} resumed and completed: ${summaryTask} succeeded; merged to ${orchBranch}.\n` +
78
+ ` → spine gate approve\n → spine integrate\n → spine batch complete\n`,
79
+ };
80
+ }
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Honest batch post-mortem (NFR-OBS-03, GAP-POST-01).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { buildTaskScorecard } from "./evidence.mjs";
8
+ import { loadGateRecord, formatGateSummary } from "./gate.mjs";
9
+ import { readJournalEvents, readJournalTail, summarizeJournalEvent } from "./journal.mjs";
10
+ import { reconcileBatch } from "./reconcile.mjs";
11
+
12
+ const FAILURE_DIAGNOSES = new Set(["failed", "needs_retry"]);
13
+ const FALSE_SUCCESS_PATTERN = /ran smoothly|completed successfully/i;
14
+
15
+ /**
16
+ * @param {string} projectRoot
17
+ * @param {string} batchId
18
+ */
19
+ export function postMortemPath(projectRoot, batchId) {
20
+ return path.join(projectRoot, ".spine", "runtime", batchId, "post-mortem.md");
21
+ }
22
+
23
+ /**
24
+ * @param {string} batchId
25
+ */
26
+ export function postMortemRelPath(batchId) {
27
+ return path.join(".spine", "runtime", batchId, "post-mortem.md");
28
+ }
29
+
30
+ /**
31
+ * @param {object|null|undefined} batchState
32
+ */
33
+ export function countTaskOutcomes(batchState) {
34
+ const tasks = Array.isArray(batchState?.tasks) ? batchState.tasks : [];
35
+ let succeeded = 0;
36
+ let failed = 0;
37
+ let skipped = 0;
38
+ let other = 0;
39
+
40
+ for (const task of tasks) {
41
+ const status = String(task.status ?? "").toLowerCase();
42
+ if (status === "succeeded" || status === "completed" || status === "done") {
43
+ succeeded += 1;
44
+ } else if (status === "failed") {
45
+ failed += 1;
46
+ } else if (status === "skipped") {
47
+ skipped += 1;
48
+ } else {
49
+ other += 1;
50
+ }
51
+ }
52
+
53
+ return {
54
+ succeeded: Number(batchState?.succeededTasks ?? succeeded) || succeeded,
55
+ failed: Number(batchState?.failedTasks ?? failed) || failed,
56
+ skipped: Number(batchState?.skippedTasks ?? skipped) || skipped,
57
+ other,
58
+ total: Number(batchState?.totalTasks ?? tasks.length) || tasks.length,
59
+ };
60
+ }
61
+
62
+ /**
63
+ * @param {object|null|undefined} batchState
64
+ * @param {import("./reconcile.mjs").ReconciliationResult|null|undefined} reconciliation
65
+ * @returns {string[]}
66
+ */
67
+ export function listFailedTaskIds(batchState, reconciliation) {
68
+ const classified = reconciliation?.signals?.tasks;
69
+ if (Array.isArray(classified) && classified.length > 0) {
70
+ return classified
71
+ .filter((task) => task.classification === "terminal-failure")
72
+ .map((task) => task.taskId)
73
+ .filter(Boolean);
74
+ }
75
+
76
+ const tasks = Array.isArray(batchState?.tasks) ? batchState.tasks : [];
77
+ return tasks
78
+ .filter((task) => String(task.status ?? "").toLowerCase() === "failed")
79
+ .map((task) => task.taskId)
80
+ .filter(Boolean);
81
+ }
82
+
83
+ /**
84
+ * @param {import("./reconcile.mjs").ReconciliationResult|null|undefined} reconciliation
85
+ * @param {object|null|undefined} batchState
86
+ */
87
+ export function buildPostMortemHeadline(reconciliation, batchState) {
88
+ const failedTasks = Number(batchState?.failedTasks ?? 0);
89
+ const diagnosis = reconciliation?.diagnosis ?? null;
90
+ const failedIds = listFailedTaskIds(batchState, reconciliation);
91
+ const hasFailures =
92
+ failedTasks > 0 || FAILURE_DIAGNOSES.has(diagnosis ?? "") || failedIds.length > 0;
93
+
94
+ if (hasFailures) {
95
+ const batchLabel = batchState?.batchId ?? batchState?.id ?? reconciliation?.batchId ?? "Batch";
96
+ if (failedIds.length === 1) {
97
+ return `${batchLabel} has failed task ${failedIds[0]} — retry before resume`;
98
+ }
99
+ if (failedIds.length > 1) {
100
+ return `${batchLabel} has ${failedIds.length} failed tasks (${failedIds.join(", ")})`;
101
+ }
102
+ if (reconciliation?.headline && !FALSE_SUCCESS_PATTERN.test(reconciliation.headline)) {
103
+ return reconciliation.headline;
104
+ }
105
+ return `${batchLabel} has ${failedTasks || failedIds.length || 1} failed task(s)`;
106
+ }
107
+
108
+ if (reconciliation?.headline) return reconciliation.headline;
109
+
110
+ const batchLabel = batchState?.batchId ?? batchState?.id ?? "Batch";
111
+ return `${batchLabel} — see diagnosis below`;
112
+ }
113
+
114
+ /**
115
+ * @param {object|null|undefined} batchState
116
+ * @param {import("./reconcile.mjs").ReconciliationResult|null|undefined} reconciliation
117
+ */
118
+ export function describeMergeStatus(batchState, reconciliation) {
119
+ const mergeResults = Array.isArray(batchState?.mergeResults) ? batchState.mergeResults : [];
120
+ if (mergeResults.length === 0) {
121
+ if (reconciliation?.signals?.mergeResultsEmpty === false) {
122
+ return "merge results recorded (see batch state)";
123
+ }
124
+ return "not started (no merge results yet)";
125
+ }
126
+
127
+ const succeeded = mergeResults.filter((row) => String(row.status ?? "").toLowerCase() === "succeeded").length;
128
+ const failed = mergeResults.filter((row) => String(row.status ?? "").toLowerCase() === "failed").length;
129
+ const other = mergeResults.length - succeeded - failed;
130
+
131
+ const parts = [`${mergeResults.length} wave(s)`];
132
+ if (succeeded) parts.push(`${succeeded} succeeded`);
133
+ if (failed) parts.push(`${failed} failed`);
134
+ if (other) parts.push(`${other} other`);
135
+ return parts.join("; ");
136
+ }
137
+
138
+ /**
139
+ * @param {string} projectRoot
140
+ * @param {string|null|undefined} batchId
141
+ */
142
+ export function describeGateStatus(projectRoot, batchId) {
143
+ if (!batchId) return "no batch id";
144
+ const gate = loadGateRecord(projectRoot, batchId);
145
+ if (!gate) return "not opened";
146
+ return formatGateSummary(gate);
147
+ }
148
+
149
+ /**
150
+ * @param {object[]} journalTail
151
+ * @param {import("./reconcile.mjs").ReconciliationResult|null|undefined} reconciliation
152
+ */
153
+ export function describeIntegrateStatus(journalTail, reconciliation) {
154
+ const integrateEvent = [...journalTail]
155
+ .reverse()
156
+ .find((event) => String(event.type ?? "").startsWith("integrate."));
157
+
158
+ if (integrateEvent?.type === "integrate.completed") {
159
+ return "completed (journal)";
160
+ }
161
+ if (integrateEvent?.type === "integrate.failed") {
162
+ return `failed (journal): ${summarizeJournalEvent(integrateEvent)}`;
163
+ }
164
+ if (integrateEvent?.type === "integrate.started") {
165
+ return "in progress (journal)";
166
+ }
167
+
168
+ const git = reconciliation?.signals?.git;
169
+ if (git?.orchMergedToBase) {
170
+ return `orch merged to ${git.baseBranch ?? "base"} (${git.mergedOrchBranch ?? git.orchBranch ?? "orch"})`;
171
+ }
172
+ if (git?.orchBranchExists) {
173
+ const ahead = git.orchCommitsAhead;
174
+ if (ahead != null) return `orch branch ahead of base (${ahead} commit(s)) — integrate pending`;
175
+ return "orch branch exists — integrate pending";
176
+ }
177
+ return "no orch branch detected";
178
+ }
179
+
180
+ /**
181
+ * @param {object|null|undefined} batchState
182
+ * @param {object[]} journalTail
183
+ * @param {import("./reconcile.mjs").ReconciliationResult|null|undefined} reconciliation
184
+ * @param {string} [projectRoot]
185
+ */
186
+ export function generateBatchPostMortem(batchState, journalTail = [], reconciliation = null, projectRoot = "") {
187
+ const batchId = batchState?.batchId ?? batchState?.id ?? reconciliation?.batchId ?? "—";
188
+ const diagnosis = reconciliation?.diagnosis ?? "—";
189
+ const phase = batchState?.phase ?? reconciliation?.phase ?? "—";
190
+ const outcomes = countTaskOutcomes(batchState);
191
+ const failedIds = listFailedTaskIds(batchState, reconciliation);
192
+ const headline = buildPostMortemHeadline(reconciliation, batchState);
193
+ const suggested = reconciliation?.suggestedCommand ?? "spine status --diagnose";
194
+ const alternatives = reconciliation?.alternatives ?? [];
195
+
196
+ const lines = [
197
+ "# Batch post-mortem",
198
+ "",
199
+ `| Field | Value |`,
200
+ `|-------|-------|`,
201
+ `| Batch ID | ${batchId} |`,
202
+ `| Diagnosis | ${diagnosis} |`,
203
+ `| Phase | ${phase} |`,
204
+ `| Base branch | ${batchState?.baseBranch ?? "—"} |`,
205
+ `| Orch branch | ${batchState?.orchBranch ?? "—"} |`,
206
+ "",
207
+ "## Headline",
208
+ "",
209
+ headline,
210
+ "",
211
+ "## Task outcomes",
212
+ "",
213
+ `| Succeeded | Failed | Skipped | Total |`,
214
+ `|-----------|--------|---------|-------|`,
215
+ `| ${outcomes.succeeded} | ${outcomes.failed} | ${outcomes.skipped} | ${outcomes.total} |`,
216
+ "",
217
+ ];
218
+
219
+ if (failedIds.length > 0) {
220
+ lines.push("### Failed task IDs", "");
221
+ for (const taskId of failedIds) {
222
+ lines.push(`- ${taskId}`);
223
+ }
224
+ lines.push("");
225
+ }
226
+
227
+ lines.push("## Recovery", "", `**Suggested:** \`${suggested}\``, "");
228
+ if (alternatives.length > 0) {
229
+ lines.push("**Alternatives:**", "");
230
+ for (const alt of alternatives) {
231
+ lines.push(`- \`${alt}\``);
232
+ }
233
+ lines.push("");
234
+ }
235
+
236
+ if (failedIds.length > 0) {
237
+ const primaryFailed = failedIds[0];
238
+ lines.push(
239
+ `For mixed-outcome batches (incident I-05), retry failed tasks before resume: \`/spine-retry-task ${primaryFailed}\` then \`/spine-resume --force\`.`,
240
+ "",
241
+ );
242
+ }
243
+
244
+ lines.push(
245
+ "## Merge / gate / integrate",
246
+ "",
247
+ `- **Merge:** ${describeMergeStatus(batchState, reconciliation)}`,
248
+ `- **Gate:** ${projectRoot ? describeGateStatus(projectRoot, String(batchId)) : "unknown (no project root)"}`,
249
+ `- **Integrate:** ${describeIntegrateStatus(journalTail, reconciliation)}`,
250
+ "",
251
+ );
252
+
253
+ if (journalTail.length > 0) {
254
+ lines.push("## Journal (recent)", "");
255
+ const recent = journalTail.slice(-8);
256
+ for (const event of recent) {
257
+ lines.push(`- \`${event.type}\` @ ${event.timestamp}: ${summarizeJournalEvent(event)}`);
258
+ }
259
+ lines.push("");
260
+ }
261
+
262
+ const scorecard = buildTaskScorecard(batchState).replace(/^# Batch evidence summary\n\n/, "");
263
+ lines.push("## Task scorecard", "", scorecard.trimEnd(), "", "_Generated by pi-spine (TP-022, NFR-OBS-03)._", "");
264
+
265
+ return `${lines.join("\n")}\n`;
266
+ }
267
+
268
+ /**
269
+ * @param {object} ctx
270
+ * @param {string} ctx.projectRoot
271
+ * @param {object} ctx.batchState
272
+ * @param {import("./reconcile.mjs").ReconciliationResult} [ctx.reconciliation]
273
+ * @param {object[]} [ctx.journalTail]
274
+ */
275
+ export function writeBatchPostMortem(ctx) {
276
+ const { projectRoot, batchState } = ctx;
277
+ const batchId = String(batchState?.batchId ?? batchState?.id ?? "");
278
+ const reconciliation =
279
+ ctx.reconciliation ??
280
+ reconcileBatch({ projectRoot, batchState, verbose: true });
281
+ const journalTail =
282
+ ctx.journalTail ??
283
+ readJournalTail(readJournalEvents(projectRoot, batchId));
284
+
285
+ const markdown = generateBatchPostMortem(
286
+ batchState,
287
+ journalTail,
288
+ reconciliation,
289
+ projectRoot,
290
+ );
291
+ const filePath = postMortemPath(projectRoot, batchId);
292
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
293
+ fs.writeFileSync(filePath, markdown, "utf-8");
294
+
295
+ return postMortemRelPath(batchId);
296
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Parse pi-spine batch-state.json (schema v1, tolerant reader).
3
+ */
4
+
5
+ const TERMINAL_SUCCESS = new Set(["completed", "succeeded", "skipped"]);
6
+ const TERMINAL_FAILURE = new Set(["failed", "aborted"]);
7
+ const ACTIVE = new Set(["pending", "running"]);
8
+
9
+ /**
10
+ * @param {unknown} raw
11
+ * @returns {import("../reconcile.mjs").NormalizedBatchState | null}
12
+ */
13
+ export function parseSpineBatchState(raw) {
14
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
15
+
16
+ /** @type {Record<string, unknown>} */
17
+ const state = /** @type {Record<string, unknown>} */ (raw);
18
+ const batchId = String(state.batchId ?? state.id ?? "").trim();
19
+ if (!batchId) return null;
20
+
21
+ const tasks = normalizeTasks(state.tasks);
22
+ const segments = normalizeSegments(state.segments);
23
+
24
+ return {
25
+ source: "spine",
26
+ batchId,
27
+ phase: String(state.phase ?? state.status ?? "unknown"),
28
+ baseBranch: String(state.baseBranch ?? "main"),
29
+ orchBranch: state.orchBranch ? String(state.orchBranch) : null,
30
+ startedAt: state.startedAt ?? null,
31
+ endedAt: state.endedAt ?? null,
32
+ failedTasks: Number(state.failedTasks ?? 0),
33
+ succeededTasks: Number(state.succeededTasks ?? 0),
34
+ totalTasks: Number(state.totalTasks ?? tasks.length),
35
+ mergeResults: Array.isArray(state.mergeResults) ? state.mergeResults : [],
36
+ tasks,
37
+ segments,
38
+ lanes: Array.isArray(state.lanes) ? state.lanes : [],
39
+ raw: state,
40
+ };
41
+ }
42
+
43
+ /**
44
+ * @param {unknown} tasks
45
+ */
46
+ function normalizeTasks(tasks) {
47
+ if (!Array.isArray(tasks)) return [];
48
+
49
+ return tasks.map((entry) => {
50
+ /** @type {Record<string, unknown>} */
51
+ const task = entry && typeof entry === "object" ? /** @type {Record<string, unknown>} */ (entry) : {};
52
+ const status = String(task.status ?? "pending").toLowerCase();
53
+ return {
54
+ taskId: String(task.taskId ?? task.id ?? ""),
55
+ status,
56
+ taskFolder: task.taskFolder ? String(task.taskFolder) : null,
57
+ doneFileFound: Boolean(task.doneFileFound),
58
+ laneNumber: task.laneNumber ?? null,
59
+ startedAt: task.startedAt ?? null,
60
+ endedAt: task.endedAt ?? null,
61
+ classification: classifyStatus(status),
62
+ };
63
+ });
64
+ }
65
+
66
+ /**
67
+ * @param {unknown} segments
68
+ */
69
+ function normalizeSegments(segments) {
70
+ if (!Array.isArray(segments)) return [];
71
+
72
+ return segments.map((entry) => {
73
+ /** @type {Record<string, unknown>} */
74
+ const segment =
75
+ entry && typeof entry === "object" ? /** @type {Record<string, unknown>} */ (entry) : {};
76
+ const status = String(segment.status ?? "pending").toLowerCase();
77
+ return {
78
+ segmentId: String(segment.segmentId ?? segment.id ?? ""),
79
+ taskId: String(segment.taskId ?? ""),
80
+ status,
81
+ classification: classifyStatus(status),
82
+ };
83
+ });
84
+ }
85
+
86
+ /**
87
+ * @param {string} status
88
+ */
89
+ function classifyStatus(status) {
90
+ const normalized = String(status ?? "pending").toLowerCase();
91
+ if (TERMINAL_SUCCESS.has(normalized)) return "terminal-success";
92
+ if (TERMINAL_FAILURE.has(normalized)) return "terminal-failure";
93
+ if (ACTIVE.has(normalized)) return normalized === "running" ? "running" : "pending";
94
+ return "pending";
95
+ }