pi-spine 1.0.2 → 1.2.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 (129) hide show
  1. package/README.md +61 -489
  2. package/bin/get-version.mjs +1 -13
  3. package/bin/spine-batch.mjs +162 -51
  4. package/bin/spine-cli/batch.mjs +3 -3
  5. package/bin/spine-cli/lane-logs.mjs +24 -0
  6. package/bin/spine-cli/scenarios.mjs +298 -0
  7. package/bin/spine-cli/wait.mjs +30 -0
  8. package/bin/spine-cli/watch.mjs +27 -0
  9. package/bin/spine-config.mjs +1 -212
  10. package/bin/spine-doctor.mjs +2 -418
  11. package/bin/spine-init.mjs +1 -398
  12. package/bin/spine-issue.mjs +196 -0
  13. package/bin/spine-journal.mjs +1 -0
  14. package/bin/spine-preflight.mjs +1 -700
  15. package/bin/spine-review-step.mjs +6 -4
  16. package/bin/spine-run.mjs +30 -0
  17. package/bin/spine-status.mjs +19 -1
  18. package/bin/spine-tasks.mjs +112 -13
  19. package/bin/spine-worker-runner.mjs +24 -14
  20. package/bin/spine.mjs +52 -2
  21. package/extensions/spine/worker-tools.ts +14 -12
  22. package/package.json +5 -2
  23. package/skills/create-spine-tasks/SKILL.md +135 -6
  24. package/skills/create-spine-tasks/references/clarify-template.md +73 -0
  25. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  26. package/skills/create-spine-tasks/references/prompt-template.md +2 -0
  27. package/skills/create-spine-tasks/references/requirements-checklist-template.md +94 -0
  28. package/src/batch/abort.mjs +3 -12
  29. package/src/batch/agent-session-worker.mjs +45 -5
  30. package/src/batch/attached-engine-handoff.mjs +188 -0
  31. package/src/batch/attached-runner.mjs +312 -0
  32. package/src/batch/contract-prelanded.mjs +180 -0
  33. package/src/batch/contract-verify.mjs +140 -2
  34. package/src/batch/detached-start.mjs +105 -7
  35. package/src/batch/diagnosis-alternatives.mjs +46 -0
  36. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  37. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  38. package/src/batch/diagnosis-stub.mjs +109 -0
  39. package/src/batch/diagnosis-task-done.mjs +110 -0
  40. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  41. package/src/batch/diagnosis.mjs +174 -62
  42. package/src/batch/engine-lanes/merge.mjs +168 -77
  43. package/src/batch/engine-lanes/queue.mjs +4 -1
  44. package/src/batch/engine-lanes/review.mjs +32 -74
  45. package/src/batch/engine-lanes/watch.mjs +29 -0
  46. package/src/batch/engine-lanes.mjs +1 -0
  47. package/src/batch/engine-scope.mjs +42 -5
  48. package/src/batch/engine.mjs +115 -68
  49. package/src/batch/evidence.mjs +81 -17
  50. package/src/batch/gate.mjs +46 -17
  51. package/src/batch/git-helpers.mjs +96 -0
  52. package/src/batch/heartbeat.mjs +73 -7
  53. package/src/batch/integrate.mjs +3 -5
  54. package/src/batch/journal.mjs +25 -0
  55. package/src/batch/lane-commit.mjs +90 -5
  56. package/src/batch/lifecycle.mjs +131 -4
  57. package/src/batch/macro-phase.mjs +226 -0
  58. package/src/batch/merge/adoption-doc-merge.mjs +243 -0
  59. package/src/batch/merge/wave-merge-state.mjs +108 -0
  60. package/src/batch/metrics.mjs +74 -5
  61. package/src/batch/orphan-detect.mjs +74 -0
  62. package/src/batch/pause.mjs +223 -0
  63. package/src/batch/post-merge-limbo.mjs +345 -17
  64. package/src/batch/reconcile.mjs +473 -50
  65. package/src/batch/resume-common.mjs +6 -2
  66. package/src/batch/resume-engine.mjs +58 -1
  67. package/src/batch/resume-lane-reviews.mjs +16 -0
  68. package/src/batch/resume-multi-lanes.mjs +56 -1
  69. package/src/batch/resume-multi-validate.mjs +148 -8
  70. package/src/batch/resume-multi.mjs +45 -44
  71. package/src/batch/resume.mjs +64 -47
  72. package/src/batch/retry.mjs +56 -5
  73. package/src/batch/review-shared.mjs +196 -0
  74. package/src/batch/review-spawn.mjs +326 -0
  75. package/src/batch/review.mjs +178 -212
  76. package/src/batch/rules-manifest-drift.mjs +157 -0
  77. package/src/batch/salvage.mjs +2 -1
  78. package/src/batch/sequence.mjs +454 -0
  79. package/src/batch/state.mjs +18 -3
  80. package/src/batch/status-json.mjs +67 -0
  81. package/src/batch/task-stall-budget.mjs +94 -10
  82. package/src/batch/worker-host.mjs +185 -37
  83. package/src/batch/worker-output.mjs +196 -3
  84. package/src/batch/worktree.mjs +10 -0
  85. package/src/cli/handoff.mjs +1 -1
  86. package/src/cli/issue-draft.mjs +180 -0
  87. package/src/cli/journal-follow.mjs +239 -0
  88. package/src/cli/lane-logs.mjs +291 -0
  89. package/src/cli/rules.mjs +1 -1
  90. package/src/cli/sequence.mjs +108 -0
  91. package/src/cli/settings-set.mjs +3 -22
  92. package/src/cli/settings-slash.mjs +27 -5
  93. package/src/cli/wait.mjs +187 -0
  94. package/src/cli/watch.mjs +160 -0
  95. package/src/config/agent-model-resolve.mjs +48 -0
  96. package/src/config/cursor-rules/discover.mjs +3 -21
  97. package/src/config/defaults.mjs +7 -1
  98. package/src/config/settings-fields.mjs +48 -0
  99. package/src/config/spine-config-load.mjs +221 -0
  100. package/src/config/spine-init-constants.mjs +424 -0
  101. package/src/config/spine-preflight-lib.mjs +1180 -0
  102. package/src/dashboard/lane-throughput.mjs +351 -0
  103. package/src/dashboard/public/dashboard.css +25 -1
  104. package/src/dashboard/public/dashboard.js +224 -40
  105. package/src/dashboard/public/index.html +15 -9
  106. package/src/dashboard/server.mjs +4 -0
  107. package/src/dashboard/snapshot.mjs +387 -6
  108. package/src/dashboard/view.mjs +170 -15
  109. package/src/doctor/agent-model-inherit.mjs +61 -6
  110. package/src/doctor/run-doctor-checks.mjs +483 -0
  111. package/src/doctor/sequence-safety.mjs +57 -0
  112. package/src/doctor/stale-path.mjs +22 -0
  113. package/src/doctor/stale-worktrees.mjs +102 -0
  114. package/src/fixtures/scenario-registry.mjs +194 -0
  115. package/src/fs/atomic-write.mjs +49 -0
  116. package/src/migrate/taskplane-config.mjs +1 -1
  117. package/src/planner/file-scope.mjs +246 -0
  118. package/src/planner/format-plan.mjs +9 -7
  119. package/src/planner/index.mjs +6 -2
  120. package/src/planner/pending.mjs +92 -1
  121. package/src/planner/wave-scope.mjs +136 -0
  122. package/src/planner/waves.mjs +133 -0
  123. package/src/tasks/analyze/index.mjs +453 -0
  124. package/src/tasks/packet/index.mjs +1 -0
  125. package/src/tasks/packet/parse-prompt.mjs +42 -1
  126. package/src/tasks/packet/validate-prompt.mjs +124 -0
  127. package/src/util/command-exists.mjs +19 -0
  128. package/templates/docs/constitution.md +61 -0
  129. package/templates/spine-config.json +9 -2
@@ -4,31 +4,55 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
- import { spawnSync } from "node:child_process";
8
7
  import { fileURLToPath } from "node:url";
9
8
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
10
9
  import { loadSpineBatchState } from "./state.mjs";
11
10
  import { buildReviewerContext } from "../config/reviewer-context.mjs";
12
11
  import { resolveReviewScopePaths } from "./review-scope.mjs";
12
+ import { commandExists as pathCommandExists } from "../util/command-exists.mjs";
13
+ import {
14
+ DEFAULT_REVIEW_SPAWN_TIMEOUT_MS,
15
+ ARTIFACT_READY_HONOR_REASON,
16
+ isActiveWorkerSession,
17
+ NESTED_REVIEW_SPAWN_BLOCKED,
18
+ NESTED_REVIEW_SPAWN_REASON,
19
+ REVIEW_SPAWN_TIMEOUT_EXIT_CODE,
20
+ REVIEW_TIMEOUT_REASON,
21
+ shouldBlockNestedReviewerSpawn,
22
+ spawnReviewerPi,
23
+ } from "./review-spawn.mjs";
24
+ import {
25
+ REVIEW_LEVEL_RE,
26
+ buildFinalReviewArtifactPath,
27
+ buildReviewArtifactPath,
28
+ isReviewTypeRequired,
29
+ normalizeVerdict,
30
+ parseReviewLevel,
31
+ parseReviewVerdict,
32
+ } from "./review-shared.mjs";
33
+
34
+ export {
35
+ REVIEW_LEVEL_RE,
36
+ buildFinalReviewArtifactPath,
37
+ buildReviewArtifactPath,
38
+ isReviewTypeRequired,
39
+ parseReviewLevel,
40
+ parseReviewVerdict,
41
+ } from "./review-shared.mjs";
13
42
 
14
43
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
44
  const PACKAGE_ROOT = path.resolve(__dirname, "../..");
16
45
 
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
- }
46
+ export {
47
+ DEFAULT_REVIEW_SPAWN_TIMEOUT_MS,
48
+ ARTIFACT_READY_HONOR_REASON,
49
+ isActiveWorkerSession,
50
+ NESTED_REVIEW_SPAWN_BLOCKED,
51
+ NESTED_REVIEW_SPAWN_REASON,
52
+ REVIEW_SPAWN_TIMEOUT_EXIT_CODE,
53
+ REVIEW_TIMEOUT_REASON,
54
+ shouldBlockNestedReviewerSpawn,
55
+ } from "./review-spawn.mjs";
32
56
 
33
57
  /**
34
58
  * @param {string} taskFolder
@@ -39,41 +63,6 @@ export function readReviewLevel(taskFolder) {
39
63
  return parseReviewLevel(fs.readFileSync(promptPath, "utf-8"));
40
64
  }
41
65
 
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
66
  /**
78
67
  * Highest numbered ### Step N heading in PROMPT.md (defaults to 1).
79
68
  * @param {string} taskFolder
@@ -258,84 +247,6 @@ export function findCompletedFinalReview({ taskFolder, journalEvents = [], taskI
258
247
  return result;
259
248
  }
260
249
 
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
250
  /**
340
251
  * @param {string} worktreePath
341
252
  */
@@ -398,12 +309,7 @@ export function buildReviewerSystemPrompt({
398
309
  */
399
310
  export function commandExists(cmd) {
400
311
  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
- }
312
+ return pathCommandExists(cmd);
407
313
  }
408
314
 
409
315
  /**
@@ -560,6 +466,40 @@ function journalReviewEvent(type, journal, payload) {
560
466
  });
561
467
  }
562
468
 
469
+ /**
470
+ * In-worker plan/code checkpoints must journal `review.skipped` (SP-278/SP-308), never
471
+ * `review.failed`, when nested reviewer spawn is blocked inside a pi worker session.
472
+ *
473
+ * @param {object} params
474
+ */
475
+ function completeNestedReviewSpawnSkipped({
476
+ stepNumber,
477
+ reviewType,
478
+ reviewLevel,
479
+ journal,
480
+ artifactPath,
481
+ feedback,
482
+ }) {
483
+ const message = feedback ?? NESTED_REVIEW_SPAWN_BLOCKED;
484
+ journalReviewEvent("review.skipped", journal, {
485
+ stepNumber,
486
+ reviewType,
487
+ reviewLevel,
488
+ reason: NESTED_REVIEW_SPAWN_REASON,
489
+ message,
490
+ });
491
+ return {
492
+ ok: true,
493
+ skipped: true,
494
+ reviewLevel,
495
+ verdict: null,
496
+ feedback: message,
497
+ artifactPath,
498
+ spawnFailed: false,
499
+ exitCode: 0,
500
+ };
501
+ }
502
+
563
503
  /**
564
504
  * True when inherited worker batch env must not write to the live journal
565
505
  * (e.g. npm test subprocess with SPINE_JOURNAL_ATTACH=1).
@@ -568,17 +508,6 @@ export function isJournalAttachBlocked() {
568
508
  return process.env.SPINE_SUPPRESS_JOURNAL_ATTACH === "1";
569
509
  }
570
510
 
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
511
  /**
583
512
  * Resolve batch journal target from env only when the batch engine opts in.
584
513
  * Prevents `npm test` (and other child processes) from polluting a live batch
@@ -602,70 +531,6 @@ export function resolveBatchJournalContext() {
602
531
  };
603
532
  }
604
533
 
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
534
  /**
670
535
  * When reviewer `pi` times out but the worker already left `.DONE` (and contract
671
536
  * passed for final review), honor the verdict instead of failing the task.
@@ -739,9 +604,74 @@ export function honorReviewSpawnFailureWhenEligible({
739
604
  }
740
605
 
741
606
  /**
607
+ * Complete review from an on-disk artifact honored while reviewer pi is still running.
608
+ *
742
609
  * @param {object} params
610
+ * @returns {ReturnType<typeof runStepReview>}
743
611
  */
744
- export function runStepReview({
612
+ export function completeReviewFromHonoredArtifact({
613
+ artifactPath,
614
+ reviewType,
615
+ journal,
616
+ stepNumber,
617
+ reviewLevel,
618
+ honorReason = ARTIFACT_READY_HONOR_REASON,
619
+ }) {
620
+ const reviewContent = fs.readFileSync(artifactPath, "utf-8");
621
+ const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType });
622
+ if (!verdict) {
623
+ const error = "honored review artifact missing structured verdict";
624
+ journalReviewEvent("review.failed", journal, {
625
+ stepNumber,
626
+ reviewType,
627
+ reviewLevel,
628
+ error,
629
+ artifactPath,
630
+ spawnFailed: true,
631
+ });
632
+ return {
633
+ ok: false,
634
+ skipped: false,
635
+ reviewLevel,
636
+ verdict: null,
637
+ feedback,
638
+ artifactPath,
639
+ spawnFailed: true,
640
+ error,
641
+ exitCode: 1,
642
+ };
643
+ }
644
+
645
+ const ok = reviewType === "final" ? verdict === "PASS" : verdict === "APPROVE";
646
+ journalReviewEvent("review.completed", journal, {
647
+ stepNumber,
648
+ reviewType,
649
+ reviewLevel,
650
+ verdict,
651
+ artifactPath,
652
+ feedback,
653
+ honored: true,
654
+ honorReason,
655
+ });
656
+
657
+ return {
658
+ ok,
659
+ skipped: false,
660
+ honored: true,
661
+ honorReason,
662
+ reviewLevel,
663
+ verdict,
664
+ feedback,
665
+ artifactPath,
666
+ spawnFailed: false,
667
+ exitCode: ok ? 0 : 2,
668
+ };
669
+ }
670
+
671
+ /**
672
+ * @param {object} params
673
+ */
674
+ export async function runStepReview({
745
675
  taskFolder,
746
676
  worktreePath,
747
677
  stepNumber,
@@ -901,15 +831,50 @@ export function runStepReview({
901
831
  config,
902
832
  journal,
903
833
  });
904
- const spawnResult = spawnReviewerPi({
834
+
835
+ if (shouldBlockNestedReviewerSpawn()) {
836
+ return completeNestedReviewSpawnSkipped({
837
+ stepNumber,
838
+ reviewType,
839
+ reviewLevel,
840
+ journal,
841
+ artifactPath,
842
+ });
843
+ }
844
+
845
+ const spawnResult = await spawnReviewerPi({
905
846
  worktreePath,
906
847
  taskFolder,
907
848
  reviewPrompt,
908
849
  systemPrompt,
909
850
  config,
851
+ artifactPath,
852
+ reviewType,
853
+ contractVerifyResult,
910
854
  });
911
855
 
856
+ if (spawnResult.honored && spawnResult.honorReason === ARTIFACT_READY_HONOR_REASON) {
857
+ return completeReviewFromHonoredArtifact({
858
+ artifactPath: spawnResult.artifactPath ?? artifactPath,
859
+ reviewType,
860
+ journal,
861
+ stepNumber,
862
+ reviewLevel,
863
+ });
864
+ }
865
+
912
866
  if (spawnResult.spawnFailed) {
867
+ if (spawnResult.reason === NESTED_REVIEW_SPAWN_REASON) {
868
+ return completeNestedReviewSpawnSkipped({
869
+ stepNumber,
870
+ reviewType,
871
+ reviewLevel,
872
+ journal,
873
+ artifactPath,
874
+ feedback: spawnResult.error,
875
+ });
876
+ }
877
+
913
878
  const honored = honorReviewSpawnFailureWhenEligible({
914
879
  spawnResult,
915
880
  reviewType,
@@ -942,6 +907,7 @@ export function runStepReview({
942
907
  spawnFailed: true,
943
908
  error: spawnResult.error,
944
909
  exitCode: spawnResult.exitCode ?? 1,
910
+ reason: spawnResult.reason,
945
911
  };
946
912
  }
947
913
 
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Rules-manifest drift resolution for integrate prep (SP-317 / #22).
3
+ */
4
+
5
+ import { gitExec } from "./git-exec.mjs";
6
+ import {
7
+ fingerprintRulesManifest,
8
+ loadRulesManifest,
9
+ parseRulesManifestJson,
10
+ resolveRulesManifestGeneratedAtMerge,
11
+ RULES_MANIFEST_REL_PATH,
12
+ } from "../config/cursor-rules/discover.mjs";
13
+ import { gitPorcelain } from "./lane-commit.mjs";
14
+
15
+ /**
16
+ * @param {string} line
17
+ * @returns {string | null}
18
+ */
19
+ function extractPorcelainPath(line) {
20
+ if (!line.trim()) return null;
21
+ let filePath = line.length > 2 && line[2] === " " ? line.slice(3) : line.slice(2);
22
+ filePath = filePath.trim();
23
+ if (!filePath) return null;
24
+ if (filePath.includes(" -> ")) {
25
+ return filePath.split(" -> ").pop()?.trim() ?? null;
26
+ }
27
+ return filePath;
28
+ }
29
+
30
+ /**
31
+ * @param {string} projectRoot
32
+ * @returns {string[]}
33
+ */
34
+ export function listIntegrateDirtyPaths(projectRoot) {
35
+ const output = gitPorcelain(projectRoot);
36
+ if (!output) return [];
37
+ return output
38
+ .split("\n")
39
+ .map((line) => extractPorcelainPath(line))
40
+ .filter((entry) => Boolean(entry));
41
+ }
42
+
43
+ /**
44
+ * @param {string} projectRoot
45
+ * @param {string} ref
46
+ */
47
+ function readRulesManifestFromRef(projectRoot, ref) {
48
+ const output = gitExec(
49
+ projectRoot,
50
+ ["show", `${ref}:${RULES_MANIFEST_REL_PATH}`],
51
+ { throwOnError: false, projectRoot },
52
+ );
53
+ if (output == null) {
54
+ return { ok: false, error: `missing ${RULES_MANIFEST_REL_PATH} at ${ref}` };
55
+ }
56
+ return parseRulesManifestJson(output);
57
+ }
58
+
59
+ /**
60
+ * @param {string} projectRoot
61
+ */
62
+ function restoreRulesManifestFromHead(projectRoot) {
63
+ gitExec(
64
+ projectRoot,
65
+ ["restore", "--source=HEAD", "--staged", "--worktree", RULES_MANIFEST_REL_PATH],
66
+ { projectRoot },
67
+ );
68
+ }
69
+
70
+ /**
71
+ * Before orch→main integrate, resolve manifest-only drift on the base worktree.
72
+ * Restores HEAD when drift is generatedAt-only or when uncommitted manifest matches orch
73
+ * (worker-generated entries on main that orch merge will land).
74
+ *
75
+ * @param {object} params
76
+ * @param {string} params.projectRoot
77
+ * @param {string} params.baseBranch
78
+ * @param {string} params.orchBranch
79
+ */
80
+ export function resolveRulesManifestIntegrateDrift({ projectRoot, baseBranch, orchBranch }) {
81
+ const dirtyPaths = listIntegrateDirtyPaths(projectRoot);
82
+ if (dirtyPaths.length === 0) {
83
+ return { ok: true, resolved: false };
84
+ }
85
+
86
+ if (dirtyPaths.length !== 1 || dirtyPaths[0] !== RULES_MANIFEST_REL_PATH) {
87
+ const preview = dirtyPaths.slice(0, 5).join(", ");
88
+ const suffix = dirtyPaths.length > 5 ? ` (+${dirtyPaths.length - 5} more)` : "";
89
+ return {
90
+ ok: false,
91
+ failureClass: "DirtyWorktree",
92
+ error:
93
+ `integrate refused — working tree has uncommitted changes (${preview}${suffix}); ` +
94
+ "commit or stash before integrate",
95
+ dirtyPaths,
96
+ };
97
+ }
98
+
99
+ const working = loadRulesManifest(projectRoot);
100
+ if (!working) {
101
+ return {
102
+ ok: false,
103
+ failureClass: "DirtyWorktree",
104
+ error: `${RULES_MANIFEST_REL_PATH} is dirty but unreadable`,
105
+ };
106
+ }
107
+
108
+ const headResult = readRulesManifestFromRef(projectRoot, baseBranch);
109
+ const orchResult = readRulesManifestFromRef(projectRoot, orchBranch);
110
+ if (!headResult.ok || !orchResult.ok) {
111
+ return {
112
+ ok: false,
113
+ failureClass: "DirtyWorktree",
114
+ error: "unable to read rules-manifest from base or orch branch",
115
+ };
116
+ }
117
+
118
+ const workingFingerprint = fingerprintRulesManifest(working);
119
+ const headFingerprint = fingerprintRulesManifest(headResult.manifest);
120
+ const orchFingerprint = fingerprintRulesManifest(orchResult.manifest);
121
+
122
+ if (workingFingerprint !== headFingerprint) {
123
+ if (workingFingerprint !== orchFingerprint) {
124
+ return {
125
+ ok: false,
126
+ failureClass: "DirtyWorktree",
127
+ error:
128
+ `${RULES_MANIFEST_REL_PATH} has uncommitted content changes beyond generatedAt — ` +
129
+ "commit or stash before integrate",
130
+ };
131
+ }
132
+
133
+ restoreRulesManifestFromHead(projectRoot);
134
+ return {
135
+ ok: true,
136
+ resolved: true,
137
+ action: "restored_head_worker_manifest_drift",
138
+ };
139
+ }
140
+
141
+ if (headFingerprint !== orchFingerprint) {
142
+ const contentMerge = resolveRulesManifestGeneratedAtMerge({
143
+ ours: headResult.manifest,
144
+ theirs: orchResult.manifest,
145
+ });
146
+ if (!contentMerge.ok) {
147
+ return contentMerge;
148
+ }
149
+ }
150
+
151
+ restoreRulesManifestFromHead(projectRoot);
152
+ return {
153
+ ok: true,
154
+ resolved: true,
155
+ action: "restored_head_for_merge",
156
+ };
157
+ }
@@ -8,6 +8,7 @@
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
10
10
  import { execFileSync } from "node:child_process";
11
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
11
12
  import { resolveScopedDirtyPaths } from "./heartbeat.mjs";
12
13
  import { appendJournalEvent } from "./journal.mjs";
13
14
  import { evidenceDir } from "./evidence.mjs";
@@ -216,7 +217,7 @@ export function writeSalvageEvidence({
216
217
  salvageCommit: salvageCommit ?? null,
217
218
  recordedAt: new Date().toISOString(),
218
219
  };
219
- fs.writeFileSync(abs, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
220
+ writeJsonAtomic(abs, payload);
220
221
  return rel;
221
222
  }
222
223