@juicesharp/rpiv-pi 2.6.3 → 2.7.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 (33) hide show
  1. package/docs/workflows.md +1 -1
  2. package/extensions/rpiv-core/agents.ts +10 -13
  3. package/extensions/rpiv-core/artifact-collector.ts +111 -6
  4. package/extensions/rpiv-core/bash-timeout.ts +12 -2
  5. package/extensions/rpiv-core/built-in-workflows.ts +233 -3514
  6. package/extensions/rpiv-core/built-ins/citations.ts +357 -0
  7. package/extensions/rpiv-core/built-ins/gates.ts +613 -0
  8. package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
  9. package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
  10. package/extensions/rpiv-core/built-ins/index.ts +46 -0
  11. package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
  12. package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
  13. package/extensions/rpiv-core/built-ins/priors.ts +352 -0
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
  15. package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
  16. package/extensions/rpiv-core/built-ins/shared.ts +17 -1
  17. package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
  18. package/extensions/rpiv-core/built-ins/slices.ts +288 -0
  19. package/extensions/rpiv-core/constants.ts +5 -1
  20. package/extensions/rpiv-core/lane-console.ts +9 -2
  21. package/extensions/rpiv-core/lane-list.ts +10 -1
  22. package/extensions/rpiv-core/question-lifecycle.ts +2 -2
  23. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  24. package/extensions/rpiv-core/run-lane-registry.ts +83 -83
  25. package/package.json +2 -2
  26. package/skills/elaborate/SKILL.md +1 -1
  27. package/skills/grade/SKILL.md +1 -1
  28. package/skills/implement/SKILL.md +1 -0
  29. package/skills/plan/SKILL.md +3 -1
  30. package/skills/remediate/SKILL.md +1 -0
  31. package/skills/synthesize/SKILL.md +1 -0
  32. package/skills/validate/SKILL.md +25 -19
  33. package/skills/validate/templates/validation.md +1 -1
@@ -0,0 +1,219 @@
1
+ /**
2
+ * The plan citation/coverage floor: verifies every `file:line` citation in the
3
+ * latest plan resolves and that each phase body's edit paths are declared in
4
+ * its frontmatter `files:`.
5
+ */
6
+ import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
7
+ import type { Output, ScriptContext } from "@juicesharp/rpiv-workflow/registration";
8
+ import { verifyCitations } from "./citations.js";
9
+ import { forEachLineOutsideFences } from "./markdown-fence.js";
10
+ import { PLAN_PHASE_RE, phaseFiles } from "./plan-phases.js";
11
+ import { haltPreflight, latestFsArtifact, readArtifactFile, writeStructureVerdict } from "./shared.js";
12
+
13
+ /**
14
+ * Slice a plan body into per-phase text keyed by phase number, splitting on
15
+ * `## Phase N:` headings OUTSIDE fenced code blocks (a heading inside a ``` or
16
+ * ~~~ fence is example/fixture text, not a structural phase boundary — mirrors
17
+ * `countHeadingsOutsideFences` so the slice and the derive-check agree). The
18
+ * body for phase N runs from its heading line up to (not including) the next
19
+ * out-of-fence `## Phase M:` heading, or end-of-text for the last phase.
20
+ * Returns a `Map<number, string>` (phase n → body text, heading included).
21
+ */
22
+ const phaseBodySlices = (content: string): Map<number, string> => {
23
+ const lineRe = new RegExp(PLAN_PHASE_RE.source); // drop g/m; per-line test, lastIndex can't drift
24
+ const lines = content.split("\n");
25
+ const openings: { n: number; start: number }[] = [];
26
+ forEachLineOutsideFences(content, (line, i) => {
27
+ const m = lineRe.exec(line);
28
+ if (m?.[1]) openings.push({ n: Number(m[1]), start: i });
29
+ });
30
+ const slices = new Map<number, string>();
31
+ for (let idx = 0; idx < openings.length; idx++) {
32
+ const end = idx + 1 < openings.length ? openings[idx + 1].start : lines.length;
33
+ slices.set(openings[idx].n, lines.slice(openings[idx].start, end).join("\n"));
34
+ }
35
+ return slices;
36
+ };
37
+
38
+ /** Strip a trailing `:line` or `:line-line` citation suffix from a path token. */
39
+ const stripLineSuffix = (p: string): string => p.replace(/:\d+(?:-\d+)?$/, "");
40
+
41
+ /** Well-known extensionless filenames — the extension heuristic below would drop
42
+ * them, so an undeclared write to one would silently escape the coverage floor.
43
+ * Recognized bare or as the basename of a path. */
44
+ const EXTENSIONLESS_FILENAME_RE =
45
+ /^(?:Makefile|Dockerfile|Rakefile|Gemfile|Justfile|Procfile|LICENSE|NOTICE|CODEOWNERS)$/;
46
+
47
+ /** Path-like test mirroring slice-overlap.mjs's `looksLikePath`, applied AFTER
48
+ * stripping a `:line` suffix (the blueprint MODIFY heading — `#### N. path/to/file.ext`
49
+ * with a `:12-30` range appended — carries a line range the bare form rejects).
50
+ * Extensionless recognition is allowlist-only (never "any `/`-bearing token"):
51
+ * prose like `and/or` must not read as a declared write. The extension is
52
+ * bounded to 1–5 chars starting with a letter (mirroring FILE_LINE_CITATION_RE)
53
+ * so a dotted IDENTIFIER (`deps.finalize` — an observed false coverage
54
+ * finding) never reads as a file. */
55
+ const isPathLike = (s: string): boolean => {
56
+ if (/\s/.test(s)) return false;
57
+ if (EXTENSIONLESS_FILENAME_RE.test(s.slice(s.lastIndexOf("/") + 1))) return true;
58
+ return /\.[A-Za-z][A-Za-z0-9]{0,4}$/.test(s) && (s.includes("/") || /^[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}$/.test(s));
59
+ };
60
+
61
+ /**
62
+ * Extract the edit paths a phase body names, across the three artifact
63
+ * conventions the plan/blueprint/synthesize skills emit, OUTSIDE fenced code
64
+ * blocks (a path inside a ``` fence is a code reference, not a declared write —
65
+ * post-`code-splice` safety, since code-splice folds elaborations' fenced code
66
+ * into the plan and those fenced paths must NOT read as phase writes):
67
+ * • `**File**:` / `**Files**:` — plan/blueprint's per-change file line
68
+ * (a backticked comma-list under `**Files**:`, or a single path under `**File**:`).
69
+ * • `#### N. path/to/file.ext` — blueprint's change subsection heading
70
+ * (may carry a `:line`-range suffix on MODIFY entries — stripped).
71
+ * • `- `path/to/file.ts`` — synthesize's backticked-path list item under
72
+ * `### Changes` (the form `elaborate`/`synthesize` emit).
73
+ * Strips a trailing `:line`/`:line-line` suffix. Mirrors slice-overlap.mjs's
74
+ * `filesOf` + `looksLikePath` and extends them with the synthesize list-item
75
+ * form. Returns a de-duplicated `string[]`.
76
+ */
77
+ const editPathsOfPhase = (phaseBody: string): string[] => {
78
+ const files = new Set<string>();
79
+ const add = (raw: string) => {
80
+ const stripped = stripLineSuffix(raw.replace(/[`*]/g, "").trim());
81
+ if (stripped && isPathLike(stripped)) files.add(stripped);
82
+ };
83
+ // The list-item form is scoped to a Changes section (`### Changes` heading or
84
+ // a `**Changes**:` field line): a backticked bullet elsewhere in the body is
85
+ // a REFERENCE ("mirror `x/state.ts`"), not a declared write — unscoped, those
86
+ // read as coverage gaps and block. Any other heading or `**Field**:` label
87
+ // exits the scope; `**File(s)**:` lines don't flip it (they're the path form
88
+ // themselves and legitimately precede `**Changes**:`).
89
+ let inChanges = false;
90
+ forEachLineOutsideFences(phaseBody, (line) => {
91
+ const heading = line.match(/^#{2,5}\s+(.*)$/);
92
+ if (heading) inChanges = /^changes\b/i.test(heading[1].trim());
93
+ const fm = line.match(/^\*\*Files?\*\*:\s*(.+)$/);
94
+ if (fm) {
95
+ for (const tok of fm[1].split(/[,\s]+/)) add(tok);
96
+ return;
97
+ }
98
+ const label = line.match(/^\*\*([A-Za-z][A-Za-z ]*)\*\*:/);
99
+ if (label?.[1]) inChanges = /^changes$/i.test(label[1].trim());
100
+ const hm = line.match(/^#{3,4}\s+\d+\.\s+(\S+)/);
101
+ if (hm) {
102
+ add(hm[1]);
103
+ return;
104
+ }
105
+ const lm = line.match(/^-\s+`([^`]+)`/);
106
+ if (lm && inChanges) add(lm[1]);
107
+ });
108
+ return [...files];
109
+ };
110
+
111
+ /**
112
+ * Deterministic plan-time coverage floor: every edit path a phase body NAMES
113
+ * (in `### Changes`/`#### N. path`/`**File**:`) must be DECLARED in that phase's
114
+ * frontmatter `files:` array. An undeclared write is the per-phase attribution
115
+ * gap the dep-gated implement fanout and the lane-level scope floor both need
116
+ * closed upstream — a body edit not in `files:` is invisible to dependency
117
+ * derivation and unattributable under concurrency. PURE: no LLM judgment, never
118
+ * throws (a malformed frontmatter degrades to `[]`). A `files:`-LESS phase
119
+ * (absent key) yields NO findings — empty-set degradation so a legacy/
120
+ * `files:`-less plan never false-fails; a phase that declares `files: []` is
121
+ * checked (every body edit is a gap). Folded into `planCitationCheck(who)` so
122
+ * both the `plan-cite-check` and `code-cite-check` arms emit coverage findings
123
+ * on their shared `dimension: "structure"` verdict — no new stage/channel/route.
124
+ */
125
+ const verifyPhaseFilesCoverage = (content: string, who: string, path: string): { detail: string; where: string }[] => {
126
+ let fm: Record<string, unknown>;
127
+ try {
128
+ const { frontmatter } = parseFrontmatter(content);
129
+ fm = frontmatter as Record<string, unknown>;
130
+ } catch {
131
+ return []; // malformed frontmatter → degrade to no findings, never throw
132
+ }
133
+ const phases = Array.isArray(fm.phases) ? fm.phases : [];
134
+ const entryByN = new Map<number, Record<string, unknown>>();
135
+ phases.forEach((entry, idx) => {
136
+ const e = (entry ?? {}) as Record<string, unknown>;
137
+ const n = typeof e.n === "number" ? e.n : idx + 1;
138
+ entryByN.set(n, e);
139
+ });
140
+ const findings: { detail: string; where: string }[] = [];
141
+ for (const [n, body] of phaseBodySlices(content)) {
142
+ const entry = entryByN.get(n);
143
+ if (!entry) continue; // body phase with no matching frontmatter entry — derive-check's concern, not coverage's
144
+ // `files:` key ABSENT → degradation (legacy plan): skip. Present (even `[]`) → check.
145
+ if (!Array.isArray(entry.files)) continue;
146
+ const declared = new Set(phaseFiles(entry));
147
+ for (const editPath of editPathsOfPhase(body)) {
148
+ if (declared.has(editPath)) continue;
149
+ // Whole-segment suffix tolerance: a body form citing the file by bare
150
+ // basename or partial path (`#### 2. config.ts` for a declared
151
+ // `packages/x/config.ts`) is covered by the declaration — exact-match
152
+ // only was fixable solely by polluting `files:` with the bare name,
153
+ // corrupting the very dep derivation this floor protects.
154
+ if ([...declared].some((d) => `/${d}`.endsWith(`/${editPath}`) || `/${editPath}`.endsWith(`/${d}`))) continue;
155
+ findings.push({
156
+ detail: `Phase ${n} names edit path ${editPath} in its body but does not declare it in its frontmatter 'files:' array. Every path a phase creates or edits must be listed in 'files:' (repo-root-relative, never a bare basename) so the plan-time coverage floor and the dep-gated implement fanout see the phase's full write set. Add ${editPath} to phase ${n}'s 'files:' array, or drop the body reference if the write belongs to another phase.`,
157
+ where: `${who} ${path} phase ${n}: ${editPath}`,
158
+ });
159
+ }
160
+ }
161
+ return findings;
162
+ };
163
+
164
+ /**
165
+ * The union of every phase's declared `files:` across the plan's frontmatter —
166
+ * the disambiguation pool `planCitationCheck` hands `verifyCitations`. A plan's
167
+ * write-set is the one place the plan itself names its files repo-root-relative
168
+ * (the coverage floor enforces exactly that), so it is a deterministic
169
+ * tiebreaker for the ambiguous-suffix findings that would otherwise STOP a
170
+ * loop-less preset (ship) over a bare `messages.ts:18` whose owning file the
171
+ * plan already declares. Degrades to the empty set on malformed frontmatter —
172
+ * never throws out of the deterministic floor.
173
+ */
174
+ const declaredPlanFiles = (content: string): ReadonlySet<string> => {
175
+ let fm: Record<string, unknown>;
176
+ try {
177
+ fm = parseFrontmatter(content).frontmatter as Record<string, unknown>;
178
+ } catch {
179
+ return new Set();
180
+ }
181
+ const phases = Array.isArray(fm.phases) ? fm.phases : [];
182
+ const declared = new Set<string>();
183
+ for (const entry of phases) for (const f of phaseFiles(entry)) declared.add(f);
184
+ return declared;
185
+ };
186
+
187
+ /**
188
+ * Deterministic citation floor for a synthesized/spliced plan — the plan-scope
189
+ * twin of `sliceStructureCheck`'s citation backing, extending the citation
190
+ * floor past the slice map to the plan and the code-bearing plan (a fabricated `file:line` in
191
+ * the plan misdirects `implement`). Verifies every
192
+ * citation resolves against the working tree and emits a `{ dimension:
193
+ * "structure" }` verdict on `who`'s channel that the gate route folds via
194
+ * `allDimensionsPass`; the matching `<fix>` stage reads `fanin(who)` so the
195
+ * findings DRIVE the amend rather than blind-halt. Reuses `verifyCitations` — no
196
+ * fuzzy wrong-symbol heuristic — threading the plan's declared `files:` union so
197
+ * an ambiguous suffix citation resolves when exactly one candidate is in the
198
+ * plan's own write-set. Basename-keyed ⇒ idempotent across fix rounds.
199
+ */
200
+ const planCitationCheck =
201
+ (who: string) =>
202
+ ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
203
+ const latest = latestFsArtifact(state, "plans");
204
+ if (latest?.handle.kind !== "fs") {
205
+ throw haltPreflight(
206
+ who,
207
+ `${who}: no plan to check`,
208
+ `${who}: no fs artifact on the 'plans' channel — the plan must be produced before the citation check`,
209
+ );
210
+ }
211
+ const body = readArtifactFile(latest.handle.path, cwd);
212
+ const findings = verifyCitations(body, cwd, declaredPlanFiles(body));
213
+ // Plan-time coverage floor: a body edit not declared in its phase's `files:`
214
+ // fails structurally, same channel/verdict/route as an unbacked citation.
215
+ findings.push(...verifyPhaseFilesCoverage(body, who, latest.handle.path));
216
+ return writeStructureVerdict(who, latest.handle, findings, cwd);
217
+ };
218
+
219
+ export { planCitationCheck };
@@ -0,0 +1,424 @@
1
+ /**
2
+ * The plan/review phase layer: `phases:` and `### Phase N` frontmatter parsing,
3
+ * per-phase declared write-sets (with test-twin expansion), and the
4
+ * implement/blueprint fanouts built on them.
5
+ */
6
+ import { basename } from "node:path";
7
+ import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
+ import {
9
+ type FanoutContext,
10
+ fanout,
11
+ handleToString,
12
+ iterate,
13
+ type Output,
14
+ type RunView,
15
+ type Unit,
16
+ } from "@juicesharp/rpiv-workflow/registration";
17
+ import { countHeadingsOutsideFences } from "./markdown-fence.js";
18
+ import {
19
+ haltPreflight,
20
+ latestFsArtifact,
21
+ MAX_PHASES,
22
+ type PhaseRecord,
23
+ readArtifactFile,
24
+ TEST_PATH_RE,
25
+ } from "./shared.js";
26
+
27
+ /**
28
+ * `## Phase N:` headings — the source of truth a plan's `phases:` frontmatter
29
+ * array is derived from. Used to verify that derived array, not to enumerate
30
+ * (enumeration reads the typed `phases:` array).
31
+ */
32
+ const PLAN_PHASE_RE = /^## Phase (\d+):/gm;
33
+
34
+ /**
35
+ * Parse a plan's `phases:` frontmatter into records, derive-checked against the
36
+ * body's `## Phase N:` headings — the source of truth both the single-plan
37
+ * (`FRONTMATTER_PHASE_FANOUT`) and multi-plan (`PLANS_PHASE_FANOUT`) fanouts
38
+ * share. A length mismatch means the producer's rebuild step was skipped or the
39
+ * array went stale; throw rather than dispatch a wrong unit list. `who`/`path`
40
+ * shape the diagnostic.
41
+ */
42
+ const planPhaseRecords = (content: string, who: string, path: string): readonly PhaseRecord[] => {
43
+ const { frontmatter } = parseFrontmatter(content);
44
+ const fm = frontmatter as Record<string, unknown>;
45
+ const raw = fm.phases;
46
+ const phases = Array.isArray(raw) ? raw : [];
47
+ const headingCount = countHeadingsOutsideFences(content, PLAN_PHASE_RE);
48
+ if (phases.length !== headingCount) {
49
+ throw haltPreflight(
50
+ who,
51
+ `${who}: plan ${path} has mismatched phases`,
52
+ `${who}: plan ${path} frontmatter phases (${phases.length}) ≠ '## Phase N:' headings (${headingCount}) — the derived array is stale against the body`,
53
+ );
54
+ }
55
+ // The REQUIRED scalar `phase_count` must equal the derived phase count — it
56
+ // drives the fanout unit count. Fire only when the file declares
57
+ // plan-ness (has phases OR a phase_count) so a genuinely empty / non-plan file
58
+ // still degrades to [] (the existing "neither phases nor headings" path); a plan
59
+ // that declares phases but omits phase_count THROWS (the field is contract-required).
60
+ if ((phases.length > 0 || fm.phase_count !== undefined) && fm.phase_count !== phases.length) {
61
+ throw haltPreflight(
62
+ who,
63
+ `${who}: plan ${path} has invalid phase_count`,
64
+ `${who}: plan ${path} frontmatter phase_count (${String(fm.phase_count)}) ≠ phases length (${phases.length}) — rebuild phase_count from the '## Phase N:' headings`,
65
+ );
66
+ }
67
+ return phases.map((entry, index) => {
68
+ const e = (entry ?? {}) as Record<string, unknown>;
69
+ return {
70
+ entry: e,
71
+ n: typeof e.n === "number" ? e.n : index + 1,
72
+ title: typeof e.title === "string" ? e.title : "",
73
+ index,
74
+ total: phases.length,
75
+ };
76
+ });
77
+ };
78
+
79
+ /**
80
+ * Read the latest plan published to the named `"plans"` channel and parse its
81
+ * `phases:` frontmatter into records — the shared read/halt body both
82
+ * `FRONTMATTER_PHASE_FANOUT` and `IMPLEMENT_DAG_FANOUT` source from. Returns
83
+ * `null` when no fs plan is published (each caller degrades to `[]`); throws
84
+ * the two `haltPreflight` diagnostics (plan-not-found, exceeds `MAX_PHASES`)
85
+ * attributed to `who`. `promptPath` is the plan handle's string form, so each
86
+ * fanout emits the same `${promptPath} Phase N:` prompt arg.
87
+ */
88
+ const readPlanPhaseRecords = (
89
+ state: RunView,
90
+ cwd: string,
91
+ who: string,
92
+ ): { records: readonly PhaseRecord[]; promptPath: string } | null => {
93
+ const plan = latestFsArtifact(state, "plans");
94
+ if (plan?.handle.kind !== "fs") return null;
95
+ const path = plan.handle.path;
96
+ let content: string;
97
+ try {
98
+ content = readArtifactFile(path, cwd);
99
+ } catch (err) {
100
+ throw haltPreflight(
101
+ who,
102
+ `${who}: plan file not found`,
103
+ `${who}: could not read ${path} — ${err instanceof Error ? err.message : String(err)}`,
104
+ );
105
+ }
106
+ const records = planPhaseRecords(content, who, path);
107
+ if (records.length > MAX_PHASES) {
108
+ throw haltPreflight(
109
+ who,
110
+ `${who}: plan ${path} exceeds phase limit`,
111
+ `${who}: plan ${path} declares ${records.length} phases — exceeds MAX_PHASES (${MAX_PHASES}); split into smaller plans`,
112
+ );
113
+ }
114
+ const promptPath = handleToString(plan.handle);
115
+ return { records, promptPath };
116
+ };
117
+
118
+ /**
119
+ * Fan `implement` out over the structured `phases:` frontmatter array of the
120
+ * latest plan published to the named `"plans"` channel. Sourcing from the named
121
+ * channel (not the rolling primary) makes the stage's `reads: ["plans"]`
122
+ * declaration semantically honest. Used by every workflow whose `implement`
123
+ * inherits one plan (build/vet); polish's accumulating multi-plan
124
+ * variant is `PLANS_PHASE_FANOUT`.
125
+ */
126
+ const FRONTMATTER_PHASE_FANOUT = fanout({
127
+ source: "plans",
128
+ unit: { by: "frontmatter-array", pattern: "phases" },
129
+ max: MAX_PHASES,
130
+ units: ({ state, cwd }) => {
131
+ const read = readPlanPhaseRecords(state, cwd, "FRONTMATTER_PHASE_FANOUT");
132
+ if (!read) return [];
133
+ const { records, promptPath } = read;
134
+ return records.map((r) => ({
135
+ prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
136
+ label: `phase ${r.index + 1}/${r.total}`,
137
+ }));
138
+ },
139
+ });
140
+
141
+ /**
142
+ * Derive the directed `deps` edges for ONE implement phase under the dep-gated
143
+ * DAG fanout (`IMPLEMENT_DAG_FANOUT`). Edges point strictly downward (toward
144
+ * LOWER phase numbers), so the graph is acyclic by construction. Two clauses:
145
+ *
146
+ * - clause A (self declares a `files:` write-set): `self` depends on every
147
+ * LOWER phase whose declared `files:` shares ≥1 entry, UNIONED with `self`'s
148
+ * explicit `depends_on` (semantic ordering not visible in `files:`).
149
+ * - clause B (self declares NO `files:`): `self` conflicts with EVERY lower
150
+ * phase → full chain (a write-set-less phase's writes are unknown, so it
151
+ * cannot be proven independent of anything below it). This is the
152
+ * empty-set degradation that keeps a legacy / `files:`-less plan serial at
153
+ * any cap (one phase per Kahn wave).
154
+ *
155
+ * Returns `phase-<n>` unit ids, sorted ascending. Reads `phaseFiles`
156
+ * and `phaseDeps` — both defined later textually, but only inside this
157
+ * runtime closure, so no TDZ (same pattern as `sliceDeps`).
158
+ */
159
+ const implementPhaseDeps = (records: readonly PhaseRecord[], self: PhaseRecord): string[] => {
160
+ // Twin-expanded (`withTestTwins`) so a phase declaring `x.ts` conflicts with
161
+ // one declaring `x.test.ts` — the production phase's implicit twin write would
162
+ // otherwise race a concurrent sibling that owns the test explicitly.
163
+ const selfFiles = withTestTwins(phaseFiles(self.entry));
164
+ const explicit = phaseDeps(self.entry);
165
+ const ns = new Set<number>();
166
+ for (const e of explicit) if (e < self.n) ns.add(e);
167
+ if (selfFiles.length === 0) {
168
+ // clause B — unknown write-set ⇒ conflict with every lower phase.
169
+ for (const r of records) if (r.n < self.n) ns.add(r.n);
170
+ } else {
171
+ // clause A — overlap on ≥1 declared write path.
172
+ for (const r of records) {
173
+ if (r.n >= self.n) continue;
174
+ const rFiles = withTestTwins(phaseFiles(r.entry));
175
+ if (rFiles.some((f) => selfFiles.includes(f))) ns.add(r.n);
176
+ }
177
+ }
178
+ return [...ns].sort((a, b) => a - b).map((n) => `phase-${n}`);
179
+ };
180
+
181
+ /**
182
+ * Dep-gated DAG variant of `FRONTMATTER_PHASE_FANOUT` — `implement`'s twin that
183
+ * emits per-phase `id`/`deps` edges so the wave scheduler orders phases by their
184
+ * declared write-set overlap + explicit `depends_on`. The spread idiom inherits
185
+ * `source`/`unit`/`max`/`onCap`/`result`/`kind` verbatim from the base; the new
186
+ * `units` closure emits the SAME `prompt`/`label` strings AND adds
187
+ * `id: \`phase-${r.n}\`` + `deps: implementPhaseDeps(records, r)`. NO
188
+ * `depArtifactFlag` — implement phases feed each other through the working tree
189
+ * (not published artifacts), so `deps` drive ONLY wave ordering. NO
190
+ * `concurrency` property is set (the spread overrides only `units`), so the loop
191
+ * inherits the host cap and phases fan out concurrently, bounded by `deps`.
192
+ */
193
+ const IMPLEMENT_DAG_FANOUT = {
194
+ ...FRONTMATTER_PHASE_FANOUT,
195
+ units: ({ state, cwd }: FanoutContext) => {
196
+ const read = readPlanPhaseRecords(state, cwd, "IMPLEMENT_DAG_FANOUT");
197
+ if (!read) return [];
198
+ const { records, promptPath } = read;
199
+ return records.map((r) => ({
200
+ prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
201
+ label: `phase ${r.index + 1}/${r.total}`,
202
+ id: `phase-${r.n}`,
203
+ deps: implementPhaseDeps(records, r),
204
+ }));
205
+ },
206
+ };
207
+
208
+ /**
209
+ * `### Phase N — name` headings — the source of truth the review's `phases:`
210
+ * frontmatter array is derived from. Used to verify that derived array, not to
211
+ * enumerate (enumeration reads the typed `phases:` array).
212
+ */
213
+ const REVIEW_PHASE_RE = /^### Phase (\d+) — (.+)$/gm;
214
+
215
+ /** Number of structured `phases` in the latest architecture review's frontmatter (0 if none). */
216
+ const reviewPhaseCount = (state: RunView, cwd: string): number => {
217
+ const review = latestFsArtifact(state, "architecture-reviews");
218
+ if (review?.handle.kind !== "fs") return 0;
219
+ const { frontmatter } = parseFrontmatter(readArtifactFile(review.handle.path, cwd));
220
+ const raw = (frontmatter as Record<string, unknown>).phases;
221
+ return Array.isArray(raw) ? raw.length : 0;
222
+ };
223
+
224
+ /**
225
+ * The plans from the most recent blueprint pass. blueprint's iterate stage
226
+ * pushes one `Output` per review phase into `state.named["plans"]`; on a
227
+ * corrective loop it re-plans every phase, so keep only the last `phaseCount`
228
+ * (the review's phase count) and drop the stale generation. Shared by the
229
+ * implement fanout and the validate prompt so both see the same plan set.
230
+ */
231
+ const latestPlans = (state: RunView, cwd: string): readonly Output[] => {
232
+ const plans = state.named.plans ?? [];
233
+ const phaseCount = reviewPhaseCount(state, cwd);
234
+ return phaseCount > 0 && plans.length > phaseCount ? plans.slice(-phaseCount) : plans;
235
+ };
236
+
237
+ /** Phase number for a `phases:` entry, falling back to its 1-based position. */
238
+ const phaseNum = (entry: unknown, index: number): number => {
239
+ const n = (entry as { n?: unknown } | undefined)?.n;
240
+ return typeof n === "number" ? n : index + 1;
241
+ };
242
+
243
+ /** `depends_on` phase numbers an entry declares (empty when absent). */
244
+ const phaseDeps = (entry: unknown): number[] => {
245
+ const raw = (entry as { depends_on?: unknown } | undefined)?.depends_on;
246
+ return Array.isArray(raw) ? raw.filter((d): d is number => typeof d === "number") : [];
247
+ };
248
+
249
+ /** The repo-root-relative paths a phase entry declares it creates/edits (its
250
+ * `files:` array — `[]` when absent). The open-schema twin of `phaseDeps`,
251
+ * read straight off `PhaseRecord.entry` so `planPhaseRecords` preserves the new
252
+ * key unchanged. Consumed by the plan-time coverage floor
253
+ * (`verifyPhaseFilesCoverage`) and, in a later phase, the dep-gated implement
254
+ * fanout (`implementPhaseDeps`). */
255
+ const phaseFiles = (entry: unknown): string[] => {
256
+ const raw = (entry as { files?: unknown } | undefined)?.files;
257
+ return Array.isArray(raw) ? raw.filter((f): f is string => typeof f === "string") : [];
258
+ };
259
+
260
+ /**
261
+ * Expand a declared write-set with each production file's co-located test twin
262
+ * (`x.ts → x.test.ts`, likewise tsx/js/jsx). This monorepo's tests are
263
+ * compile-coupled siblings — widening a declared file's signature forces the
264
+ * mechanical follow-up edit in its twin — so requiring every plan author,
265
+ * elaborator, and grader to re-declare the twin is paperwork the convention
266
+ * already guarantees. Applied at BOTH consumers of the declared set — the
267
+ * DAG conflict fold (`implementPhaseDeps`) and the scope floors — so the
268
+ * planner and the floor can never disagree; on the DAG side it also closes the
269
+ * latent race where phases declaring `x.ts` and `x.test.ts` counted as
270
+ * disjoint yet predictably collide. Asymmetric by design: declaring a TEST
271
+ * file licenses nothing extra — production writes remain the act that must be
272
+ * declared, and a write to a non-twin test still fails the floor. A file
273
+ * already matching `TEST_PATH_RE` maps to itself (no `x.test.test.ts`).
274
+ */
275
+ const withTestTwins = (files: readonly string[]): string[] => {
276
+ const out = new Set(files);
277
+ for (const f of files) {
278
+ if (TEST_PATH_RE.test(f)) continue;
279
+ const twin = f.replace(/\.([tj]sx?)$/, ".test.$1");
280
+ if (twin !== f) out.add(twin);
281
+ }
282
+ return [...out];
283
+ };
284
+
285
+ /**
286
+ * Per-review-phase blueprint generator (the `iterate` dual of
287
+ * FRONTMATTER_PHASE_FANOUT). One blueprint pass per review phase, enumerating the
288
+ * review's structured `phases:` array (derived by architecture-review from its
289
+ * `### Phase N — name` headings). blueprint writes its own natural plan file; the
290
+ * `plans` collector captures whatever path it announces.
291
+ *
292
+ * Each phase reads only the plans of the phases it `depends_on` (vs. every prior
293
+ * plan) — accurate context, and the seam a future scheduler could parallelize on.
294
+ * `blast_radius`/`effort` tag the label. Absent `depends_on` falls back to all
295
+ * prior plans.
296
+ *
297
+ * Guards (first call): the array's length must equal the `### Phase N — name`
298
+ * heading count (stale derive), and every `depends_on` must reference an earlier
299
+ * phase (exists, no self/forward/cyclic edge against body order).
300
+ */
301
+ const REVIEW_PHASE_ITERATE = iterate({
302
+ source: "architecture-reviews",
303
+ unit: { by: "frontmatter-array", pattern: "phases" },
304
+ max: MAX_PHASES,
305
+ next: ({ artifact, state, accumulated, cwd }) => {
306
+ // Source the review from the named registry — robust to corrective re-entry,
307
+ // where the rolling primary is the latest code-review doc, not the review.
308
+ const review = latestFsArtifact(state, "architecture-reviews") ?? artifact;
309
+ if (review?.handle.kind !== "fs") return null;
310
+ const reviewPath = review.handle.path; // captured: narrowing is lost inside nested closures below
311
+ const content = readArtifactFile(reviewPath, cwd);
312
+ const { frontmatter } = parseFrontmatter(content);
313
+ const raw = (frontmatter as Record<string, unknown>).phases;
314
+ const phases = Array.isArray(raw) ? raw : [];
315
+ const i = accumulated.length;
316
+ if (i === 0) {
317
+ const headingCount = countHeadingsOutsideFences(content, REVIEW_PHASE_RE);
318
+ if (phases.length !== headingCount) {
319
+ throw haltPreflight(
320
+ "REVIEW_PHASE_ITERATE",
321
+ `REVIEW_PHASE_ITERATE: review ${reviewPath} has mismatched phases`,
322
+ `REVIEW_PHASE_ITERATE: review ${reviewPath} frontmatter phases (${phases.length}) ≠ '### Phase N —' headings (${headingCount}) — the derived array is stale against the body`,
323
+ );
324
+ }
325
+ const indexByN = new Map(phases.map((e, idx) => [phaseNum(e, idx), idx]));
326
+ phases.forEach((e, idx) => {
327
+ for (const d of phaseDeps(e)) {
328
+ const di = indexByN.get(d);
329
+ if (di === undefined)
330
+ throw haltPreflight(
331
+ "REVIEW_PHASE_ITERATE",
332
+ `REVIEW_PHASE_ITERATE: review ${reviewPath} has invalid depends_on`,
333
+ `REVIEW_PHASE_ITERATE: review ${reviewPath} phase ${phaseNum(e, idx)} depends_on ${d}, which is not a declared phase`,
334
+ );
335
+ if (di >= idx)
336
+ throw haltPreflight(
337
+ "REVIEW_PHASE_ITERATE",
338
+ `REVIEW_PHASE_ITERATE: review ${reviewPath} has cyclic dependency`,
339
+ `REVIEW_PHASE_ITERATE: review ${reviewPath} phase ${phaseNum(e, idx)} depends_on ${d}, which is not an earlier phase (self/forward/cyclic dependency)`,
340
+ );
341
+ }
342
+ });
343
+ }
344
+ if (i >= phases.length) return null; // every phase planned → terminate
345
+ const entry = (phases[i] ?? {}) as { title?: unknown; blast_radius?: unknown; effort?: unknown };
346
+ const n = phaseNum(entry, i);
347
+ const title = typeof entry.title === "string" ? entry.title : "";
348
+
349
+ // accumulated[j] is phase j's output — map each prior phase number to its plans.
350
+ const priorByN = new Map<number, string[]>();
351
+ accumulated.forEach((o, j) => {
352
+ const paths = o.artifacts.filter((a) => a.handle.kind === "fs").map((a) => handleToString(a.handle));
353
+ if (paths.length) priorByN.set(phaseNum(phases[j], j), paths);
354
+ });
355
+ const deps = phaseDeps(phases[i]);
356
+ const prior = deps.length ? deps.flatMap((d) => priorByN.get(d) ?? []) : [...priorByN.values()].flat();
357
+ // On a corrective pass the latest code-review is in `reviews`; fold its blockers in.
358
+ const feedback = latestFsArtifact(state, "reviews");
359
+
360
+ let prompt = `${handleToString(review.handle)} Implement Phase ${n}: ${title}`;
361
+ if (prior.length)
362
+ prompt += `\nPrior phase plans (read first; build on them, don't duplicate): ${prior.join(", ")}`;
363
+ if (feedback?.handle.kind === "fs")
364
+ prompt += `\nAddress the blockers in the latest code review: ${handleToString(feedback.handle)}`;
365
+ const tags = [entry.effort, entry.blast_radius].filter((t): t is string => typeof t === "string");
366
+ let label = `phase ${i + 1}/${phases.length} — ${title}`;
367
+ if (tags.length) label += ` [${tags.join(", ")}]`;
368
+ return { prompt, label, id: `phase-${n}` };
369
+ },
370
+ });
371
+
372
+ /**
373
+ * Fan implement out over the `phases:` array of EVERY plan in the latest
374
+ * blueprint pass (see `latestPlans` for the corrective-loop dedup), so blueprint
375
+ * keeps its natural timestamped filenames. The single-plan
376
+ * `FRONTMATTER_PHASE_FANOUT` is the same over one inherited plan; both share
377
+ * `planPhaseRecords`. MAX_PHASES is enforced on the aggregate unit count, since
378
+ * polish fans one implement pass over the whole plan set.
379
+ */
380
+ const PLANS_PHASE_FANOUT = fanout({
381
+ source: "plans",
382
+ unit: { by: "frontmatter-array", pattern: "phases" },
383
+ max: MAX_PHASES,
384
+ units: ({ state, cwd }) => {
385
+ const units: Unit[] = [];
386
+ for (const out of latestPlans(state, cwd)) {
387
+ for (const a of out.artifacts) {
388
+ if (a.handle.kind !== "fs") continue;
389
+ const path = a.handle.path;
390
+ const content = readArtifactFile(path, cwd);
391
+ const promptPath = handleToString(a.handle);
392
+ for (const r of planPhaseRecords(content, "PLANS_PHASE_FANOUT", path)) {
393
+ units.push({
394
+ prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
395
+ label: `${basename(path)} P${r.n}`,
396
+ });
397
+ }
398
+ }
399
+ }
400
+ if (units.length > MAX_PHASES) {
401
+ throw haltPreflight(
402
+ "PLANS_PHASE_FANOUT",
403
+ `PLANS_PHASE_FANOUT: phase limit exceeded`,
404
+ `PLANS_PHASE_FANOUT: ${units.length} phases exceeds MAX_PHASES (${MAX_PHASES})`,
405
+ );
406
+ }
407
+ return units;
408
+ },
409
+ });
410
+
411
+ /** `implement`'s serial twin of `PLANS_PHASE_FANOUT` (polish's multi-plan variant) — serialized (`concurrency: 1`) because the fanout's units share a working tree and their write-sets are unknown, so the scheduler cannot derive dep edges (no scope floor guards it). */
412
+ const IMPLEMENT_PLANS_FANOUT = { ...PLANS_PHASE_FANOUT, concurrency: 1 };
413
+
414
+ export {
415
+ FRONTMATTER_PHASE_FANOUT,
416
+ IMPLEMENT_DAG_FANOUT,
417
+ IMPLEMENT_PLANS_FANOUT,
418
+ latestPlans,
419
+ PLAN_PHASE_RE,
420
+ phaseFiles,
421
+ planPhaseRecords,
422
+ REVIEW_PHASE_ITERATE,
423
+ withTestTwins,
424
+ };