@juicesharp/rpiv-pi 1.20.0 → 2.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 (95) hide show
  1. package/agents/integration-scanner.md +1 -1
  2. package/extensions/rpiv-core/agents.ts +4 -4
  3. package/extensions/rpiv-core/artifact-collector.ts +20 -3
  4. package/extensions/rpiv-core/bash-timeout.ts +110 -0
  5. package/extensions/rpiv-core/built-in-workflows.ts +1484 -81
  6. package/extensions/rpiv-core/constants.ts +1 -0
  7. package/extensions/rpiv-core/index.ts +50 -18
  8. package/extensions/rpiv-core/lane-console.ts +566 -0
  9. package/extensions/rpiv-core/lane-dock-editor.ts +184 -0
  10. package/extensions/rpiv-core/lane-dock.ts +197 -0
  11. package/extensions/rpiv-core/lane-failure.ts +28 -0
  12. package/extensions/rpiv-core/lane-list.ts +414 -0
  13. package/extensions/rpiv-core/lane-progress.ts +330 -0
  14. package/extensions/rpiv-core/lane-relay-ui.ts +101 -0
  15. package/extensions/rpiv-core/lane-streaming.ts +68 -0
  16. package/extensions/rpiv-core/lane-switcher.ts +176 -0
  17. package/extensions/rpiv-core/lane-tool-defs.ts +73 -0
  18. package/extensions/rpiv-core/lane-transcript-disk.ts +91 -0
  19. package/extensions/rpiv-core/lane-transcript-view.ts +172 -0
  20. package/extensions/rpiv-core/lane-transcript.ts +277 -0
  21. package/extensions/rpiv-core/lane-usage.ts +96 -0
  22. package/extensions/rpiv-core/models-config.ts +7 -7
  23. package/extensions/rpiv-core/outcome-derivation.ts +2 -0
  24. package/extensions/rpiv-core/pipeline-pointer.ts +47 -0
  25. package/extensions/rpiv-core/question-lifecycle.ts +157 -0
  26. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  27. package/extensions/rpiv-core/rpiv-models/command.ts +3 -3
  28. package/extensions/rpiv-core/rpiv-models/items.ts +3 -8
  29. package/extensions/rpiv-core/run-lane-registry.ts +839 -0
  30. package/extensions/rpiv-core/sdk-workflow-host.ts +481 -0
  31. package/extensions/rpiv-core/session-capture.ts +261 -0
  32. package/extensions/rpiv-core/session-hooks.ts +8 -66
  33. package/extensions/rpiv-core/skill-bracket.ts +9 -19
  34. package/extensions/rpiv-core/workflow-execution-host.ts +184 -0
  35. package/extensions/rpiv-core/workflow-question-warp-bridge.ts +161 -0
  36. package/package.json +7 -5
  37. package/skills/_shared/git-changes.mjs +52 -1
  38. package/skills/_shared/slice-overlap.mjs +6 -8
  39. package/skills/_shared/stitch-elaborations.mjs +160 -0
  40. package/skills/amend/SKILL.md +48 -0
  41. package/skills/architecture-review/SKILL.md +2 -1
  42. package/skills/architecture-review/templates/architecture-review.md +1 -1
  43. package/skills/blueprint/SKILL.md +2 -1
  44. package/skills/code-review/SKILL.md +47 -17
  45. package/skills/code-review/_helpers/review-range.mjs +160 -3
  46. package/skills/commit/SKILL.md +12 -4
  47. package/skills/design/SKILL.md +2 -1
  48. package/skills/design-review/SKILL.md +77 -0
  49. package/skills/design-slice/SKILL.md +114 -0
  50. package/skills/discover/SKILL.md +1 -0
  51. package/skills/elaborate/SKILL.md +112 -0
  52. package/skills/explore/SKILL.md +1 -0
  53. package/skills/frontend-design/SKILL.md +1 -0
  54. package/skills/grade/SKILL.md +142 -0
  55. package/skills/implement/SKILL.md +16 -8
  56. package/skills/plan/SKILL.md +1 -0
  57. package/skills/pr-triage/SKILL.md +6 -3
  58. package/skills/research/SKILL.md +3 -1
  59. package/skills/revise/SKILL.md +1 -0
  60. package/skills/slice/SKILL.md +160 -0
  61. package/skills/synthesize/SKILL.md +165 -0
  62. package/skills/validate/SKILL.md +28 -5
  63. package/extensions/rpiv-core/agents.test.ts +0 -782
  64. package/extensions/rpiv-core/banner.test.ts +0 -27
  65. package/extensions/rpiv-core/built-in-workflows.test.ts +0 -1301
  66. package/extensions/rpiv-core/constants.test.ts +0 -14
  67. package/extensions/rpiv-core/frontmatter.test.ts +0 -51
  68. package/extensions/rpiv-core/git-context.matcher.test.ts +0 -47
  69. package/extensions/rpiv-core/git-context.test.ts +0 -109
  70. package/extensions/rpiv-core/guidance.test.ts +0 -140
  71. package/extensions/rpiv-core/model-override.test.ts +0 -637
  72. package/extensions/rpiv-core/model-override.ts +0 -356
  73. package/extensions/rpiv-core/models-config-validate.test.ts +0 -131
  74. package/extensions/rpiv-core/models-config.test.ts +0 -461
  75. package/extensions/rpiv-core/models-picker.test.ts +0 -136
  76. package/extensions/rpiv-core/outcome-derivation.test.ts +0 -550
  77. package/extensions/rpiv-core/package-checks.test.ts +0 -68
  78. package/extensions/rpiv-core/paths.test.ts +0 -58
  79. package/extensions/rpiv-core/pi-installer.test.ts +0 -100
  80. package/extensions/rpiv-core/prune-legacy-siblings.test.ts +0 -183
  81. package/extensions/rpiv-core/register-built-in-workflows.test.ts +0 -69
  82. package/extensions/rpiv-core/rpiv-models/units.test.ts +0 -136
  83. package/extensions/rpiv-core/rpiv-models-command.test.ts +0 -797
  84. package/extensions/rpiv-core/session-hooks.test.ts +0 -645
  85. package/extensions/rpiv-core/setup-command.test.ts +0 -213
  86. package/extensions/rpiv-core/sibling-import-graph.test.ts +0 -115
  87. package/extensions/rpiv-core/siblings.test.ts +0 -96
  88. package/extensions/rpiv-core/skill-bracket.test.ts +0 -251
  89. package/extensions/rpiv-core/skill-contracts-source.test.ts +0 -660
  90. package/extensions/rpiv-core/update-agents-command.test.ts +0 -106
  91. package/extensions/rpiv-core/utils.test.ts +0 -214
  92. package/skills/_shared/git-changes.test.ts +0 -107
  93. package/skills/_shared/git-context.test.ts +0 -90
  94. package/skills/_shared/list-recent.test.ts +0 -77
  95. package/skills/_shared/now.test.ts +0 -48
@@ -13,28 +13,37 @@
13
13
  * users author their own over their own skills.
14
14
  */
15
15
 
16
- import { readFileSync } from "node:fs";
17
- import { basename, isAbsolute, join } from "node:path";
16
+ import { execFileSync } from "node:child_process";
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
18
+ import { basename, dirname, isAbsolute, join, sep } from "node:path";
19
+ import { fileURLToPath } from "node:url";
18
20
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
19
21
  import {
20
22
  type Artifact,
21
23
  acts,
24
+ defineRoute,
22
25
  defineWorkflow,
26
+ directoryPathCollector,
23
27
  eq,
28
+ fanin,
24
29
  fanout,
25
30
  gate,
26
31
  gitCommitOutcome,
27
32
  gt,
28
33
  handleToString,
29
34
  iterate,
35
+ jsonBodyParser,
36
+ match,
30
37
  type Output,
31
38
  type PromptFn,
32
39
  produces,
33
40
  type RunView,
41
+ type ScriptContext,
34
42
  type Unit,
35
43
  type Workflow,
36
44
  } from "@juicesharp/rpiv-workflow/registration";
37
45
  import { StagePreflightError } from "@juicesharp/rpiv-workflow/runner";
46
+ import { rpivBucketOutcome } from "./artifact-collector.js";
38
47
 
39
48
  // The code-review stage's output schema is no longer declared here — every
40
49
  // code-review stage sources it from the skill's contract `produces.data`
@@ -62,6 +71,39 @@ const MAX_PHASES = 32;
62
71
  */
63
72
  const PLAN_PHASE_RE = /^## Phase (\d+):/gm;
64
73
 
74
+ /**
75
+ * Count lines matching `re` (a `^…` heading pattern) that sit OUTSIDE fenced code
76
+ * blocks. A `## Phase N:` / `## Slice N:` / `### Phase N —` inside a ``` or ~~~
77
+ * fence is example/fixture text — a meta-plan (one whose subject is the pipeline)
78
+ * legitimately embeds the pipeline's own plan/slice fixtures — not a structural
79
+ * heading. Mirrors the fence-aware boundary scan in
80
+ * skills/_shared/stitch-elaborations.mjs so the derive-check and the stitch that
81
+ * produced the body agree on what a heading is (a naive `matchAll` counts fenced
82
+ * examples and false-throws the derived-array staleness guard).
83
+ */
84
+ const countHeadingsOutsideFences = (content: string, re: RegExp): number => {
85
+ const lineRe = new RegExp(re.source); // per-line test; drop g/m so lastIndex can't drift
86
+ let count = 0;
87
+ let inFence = false;
88
+ let fenceLen = 0;
89
+ for (const line of content.split("\n")) {
90
+ const fence = /^\s*(`{3,}|~{3,})/.exec(line);
91
+ if (fence) {
92
+ const len = fence[1].length;
93
+ if (!inFence) {
94
+ inFence = true;
95
+ fenceLen = len;
96
+ } else if (len >= fenceLen && line.trim().length === len) {
97
+ inFence = false;
98
+ fenceLen = 0;
99
+ }
100
+ continue;
101
+ }
102
+ if (!inFence && lineRe.test(line)) count++;
103
+ }
104
+ return count;
105
+ };
106
+
65
107
  /**
66
108
  * One parsed entry of a plan's `phases:` array. `entry` carries the whole raw
67
109
  * frontmatter object, so a consumer can read fields beyond `{ n, title }`
@@ -100,7 +142,7 @@ const planPhaseRecords = (content: string, who: string, path: string): readonly
100
142
  const fm = frontmatter as Record<string, unknown>;
101
143
  const raw = fm.phases;
102
144
  const phases = Array.isArray(raw) ? raw : [];
103
- const headingCount = [...content.matchAll(PLAN_PHASE_RE)].length;
145
+ const headingCount = countHeadingsOutsideFences(content, PLAN_PHASE_RE);
104
146
  if (phases.length !== headingCount) {
105
147
  throw haltPreflight(
106
148
  who,
@@ -178,6 +220,17 @@ const FRONTMATTER_PHASE_FANOUT = fanout({
178
220
  },
179
221
  });
180
222
 
223
+ /**
224
+ * `implement`'s serial twin of `FRONTMATTER_PHASE_FANOUT`. Applying a plan to ONE
225
+ * working tree is a patch-series / migration: phases share files (a later phase
226
+ * EDITS a file an earlier phase CREATES) and mutate shared state, so running them
227
+ * in parallel races on those files and lets a dependent phase run before its
228
+ * prerequisite has landed. `concurrency: 1` serializes the units in the plan's
229
+ * (topological) phase order — same units, no race, prerequisites always present.
230
+ * `elaborate` keeps the parallel fanout: it writes ISOLATED per-phase docs.
231
+ */
232
+ const IMPLEMENT_PHASE_FANOUT = { ...FRONTMATTER_PHASE_FANOUT, concurrency: 1 };
233
+
181
234
  // ===========================================================================
182
235
  // ship — blueprint → implement → validate → commit
183
236
  // ===========================================================================
@@ -189,7 +242,7 @@ const shipWorkflow = defineWorkflow({
189
242
  start: "blueprint",
190
243
  stages: {
191
244
  blueprint: produces(),
192
- implement: acts({ loop: FRONTMATTER_PHASE_FANOUT, reads: ["plans"] }),
245
+ implement: acts({ loop: IMPLEMENT_PHASE_FANOUT, reads: ["plans"] }),
193
246
  validate: produces(),
194
247
  commit: acts({ outcome: gitCommitOutcome }),
195
248
  },
@@ -201,41 +254,6 @@ const shipWorkflow = defineWorkflow({
201
254
  },
202
255
  });
203
256
 
204
- // ===========================================================================
205
- // build — research → blueprint → implement → validate → code-review →
206
- // (revise → implement → loop) | commit
207
- // Loops until code-review reports zero blockers, bounded by the
208
- // runner's maxBackwardJumps (default 2 → up to 3 review iterations).
209
- // ===========================================================================
210
-
211
- const buildWorkflow = defineWorkflow({
212
- name: "build",
213
- description:
214
- "Research-backed feature work with a review loop. Best for medium changes where you want a second pass before committing. Chain: research → blueprint → implement → validate → code-review → (revise loop) → commit.",
215
- start: "research",
216
- stages: {
217
- research: produces(),
218
- blueprint: produces(),
219
- implement: acts({ loop: FRONTMATTER_PHASE_FANOUT, reads: ["plans"] }),
220
- validate: produces(),
221
- "code-review": produces(),
222
- revise: produces({ reads: ["plans", "reviews"] }),
223
- commit: acts({ outcome: gitCommitOutcome }),
224
- },
225
- edges: {
226
- research: "blueprint",
227
- blueprint: "implement",
228
- implement: "validate",
229
- validate: "code-review",
230
- "code-review": gate("blockers_count", { revise: gt(0), commit: eq(0) }, "commit"),
231
- // Backward edge: revise → implement re-enters the implement/validate/
232
- // code-review cycle. Bounded by the runner's default maxBackwardJumps
233
- // (2), permitting at most 3 review iterations before the guard halts.
234
- revise: "implement",
235
- commit: "stop",
236
- },
237
- });
238
-
239
257
  // ===========================================================================
240
258
  // arch — research → design → plan → implement → validate → code-review →
241
259
  // (design → loop) | commit
@@ -253,7 +271,7 @@ const archWorkflow = defineWorkflow({
253
271
  research: produces(),
254
272
  design: produces(),
255
273
  plan: produces(),
256
- implement: acts({ loop: FRONTMATTER_PHASE_FANOUT, reads: ["plans"] }),
274
+ implement: acts({ loop: IMPLEMENT_PHASE_FANOUT, reads: ["plans"] }),
257
275
  validate: produces(),
258
276
  "code-review": produces(),
259
277
  commit: acts({ outcome: gitCommitOutcome }),
@@ -287,7 +305,7 @@ const vetWorkflow = defineWorkflow({
287
305
  stages: {
288
306
  "code-review": produces(),
289
307
  blueprint: produces(),
290
- implement: acts({ loop: FRONTMATTER_PHASE_FANOUT, reads: ["plans"] }),
308
+ implement: acts({ loop: IMPLEMENT_PHASE_FANOUT, reads: ["plans"] }),
291
309
  validate: produces(),
292
310
  commit: acts({ outcome: gitCommitOutcome }),
293
311
  },
@@ -389,7 +407,7 @@ const REVIEW_PHASE_ITERATE = iterate({
389
407
  const phases = Array.isArray(raw) ? raw : [];
390
408
  const i = accumulated.length;
391
409
  if (i === 0) {
392
- const headingCount = [...content.matchAll(REVIEW_PHASE_RE)].length;
410
+ const headingCount = countHeadingsOutsideFences(content, REVIEW_PHASE_RE);
393
411
  if (phases.length !== headingCount) {
394
412
  throw haltPreflight(
395
413
  "REVIEW_PHASE_ITERATE",
@@ -483,6 +501,9 @@ const PLANS_PHASE_FANOUT = fanout({
483
501
  },
484
502
  });
485
503
 
504
+ /** `implement`'s serial twin of `PLANS_PHASE_FANOUT` (polish's multi-plan variant) — same serialize-shared-tree rationale as `IMPLEMENT_PHASE_FANOUT`. */
505
+ const IMPLEMENT_PLANS_FANOUT = { ...PLANS_PHASE_FANOUT, concurrency: 1 };
506
+
486
507
  /**
487
508
  * Hand the single validate session EVERY plan from the latest blueprint pass
488
509
  * (`latestPlans`). The runner's default rolling-primary — and a plain
@@ -506,7 +527,7 @@ const polishWorkflow = defineWorkflow({
506
527
  stages: {
507
528
  "architecture-review": produces(),
508
529
  blueprint: produces({ loop: REVIEW_PHASE_ITERATE }),
509
- implement: acts({ loop: PLANS_PHASE_FANOUT, reads: ["plans"] }),
530
+ implement: acts({ loop: IMPLEMENT_PLANS_FANOUT, reads: ["plans"] }),
510
531
  validate: produces({ prompt: VALIDATE_PLANS_PROMPT }),
511
532
  "code-review": produces(),
512
533
  commit: acts({ outcome: gitCommitOutcome }),
@@ -525,54 +546,1437 @@ const polishWorkflow = defineWorkflow({
525
546
  });
526
547
 
527
548
  // ===========================================================================
528
- // pr-triage — pr-triage → security-gate → stop
529
- // Read-only front door for an incoming GitHub PR. The `pr-triage` skill
530
- // fetches the PR thread, assesses the diff against whatever standard the repo
531
- // actually carries, writes a triage artifact, and recommends a triage
532
- // disposition (Review / Request changes / Hold / Decline) as a plain next
533
- // action. The `security-gate` script stage reads the skill's
534
- // `security_flag` and HALTS the run on a BLOCK (≥ 2) via `haltPreflight` — the
535
- // "security gate first, before any checkout" posture — while SAFE/REVIEW (< 2)
536
- // fall through to `stop` carrying the verdict.
537
- //
538
- // It terminates rather than dispatching a follow-up workflow: triage gates entry
539
- // to review, it does not merge. The disposition is a plain action; `vet` (the
540
- // review stage) is offered as optional sugar under Review. Only the security gate
541
- // is enforced by the graph. A linear guard stage (not a `gate(...)`
542
- // edge) keeps the halt off the data-routing path — the throw lives inside the
543
- // script, read from the prior stage's output.
549
+ // build — goal (verbatim-brief capture) → research → slice → slice-check
550
+ // (deterministic floor) → slice-grade (design-readiness, slice-fix loop)
551
+ // → slice-design (fanout) → design-review (one human checkpoint) →
552
+ // subplan (cluster fanout) → plan → plan-grade (plan-fix loop) →
553
+ // code (fanout) → code-splice → code-grade (code-fix loop) →
554
+ // implement → validate → commit
555
+ // The sliced, panel-gated heavy path: capture the user's brief verbatim as the
556
+ // `goal` channel (the north star the judgment seams — the two grade panels'
557
+ // completeness/correctness dimensions and validate — anchor against), research
558
+ // the brief (so every slice
559
+ // rests on a real, cited footing and the plan gate can grade architecture-fit),
560
+ // decompose it into independent
561
+ // vertical slices, gate that breakdown BEFORE any design so each slice is
562
+ // chewable by one design-slice pass. The gate is two-phase: a DETERMINISTIC
563
+ // floor (`slice-check`) enforces dependency-cycle freedom and brief-coverage
564
+ // conservation (a slice-fix may redistribute the brief, never drop scope to pass),
565
+ // then ONE LLM `design-readiness` judgment reconciles the formerly-opposing
566
+ // split/merge forces. Then design every slice in parallel and pause at ONE
567
+ // consolidated human checkpoint (`design-review`) — the single fan-in seam where
568
+ // every design exists and nothing parallel runs — to accept or adjust the
569
+ // proposed interfaces/data types before synthesis. Then merge hierarchically
570
+ // (per-cluster sub-plans → one plan) so no pass holds every design, gate the
571
+ // plan on quality dimensions BEFORE any code, elaborate code per phase and
572
+ // splice it in, re-grade the code-bearing plan, then implement/validate/commit.
573
+ // The parallel generalization of `arch`.
544
574
  // ===========================================================================
545
575
 
546
- /** BLOCK tier the pr-triage `security_flag` contract field emits (0 SAFE · 1 REVIEW · 2 BLOCK). */
547
- const PR_TRIAGE_BLOCK = 2;
576
+ /**
577
+ * The single LLM dimension the EARLY gate grades the slice map against — before
578
+ * any design. `design-readiness` asks the one question the whole gate exists to
579
+ * answer: is each slice chewable by ONE `design-slice` pass? It subsumes the old
580
+ * four-way panel (right-sizing + vertical-shape + design-readiness + the
581
+ * contract-ownership half of independence) into one holistic judgment — taking
582
+ * its own name from that design-readiness member, the dominant sub-aspect — so
583
+ * the formerly-opposing split-pressure (right-sizing) and merge-pressure
584
+ * (vertical-shape) forces are reconciled by ONE grader instead of two blind
585
+ * panelists that ping-pong the reslice loop. The structural floor that was the
586
+ * other half of independence — dependency-cycle freedom — plus brief-coverage
587
+ * conservation are enforced DETERMINISTICALLY by `slice-check`, not graded
588
+ * here. Mirrors the `design-readiness` rubric row in the `grade` skill.
589
+ */
590
+ const SLICE_DIMENSIONS = ["design-readiness"] as const;
591
+
592
+ /**
593
+ * Quality dimensions the LATER gate grades the synthesized plan against.
594
+ * Includes `architecture-fit`: build front-loads a `research` stage, so the
595
+ * research artifact is always present to feed that dimension's `--context`
596
+ * (threaded in by `gradePanelFanout` for this one dimension).
597
+ */
598
+ const PLAN_DIMENSIONS = [
599
+ "completeness",
600
+ "correctness",
601
+ "actionability",
602
+ "pattern-following",
603
+ "architecture-fit",
604
+ ] as const;
605
+
606
+ /** Bucket directory the goal capture writes into — build's verbatim-brief channel. */
607
+ const GOAL_DIR = ".rpiv/artifacts/goal";
608
+
609
+ /**
610
+ * Capture the user's brief VERBATIM as build's `goal` channel — the north-star
611
+ * artifact the judgment seams anchor against (the grade panels'
612
+ * completeness/correctness dimensions and `validate`). A script stage (no LLM)
613
+ * so nothing refracts the wording: `research` carries the goal's intent,
614
+ * grounded and expanded, but explicit user constraints ("keep it minimal",
615
+ * "don't touch auth") routinely don't survive that refraction — the raw file
616
+ * is the only artifact that holds them. The body is the brief byte-for-byte;
617
+ * added frontmatter or headers would pollute "the user's exact words".
618
+ *
619
+ * Publishes under its record key (`goal`): a script stage may not carry an
620
+ * `outcome` (`script-with-outcome` is a load error) and needs none — the
621
+ * returned envelope IS the output. Timestamped filename so concurrent/repeat
622
+ * runs never collide; on resume the recorded path replays from the JSONL
623
+ * trail, so the fanout `units()` closures reading the channel stay
624
+ * deterministic.
625
+ */
626
+ const captureGoal = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
627
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
628
+ const rel = join(GOAL_DIR, `goal-${stamp}.md`);
629
+ mkdirSync(join(cwd, GOAL_DIR), { recursive: true });
630
+ writeFileSync(join(cwd, rel), state.originalInput, "utf-8");
631
+ // Snapshot the paths ALREADY dirty before the run touched anything — the
632
+ // validate stage judges working-tree scope criteria against the run's own
633
+ // delta, and the commit skill fences these paths off its commit. Timestamped
634
+ // like the goal file itself (concurrent/repeat runs never read each other's
635
+ // snapshot — there is NO fixed rendezvous path) and published on the goal
636
+ // channel with role "baseline", so the JSONL trail carries the exact path to
637
+ // every consumer and replays it deterministically on resume. Best-effort: a
638
+ // non-repo / git-unavailable cwd writes an empty snapshot, so consumers
639
+ // degrade to baseline-less behavior rather than failing the goal capture.
640
+ const baselineRel = join(GOAL_DIR, `baseline-${stamp}.json`);
641
+ writeCommitBaseline(cwd, baselineRel);
642
+ return {
643
+ kind: "md",
644
+ // Order is load-bearing: `latestFsArtifact(state, "goal")` takes the FIRST
645
+ // fs artifact — the goal md stays the channel's face (grade --goal flags,
646
+ // rolling primary); the baseline rides behind it under its role.
647
+ artifacts: [
648
+ { handle: { kind: "fs", path: rel } },
649
+ { handle: { kind: "fs", path: baselineRel }, role: "baseline" },
650
+ ],
651
+ data: {},
652
+ };
653
+ };
654
+
655
+ /** Record the paths dirty before the run to `rel` (best-effort; empty on any git failure). */
656
+ const writeCommitBaseline = (cwd: string, rel: string): void => {
657
+ let paths: string[] = [];
658
+ try {
659
+ const out = execFileSync("git", ["status", "--short"], { cwd, encoding: "utf-8" });
660
+ paths = out
661
+ .split("\n")
662
+ .filter((l) => l.trim() !== "")
663
+ .map((l) => {
664
+ const rest = l.slice(3).trim();
665
+ const arrow = rest.indexOf(" -> ");
666
+ return arrow >= 0 ? rest.slice(arrow + 4).trim() : rest;
667
+ });
668
+ } catch {
669
+ paths = [];
670
+ }
671
+ mkdirSync(dirname(join(cwd, rel)), { recursive: true });
672
+ writeFileSync(join(cwd, rel), JSON.stringify({ paths }, null, 2), "utf-8");
673
+ };
674
+
675
+ /** The run-start pre-existing-dirty snapshot riding the goal channel (role "baseline"). */
676
+ const goalBaselinePath = (state: RunView): string | undefined => {
677
+ const a = state.named.goal?.at(-1)?.artifacts.find((x) => x.role === "baseline" && x.handle.kind === "fs");
678
+ return a ? handleToString(a.handle) : undefined;
679
+ };
680
+
681
+ /**
682
+ * `goal` displaces `research` as build's start stage, and ONLY the start stage
683
+ * receives `originalInput` as its skill arg (`stageEntryArgs` case 1) — a plain
684
+ * `produces()` research would silently receive the rolling primary (the goal
685
+ * FILE PATH) instead of the brief text. A prompt stage owns its whole message,
686
+ * so this rebuilds research's pre-goal dispatch byte-for-byte; the outcome
687
+ * deriver still wires the `research` bucket off the record key (the polish
688
+ * `validate` prompt-stage precedent).
689
+ */
690
+ const RESEARCH_BRIEF_PROMPT: PromptFn = ({ state }) => `/skill:research ${state.originalInput}`;
691
+
692
+ /** `## Slice N:` headings — the source of truth a slice map's `slices:` array is derived from. */
693
+ const SLICE_HEADING_RE = /^## Slice (\d+):/gm;
694
+
695
+ /**
696
+ * Parse a slice map's `slices:` frontmatter into `{ n, title }` records,
697
+ * derive-checked against the body's `## Slice N:` headings and the required
698
+ * `slice_count` scalar — the slices twin of `planPhaseRecords`. A mismatch means
699
+ * the producer's rebuild was skipped or the array went stale; throw rather than
700
+ * dispatch a wrong unit list.
701
+ */
702
+ const sliceRecords = (content: string, who: string, path: string): readonly PhaseRecord[] => {
703
+ const { frontmatter } = parseFrontmatter(content);
704
+ const fm = frontmatter as Record<string, unknown>;
705
+ const raw = fm.slices;
706
+ const slices = Array.isArray(raw) ? raw : [];
707
+ const headingCount = countHeadingsOutsideFences(content, SLICE_HEADING_RE);
708
+ if (slices.length !== headingCount) {
709
+ throw haltPreflight(
710
+ who,
711
+ `${who}: slice map ${path} has mismatched slices`,
712
+ `${who}: slice map ${path} frontmatter slices (${slices.length}) ≠ '## Slice N:' headings (${headingCount}) — the derived array is stale against the body`,
713
+ );
714
+ }
715
+ if ((slices.length > 0 || fm.slice_count !== undefined) && fm.slice_count !== slices.length) {
716
+ throw haltPreflight(
717
+ who,
718
+ `${who}: slice map ${path} has invalid slice_count`,
719
+ `${who}: slice map ${path} frontmatter slice_count (${String(fm.slice_count)}) ≠ slices length (${slices.length}) — rebuild slice_count from the '## Slice N:' headings`,
720
+ );
721
+ }
722
+ return slices.map((entry, index) => {
723
+ const e = (entry ?? {}) as Record<string, unknown>;
724
+ return {
725
+ entry: e,
726
+ n: typeof e.n === "number" ? e.n : index + 1,
727
+ title: typeof e.title === "string" ? e.title : "",
728
+ index,
729
+ total: slices.length,
730
+ };
731
+ });
732
+ };
733
+
734
+ // Relocated ABOVE SLICE_DESIGN_FANOUT (deleted from its old location below) so it sits
735
+ // above its first textual reference. (No TDZ today even unrelocated — `sliceDeps` is only
736
+ // read inside the `units` runtime closure, which runs at dispatch, not module-eval — but
737
+ // placing it above the fanout keeps the read-order obvious and matches `clusterSliceDag`'s
738
+ // existing use below.)
739
+ /** The slice-number deps a slice-map entry declares (empty when absent). */
740
+ const sliceDeps = (entry: Record<string, unknown>): number[] => {
741
+ const raw = entry.deps;
742
+ return Array.isArray(raw) ? raw.filter((d): d is number => typeof d === "number") : [];
743
+ };
744
+
745
+ /** Fan `design-slice` out over the latest slice map's `slices:` array — one design
746
+ * session per slice, dependency-ordered. `deps` (slice-N unit ids) drive the wave
747
+ * scheduler; `depArtifactFlag` injects each completed dependency's design path as
748
+ * `--upstream <path>` so a dependent slice reads its dependency's decided Key Interfaces. */
749
+ const SLICE_DESIGN_FANOUT = fanout({
750
+ source: "slices",
751
+ unit: { by: "frontmatter-array", pattern: "slices" },
752
+ max: MAX_PHASES,
753
+ depArtifactFlag: "--upstream",
754
+ units: ({ state, cwd }) => {
755
+ const doc = latestFsArtifact(state, "slices");
756
+ if (doc?.handle.kind !== "fs") return [];
757
+ const path = doc.handle.path;
758
+ const promptPath = handleToString(doc.handle);
759
+ return sliceRecords(readArtifactFile(path, cwd), "SLICE_DESIGN_FANOUT", path).map((r) => ({
760
+ prompt: `${promptPath} Slice ${r.n}: ${r.title}`.trimEnd(),
761
+ label: `slice ${r.index + 1}/${r.total}`,
762
+ id: `slice-${r.n}`,
763
+ deps: sliceDeps(r.entry).map((n) => `slice-${n}`), // directed edges → unit ids (slice-N)
764
+ }));
765
+ },
766
+ });
767
+
768
+ /** Max slices per synth cluster — a context-budget proxy; oversized DAG components split by this. */
769
+ const MAX_CLUSTER_SLICES = 6;
770
+
771
+ /**
772
+ * Group slices into clusters = connected components of the `deps` DAG (a slice
773
+ * and everything it transitively depends on / that depends on it land together),
774
+ * so coupled slices reconcile inside ONE subplan pass and only cross-cluster
775
+ * seams reach the root. Components larger than `MAX_CLUSTER_SLICES` are chunked
776
+ * (by slice number) to bound each pass's context. Returns clusters of slice
777
+ * numbers, each sorted ascending; components ordered by their smallest slice.
778
+ */
779
+ const clusterSliceDag = (records: readonly PhaseRecord[]): number[][] => {
780
+ const ns = records.map((r) => r.n);
781
+ const parent = new Map<number, number>(ns.map((n) => [n, n]));
782
+ const find = (x: number): number => {
783
+ let root = x;
784
+ while (parent.get(root) !== root) root = parent.get(root) ?? root;
785
+ let cur = x;
786
+ while (parent.get(cur) !== root) {
787
+ const next = parent.get(cur) ?? root;
788
+ parent.set(cur, root);
789
+ cur = next;
790
+ }
791
+ return root;
792
+ };
793
+ const union = (a: number, b: number): void => {
794
+ const ra = find(a);
795
+ const rb = find(b);
796
+ if (ra !== rb) parent.set(ra, rb);
797
+ };
798
+ for (const r of records) for (const d of sliceDeps(r.entry)) if (parent.has(d)) union(r.n, d);
799
+ const byRoot = new Map<number, number[]>();
800
+ for (const n of ns) {
801
+ const root = find(n);
802
+ const arr = byRoot.get(root);
803
+ if (arr) arr.push(n);
804
+ else byRoot.set(root, [n]);
805
+ }
806
+ const clusters: number[][] = [];
807
+ for (const comp of [...byRoot.values()].sort((a, b) => (a[0] ?? 0) - (b[0] ?? 0))) {
808
+ const sorted = [...comp].sort((a, b) => a - b);
809
+ for (let i = 0; i < sorted.length; i += MAX_CLUSTER_SLICES) {
810
+ clusters.push(sorted.slice(i, i + MAX_CLUSTER_SLICES));
811
+ }
812
+ }
813
+ return clusters;
814
+ };
815
+
816
+ /**
817
+ * A directed dependency cycle in the slice DAG (`A→B→…→A`), returned as the slice
818
+ * numbers on the cycle; empty when acyclic. `clusterSliceDag` groups by the
819
+ * UNDIRECTED connected component, which a directed cycle survives — so the
820
+ * design-readiness gate needs this separate directed check. A cycle is the true
821
+ * independence defect (slices in a cycle cannot be designed independently); the
822
+ * deterministic floor catches it without an LLM coin-flip.
823
+ */
824
+ const sliceDepCycle = (records: readonly PhaseRecord[]): number[] => {
825
+ const deps = new Map<number, number[]>(records.map((r) => [r.n, sliceDeps(r.entry)]));
826
+ const WHITE = 0;
827
+ const GRAY = 1;
828
+ const BLACK = 2;
829
+ const color = new Map<number, number>();
830
+ const stack: number[] = [];
831
+ let cycle: number[] = [];
832
+ const visit = (n: number): boolean => {
833
+ color.set(n, GRAY);
834
+ stack.push(n);
835
+ for (const d of deps.get(n) ?? []) {
836
+ if (!deps.has(d)) continue; // a dangling dep is a derive/numbering concern, not a cycle
837
+ const c = color.get(d) ?? WHITE;
838
+ if (c === GRAY) {
839
+ cycle = stack.slice(stack.indexOf(d));
840
+ return true;
841
+ }
842
+ if (c === WHITE && visit(d)) return true;
843
+ }
844
+ stack.pop();
845
+ color.set(n, BLACK);
846
+ return false;
847
+ };
848
+ for (const r of records) if ((color.get(r.n) ?? WHITE) === WHITE && visit(r.n)) break;
849
+ return cycle;
850
+ };
851
+
852
+ /**
853
+ * One frozen coverage unit — the brief's ID'd decomposition, set once at the
854
+ * first (human-confirmed) cut and conserved across every reslice. The conserved
855
+ * quantity the gate was missing: a reslice may REDISTRIBUTE units across slices,
856
+ * never DROP one — which is what closes the "pass by simplifying / shrinking
857
+ * scope" escape hatch the sizing dimensions can't see.
858
+ */
859
+ interface CoverageUnit {
860
+ id: string;
861
+ brief: string;
862
+ }
863
+
864
+ /** Parse a slice map's `coverage:` frontmatter into `{ id, brief }` units (empty when absent). */
865
+ const sliceCoverageUnits = (content: string): CoverageUnit[] => {
866
+ const { frontmatter } = parseFrontmatter(content);
867
+ const raw = (frontmatter as Record<string, unknown>).coverage;
868
+ if (!Array.isArray(raw)) return [];
869
+ return raw.flatMap((e) => {
870
+ const o = (e ?? {}) as Record<string, unknown>;
871
+ return typeof o.id === "string" ? [{ id: o.id, brief: typeof o.brief === "string" ? o.brief : "" }] : [];
872
+ });
873
+ };
874
+
875
+ /** The coverage-unit ids a slice entry claims to deliver (its `covers:` array). */
876
+ const sliceCovers = (entry: Record<string, unknown>): string[] => {
877
+ const raw = entry.covers;
878
+ return Array.isArray(raw) ? raw.filter((c): c is string => typeof c === "string") : [];
879
+ };
880
+
881
+ /** The verdict directory the deterministic checks and the LLM grade panel share. */
882
+ const VERDICT_DIR = ".rpiv/artifacts/verdicts";
548
883
 
549
- const prTriageWorkflow = defineWorkflow({
550
- name: "pr-triage",
884
+ /**
885
+ * A `path:line` (or `path:line-line`) citation in an artifact's prose. Requires a
886
+ * dotted extension so timestamps (`17:13:27`), ratios, and bare `Slice 2:` labels
887
+ * never match — only file references with a real extension are verified.
888
+ *
889
+ * A citation may START with a single dot (`.github/workflows/ci.yml:12`,
890
+ * `.eslintrc.js:3`) — without it, dot-dirs and dotfiles were captured with the
891
+ * dot stripped and guaranteed to fail the floor as a mangled path. The leading
892
+ * dot is taken only when the preceding char is not a word char or another dot
893
+ * (`(?<![\w.])`), and a dotless start only at a word boundary (`(?<!\w)`), so a
894
+ * prose ellipsis (`...packages/x.ts:5`) still yields `packages/x.ts`, never
895
+ * `...packages/x.ts`.
896
+ */
897
+ const FILE_LINE_CITATION_RE = /((?:(?<![\w.])\.)?(?<!\w)[\w][\w./-]*\.[a-zA-Z][a-zA-Z0-9]{0,4}):(\d+)(?:-(\d+))?/g;
898
+
899
+ /**
900
+ * Verify every `file:line` citation in `body` resolves against the working tree:
901
+ * the cited file must exist AND carry at least the cited line (a range's high end).
902
+ * A path that misses direct (repo-root/absolute) resolution falls back to the
903
+ * tree file whose path ends with it on whole segments — bare basenames and
904
+ * package-relative forms both back the citation iff exactly ONE tree file
905
+ * matches; an ambiguous suffix stays unresolved (the finding names the
906
+ * candidates so the fix arm can disambiguate). A citation that names no real
907
+ * file, or points past end-of-file, is UNBACKED precision — a fabricated
908
+ * reference that must fail the gate rather than propagate into design. A bare
909
+ * `path` with no `:line` is not checked (the contract is "verifiable line
910
+ * numbers, or omit them"). Returns one finding per bad citation.
911
+ */
912
+ /** Trees a citation must never resolve INTO — vendored deps, build copies, or
913
+ * prior pipeline artifacts (a stale artifact copy would back a fabricated line). */
914
+ const CITATION_WALK_SKIP: ReadonlySet<string> = new Set(["node_modules", ".git", "dist", "coverage", ".rpiv"]);
915
+ /** Backstop so a pathological tree can't stall the deterministic cite floor. */
916
+ const CITATION_WALK_FILE_CAP = 50_000;
917
+
918
+ /**
919
+ * Index every source file's basename → its absolute path(s) under `cwd` — the
920
+ * candidate pool behind the suffix fallback in `verifyCitations`. The generative
921
+ * producers (slice/synthesize/elaborate) routinely cite a file by bare basename
922
+ * (`built-in-workflows.ts:1431`) or by a package-relative suffix
923
+ * (`validate/stage-rules.ts:70` for `packages/rpiv-workflow/validate/stage-rules.ts`)
924
+ * — mechanical path-prefix omissions, not fabricated references. The basename
925
+ * keys the candidates; `verifyCitations` narrows them by whole-segment suffix.
926
+ * A UNIQUE match backs the citation; an AMBIGUOUS one stays unresolved so the
927
+ * producer must disambiguate with the repo-root-relative path. Skips
928
+ * vendored/generated trees so a citation never resolves to a build copy or a
929
+ * prior artifact. Bounded by the file cap.
930
+ */
931
+ const buildBasenameIndex = (cwd: string): { index: Map<string, string[]>; truncated: boolean } => {
932
+ // Unreadable dir → empty listing, never a throw from the deterministic floor.
933
+ const listDir = (dir: string) => {
934
+ try {
935
+ return readdirSync(dir, { withFileTypes: true });
936
+ } catch {
937
+ return [];
938
+ }
939
+ };
940
+ const index = new Map<string, string[]>();
941
+ const stack: string[] = [cwd];
942
+ let seen = 0;
943
+ while (stack.length > 0) {
944
+ const dir = stack.pop() as string;
945
+ for (const e of listDir(dir)) {
946
+ if (e.isDirectory()) {
947
+ if (!CITATION_WALK_SKIP.has(e.name)) stack.push(join(dir, e.name));
948
+ continue;
949
+ }
950
+ if (!e.isFile()) continue;
951
+ // Past the cap the index is INCOMPLETE, so "exactly one match" can no
952
+ // longer be trusted — mark it truncated and let the caller disable the
953
+ // fallback (strict direct-resolution only) rather than back a possibly
954
+ // wrong file off a partial walk.
955
+ if (++seen > CITATION_WALK_FILE_CAP) return { index, truncated: true };
956
+ const abs = join(dir, e.name);
957
+ const arr = index.get(e.name);
958
+ if (arr) arr.push(abs);
959
+ else index.set(e.name, [abs]);
960
+ }
961
+ }
962
+ return { index, truncated: false };
963
+ };
964
+
965
+ const verifyCitations = (body: string, cwd: string): { detail: string; where: string }[] => {
966
+ const findings: { detail: string; where: string }[] = [];
967
+ const seen = new Set<string>();
968
+ // Built lazily and reused across citations — only the first direct-resolution
969
+ // miss pays the tree walk, and only when at least one such citation exists.
970
+ let basenameIndex: { index: Map<string, string[]>; truncated: boolean } | undefined;
971
+ // Tree files whose REPO-RELATIVE path ends with the cited path on WHOLE
972
+ // segments. A bare basename is the one-segment case; a multi-segment citation
973
+ // narrows the basename's candidates at a `/` boundary, so `workflow/validate/x.ts`
974
+ // can never match inside `rpiv-workflow/validate/x.ts`. Compared repo-relative
975
+ // (never against the absolute path) so the checkout directory's own name can
976
+ // never back a citation — `src/utils.ts` must not resolve to `<cwd>/utils.ts`
977
+ // just because the repo happens to be cloned at `/tmp/src`.
978
+ const suffixMatches = (path: string): string[] => {
979
+ basenameIndex ??= buildBasenameIndex(cwd);
980
+ if (basenameIndex.truncated) return []; // partial index ⇒ uniqueness untrustworthy ⇒ strict
981
+ const candidates = basenameIndex.index.get(basename(path)) ?? [];
982
+ if (!path.includes("/")) return candidates;
983
+ const suffix = `/${path}`;
984
+ return candidates.filter((abs) =>
985
+ `/${abs
986
+ .slice(cwd.length + 1)
987
+ .split(sep)
988
+ .join("/")}`.endsWith(suffix),
989
+ );
990
+ };
991
+ for (const m of body.matchAll(FILE_LINE_CITATION_RE)) {
992
+ const [, path, startStr, endStr] = m;
993
+ if (!path || !startStr) continue;
994
+ const key = `${path}:${startStr}${endStr ? `-${endStr}` : ""}`;
995
+ if (seen.has(key)) continue;
996
+ seen.add(key);
997
+ const direct = isAbsolute(path) ? path : join(cwd, path);
998
+ let abs: string | undefined;
999
+ if (existsSync(direct) && statSync(direct).isFile()) {
1000
+ abs = direct;
1001
+ } else {
1002
+ // Suffix fallback: back the citation iff exactly ONE tree file matches.
1003
+ const matches = suffixMatches(path);
1004
+ if (matches.length === 1) {
1005
+ abs = matches[0];
1006
+ } else if (matches.length > 1) {
1007
+ const shown = matches.slice(0, 3).map((a) => (a.startsWith(cwd + sep) ? a.slice(cwd.length + 1) : a));
1008
+ findings.push({
1009
+ detail: `Unbacked citation ${key} — ${path} matches ${matches.length} tree files (${shown.join(", ")}${matches.length > shown.length ? ", …" : ""}); a citation must name ONE file. Disambiguate with the repo-root-relative path.`,
1010
+ where: key,
1011
+ });
1012
+ continue;
1013
+ }
1014
+ }
1015
+ if (!abs) {
1016
+ findings.push({
1017
+ detail: `Unbacked citation ${key} — the cited file does not exist at this revision. A file:line citation must resolve, or the line numbers must be omitted. Fix the path (repo-root-relative) or drop the citation.`,
1018
+ where: key,
1019
+ });
1020
+ continue;
1021
+ }
1022
+ // A file that vanishes or turns unreadable between resolution and the read
1023
+ // is an unbacked citation, never a throw out of the deterministic floor.
1024
+ let lineCount: number;
1025
+ try {
1026
+ lineCount = readFileSync(abs, "utf-8").split("\n").length;
1027
+ } catch {
1028
+ findings.push({
1029
+ detail: `Unbacked citation ${key} — ${path} resolved but could not be read at this revision. A file:line citation must be verifiable, or the line numbers must be omitted. Fix the path (repo-root-relative) or drop the citation.`,
1030
+ where: key,
1031
+ });
1032
+ continue;
1033
+ }
1034
+ const high = Math.max(Number(startStr), endStr ? Number(endStr) : 0);
1035
+ if (high > lineCount) {
1036
+ findings.push({
1037
+ detail: `Unbacked citation ${key} — ${path} has ${lineCount} lines, so line ${high} matches no version of the file. A file:line citation must be verifiable, or the line numbers must be omitted. Correct the range or drop the line numbers.`,
1038
+ where: key,
1039
+ });
1040
+ }
1041
+ }
1042
+ return findings;
1043
+ };
1044
+
1045
+ /**
1046
+ * Deterministic Phase-1 slice-check — the un-gameable floor beneath the LLM
1047
+ * `design-readiness` panel. It enforces the invariants a prose grader cannot
1048
+ * reliably hold because it grades the slicer's own self-description:
1049
+ * • acyclicity — the `deps` DAG must be cycle-free.
1050
+ * • coverage conservation — every coverage unit FROZEN at the first cut
1051
+ * (`state.named.slices[0]`) must still be claimed by ≥1 slice's `covers`,
1052
+ * so a reslice can only redistribute the brief, never simplify by dropping
1053
+ * scope. Anchored to the FIRST cut (not the latest map) so a reslice cannot
1054
+ * disable the check by deleting the `coverage:` array — the frozen set is
1055
+ * read from round 0.
1056
+ * • citation backing — every `file:line` the slice map cites (its `Draws on:`
1057
+ * footing, refracted up from research) must resolve against the tree. An
1058
+ * unbacked citation is fabricated precision that would otherwise starve or
1059
+ * mislead the design pass; the deterministic floor stops it here.
1060
+ * Emits one combined `{ dimension: "structure" }` verdict onto the
1061
+ * `slice-check` channel AND writes it to an fs artifact so the reslice arm's
1062
+ * `reads: [fanin("slice-check")]` projection carries the FINDINGS (not just the
1063
+ * pass/fail) into `slice-fix` — the way `amend` receives `--code-verdicts`. The
1064
+ * gate route folds the channel `data` with the LLM verdicts.
1065
+ * Deterministic ⇒ idempotent across reslice rounds (no flicker, resume-safe): the
1066
+ * verdict basename is keyed on the slice-map basename, so a re-run OVERWRITES its
1067
+ * own slot rather than duplicating it.
1068
+ */
1069
+ const sliceStructureCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1070
+ const latest = latestFsArtifact(state, "slices");
1071
+ if (latest?.handle.kind !== "fs") {
1072
+ throw haltPreflight(
1073
+ "slice-check",
1074
+ "slice-check: no slice map to check",
1075
+ "slice-check: no fs artifact on the 'slices' channel — slice must run before the structure check",
1076
+ );
1077
+ }
1078
+ const mapBody = readArtifactFile(latest.handle.path, cwd);
1079
+ const records = sliceRecords(mapBody, "slice-check", latest.handle.path);
1080
+ const findings: { detail: string; where: string }[] = [];
1081
+
1082
+ const cycle = sliceDepCycle(records);
1083
+ if (cycle.length > 0) {
1084
+ const loop = [...cycle, cycle[0]].join("→");
1085
+ findings.push({
1086
+ detail: `Dependency cycle ${loop} — slices in a cycle cannot be designed independently. Break it: merge the cycle into one slice, or invert one edge so a shared contract has a single owning slice.`,
1087
+ where: `deps: ${cycle.map((n) => `Slice ${n}`).join(", ")}`,
1088
+ });
1089
+ }
1090
+
1091
+ // Coverage conservation, anchored to the FROZEN units of the first cut.
1092
+ const firstFs = state.named.slices?.[0]?.artifacts.find((a) => a.handle.kind === "fs");
1093
+ const frozen = firstFs?.handle.kind === "fs" ? sliceCoverageUnits(readArtifactFile(firstFs.handle.path, cwd)) : [];
1094
+ if (frozen.length > 0) {
1095
+ const covered = new Set(records.flatMap((r) => sliceCovers(r.entry)));
1096
+ const dropped = frozen.filter((u) => !covered.has(u.id));
1097
+ if (dropped.length > 0) {
1098
+ findings.push({
1099
+ detail: `Coverage regression — ${dropped.length} brief unit(s) frozen at the first cut are no longer claimed by any slice's 'covers': ${dropped.map((u) => `${u.id} (${u.brief})`).join("; ")}. A reslice must redistribute every unit across slices, never drop one. Re-add the dropped unit(s) to an owning slice's 'covers'.`,
1100
+ where: `coverage: ${dropped.map((u) => u.id).join(", ")}`,
1101
+ });
1102
+ }
1103
+ }
1104
+
1105
+ // Citation backing — every file:line the map cites must resolve.
1106
+ findings.push(...verifyCitations(mapBody, cwd));
1107
+
1108
+ const pass = findings.length === 0;
1109
+ const data = {
1110
+ dimension: "structure",
1111
+ pass,
1112
+ score: pass ? 100 : 0,
1113
+ severity: pass ? "none" : "high",
1114
+ artifact: handleToString(latest.handle),
1115
+ findings,
1116
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
1117
+ };
1118
+ // Write the verdict to an fs artifact so slice-fix's fanin projection forwards
1119
+ // the findings, not just the rolling pass/fail. Basename-keyed off the slice map
1120
+ // ⇒ idempotent across reslice rounds.
1121
+ const rel = join(VERDICT_DIR, `slice-check__${basename(latest.handle.path, ".md")}.json`);
1122
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
1123
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
1124
+ return {
1125
+ kind: "json",
1126
+ artifacts: [{ handle: { kind: "fs", path: rel } }],
1127
+ data,
1128
+ };
1129
+ };
1130
+
1131
+ /**
1132
+ * Deterministic citation floor for a synthesized/spliced plan — the plan-scope
1133
+ * twin of `sliceStructureCheck`'s citation backing, extending finding 6 past the
1134
+ * slice map to the plan and the code-bearing plan (a fabricated `file:line` in
1135
+ * the plan misdirects `implement`, exactly the #103 class). Verifies every
1136
+ * citation resolves against the working tree and emits a `{ dimension:
1137
+ * "structure" }` verdict on `who`'s channel that the gate route folds via
1138
+ * `allDimensionsPass`; the matching `<fix>` stage reads `fanin(who)` so the
1139
+ * findings DRIVE the amend rather than blind-halt. Reuses `verifyCitations` — no
1140
+ * fuzzy wrong-symbol heuristic. Basename-keyed ⇒ idempotent across fix rounds.
1141
+ */
1142
+ const planCitationCheck =
1143
+ (who: string) =>
1144
+ ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1145
+ const latest = latestFsArtifact(state, "plans");
1146
+ if (latest?.handle.kind !== "fs") {
1147
+ throw haltPreflight(
1148
+ who,
1149
+ `${who}: no plan to check`,
1150
+ `${who}: no fs artifact on the 'plans' channel — the plan must be produced before the citation check`,
1151
+ );
1152
+ }
1153
+ const body = readArtifactFile(latest.handle.path, cwd);
1154
+ const findings = verifyCitations(body, cwd);
1155
+ const pass = findings.length === 0;
1156
+ const data = {
1157
+ dimension: "structure",
1158
+ pass,
1159
+ score: pass ? 100 : 0,
1160
+ severity: pass ? "none" : "high",
1161
+ artifact: handleToString(latest.handle),
1162
+ findings,
1163
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
1164
+ };
1165
+ const rel = join(VERDICT_DIR, `${who}__${basename(latest.handle.path, ".md")}.json`);
1166
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
1167
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
1168
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
1169
+ };
1170
+
1171
+ /** A design filename encodes its slice as `…slice-<N>…` — the design-fanout naming convention. */
1172
+ const DESIGN_SLICE_RE = /slice-(\d+)/;
1173
+
1174
+ /**
1175
+ * Map slice number → its design artifact path, from the design fanout's published
1176
+ * outputs. An identity resolver: it maps an ARTIFACT to a slice NUMBER. It FAILS
1177
+ * LOUD only when identity is genuinely UNRESOLVABLE — a design filename that
1178
+ * carries no `slice-<N>` token, where a positional `idx + 1` guess would scramble
1179
+ * the cluster→design wiring and drop slices.
1180
+ *
1181
+ * A slice claimed by MORE THAN ONE output is NOT ambiguous: the `designs` channel
1182
+ * legitimately accumulates several entries per slice — `slice-design` emits it,
1183
+ * then `design-review` re-emits the accepted/edited design on the SAME channel
1184
+ * (its documented "latest-wins, same paths" contract, so `subplan`/`synthesize`
1185
+ * read the accepted docs). So the newest entry wins, deterministically — throwing
1186
+ * on a duplicate would halt every normal run at `subplan`. (The resume re-dispatch
1187
+ * that once left CONFLICTING designs on the channel is fixed at its source —
1188
+ * finding 7 — so there is no corruption left to fail loud on here.)
1189
+ */
1190
+ const designPathsBySlice = (state: RunView): Map<number, string> => {
1191
+ const bySlice = new Map<number, string>();
1192
+ for (const out of state.named.designs ?? []) {
1193
+ for (const a of out.artifacts) {
1194
+ if (a.handle.kind !== "fs") continue;
1195
+ const name = basename(a.handle.path);
1196
+ const match = DESIGN_SLICE_RE.exec(name);
1197
+ if (!match) {
1198
+ throw haltPreflight(
1199
+ "designPathsBySlice",
1200
+ `designPathsBySlice: design ${name} has no slice number`,
1201
+ `designPathsBySlice: design artifact ${a.handle.path} carries no 'slice-<N>' token — cannot resolve which slice it designs; a positional guess would mis-route the cluster→design mapping and drop slices`,
1202
+ );
1203
+ }
1204
+ // Latest design per slice wins — the channel holds multiple entries per
1205
+ // slice by design (design-review re-emits), and the newest is authoritative.
1206
+ bySlice.set(Number(match[1]), handleToString(a.handle));
1207
+ }
1208
+ }
1209
+ return bySlice;
1210
+ };
1211
+
1212
+ /**
1213
+ * Fan `subplan` out over slice-DAG clusters. Each unit merges ONE cluster's
1214
+ * per-slice designs into a sub-plan (`--as-subplan`), so no single pass holds
1215
+ * every design — the context-bounding twin of the flat fan-in `synthesize`.
1216
+ */
1217
+ const SYNTH_CLUSTER_FANOUT = fanout({
1218
+ source: "designs",
1219
+ unit: { by: "slice-dag-cluster", pattern: "clusters" },
1220
+ max: MAX_PHASES,
1221
+ units: ({ state, cwd }) => {
1222
+ const doc = latestFsArtifact(state, "slices");
1223
+ if (doc?.handle.kind !== "fs") return [];
1224
+ const records = sliceRecords(readArtifactFile(doc.handle.path, cwd), "SYNTH_CLUSTER_FANOUT", doc.handle.path);
1225
+ const designBySlice = designPathsBySlice(state);
1226
+ // Thread the research the slices rest on into every cluster's subplan pass,
1227
+ // so cross-slice constraints and acceptance criteria reach synthesis DIRECTLY
1228
+ // (not only via each design's refraction). `synthesize` accepts `--research`
1229
+ // in partial mode; the flat `synthesize` fan-in already received it, but the
1230
+ // hierarchical cluster fanout dropped it.
1231
+ const research = latestFsArtifact(state, "research");
1232
+ const researchFlag = research?.handle.kind === "fs" ? ` --research ${handleToString(research.handle)}` : "";
1233
+ return clusterSliceDag(records)
1234
+ .map((cluster, i) => {
1235
+ const designs = cluster
1236
+ .map((n) => designBySlice.get(n))
1237
+ .filter((p): p is string => p !== undefined)
1238
+ .map((p) => `--designs ${p}`);
1239
+ if (!designs.length) return undefined;
1240
+ return {
1241
+ prompt: `${designs.join(" ")}${researchFlag} --as-subplan`,
1242
+ label: `cluster ${i + 1} (slices ${cluster.join(",")})`,
1243
+ id: `cluster-${i + 1}`,
1244
+ };
1245
+ })
1246
+ .filter((u): u is { prompt: string; label: string; id: string } => u !== undefined);
1247
+ },
1248
+ });
1249
+
1250
+ /**
1251
+ * The two dimensions the grade panels anchor against the verbatim brief.
1252
+ * "Complete" and "correct" MEAN "against what the user asked" — without the
1253
+ * goal, completeness grades the plan against the plan's own claims. The other
1254
+ * dimensions (and the slice gate's `design-readiness`) deliberately stay
1255
+ * goal-blind: fit/actionability/pattern-following judge the artifact against
1256
+ * the codebase, and an ambient goal at those seams invites scope inflation.
1257
+ */
1258
+ const GOAL_DIMENSIONS: ReadonlySet<string> = new Set(["completeness", "correctness"]);
1259
+
1260
+ // ---------------------------------------------------------------------------
1261
+ // Adaptive gate scaling — tier, roster, verdict freshness.
1262
+ // ---------------------------------------------------------------------------
1263
+
1264
+ /** Latest `data` record published under `name` (undefined when absent/non-record). */
1265
+ const latestChannelData = (state: RunView, name: string): Record<string, unknown> | undefined => {
1266
+ const data = state.named[name]?.at(-1)?.data;
1267
+ return data !== null && typeof data === "object" && !Array.isArray(data)
1268
+ ? (data as Record<string, unknown>)
1269
+ : undefined;
1270
+ };
1271
+
1272
+ /** A finite numeric field off the latest `data` on `name` (undefined otherwise). */
1273
+ const channelNumber = (state: RunView, name: string, field: string): number | undefined => {
1274
+ const v = latestChannelData(state, name)?.[field];
1275
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
1276
+ };
1277
+
1278
+ /** Repo-relative path of the latest fs artifact on `name` (undefined if none). */
1279
+ const latestArtifactPath = (state: RunView, name: string): string | undefined => {
1280
+ const a = latestFsArtifact(state, name);
1281
+ return a?.handle.kind === "fs" ? handleToString(a.handle) : undefined;
1282
+ };
1283
+
1284
+ /**
1285
+ * Gate scrutiny tier, derived ONLY from signals already replayed by the resume
1286
+ * fold (the slices/plans channels' frontmatter data and the gate's own verdict
1287
+ * severities) — deterministic by construction, so routes and fanout units that
1288
+ * consult it stay resume-safe.
1289
+ *
1290
+ * `risks:` flags are deliberately NOT a tier signal: `synthesize` declares
1291
+ * them routinely (observed: 1-phase plans shipping 2-3 flags), so counting
1292
+ * them would push every small run out of the light tier. Risk flags are
1293
+ * already force-ruled per dimension via `risk_rulings`, and a blocking
1294
+ * verdict lifts the tier on its own (below).
1295
+ *
1296
+ * A missing signal never yields light, and verdict severities are read over
1297
+ * the FULL channel history (a stale medium/high is still evidence of a risky
1298
+ * run) — ambiguity always resolves toward more scrutiny.
1299
+ */
1300
+ type GateTier = "light" | "standard" | "strict";
1301
+ const TIER_LIGHT_MAX_SLICES = 1;
1302
+ const TIER_LIGHT_MAX_PHASES = 2;
1303
+ const TIER_STRICT_MIN_SLICES = 5;
1304
+ const TIER_STRICT_MIN_PHASES = 6;
1305
+
1306
+ /**
1307
+ * The dimensions a light-tier run still grades: correctness and completeness
1308
+ * are the two whose failures ship real defects (and the two that anchor on the
1309
+ * goal); fit/actionability/pattern-following are low-consequence on a
1310
+ * one-slice, <=2-phase diff, and `validate` still runs at every tier.
1311
+ */
1312
+ const LIGHT_ROSTER: ReadonlySet<string> = new Set(["correctness", "completeness"]);
1313
+
1314
+ const gateTier = (state: RunView, verdictChannel: string): GateTier => {
1315
+ const slices = channelNumber(state, "slices", "slice_count");
1316
+ const phases = channelNumber(state, "plans", "phase_count");
1317
+ const severities = new Set<string>();
1318
+ for (const o of state.named[verdictChannel] ?? []) {
1319
+ const s = (o.data as { severity?: unknown } | undefined)?.severity;
1320
+ if (typeof s === "string") severities.add(s);
1321
+ }
1322
+ if (
1323
+ (slices !== undefined && slices >= TIER_STRICT_MIN_SLICES) ||
1324
+ (phases !== undefined && phases >= TIER_STRICT_MIN_PHASES) ||
1325
+ severities.has("high")
1326
+ ) {
1327
+ return "strict";
1328
+ }
1329
+ if (
1330
+ slices !== undefined &&
1331
+ slices <= TIER_LIGHT_MAX_SLICES &&
1332
+ phases !== undefined &&
1333
+ phases <= TIER_LIGHT_MAX_PHASES &&
1334
+ !severities.has("medium")
1335
+ ) {
1336
+ return "light";
1337
+ }
1338
+ return "standard";
1339
+ };
1340
+
1341
+ /**
1342
+ * The subset of `dimensions` the tier actually grades. Never empty: a
1343
+ * dimension list with no light-roster member (the slice gate's lone
1344
+ * `design-readiness`) keeps its full list at every tier.
1345
+ */
1346
+ const gateRoster = (tier: GateTier, dimensions: readonly string[]): readonly string[] => {
1347
+ if (tier !== "light") return dimensions;
1348
+ const light = dimensions.filter((d) => LIGHT_ROSTER.has(d));
1349
+ return light.length > 0 ? light : dimensions;
1350
+ };
1351
+
1352
+ /**
1353
+ * Drop verdicts judged against an artifact the channel has since REPLACED. A
1354
+ * grade verdict embeds the `artifact` path it judged; when a fix REGENERATES
1355
+ * the artifact (`slice-fix` re-slices to a NEW file) a passing verdict on the
1356
+ * old document must not carry forward to a document that was never judged —
1357
+ * the carry-forward would otherwise let a regenerated slice map skip its
1358
+ * design-readiness judgment entirely. An in-place `amend` keeps the path, so
1359
+ * the plan-fix/code-fix carry-forward is unaffected. A verdict without an
1360
+ * `artifact` field (older trails, the deterministic structure checks) is kept:
1361
+ * matching is the compat default.
1362
+ */
1363
+ const freshVerdicts = (entries: readonly Output[] = [], currentArtifact?: string): readonly Output[] => {
1364
+ if (!currentArtifact) return entries;
1365
+ const current = basename(currentArtifact);
1366
+ return entries.filter((o) => {
1367
+ const a = (o.data as { artifact?: unknown } | undefined)?.artifact;
1368
+ return typeof a !== "string" || a.length === 0 || basename(a) === current;
1369
+ });
1370
+ };
1371
+
1372
+ /**
1373
+ * Latest verdict per dimension off an accumulated verdict channel — the shared
1374
+ * fold under `dimensionsToRegrade` (which dimensions still block) and the
1375
+ * confirm panels' `--prior` threading (which verdict file the confirming
1376
+ * grader must adjudicate).
1377
+ */
1378
+ const latestVerdictPerDimension = (entries: readonly Output[] = []): Map<string, Output> => {
1379
+ const latest = new Map<string, Output>();
1380
+ for (const o of entries) {
1381
+ const dim = (o.data as { dimension?: unknown } | undefined)?.dimension;
1382
+ if (typeof dim === "string") latest.set(dim, o);
1383
+ }
1384
+ return latest;
1385
+ };
1386
+
1387
+ /**
1388
+ * The subset of `dimensions` a re-grade must actually re-run, given the latest
1389
+ * verdict per dimension accumulated so far. A dimension needs re-grading when it
1390
+ * has NO prior verdict (first pass ⇒ grade every dimension), when its latest
1391
+ * verdict fails above the severity floor, or when that verdict ruled any plan
1392
+ * risk flag `fail` (the ruling is re-opened by re-grading its owning dimension).
1393
+ * A dimension that already passed — dimension AND its risk rulings — is carried
1394
+ * forward untouched: re-running it after a surgical fix only re-rolls a free LLM
1395
+ * judgment that flaps pass↔fail on an unchanged artifact, manufacturing extra
1396
+ * loops (the observed correctness risk-flag flap). The accumulating verdict
1397
+ * channel + `allDimensionsPass`'s latest-per-dimension fold mean a carried
1398
+ * dimension's prior passing verdict still counts at the gate.
1399
+ */
1400
+ const dimensionsToRegrade = (dimensions: readonly string[], latest: ReadonlyMap<string, Output>): string[] => {
1401
+ return dimensions.filter((d) => {
1402
+ const o = latest.get(d);
1403
+ if (!o) return true; // never graded — must grade at least once
1404
+ const v = o.data as { pass?: boolean; severity?: string } | undefined;
1405
+ const dimPass = v?.pass === true || v?.severity === "low" || v?.severity === "none";
1406
+ if (!dimPass) return true;
1407
+ const raw = (o.data as { risk_rulings?: unknown } | undefined)?.risk_rulings;
1408
+ return Array.isArray(raw) && raw.some((e) => (e as { pass?: unknown })?.pass !== true);
1409
+ });
1410
+ };
1411
+
1412
+ /**
1413
+ * A grade panel: one `grade` session per dimension over the latest artifact on
1414
+ * `channel`. Each unit's prompt is the `grade` skill's flags
1415
+ * (`--dimension <d> --artifact <path>`); the per-dimension verdicts fold via
1416
+ * `allDimensionsPass`. Shared by the slice gate (over `slices`) and the plan +
1417
+ * code gates (over `plans`), each on its own `verdictChannel`.
1418
+ *
1419
+ * The panel grades the tier's ROSTER (`gateTier`/`gateRoster`), over verdicts
1420
+ * still FRESH for the current artifact (`freshVerdicts`) — a light run grades
1421
+ * two dimensions, a regenerated artifact re-grades from scratch. On a re-grade
1422
+ * it emits ONLY the dimensions `dimensionsToRegrade` says still need it (the
1423
+ * rest carry their prior passing verdict forward) — but never an EMPTY set: an
1424
+ * empty `units()` return falls through to a single dimensionless `grade`
1425
+ * dispatch, so when nothing needs re-grading we fall back to the full roster.
1426
+ * The route into the stage already skips it entirely when the accumulated
1427
+ * verdicts clear the gate (see `plan-cite-check`/`code-cite-check`/`slice-check`
1428
+ * edges), so this fallback only fires in the degenerate case where a fix left the
1429
+ * cite floor red while every dimension passed.
1430
+ *
1431
+ * `architecture-fit` is the one dimension `grade` requires a `--context` for: it
1432
+ * grades the plan against the research the slices rest on. The build flow always
1433
+ * front-loads a `research` stage, so we thread the latest `research` artifact in
1434
+ * as `--context` for that dimension only; likewise the latest `goal` artifact
1435
+ * threads in as `--goal` for the `GOAL_DIMENSIONS` only. Every other dimension
1436
+ * (and the slice gate's `design-readiness`, which never grades fit or
1437
+ * goal-completeness) gets the bare flags.
1438
+ *
1439
+ * A CONFIRM panel (`confirm: true`) additionally threads each still-blocking
1440
+ * dimension's latest verdict in as `--prior`: the confirming grader must
1441
+ * adjudicate the prior round's findings — uphold or refute each with cited
1442
+ * evidence — instead of silently out-voting them (a blind second opinion once
1443
+ * rationalized past a checkable fact and its pass overwrote a correct fail at
1444
+ * the latest-per-dimension fold). Only PENDING dimensions get the flag: in the
1445
+ * degenerate full-roster fallback a carried passing verdict has nothing to
1446
+ * adjudicate, and a first grade has no prior at all.
1447
+ */
1448
+ const gradePanelFanout = (
1449
+ channel: string,
1450
+ dimensions: readonly string[],
1451
+ verdictChannel: string,
1452
+ { confirm = false }: { confirm?: boolean } = {},
1453
+ ) =>
1454
+ fanout({
1455
+ source: channel,
1456
+ unit: { by: "dimension-list", pattern: "dimensions" },
1457
+ max: dimensions.length,
1458
+ units: ({ state }) => {
1459
+ const doc = latestFsArtifact(state, channel);
1460
+ if (doc?.handle.kind !== "fs") return [];
1461
+ const target = handleToString(doc.handle);
1462
+ const research = latestFsArtifact(state, "research");
1463
+ const contextFlag = research?.handle.kind === "fs" ? ` --context ${handleToString(research.handle)}` : "";
1464
+ const goal = latestFsArtifact(state, "goal");
1465
+ const goalFlag = goal?.handle.kind === "fs" ? ` --goal ${handleToString(goal.handle)}` : "";
1466
+ const roster = gateRoster(gateTier(state, verdictChannel), dimensions);
1467
+ const latest = latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel], target));
1468
+ const pending = dimensionsToRegrade(roster, latest);
1469
+ const priorFlag = (d: string): string => {
1470
+ if (!confirm || !pending.includes(d)) return "";
1471
+ const handle = latest.get(d)?.artifacts.find((a) => a.handle.kind === "fs")?.handle;
1472
+ return handle ? ` --prior ${handleToString(handle)}` : "";
1473
+ };
1474
+ // Never emit zero units (empty ⇒ single dimensionless grade fall-through).
1475
+ const toGrade = pending.length > 0 ? pending : roster;
1476
+ return toGrade.map((d) => ({
1477
+ prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}${priorFlag(d)}`,
1478
+ label: d,
1479
+ id: `${channel}-dim-${d}`,
1480
+ }));
1481
+ },
1482
+ });
1483
+
1484
+ const SLICE_DIMENSION_FANOUT = gradePanelFanout("slices", SLICE_DIMENSIONS, "slice-verdicts");
1485
+ const PLAN_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts");
1486
+ // The post-splice code gate re-grades the SAME `plans` artifact on its own
1487
+ // `code-verdicts` channel, so its carry-forward reads the code gate's verdicts,
1488
+ // never the pre-elaborate plan gate's.
1489
+ const CODE_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts");
1490
+ // The confirm stages re-run the SAME panel machinery on the SAME verdict
1491
+ // channel: with the failing dimensions the only ones pending, the panel emits
1492
+ // exactly the blocking dimensions — one second judgment each, in confirm mode:
1493
+ // each unit carries the blocking verdict as `--prior`, and the grade skill is
1494
+ // contract-bound to rule on every prior finding (uphold, or refute with cited
1495
+ // evidence) so a confirming pass records WHY the fail died instead of silently
1496
+ // out-voting it at the latest-per-dimension fold.
1497
+ // Distinct fanout instances (not aliases) so each stage owns its loop object.
1498
+ const PLAN_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts", { confirm: true });
1499
+ const CODE_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts", { confirm: true });
1500
+
1501
+ /**
1502
+ * Fold the per-dimension verdicts into a gate decision: keep the latest verdict
1503
+ * per dimension (verdicts accumulate across fix loops), require all-pass.
1504
+ * Deterministic ⇒ resume-safe for a `readsData: false` route.
1505
+ *
1506
+ * Severity floor: a verdict whose worst finding is `low`/`none` never blocks the
1507
+ * gate, even when the grader set `pass: false` on a nit. `grade` decides `pass`
1508
+ * by a free judgment against a prose bar (independent of `severity`), so a
1509
+ * marginal dimension can flip pass↔fail across rounds on an unchanged artifact —
1510
+ * that flapping, ANDed over a 5-dimension panel, stalled the build gate loops
1511
+ * until the backward-jump guard halted them. Flooring on severity reserves a hard
1512
+ * fail for `medium`+ findings (the deterministic `slice-check` check emits
1513
+ * `high` on a real structural break, so it still blocks). A verdict with no
1514
+ * `severity` (an older or replayed grade) falls back to the raw `pass` boolean.
1515
+ */
1516
+ const allDimensionsPass = (entries: readonly Output[] = [], roster?: readonly string[]): boolean => {
1517
+ // Roster-filtered when given: a verdict for a dimension outside the tier's
1518
+ // roster (a wider earlier round, a shrunk re-slice) neither blocks nor passes
1519
+ // a gate it no longer governs.
1520
+ const member = roster ? new Set(roster) : undefined;
1521
+ const latest = new Map<string, boolean>();
1522
+ for (const o of entries) {
1523
+ const v = o.data as { dimension?: string; pass?: boolean; severity?: string } | undefined;
1524
+ if (typeof v?.dimension !== "string") continue;
1525
+ if (member && !member.has(v.dimension)) continue;
1526
+ const lowOrNone = v.severity === "low" || v.severity === "none";
1527
+ latest.set(v.dimension, v.pass === true || lowOrNone);
1528
+ }
1529
+ const verdicts = [...latest.values()];
1530
+ return verdicts.length > 0 && verdicts.every(Boolean);
1531
+ };
1532
+
1533
+ /**
1534
+ * One plan-authored risk flag ruled by a grade panel. The plan declares a
1535
+ * `risks:` frontmatter array (`{ id, claim }`) — the structured, first-class
1536
+ * channel that replaces the old prose-in-a-Notes-section flagging that graders
1537
+ * were free to skip. Each grade verdict that engages a flag emits a ruling here.
1538
+ */
1539
+ interface RiskRuling {
1540
+ id: string;
1541
+ pass: boolean;
1542
+ }
1543
+
1544
+ /** The `risk_rulings` a grade verdict emitted (empty when it ruled on none). */
1545
+ const verdictRiskRulings = (o: Output): RiskRuling[] => {
1546
+ const raw = (o.data as { risk_rulings?: unknown } | undefined)?.risk_rulings;
1547
+ if (!Array.isArray(raw)) return [];
1548
+ return raw.flatMap((e) => {
1549
+ const r = (e ?? {}) as Record<string, unknown>;
1550
+ return typeof r.id === "string" ? [{ id: r.id, pass: r.pass === true }] : [];
1551
+ });
1552
+ };
1553
+
1554
+ /**
1555
+ * Fold the grade panel's per-flag risk rulings into a gate decision: every
1556
+ * plan-authored risk flag the panel ruled on must be ruled PASS (latest ruling
1557
+ * per flag wins, mirroring `allDimensionsPass`). A flag ruled `fail` — the
1558
+ * grader confirmed the risk is real and unaddressed — blocks the gate, so a
1559
+ * self-flagged risk (e.g. the #103 override-vs-env validation bug) can no longer
1560
+ * ride a green conformance pass into commit. An empty panel (no flag engaged)
1561
+ * imposes no constraint; the plan simply declared no risks.
1562
+ */
1563
+ const allRiskFlagsPass = (entries: readonly Output[] = []): boolean => {
1564
+ const latest = new Map<string, boolean>();
1565
+ for (const o of entries) for (const r of verdictRiskRulings(o)) latest.set(r.id, r.pass);
1566
+ return [...latest.values()].every(Boolean);
1567
+ };
1568
+
1569
+ /**
1570
+ * The three gates' pass predicates — the SINGLE authority each gate consults at
1571
+ * BOTH of its seams. A gate is satisfied when its deterministic cite/structure
1572
+ * floor is green AND every quality dimension passes (severity-floored) AND — for
1573
+ * the plan/code gates — every plan-authored risk flag is ruled pass.
1574
+ *
1575
+ * Reading the identical predicate at the cite/structure-check edge (which SKIPS
1576
+ * the re-grade straight to the next stage) and at the grade edge (which gates
1577
+ * forward-vs-fix) makes the skip provably equivalent to "re-grade, then pass",
1578
+ * minus the wasted panel: after a fix that only cleared the deterministic floor,
1579
+ * the accumulated verdicts already clear the gate, so re-running the LLM panel
1580
+ * would at best reproduce them and at worst flap a passing dimension into a
1581
+ * spurious fix loop. On the FIRST pass the verdict channel is empty, so
1582
+ * `allDimensionsPass` returns false and the edge correctly routes INTO the grade
1583
+ * panel. Any regression a fix introduces is still caught downstream: the plan
1584
+ * gate by the full first-time `code-grade`, the code gate by `validate`.
1585
+ */
1586
+ // Each predicate folds the verdicts still FRESH for the channel's current
1587
+ // artifact, restricted to the tier's roster — the SAME projections the panel's
1588
+ // `units()` uses, so "skip the re-grade" stays provably equivalent to
1589
+ // "re-grade, then pass". The deterministic cite/structure channels fold
1590
+ // unfiltered: they re-run every round and carry no tier.
1591
+ const sliceGatePasses = (state: RunView): boolean => {
1592
+ const fresh = freshVerdicts(state.named["slice-verdicts"], latestArtifactPath(state, "slices"));
1593
+ const roster = gateRoster(gateTier(state, "slice-verdicts"), SLICE_DIMENSIONS);
1594
+ return allDimensionsPass(state.named["slice-check"]) && allDimensionsPass(fresh, roster);
1595
+ };
1596
+ const planGatePasses = (state: RunView): boolean => {
1597
+ const fresh = freshVerdicts(state.named["plan-verdicts"], latestArtifactPath(state, "plans"));
1598
+ const roster = gateRoster(gateTier(state, "plan-verdicts"), PLAN_DIMENSIONS);
1599
+ return (
1600
+ allDimensionsPass(state.named["plan-cite-check"]) && allDimensionsPass(fresh, roster) && allRiskFlagsPass(fresh)
1601
+ );
1602
+ };
1603
+ const codeGatePasses = (state: RunView): boolean => {
1604
+ const fresh = freshVerdicts(state.named["code-verdicts"], latestArtifactPath(state, "plans"));
1605
+ const roster = gateRoster(gateTier(state, "code-verdicts"), PLAN_DIMENSIONS);
1606
+ return (
1607
+ allDimensionsPass(state.named["code-cite-check"]) && allDimensionsPass(fresh, roster) && allRiskFlagsPass(fresh)
1608
+ );
1609
+ };
1610
+
1611
+ /**
1612
+ * Confirm-before-block: a dimension's FIRST blocking verdict against the
1613
+ * current artifact gets ONE independent second judgment before it buys a fix
1614
+ * round. Single-judge verdicts observably flap (pass/score/severity disagree
1615
+ * across rolls on a near-unchanged artifact), and a spurious block
1616
+ * manufactures an entire grade→fix cycle. Routing to the confirm stage
1617
+ * re-runs only the pending dimensions on the same verdict channel;
1618
+ * latest-per-dimension wins, so a confirming pass clears the gate and a
1619
+ * confirming fail routes to the fix with two agreeing judgments behind it. A
1620
+ * blocker already judged twice for this artifact routes straight to the fix —
1621
+ * confirmation is one extra opinion, not an unbounded re-roll.
1622
+ *
1623
+ * No tier guard is needed: a blocking verdict is medium+ by the severity
1624
+ * floor, and a medium+ severity already lifts `gateTier` out of light — every
1625
+ * run with a genuine blocker has confirm-level scrutiny by construction.
1626
+ */
1627
+ const confirmDue = (
1628
+ state: RunView,
1629
+ channel: string,
1630
+ verdictChannel: string,
1631
+ dimensions: readonly string[],
1632
+ ): boolean => {
1633
+ const roster = new Set(gateRoster(gateTier(state, verdictChannel), dimensions));
1634
+ const fresh = freshVerdicts(state.named[verdictChannel], latestArtifactPath(state, channel));
1635
+ const byDim = new Map<string, { blocking: boolean; count: number }>();
1636
+ for (const o of fresh) {
1637
+ const v = o.data as { dimension?: string; pass?: boolean; severity?: string } | undefined;
1638
+ if (typeof v?.dimension !== "string" || !roster.has(v.dimension)) continue;
1639
+ const floored = v.pass === true || v.severity === "low" || v.severity === "none";
1640
+ const riskFail = verdictRiskRulings(o).some((r) => !r.pass);
1641
+ byDim.set(v.dimension, {
1642
+ blocking: !floored || riskFail,
1643
+ count: (byDim.get(v.dimension)?.count ?? 0) + 1,
1644
+ });
1645
+ }
1646
+ const blockers = [...byDim.values()].filter((e) => e.blocking);
1647
+ return blockers.length > 0 && blockers.some((e) => e.count < 2);
1648
+ };
1649
+
1650
+ /**
1651
+ * Verdict channels — grade writes JSON to `.rpiv/artifacts/verdicts/`, so these
1652
+ * use the JSON directory collector + `jsonBodyParser` (NOT the md
1653
+ * `rpivBucketOutcome`). The slice gate and plan gate publish to DISTINCT named
1654
+ * channels (same dir, different artifact basenames) so their verdicts never
1655
+ * collide and `plan-fix`/`code-fix` can pick each via the `-verdicts` suffix convention.
1656
+ */
1657
+ const verdictOutcome = (name: string) => ({
1658
+ name,
1659
+ collector: directoryPathCollector({ dir: ".rpiv/artifacts/verdicts", ext: "json" }),
1660
+ parser: jsonBodyParser,
1661
+ });
1662
+ const sliceVerdictOutcome = verdictOutcome("slice-verdicts");
1663
+ const planVerdictOutcome = verdictOutcome("plan-verdicts");
1664
+ // The post-splice code gate re-grades the now code-bearing plan on its own
1665
+ // channel, so its verdicts never mix with the pre-elaborate plan gate's. Named
1666
+ // for the object under judgment — the code the gate grades — completing the
1667
+ // slice-verdicts / plan-verdicts / code-verdicts parallel.
1668
+ const codeVerdictOutcome = verdictOutcome("code-verdicts");
1669
+
1670
+ /**
1671
+ * Absolute path to rpiv-pi's bundled deterministic stitch script. Resolved off
1672
+ * this module's own URL so it points inside the installed package at runtime
1673
+ * (built-in-workflows lives in extensions/rpiv-core; the script in skills/_shared).
1674
+ */
1675
+ const STITCH_SCRIPT = join(
1676
+ dirname(fileURLToPath(import.meta.url)),
1677
+ "..",
1678
+ "..",
1679
+ "skills",
1680
+ "_shared",
1681
+ "stitch-elaborations.mjs",
1682
+ );
1683
+
1684
+ /**
1685
+ * Build's validate dispatch: the latest synthesized plan plus the goal and
1686
+ * run-start-baseline flags. Sourcing the plan from the NAMED channel (not the
1687
+ * rolling primary) is load-bearing: `code-grade` is a produces-fanout, so
1688
+ * after the code gate the rolling primary is the LAST VERDICT JSON
1689
+ * (`placeFanoutOutput` advances it per unit) and `implement` (acts) leaves it
1690
+ * there — a plain `produces()` validate would receive a verdict path as its
1691
+ * "plan". A prompt stage owns its whole message, so the `/skill:validate`
1692
+ * prefix is explicit (polish precedent).
1693
+ *
1694
+ * `--baseline` threads the pre-existing-dirty snapshot `goal` captured at run
1695
+ * start, so validate judges working-tree scope criteria ("only these files
1696
+ * touched") against the RUN'S OWN delta instead of failing on dirt that was
1697
+ * on disk before stage one — the same fence the commit dispatch applies. The
1698
+ * path comes off the goal channel (this run's snapshot, replayed from the
1699
+ * JSONL trail on resume), never a shared file another run could overwrite.
1700
+ */
1701
+ const VALIDATE_GOAL_PROMPT: PromptFn = ({ state }) => {
1702
+ const parts = ["/skill:validate"];
1703
+ const plan = latestFsArtifact(state, "plans");
1704
+ if (plan?.handle.kind === "fs") parts.push(handleToString(plan.handle));
1705
+ const goal = latestFsArtifact(state, "goal");
1706
+ if (goal?.handle.kind === "fs") parts.push(`--goal ${handleToString(goal.handle)}`);
1707
+ const baseline = goalBaselinePath(state);
1708
+ if (baseline) parts.push(`--baseline ${baseline}`);
1709
+ return parts.join(" ");
1710
+ };
1711
+
1712
+ /**
1713
+ * Build's commit dispatch: thread the run-start baseline so the commit skill
1714
+ * fences pre-existing dirt off the commit — `git-changes.mjs` takes the path
1715
+ * as a flag, so there is no fixed rendezvous file for concurrent/repeat runs
1716
+ * to clobber. Prompt-dispatched deliberately: the inherited rolling primary
1717
+ * (the validation report path) was reaching the skill as a meaningless
1718
+ * message-hint argument anyway; owning the message replaces that noise with
1719
+ * the one flag the skill actually consumes.
1720
+ */
1721
+ const COMMIT_BASELINE_PROMPT: PromptFn = ({ state }) => {
1722
+ const baseline = goalBaselinePath(state);
1723
+ return baseline ? `/skill:commit --baseline ${baseline}` : "/skill:commit";
1724
+ };
1725
+
1726
+ const buildWorkflow = defineWorkflow({
1727
+ name: "build",
551
1728
  description:
552
- "Read-only triage of a GitHub PR before any review effort. Fetches the PR thread, assesses the diff against the repo's own standards, writes a triage artifact, and recommends a triage disposition (Review / Request changes / Hold / Decline). A security BLOCK halts the run before any checkout. Best as the entry point for an incoming PR. Chain: pr-triage → security-gate → stop.",
553
- start: "pr-triage",
1729
+ "Ship, sliced: capture the verbatim brief as a goal artifact (the north star the quality gates' completeness/correctness dimensions and validate anchor against) → research the brief → decompose it into vertical slices → two-phase slice gate (a deterministic floor — dependency-cycle freedom + brief-coverage conservation so a slice-fix can't pass by dropping scope — then one LLM design-readiness judgment that each slice is chewable by a single design pass) with a slice-fix loop → design each slice in parallel → one consolidated developer checkpoint (accept or adjust the proposed interfaces/data types, adjustments applied surgically and cascaded to dependents) → synthesize hierarchically (per-cluster sub-plans → one merged plan) → tier-scaled quality-panel gate (a one-slice, <=2-phase run grades correctness+completeness only; larger or previously-failing runs grade the full completeness/correctness/actionability/pattern-following/architecture-fit roster) where a dimension's first blocking verdict gets one confirming second judgment before it buys a plan-fix round → elaborate code per phase in parallel → splice it into the plan → re-grade the code-bearing plan (same tier + confirm contract) → implement → validate → commit. Research-led; three automated gates plus one human design checkpoint, before design, before code, and after the splice.",
1730
+ start: "goal",
554
1731
  stages: {
555
- "pr-triage": produces(),
556
- // Skillless guard: read the triage skill's `security_flag` from the prior
557
- // stage's output and halt on BLOCK. A script stage (not a skill) — no LLM,
558
- // no session — so the gate is free. On SAFE/REVIEW it is a no-op side effect
559
- // and the chain advances to `stop`.
560
- "security-gate": acts.script({
561
- run: ({ input }) => {
562
- const flag = Number((input?.data as { security_flag?: unknown } | undefined)?.security_flag);
563
- if (Number.isNaN(flag) || flag >= PR_TRIAGE_BLOCK) {
1732
+ // The user's brief, verbatim, on its own channel — the judgment seams
1733
+ // (plan/code gates' completeness+correctness, validate) anchor against
1734
+ // it. Deliberately NOT fed to the generative stages (slice, design-slice):
1735
+ // bounded per-slice context is build's whole point, and an ambient goal
1736
+ // there invites re-litigating settled decompositions.
1737
+ goal: produces.script({ run: captureGoal }),
1738
+ // Front-loaded research grounds every slice's footing and feeds the plan
1739
+ // gate's architecture-fit dimension its --context. Prompt-dispatched so it
1740
+ // still receives the raw brief now that `goal` holds the start slot.
1741
+ research: produces({ prompt: RESEARCH_BRIEF_PROMPT }),
1742
+ slice: produces(),
1743
+ // Deterministic floor (no LLM): dependency-cycle freedom + brief-coverage conservation.
1744
+ "slice-check": produces.script({ reads: ["slices"], run: sliceStructureCheck }),
1745
+ // One LLM design-readiness judgment; verdicts on their own channel.
1746
+ "slice-grade": produces({
1747
+ skill: "grade",
1748
+ loop: SLICE_DIMENSION_FANOUT,
1749
+ outcome: sliceVerdictOutcome,
1750
+ reads: ["slices"],
1751
+ }),
1752
+ // Re-cut the slice map from the failing verdicts. Routes through `slice`
1753
+ // (re-slice mode), NOT the surgical `amend`: a `design-readiness` or structural
1754
+ // failure needs STRUCTURAL authority — split an epic, break a cycle, renumber —
1755
+ // which a surgical "touch only the cited line" edit cannot do, so `amend`
1756
+ // looped without converging until the backward-jump guard halted the run.
1757
+ "slice-fix": produces({
1758
+ skill: "slice",
1759
+ outcome: rpivBucketOutcome("slices"),
1760
+ reads: ["slices", fanin("slice-verdicts"), fanin("slice-check")],
1761
+ }),
1762
+ // Design every slice in parallel.
1763
+ "slice-design": produces({ skill: "design-slice", loop: SLICE_DESIGN_FANOUT }),
1764
+ // One consolidated developer checkpoint over EVERY per-slice design, at the
1765
+ // single fan-in seam where they all exist and nothing parallel is running.
1766
+ // Presents the proposed shape (interfaces, data types, scope) and lets the
1767
+ // developer accept or adjust; an adjustment is applied surgically in place
1768
+ // and cascaded to the changed contract's dependents BEFORE synthesis sees
1769
+ // the designs. Re-emits designs on their channel (latest-wins, same paths),
1770
+ // so `subplan`/`synthesize` read the accepted/edited docs. The interactive
1771
+ // counterpart to the LLM gates — the one human pass on the parallel path.
1772
+ "design-review": produces({
1773
+ skill: "design-review",
1774
+ outcome: rpivBucketOutcome("designs"),
1775
+ reads: [fanin("designs"), "slices"],
1776
+ }),
1777
+ // Hierarchical fan-in: merge each slice-DAG cluster into a sub-plan in
1778
+ // parallel (bounded context), then merge the sub-plans into one plan.
1779
+ subplan: produces({
1780
+ skill: "synthesize",
1781
+ loop: SYNTH_CLUSTER_FANOUT,
1782
+ outcome: rpivBucketOutcome("subplans"),
1783
+ }),
1784
+ // The root merge reads `research` (threaded as `--research` so cross-slice
1785
+ // constraints reach the merge directly, not only via each subplan's
1786
+ // refraction) alongside the cluster sub-plans it fans in.
1787
+ plan: produces({ skill: "synthesize", reads: ["research", fanin("subplans")] }),
1788
+ // Deterministic citation floor BEFORE the LLM plan gate (twin of `slice-check`):
1789
+ // a fabricated `file:line` in the plan fails structurally and routes to `plan-fix`.
1790
+ "plan-cite-check": produces.script({ reads: ["plans"], run: planCitationCheck("plan-cite-check") }),
1791
+ // Quality gate over the plan; verdicts on their own channel.
1792
+ "plan-grade": produces({
1793
+ skill: "grade",
1794
+ loop: PLAN_DIMENSION_FANOUT,
1795
+ outcome: planVerdictOutcome,
1796
+ // `research` is read so the architecture-fit unit can thread it as
1797
+ // --context; `goal` so completeness/correctness anchor on the brief.
1798
+ reads: ["plans", "research", "goal"],
1799
+ }),
1800
+ // One independent second judgment on the blocking dimensions before they
1801
+ // buy a fix round (see `confirmDue`). Same panel machinery, same verdict
1802
+ // channel — its OWN stage name so a stronger judge model can be pinned to
1803
+ // exactly the verdicts about to block (models.json `stages["plan-confirm"]`).
1804
+ "plan-confirm": produces({
1805
+ skill: "grade",
1806
+ loop: PLAN_CONFIRM_FANOUT,
1807
+ outcome: planVerdictOutcome,
1808
+ reads: ["plans", "research", "goal"],
1809
+ }),
1810
+ "plan-fix": produces({
1811
+ skill: "amend",
1812
+ outcome: rpivBucketOutcome("plans"),
1813
+ reads: ["plans", fanin("plan-verdicts"), fanin("plan-cite-check")],
1814
+ }),
1815
+ // Elaborate implement-ready code into each phase in parallel (fanout),
1816
+ // deterministically splice it back into the plan (code-splice), then
1817
+ // re-grade the now code-bearing plan — guarding the blind-splice risk.
1818
+ code: produces({ skill: "elaborate", loop: FRONTMATTER_PHASE_FANOUT, reads: ["plans"] }),
1819
+ "code-splice": acts.script({
1820
+ reads: ["plans"],
1821
+ run: ({ state, cwd }) => {
1822
+ const plan = latestFsArtifact(state, "plans");
1823
+ if (plan?.handle.kind !== "fs") {
564
1824
  throw haltPreflight(
565
- "pr-triage",
566
- "pr-triage: security BLOCK — do not proceed",
567
- `pr-triage: security_flag=${flag} (BLOCK) — the PR diff carries a high-confidence security risk. Resolve it before any checkout or review; see the triage artifact for the traced finding.`,
1825
+ "code-splice",
1826
+ "code-splice: no plan to splice into",
1827
+ "code-splice: no fs plan artifact on the 'plans' channel — synthesize must run before elaborate/code-splice",
568
1828
  );
569
1829
  }
1830
+ const planPath = isAbsolute(plan.handle.path) ? plan.handle.path : join(cwd, plan.handle.path);
1831
+ execFileSync("node", [STITCH_SCRIPT, planPath], { cwd });
570
1832
  },
571
1833
  }),
1834
+ // Deterministic citation floor over the SPLICED (code-bearing) plan before
1835
+ // the LLM code gate — the code-scope twin of `plan-cite-check`.
1836
+ "code-cite-check": produces.script({ reads: ["plans"], run: planCitationCheck("code-cite-check") }),
1837
+ "code-grade": produces({
1838
+ skill: "grade",
1839
+ loop: CODE_DIMENSION_FANOUT,
1840
+ outcome: codeVerdictOutcome,
1841
+ // `research` is read so the architecture-fit unit can thread it as
1842
+ // --context; `goal` so completeness/correctness anchor on the brief.
1843
+ reads: ["plans", "research", "goal"],
1844
+ }),
1845
+ // Repair arm for the code gate. Surgical `amend` over the SAME code-bearing
1846
+ // plan from the code verdicts — NOT a blind re-elaborate: `elaborate` never
1847
+ // sees the findings and can only rewrite a phase's code body, so it cannot fix
1848
+ // what the gate actually fails on (fabricated edit anchors, drifted line
1849
+ // citations, a cross-phase naming collision) and sometimes regressed a passing
1850
+ // dimension. `amend` reads the verdicts and edits the spliced plan in place
1851
+ // (its embedded code blocks included), then loops straight back to re-grade —
1852
+ // the mirror of the plan gate's `plan-fix` arm, on its own `code-verdicts`
1853
+ // channel so the two loops' verdicts never cross.
1854
+ // The code gate's confirm arm — the mirror of `plan-confirm`, on the
1855
+ // `code-verdicts` channel.
1856
+ "code-confirm": produces({
1857
+ skill: "grade",
1858
+ loop: CODE_CONFIRM_FANOUT,
1859
+ outcome: codeVerdictOutcome,
1860
+ reads: ["plans", "research", "goal"],
1861
+ }),
1862
+ "code-fix": produces({
1863
+ skill: "amend",
1864
+ outcome: rpivBucketOutcome("plans"),
1865
+ reads: ["plans", fanin("code-verdicts"), fanin("code-cite-check")],
1866
+ }),
1867
+ implement: acts({ loop: IMPLEMENT_PHASE_FANOUT, reads: ["plans"] }),
1868
+ validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
1869
+ commit: acts({ prompt: COMMIT_BASELINE_PROMPT, outcome: gitCommitOutcome }),
572
1870
  },
573
1871
  edges: {
574
- "pr-triage": "security-gate",
575
- "security-gate": "stop",
1872
+ goal: "research",
1873
+ // Research's artifact is auto-fed to slice as its argument (the slice skill's
1874
+ // "Fresh" input is a research path) — mirrors arch's research → design edge.
1875
+ research: "slice",
1876
+ slice: "slice-check",
1877
+ // Skip the design-readiness re-grade when the gate is already satisfied — after
1878
+ // a `slice-fix` that only cleared the deterministic structure floor (the common
1879
+ // case: a bare-basename citation), the accumulated design-readiness verdict
1880
+ // already passes, so re-grading would only re-roll a flappy judgment. First
1881
+ // pass (no verdict yet) ⇒ not satisfied ⇒ into `slice-grade`.
1882
+ "slice-check": defineRoute(
1883
+ ["slice-design", "slice-grade"],
1884
+ ({ state }) => (sliceGatePasses(state) ? "slice-design" : "slice-grade"),
1885
+ { readsData: false },
1886
+ ),
1887
+ // Design-readiness gate BEFORE any design. Structure + design-readiness pass⇒ design; any fails ⇒
1888
+ // slice-fix and loop back. Bounded by the runner's maxBackwardJumps (default 2).
1889
+ "slice-grade": defineRoute(
1890
+ ["slice-design", "slice-fix"],
1891
+ ({ state }) => (sliceGatePasses(state) ? "slice-design" : "slice-fix"),
1892
+ { readsData: false },
1893
+ ),
1894
+ "slice-fix": "slice-check",
1895
+ // Design fanout → consolidated human checkpoint → hierarchical synthesis.
1896
+ "slice-design": "design-review",
1897
+ "design-review": "subplan",
1898
+ subplan: "plan",
1899
+ plan: "plan-cite-check",
1900
+ // Skip the quality re-grade straight to `code` when the gate is already
1901
+ // satisfied — a `plan-fix` that only cleared the citation floor leaves every
1902
+ // dimension + risk flag already passing, so re-grading the whole panel would
1903
+ // only re-roll flappy judgments. First pass (empty verdict channel) ⇒ not
1904
+ // satisfied ⇒ into `plan-grade`. If a fix left the cite floor RED, the gate
1905
+ // isn't satisfied and we re-enter `plan-grade` (which re-runs the subset).
1906
+ "plan-cite-check": defineRoute(
1907
+ ["code", "plan-grade"],
1908
+ ({ state }) => (planGatePasses(state) ? "code" : "plan-grade"),
1909
+ { readsData: false },
1910
+ ),
1911
+ // Quality gate BEFORE any code. Pass ⇒ code. A dimension's FIRST blocking
1912
+ // verdict ⇒ plan-confirm (one independent second judgment — see
1913
+ // `confirmDue`); a confirmed blocker, or a failure with no dimension
1914
+ // blocking (the citation floor alone is red) ⇒ plan-fix, looping back
1915
+ // THROUGH the citation floor so the amended plan re-verifies (else a stale
1916
+ // failing cite verdict would loop forever).
1917
+ "plan-grade": defineRoute(
1918
+ ["code", "plan-confirm", "plan-fix"],
1919
+ ({ state }) =>
1920
+ planGatePasses(state)
1921
+ ? "code"
1922
+ : confirmDue(state, "plans", "plan-verdicts", PLAN_DIMENSIONS)
1923
+ ? "plan-confirm"
1924
+ : "plan-fix",
1925
+ { readsData: false },
1926
+ ),
1927
+ // After the second judgment the gate re-folds on the latest verdicts: a
1928
+ // confirming pass overwrote the flap and clears the gate; a confirming
1929
+ // fail routes to the fix with two agreeing judgments behind it.
1930
+ "plan-confirm": defineRoute(["code", "plan-fix"], ({ state }) => (planGatePasses(state) ? "code" : "plan-fix"), {
1931
+ readsData: false,
1932
+ }),
1933
+ "plan-fix": "plan-cite-check",
1934
+ code: "code-splice",
1935
+ "code-splice": "code-cite-check",
1936
+ // Skip the code re-grade straight to `implement` when the code gate is already
1937
+ // satisfied — a `code-fix` that only cleared the citation floor leaves the
1938
+ // panel already green. First pass (empty channel) ⇒ into `code-grade`.
1939
+ "code-cite-check": defineRoute(
1940
+ ["implement", "code-grade"],
1941
+ ({ state }) => (codeGatePasses(state) ? "implement" : "code-grade"),
1942
+ { readsData: false },
1943
+ ),
1944
+ // Re-grade the code-bearing plan. Pass ⇒ implement. A first blocking
1945
+ // verdict ⇒ code-confirm (the plan gate's confirm contract, on the
1946
+ // code-verdicts channel); a confirmed blocker or cite-floor-only failure ⇒
1947
+ // code-fix. Routes to `code-fix`, NOT back to `code`: the gate fails on
1948
+ // plan-text defects (edit anchors, line citations, naming) that a
1949
+ // per-phase code rewrite cannot reach, so the surgical arm is the one with
1950
+ // authority over them. Bounded by the runner's maxBackwardJumps.
1951
+ "code-grade": defineRoute(
1952
+ ["implement", "code-confirm", "code-fix"],
1953
+ ({ state }) =>
1954
+ codeGatePasses(state)
1955
+ ? "implement"
1956
+ : confirmDue(state, "plans", "code-verdicts", PLAN_DIMENSIONS)
1957
+ ? "code-confirm"
1958
+ : "code-fix",
1959
+ { readsData: false },
1960
+ ),
1961
+ "code-confirm": defineRoute(
1962
+ ["implement", "code-fix"],
1963
+ ({ state }) => (codeGatePasses(state) ? "implement" : "code-fix"),
1964
+ { readsData: false },
1965
+ ),
1966
+ "code-fix": "code-cite-check",
1967
+ implement: "validate",
1968
+ // Gate commit on validate's own verdict — an unconditional `validate → commit`
1969
+ // let a `verdict: fail` (incomplete goal coverage) commit anyway. `match` with
1970
+ // no fallback commits ONLY on an explicit `verdict: "pass"`; every other value
1971
+ // (a `fail`, or a missing verdict) routes to STOP — a failed validation halts
1972
+ // WITHOUT committing, leaving the report on disk for the user. Safe by
1973
+ // construction: the sole path to commit is an explicit pass, so un-anticipated
1974
+ // data can never route INTO commit. Sourced from validate's published verdict
1975
+ // channel (`from: "validation"` — the bucket its contract's `artifactKind`
1976
+ // derives) — a prompt stage owns its message and can't inherit its contract's
1977
+ // output schema, so route on the channel, not the raw (un-validated) stage output.
1978
+ validate: match("verdict", { commit: "pass" }, { from: "validation" }),
1979
+ commit: "stop",
576
1980
  },
577
1981
  });
578
1982
 
@@ -582,9 +1986,8 @@ const prTriageWorkflow = defineWorkflow({
582
1986
 
583
1987
  export const builtInWorkflows: readonly Workflow[] = [
584
1988
  shipWorkflow,
585
- buildWorkflow,
586
1989
  archWorkflow,
587
1990
  vetWorkflow,
588
1991
  polishWorkflow,
589
- prTriageWorkflow,
1992
+ buildWorkflow,
590
1993
  ];