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,141 @@
1
+ /**
2
+ * spine deps — dependency graph inspection (FR-SCHED-01 subset).
3
+ */
4
+
5
+ import path from 'node:path';
6
+
7
+ import { resolveTasksRootPath } from '../config/env-overrides.mjs';
8
+ import {
9
+ discoverTasks,
10
+ loadDependenciesJson,
11
+ loadTaskPacket,
12
+ mergeTaskDeps,
13
+ } from '../tasks/packet/index.mjs';
14
+ import { buildGraph, topoWaves } from '../planner/graph.mjs';
15
+ import { findCyclePath } from '../planner/cycles.mjs';
16
+ import { parseScope } from '../planner/scope.mjs';
17
+
18
+ /**
19
+ * @param {string} projectRoot
20
+ * @param {string} scopeArg
21
+ * @param {{ config: { paths: { tasksRoot: string } } }} args
22
+ * @returns {{ mode: string, taskIds: string[] }}
23
+ */
24
+ export function resolveDepsScope(projectRoot, scopeArg, { config }) {
25
+ const tasksRoot = resolveTasksRootPath(projectRoot, config);
26
+ if (!tasksRoot) {
27
+ throw new Error('Cannot resolve tasks root');
28
+ }
29
+ const discovered = discoverTasks(tasksRoot);
30
+ return parseScope(scopeArg, { tasksRoot, discoveredTasks: discovered });
31
+ }
32
+
33
+ /**
34
+ * @param {Record<string, string[]>} depsByTask
35
+ * @returns {{ from: string, to: string }[]}
36
+ */
37
+ export function depsToEdges(depsByTask) {
38
+ /** @type {{ from: string, to: string }[]} */
39
+ const edges = [];
40
+
41
+ for (const [to, deps] of Object.entries(depsByTask)) {
42
+ for (const from of deps ?? []) {
43
+ edges.push({ from: String(from), to: String(to) });
44
+ }
45
+ }
46
+
47
+ edges.sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to));
48
+ return edges;
49
+ }
50
+
51
+ /**
52
+ * @param {string[] | null} cyclePath
53
+ * @returns {string[]}
54
+ */
55
+ export function cycleNodesFromPath(cyclePath) {
56
+ if (!cyclePath || cyclePath.length === 0) return [];
57
+ const nodes = cyclePath[cyclePath.length - 1] === cyclePath[0]
58
+ ? cyclePath.slice(0, -1)
59
+ : cyclePath;
60
+ return [...new Set(nodes.map(String))].sort();
61
+ }
62
+
63
+ /**
64
+ * @param {{ nodes: string[], edges: { from: string, to: string }[], cycles: string[][], waves?: string[][], scope?: { mode: string, taskIds: string[] } }} report
65
+ * @returns {string}
66
+ */
67
+ export function formatDepsHuman(report) {
68
+ const lines = [];
69
+ const mode = report.scope?.mode ?? 'custom';
70
+ lines.push(`\nSpine dependency graph (${mode})`);
71
+ lines.push(`Nodes: ${report.nodes.length}`);
72
+ lines.push('');
73
+
74
+ if (report.edges.length === 0) {
75
+ lines.push('(no dependency edges in scope)');
76
+ } else {
77
+ for (const { from, to } of report.edges) {
78
+ lines.push(`${from} → ${to}`);
79
+ }
80
+ }
81
+
82
+ if (report.cycles.length > 0) {
83
+ lines.push('');
84
+ for (const cycle of report.cycles) {
85
+ lines.push(`Cycle: ${cycle.join(' → ')}`);
86
+ }
87
+ }
88
+
89
+ return lines.join('\n').trimEnd() + '\n';
90
+ }
91
+
92
+ /**
93
+ * @param {{ projectRoot: string, scope?: string, config: { paths: { tasksRoot: string } } }} args
94
+ * @returns {{ nodes: string[], edges: { from: string, to: string }[], cycles: string[][], waves?: string[][], scope: ReturnType<typeof parseScope>, error?: string }}
95
+ */
96
+ export function buildDepsReport({ projectRoot, scope = 'all', config }) {
97
+ const tasksRoot = resolveTasksRootPath(projectRoot, config);
98
+ if (!tasksRoot) {
99
+ return { nodes: [], edges: [], cycles: [], scope: { mode: 'custom', taskIds: [] }, error: 'tasks root not configured' };
100
+ }
101
+ const discovered = discoverTasks(tasksRoot);
102
+ const scopeResult = parseScope(scope, { tasksRoot, discoveredTasks: discovered });
103
+ const selectedTaskIds = new Set(scopeResult.taskIds);
104
+ const depsJson = loadDependenciesJson(tasksRoot);
105
+
106
+ /** @type {Record<string, string[]>} */
107
+ const depsByTask = {};
108
+
109
+ for (const discoveredTask of discovered) {
110
+ const taskId = discoveredTask.taskId;
111
+ if (!selectedTaskIds.has(taskId)) continue;
112
+
113
+ const packet = loadTaskPacket(discoveredTask.folderPath);
114
+ const mergedDeps = mergeTaskDeps({ taskId, prompt: packet.prompt }, depsJson);
115
+ depsByTask[taskId] = mergedDeps.map(String);
116
+ }
117
+
118
+ const graph = buildGraph(depsByTask);
119
+ const edges = depsToEdges(graph.depsByTask);
120
+ const cyclePath = findCyclePath(graph);
121
+ const cycles = cyclePath ? [cyclePath] : [];
122
+ const { waves, remainingWithDeps } = topoWaves(graph);
123
+
124
+ /** @type {{ nodes: string[], edges: { from: string, to: string }[], cycles: string[][], waves?: string[][], scope: typeof scopeResult, error?: string }} */
125
+ const report = {
126
+ scope: scopeResult,
127
+ nodes: graph.nodes,
128
+ edges,
129
+ cycles,
130
+ };
131
+
132
+ if (cycles.length === 0 && remainingWithDeps.length === 0) {
133
+ report.waves = waves;
134
+ }
135
+
136
+ if (cycles.length > 0) {
137
+ report.error = `Dependency cycle detected: ${cyclePath.join(' -> ')}`;
138
+ }
139
+
140
+ return report;
141
+ }
@@ -0,0 +1,364 @@
1
+ /**
2
+ * Handoff data assembly and rendering (FR-UXB-05, §7.4).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ import { loadSpineConfig } from "../../bin/spine-config.mjs";
9
+ import { HANDOFF_DEFAULTS } from "../config/defaults.mjs";
10
+ import {
11
+ classifyTasks,
12
+ loadBatchStateFile,
13
+ parseBatchState,
14
+ reconcileBatch,
15
+ } from "../batch/reconcile.mjs";
16
+ import {
17
+ readJournalEvents,
18
+ readJournalTail,
19
+ redactSecrets,
20
+ } from "../batch/journal.mjs";
21
+ import { computePendingTasks } from "../batch/resume-multi-validate.mjs";
22
+ import { formatJournalTailEntry } from "../dashboard/snapshot.mjs";
23
+
24
+ const SECRET_VALUE_PATTERN =
25
+ /\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET)[A-Z0-9_]*\s*=\s*\S+|\b(sk-[A-Za-z0-9_-]{8,})\b/gi;
26
+
27
+ const JOURNAL_TAIL_LIMIT = 10;
28
+
29
+ /**
30
+ * @param {string} text
31
+ */
32
+ export function redactHandoffText(text) {
33
+ if (typeof text !== "string") return text;
34
+ return text.replace(SECRET_VALUE_PATTERN, "[REDACTED]");
35
+ }
36
+
37
+ /**
38
+ * @param {unknown} value
39
+ */
40
+ export function redactHandoffSecrets(value) {
41
+ if (value == null || typeof value !== "object") {
42
+ return typeof value === "string" ? redactHandoffText(value) : value;
43
+ }
44
+
45
+ if (Array.isArray(value)) {
46
+ return value.map((entry) => redactHandoffSecrets(entry));
47
+ }
48
+
49
+ const redacted = redactSecrets(value);
50
+ if (!redacted || typeof redacted !== "object") {
51
+ return typeof redacted === "string" ? redactHandoffText(redacted) : redacted;
52
+ }
53
+
54
+ /** @type {Record<string, unknown>} */
55
+ const out = {};
56
+ for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (redacted))) {
57
+ out[key] = redactHandoffSecrets(entry);
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /**
63
+ * @param {string} projectRoot
64
+ */
65
+ function resolveHandoffPath(projectRoot) {
66
+ const loaded = loadSpineConfig(projectRoot);
67
+ const configured = loaded.config?.handoff?.path;
68
+ return configured && typeof configured === "string" ? configured : HANDOFF_DEFAULTS.path;
69
+ }
70
+
71
+ /**
72
+ * @param {string} projectRoot
73
+ * @param {string} batchId
74
+ */
75
+ function loadArchivedBatchState(projectRoot, batchId) {
76
+ const archivePath = path.join(
77
+ projectRoot,
78
+ ".spine",
79
+ "runtime",
80
+ batchId,
81
+ "archive",
82
+ "batch-state.json",
83
+ );
84
+ if (!fs.existsSync(archivePath)) return null;
85
+ try {
86
+ const raw = JSON.parse(fs.readFileSync(archivePath, "utf-8"));
87
+ return { path: archivePath, raw, batchId };
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * @param {object[]} lanes
95
+ * @param {import("../batch/reconcile.mjs").NormalizedTask[]} classifiedTasks
96
+ */
97
+ function buildLaneSummary(lanes, classifiedTasks) {
98
+ return (lanes ?? []).map((lane) => {
99
+ const taskIds = lane.taskIds ?? [];
100
+ return redactSecrets({
101
+ laneNumber: lane.laneNumber,
102
+ laneId: lane.laneId ?? `lane-${lane.laneNumber}`,
103
+ taskIds,
104
+ tasks: taskIds.map((taskId) => {
105
+ const task = classifiedTasks.find((entry) => entry.taskId === taskId);
106
+ return {
107
+ taskId,
108
+ status: task?.status ?? "unknown",
109
+ classification: task?.classification ?? "unknown",
110
+ };
111
+ }),
112
+ });
113
+ });
114
+ }
115
+
116
+ /**
117
+ * @param {{ suggestedCommand?: string|null, alternatives?: string[] }} reconciliation
118
+ */
119
+ function buildRestoreCommands(reconciliation) {
120
+ const commands = [];
121
+ if (reconciliation.suggestedCommand) {
122
+ commands.push(reconciliation.suggestedCommand);
123
+ }
124
+ for (const alt of reconciliation.alternatives ?? []) {
125
+ if (alt && !commands.includes(alt)) commands.push(alt);
126
+ }
127
+ return commands;
128
+ }
129
+
130
+ /**
131
+ * @param {object[]} pendingTasks
132
+ */
133
+ function formatPendingTasks(pendingTasks) {
134
+ return pendingTasks.map((task) =>
135
+ redactSecrets({
136
+ taskId: task.taskId,
137
+ status: task.status ?? "pending",
138
+ taskFolder: task.taskFolder ?? null,
139
+ }),
140
+ );
141
+ }
142
+
143
+ /**
144
+ * Assemble structured handoff data from reconciliation, batch-state, and journal.
145
+ *
146
+ * @param {string} projectRoot
147
+ * @param {string} [batchId]
148
+ */
149
+ export function assembleHandoffData(projectRoot, batchId) {
150
+ const generatedAt = new Date().toISOString();
151
+ const reconciliation = reconcileBatch({ projectRoot, verbose: true });
152
+
153
+ if (!reconciliation.batchId && reconciliation.signals?.idle) {
154
+ return redactHandoffSecrets({
155
+ generatedAt,
156
+ batchId: null,
157
+ diagnosis: "idle",
158
+ headline: reconciliation.headline,
159
+ suggestedCommand: reconciliation.suggestedCommand,
160
+ alternatives: reconciliation.alternatives ?? [],
161
+ pendingTasks: [],
162
+ laneSummary: [],
163
+ journalTail: [],
164
+ restoreCommands: buildRestoreCommands(reconciliation),
165
+ idle: true,
166
+ handoffPath: resolveHandoffPath(projectRoot),
167
+ });
168
+ }
169
+
170
+ const effectiveBatchId = batchId ?? reconciliation.batchId;
171
+ let batch = null;
172
+ let batchStatePath = reconciliation.batchStatePath;
173
+
174
+ if (effectiveBatchId && effectiveBatchId !== reconciliation.batchId) {
175
+ const archived = loadArchivedBatchState(projectRoot, effectiveBatchId);
176
+ if (archived) {
177
+ batch = parseBatchState(archived.raw, archived.path);
178
+ batchStatePath = archived.path;
179
+ }
180
+ } else if (reconciliation.batchStatePath) {
181
+ const loaded = loadBatchStateFile(projectRoot, reconciliation.batchStatePath);
182
+ if (loaded.raw) {
183
+ batch = parseBatchState(loaded.raw, loaded.path ?? reconciliation.batchStatePath);
184
+ }
185
+ }
186
+
187
+ const classifiedTasks =
188
+ reconciliation.signals?.tasks ??
189
+ (batch ? classifyTasks(batch, null) : []);
190
+
191
+ const pendingTasks = batch
192
+ ? formatPendingTasks(computePendingTasks(batch.raw ?? /** @type {object} */ (batch)))
193
+ : [];
194
+ const laneSummary = buildLaneSummary(batch?.lanes ?? reconciliation.signals?.lanes ?? [], classifiedTasks);
195
+
196
+ let journalEvents = [];
197
+ if (effectiveBatchId) {
198
+ journalEvents = readJournalEvents(projectRoot, effectiveBatchId);
199
+ }
200
+ const journalTail = readJournalTail(journalEvents, JOURNAL_TAIL_LIMIT).map(formatJournalTailEntry);
201
+
202
+ const diagnosis = reconciliation.diagnosis ?? "idle";
203
+
204
+ return redactHandoffSecrets({
205
+ generatedAt,
206
+ batchId: effectiveBatchId ?? reconciliation.batchId ?? null,
207
+ diagnosis,
208
+ headline: reconciliation.headline,
209
+ suggestedCommand: reconciliation.suggestedCommand,
210
+ alternatives: reconciliation.alternatives ?? [],
211
+ pendingTasks,
212
+ laneSummary,
213
+ journalTail,
214
+ restoreCommands: buildRestoreCommands(reconciliation),
215
+ batchStatePath,
216
+ phase: reconciliation.phase ?? batch?.phase ?? null,
217
+ idle: diagnosis === "idle",
218
+ handoffPath: resolveHandoffPath(projectRoot),
219
+ });
220
+ }
221
+
222
+ /**
223
+ * @param {object[]} laneSummary
224
+ * @param {string} taskId
225
+ */
226
+ function findLaneNumber(laneSummary, taskId) {
227
+ for (const lane of laneSummary ?? []) {
228
+ if ((lane.taskIds ?? []).includes(taskId)) {
229
+ return lane.laneNumber ?? null;
230
+ }
231
+ }
232
+ return null;
233
+ }
234
+
235
+ /**
236
+ * @param {ReturnType<typeof assembleHandoffData>} data
237
+ */
238
+ export function renderHandoffMarkdown(data) {
239
+ const lines = [
240
+ "# pi-spine operator handoff",
241
+ "",
242
+ `**Generated at:** ${data.generatedAt}`,
243
+ `**Batch ID:** ${data.batchId ?? "—"}`,
244
+ "",
245
+ "## Diagnosis",
246
+ `**${data.diagnosis}** — ${data.headline}`,
247
+ "",
248
+ "## Suggested command",
249
+ data.suggestedCommand,
250
+ "",
251
+ "## Alternatives",
252
+ ];
253
+
254
+ if (data.alternatives?.length) {
255
+ for (const alt of data.alternatives) {
256
+ lines.push(`- ${alt}`);
257
+ }
258
+ } else {
259
+ lines.push("- (none)");
260
+ }
261
+
262
+ lines.push("", "## Pending tasks");
263
+ if (data.pendingTasks?.length) {
264
+ for (const task of data.pendingTasks) {
265
+ const laneNumber = findLaneNumber(data.laneSummary, task.taskId);
266
+ const laneLabel = laneNumber != null ? `lane ${laneNumber}` : "lane —";
267
+ lines.push(`- ${task.taskId} (${laneLabel}, ${task.status})`);
268
+ }
269
+ } else {
270
+ lines.push("- (none)");
271
+ }
272
+
273
+ lines.push("", "## Lane summary", "| Lane | Status | Tasks |", "|------|--------|-------|");
274
+ if (data.laneSummary?.length) {
275
+ for (const lane of data.laneSummary) {
276
+ const activeTasks = (lane.tasks ?? [])
277
+ .filter(
278
+ (task) =>
279
+ task.classification === "running" ||
280
+ task.classification === "pending" ||
281
+ task.status === "running" ||
282
+ task.status === "pending",
283
+ )
284
+ .map((task) => task.taskId);
285
+ const status =
286
+ activeTasks.length > 0
287
+ ? (lane.tasks ?? []).some(
288
+ (task) => task.status === "running" || task.classification === "running",
289
+ )
290
+ ? "running"
291
+ : "pending"
292
+ : "idle";
293
+ const tasksCell =
294
+ activeTasks.length > 0 ? activeTasks.join(", ") : (lane.taskIds ?? []).join(", ") || "—";
295
+ lines.push(`| ${lane.laneNumber ?? lane.laneId ?? "—"} | ${status} | ${tasksCell} |`);
296
+ }
297
+ } else if (data.pendingTasks?.length) {
298
+ for (const task of data.pendingTasks) {
299
+ lines.push(`| — | ${task.status} | ${task.taskId} |`);
300
+ }
301
+ } else {
302
+ lines.push("| — | — | — |");
303
+ }
304
+
305
+ lines.push("", "## Journal tail");
306
+ if (data.journalTail?.length) {
307
+ for (const entry of data.journalTail) {
308
+ const suffix = entry.taskId ? ` ${entry.taskId}` : entry.laneId ? ` ${entry.laneId}` : "";
309
+ lines.push(`- ${entry.timestamp} ${entry.type}${suffix}`);
310
+ }
311
+ } else {
312
+ lines.push("- (none)");
313
+ }
314
+
315
+ lines.push("", "## Restore");
316
+ if (data.restoreCommands?.length) {
317
+ data.restoreCommands.forEach((command, index) => {
318
+ lines.push(`${index + 1}. ${command}`);
319
+ });
320
+ } else {
321
+ lines.push("1. spine preflight");
322
+ }
323
+
324
+ lines.push("");
325
+ return redactHandoffText(lines.join("\n"));
326
+ }
327
+
328
+ /**
329
+ * @param {string[]} argv
330
+ */
331
+ export function parseHandoffArgs(argv) {
332
+ const args = { batchId: null, json: false };
333
+ for (let i = 0; i < argv.length; i++) {
334
+ const arg = argv[i];
335
+ if (arg === "--batch") args.batchId = argv[++i] ?? null;
336
+ else if (arg === "--json") args.json = true;
337
+ }
338
+ return args;
339
+ }
340
+
341
+ /**
342
+ * @param {object} options
343
+ * @param {string} options.projectRoot
344
+ * @param {string[]} [options.args]
345
+ */
346
+ export function runSpineHandoff(options) {
347
+ const { projectRoot, args: argv = [] } = options;
348
+ const args = parseHandoffArgs(argv);
349
+ const data = assembleHandoffData(projectRoot, args.batchId ?? undefined);
350
+ const handoffPath = path.resolve(projectRoot, data.handoffPath ?? resolveHandoffPath(projectRoot));
351
+ const markdown = renderHandoffMarkdown(data);
352
+
353
+ fs.mkdirSync(path.dirname(handoffPath), { recursive: true });
354
+ fs.writeFileSync(handoffPath, markdown, "utf-8");
355
+
356
+ if (args.json) {
357
+ return {
358
+ exitCode: 0,
359
+ output: `${JSON.stringify({ ...data, handoffPath: data.handoffPath ?? resolveHandoffPath(projectRoot) }, null, 2)}\n`,
360
+ };
361
+ }
362
+
363
+ return { exitCode: 0, output: `${markdown}\n` };
364
+ }