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,79 @@
1
+ import { loadBatchStateFile } from "../src/batch/reconcile.mjs";
2
+ import { generateBatchPostMortem } from "../src/batch/postmortem.mjs";
3
+ import { readJournalEvents, readJournalTail } from "../src/batch/journal.mjs";
4
+ import { reconcileBatch } from "../src/batch/reconcile.mjs";
5
+
6
+ /**
7
+ * @param {object} options
8
+ * @param {string} options.projectRoot
9
+ * @param {boolean} [options.diagnose]
10
+ * @param {boolean} [options.verbose]
11
+ * @param {boolean} [options.json]
12
+ */
13
+ export function runSpineStatus(options) {
14
+ const { projectRoot, diagnose = false, verbose = false, json = false } = options;
15
+ const result = reconcileBatch({ projectRoot, verbose: verbose || diagnose });
16
+
17
+ if (json) {
18
+ return {
19
+ exitCode: 0,
20
+ output: `${JSON.stringify(result, null, 2)}\n`,
21
+ };
22
+ }
23
+
24
+ const lines = ["", "Batch status", ""];
25
+
26
+ if (result.batchId) {
27
+ lines.push(` Batch: ${result.batchId}`);
28
+ }
29
+ if (result.phase) {
30
+ lines.push(` Phase: ${result.phase}`);
31
+ }
32
+ if (result.diagnosis) {
33
+ lines.push(` Diagnosis: ${result.diagnosis}`);
34
+ }
35
+
36
+ lines.push("", ` ${result.headline}`, "");
37
+ lines.push(` → ${result.suggestedCommand}`);
38
+
39
+ if (result.alternatives?.length) {
40
+ lines.push("", " Alternatives:");
41
+ for (const alt of result.alternatives) {
42
+ lines.push(` • ${alt}`);
43
+ }
44
+ }
45
+
46
+ if (diagnose && result.signals) {
47
+ lines.push("", " Signals:");
48
+ lines.push(` ${JSON.stringify(result.signals, null, 2).split("\n").join("\n ")}`);
49
+ }
50
+
51
+ if (diagnose && result.signals?.journalHints?.length) {
52
+ lines.push("", " Journal hints (tail):");
53
+ for (const hint of result.signals.journalHints) {
54
+ lines.push(` • ${hint.type} @ ${hint.timestamp}: ${hint.summary}`);
55
+ }
56
+ }
57
+
58
+ if (verbose && result.signals?.segments?.length) {
59
+ lines.push("", " Segment frontier:");
60
+ for (const segment of result.signals.segments) {
61
+ lines.push(` ${segment.segmentId}: ${segment.status} (${segment.classification})`);
62
+ }
63
+ }
64
+
65
+ if (verbose && result.batchId) {
66
+ const loaded = loadBatchStateFile(projectRoot, result.batchStatePath ?? null);
67
+ if (loaded.raw) {
68
+ const journalTail = readJournalTail(readJournalEvents(projectRoot, result.batchId));
69
+ const postMortem = generateBatchPostMortem(loaded.raw, journalTail, result, projectRoot);
70
+ lines.push("", " Post-mortem:", "");
71
+ for (const line of postMortem.split("\n")) {
72
+ lines.push(line ? ` ${line}` : "");
73
+ }
74
+ }
75
+ }
76
+
77
+ lines.push("");
78
+ return { exitCode: 0, output: lines.join("\n") };
79
+ }
@@ -0,0 +1,293 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * spine tasks
4
+ *
5
+ * FR-UXB-02: validate task PROMPT packets for a planner scope.
6
+ */
7
+
8
+ import { c, isCliEntrypoint, writeCommandResult } from './spine-cli/shared.mjs';
9
+ import { loadSpineConfig } from './spine-config.mjs';
10
+ import { resolveTasksRootPath } from '../src/config/env-overrides.mjs';
11
+ import {
12
+ collectPromptValidationFailure,
13
+ discoverTasks,
14
+ formatPromptValidationFailures,
15
+ loadDependenciesJson,
16
+ loadTaskPacket,
17
+ } from '../src/tasks/packet/index.mjs';
18
+ import { parseScope } from '../src/planner/scope.mjs';
19
+
20
+ /**
21
+ * @param {{ failures: Array<{ taskId: string, promptPath?: string, errors: string[] }>, totalCount: number, passedCount: number, failedCount: number, warningsByTask?: Array<{ taskId: string, warnings: string[] }> }} args
22
+ * @returns {string}
23
+ */
24
+ export function formatTasksValidateHuman({
25
+ failures,
26
+ totalCount,
27
+ passedCount,
28
+ failedCount,
29
+ warningsByTask = [],
30
+ }) {
31
+ const lines = [`Validated ${totalCount} task(s): ${passedCount} passed, ${failedCount} failed`];
32
+ if (warningsByTask.length > 0) {
33
+ lines.push('');
34
+ for (const entry of warningsByTask) {
35
+ lines.push(`${entry.taskId}:`);
36
+ for (const warning of entry.warnings) {
37
+ lines.push(` - warning: ${warning}`);
38
+ }
39
+ }
40
+ }
41
+ if (failures.length > 0) {
42
+ lines.push('');
43
+ lines.push(formatPromptValidationFailures(failures).trimEnd());
44
+ }
45
+ return lines.join('\n').trimEnd() + '\n';
46
+ }
47
+
48
+ /**
49
+ * @param {object} packet
50
+ * @param {{ taskId: string, folderName: string }} discoveredTask
51
+ * @param {{ tasks?: Record<string, string[]> }} depsJson
52
+ * @returns {string[]}
53
+ */
54
+ export function collectTaskAdvisoryWarnings(packet, discoveredTask, depsJson) {
55
+ /** @type {string[]} */
56
+ const warnings = [];
57
+
58
+ const headingTaskId = packet.prompt?.taskId;
59
+ if (headingTaskId && discoveredTask.taskId !== headingTaskId) {
60
+ warnings.push(
61
+ `Folder name task ID ${discoveredTask.taskId} does not match PROMPT heading ${headingTaskId}`,
62
+ );
63
+ }
64
+
65
+ if (!packet.statusPath) {
66
+ warnings.push('Missing STATUS.md');
67
+ }
68
+
69
+ const promptDeps = packet.prompt?.dependencies ?? [];
70
+ if (promptDeps.length > 0) {
71
+ const jsonDeps = depsJson?.tasks?.[discoveredTask.taskId];
72
+ if (!jsonDeps) {
73
+ warnings.push(
74
+ `PROMPT lists dependencies but ${discoveredTask.taskId} is missing from dependencies.json`,
75
+ );
76
+ } else {
77
+ const missing = promptDeps.filter((dep) => !jsonDeps.includes(dep));
78
+ if (missing.length > 0) {
79
+ warnings.push(
80
+ `PROMPT dependencies not in dependencies.json: ${missing.join(', ')}`,
81
+ );
82
+ }
83
+ }
84
+ }
85
+
86
+ return warnings;
87
+ }
88
+
89
+ /**
90
+ * @param {object} params
91
+ * @param {ReturnType<typeof parseScope>} params.scope
92
+ * @param {Array<{ taskId: string, ok: boolean, promptPath: string, errors: string[], warnings?: string[], contract?: { ok: boolean, errors: string[] } }>} params.tasks
93
+ * @returns {{ ok: boolean, scope: { mode: string, taskCount: number }, tasks: typeof params.tasks }}
94
+ */
95
+ export function buildTasksValidateResult({ scope, tasks }) {
96
+ return {
97
+ ok: tasks.every((task) => task.ok),
98
+ scope: {
99
+ mode: scope.mode,
100
+ taskCount: scope.taskIds.length,
101
+ },
102
+ tasks,
103
+ };
104
+ }
105
+
106
+ export function printTasksHelp() {
107
+ console.log(`
108
+ ${c.bold}spine tasks${c.reset} — validate task PROMPT packets (FR-UXB-02)
109
+
110
+ ${c.bold}Usage:${c.reset}
111
+ spine tasks validate <scope> [--json] [--warnings-only]
112
+
113
+ ${c.bold}Scope:${c.reset}
114
+ Same resolution as ${c.cyan}spine plan${c.reset}: all, pending, task IDs, globs.
115
+
116
+ ${c.bold}Options:${c.reset}
117
+ --json Emit TasksValidateResult JSON (handoff §6.4)
118
+ --warnings-only Include non-blocking P1 checks as warnings:
119
+ folder name ≠ heading ID, missing STATUS.md, deps mismatch
120
+
121
+ ${c.bold}Exit codes:${c.reset}
122
+ 0 all selected tasks pass
123
+ 1 one or more PROMPT validation failures
124
+ 2 config, tasksRoot, or scope resolution error
125
+
126
+ ${c.bold}Examples:${c.reset}
127
+ spine tasks validate all
128
+ spine tasks validate pending --warnings-only
129
+ spine tasks validate FX-101 --json
130
+ `);
131
+ }
132
+
133
+ /**
134
+ * @param {string} message
135
+ * @param {{ suggestedCommand?: string, exitCode?: number }} [options]
136
+ */
137
+ function throwTasksValidateError(message, { suggestedCommand, exitCode = 2 } = {}) {
138
+ const err = new Error(message);
139
+ if (suggestedCommand) err.suggestedCommand = suggestedCommand;
140
+ err.exitCode = exitCode;
141
+ throw err;
142
+ }
143
+
144
+ /**
145
+ * @param {{ projectRoot?: string, scope?: string, json?: boolean, warningsOnly?: boolean }} [args]
146
+ */
147
+ export async function runSpineTasksValidate({
148
+ projectRoot = process.cwd(),
149
+ scope = 'all',
150
+ json = false,
151
+ warningsOnly = false,
152
+ } = {}) {
153
+ const configResult = loadSpineConfig(projectRoot);
154
+ if (configResult.error) {
155
+ throwTasksValidateError(configResult.error.message, {
156
+ suggestedCommand: configResult.error.suggestedCommand,
157
+ });
158
+ }
159
+
160
+ const config = configResult.config;
161
+ const tasksRoot = resolveTasksRootPath(projectRoot, config);
162
+ if (!tasksRoot) {
163
+ throwTasksValidateError('Cannot validate tasks: tasksRoot not configured', {
164
+ suggestedCommand: 'spine init',
165
+ });
166
+ }
167
+
168
+ const discovered = discoverTasks(tasksRoot);
169
+ let scopeResult;
170
+ try {
171
+ scopeResult = parseScope(scope, { tasksRoot, discoveredTasks: discovered });
172
+ } catch (err) {
173
+ throwTasksValidateError(err?.message ?? String(err));
174
+ }
175
+
176
+ const depsJson = warningsOnly ? loadDependenciesJson(tasksRoot) : { tasks: {} };
177
+ const selectedTaskIds = new Set(scopeResult.taskIds);
178
+ /** @type {Array<{ taskId: string, promptPath?: string, errors: string[] }>} */
179
+ const failures = [];
180
+ /** @type {Array<{ taskId: string, ok: boolean, promptPath: string, errors: string[], warnings?: string[], contract?: { ok: boolean, errors: string[] } }>} */
181
+ const taskResults = [];
182
+ /** @type {Array<{ taskId: string, warnings: string[] }>} */
183
+ const warningsByTask = [];
184
+ let passedCount = 0;
185
+
186
+ for (const discoveredTask of discovered) {
187
+ const taskId = discoveredTask.taskId;
188
+ if (!selectedTaskIds.has(taskId)) continue;
189
+
190
+ const packet = loadTaskPacket(discoveredTask.folderPath, {
191
+ contract: config.contract,
192
+ });
193
+ const failure = collectPromptValidationFailure(packet, taskId);
194
+ /** @type {string[]} */
195
+ const warnings = warningsOnly
196
+ ? [
197
+ ...collectTaskAdvisoryWarnings(packet, discoveredTask, depsJson),
198
+ ...(packet.validation?.warnings ?? []),
199
+ ]
200
+ : [];
201
+
202
+ if (warnings.length > 0) {
203
+ warningsByTask.push({ taskId, warnings });
204
+ }
205
+
206
+ const contractErrors = packet.validation?.errors?.filter((error) =>
207
+ /contract/i.test(error),
208
+ );
209
+ const contract =
210
+ packet.validation?.contract?.hasSection || contractErrors?.length
211
+ ? {
212
+ ok: (contractErrors?.length ?? 0) === 0,
213
+ errors: contractErrors ?? [],
214
+ }
215
+ : undefined;
216
+
217
+ const taskResult = {
218
+ taskId,
219
+ ok: !failure,
220
+ promptPath: packet.promptPath,
221
+ errors: failure?.errors ?? [],
222
+ ...(warnings.length > 0 ? { warnings } : {}),
223
+ ...(contract ? { contract } : {}),
224
+ };
225
+ taskResults.push(taskResult);
226
+
227
+ if (failure) {
228
+ failures.push(failure);
229
+ } else {
230
+ passedCount += 1;
231
+ }
232
+ }
233
+
234
+ const totalCount = scopeResult.taskIds.length;
235
+ const failedCount = failures.length;
236
+ const validateResult = buildTasksValidateResult({ scope: scopeResult, tasks: taskResults });
237
+ const output = json
238
+ ? JSON.stringify(validateResult, null, 2) + '\n'
239
+ : formatTasksValidateHuman({
240
+ failures,
241
+ totalCount,
242
+ passedCount,
243
+ failedCount,
244
+ warningsByTask,
245
+ });
246
+
247
+ return {
248
+ scope: scopeResult,
249
+ failures,
250
+ result: validateResult,
251
+ output,
252
+ exitCode: failedCount > 0 ? 1 : 0,
253
+ };
254
+ }
255
+
256
+ /**
257
+ * @param {string[]} args
258
+ */
259
+ export async function handleTasks(args) {
260
+ const sub = args[0];
261
+ if (sub !== 'validate') {
262
+ const { die } = await import('./spine-cli/shared.mjs');
263
+ die(
264
+ `Unknown tasks subcommand: ${sub ?? '(none)'}\nRun ${c.cyan}spine help tasks${c.reset} for usage.`,
265
+ );
266
+ }
267
+
268
+ const json = args.includes('--json');
269
+ const warningsOnly = args.includes('--warnings-only');
270
+ const scope = args.filter((a) => !a.startsWith('--')).slice(1).join(' ') || 'all';
271
+
272
+ try {
273
+ const result = await runSpineTasksValidate({
274
+ projectRoot: process.cwd(),
275
+ scope,
276
+ json,
277
+ warningsOnly,
278
+ });
279
+ writeCommandResult(result);
280
+ } catch (err) {
281
+ const msg = err?.message ?? String(err);
282
+ if (err?.suggestedCommand) {
283
+ console.error(`Error: ${msg}\nSuggested: ${err.suggestedCommand}`);
284
+ } else {
285
+ console.error(`Error: ${msg}`);
286
+ }
287
+ process.exit(err?.exitCode ?? 2);
288
+ }
289
+ }
290
+
291
+ if (isCliEntrypoint(import.meta.url)) {
292
+ handleTasks(process.argv.slice(2));
293
+ }
@@ -0,0 +1,314 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Worker runner invoked by spine engine in lane worktree.
4
+ * --stub: create .DONE for CI / tests when pi is unavailable.
5
+ * --pi: run `pi -p` with task PROMPT unless SPINE_WORKER_PI_AGENT=0.
6
+ *
7
+ * Batch context env (set by worker-host.mjs, inherited by pi child):
8
+ * SPINE_TASK_FOLDER — absolute path to taskplane-tasks/TP-NNN-…/
9
+ * SPINE_WORKTREE — lane git worktree root
10
+ * SPINE_PROJECT_ROOT — pi-spine project root (journal + gate paths)
11
+ * SPINE_BATCH_ID — active batch id
12
+ * SPINE_TASK_ID — e.g. TP-038
13
+ * SPINE_LANE_NUMBER — 1-based lane index
14
+ * SPINE_LANE_ID — optional alias (falls back to lane number in CLIs)
15
+ * SPINE_LANE_CORRELATION_ID — journal correlation id for this lane run
16
+ * SPINE_JOURNAL_ATTACH — "1" when batch journal writes are enabled
17
+ */
18
+
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import { spawnSync } from "node:child_process";
22
+ import {
23
+ assertReviewToolAvailable,
24
+ readReviewLevel,
25
+ resolveBatchJournalContext,
26
+ runStepReview,
27
+ } from "../src/batch/review.mjs";
28
+ import { reportTaskProgress } from "../src/worker-tools/report-progress.mjs";
29
+ import { isCliEntrypoint } from "./spine-cli/shared.mjs";
30
+ import { loadSpineConfig } from "./spine-config.mjs";
31
+ import { buildWorkerTailPrompt, taskIdFromFolder } from "../src/batch/worker-prompt.mjs";
32
+ import { parsePrompt } from "../src/tasks/packet/parse-prompt.mjs";
33
+
34
+ function buildReviewJournal() {
35
+ return resolveBatchJournalContext();
36
+ }
37
+
38
+ /**
39
+ * Append worker model/thinking flags from spine-config (mirrors reviewer spawn in review.mjs).
40
+ *
41
+ * @param {string[]} piArgs
42
+ * @param {object} [config]
43
+ */
44
+ export function appendWorkerAgentModelArgs(piArgs, config = {}) {
45
+ const workerModel = config?.agents?.worker?.model;
46
+ const workerThinking = config?.agents?.worker?.thinking;
47
+ if (workerModel && workerModel !== "inherit") {
48
+ piArgs.push("--model", workerModel);
49
+ }
50
+ if (workerThinking && workerThinking !== "off") {
51
+ piArgs.push("--thinking", workerThinking);
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Build argv for `pi -p` worker spawn (exported for unit tests).
57
+ *
58
+ * @param {object} options
59
+ * @param {string|null|undefined} options.worktreePath
60
+ * @param {string} options.taskFolder
61
+ * @param {string} options.donePath
62
+ * @param {object} [options.spineConfig]
63
+ * @param {ReturnType<typeof resolveBatchJournalContext>} [options.journal]
64
+ * @returns {Promise<string[]>}
65
+ */
66
+ export async function buildWorkerPiArgs({
67
+ worktreePath,
68
+ taskFolder,
69
+ donePath,
70
+ spineConfig = {},
71
+ journal = buildReviewJournal(),
72
+ }) {
73
+ const promptPath = path.join(taskFolder, "PROMPT.md");
74
+ const workerAgentPath = worktreePath
75
+ ? path.join(worktreePath, ".spine", "agents", "worker.md")
76
+ : null;
77
+
78
+ const piArgs = ["-p", "--no-session"];
79
+ if (workerAgentPath && fs.existsSync(workerAgentPath)) {
80
+ piArgs.push("--append-system-prompt", workerAgentPath);
81
+ }
82
+ if (fs.existsSync(promptPath)) {
83
+ piArgs.push(`@${promptPath}`);
84
+ }
85
+ appendWorkerAgentModelArgs(piArgs, spineConfig);
86
+ const projectRoot = process.env.SPINE_PROJECT_ROOT || worktreePath || process.cwd();
87
+ const taskFileScope = resolveTaskFileScope(taskFolder);
88
+ const tailPrompt = await buildWorkerTailPrompt({
89
+ worktreePath,
90
+ taskFolder,
91
+ donePath,
92
+ taskIdHint: taskIdFromFolder(taskFolder),
93
+ reviewLevel: readReviewLevel(taskFolder),
94
+ includePromptInclude: false,
95
+ config: spineConfig,
96
+ projectRoot,
97
+ taskFileScope,
98
+ journal,
99
+ });
100
+ piArgs.push(tailPrompt);
101
+ return piArgs;
102
+ }
103
+
104
+ /**
105
+ * @param {string} taskFolder
106
+ * @returns {string[]}
107
+ */
108
+ function resolveTaskFileScope(taskFolder) {
109
+ const envScope = process.env.SPINE_TASK_FILE_SCOPE;
110
+ if (envScope) {
111
+ try {
112
+ const parsed = JSON.parse(envScope);
113
+ if (Array.isArray(parsed)) {
114
+ return parsed.filter((entry) => typeof entry === "string");
115
+ }
116
+ } catch {
117
+ /* fall through to PROMPT parse */
118
+ }
119
+ }
120
+
121
+ const promptPath = path.join(taskFolder, "PROMPT.md");
122
+ if (!fs.existsSync(promptPath)) {
123
+ return [];
124
+ }
125
+ return parsePrompt(fs.readFileSync(promptPath, "utf-8")).fileScope ?? [];
126
+ }
127
+
128
+ function enforceStubReviewIfConfigured(taskFolder, worktreePath) {
129
+ if (process.env.SPINE_WORKER_STUB_ENFORCE_REVIEW !== "1") return;
130
+ if (readReviewLevel(taskFolder) <= 0) return;
131
+
132
+ const reviewResult = runStepReview({
133
+ taskFolder,
134
+ worktreePath: worktreePath || process.cwd(),
135
+ stepNumber: Number(process.env.SPINE_WORKER_STUB_REVIEW_STEP || 1),
136
+ reviewType: process.env.SPINE_WORKER_STUB_REVIEW_TYPE === "code" ? "code" : "plan",
137
+ stub: true,
138
+ journal: buildReviewJournal(),
139
+ });
140
+
141
+ if (!reviewResult.ok) {
142
+ console.error(reviewResult.error ?? `review failed: ${reviewResult.verdict ?? "spawn"}`);
143
+ process.exit(reviewResult.exitCode ?? 1);
144
+ }
145
+ }
146
+
147
+ async function runWorkerRunner() {
148
+ const taskFolder = process.env.SPINE_TASK_FOLDER;
149
+ const worktreePath = process.env.SPINE_WORKTREE;
150
+ if (!taskFolder) {
151
+ console.error("SPINE_TASK_FOLDER required");
152
+ process.exit(1);
153
+ }
154
+
155
+ const reviewGate = assertReviewToolAvailable({ taskFolder });
156
+ if (!reviewGate.ok) {
157
+ console.error(reviewGate.error);
158
+ process.exit(1);
159
+ }
160
+
161
+ const mode = process.argv.includes("--stub") ? "stub" : "pi";
162
+
163
+ if (mode === "stub") {
164
+ const taskIdFromFolder = path.basename(taskFolder).match(/^([A-Z]+-\d+)/)?.[1] ?? "";
165
+ const failTasks = String(process.env.SPINE_WORKER_STUB_FAIL_TASKS ?? "")
166
+ .split(/[,\s]+/)
167
+ .filter(Boolean);
168
+ if (failTasks.includes(taskIdFromFolder)) {
169
+ const dirtyRel = process.env.SPINE_WORKER_STUB_DIRTY_FILE;
170
+ if (dirtyRel && worktreePath) {
171
+ const dirtyPath = path.join(worktreePath, dirtyRel);
172
+ fs.mkdirSync(path.dirname(dirtyPath), { recursive: true });
173
+ fs.writeFileSync(dirtyPath, `stub dirty ${new Date().toISOString()}\n`, "utf-8");
174
+ }
175
+ console.error(`stub worker forced failure for ${taskIdFromFolder}`);
176
+ process.exit(1);
177
+ }
178
+
179
+ if (process.env.SPINE_WORKER_STUB_SAT020 === "1") {
180
+ const journal = buildReviewJournal();
181
+ const laneNumber = Number(process.env.SPINE_LANE_NUMBER || 1);
182
+ const taskId = process.env.SPINE_TASK_ID || taskIdFromFolder;
183
+ const correlationId = process.env.SPINE_LANE_CORRELATION_ID;
184
+ // Let the host poll once before checkpoint signals land.
185
+ spawnSync("sleep", ["1"], { stdio: "ignore" });
186
+ if (journal?.projectRoot && journal?.batchId && taskId) {
187
+ for (const step of [0, 1]) {
188
+ reportTaskProgress({
189
+ projectRoot: journal.projectRoot,
190
+ batchId: journal.batchId,
191
+ taskId,
192
+ laneNumber,
193
+ step,
194
+ checkboxesComplete: step + 1,
195
+ checkboxesTotal: 2,
196
+ correlationId,
197
+ });
198
+ }
199
+ }
200
+ // Separate poll epochs: checkpoint progress first, then file-scope activity only.
201
+ spawnSync("sleep", ["4"], { stdio: "ignore" });
202
+ const scopeRel = process.env.SPINE_WORKER_STUB_FILE_SCOPE;
203
+ if (scopeRel && worktreePath) {
204
+ const scopePath = path.join(worktreePath, scopeRel);
205
+ fs.mkdirSync(path.dirname(scopePath), { recursive: true });
206
+ fs.writeFileSync(scopePath, `sat020 scope touch ${new Date().toISOString()}\n`, "utf-8");
207
+ }
208
+ spawnSync("sleep", ["10"], { stdio: "ignore" });
209
+ }
210
+
211
+ const delayMs = Number(process.env.SPINE_WORKER_STUB_DELAY_MS || 0);
212
+ const hangMs = Number(process.env.SPINE_WORKER_STUB_HANG_MS || 0);
213
+ if (process.env.SPINE_WORKER_STUB_OUTPUT) {
214
+ console.error(process.env.SPINE_WORKER_STUB_OUTPUT);
215
+ }
216
+ if (hangMs > 0 || process.env.SPINE_WORKER_STUB_SAT020 === "1") {
217
+ const effectiveHang =
218
+ hangMs > 0 ? hangMs : Number(process.env.SPINE_WORKER_STUB_SAT020_HANG_MS || 25_000);
219
+ const step = 100;
220
+ let elapsed = 0;
221
+ while (elapsed < effectiveHang) {
222
+ const slice = Math.min(step, effectiveHang - elapsed);
223
+ spawnSync("sleep", [String(slice / 1000)], { stdio: "ignore" });
224
+ elapsed += slice;
225
+ }
226
+ console.error("stub worker hang finished without .DONE");
227
+ process.exit(1);
228
+ }
229
+
230
+ if (delayMs > 0) {
231
+ const dirtyRel = process.env.SPINE_WORKER_STUB_DIRTY_FILE;
232
+ if (dirtyRel && worktreePath) {
233
+ const dirtyPath = path.join(worktreePath, dirtyRel);
234
+ fs.mkdirSync(path.dirname(dirtyPath), { recursive: true });
235
+ fs.writeFileSync(dirtyPath, `stub dirty ${new Date().toISOString()}\n`, "utf-8");
236
+ }
237
+ spawnSync("sleep", [String(delayMs / 1000)], { stdio: "ignore" });
238
+ }
239
+ if (process.env.SPINE_WORKER_STUB_TOUCH === "1" && worktreePath) {
240
+ fs.writeFileSync(
241
+ path.join(worktreePath, "stub-worker-touch.txt"),
242
+ `stub touch ${new Date().toISOString()}\n`,
243
+ "utf-8",
244
+ );
245
+ }
246
+
247
+ enforceStubReviewIfConfigured(taskFolder, worktreePath);
248
+
249
+ const donePath = path.join(taskFolder, ".DONE");
250
+ fs.writeFileSync(
251
+ donePath,
252
+ `Completed: ${new Date().toISOString()}\nTask: stub\n`,
253
+ "utf-8",
254
+ );
255
+ process.exit(0);
256
+ }
257
+
258
+ const version = spawnSync("pi", ["--version"], { encoding: "utf-8" });
259
+ if (version.status !== 0) {
260
+ console.error("pi not available:", version.stderr);
261
+ process.exit(1);
262
+ }
263
+
264
+ const donePath = path.join(taskFolder, ".DONE");
265
+ if (fs.existsSync(donePath)) {
266
+ process.exit(0);
267
+ }
268
+
269
+ if (process.env.SPINE_WORKER_PI_AGENT === "0") {
270
+ console.error(
271
+ "pi worker mode requires manual agent completion (.DONE in task folder). Set SPINE_WORKER_PI_AGENT=1 to run pi -p.",
272
+ );
273
+ process.exit(1);
274
+ }
275
+
276
+ const projectRoot = process.env.SPINE_PROJECT_ROOT || worktreePath || process.cwd();
277
+ const spineConfig = loadSpineConfig(projectRoot).config ?? {};
278
+ const piArgs = await buildWorkerPiArgs({
279
+ worktreePath,
280
+ taskFolder,
281
+ donePath,
282
+ spineConfig,
283
+ journal: buildReviewJournal(),
284
+ });
285
+
286
+ const timeoutMs = Number(process.env.SPINE_WORKER_PI_TIMEOUT_MS || 60 * 60 * 1000);
287
+ const result = spawnSync("pi", piArgs, {
288
+ cwd: worktreePath || process.cwd(),
289
+ encoding: "utf-8",
290
+ timeout: timeoutMs,
291
+ });
292
+
293
+ if (result.error?.code === "ETIMEDOUT") {
294
+ console.error("pi worker timed out");
295
+ process.exit(124);
296
+ }
297
+
298
+ if (result.status !== 0) {
299
+ process.stderr.write(result.stderr ?? "");
300
+ process.stdout.write(result.stdout ?? "");
301
+ process.exit(result.status ?? 1);
302
+ }
303
+
304
+ if (!fs.existsSync(donePath)) {
305
+ console.error("pi exited but .DONE was not created");
306
+ process.exit(1);
307
+ }
308
+
309
+ process.exit(0);
310
+ }
311
+
312
+ if (isCliEntrypoint(import.meta.url)) {
313
+ await runWorkerRunner();
314
+ }