pi-spine 2.1.0 → 2.3.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 (49) hide show
  1. package/bin/spine-batch.mjs +74 -5
  2. package/bin/spine-cli/verify.mjs +2 -18
  3. package/package.json +1 -1
  4. package/src/batch/attached-runner-promote.mjs +370 -0
  5. package/src/batch/attached-runner-reconcile.mjs +291 -0
  6. package/src/batch/attached-runner.mjs +24 -634
  7. package/src/batch/batch-guards.mjs +69 -0
  8. package/src/batch/contract-exec.mjs +483 -0
  9. package/src/batch/contract-parse.mjs +243 -0
  10. package/src/batch/contract-verify.mjs +32 -707
  11. package/src/batch/detached-diagnostics.mjs +255 -0
  12. package/src/batch/detached-run.mjs +326 -0
  13. package/src/batch/detached-start.mjs +18 -894
  14. package/src/batch/detached-wait.mjs +346 -0
  15. package/src/batch/engine-lanes/merge.mjs +25 -0
  16. package/src/batch/engine.mjs +8 -67
  17. package/src/batch/integrate-git.mjs +21 -0
  18. package/src/batch/integrate.mjs +5 -15
  19. package/src/batch/journal-rebuild-structural.mjs +352 -0
  20. package/src/batch/journal-rebuild.mjs +94 -347
  21. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  22. package/src/batch/lane-dirty-check-git.mjs +298 -0
  23. package/src/batch/lane-dirty-check.mjs +31 -297
  24. package/src/batch/reconcile-batch.mjs +483 -0
  25. package/src/batch/reconcile-classify.mjs +433 -0
  26. package/src/batch/reconcile-diagnosis.mjs +459 -0
  27. package/src/batch/reconcile-light-cache.mjs +61 -0
  28. package/src/batch/reconcile-orphan.mjs +198 -0
  29. package/src/batch/reconcile.mjs +19 -1693
  30. package/src/batch/resume-multi-lanes.mjs +44 -149
  31. package/src/batch/resume-multi-queue.mjs +159 -0
  32. package/src/batch/resume-single-validate.mjs +25 -0
  33. package/src/batch/resume.mjs +3 -20
  34. package/src/batch/review-artifacts.mjs +419 -0
  35. package/src/batch/review-step-run.mjs +383 -0
  36. package/src/batch/review-step.mjs +451 -0
  37. package/src/batch/review.mjs +32 -1199
  38. package/src/batch/salvage-batch-list.mjs +291 -0
  39. package/src/batch/salvage-batch.mjs +417 -0
  40. package/src/batch/sequence-plan.mjs +234 -0
  41. package/src/batch/sequence-run.mjs +418 -0
  42. package/src/batch/sequence-wait.mjs +167 -0
  43. package/src/batch/sequence.mjs +22 -783
  44. package/src/batch/state-guards.mjs +284 -0
  45. package/src/batch/state-io.mjs +135 -0
  46. package/src/batch/state.mjs +27 -396
  47. package/src/batch/worker-heartbeat.mjs +375 -0
  48. package/src/batch/worker-host.mjs +50 -541
  49. package/src/batch/worker-spawn.mjs +315 -0
@@ -0,0 +1,451 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Step review helpers — spawn honor paths, prompts, journal attach (SP-597).
4
+ * runStepReview lives in review-step-run.mjs (salvage for #192 / SP-593).
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { appendJournalEvent } from "./journal.mjs";
11
+ import { loadSpineBatchState } from "./state.mjs";
12
+ import { buildReviewerContext } from "../config/reviewer-context.mjs";
13
+ import { resolveReviewScopePaths } from "./review-scope.mjs";
14
+ import { commandExists as pathCommandExists } from "../util/command-exists.mjs";
15
+ import {
16
+ ARTIFACT_READY_HONOR_REASON,
17
+ NESTED_REVIEW_SPAWN_BLOCKED,
18
+ NESTED_REVIEW_SPAWN_REASON,
19
+ REVIEW_SPAWN_TIMEOUT_EXIT_CODE,
20
+ } from "./review-spawn.mjs";
21
+ import {
22
+ buildFinalReviewArtifactPath,
23
+ buildReviewArtifactPath,
24
+ parseReviewVerdict,
25
+ } from "./review-shared.mjs";
26
+
27
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
28
+ const PACKAGE_ROOT = path.resolve(__dirname, "../..");
29
+
30
+ /**
31
+ * @param {string} worktreePath
32
+ */
33
+ export function loadReviewerPrompt(worktreePath) {
34
+ const candidates = [
35
+ path.join(worktreePath, ".spine", "agents", "reviewer.md"),
36
+ path.join(PACKAGE_ROOT, "templates", "agents", "reviewer.md"),
37
+ ];
38
+ for (const candidate of candidates) {
39
+ if (!fs.existsSync(candidate)) continue;
40
+ const raw = fs.readFileSync(candidate, "utf-8");
41
+ const fmEnd = raw.indexOf("---", 4);
42
+ if (fmEnd > 0) return raw.slice(fmEnd + 3).trim();
43
+ return raw.trim();
44
+ }
45
+ return "You are a code reviewer. Write your review to the specified output file.";
46
+ }
47
+
48
+ /**
49
+ * Base reviewer agent prompt plus auto-selected Cursor rules (system prompt only).
50
+ *
51
+ * @param {object} params
52
+ * @param {string} params.worktreePath
53
+ * @param {string} params.taskFolder
54
+ * @param {"plan"|"code"|"final"} params.reviewType
55
+ * @param {string} [params.baseline]
56
+ * @param {object} [params.config]
57
+ * @param {object} [params.journal]
58
+ */
59
+ export function buildReviewerSystemPrompt({
60
+ worktreePath,
61
+ taskFolder,
62
+ reviewType,
63
+ baseline,
64
+ config = {},
65
+ journal,
66
+ }) {
67
+ let systemPrompt = loadReviewerPrompt(worktreePath);
68
+ const { scopePaths } = resolveReviewScopePaths({
69
+ worktreePath,
70
+ baseline,
71
+ reviewType,
72
+ taskFolder,
73
+ });
74
+ const reviewerContext = buildReviewerContext({
75
+ projectRoot: journal?.projectRoot ?? worktreePath ?? process.cwd(),
76
+ config,
77
+ reviewType,
78
+ scopePaths,
79
+ journal,
80
+ });
81
+ if (reviewerContext.text) {
82
+ systemPrompt = `${systemPrompt}${reviewerContext.text}`;
83
+ }
84
+ return systemPrompt;
85
+ }
86
+
87
+ /**
88
+ * @param {string} cmd
89
+ */
90
+ export function commandExists(cmd) {
91
+ if (process.env.SPINE_REVIEW_TEST_NO_PI === "1") return false;
92
+ return pathCommandExists(cmd);
93
+ }
94
+
95
+ /**
96
+ * @param {object} params
97
+ */
98
+ export function buildReviewRequest({
99
+ reviewType,
100
+ stepNumber,
101
+ stepName,
102
+ taskFolder,
103
+ worktreePath,
104
+ outputPath,
105
+ baseline,
106
+ projectName = "project",
107
+ contractVerifyResult = null,
108
+ }) {
109
+ const promptPath = path.join(taskFolder, "PROMPT.md");
110
+ const statusPath = path.join(taskFolder, "STATUS.md");
111
+ if (reviewType === "final") {
112
+ const contractLines =
113
+ contractVerifyResult && Array.isArray(contractVerifyResult.checks)
114
+ ? [
115
+ "",
116
+ "## Contract verification",
117
+ `Machine verifier: ${contractVerifyResult.ok ? "PASS" : "FAIL"}`,
118
+ ...contractVerifyResult.checks.map(
119
+ (check) =>
120
+ `- ${check.ok ? "OK" : "FAIL"} ${check.field}: ${check.message}`,
121
+ ),
122
+ ]
123
+ : [];
124
+
125
+ return [
126
+ "# Review Request: Final Verdict",
127
+ "",
128
+ `You are performing a final verdict review for a ${projectName} task.`,
129
+ "",
130
+ "## Task Context",
131
+ `- **Task PROMPT:** ${promptPath}`,
132
+ `- **Task STATUS:** ${statusPath}`,
133
+ `- **Step completed:** Step ${stepNumber}: ${stepName}`,
134
+ `- **Worktree:** ${worktreePath}`,
135
+ "",
136
+ "## Instructions",
137
+ "Verify completion criteria and contract checks before returning a final verdict.",
138
+ ...contractLines,
139
+ "",
140
+ "## Output",
141
+ `Write your review to: \`${outputPath}\``,
142
+ "Include `### Verdict: PASS`, `### Verdict: REVISE`, or `### Verdict: REPLAN` and a JSON block.",
143
+ ].join("\n");
144
+ }
145
+ if (reviewType === "plan") {
146
+ return [
147
+ "# Review Request: Plan Review",
148
+ "",
149
+ `You are reviewing an implementation plan for a ${projectName} task.`,
150
+ "",
151
+ "## Task Context",
152
+ `- **Task PROMPT:** ${promptPath}`,
153
+ `- **Task STATUS:** ${statusPath}`,
154
+ `- **Step being planned:** Step ${stepNumber}: ${stepName}`,
155
+ `- **Worktree:** ${worktreePath}`,
156
+ "",
157
+ "## Output",
158
+ `Write your review to: \`${outputPath}\``,
159
+ "Include `### Verdict: APPROVE` or `### Verdict: REVISE` and a JSON block.",
160
+ ].join("\n");
161
+ }
162
+
163
+ const diffNamesCmd = baseline ? `git diff ${baseline}..HEAD --name-only` : "git diff --name-only";
164
+ const diffCmd = baseline ? `git diff ${baseline}..HEAD` : "git diff";
165
+
166
+ return [
167
+ "# Review Request: Code Review",
168
+ "",
169
+ `You are reviewing code changes for a ${projectName} task.`,
170
+ "",
171
+ "## Task Context",
172
+ `- **Task PROMPT:** ${promptPath}`,
173
+ `- **Step reviewed:** Step ${stepNumber}: ${stepName}`,
174
+ `- **Worktree:** ${worktreePath}`,
175
+ ...(baseline ? [`- **Baseline commit:** ${baseline}`] : []),
176
+ "",
177
+ "## Instructions",
178
+ `1. Run \`${diffNamesCmd}\` to see changed files`,
179
+ `2. Run \`${diffCmd}\` for the full diff`,
180
+ "",
181
+ "## Output",
182
+ `Write your review to: \`${outputPath}\``,
183
+ "Include `### Verdict: APPROVE` or `### Verdict: REVISE` and a JSON block.",
184
+ ].join("\n");
185
+ }
186
+
187
+ /**
188
+ * @param {string} taskFolder
189
+ * @param {number} stepNumber
190
+ */
191
+ export function findStepName(taskFolder, stepNumber) {
192
+ const promptPath = path.join(taskFolder, "PROMPT.md");
193
+ if (!fs.existsSync(promptPath)) return `Step ${stepNumber}`;
194
+ const content = fs.readFileSync(promptPath, "utf-8");
195
+ const re = new RegExp(`###\\s+Step\\s+${stepNumber}[:\\s]+(.+)`);
196
+ const match = content.match(re);
197
+ return match ? match[1].trim() : `Step ${stepNumber}`;
198
+ }
199
+
200
+ /**
201
+ * @param {object} params
202
+ */
203
+ export function writeStubReviewArtifact({ artifactPath, reviewType, stepNumber, stepName, verdict, feedback }) {
204
+ fs.mkdirSync(path.dirname(artifactPath), { recursive: true });
205
+ const reviewLabel =
206
+ reviewType === "final" ? "Final" : reviewType === "plan" ? "Plan" : "Code";
207
+ const body = [
208
+ `## ${reviewLabel} Review: ${stepName}`,
209
+ "",
210
+ `### Verdict: ${verdict}`,
211
+ "",
212
+ "### Summary",
213
+ feedback || `Stub ${reviewType} review for step ${stepNumber}.`,
214
+ "",
215
+ "```json",
216
+ JSON.stringify({ verdict, feedback: feedback || "" }, null, 2),
217
+ "```",
218
+ "",
219
+ ].join("\n");
220
+ fs.writeFileSync(artifactPath, body, "utf-8");
221
+ }
222
+
223
+ /**
224
+ * @param {object} journal
225
+ */
226
+ function isBatchJournalFrozen(journal) {
227
+ const loaded = loadSpineBatchState(journal.projectRoot);
228
+ if (!loaded.raw || loaded.raw.batchId !== journal.batchId) return false;
229
+ const phase = String(loaded.raw.phase ?? "");
230
+ return phase === "completed" || phase === "dismissed";
231
+ }
232
+
233
+ export function journalReviewEvent(type, journal, payload) {
234
+ if (!journal?.projectRoot || !journal?.batchId) return;
235
+ if (type === "review.failed" && isBatchJournalFrozen(journal)) {
236
+ return;
237
+ }
238
+ appendJournalEvent(journal.projectRoot, journal.batchId, type, {
239
+ taskId: journal.taskId,
240
+ laneNumber: journal.laneNumber,
241
+ correlationId: journal.correlationId,
242
+ ...payload,
243
+ });
244
+ }
245
+
246
+ /**
247
+ * In-worker plan/code checkpoints must journal `review.skipped` (SP-278/SP-308), never
248
+ * `review.failed`, when nested reviewer spawn is blocked inside a pi worker session.
249
+ *
250
+ * @param {object} params
251
+ */
252
+ export function completeNestedReviewSpawnSkipped({
253
+ stepNumber,
254
+ reviewType,
255
+ reviewLevel,
256
+ journal,
257
+ artifactPath,
258
+ feedback,
259
+ }) {
260
+ const message = feedback ?? NESTED_REVIEW_SPAWN_BLOCKED;
261
+ journalReviewEvent("review.skipped", journal, {
262
+ stepNumber,
263
+ reviewType,
264
+ reviewLevel,
265
+ reason: NESTED_REVIEW_SPAWN_REASON,
266
+ message,
267
+ });
268
+ return {
269
+ ok: true,
270
+ skipped: true,
271
+ reviewLevel,
272
+ verdict: null,
273
+ feedback: message,
274
+ artifactPath,
275
+ spawnFailed: false,
276
+ exitCode: 0,
277
+ };
278
+ }
279
+
280
+ /**
281
+ * True when inherited worker batch env must not write to the live journal
282
+ * (e.g. npm test subprocess with SPINE_JOURNAL_ATTACH=1).
283
+ */
284
+ export function isJournalAttachBlocked() {
285
+ return process.env.SPINE_SUPPRESS_JOURNAL_ATTACH === "1";
286
+ }
287
+
288
+ /**
289
+ * Resolve batch journal target from env only when the batch engine opts in.
290
+ * Prevents `npm test` (and other child processes) from polluting a live batch
291
+ * journal via inherited SPINE_BATCH_ID / SPINE_PROJECT_ROOT.
292
+ */
293
+ export function resolveBatchJournalContext() {
294
+ if (process.env.SPINE_JOURNAL_ATTACH !== "1") return undefined;
295
+ if (isJournalAttachBlocked()) return undefined;
296
+ const projectRoot = process.env.SPINE_PROJECT_ROOT;
297
+ const batchId = process.env.SPINE_BATCH_ID;
298
+ if (!projectRoot || !batchId) return undefined;
299
+
300
+ return {
301
+ projectRoot,
302
+ batchId,
303
+ taskId: process.env.SPINE_TASK_ID,
304
+ laneNumber: process.env.SPINE_LANE_NUMBER
305
+ ? Number(process.env.SPINE_LANE_NUMBER)
306
+ : undefined,
307
+ correlationId: process.env.SPINE_LANE_CORRELATION_ID,
308
+ };
309
+ }
310
+
311
+ /**
312
+ * When reviewer `pi` times out but the worker already left `.DONE` (and contract
313
+ * passed for final review), honor the verdict instead of failing the task.
314
+ *
315
+ * @param {object} params
316
+ * @returns {ReturnType<typeof runStepReview> | null}
317
+ */
318
+ export function honorReviewSpawnFailureWhenEligible({
319
+ spawnResult,
320
+ reviewType,
321
+ taskFolder,
322
+ contractVerifyResult,
323
+ journal,
324
+ stepNumber,
325
+ reviewLevel,
326
+ }) {
327
+ if (!spawnResult?.spawnFailed) return null;
328
+ if (spawnResult.exitCode !== REVIEW_SPAWN_TIMEOUT_EXIT_CODE) return null;
329
+ if (!fs.existsSync(path.join(taskFolder, ".DONE"))) return null;
330
+
331
+ if (reviewType === "final" && contractVerifyResult && !contractVerifyResult.ok) {
332
+ return null;
333
+ }
334
+
335
+ const artifactPath =
336
+ reviewType === "final"
337
+ ? buildFinalReviewArtifactPath(taskFolder)
338
+ : buildReviewArtifactPath(taskFolder, stepNumber);
339
+ const verdict =
340
+ reviewType === "final"
341
+ ? contractVerifyResult?.ok === false
342
+ ? "REVISE"
343
+ : "PASS"
344
+ : "APPROVE";
345
+ const feedback =
346
+ reviewType === "final"
347
+ ? "Reviewer spawn timed out; honoring contract verification and worker .DONE."
348
+ : "Reviewer spawn timed out; honoring worker .DONE and proceeding.";
349
+
350
+ writeStubReviewArtifact({
351
+ artifactPath,
352
+ reviewType,
353
+ verdict,
354
+ feedback,
355
+ });
356
+
357
+ journalReviewEvent("review.completed", journal, {
358
+ stepNumber,
359
+ reviewType,
360
+ reviewLevel,
361
+ verdict,
362
+ artifactPath,
363
+ stub: true,
364
+ honored: true,
365
+ honorReason: "spawn_timeout_with_done",
366
+ });
367
+
368
+ const ok = reviewType === "final" ? verdict === "PASS" : verdict === "APPROVE";
369
+ return {
370
+ ok,
371
+ skipped: false,
372
+ honored: true,
373
+ honorReason: "spawn_timeout_with_done",
374
+ reviewLevel,
375
+ verdict,
376
+ feedback,
377
+ artifactPath,
378
+ spawnFailed: false,
379
+ exitCode: ok ? 0 : 2,
380
+ };
381
+ }
382
+
383
+ /**
384
+ * Complete review from an on-disk artifact honored while reviewer pi is still running.
385
+ *
386
+ * @param {object} params
387
+ * @returns {ReturnType<typeof runStepReview>}
388
+ */
389
+ export function completeReviewFromHonoredArtifact({
390
+ artifactPath,
391
+ reviewType,
392
+ journal,
393
+ stepNumber,
394
+ reviewLevel,
395
+ honorReason = ARTIFACT_READY_HONOR_REASON,
396
+ }) {
397
+ const reviewContent = fs.readFileSync(artifactPath, "utf-8");
398
+ const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType });
399
+ if (!verdict) {
400
+ const error = "honored review artifact missing structured verdict";
401
+ journalReviewEvent("review.failed", journal, {
402
+ stepNumber,
403
+ reviewType,
404
+ reviewLevel,
405
+ error,
406
+ artifactPath,
407
+ spawnFailed: true,
408
+ });
409
+ return {
410
+ ok: false,
411
+ skipped: false,
412
+ reviewLevel,
413
+ verdict: null,
414
+ feedback,
415
+ artifactPath,
416
+ spawnFailed: true,
417
+ error,
418
+ exitCode: 1,
419
+ };
420
+ }
421
+
422
+ const ok = reviewType === "final" ? verdict === "PASS" : verdict === "APPROVE";
423
+ journalReviewEvent("review.completed", journal, {
424
+ stepNumber,
425
+ reviewType,
426
+ reviewLevel,
427
+ verdict,
428
+ artifactPath,
429
+ feedback,
430
+ honored: true,
431
+ honorReason,
432
+ });
433
+
434
+ return {
435
+ ok,
436
+ skipped: false,
437
+ honored: true,
438
+ honorReason,
439
+ reviewLevel,
440
+ verdict,
441
+ feedback,
442
+ artifactPath,
443
+ spawnFailed: false,
444
+ exitCode: ok ? 0 : 2,
445
+ };
446
+ }
447
+
448
+ export {
449
+ assertReviewToolAvailable,
450
+ runStepReview,
451
+ } from "./review-step-run.mjs";