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,1045 @@
1
+ /**
2
+ * Step review spawn + verdict parsing (FR-REV, GAP-REV-01).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { spawnSync } from "node:child_process";
8
+ import { fileURLToPath } from "node:url";
9
+ import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
10
+ import { loadSpineBatchState } from "./state.mjs";
11
+ import { buildReviewerContext } from "../config/reviewer-context.mjs";
12
+ import { resolveReviewScopePaths } from "./review-scope.mjs";
13
+
14
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
+ const PACKAGE_ROOT = path.resolve(__dirname, "../..");
16
+
17
+ /** Exit code from `spawnSync` when `timeout` elapses (SP-221/SP-249). */
18
+ export const REVIEW_SPAWN_TIMEOUT_EXIT_CODE = 124;
19
+
20
+ /** Default reviewer `pi` spawn timeout (90m); override with `SPINE_REVIEW_TIMEOUT_MS`. */
21
+ export const DEFAULT_REVIEW_SPAWN_TIMEOUT_MS = 90 * 60 * 1000;
22
+
23
+ export const REVIEW_LEVEL_RE = /^##\s+Review Level:\s*(\d+)/m;
24
+
25
+ /**
26
+ * @param {string} markdown
27
+ */
28
+ export function parseReviewLevel(markdown) {
29
+ const match = REVIEW_LEVEL_RE.exec(markdown);
30
+ return match ? Number.parseInt(match[1], 10) : 0;
31
+ }
32
+
33
+ /**
34
+ * @param {string} taskFolder
35
+ */
36
+ export function readReviewLevel(taskFolder) {
37
+ const promptPath = path.join(taskFolder, "PROMPT.md");
38
+ if (!fs.existsSync(promptPath)) return 0;
39
+ return parseReviewLevel(fs.readFileSync(promptPath, "utf-8"));
40
+ }
41
+
42
+ /**
43
+ * @param {number} reviewLevel
44
+ * @param {"plan"|"code"|"final"} reviewType
45
+ */
46
+ export function isReviewTypeRequired(reviewLevel, reviewType) {
47
+ if (reviewLevel <= 0) return false;
48
+ if (reviewType === "final") return reviewLevel >= 1;
49
+ if (reviewType === "plan") return reviewLevel >= 1;
50
+ return reviewLevel >= 2;
51
+ }
52
+
53
+ /**
54
+ * @param {Date} [date]
55
+ */
56
+ export function formatReviewTimestamp(date = new Date()) {
57
+ return date.toISOString().replace(/[-:]/g, "").replace(/\..+$/, "");
58
+ }
59
+
60
+ /**
61
+ * @param {string} taskFolder
62
+ * @param {number} stepNumber
63
+ * @param {Date} [date]
64
+ */
65
+ export function buildReviewArtifactPath(taskFolder, stepNumber, date = new Date()) {
66
+ return path.join(taskFolder, ".reviews", `${stepNumber}-${formatReviewTimestamp(date)}.md`);
67
+ }
68
+
69
+ /**
70
+ * @param {string} taskFolder
71
+ * @param {Date} [date]
72
+ */
73
+ export function buildFinalReviewArtifactPath(taskFolder, date = new Date()) {
74
+ return path.join(taskFolder, ".reviews", `final-${formatReviewTimestamp(date)}.md`);
75
+ }
76
+
77
+ /**
78
+ * Highest numbered ### Step N heading in PROMPT.md (defaults to 1).
79
+ * @param {string} taskFolder
80
+ */
81
+ export function findFinalReviewStepNumber(taskFolder) {
82
+ const promptPath = path.join(taskFolder, "PROMPT.md");
83
+ if (!fs.existsSync(promptPath)) return 1;
84
+ const content = fs.readFileSync(promptPath, "utf-8");
85
+ const matches = [...content.matchAll(/###\s+Step\s+(\d+)/g)];
86
+ if (matches.length === 0) return 1;
87
+ return Math.max(...matches.map((match) => Number(match[1])));
88
+ }
89
+
90
+ /**
91
+ * Step number containing a code review checkpoint blockquote, else highest step.
92
+ * @param {string} taskFolder
93
+ */
94
+ export function findCodeReviewStepNumber(taskFolder) {
95
+ const promptPath = path.join(taskFolder, "PROMPT.md");
96
+ if (!fs.existsSync(promptPath)) return findFinalReviewStepNumber(taskFolder);
97
+ const content = fs.readFileSync(promptPath, "utf-8");
98
+ const stepBlocks = [...content.matchAll(/###\s+Step\s+(\d+)[:\s][\s\S]*?(?=###\s+Step\s+\d+|$)/g)];
99
+ for (const match of stepBlocks) {
100
+ if (/code\s+review\s+checkpoint/i.test(match[0])) {
101
+ return Number(match[1]);
102
+ }
103
+ }
104
+ return findFinalReviewStepNumber(taskFolder);
105
+ }
106
+
107
+ /**
108
+ * Latest `.reviews/{stepNumber}-*.md` by mtime, if any.
109
+ * @param {string} taskFolder
110
+ * @param {number} stepNumber
111
+ * @returns {{ artifactPath: string, mtimeMs: number }|null}
112
+ */
113
+ export function findLatestStepReviewArtifact(taskFolder, stepNumber) {
114
+ const reviewsDir = path.join(taskFolder, ".reviews");
115
+ if (!fs.existsSync(reviewsDir)) return null;
116
+ const prefix = `${stepNumber}-`;
117
+ const candidates = fs
118
+ .readdirSync(reviewsDir)
119
+ .filter((name) => name.startsWith(prefix) && name.endsWith(".md"))
120
+ .map((name) => {
121
+ const artifactPath = path.join(reviewsDir, name);
122
+ return { artifactPath, mtimeMs: fs.statSync(artifactPath).mtimeMs };
123
+ })
124
+ .sort((left, right) => right.mtimeMs - left.mtimeMs);
125
+ return candidates[0] ?? null;
126
+ }
127
+
128
+ /**
129
+ * Resolve an existing worker or lane code review from journal and/or artifacts.
130
+ *
131
+ * @param {object} params
132
+ * @param {string} params.taskFolder
133
+ * @param {object[]} [params.journalEvents]
134
+ * @param {string} [params.taskId]
135
+ * @returns {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
136
+ */
137
+ export function findCompletedCodeReview({ taskFolder, journalEvents = [], taskId }) {
138
+ /** @type {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
139
+ let journalMatch = null;
140
+ for (let index = 0; index < journalEvents.length; index += 1) {
141
+ const event = journalEvents[index];
142
+ if (taskId && event.taskId !== taskId) continue;
143
+ if (event.type !== "review.completed") continue;
144
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
145
+ if (payload.reviewType !== "code") continue;
146
+ const verdict = normalizeVerdict(payload.verdict, "code");
147
+ if (!verdict) continue;
148
+ journalMatch = {
149
+ verdict,
150
+ feedback: typeof payload.feedback === "string" ? payload.feedback : "",
151
+ artifactPath: typeof payload.artifactPath === "string" ? payload.artifactPath : "",
152
+ source: "journal",
153
+ seq: index,
154
+ };
155
+ }
156
+
157
+ if (journalMatch?.verdict === "APPROVE") {
158
+ const { seq: _seq, ...result } = journalMatch;
159
+ return result;
160
+ }
161
+
162
+ const stepNumber = findCodeReviewStepNumber(taskFolder);
163
+ const latestArtifact = findLatestStepReviewArtifact(taskFolder, stepNumber);
164
+ if (latestArtifact) {
165
+ const reviewContent = fs.readFileSync(latestArtifact.artifactPath, "utf-8");
166
+ const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType: "code" });
167
+ if (verdict) {
168
+ const artifactMatch = {
169
+ verdict,
170
+ feedback,
171
+ artifactPath: latestArtifact.artifactPath,
172
+ source: /** @type {"artifact"} */ ("artifact"),
173
+ };
174
+ if (verdict === "APPROVE") return artifactMatch;
175
+ if (!journalMatch) return artifactMatch;
176
+ }
177
+ }
178
+
179
+ if (!journalMatch) return null;
180
+ const { seq: _seq, ...result } = journalMatch;
181
+ return result;
182
+ }
183
+
184
+ /**
185
+ * Latest `.reviews/final-*.md` by mtime, if any.
186
+ * @param {string} taskFolder
187
+ * @returns {{ artifactPath: string, mtimeMs: number }|null}
188
+ */
189
+ export function findLatestFinalReviewArtifact(taskFolder) {
190
+ const reviewsDir = path.join(taskFolder, ".reviews");
191
+ if (!fs.existsSync(reviewsDir)) return null;
192
+
193
+ const candidates = fs
194
+ .readdirSync(reviewsDir)
195
+ .filter((name) => name.startsWith("final-") && name.endsWith(".md"))
196
+ .map((name) => {
197
+ const artifactPath = path.join(reviewsDir, name);
198
+ return { artifactPath, mtimeMs: fs.statSync(artifactPath).mtimeMs };
199
+ })
200
+ .sort((left, right) => right.mtimeMs - left.mtimeMs);
201
+
202
+ return candidates[0] ?? null;
203
+ }
204
+
205
+ /**
206
+ * Resolve an existing worker or lane final review from journal and/or artifacts.
207
+ * Honors PASS from journal `review.completed` or latest final artifact.
208
+ *
209
+ * @param {object} params
210
+ * @param {string} params.taskFolder
211
+ * @param {object[]} [params.journalEvents]
212
+ * @param {string} [params.taskId]
213
+ * @returns {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
214
+ */
215
+ export function findCompletedFinalReview({ taskFolder, journalEvents = [], taskId }) {
216
+ /** @type {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
217
+ let journalMatch = null;
218
+ for (let index = 0; index < journalEvents.length; index += 1) {
219
+ const event = journalEvents[index];
220
+ if (taskId && event.taskId !== taskId) continue;
221
+ if (event.type !== "review.completed") continue;
222
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
223
+ if (payload.reviewType !== "final") continue;
224
+ const verdict = normalizeVerdict(payload.verdict, "final");
225
+ if (!verdict) continue;
226
+ journalMatch = {
227
+ verdict,
228
+ feedback: typeof payload.feedback === "string" ? payload.feedback : "",
229
+ artifactPath: typeof payload.artifactPath === "string" ? payload.artifactPath : "",
230
+ source: "journal",
231
+ seq: index,
232
+ };
233
+ }
234
+
235
+ if (journalMatch?.verdict === "PASS") {
236
+ const { seq: _seq, ...result } = journalMatch;
237
+ return result;
238
+ }
239
+
240
+ const latestArtifact = findLatestFinalReviewArtifact(taskFolder);
241
+ if (latestArtifact) {
242
+ const reviewContent = fs.readFileSync(latestArtifact.artifactPath, "utf-8");
243
+ const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType: "final" });
244
+ if (verdict) {
245
+ const artifactMatch = {
246
+ verdict,
247
+ feedback,
248
+ artifactPath: latestArtifact.artifactPath,
249
+ source: /** @type {"artifact"} */ ("artifact"),
250
+ };
251
+ if (verdict === "PASS") return artifactMatch;
252
+ if (!journalMatch) return artifactMatch;
253
+ }
254
+ }
255
+
256
+ if (!journalMatch) return null;
257
+ const { seq: _seq, ...result } = journalMatch;
258
+ return result;
259
+ }
260
+
261
+ /**
262
+ * @param {string} reviewContent
263
+ * @param {{ reviewType?: "plan"|"code"|"final" }} [options]
264
+ * @returns {{ verdict: "APPROVE"|"REVISE"|"PASS"|"REPLAN"|null, feedback: string }}
265
+ */
266
+ export function parseReviewVerdict(reviewContent, options = {}) {
267
+ const reviewType = options.reviewType ?? "code";
268
+ const isFinal = reviewType === "final";
269
+
270
+ const jsonMatch = reviewContent.match(/```json\s*\n([\s\S]*?)\n```/i);
271
+ if (jsonMatch) {
272
+ try {
273
+ const parsed = JSON.parse(jsonMatch[1]);
274
+ const verdict = normalizeVerdict(parsed.verdict, reviewType);
275
+ if (verdict) {
276
+ return {
277
+ verdict,
278
+ feedback: typeof parsed.feedback === "string" ? parsed.feedback : "",
279
+ };
280
+ }
281
+ } catch {
282
+ /* fall through */
283
+ }
284
+ }
285
+
286
+ const headingPattern = isFinal
287
+ ? /###?\s*Verdict[:\s]*(PASS|REVISE|REPLAN)/i
288
+ : /###?\s*Verdict[:\s]*(APPROVE|REVISE)/i;
289
+ const headingMatch = reviewContent.match(headingPattern);
290
+ if (headingMatch) {
291
+ return {
292
+ verdict: normalizeVerdict(headingMatch[1], reviewType),
293
+ feedback: extractSummary(reviewContent),
294
+ };
295
+ }
296
+
297
+ const lower = reviewContent.toLowerCase();
298
+ if (
299
+ lower.includes("changes requested") ||
300
+ lower.includes("request changes") ||
301
+ lower.includes("needs revision")
302
+ ) {
303
+ return { verdict: "REVISE", feedback: extractSummary(reviewContent) };
304
+ }
305
+ if (isFinal && (lower.includes("replan") || lower.includes("re-plan"))) {
306
+ return { verdict: "REPLAN", feedback: extractSummary(reviewContent) };
307
+ }
308
+ if (isFinal && lower.includes("pass") && !lower.includes("cannot pass") && !lower.includes("do not pass")) {
309
+ return { verdict: "PASS", feedback: extractSummary(reviewContent) };
310
+ }
311
+ if (lower.includes("approve") && !lower.includes("do not approve") && !lower.includes("cannot approve")) {
312
+ return { verdict: "APPROVE", feedback: extractSummary(reviewContent) };
313
+ }
314
+
315
+ return { verdict: null, feedback: extractSummary(reviewContent) };
316
+ }
317
+
318
+ /**
319
+ * @param {unknown} value
320
+ * @param {"plan"|"code"|"final"} [reviewType]
321
+ */
322
+ function normalizeVerdict(value, reviewType = "code") {
323
+ if (typeof value !== "string") return null;
324
+ const upper = value.trim().toUpperCase();
325
+ if (reviewType === "final") {
326
+ return upper === "PASS" || upper === "REVISE" || upper === "REPLAN" ? upper : null;
327
+ }
328
+ return upper === "APPROVE" || upper === "REVISE" ? upper : null;
329
+ }
330
+
331
+ /**
332
+ * @param {string} reviewContent
333
+ */
334
+ function extractSummary(reviewContent) {
335
+ const summaryMatch = reviewContent.match(/###?\s*Summary[:\s]*([\s\S]*?)(?=###|$)/i);
336
+ return summaryMatch ? summaryMatch[1].trim().slice(0, 500) : "";
337
+ }
338
+
339
+ /**
340
+ * @param {string} worktreePath
341
+ */
342
+ export function loadReviewerPrompt(worktreePath) {
343
+ const candidates = [
344
+ path.join(worktreePath, ".spine", "agents", "reviewer.md"),
345
+ path.join(PACKAGE_ROOT, "templates", "agents", "reviewer.md"),
346
+ ];
347
+ for (const candidate of candidates) {
348
+ if (!fs.existsSync(candidate)) continue;
349
+ const raw = fs.readFileSync(candidate, "utf-8");
350
+ const fmEnd = raw.indexOf("---", 4);
351
+ if (fmEnd > 0) return raw.slice(fmEnd + 3).trim();
352
+ return raw.trim();
353
+ }
354
+ return "You are a code reviewer. Write your review to the specified output file.";
355
+ }
356
+
357
+ /**
358
+ * Base reviewer agent prompt plus auto-selected Cursor rules (system prompt only).
359
+ *
360
+ * @param {object} params
361
+ * @param {string} params.worktreePath
362
+ * @param {string} params.taskFolder
363
+ * @param {"plan"|"code"|"final"} params.reviewType
364
+ * @param {string} [params.baseline]
365
+ * @param {object} [params.config]
366
+ * @param {object} [params.journal]
367
+ */
368
+ export function buildReviewerSystemPrompt({
369
+ worktreePath,
370
+ taskFolder,
371
+ reviewType,
372
+ baseline,
373
+ config = {},
374
+ journal,
375
+ }) {
376
+ let systemPrompt = loadReviewerPrompt(worktreePath);
377
+ const { scopePaths } = resolveReviewScopePaths({
378
+ worktreePath,
379
+ baseline,
380
+ reviewType,
381
+ taskFolder,
382
+ });
383
+ const reviewerContext = buildReviewerContext({
384
+ projectRoot: journal?.projectRoot ?? worktreePath ?? process.cwd(),
385
+ config,
386
+ reviewType,
387
+ scopePaths,
388
+ journal,
389
+ });
390
+ if (reviewerContext.text) {
391
+ systemPrompt = `${systemPrompt}${reviewerContext.text}`;
392
+ }
393
+ return systemPrompt;
394
+ }
395
+
396
+ /**
397
+ * @param {string} cmd
398
+ */
399
+ export function commandExists(cmd) {
400
+ if (process.env.SPINE_REVIEW_TEST_NO_PI === "1") return false;
401
+ try {
402
+ spawnSync("which", [cmd], { stdio: "ignore" });
403
+ return true;
404
+ } catch {
405
+ return false;
406
+ }
407
+ }
408
+
409
+ /**
410
+ * @param {object} params
411
+ */
412
+ export function buildReviewRequest({
413
+ reviewType,
414
+ stepNumber,
415
+ stepName,
416
+ taskFolder,
417
+ worktreePath,
418
+ outputPath,
419
+ baseline,
420
+ projectName = "project",
421
+ contractVerifyResult = null,
422
+ }) {
423
+ const promptPath = path.join(taskFolder, "PROMPT.md");
424
+ const statusPath = path.join(taskFolder, "STATUS.md");
425
+ if (reviewType === "final") {
426
+ const contractLines =
427
+ contractVerifyResult && Array.isArray(contractVerifyResult.checks)
428
+ ? [
429
+ "",
430
+ "## Contract verification",
431
+ `Machine verifier: ${contractVerifyResult.ok ? "PASS" : "FAIL"}`,
432
+ ...contractVerifyResult.checks.map(
433
+ (check) =>
434
+ `- ${check.ok ? "OK" : "FAIL"} ${check.field}: ${check.message}`,
435
+ ),
436
+ ]
437
+ : [];
438
+
439
+ return [
440
+ "# Review Request: Final Verdict",
441
+ "",
442
+ `You are performing a final verdict review for a ${projectName} task.`,
443
+ "",
444
+ "## Task Context",
445
+ `- **Task PROMPT:** ${promptPath}`,
446
+ `- **Task STATUS:** ${statusPath}`,
447
+ `- **Step completed:** Step ${stepNumber}: ${stepName}`,
448
+ `- **Worktree:** ${worktreePath}`,
449
+ "",
450
+ "## Instructions",
451
+ "Verify completion criteria and contract checks before returning a final verdict.",
452
+ ...contractLines,
453
+ "",
454
+ "## Output",
455
+ `Write your review to: \`${outputPath}\``,
456
+ "Include `### Verdict: PASS`, `### Verdict: REVISE`, or `### Verdict: REPLAN` and a JSON block.",
457
+ ].join("\n");
458
+ }
459
+ if (reviewType === "plan") {
460
+ return [
461
+ "# Review Request: Plan Review",
462
+ "",
463
+ `You are reviewing an implementation plan for a ${projectName} task.`,
464
+ "",
465
+ "## Task Context",
466
+ `- **Task PROMPT:** ${promptPath}`,
467
+ `- **Task STATUS:** ${statusPath}`,
468
+ `- **Step being planned:** Step ${stepNumber}: ${stepName}`,
469
+ `- **Worktree:** ${worktreePath}`,
470
+ "",
471
+ "## Output",
472
+ `Write your review to: \`${outputPath}\``,
473
+ "Include `### Verdict: APPROVE` or `### Verdict: REVISE` and a JSON block.",
474
+ ].join("\n");
475
+ }
476
+
477
+ const diffNamesCmd = baseline ? `git diff ${baseline}..HEAD --name-only` : "git diff --name-only";
478
+ const diffCmd = baseline ? `git diff ${baseline}..HEAD` : "git diff";
479
+
480
+ return [
481
+ "# Review Request: Code Review",
482
+ "",
483
+ `You are reviewing code changes for a ${projectName} task.`,
484
+ "",
485
+ "## Task Context",
486
+ `- **Task PROMPT:** ${promptPath}`,
487
+ `- **Step reviewed:** Step ${stepNumber}: ${stepName}`,
488
+ `- **Worktree:** ${worktreePath}`,
489
+ ...(baseline ? [`- **Baseline commit:** ${baseline}`] : []),
490
+ "",
491
+ "## Instructions",
492
+ `1. Run \`${diffNamesCmd}\` to see changed files`,
493
+ `2. Run \`${diffCmd}\` for the full diff`,
494
+ "",
495
+ "## Output",
496
+ `Write your review to: \`${outputPath}\``,
497
+ "Include `### Verdict: APPROVE` or `### Verdict: REVISE` and a JSON block.",
498
+ ].join("\n");
499
+ }
500
+
501
+ /**
502
+ * @param {string} taskFolder
503
+ * @param {number} stepNumber
504
+ */
505
+ export function findStepName(taskFolder, stepNumber) {
506
+ const promptPath = path.join(taskFolder, "PROMPT.md");
507
+ if (!fs.existsSync(promptPath)) return `Step ${stepNumber}`;
508
+ const content = fs.readFileSync(promptPath, "utf-8");
509
+ const re = new RegExp(`###\\s+Step\\s+${stepNumber}[:\\s]+(.+)`);
510
+ const match = content.match(re);
511
+ return match ? match[1].trim() : `Step ${stepNumber}`;
512
+ }
513
+
514
+ /**
515
+ * @param {object} params
516
+ */
517
+ function writeStubReviewArtifact({ artifactPath, reviewType, stepNumber, stepName, verdict, feedback }) {
518
+ fs.mkdirSync(path.dirname(artifactPath), { recursive: true });
519
+ const reviewLabel =
520
+ reviewType === "final" ? "Final" : reviewType === "plan" ? "Plan" : "Code";
521
+ const body = [
522
+ `## ${reviewLabel} Review: ${stepName}`,
523
+ "",
524
+ `### Verdict: ${verdict}`,
525
+ "",
526
+ "### Summary",
527
+ feedback || `Stub ${reviewType} review for step ${stepNumber}.`,
528
+ "",
529
+ "```json",
530
+ JSON.stringify({ verdict, feedback: feedback || "" }, null, 2),
531
+ "```",
532
+ "",
533
+ ].join("\n");
534
+ fs.writeFileSync(artifactPath, body, "utf-8");
535
+ }
536
+
537
+ /**
538
+ * @param {object} params
539
+ */
540
+ /**
541
+ * @param {object} journal
542
+ */
543
+ function isBatchJournalFrozen(journal) {
544
+ const loaded = loadSpineBatchState(journal.projectRoot);
545
+ if (!loaded.raw || loaded.raw.batchId !== journal.batchId) return false;
546
+ const phase = String(loaded.raw.phase ?? "");
547
+ return phase === "completed" || phase === "dismissed";
548
+ }
549
+
550
+ function journalReviewEvent(type, journal, payload) {
551
+ if (!journal?.projectRoot || !journal?.batchId) return;
552
+ if (type === "review.failed" && isBatchJournalFrozen(journal)) {
553
+ return;
554
+ }
555
+ appendJournalEvent(journal.projectRoot, journal.batchId, type, {
556
+ taskId: journal.taskId,
557
+ laneNumber: journal.laneNumber,
558
+ correlationId: journal.correlationId,
559
+ ...payload,
560
+ });
561
+ }
562
+
563
+ /**
564
+ * True when inherited worker batch env must not write to the live journal
565
+ * (e.g. npm test subprocess with SPINE_JOURNAL_ATTACH=1).
566
+ */
567
+ export function isJournalAttachBlocked() {
568
+ return process.env.SPINE_SUPPRESS_JOURNAL_ATTACH === "1";
569
+ }
570
+
571
+ /** Set by {@link buildWorkerChildEnv} when the batch engine launches a pi worker child. */
572
+ export function isActiveWorkerSession() {
573
+ const marker = process.env.SPINE_WORKER_RUNNER;
574
+ return typeof marker === "string" && marker.length > 0;
575
+ }
576
+
577
+ export const NESTED_REVIEW_SPAWN_BLOCKED =
578
+ "Nested reviewer spawn blocked inside pi worker session. Skip in-worker code review — the batch engine runs code review after worker success (SP-195).";
579
+
580
+ export const NESTED_REVIEW_SPAWN_REASON = "nested_spawn_blocked";
581
+
582
+ /**
583
+ * Resolve batch journal target from env only when the batch engine opts in.
584
+ * Prevents `npm test` (and other child processes) from polluting a live batch
585
+ * journal via inherited SPINE_BATCH_ID / SPINE_PROJECT_ROOT.
586
+ */
587
+ export function resolveBatchJournalContext() {
588
+ if (process.env.SPINE_JOURNAL_ATTACH !== "1") return undefined;
589
+ if (isJournalAttachBlocked()) return undefined;
590
+ const projectRoot = process.env.SPINE_PROJECT_ROOT;
591
+ const batchId = process.env.SPINE_BATCH_ID;
592
+ if (!projectRoot || !batchId) return undefined;
593
+
594
+ return {
595
+ projectRoot,
596
+ batchId,
597
+ taskId: process.env.SPINE_TASK_ID,
598
+ laneNumber: process.env.SPINE_LANE_NUMBER
599
+ ? Number(process.env.SPINE_LANE_NUMBER)
600
+ : undefined,
601
+ correlationId: process.env.SPINE_LANE_CORRELATION_ID,
602
+ };
603
+ }
604
+
605
+ /**
606
+ * @param {object} params
607
+ */
608
+ function spawnReviewerPi({ worktreePath, taskFolder, reviewPrompt, systemPrompt, config = {} }) {
609
+ if (isActiveWorkerSession()) {
610
+ return {
611
+ spawnFailed: true,
612
+ exitCode: 1,
613
+ error: NESTED_REVIEW_SPAWN_BLOCKED,
614
+ reason: NESTED_REVIEW_SPAWN_REASON,
615
+ };
616
+ }
617
+
618
+ if (!commandExists("pi")) {
619
+ return {
620
+ spawnFailed: true,
621
+ exitCode: 127,
622
+ error: "pi not available for reviewer spawn",
623
+ };
624
+ }
625
+
626
+ const reviewerAgentPath = path.join(worktreePath, ".spine", "agents", "reviewer.md");
627
+ const reviewerModel = config?.agents?.reviewer?.model;
628
+ const reviewerThinking = config?.agents?.reviewer?.thinking;
629
+
630
+ const piArgs = ["-p", "--no-session"];
631
+ if (reviewerAgentPath && fs.existsSync(reviewerAgentPath)) {
632
+ piArgs.push("--append-system-prompt", reviewerAgentPath);
633
+ }
634
+ if (systemPrompt) {
635
+ piArgs.push("--append-system-prompt", systemPrompt);
636
+ }
637
+ if (reviewerModel && reviewerModel !== "inherit") {
638
+ piArgs.push("--model", reviewerModel);
639
+ }
640
+ if (reviewerThinking && reviewerThinking !== "off") {
641
+ piArgs.push("--thinking", reviewerThinking);
642
+ }
643
+ piArgs.push(reviewPrompt);
644
+
645
+ const result = spawnSync("pi", piArgs, {
646
+ cwd: worktreePath || path.dirname(taskFolder),
647
+ encoding: "utf-8",
648
+ timeout: Number(process.env.SPINE_REVIEW_TIMEOUT_MS || DEFAULT_REVIEW_SPAWN_TIMEOUT_MS),
649
+ env: {
650
+ ...process.env,
651
+ SPINE_TASK_FOLDER: taskFolder,
652
+ SPINE_WORKTREE: worktreePath,
653
+ },
654
+ });
655
+
656
+ if (result.error?.code === "ETIMEDOUT") {
657
+ return { spawnFailed: true, exitCode: 124, error: "reviewer spawn timed out" };
658
+ }
659
+ if (result.status !== 0) {
660
+ return {
661
+ spawnFailed: true,
662
+ exitCode: result.status ?? 1,
663
+ error: result.stderr?.trim() || `reviewer exited with code ${result.status ?? 1}`,
664
+ };
665
+ }
666
+ return { spawnFailed: false, exitCode: 0, error: "" };
667
+ }
668
+
669
+ /**
670
+ * When reviewer `pi` times out but the worker already left `.DONE` (and contract
671
+ * passed for final review), honor the verdict instead of failing the task.
672
+ *
673
+ * @param {object} params
674
+ * @returns {ReturnType<typeof runStepReview> | null}
675
+ */
676
+ export function honorReviewSpawnFailureWhenEligible({
677
+ spawnResult,
678
+ reviewType,
679
+ taskFolder,
680
+ contractVerifyResult,
681
+ journal,
682
+ stepNumber,
683
+ reviewLevel,
684
+ }) {
685
+ if (!spawnResult?.spawnFailed) return null;
686
+ if (spawnResult.exitCode !== REVIEW_SPAWN_TIMEOUT_EXIT_CODE) return null;
687
+ if (!fs.existsSync(path.join(taskFolder, ".DONE"))) return null;
688
+
689
+ if (reviewType === "final" && contractVerifyResult && !contractVerifyResult.ok) {
690
+ return null;
691
+ }
692
+
693
+ const artifactPath =
694
+ reviewType === "final"
695
+ ? buildFinalReviewArtifactPath(taskFolder)
696
+ : buildReviewArtifactPath(taskFolder, stepNumber);
697
+ const verdict =
698
+ reviewType === "final"
699
+ ? contractVerifyResult?.ok === false
700
+ ? "REVISE"
701
+ : "PASS"
702
+ : "APPROVE";
703
+ const feedback =
704
+ reviewType === "final"
705
+ ? "Reviewer spawn timed out; honoring contract verification and worker .DONE."
706
+ : "Reviewer spawn timed out; honoring worker .DONE and proceeding.";
707
+
708
+ writeStubReviewArtifact({
709
+ artifactPath,
710
+ reviewType,
711
+ verdict,
712
+ feedback,
713
+ });
714
+
715
+ journalReviewEvent("review.completed", journal, {
716
+ stepNumber,
717
+ reviewType,
718
+ reviewLevel,
719
+ verdict,
720
+ artifactPath,
721
+ stub: true,
722
+ honored: true,
723
+ honorReason: "spawn_timeout_with_done",
724
+ });
725
+
726
+ const ok = reviewType === "final" ? verdict === "PASS" : verdict === "APPROVE";
727
+ return {
728
+ ok,
729
+ skipped: false,
730
+ honored: true,
731
+ honorReason: "spawn_timeout_with_done",
732
+ reviewLevel,
733
+ verdict,
734
+ feedback,
735
+ artifactPath,
736
+ spawnFailed: false,
737
+ exitCode: ok ? 0 : 2,
738
+ };
739
+ }
740
+
741
+ /**
742
+ * @param {object} params
743
+ */
744
+ export function runStepReview({
745
+ taskFolder,
746
+ worktreePath,
747
+ stepNumber,
748
+ reviewType = "plan",
749
+ baseline,
750
+ config = {},
751
+ journal,
752
+ stub,
753
+ stubVerdict = "APPROVE",
754
+ stubFail = false,
755
+ projectName,
756
+ contractVerifyResult = null,
757
+ }) {
758
+ const reviewLevel = readReviewLevel(taskFolder);
759
+ if (!isReviewTypeRequired(reviewLevel, reviewType)) {
760
+ return {
761
+ ok: true,
762
+ skipped: true,
763
+ reviewLevel,
764
+ verdict: null,
765
+ feedback: "",
766
+ artifactPath: "",
767
+ spawnFailed: false,
768
+ exitCode: 0,
769
+ };
770
+ }
771
+
772
+ if (reviewType === "final" && journal?.projectRoot && journal?.batchId) {
773
+ const honored = findCompletedFinalReview({
774
+ taskFolder,
775
+ journalEvents: readJournalEvents(journal.projectRoot, journal.batchId),
776
+ taskId: journal.taskId,
777
+ });
778
+ if (honored?.verdict === "PASS") {
779
+ return {
780
+ ok: true,
781
+ skipped: true,
782
+ honored: true,
783
+ honorSource: honored.source,
784
+ reviewLevel,
785
+ verdict: "PASS",
786
+ feedback: honored.feedback,
787
+ artifactPath: honored.artifactPath,
788
+ spawnFailed: false,
789
+ exitCode: 0,
790
+ };
791
+ }
792
+ }
793
+
794
+ const stepName = findStepName(taskFolder, stepNumber);
795
+ const artifactPath =
796
+ reviewType === "final"
797
+ ? buildFinalReviewArtifactPath(taskFolder)
798
+ : buildReviewArtifactPath(taskFolder, stepNumber);
799
+ const reviewPrompt = buildReviewRequest({
800
+ reviewType,
801
+ stepNumber,
802
+ stepName,
803
+ taskFolder,
804
+ worktreePath,
805
+ outputPath: artifactPath,
806
+ baseline,
807
+ projectName,
808
+ contractVerifyResult,
809
+ });
810
+
811
+ journalReviewEvent("review.started", journal, {
812
+ stepNumber,
813
+ reviewType,
814
+ reviewLevel,
815
+ artifactPath,
816
+ });
817
+
818
+ const useStub =
819
+ stub === true ||
820
+ stubFail === true ||
821
+ process.env.SPINE_REVIEW_STUB === "1" ||
822
+ process.env.SPINE_REVIEW_STUB === "true";
823
+
824
+ const stubFailRequested =
825
+ stubFail === true ||
826
+ (useStub &&
827
+ (process.env.SPINE_REVIEW_STUB === "1" ||
828
+ process.env.SPINE_REVIEW_STUB === "true") &&
829
+ (process.env.SPINE_REVIEW_STUB_FAIL === "1" ||
830
+ process.env.SPINE_REVIEW_STUB_FAIL === "true"));
831
+
832
+ if (useStub) {
833
+ if (stubFailRequested) {
834
+ const error = "review spawn failed (stub)";
835
+ journalReviewEvent("review.failed", journal, {
836
+ stepNumber,
837
+ reviewType,
838
+ reviewLevel,
839
+ error,
840
+ spawnFailed: true,
841
+ });
842
+ return {
843
+ ok: false,
844
+ skipped: false,
845
+ reviewLevel,
846
+ verdict: null,
847
+ feedback: "",
848
+ artifactPath,
849
+ spawnFailed: true,
850
+ error,
851
+ exitCode: 1,
852
+ };
853
+ }
854
+
855
+ const defaultVerdict = reviewType === "final" ? "PASS" : "APPROVE";
856
+ const verdict = normalizeVerdict(stubVerdict, reviewType) ?? defaultVerdict;
857
+ const feedback =
858
+ verdict === "REVISE"
859
+ ? "Stub reviewer requested changes."
860
+ : verdict === "REPLAN"
861
+ ? "Stub reviewer requested replan."
862
+ : reviewType === "final"
863
+ ? "Stub reviewer passed final verdict."
864
+ : "Stub reviewer approved.";
865
+ writeStubReviewArtifact({
866
+ artifactPath,
867
+ reviewType,
868
+ stepNumber,
869
+ stepName,
870
+ verdict,
871
+ feedback,
872
+ });
873
+
874
+ const ok = reviewType === "final" ? verdict === "PASS" : verdict === "APPROVE";
875
+ journalReviewEvent("review.completed", journal, {
876
+ stepNumber,
877
+ reviewType,
878
+ reviewLevel,
879
+ verdict,
880
+ artifactPath,
881
+ stub: true,
882
+ });
883
+
884
+ return {
885
+ ok,
886
+ skipped: false,
887
+ reviewLevel,
888
+ verdict,
889
+ feedback,
890
+ artifactPath,
891
+ spawnFailed: false,
892
+ exitCode: ok ? 0 : 2,
893
+ };
894
+ }
895
+
896
+ const systemPrompt = buildReviewerSystemPrompt({
897
+ worktreePath,
898
+ taskFolder,
899
+ reviewType,
900
+ baseline,
901
+ config,
902
+ journal,
903
+ });
904
+ const spawnResult = spawnReviewerPi({
905
+ worktreePath,
906
+ taskFolder,
907
+ reviewPrompt,
908
+ systemPrompt,
909
+ config,
910
+ });
911
+
912
+ if (spawnResult.spawnFailed) {
913
+ const honored = honorReviewSpawnFailureWhenEligible({
914
+ spawnResult,
915
+ reviewType,
916
+ taskFolder,
917
+ contractVerifyResult,
918
+ journal,
919
+ stepNumber,
920
+ reviewLevel,
921
+ });
922
+ if (honored) {
923
+ return honored;
924
+ }
925
+
926
+ journalReviewEvent("review.failed", journal, {
927
+ stepNumber,
928
+ reviewType,
929
+ reviewLevel,
930
+ error: spawnResult.error,
931
+ spawnFailed: true,
932
+ exitCode: spawnResult.exitCode,
933
+ ...(spawnResult.reason ? { reason: spawnResult.reason } : {}),
934
+ });
935
+ return {
936
+ ok: false,
937
+ skipped: false,
938
+ reviewLevel,
939
+ verdict: null,
940
+ feedback: "",
941
+ artifactPath,
942
+ spawnFailed: true,
943
+ error: spawnResult.error,
944
+ exitCode: spawnResult.exitCode ?? 1,
945
+ };
946
+ }
947
+
948
+ if (!fs.existsSync(artifactPath)) {
949
+ const error = "reviewer exited but produced no artifact";
950
+ journalReviewEvent("review.failed", journal, {
951
+ stepNumber,
952
+ reviewType,
953
+ reviewLevel,
954
+ error,
955
+ spawnFailed: true,
956
+ });
957
+ return {
958
+ ok: false,
959
+ skipped: false,
960
+ reviewLevel,
961
+ verdict: null,
962
+ feedback: "",
963
+ artifactPath,
964
+ spawnFailed: true,
965
+ error,
966
+ exitCode: 1,
967
+ };
968
+ }
969
+
970
+ const reviewContent = fs.readFileSync(artifactPath, "utf-8");
971
+ const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType });
972
+ if (!verdict) {
973
+ const error = "review artifact missing structured verdict";
974
+ journalReviewEvent("review.failed", journal, {
975
+ stepNumber,
976
+ reviewType,
977
+ reviewLevel,
978
+ error,
979
+ artifactPath,
980
+ });
981
+ return {
982
+ ok: false,
983
+ skipped: false,
984
+ reviewLevel,
985
+ verdict: null,
986
+ feedback,
987
+ artifactPath,
988
+ spawnFailed: false,
989
+ error,
990
+ exitCode: 1,
991
+ };
992
+ }
993
+
994
+ const ok = reviewType === "final" ? verdict === "PASS" : verdict === "APPROVE";
995
+ journalReviewEvent("review.completed", journal, {
996
+ stepNumber,
997
+ reviewType,
998
+ reviewLevel,
999
+ verdict,
1000
+ artifactPath,
1001
+ feedback,
1002
+ });
1003
+
1004
+ return {
1005
+ ok,
1006
+ skipped: false,
1007
+ reviewLevel,
1008
+ verdict,
1009
+ feedback,
1010
+ artifactPath,
1011
+ spawnFailed: false,
1012
+ exitCode: ok ? 0 : 2,
1013
+ };
1014
+ }
1015
+
1016
+ /**
1017
+ * @param {object} params
1018
+ */
1019
+ export function assertReviewToolAvailable({ taskFolder }) {
1020
+ const reviewLevel = readReviewLevel(taskFolder);
1021
+ if (reviewLevel <= 0) {
1022
+ return { ok: true, reviewLevel };
1023
+ }
1024
+
1025
+ const reviewScript = path.join(PACKAGE_ROOT, "bin", "spine-review-step.mjs");
1026
+ if (!fs.existsSync(reviewScript)) {
1027
+ return {
1028
+ ok: false,
1029
+ reviewLevel,
1030
+ error: `Review level ${reviewLevel} requires spine-review-step but ${reviewScript} is missing`,
1031
+ };
1032
+ }
1033
+
1034
+ const useStub =
1035
+ process.env.SPINE_REVIEW_STUB === "1" || process.env.SPINE_REVIEW_STUB === "true";
1036
+ if (!useStub && !commandExists("pi")) {
1037
+ return {
1038
+ ok: false,
1039
+ reviewLevel,
1040
+ error: `Review level ${reviewLevel} requires pi for reviewer spawn (fail closed, FR-REV-06)`,
1041
+ };
1042
+ }
1043
+
1044
+ return { ok: true, reviewLevel };
1045
+ }