@juicesharp/rpiv-pi 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +9 -8
  2. package/docs/lanes.md +3 -2
  3. package/docs/models-config.md +6 -6
  4. package/docs/workflows.md +4 -18
  5. package/extensions/rpiv-core/artifact-collector.ts +2 -2
  6. package/extensions/rpiv-core/bash-timeout.ts +16 -0
  7. package/extensions/rpiv-core/built-in-workflows.ts +2289 -318
  8. package/extensions/rpiv-core/guidance.ts +35 -19
  9. package/extensions/rpiv-core/index.ts +2 -2
  10. package/extensions/rpiv-core/lane-console.ts +62 -5
  11. package/extensions/rpiv-core/lane-list.ts +84 -32
  12. package/extensions/rpiv-core/lane-progress.ts +13 -77
  13. package/extensions/rpiv-core/lane-switcher.ts +114 -33
  14. package/extensions/rpiv-core/lane-usage.ts +25 -0
  15. package/extensions/rpiv-core/models-config-validate.ts +1 -1
  16. package/extensions/rpiv-core/models-config.ts +38 -3
  17. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  18. package/extensions/rpiv-core/run-lane-registry.ts +80 -69
  19. package/extensions/rpiv-core/sdk-workflow-host.ts +43 -3
  20. package/extensions/rpiv-core/subagent-usage.ts +147 -0
  21. package/extensions/rpiv-core/workflow-execution-host.ts +24 -7
  22. package/package.json +3 -3
  23. package/skills/amend/SKILL.md +7 -3
  24. package/skills/annotate-guidance/SKILL.md +1 -0
  25. package/skills/architecture-review/SKILL.md +1 -0
  26. package/skills/blueprint/SKILL.md +10 -4
  27. package/skills/changelog/SKILL.md +1 -0
  28. package/skills/commit/SKILL.md +1 -0
  29. package/skills/design/SKILL.md +4 -3
  30. package/skills/design-review/SKILL.md +1 -0
  31. package/skills/design-slice/SKILL.md +2 -1
  32. package/skills/discover/SKILL.md +1 -1
  33. package/skills/elaborate/SKILL.md +21 -9
  34. package/skills/elaborate/_helpers/validate-workflow-invariant.mjs +88 -0
  35. package/skills/explore/SKILL.md +1 -0
  36. package/skills/frontend-design/SKILL.md +1 -0
  37. package/skills/grade/SKILL.md +24 -6
  38. package/skills/implement/SKILL.md +10 -2
  39. package/skills/plan/SKILL.md +10 -6
  40. package/skills/research/SKILL.md +9 -8
  41. package/skills/resume-handoff/SKILL.md +1 -0
  42. package/skills/revise/SKILL.md +1 -0
  43. package/skills/slice/SKILL.md +4 -3
  44. package/skills/synthesize/SKILL.md +16 -7
  45. package/skills/validate/SKILL.md +1 -0
@@ -14,7 +14,7 @@
14
14
  */
15
15
 
16
16
  import { execFileSync } from "node:child_process";
17
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
17
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
18
18
  import { basename, dirname, isAbsolute, join, sep } from "node:path";
19
19
  import { fileURLToPath } from "node:url";
20
20
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
@@ -25,6 +25,7 @@ import {
25
25
  defineWorkflow,
26
26
  directoryPathCollector,
27
27
  eq,
28
+ type FanoutContext,
28
29
  fanin,
29
30
  fanout,
30
31
  gate,
@@ -49,8 +50,8 @@ import { rpivBucketOutcome } from "./artifact-collector.js";
49
50
  // code-review stage sources it from the skill's contract `produces.data`
50
51
  // (`blockers_count` required), validated by the runtime output loop via
51
52
  // `effectiveOutputSchema`. One source of truth, in the skill, not copy-pasted
52
- // per workflow. Every workflow — build/arch/polish AND vet — routes on the
53
- // same numeric gate: `gate("blockers_count", { <fix>: gt(0), commit: eq(0) }, "commit")`.
53
+ // per workflow. Every workflow with a `code-review` stage — polish AND vet —
54
+ // routes on the same numeric gate: `gate("blockers_count", { <fix>: gt(0), commit: eq(0) }, "commit")`.
54
55
 
55
56
  /**
56
57
  * A plan's structured `phases:` frontmatter array — the machine-readable phase
@@ -72,35 +73,74 @@ const MAX_PHASES = 32;
72
73
  const PLAN_PHASE_RE = /^## Phase (\d+):/gm;
73
74
 
74
75
  /**
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).
76
+ * A fence-opening line: optional leading whitespace then 3+ backticks or 3+
77
+ * tildes (the CommonMark info-string delimiter). Single source of truth every
78
+ * fence-aware scan shares.
83
79
  */
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;
80
+ const FENCE_LINE_RE = /^\s*(`{3,}|~{3,})/;
81
+
82
+ /**
83
+ * Whether `line` CLOSES the fence whose opener recorded `fenceChar` and
84
+ * `fenceLen`. CommonMark: a closing fence uses the SAME char (``` ``` ``` does not
85
+ * close `~~~`) and is at least as long (a 4-backtick opener needs 4+ to close),
86
+ * with only that char plus optional trailing whitespace on the line. `fence` is
87
+ * the current line's `RegExpExecArray` match (narrowed from the guarded
88
+ * `.exec()` result).
89
+ */
90
+ const closesFence = (line: string, fence: RegExpExecArray, fenceChar: string, fenceLen: number): boolean => {
91
+ const len = fence[1].length;
92
+ return fence[1][0] === fenceChar && len >= fenceLen && line.trim().length === len;
93
+ };
94
+
95
+ /**
96
+ * Visit every line of `content` that sits OUTSIDE fenced code blocks, calling
97
+ * `visit(line, index)` with the line text and its 0-based index in
98
+ * `content.split("\n")`. A `## Phase N:` / `## Slice N:` / `### Phase N —` / a
99
+ * `#### N. path` inside a ``` or ~~~ fence is example/fixture text — a meta-plan
100
+ * (one whose subject is the pipeline) legitimately embeds the pipeline's own
101
+ * plan/slice fixtures — not a structural heading or declared write, so a naive
102
+ * line scan would false-count it. Mirrors the fence-aware boundary scan in
103
+ * skills/_shared/stitch-elaborations.mjs. Fence-opener and fence-closer lines
104
+ * are skipped (never visited); `index` advances once per line (including skipped
105
+ * fence lines) so it stays aligned with any caller's own `content.split("\n")`
106
+ * array.
107
+ */
108
+ const forEachLineOutsideFences = (content: string, visit: (line: string, index: number) => void): void => {
87
109
  let inFence = false;
88
110
  let fenceLen = 0;
111
+ let fenceChar = "";
112
+ let index = 0;
89
113
  for (const line of content.split("\n")) {
90
- const fence = /^\s*(`{3,}|~{3,})/.exec(line);
114
+ const fence = FENCE_LINE_RE.exec(line);
91
115
  if (fence) {
92
- const len = fence[1].length;
93
116
  if (!inFence) {
94
117
  inFence = true;
95
- fenceLen = len;
96
- } else if (len >= fenceLen && line.trim().length === len) {
118
+ fenceLen = fence[1].length;
119
+ fenceChar = fence[1][0];
120
+ } else if (closesFence(line, fence, fenceChar, fenceLen)) {
97
121
  inFence = false;
98
122
  fenceLen = 0;
123
+ fenceChar = "";
99
124
  }
100
- continue;
125
+ } else if (!inFence) {
126
+ visit(line, index);
101
127
  }
102
- if (!inFence && lineRe.test(line)) count++;
128
+ index++;
103
129
  }
130
+ };
131
+
132
+ /**
133
+ * Count lines matching `re` (a `^…` heading pattern) that sit OUTSIDE fenced code
134
+ * blocks. Fence-awareness lives on `forEachLineOutsideFences` (a naive `matchAll`
135
+ * counts fenced examples and false-throws the derived-array staleness guard);
136
+ * the per-line `lineRe` drops the source's `g`/`m` flags so `lastIndex` can't drift.
137
+ */
138
+ const countHeadingsOutsideFences = (content: string, re: RegExp): number => {
139
+ const lineRe = new RegExp(re.source); // per-line test; drop g/m so lastIndex can't drift
140
+ let count = 0;
141
+ forEachLineOutsideFences(content, (line) => {
142
+ if (lineRe.test(line)) count++;
143
+ });
104
144
  return count;
105
145
  };
106
146
 
@@ -178,12 +218,109 @@ const planPhaseRecords = (content: string, who: string, path: string): readonly
178
218
  const latestFsArtifact = (state: RunView, name: string): Artifact | undefined =>
179
219
  state.named[name]?.at(-1)?.artifacts.find((a) => a.handle.kind === "fs");
180
220
 
221
+ /**
222
+ * Read the latest plan published to the named `"plans"` channel and parse its
223
+ * `phases:` frontmatter into records — the shared read/halt body both
224
+ * `FRONTMATTER_PHASE_FANOUT` and `IMPLEMENT_DAG_FANOUT` source from. Returns
225
+ * `null` when no fs plan is published (each caller degrades to `[]`); throws
226
+ * the two `haltPreflight` diagnostics (plan-not-found, exceeds `MAX_PHASES`)
227
+ * attributed to `who`. `promptPath` is the plan handle's string form, so each
228
+ * fanout emits the same `${promptPath} Phase N:` prompt arg.
229
+ */
230
+ const readPlanPhaseRecords = (
231
+ state: RunView,
232
+ cwd: string,
233
+ who: string,
234
+ ): { records: readonly PhaseRecord[]; promptPath: string } | null => {
235
+ const plan = latestFsArtifact(state, "plans");
236
+ if (plan?.handle.kind !== "fs") return null;
237
+ const path = plan.handle.path;
238
+ let content: string;
239
+ try {
240
+ content = readArtifactFile(path, cwd);
241
+ } catch (err) {
242
+ throw haltPreflight(
243
+ who,
244
+ `${who}: plan file not found`,
245
+ `${who}: could not read ${path} — ${err instanceof Error ? err.message : String(err)}`,
246
+ );
247
+ }
248
+ const records = planPhaseRecords(content, who, path);
249
+ if (records.length > MAX_PHASES) {
250
+ throw haltPreflight(
251
+ who,
252
+ `${who}: plan ${path} exceeds phase limit`,
253
+ `${who}: plan ${path} declares ${records.length} phases — exceeds MAX_PHASES (${MAX_PHASES}); split into smaller plans`,
254
+ );
255
+ }
256
+ const promptPath = handleToString(plan.handle);
257
+ return { records, promptPath };
258
+ };
259
+
260
+ /**
261
+ * An `Artifact` narrowed to its `fs`-handle variant — the plan-path-carrying
262
+ * shape the scope checks key the verdict path + `artifact` field off. Annotates
263
+ * a captured artifact ACROSS loop iterations so the `if (a.handle.kind !== "fs")
264
+ * continue` guard's narrowing carries to the post-loop `latest.handle.path` read
265
+ * (the file's idiom — `designPathsBySlice` reads `.path` inside its own
266
+ * same-scope guard; this loop captures the artifact across iterations, so the
267
+ * narrowed type annotates the capture).
268
+ */
269
+ type FsArtifact = Artifact & { handle: { kind: "fs"; path: string } };
270
+
271
+ /**
272
+ * Union the per-phase `files:` write-set declared across the FULL `plans`
273
+ * channel history. vet's review-fix loop appends a DISTINCT non-superseding fix
274
+ * plan per iteration (a `produces` stage APPENDS to its named slot, and backward
275
+ * jumps don't reset channels), so a path a prior plan legitimately wrote is not
276
+ * excess against the latest plan — hence the union, not latest-only.
277
+ *
278
+ * Reads every fs artifact in every plan via `planPhaseRecords` + `phaseFiles`,
279
+ * skipping unreadable/unparseable plans (the union stays the sum of the
280
+ * parseable ones; a plan too malformed to parse is a `plan-cite-check`/
281
+ * `plan-fix` concern, not scope). `latest` is the FIRST fs artifact of the LAST
282
+ * plan carrying one (mirrors `latestFsArtifact`'s last-channel-entry / first-fs-
283
+ * artifact resolution) — it keys the basename-keyed verdict path + `artifact`
284
+ * field.
285
+ */
286
+ const unionDeclaredWriteSet = (
287
+ plans: readonly Output[],
288
+ cwd: string,
289
+ ): { declared: Set<string>; latest: FsArtifact | undefined } => {
290
+ const declared = new Set<string>();
291
+ let latest: FsArtifact | undefined;
292
+ for (const out of plans) {
293
+ // Per plan, capture its FIRST fs artifact as the `latest` candidate so the
294
+ // LAST plan with an fs artifact wins (mirrors `latestFsArtifact`'s
295
+ // `.at(-1)?.artifacts.find(kind==="fs")` — last channel entry, first fs
296
+ // artifact in it — which keys the verdict path + `artifact` field).
297
+ let firstFsInPlan: FsArtifact | undefined;
298
+ for (const a of out.artifacts) {
299
+ if (a.handle.kind !== "fs") continue; // fs-artifact filter
300
+ if (!firstFsInPlan) firstFsInPlan = a as FsArtifact;
301
+ const path = a.handle.path;
302
+ try {
303
+ const content = readArtifactFile(path, cwd);
304
+ for (const r of planPhaseRecords(content, "implement-scope-check", path)) {
305
+ for (const f of phaseFiles(r.entry)) declared.add(f);
306
+ }
307
+ } catch {
308
+ // Unreadable/unparseable plan: don't widen the declared set on error —
309
+ // the union stays the sum of the parseable plans. (A plan so malformed
310
+ // it can't be parsed is a `plan-cite-check`/`plan-fix` concern, not scope.)
311
+ }
312
+ }
313
+ if (firstFsInPlan) latest = firstFsInPlan;
314
+ }
315
+ return { declared, latest };
316
+ };
317
+
181
318
  /**
182
319
  * Fan `implement` out over the structured `phases:` frontmatter array of the
183
320
  * latest plan published to the named `"plans"` channel. Sourcing from the named
184
321
  * channel (not the rolling primary) makes the stage's `reads: ["plans"]`
185
322
  * declaration semantically honest. Used by every workflow whose `implement`
186
- * inherits one plan (ship/build/arch/vet); polish's accumulating multi-plan
323
+ * inherits one plan (build/vet); polish's accumulating multi-plan
187
324
  * variant is `PLANS_PHASE_FANOUT`.
188
325
  */
189
326
  const FRONTMATTER_PHASE_FANOUT = fanout({
@@ -191,28 +328,9 @@ const FRONTMATTER_PHASE_FANOUT = fanout({
191
328
  unit: { by: "frontmatter-array", pattern: "phases" },
192
329
  max: MAX_PHASES,
193
330
  units: ({ state, cwd }) => {
194
- const plan = latestFsArtifact(state, "plans");
195
- if (plan?.handle.kind !== "fs") return [];
196
- const path = plan.handle.path;
197
- let content: string;
198
- try {
199
- content = readArtifactFile(path, cwd);
200
- } catch (err) {
201
- throw haltPreflight(
202
- "FRONTMATTER_PHASE_FANOUT",
203
- `FRONTMATTER_PHASE_FANOUT: plan file not found`,
204
- `FRONTMATTER_PHASE_FANOUT: could not read ${path} — ${err instanceof Error ? err.message : String(err)}`,
205
- );
206
- }
207
- const records = planPhaseRecords(content, "FRONTMATTER_PHASE_FANOUT", path);
208
- if (records.length > MAX_PHASES) {
209
- throw haltPreflight(
210
- "FRONTMATTER_PHASE_FANOUT",
211
- `FRONTMATTER_PHASE_FANOUT: plan ${path} exceeds phase limit`,
212
- `FRONTMATTER_PHASE_FANOUT: plan ${path} declares ${records.length} phases — exceeds MAX_PHASES (${MAX_PHASES}); split into smaller plans`,
213
- );
214
- }
215
- const promptPath = handleToString(plan.handle);
331
+ const read = readPlanPhaseRecords(state, cwd, "FRONTMATTER_PHASE_FANOUT");
332
+ if (!read) return [];
333
+ const { records, promptPath } = read;
216
334
  return records.map((r) => ({
217
335
  prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
218
336
  label: `phase ${r.index + 1}/${r.total}`,
@@ -221,110 +339,71 @@ const FRONTMATTER_PHASE_FANOUT = fanout({
221
339
  });
222
340
 
223
341
  /**
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.
342
+ * Derive the directed `deps` edges for ONE implement phase under the dep-gated
343
+ * DAG fanout (`IMPLEMENT_DAG_FANOUT`). Edges point strictly downward (toward
344
+ * LOWER phase numbers), so the graph is acyclic by construction. Two clauses:
345
+ *
346
+ * - clause A (self declares a `files:` write-set): `self` depends on every
347
+ * LOWER phase whose declared `files:` shares ≥1 entry, UNIONED with `self`'s
348
+ * explicit `depends_on` (semantic ordering not visible in `files:`).
349
+ * - clause B (self declares NO `files:`): `self` conflicts with EVERY lower
350
+ * phase → full chain (a write-set-less phase's writes are unknown, so it
351
+ * cannot be proven independent of anything below it). This is the
352
+ * empty-set degradation that keeps a legacy / `files:`-less plan serial at
353
+ * any cap (one phase per Kahn wave).
354
+ *
355
+ * Returns `phase-<n>` unit ids, sorted ascending. Reads `phaseFiles`
356
+ * and `phaseDeps` — both defined later textually, but only inside this
357
+ * runtime closure, so no TDZ (same pattern as `sliceDeps`).
231
358
  */
232
- const IMPLEMENT_PHASE_FANOUT = { ...FRONTMATTER_PHASE_FANOUT, concurrency: 1 };
233
-
234
- // ===========================================================================
235
- // ship — blueprint → implement → validate → commit
236
- // ===========================================================================
237
-
238
- const shipWorkflow = defineWorkflow({
239
- name: "ship",
240
- description:
241
- "Fast path with no research or review. Best when the change is small and the approach is obvious. Chain: blueprint → implement → validate → commit.",
242
- start: "blueprint",
243
- stages: {
244
- blueprint: produces(),
245
- implement: acts({ loop: IMPLEMENT_PHASE_FANOUT, reads: ["plans"] }),
246
- validate: produces(),
247
- commit: acts({ outcome: gitCommitOutcome }),
248
- },
249
- edges: {
250
- blueprint: "implement",
251
- implement: "validate",
252
- validate: "commit",
253
- commit: "stop",
254
- },
255
- });
256
-
257
- // ===========================================================================
258
- // arch — research → design → plan → implement → validate → code-review →
259
- // (design → loop) | commit
260
- // Loops the full design/plan/implement/validate/review chain until
261
- // code-review reports zero blockers, bounded by the runner's
262
- // maxBackwardJumps (default 2 → up to 3 review iterations).
263
- // ===========================================================================
264
-
265
- const archWorkflow = defineWorkflow({
266
- name: "arch",
267
- description:
268
- "Design-led pipeline for complex changes touching many files or layers. Best when the approach itself needs to be worked out before planning. Chain: research → design → plan → implement → validate → code-review → (design loop) → commit.",
269
- start: "research",
270
- stages: {
271
- research: produces(),
272
- design: produces(),
273
- plan: produces(),
274
- implement: acts({ loop: IMPLEMENT_PHASE_FANOUT, reads: ["plans"] }),
275
- validate: produces(),
276
- "code-review": produces(),
277
- commit: acts({ outcome: gitCommitOutcome }),
278
- },
279
- edges: {
280
- research: "design",
281
- design: "plan",
282
- plan: "implement",
283
- implement: "validate",
284
- validate: "code-review",
285
- // Backward edge: code-review → design re-enters the full
286
- // design/plan/implement/validate/review cycle. Bounded by the
287
- // runner's default maxBackwardJumps (2), permitting at most 3
288
- // review iterations before the guard halts.
289
- "code-review": gate("blockers_count", { design: gt(0), commit: eq(0) }, "commit"),
290
- commit: "stop",
291
- },
292
- });
293
-
294
- // ===========================================================================
295
- // vet — code-review → (blueprint → implement → validate → loop) | commit
296
- // Examine existing changes; if not approved, blueprint a fix plan,
297
- // implement it, validate, and re-review. Loops until approved.
298
- // ===========================================================================
359
+ const implementPhaseDeps = (records: readonly PhaseRecord[], self: PhaseRecord): string[] => {
360
+ // Twin-expanded (`withTestTwins`) so a phase declaring `x.ts` conflicts with
361
+ // one declaring `x.test.ts` — the production phase's implicit twin write would
362
+ // otherwise race a concurrent sibling that owns the test explicitly.
363
+ const selfFiles = withTestTwins(phaseFiles(self.entry));
364
+ const explicit = phaseDeps(self.entry);
365
+ const ns = new Set<number>();
366
+ for (const e of explicit) if (e < self.n) ns.add(e);
367
+ if (selfFiles.length === 0) {
368
+ // clause B — unknown write-set ⇒ conflict with every lower phase.
369
+ for (const r of records) if (r.n < self.n) ns.add(r.n);
370
+ } else {
371
+ // clause A — overlap on ≥1 declared write path.
372
+ for (const r of records) {
373
+ if (r.n >= self.n) continue;
374
+ const rFiles = withTestTwins(phaseFiles(r.entry));
375
+ if (rFiles.some((f) => selfFiles.includes(f))) ns.add(r.n);
376
+ }
377
+ }
378
+ return [...ns].sort((a, b) => a - b).map((n) => `phase-${n}`);
379
+ };
299
380
 
300
- const vetWorkflow = defineWorkflow({
301
- name: "vet",
302
- description:
303
- "Examine existing changes for approval; loop a fix cycle if not approved. Best when a diff already exists (yours or a teammate's) and you want a structured review with optional repair. Chain: code-review → (blueprint → implement → validate → loop) → commit.",
304
- start: "code-review",
305
- stages: {
306
- "code-review": produces(),
307
- blueprint: produces(),
308
- implement: acts({ loop: IMPLEMENT_PHASE_FANOUT, reads: ["plans"] }),
309
- validate: produces(),
310
- commit: acts({ outcome: gitCommitOutcome }),
311
- },
312
- edges: {
313
- // Same numeric gate as build/arch/polish: zero remaining blockers →
314
- // commit; any blockers → loop a fix pass through blueprint. The
315
- // `blockers_count` field is sourced + validated from the code-review
316
- // contract (`produces.data`, required), so a missing field fails
317
- // output validation rather than silently routing.
318
- "code-review": gate("blockers_count", { blueprint: gt(0), commit: eq(0) }, "commit"),
319
- blueprint: "implement",
320
- implement: "validate",
321
- // Backward edge: validate → code-review creates the review-fix loop.
322
- // Bounded by the runner's default maxBackwardJumps (2), permitting at
323
- // most 3 review iterations (initial + 2 retries) before the guard halts.
324
- validate: "code-review",
325
- commit: "stop",
381
+ /**
382
+ * Dep-gated DAG variant of `FRONTMATTER_PHASE_FANOUT` — `implement`'s twin that
383
+ * emits per-phase `id`/`deps` edges so the wave scheduler orders phases by their
384
+ * declared write-set overlap + explicit `depends_on`. The spread idiom inherits
385
+ * `source`/`unit`/`max`/`onCap`/`result`/`kind` verbatim from the base; the new
386
+ * `units` closure emits the SAME `prompt`/`label` strings AND adds
387
+ * `id: \`phase-${r.n}\`` + `deps: implementPhaseDeps(records, r)`. NO
388
+ * `depArtifactFlag` — implement phases feed each other through the working tree
389
+ * (not published artifacts), so `deps` drive ONLY wave ordering. NO
390
+ * `concurrency` property is set (the spread overrides only `units`), so the loop
391
+ * inherits the host cap and phases fan out concurrently, bounded by `deps`.
392
+ */
393
+ const IMPLEMENT_DAG_FANOUT = {
394
+ ...FRONTMATTER_PHASE_FANOUT,
395
+ units: ({ state, cwd }: FanoutContext) => {
396
+ const read = readPlanPhaseRecords(state, cwd, "IMPLEMENT_DAG_FANOUT");
397
+ if (!read) return [];
398
+ const { records, promptPath } = read;
399
+ return records.map((r) => ({
400
+ prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
401
+ label: `phase ${r.index + 1}/${r.total}`,
402
+ id: `phase-${r.n}`,
403
+ deps: implementPhaseDeps(records, r),
404
+ }));
326
405
  },
327
- });
406
+ };
328
407
 
329
408
  // ===========================================================================
330
409
  // polish — architecture-review → blueprint (iterate, per review phase) →
@@ -375,6 +454,44 @@ const phaseDeps = (entry: unknown): number[] => {
375
454
  return Array.isArray(raw) ? raw.filter((d): d is number => typeof d === "number") : [];
376
455
  };
377
456
 
457
+ /** The repo-root-relative paths a phase entry declares it creates/edits (its
458
+ * `files:` array — `[]` when absent). The open-schema twin of `phaseDeps`,
459
+ * read straight off `PhaseRecord.entry` so `planPhaseRecords` preserves the new
460
+ * key unchanged. Consumed by the plan-time coverage floor
461
+ * (`verifyPhaseFilesCoverage`) and, in a later phase, the dep-gated implement
462
+ * fanout (`implementPhaseDeps`). */
463
+ const phaseFiles = (entry: unknown): string[] => {
464
+ const raw = (entry as { files?: unknown } | undefined)?.files;
465
+ return Array.isArray(raw) ? raw.filter((f): f is string => typeof f === "string") : [];
466
+ };
467
+
468
+ /**
469
+ * Expand a declared write-set with each production file's co-located test twin
470
+ * (`x.ts → x.test.ts`, likewise tsx/js/jsx). This monorepo's tests are
471
+ * compile-coupled siblings — widening a declared file's signature forces the
472
+ * mechanical follow-up edit in its twin — so requiring every plan author,
473
+ * elaborator, and grader to re-declare the twin is paperwork the convention
474
+ * already guarantees (a live run STOPPED at the scope floor over exactly this:
475
+ * a declared `lane-switcher.ts` signature change whose five-assertion twin fix
476
+ * was undeclared prose). Applied at BOTH consumers of the declared set — the
477
+ * DAG conflict fold (`implementPhaseDeps`) and the scope floors — so the
478
+ * planner and the floor can never disagree; on the DAG side it also closes the
479
+ * latent race where phases declaring `x.ts` and `x.test.ts` counted as
480
+ * disjoint yet predictably collide. Asymmetric by design: declaring a TEST
481
+ * file licenses nothing extra — production writes remain the act that must be
482
+ * declared, and a write to a non-twin test still fails the floor. A file
483
+ * already matching `TEST_PATH_RE` maps to itself (no `x.test.test.ts`).
484
+ */
485
+ const withTestTwins = (files: readonly string[]): string[] => {
486
+ const out = new Set(files);
487
+ for (const f of files) {
488
+ if (TEST_PATH_RE.test(f)) continue;
489
+ const twin = f.replace(/\.([tj]sx?)$/, ".test.$1");
490
+ if (twin !== f) out.add(twin);
491
+ }
492
+ return [...out];
493
+ };
494
+
378
495
  /**
379
496
  * Per-review-phase blueprint generator (the `iterate` dual of
380
497
  * FRONTMATTER_PHASE_FANOUT). One blueprint pass per review phase, enumerating the
@@ -501,7 +618,7 @@ const PLANS_PHASE_FANOUT = fanout({
501
618
  },
502
619
  });
503
620
 
504
- /** `implement`'s serial twin of `PLANS_PHASE_FANOUT` (polish's multi-plan variant) — same serialize-shared-tree rationale as `IMPLEMENT_PHASE_FANOUT`. */
621
+ /** `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). */
505
622
  const IMPLEMENT_PLANS_FANOUT = { ...PLANS_PHASE_FANOUT, concurrency: 1 };
506
623
 
507
624
  /**
@@ -551,7 +668,7 @@ const polishWorkflow = defineWorkflow({
551
668
  // → slice-design (fanout) → design-review (one human checkpoint) →
552
669
  // subplan (cluster fanout) → plan → plan-grade (plan-fix loop) →
553
670
  // code (fanout) → code-splice → code-grade (code-fix loop) →
554
- // implement → validate → commit
671
+ // implement → implement-scope-check → reconcile → validate → commit
555
672
  // The sliced, panel-gated heavy path: capture the user's brief verbatim as the
556
673
  // `goal` channel (the north star the judgment seams — the two grade panels'
557
674
  // completeness/correctness dimensions and validate — anchor against), research
@@ -570,7 +687,6 @@ const polishWorkflow = defineWorkflow({
570
687
  // (per-cluster sub-plans → one plan) so no pass holds every design, gate the
571
688
  // plan on quality dimensions BEFORE any code, elaborate code per phase and
572
689
  // splice it in, re-grade the code-bearing plan, then implement/validate/commit.
573
- // The parallel generalization of `arch`.
574
690
  // ===========================================================================
575
691
 
576
692
  /**
@@ -652,19 +768,38 @@ const captureGoal = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
652
768
  };
653
769
  };
654
770
 
771
+ /** Parse `git status --porcelain`/`--short` output into dirty paths. Strips the
772
+ * 2-char `XY` status prefix and resolves rename targets (`XY old -> new` → `new`),
773
+ * so the two output forms (`--porcelain`, `--short`) normalize identically. A
774
+ * porcelain line is always `XY <path>` or `XY <old> -> <new>`; blank lines drop. */
775
+ const parseGitStatusPaths = (out: string): string[] =>
776
+ out
777
+ .split("\n")
778
+ .filter((l) => l.trim() !== "")
779
+ .map((l) => {
780
+ const rest = l.slice(3).trim();
781
+ const arrow = rest.indexOf(" -> ");
782
+ return arrow >= 0 ? rest.slice(arrow + 4).trim() : rest;
783
+ });
784
+
655
785
  /** Record the paths dirty before the run to `rel` (best-effort; empty on any git failure). */
656
786
  const writeCommitBaseline = (cwd: string, rel: string): void => {
657
787
  let paths: string[] = [];
658
788
  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
- });
789
+ // stdio: stderr ignored — without this, git's "fatal: not a git repository"
790
+ // leaks to the parent's stderr even though the catch treats it as a
791
+ // supported silent degrade (best-effort baseline, empty on failure).
792
+ // -uall: git collapses an untracked directory to one `dir/` entry by
793
+ // default, so a phase's brand-new files under a new directory would never
794
+ // string-match their `files:` declarations at the scope floor. Enumerate
795
+ // every file; the baseline and both scope checks MUST share this flag or
796
+ // their path universes diverge.
797
+ const out = execFileSync("git", ["status", "--short", "--untracked-files=all"], {
798
+ cwd,
799
+ encoding: "utf-8",
800
+ stdio: ["ignore", "pipe", "ignore"],
801
+ });
802
+ paths = parseGitStatusPaths(out);
668
803
  } catch {
669
804
  paths = [];
670
805
  }
@@ -678,6 +813,89 @@ const goalBaselinePath = (state: RunView): string | undefined => {
678
813
  return a ? handleToString(a.handle) : undefined;
679
814
  };
680
815
 
816
+ /**
817
+ * Read the run-start pre-existing-dirty baseline off the goal channel's
818
+ * "baseline" artifact: the `{ paths }` JSON the baseline writer records. Best-
819
+ * effort — `[]` on no path (no `goal` stage), an unreadable file, or a `paths`
820
+ * value that isn't a string array, so the scope floor degrades to baseline-less
821
+ * (nothing subtracted) rather than throwing.
822
+ */
823
+ const readGoalBaseline = (path: string | undefined, cwd: string): string[] => {
824
+ if (!path) return [];
825
+ try {
826
+ const parsed = JSON.parse(readArtifactFile(path, cwd)) as { paths?: unknown };
827
+ const p = parsed.paths;
828
+ return Array.isArray(p) ? p.filter((x): x is string => typeof x === "string") : [];
829
+ } catch {
830
+ return [];
831
+ }
832
+ };
833
+
834
+ /**
835
+ * Current dirty-path set via `git status --porcelain` (rename targets resolved by
836
+ * the shared parser). Best-effort — `[]` on a non-repo / git-missing tree (the
837
+ * scope floor degrades to unguarded rather than failing a non-repo run; the
838
+ * catch treats that as a supported silent degrade). stdio: stderr is ignored,
839
+ * otherwise git's "fatal: not a git repository" leaks to the parent's stderr
840
+ * despite the catch. `-uall` enumerates untracked files individually (a collapsed
841
+ * `newdir/` entry can never string-match a declared `files:` path) — the
842
+ * baseline writer and both scope checks MUST share this flag or their path
843
+ * universes diverge.
844
+ */
845
+ const gitDirtyPaths = (cwd: string): string[] => {
846
+ try {
847
+ const out = execFileSync("git", ["status", "--porcelain", "--untracked-files=all"], {
848
+ cwd,
849
+ encoding: "utf-8",
850
+ stdio: ["ignore", "pipe", "ignore"],
851
+ });
852
+ return parseGitStatusPaths(out);
853
+ } catch {
854
+ return [];
855
+ }
856
+ };
857
+
858
+ /** Paths under these run-bookkeeping trees are NEVER a scope violation — the run
859
+ * legitimately writes its artifacts/notes/trails here regardless of phase scope. */
860
+ const SCOPE_BOOKKEEPING_DIRS: ReadonlySet<string> = new Set([".rpiv", "thoughts"]);
861
+
862
+ /**
863
+ * The lane-level scope floor's pure core. Returns the dirty paths that are NOT
864
+ * explained by the run's declared write-set: a path is excess when it is outside
865
+ * `declared`, was NOT dirty at the run-start `baseline`, and is NOT under a
866
+ * bookkeeping tree (`.rpiv/`, `thoughts/`). The `implement` lane declared-set is
867
+ * the union of its plan's per-phase `files:`; `validate`'s whole-repo
868
+ * build/test writes are owned by a later stage, never by a phase.
869
+ *
870
+ * Empty `declared` ⇒ `[]` (degradation): a `files:`-less plan is serial-by-
871
+ * construction under the DAG fanout's missing-`files:` clause (full dep chain ⇒
872
+ * one phase per wave), so there is no concurrent sibling to corrupt and nothing
873
+ * to guard — the floor returns no excess and never false-fails a legacy plan.
874
+ * `validate`'s whole-repo writes are out of scope here regardless: they belong
875
+ * to `validate`, which runs AFTER this gate, so the lane's dirty set never
876
+ * carries them at the scope-check's read time.
877
+ *
878
+ * This is deliberately LANE-level, not per-phase: under concurrency, a dirty
879
+ * path cannot be attributed to the specific phase that wrote it, so per-phase
880
+ * enforcement would be unsound. The per-phase discipline is enforced upstream
881
+ * by the plan-authoring write-scope rule + the plan-time coverage floor;
882
+ * this lane floor is the structural backstop that catches a phase that escaped
883
+ * upstream discipline. Returns one entry per excess path.
884
+ */
885
+ const scopeExcess = (dirty: readonly string[], baseline: readonly string[], declared: readonly string[]): string[] => {
886
+ if (declared.length === 0) return [];
887
+ const declaredSet = new Set(declared);
888
+ const baselineSet = new Set(baseline);
889
+ const excess: string[] = [];
890
+ for (const path of dirty) {
891
+ if (declaredSet.has(path) || baselineSet.has(path)) continue;
892
+ const top = path.split("/")[0];
893
+ if (SCOPE_BOOKKEEPING_DIRS.has(top)) continue;
894
+ excess.push(path);
895
+ }
896
+ return excess;
897
+ };
898
+
681
899
  /**
682
900
  * `goal` displaces `research` as build's start stage, and ONLY the start stage
683
901
  * receives `originalInput` as its skill arg (`stageEntryArgs` case 1) — a plain
@@ -880,6 +1098,10 @@ const sliceCovers = (entry: Record<string, unknown>): string[] => {
880
1098
 
881
1099
  /** The verdict directory the deterministic checks and the LLM grade panel share. */
882
1100
  const VERDICT_DIR = ".rpiv/artifacts/verdicts";
1101
+ /** Binary verdict score: a clean pass. The gate keys off `severity`, never this number. */
1102
+ const VERDICT_PASS_SCORE = 100;
1103
+ /** Binary verdict score: at least one finding. The gate keys off `severity`, never this number. */
1104
+ const VERDICT_FAIL_SCORE = 0;
883
1105
 
884
1106
  /**
885
1107
  * A `path:line` (or `path:line-line`) citation in an artifact's prose. Requires a
@@ -915,6 +1137,12 @@ const CITATION_WALK_SKIP: ReadonlySet<string> = new Set(["node_modules", ".git",
915
1137
  /** Backstop so a pathological tree can't stall the deterministic cite floor. */
916
1138
  const CITATION_WALK_FILE_CAP = 50_000;
917
1139
 
1140
+ /** The lazily-built basename → absolute-path(s) index backing the suffix
1141
+ * fallback in `resolveCitationPath`. `truncated` marks a partial walk past
1142
+ * `CITATION_WALK_FILE_CAP`, which disables the fallback (uniqueness
1143
+ * untrustworthy). */
1144
+ type BasenameIndex = { index: Map<string, string[]>; truncated: boolean };
1145
+
918
1146
  /**
919
1147
  * Index every source file's basename → its absolute path(s) under `cwd` — the
920
1148
  * candidate pool behind the suffix fallback in `verifyCitations`. The generative
@@ -928,7 +1156,7 @@ const CITATION_WALK_FILE_CAP = 50_000;
928
1156
  * vendored/generated trees so a citation never resolves to a build copy or a
929
1157
  * prior artifact. Bounded by the file cap.
930
1158
  */
931
- const buildBasenameIndex = (cwd: string): { index: Map<string, string[]>; truncated: boolean } => {
1159
+ const buildBasenameIndex = (cwd: string): BasenameIndex => {
932
1160
  // Unreadable dir → empty listing, never a throw from the deterministic floor.
933
1161
  const listDir = (dir: string) => {
934
1162
  try {
@@ -962,59 +1190,149 @@ const buildBasenameIndex = (cwd: string): { index: Map<string, string[]>; trunca
962
1190
  return { index, truncated: false };
963
1191
  };
964
1192
 
1193
+ /** Outcome of resolving a single citation's `path` against `cwd`. `abs` is the
1194
+ * one backing file when resolution is unique; `ambiguous` carries the candidate
1195
+ * list (absolute paths) when more than one tree file matches, so the caller can
1196
+ * render the disambiguation finding text. `undefined` ⇒ no match
1197
+ * (does-not-exist). This is the minimal-deviation return shape — a plain
1198
+ * `string | undefined` would drop the candidate list the disambiguation finding
1199
+ * text depends on. */
1200
+ type CitationResolution = { abs: string } | { ambiguous: string[] };
1201
+
1202
+ /** Strategy 4 of `resolveCitationPath`: tree files whose REPO-RELATIVE path ends
1203
+ * with the cited `path` on WHOLE segments. A bare basename is the one-segment
1204
+ * case; a multi-segment citation narrows the basename's candidates at a `/`
1205
+ * boundary, so `workflow/validate/x.ts` can never match inside
1206
+ * `rpiv-workflow/validate/x.ts`. Compared repo-relative (never against the
1207
+ * absolute path) so the checkout directory's own name can never back a citation
1208
+ * — `src/utils.ts` must not resolve to `<cwd>/utils.ts` just because the repo
1209
+ * happens to be cloned at `/tmp/src`. Reads/writes the shared `indexHolder` so
1210
+ * the basename index is built lazily ONCE and shared across citations (the
1211
+ * first direct-resolution miss pays the tree walk). */
1212
+ const suffixMatchesFor = (path: string, cwd: string, indexHolder: { value: BasenameIndex | undefined }): string[] => {
1213
+ indexHolder.value ??= buildBasenameIndex(cwd);
1214
+ if (indexHolder.value.truncated) return []; // partial index ⇒ uniqueness untrustworthy ⇒ strict
1215
+ const candidates = indexHolder.value.index.get(basename(path)) ?? [];
1216
+ if (!path.includes("/")) return candidates;
1217
+ const suffix = `/${path}`;
1218
+ return candidates.filter((abs) =>
1219
+ `/${abs
1220
+ .slice(cwd.length + 1)
1221
+ .split(sep)
1222
+ .join("/")}`.endsWith(suffix),
1223
+ );
1224
+ };
1225
+
1226
+ /** Resolve a citation's `path` to one backing file under `cwd`, encapsulating
1227
+ * all four strategies in order: (1) direct — `path` or `cwd/path`; (2,3)
1228
+ * dependency probes — `node_modules/<path>` and `node_modules/@<path>` (the
1229
+ * latter because the citation regex cannot carry `@`, so a cited
1230
+ * `node_modules/@scope/pkg/f.js` parses as `scope/pkg/f.js`); DIRECT probes
1231
+ * only — the suffix walk still skips `node_modules` (per `CITATION_WALK_SKIP`),
1232
+ * so a bare basename never resolves into a dep; (4) suffix fallback — a UNIQUE
1233
+ * tree-file suffix match backs the citation, an AMBIGUOUS one returns the
1234
+ * candidate list. PURE: emits no findings and throws never — all finding text
1235
+ * lives in `verifyCitations`. The lazily-built basename index is shared across
1236
+ * calls via `indexHolder`. */
1237
+ const resolveCitationPath = (
1238
+ path: string,
1239
+ cwd: string,
1240
+ indexHolder: { value: BasenameIndex | undefined },
1241
+ ): CitationResolution | undefined => {
1242
+ // Strategy 1 — direct.
1243
+ const direct = isAbsolute(path) ? path : join(cwd, path);
1244
+ if (existsSync(direct) && statSync(direct).isFile()) return { abs: direct };
1245
+ // Strategies 2 & 3 — dependency probes (lockfile-pinned dep source; the regex
1246
+ // cannot carry `@`, so `node_modules/@scope/pkg/f.js` is cited as `scope/pkg/f.js`).
1247
+ for (const candidate of [join(cwd, "node_modules", path), join(cwd, "node_modules", `@${path}`)]) {
1248
+ if (existsSync(candidate) && statSync(candidate).isFile()) return { abs: candidate };
1249
+ }
1250
+ // Strategy 4 — suffix fallback: back the citation iff exactly ONE tree file matches.
1251
+ const matches = suffixMatchesFor(path, cwd, indexHolder);
1252
+ if (matches.length === 1) return { abs: matches[0] };
1253
+ if (matches.length > 1) return { ambiguous: matches };
1254
+ return undefined;
1255
+ };
1256
+
1257
+ /**
1258
+ * Character-offset spans of fenced code blocks (delimiter lines included), an
1259
+ * unterminated fence running to end-of-text. Mirrors the `inFence`/`fenceLen`
1260
+ * toggle `countHeadingsOutsideFences` carries so every fence-aware scan agrees
1261
+ * on the same boundaries.
1262
+ */
1263
+ const fencedSpans = (content: string): [number, number][] => {
1264
+ const spans: [number, number][] = [];
1265
+ let inFence = false;
1266
+ let fenceLen = 0;
1267
+ let fenceChar = "";
1268
+ let spanStart = 0;
1269
+ let offset = 0;
1270
+ for (const line of content.split("\n")) {
1271
+ const lineEnd = offset + line.length + 1; // +1 for the split-consumed \n
1272
+ const fence = FENCE_LINE_RE.exec(line);
1273
+ if (fence) {
1274
+ if (!inFence) {
1275
+ inFence = true;
1276
+ fenceLen = fence[1].length;
1277
+ fenceChar = fence[1][0];
1278
+ spanStart = offset;
1279
+ } else if (closesFence(line, fence, fenceChar, fenceLen)) {
1280
+ inFence = false;
1281
+ fenceLen = 0;
1282
+ fenceChar = "";
1283
+ spans.push([spanStart, lineEnd]);
1284
+ }
1285
+ }
1286
+ offset = lineEnd;
1287
+ }
1288
+ if (inFence) spans.push([spanStart, offset]);
1289
+ return spans;
1290
+ };
1291
+
1292
+ /** Example-path namespaces the skill prompts use in illustrative citations
1293
+ * (`path/to/file.ext:12`, `packages/x/y.ts:42`). Artifacts quote — and models
1294
+ * imitate — these examples in unfenced prose, where the fence skip cannot
1295
+ * reach them; a citation under one of these prefixes is documentation shape,
1296
+ * never a claim about the tree, and prosecuting one buys a full LLM fix round
1297
+ * for zero risk averted (three of f329's floor failures were this class). */
1298
+ const PLACEHOLDER_CITATION_PREFIXES: readonly string[] = ["path/to/", "packages/x/"];
1299
+
965
1300
  const verifyCitations = (body: string, cwd: string): { detail: string; where: string }[] => {
966
1301
  const findings: { detail: string; where: string }[] = [];
967
1302
  const seen = new Set<string>();
1303
+ // Fenced text is example/fixture territory, not prose asserting a real
1304
+ // file:line — a fenced placeholder shaped like a citation must not fail the
1305
+ // floor (it false-failed the very plan that fixes this). Span check, not a
1306
+ // placeholder-pattern skip: a REAL citation that merely looks placeholder-ish
1307
+ // still verifies when it appears in prose.
1308
+ const fenced = fencedSpans(body);
968
1309
  // Built lazily and reused across citations — only the first direct-resolution
969
1310
  // 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
- };
1311
+ const indexHolder: { value: BasenameIndex | undefined } = { value: undefined };
991
1312
  for (const m of body.matchAll(FILE_LINE_CITATION_RE)) {
992
1313
  const [, path, startStr, endStr] = m;
993
1314
  if (!path || !startStr) continue;
1315
+ if (fenced.some(([s, e]) => m.index >= s && m.index < e)) continue;
1316
+ if (PLACEHOLDER_CITATION_PREFIXES.some((p) => path.startsWith(p))) continue;
994
1317
  const key = `${path}:${startStr}${endStr ? `-${endStr}` : ""}`;
995
1318
  if (seen.has(key)) continue;
996
1319
  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
- }
1320
+ const resolved = resolveCitationPath(path, cwd, indexHolder);
1321
+ if (resolved && "ambiguous" in resolved) {
1322
+ // More than one tree file matches — name the candidates so the fix arm can disambiguate.
1323
+ const shown = resolved.ambiguous
1324
+ .slice(0, 3)
1325
+ .map((a) => (a.startsWith(cwd + sep) ? a.slice(cwd.length + 1) : a));
1326
+ findings.push({
1327
+ detail: `Unbacked citation ${key} — ${path} matches ${resolved.ambiguous.length} tree files (${shown.join(", ")}${resolved.ambiguous.length > shown.length ? ", …" : ""}); a citation must name ONE file. Disambiguate with the repo-root-relative path.`,
1328
+ where: key,
1329
+ });
1330
+ continue;
1014
1331
  }
1332
+ const abs = resolved?.abs;
1015
1333
  if (!abs) {
1016
1334
  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.`,
1335
+ 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 node_modules/<pkg>/… for an installed dependency file) or drop the citation.`,
1018
1336
  where: key,
1019
1337
  });
1020
1338
  continue;
@@ -1042,6 +1360,148 @@ const verifyCitations = (body: string, cwd: string): { detail: string; where: st
1042
1360
  return findings;
1043
1361
  };
1044
1362
 
1363
+ /** A structure-dimension finding — the shared shape the deterministic verdict
1364
+ * checks emit (`detail` is the actionable message, `where` locates the defect). */
1365
+ type StructureFinding = { detail: string; where: string };
1366
+
1367
+ /** A dispatched sub-plan basename with its `_cluster-<k>` ordinal resolved. */
1368
+ type DispatchedCluster = { path: string; k: number };
1369
+
1370
+ /** An `fs` artifact handle (the only handle kind the verdict checks operate on). */
1371
+ type FsHandle = { kind: "fs"; path: string };
1372
+
1373
+ /**
1374
+ * Write the shared `{ dimension: "structure" }` verdict and publish it on an fs
1375
+ * artifact. The three deterministic structure checks (`sliceStructureCheck`,
1376
+ * `subplanCoverageCheck`, `planCitationCheck`) all emit the SAME verdict shape
1377
+ * and basename-keyed JSON write, so it lives here once. `who` is the channel
1378
+ * prefix folded into the basename (so a re-run OVERWRITES its own slot —
1379
+ * idempotent across fix/reslice/re-dispatch rounds); `handle` is the artifact
1380
+ * the check inspected (serialized into `data.artifact` and basename-keyed).
1381
+ *
1382
+ * The `severity: pass ? "none" : "high"` floor is load-bearing: the gate routes
1383
+ * via `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently
1384
+ * passes a `pass:false` verdict rated `low`/`none`; a structural defect MUST
1385
+ * rate `high` or it ships. The `score` is the binary verdict scale (100 = clean,
1386
+ * 0 = finding; the gate keys off `severity`, never this number).
1387
+ *
1388
+ * `extra` lets a caller stamp additional gate-readable fields onto the verdict
1389
+ * data (and the persisted JSON, so the trail records them) — currently only
1390
+ * `sliceStructureCheck`'s `citeDischarged` stamp.
1391
+ */
1392
+ const writeStructureVerdict = (
1393
+ who: string,
1394
+ handle: FsHandle,
1395
+ findings: StructureFinding[],
1396
+ cwd: string,
1397
+ extra?: Record<string, unknown>,
1398
+ ): Omit<Output, "meta"> => {
1399
+ const pass = findings.length === 0;
1400
+ const data = {
1401
+ dimension: "structure",
1402
+ pass,
1403
+ score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
1404
+ severity: pass ? "none" : "high",
1405
+ artifact: handleToString(handle),
1406
+ findings,
1407
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
1408
+ ...extra,
1409
+ };
1410
+ const rel = join(VERDICT_DIR, `${who}__${basename(handle.path, ".md")}.json`);
1411
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
1412
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
1413
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
1414
+ };
1415
+
1416
+ /**
1417
+ * A citation string occurs LIVE in the slice-map text — outside fenced spans
1418
+ * and not as half of an `old→new` refresh-note pair. A re-slice's revision
1419
+ * note legitimately QUOTES the citations it refreshed (contract: only as
1420
+ * arrow pairs or inside a fence — see the slice skill's re-slice mode);
1421
+ * treating a quoted old citation as still-live would forfeit every documented
1422
+ * refresh's discharge, and treating a quoted new one as present would credit
1423
+ * a fix that never touched the live `Draws on` lines.
1424
+ */
1425
+ const citeOccursLive = (body: string, spans: readonly [number, number][], cite: string): boolean => {
1426
+ for (let i = body.indexOf(cite); i !== -1; i = body.indexOf(cite, i + 1)) {
1427
+ if (spans.some(([s, e]) => i >= s && i < e)) continue;
1428
+ if (body.startsWith("→", i + cite.length)) continue;
1429
+ if (body.endsWith("→", i)) continue;
1430
+ return true;
1431
+ }
1432
+ return false;
1433
+ };
1434
+
1435
+ /**
1436
+ * One cite-remedy finding is satisfied by the slice-map text: the demanded
1437
+ * seed's path occurs live — line suffixes are stripped before matching,
1438
+ * because the fix may cite a corrected range and the citation floor
1439
+ * (`verifyCitations`) verifies whatever range it actually wrote. `Draws on`
1440
+ * and `Out of scope` both satisfy the remedy, so a live occurrence anywhere
1441
+ * in the map is the contract. (The former REFRESH mode — a `stale` drifted
1442
+ * line number to replace — was removed with anchor-precision grading: a
1443
+ * drifted line number is no longer a finding, so nothing demands a refresh.)
1444
+ *
1445
+ * A finding without a concrete string `requires` is unverifiable ⇒ not satisfied.
1446
+ */
1447
+ const citeFindingSatisfied = (
1448
+ mapBody: string,
1449
+ spans: readonly [number, number][],
1450
+ f: { requires?: unknown },
1451
+ ): boolean =>
1452
+ typeof f.requires === "string" &&
1453
+ f.requires.length > 0 &&
1454
+ citeOccursLive(mapBody, spans, f.requires.replace(/:\d[-\d,:]*$/, ""));
1455
+
1456
+ /**
1457
+ * Structural fingerprint of one slice-map round: the `slices` + `coverage`
1458
+ * frontmatter it published on the `slices` channel — no file re-read.
1459
+ * `undefined` when the round carried no `slices` data; a caller must treat
1460
+ * that as "cannot compare", never as "unchanged".
1461
+ */
1462
+ const sliceShape = (round: Output | undefined): string | undefined => {
1463
+ const d = round?.data as { slices?: unknown; coverage?: unknown } | undefined;
1464
+ return d?.slices === undefined ? undefined : JSON.stringify({ slices: d.slices, coverage: d.coverage ?? null });
1465
+ };
1466
+
1467
+ /** The verdict fields the cite-only discharge consults. */
1468
+ type CiteRemedyVerdict = {
1469
+ pass?: boolean;
1470
+ remedy?: string;
1471
+ findings?: readonly { requires?: unknown }[];
1472
+ };
1473
+
1474
+ /**
1475
+ * Deterministic discharge of a CITE-ONLY `design-readiness` fail — the middle
1476
+ * case between "carry a passing verdict" (impossible on the slice gate: its
1477
+ * lone dimension failed) and "buy a full re-grade panel" (wasteful when the
1478
+ * grader already named the exact citations to add or refresh). A fix that
1479
+ * also restructured forfeits the discharge and takes the normal re-grade.
1480
+ */
1481
+ const citeRemedyDischarged = (state: RunView, mapBody: string): boolean => {
1482
+ const verdict = latestVerdictPerDimension(state.named["slice-verdicts"]).get("design-readiness");
1483
+ const v = verdict?.data as CiteRemedyVerdict | undefined;
1484
+ if (v?.pass !== false || v.remedy !== "cite") return false;
1485
+ // A fix must have LANDED since the verdict — discharging the judged map
1486
+ // unchanged would contradict the grader, who read it and found the cites
1487
+ // wrong. Basename inequality cannot witness the fix (a re-slice may
1488
+ // legitimately edit the map in place); publication order can: the latest
1489
+ // `slices` round must postdate the verdict.
1490
+ const entries = state.named.slices ?? [];
1491
+ const verdictTs = verdict?.meta?.ts;
1492
+ const currentTs = entries.at(-1)?.meta?.ts;
1493
+ if (typeof verdictTs !== "string" || typeof currentTs !== "string" || currentTs <= verdictTs) return false;
1494
+ const findings = Array.isArray(v.findings) ? v.findings : [];
1495
+ if (findings.length === 0) return false;
1496
+ const spans = fencedSpans(mapBody);
1497
+ if (!findings.every((f) => f != null && citeFindingSatisfied(mapBody, spans, f))) return false;
1498
+ // Shape must match the round the grader judged — located by publication
1499
+ // order, not filename, for the same in-place reason.
1500
+ const judged = [...entries].reverse().find((s) => typeof s.meta?.ts === "string" && s.meta.ts <= verdictTs);
1501
+ const judgedShape = sliceShape(judged);
1502
+ return judgedShape !== undefined && judgedShape === sliceShape(entries.at(-1));
1503
+ };
1504
+
1045
1505
  /**
1046
1506
  * Deterministic Phase-1 slice-check — the un-gameable floor beneath the LLM
1047
1507
  * `design-readiness` panel. It enforces the invariants a prose grader cannot
@@ -1105,69 +1565,948 @@ const sliceStructureCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"
1105
1565
  // Citation backing — every file:line the map cites must resolve.
1106
1566
  findings.push(...verifyCitations(mapBody, cwd));
1107
1567
 
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
- };
1568
+ // Stamp the cite-only discharge ONLY on a green floor: structure clean +
1569
+ // citation backing verified + demanded seeds present + shape unchanged is
1570
+ // exactly what a fresh design-readiness pass on this map would re-establish,
1571
+ // so the `sliceGatePasses` skip stays provably equivalent to "re-grade, then pass".
1572
+ const discharge =
1573
+ findings.length === 0 && citeRemedyDischarged(state, mapBody)
1574
+ ? { citeDischarged: basename(latest.handle.path) }
1575
+ : undefined;
1576
+ return writeStructureVerdict("slice-check", latest.handle, findings, cwd, discharge);
1129
1577
  };
1130
1578
 
1131
1579
  /**
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.
1580
+ * `_<k>` cluster ordinal a partial sub-plan carries in its basename
1581
+ * (`<slug>_cluster-<k>.md`), emitted by `synthesize`'s partial mode from the
1582
+ * `--cluster <k>` the fanout threads on every cluster unit. The token a
1583
+ * `subplan-check` reconciliation keys dispatched sub-plans on. Anchored to the
1584
+ * basename TAIL (extension optional — extensionless agent writes happen, see
1585
+ * the implement-scope floor precedent) so a name carrying several `_cluster-`
1586
+ * tokens binds the trailing one deterministically, not the first match.
1141
1587
  */
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
- );
1588
+ const CLUSTER_TOKEN_RE = /_cluster-(\d+)(?:\.\w+)?$/;
1589
+
1590
+ /** The pre-filter cluster count the fanout received — the count
1591
+ * `subplanCoverageCheck` reconciles dispatched ordinals against. Delegates to
1592
+ * `clusterSliceDag`. */
1593
+ const expectedClusterCount = (records: readonly PhaseRecord[]): number => clusterSliceDag(records).length;
1594
+
1595
+ /** Slice numbers that have NO design artifact on the `designs` channel — the gap
1596
+ * the missing-design preflight halts on (a slice with no design is unrepairable
1597
+ * by re-dispatch). */
1598
+ const designCoverageGap = (sliceNumbers: Set<number>, designBySlice: Map<number, string>): number[] =>
1599
+ [...sliceNumbers].filter((n) => !designBySlice.has(n)).sort((a, b) => a - b);
1600
+
1601
+ /** Collect every dispatched sub-plan's `_cluster-<k>` ordinal from the `subplans`
1602
+ * channel. The `subplans` slot is a produces-fanout channel: `placeFanoutOutput`
1603
+ * pre-sizes it to the round's unit total and overwrites each unit's own index, so
1604
+ * with a stable unit set iterating it reflects the latest output per unit — a
1605
+ * re-dispatch's fresh artifacts re-evaluate cleanly. (A unit that FAILS on
1606
+ * re-dispatch leaves its prior-round output at its index; that stale entry
1607
+ * re-reads as current here.) Returns the resolved ordinals AND a `tokenless`
1608
+ * finding per basename that carries no `_cluster-<k>` token (the root merge
1609
+ * cannot attribute a tokenless sub-plan to a slice-DAG cluster). */
1610
+ const dispatchedClusterOrdinals = (
1611
+ state: RunView,
1612
+ ): { dispatched: DispatchedCluster[]; tokenless: StructureFinding[] } => {
1613
+ const dispatched: DispatchedCluster[] = [];
1614
+ const tokenless: StructureFinding[] = [];
1615
+ for (const out of state.named.subplans ?? []) {
1616
+ for (const a of out.artifacts) {
1617
+ if (a.handle.kind !== "fs") continue;
1618
+ const name = basename(a.handle.path);
1619
+ const m = CLUSTER_TOKEN_RE.exec(name);
1620
+ if (!m) {
1621
+ tokenless.push({
1622
+ detail: `Tokenless sub-plan basename ${name} — it carries no '_cluster-<k>' ordinal, so the root merge cannot attribute it to a slice-DAG cluster. The cluster fanout threads '--cluster <k>' on every unit; a tokenless name means 'synthesize' dropped the flag. Re-dispatch the cluster with its '--cluster <k>' honored in the output filename.`,
1623
+ where: name,
1624
+ });
1625
+ continue;
1626
+ }
1627
+ dispatched.push({ path: handleToString(a.handle), k: Number(m[1]) });
1628
+ }
1629
+ }
1630
+ return { dispatched, tokenless };
1631
+ };
1632
+
1633
+ /** A finding per `_cluster-<k>` ordinal claimed by MORE THAN ONE dispatched
1634
+ * sub-plan — a clobber (not a legitimate re-emit: within one round every unit
1635
+ * index is a distinct artifact because the channel is replaced each round, so a
1636
+ * shared `<k>` is the lost-cluster collision itself). */
1637
+ const clobberedOrdinals = (dispatched: readonly DispatchedCluster[]): StructureFinding[] => {
1638
+ const pathsByK = new Map<number, string[]>();
1639
+ for (const d of dispatched) {
1640
+ const arr = pathsByK.get(d.k);
1641
+ if (arr) arr.push(d.path);
1642
+ else pathsByK.set(d.k, [d.path]);
1643
+ }
1644
+ const findings: StructureFinding[] = [];
1645
+ for (const [k, paths] of pathsByK) {
1646
+ if (paths.length > 1) {
1647
+ findings.push({
1648
+ detail: `Duplicate/clobbered cluster-${k} — ${paths.length} dispatched sub-plans claim the same '_cluster-${k}' ordinal (${paths.map((p) => basename(p)).join(", ")}). Two clusters collided on one filename token, so the root merge would fold one cluster's content over the other and lose a slice-DAG component. Re-dispatch with each cluster's '--cluster <k>' distinct.`,
1649
+ where: `cluster-${k}`,
1650
+ });
1651
+ }
1652
+ }
1653
+ return findings;
1654
+ };
1655
+
1656
+ /** sources-coverage — every slice's design must appear in SOME sub-plan's
1657
+ * `sources:`. Reads the covered-slice set off each sub-plan's parsed `sources:`
1658
+ * (designs follow the `_slice-<N>` convention) and reconciles it against the full
1659
+ * slice map. A sub-plan whose frontmatter does not PARSE gets its own
1660
+ * re-dispatchable finding naming the FILE (never a terminal halt — the same
1661
+ * stray-colon class `artifact-collector` degrades on); when ANY sub-plan is
1662
+ * unparseable, the per-slice reconciliation DEFERS (an unreadable sub-plan's
1663
+ * coverage is unknowable; blaming its slices would misdirect the repair). */
1664
+ const sourcesCoverageGaps = (state: RunView, cwd: string, sliceNumbers: Set<number>): StructureFinding[] => {
1665
+ const findings: StructureFinding[] = [];
1666
+ const coveredSlices = new Set<number>();
1667
+ let unparseable = false;
1668
+ for (const out of state.named.subplans ?? []) {
1669
+ for (const a of out.artifacts) {
1670
+ if (a.handle.kind !== "fs") continue;
1671
+ let frontmatter: unknown;
1672
+ try {
1673
+ ({ frontmatter } = parseFrontmatter(readArtifactFile(handleToString(a.handle), cwd)));
1674
+ } catch {
1675
+ unparseable = true;
1676
+ findings.push({
1677
+ detail: `Unparseable frontmatter in sub-plan ${basename(a.handle.path)} — its YAML frontmatter does not parse (typically a bare ': ' inside an unquoted scalar), so its 'sources:' coverage cannot be read. Re-dispatch the cluster and re-write the sub-plan with parseable frontmatter listing every '--designs' path in 'sources:'.`,
1678
+ where: basename(a.handle.path),
1679
+ });
1680
+ continue;
1681
+ }
1682
+ const fm = frontmatter && typeof frontmatter === "object" ? (frontmatter as Record<string, unknown>) : {};
1683
+ const sources = fm.sources;
1684
+ if (!Array.isArray(sources)) continue;
1685
+ for (const s of sources) {
1686
+ if (typeof s !== "string") continue;
1687
+ const sm = DESIGN_SLICE_RE.exec(s);
1688
+ if (sm) coveredSlices.add(Number(sm[1]));
1689
+ }
1690
+ }
1691
+ }
1692
+ if (!unparseable) {
1693
+ for (const n of [...sliceNumbers].sort((a, b) => a - b)) {
1694
+ if (!coveredSlices.has(n)) {
1695
+ findings.push({
1696
+ detail: `Slice ${n} design absent from every sub-plan's 'sources:' — the cluster fanout threads each '--designs <path>' and 'synthesize' echoes them into 'sources:'; a slice whose design no sub-plan lists is one the root merge would silently drop. List every '--designs' path in its sub-plan's 'sources:'.`,
1697
+ where: `sources: slice ${n}`,
1698
+ });
1699
+ }
1700
+ }
1701
+ }
1702
+ return findings;
1703
+ };
1704
+
1705
+ /**
1706
+ * Deterministic subplan cluster-coverage floor — the structural backstop between
1707
+ * the cluster fanout and the root merge. After `subplan` fans each slice-DAG
1708
+ * cluster out to a partial sub-plan, this reconciles what was DISPATCHED against
1709
+ * what the slice map PROMISED, before the root `plan` merge fans them in:
1710
+ * • cluster-count conservation — the PRE-FILTER cluster count
1711
+ * (`clusterSliceDag(sliceRecords(latest slices)).length`) must equal the
1712
+ * number of distinct `_cluster-<k>` ordinals the fanout emitted. A re-dispatch
1713
+ * that re-clobbered an ordinal (the pre-fix clobber bug — two clusters
1714
+ * sharing `<k>`, or a tokenless basename) collapses the distinct count,
1715
+ * surfacing as a missing cluster here.
1716
+ * • token conformance — every dispatched sub-plan basename MUST carry a
1717
+ * `_cluster-<k>` token; a tokenless name means `synthesize` dropped the
1718
+ * `--cluster <k>` flag and the merge can't attribute it to a cluster.
1719
+ * • duplicate/clobbered ordinal — two dispatched sub-plans sharing the same
1720
+ * `<k>` (a clobber, not a legitimate re-emit: `placeFanoutOutput` overwrites
1721
+ * each unit's own index in the channel slot, so within one round every unit
1722
+ * index is a distinct artifact — a shared `<k>` is a real collision, the
1723
+ * lost-cluster bug itself).
1724
+ * • sources-coverage — every slice's design must appear in SOME sub-plan's
1725
+ * `sources:` (the fanout threads each `--designs <path>` and `synthesize`
1726
+ * echoes them into `sources:`). Designs follow the `_slice-<N>` convention, so
1727
+ * the covered slice set is read off `sources:` and reconciled against the full
1728
+ * slice map; a slice whose design no sub-plan lists is a slice the merge would
1729
+ * silently drop. A sub-plan whose frontmatter does not PARSE gets its own
1730
+ * re-dispatchable finding naming the FILE (never a `FAIL_SCRIPT_THREW` halt —
1731
+ * the same stray-colon class `artifact-collector` degrades on), and the
1732
+ * per-slice reconciliation defers until every sub-plan parses, so a parse
1733
+ * failure is never mis-blamed on the slices it happened to cover.
1734
+ * Preflight: a slice with NO design on the `designs` channel halts LOUD before
1735
+ * any reconciliation — the fanout drops (or under-feeds) its cluster pre-dispatch
1736
+ * (`if (!designs.length) return undefined`), so re-dispatching `subplan` re-drops
1737
+ * it every round until `maxBackwardJumps` exhausts with a diagnostic naming the
1738
+ * refused re-entry instead of the cause. The missing design is upstream
1739
+ * (`slice-design`/`design-review`) and unreachable from this loop's backward
1740
+ * edge; halting here names the actual defect and spends no jump budget.
1741
+ * Emits `severity: pass ? "none" : "high"` (load-bearing — the route routes via
1742
+ * `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently passes a
1743
+ * `pass:false` verdict rated `low`/`none`; a lost cluster MUST rate `high` or it
1744
+ * ships). Deliberately NOT the `match("verdict", …)` STOP idiom
1745
+ * `implementScopeCheck` uses — a lost cluster IS repairable by re-dispatch, so the
1746
+ * floor routes the backward edge to `subplan`, bounded by `maxBackwardJumps`.
1747
+ * Deterministic ⇒ idempotent across re-dispatch rounds: the verdict basename is
1748
+ * keyed on the slice-map basename, so a re-run OVERWRITES its own slot.
1749
+ */
1750
+ const subplanCoverageCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1751
+ const latestSliceMap = latestFsArtifact(state, "slices");
1752
+ if (latestSliceMap?.handle.kind !== "fs") {
1753
+ throw haltPreflight(
1754
+ "subplan-check",
1755
+ "subplan-check: no slice map to reconcile against",
1756
+ "subplan-check: no fs artifact on the 'slices' channel — slice must run before the subplan coverage check",
1757
+ );
1758
+ }
1759
+ const mapBody = readArtifactFile(latestSliceMap.handle.path, cwd);
1760
+ const records = sliceRecords(mapBody, "subplan-check", latestSliceMap.handle.path);
1761
+ // PRE-FILTER expected clusters — the count the fanout RECEIVED, not the
1762
+ // post-drop dispatched count. The fanout drops a zero-design cluster
1763
+ // (`if (!designs.length) return undefined` in SYNTH_CLUSTER_FANOUT's units);
1764
+ // design-review catches those upstream, so a healthy run lands here with
1765
+ // pre-filter == dispatched — an invariant the missing-design preflight below
1766
+ // enforces loudly rather than assumes.
1767
+ const expectedK = expectedClusterCount(records);
1768
+ const sliceNumbers = new Set(records.map((r) => r.n));
1769
+
1770
+ // A slice with no design cannot be repaired by the backward edge: the fanout
1771
+ // drops a zero-design cluster pre-dispatch, so every `subplan` re-dispatch
1772
+ // reproduces the identical gap until maxBackwardJumps exhausts blaming the
1773
+ // re-entry. Halt loud at the floor instead, naming the upstream cause.
1774
+ const designBySlice = designPathsBySlice(state);
1775
+ const undesigned = designCoverageGap(sliceNumbers, designBySlice);
1776
+ if (undesigned.length > 0) {
1777
+ throw haltPreflight(
1778
+ "subplan-check",
1779
+ `subplan-check: slice(s) ${undesigned.join(", ")} have no design on the 'designs' channel`,
1780
+ `subplan-check: slice(s) ${undesigned.join(", ")} in the slice map have no design artifact on the 'designs' channel, so the cluster fanout dropped (or under-fed) their cluster(s) before dispatch. Re-dispatching 'subplan' cannot repair this — no sub-plan can list a design that was never produced. The missing design(s) come from upstream ('slice-design' emits, 'design-review' re-emits the accepted docs); investigate why they never reached the 'designs' channel.`,
1781
+ );
1782
+ }
1783
+
1784
+ const { dispatched, tokenless } = dispatchedClusterOrdinals(state);
1785
+ const findings: StructureFinding[] = [...tokenless];
1786
+ findings.push(...clobberedOrdinals(dispatched));
1787
+
1788
+ // Cluster-count conservation — distinct dispatched ordinals vs the pre-filter
1789
+ // expected count. A clobber or a never-dispatched cluster both surface here.
1790
+ const dispatchedK = new Set(dispatched.map((d) => d.k)).size;
1791
+ if (dispatchedK < expectedK) {
1792
+ findings.push({
1793
+ detail: `Missing cluster coverage — the slice map promised ${expectedK} slice-DAG cluster(s) but the fanout dispatched ${dispatchedK} distinct '_cluster-<k>' sub-plan(s). A cluster went undispatched (or two collided on one ordinal — see any duplicate finding above); its slices would be absent from the merged plan. Re-dispatch the missing cluster(s).`,
1794
+ where: `clusters (expected ${expectedK}, dispatched ${dispatchedK})`,
1795
+ });
1796
+ }
1797
+
1798
+ findings.push(...sourcesCoverageGaps(state, cwd, sliceNumbers));
1799
+
1800
+ return writeStructureVerdict("subplan-check", latestSliceMap.handle, findings, cwd);
1801
+ };
1802
+
1803
+ /**
1804
+ * Slice a plan body into per-phase text keyed by phase number, splitting on
1805
+ * `## Phase N:` headings OUTSIDE fenced code blocks (a heading inside a ``` or
1806
+ * ~~~ fence is example/fixture text, not a structural phase boundary — mirrors
1807
+ * `countHeadingsOutsideFences` so the slice and the derive-check agree). The
1808
+ * body for phase N runs from its heading line up to (not including) the next
1809
+ * out-of-fence `## Phase M:` heading, or end-of-text for the last phase.
1810
+ * Returns a `Map<number, string>` (phase n → body text, heading included).
1811
+ */
1812
+ const phaseBodySlices = (content: string): Map<number, string> => {
1813
+ const lineRe = new RegExp(PLAN_PHASE_RE.source); // drop g/m; per-line test, lastIndex can't drift
1814
+ const lines = content.split("\n");
1815
+ const openings: { n: number; start: number }[] = [];
1816
+ forEachLineOutsideFences(content, (line, i) => {
1817
+ const m = lineRe.exec(line);
1818
+ if (m?.[1]) openings.push({ n: Number(m[1]), start: i });
1819
+ });
1820
+ const slices = new Map<number, string>();
1821
+ for (let idx = 0; idx < openings.length; idx++) {
1822
+ const end = idx + 1 < openings.length ? openings[idx + 1].start : lines.length;
1823
+ slices.set(openings[idx].n, lines.slice(openings[idx].start, end).join("\n"));
1824
+ }
1825
+ return slices;
1826
+ };
1827
+
1828
+ /** Strip a trailing `:line` or `:line-line` citation suffix from a path token. */
1829
+ const stripLineSuffix = (p: string): string => p.replace(/:\d+(?:-\d+)?$/, "");
1830
+
1831
+ /** Well-known extensionless filenames — the extension heuristic below would drop
1832
+ * them, so an undeclared write to one would silently escape the coverage floor.
1833
+ * Recognized bare or as the basename of a path. */
1834
+ const EXTENSIONLESS_FILENAME_RE =
1835
+ /^(?:Makefile|Dockerfile|Rakefile|Gemfile|Justfile|Procfile|LICENSE|NOTICE|CODEOWNERS)$/;
1836
+
1837
+ /** Path-like test mirroring slice-overlap.mjs's `looksLikePath`, applied AFTER
1838
+ * stripping a `:line` suffix (the blueprint MODIFY heading — `#### N. path/to/file.ext`
1839
+ * with a `:12-30` range appended — carries a line range the bare form rejects).
1840
+ * Extensionless recognition is allowlist-only (never "any `/`-bearing token"):
1841
+ * prose like `and/or` must not read as a declared write. */
1842
+ const isPathLike = (s: string): boolean => {
1843
+ if (/\s/.test(s)) return false;
1844
+ if (EXTENSIONLESS_FILENAME_RE.test(s.slice(s.lastIndexOf("/") + 1))) return true;
1845
+ return /\.[A-Za-z0-9]+$/.test(s) && (s.includes("/") || /^[\w.-]+\.[A-Za-z0-9]+$/.test(s));
1846
+ };
1847
+
1848
+ /**
1849
+ * Extract the edit paths a phase body names, across the three artifact
1850
+ * conventions the plan/blueprint/synthesize skills emit, OUTSIDE fenced code
1851
+ * blocks (a path inside a ``` fence is a code reference, not a declared write —
1852
+ * post-`code-splice` safety, since code-splice folds elaborations' fenced code
1853
+ * into the plan and those fenced paths must NOT read as phase writes):
1854
+ * • `**File**:` / `**Files**:` — plan/blueprint's per-change file line
1855
+ * (a backticked comma-list under `**Files**:`, or a single path under `**File**:`).
1856
+ * • `#### N. path/to/file.ext` — blueprint's change subsection heading
1857
+ * (may carry a `:line`-range suffix on MODIFY entries — stripped).
1858
+ * • `- `path/to/file.ts`` — synthesize's backticked-path list item under
1859
+ * `### Changes` (the form `elaborate`/`synthesize` emit).
1860
+ * Strips a trailing `:line`/`:line-line` suffix. Mirrors slice-overlap.mjs's
1861
+ * `filesOf` + `looksLikePath` and extends them with the synthesize list-item
1862
+ * form. Returns a de-duplicated `string[]`.
1863
+ */
1864
+ const editPathsOfPhase = (phaseBody: string): string[] => {
1865
+ const files = new Set<string>();
1866
+ const add = (raw: string) => {
1867
+ const stripped = stripLineSuffix(raw.replace(/[`*]/g, "").trim());
1868
+ if (stripped && isPathLike(stripped)) files.add(stripped);
1869
+ };
1870
+ forEachLineOutsideFences(phaseBody, (line) => {
1871
+ const fm = line.match(/^\*\*Files?\*\*:\s*(.+)$/);
1872
+ if (fm) {
1873
+ for (const tok of fm[1].split(/[,\s]+/)) add(tok);
1874
+ return;
1875
+ }
1876
+ const hm = line.match(/^#{3,4}\s+\d+\.\s+(\S+)/);
1877
+ if (hm) {
1878
+ add(hm[1]);
1879
+ return;
1880
+ }
1881
+ const lm = line.match(/^-\s+`([^`]+)`/);
1882
+ if (lm) add(lm[1]);
1883
+ });
1884
+ return [...files];
1885
+ };
1886
+
1887
+ /**
1888
+ * Deterministic plan-time coverage floor: every edit path a phase body NAMES
1889
+ * (in `### Changes`/`#### N. path`/`**File**:`) must be DECLARED in that phase's
1890
+ * frontmatter `files:` array. An undeclared write is the per-phase attribution
1891
+ * gap the dep-gated implement fanout and the lane-level scope floor both need
1892
+ * closed upstream — a body edit not in `files:` is invisible to dependency
1893
+ * derivation and unattributable under concurrency. PURE: no LLM judgment, never
1894
+ * throws (a malformed frontmatter degrades to `[]`). A `files:`-LESS phase
1895
+ * (absent key) yields NO findings — empty-set degradation so a legacy/
1896
+ * `files:`-less plan never false-fails; a phase that declares `files: []` is
1897
+ * checked (every body edit is a gap). Folded into `planCitationCheck(who)` so
1898
+ * both the `plan-cite-check` and `code-cite-check` arms emit coverage findings
1899
+ * on their shared `dimension: "structure"` verdict — no new stage/channel/route.
1900
+ */
1901
+ const verifyPhaseFilesCoverage = (content: string, who: string, path: string): { detail: string; where: string }[] => {
1902
+ let fm: Record<string, unknown>;
1903
+ try {
1904
+ const { frontmatter } = parseFrontmatter(content);
1905
+ fm = frontmatter as Record<string, unknown>;
1906
+ } catch {
1907
+ return []; // malformed frontmatter → degrade to no findings, never throw
1908
+ }
1909
+ const phases = Array.isArray(fm.phases) ? fm.phases : [];
1910
+ const entryByN = new Map<number, Record<string, unknown>>();
1911
+ phases.forEach((entry, idx) => {
1912
+ const e = (entry ?? {}) as Record<string, unknown>;
1913
+ const n = typeof e.n === "number" ? e.n : idx + 1;
1914
+ entryByN.set(n, e);
1915
+ });
1916
+ const findings: { detail: string; where: string }[] = [];
1917
+ for (const [n, body] of phaseBodySlices(content)) {
1918
+ const entry = entryByN.get(n);
1919
+ if (!entry) continue; // body phase with no matching frontmatter entry — derive-check's concern, not coverage's
1920
+ // `files:` key ABSENT → degradation (legacy plan): skip. Present (even `[]`) → check.
1921
+ if (!Array.isArray(entry.files)) continue;
1922
+ const declared = new Set(phaseFiles(entry));
1923
+ for (const editPath of editPathsOfPhase(body)) {
1924
+ if (declared.has(editPath)) continue;
1925
+ findings.push({
1926
+ 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.`,
1927
+ where: `${who} ${path} phase ${n}: ${editPath}`,
1928
+ });
1929
+ }
1930
+ }
1931
+ return findings;
1932
+ };
1933
+
1934
+ /**
1935
+ * Deterministic citation floor for a synthesized/spliced plan — the plan-scope
1936
+ * twin of `sliceStructureCheck`'s citation backing, extending the citation
1937
+ * floor past the slice map to the plan and the code-bearing plan (a fabricated `file:line` in
1938
+ * the plan misdirects `implement`). Verifies every
1939
+ * citation resolves against the working tree and emits a `{ dimension:
1940
+ * "structure" }` verdict on `who`'s channel that the gate route folds via
1941
+ * `allDimensionsPass`; the matching `<fix>` stage reads `fanin(who)` so the
1942
+ * findings DRIVE the amend rather than blind-halt. Reuses `verifyCitations` — no
1943
+ * fuzzy wrong-symbol heuristic. Basename-keyed ⇒ idempotent across fix rounds.
1944
+ */
1945
+ const planCitationCheck =
1946
+ (who: string) =>
1947
+ ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1948
+ const latest = latestFsArtifact(state, "plans");
1949
+ if (latest?.handle.kind !== "fs") {
1950
+ throw haltPreflight(
1951
+ who,
1952
+ `${who}: no plan to check`,
1953
+ `${who}: no fs artifact on the 'plans' channel — the plan must be produced before the citation check`,
1954
+ );
1152
1955
  }
1153
1956
  const body = readArtifactFile(latest.handle.path, cwd);
1154
1957
  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(" "),
1958
+ // Plan-time coverage floor: a body edit not declared in its phase's `files:`
1959
+ // fails structurally, same channel/verdict/route as an unbacked citation.
1960
+ findings.push(...verifyPhaseFilesCoverage(body, who, latest.handle.path));
1961
+ return writeStructureVerdict(who, latest.handle, findings, cwd);
1962
+ };
1963
+
1964
+ /**
1965
+ * Copy the latest graded plan off `plans` into `.rpiv/artifacts/priors/`
1966
+ * basename-keyed, publishing the bytes on the snapshot stage's OWN channel with
1967
+ * role `prior` — one deterministic hop BEFORE the matching fix stage inside the
1968
+ * existing fix loop (plan-grade/plan-confirm → plan-snapshot → plan-fix; code
1969
+ * twin). Overwritten each fix round, so the prior always reflects the
1970
+ * pre-CURRENT-fix content; the re-grade reads it via `latestPriorContent` to
1971
+ * decide whether the amend was surgical. `who` attributes the halt when no plan
1972
+ * is published. `kind: "artifact-md"` is the honest kind — the prior IS a copy
1973
+ * of an artifact-md plan body (the kind plans carry under `rpivBucketOutcome`).
1974
+ */
1975
+ const snapshotLatestPlan =
1976
+ (who: string) =>
1977
+ ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1978
+ const latest = latestFsArtifact(state, "plans");
1979
+ if (latest?.handle.kind !== "fs") {
1980
+ throw haltPreflight(
1981
+ who,
1982
+ `${who}: no plan to snapshot`,
1983
+ `${who}: no fs artifact on the 'plans' channel — the plan must be graded before the snapshot stage`,
1984
+ );
1985
+ }
1986
+ const src = isAbsolute(latest.handle.path) ? latest.handle.path : join(cwd, latest.handle.path);
1987
+ const priorRel = join(PRIOR_DIR, basename(latest.handle.path));
1988
+ mkdirSync(join(cwd, PRIOR_DIR), { recursive: true });
1989
+ copyFileSync(src, join(cwd, priorRel));
1990
+ return {
1991
+ kind: "artifact-md",
1992
+ artifacts: [{ handle: { kind: "fs", path: priorRel }, role: "prior" }],
1993
+ data: { snapshot_of: handleToString(latest.handle) },
1164
1994
  };
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
1995
  };
1170
1996
 
1997
+ /** Snapshot the graded plan before `plan-fix` amends it (plan gate). */
1998
+ const planSnapshot = snapshotLatestPlan("plan-snapshot");
1999
+ /** Snapshot the graded plan before `code-fix` amends it (code gate). */
2000
+ const codeSnapshot = snapshotLatestPlan("code-snapshot");
2001
+
2002
+ /**
2003
+ * A duty demotion stamped onto a verdict's on-disk JSON — the legible record
2004
+ * that a risk ruling the panel marked `pass: true` was demoted to effective-
2005
+ * fail by the evidence or verify-at-implement duty. One entry per FAILING
2006
+ * duty (a ruling authored as BOTH mechanics AND verify-at-implement can carry
2007
+ * two). `reason` is decision-code-free prose (no run/phase ids, no absolute
2008
+ * line numbers) naming the duty that failed, so disk readers (amend, confirm
2009
+ * `--prior`) can tell a grader-side demotion from a genuine `pass: false`.
2010
+ */
2011
+ interface RiskDutyDemotion {
2012
+ id: string;
2013
+ duty: "evidence-format" | "procedure-owner";
2014
+ reason: string;
2015
+ }
2016
+
2017
+ /**
2018
+ * Materialize the duty demotion as legible on-disk data. After a grade round,
2019
+ * each latest-per-dimension verdict whose `pass: true` rulings were demoted by
2020
+ * the evidence or verify-at-implement duty gets a `risk_duty_demotions` array
2021
+ * written onto its on-disk JSON IN PLACE — the one medium amend and confirm's
2022
+ * `--prior` read. The verdict's own `pass` is NEVER flipped (every gate fold —
2023
+ * `allRiskFlagsPass`/`dimensionsToRegrade`/`confirmDue` — consults
2024
+ * `rulingEffectivePass` off in-memory `state.named`, which never re-reads the
2025
+ * rewritten file, so gate outcomes are unchanged); the field is an additive,
2026
+ * read-only signal for the disk readers.
2027
+ *
2028
+ * Modeled on `snapshotLatestPlan(who)` (a `ScriptFn` that side-effects AND
2029
+ * returns an `Output`): it reads the PLAN-sourced duty triggers
2030
+ * (`planAuthoredRisks`), iterates the EXACT verdict set amend keeps + confirm
2031
+ * reads (`latestVerdictPerDimension(freshVerdicts(...))`), and rewrites each
2032
+ * demoted verdict's fs handle in place. Writes ONLY when ≥1 demotion (a clean
2033
+ * grade is a no-op — no needless reformat/mtime churn); each per-file
2034
+ * read/parse/write is wrapped so a single unparseable/stale file is skipped
2035
+ * (never halts the gate). Returns `{ demotions }` echoing `{dimension, id,
2036
+ * duty, verdict}` for journal greppability. `channel` is the plan channel the
2037
+ * risks + current artifact live on; `verdictChannel` is the grade's own
2038
+ * verdict channel (plan-verdicts / code-verdicts).
2039
+ */
2040
+ const demoteDuties =
2041
+ (who: string, channel: string, verdictChannel: string) =>
2042
+ ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2043
+ const risks = planAuthoredRisks(state, channel);
2044
+ const current = latestArtifactPath(state, channel);
2045
+ const demotions: { dimension: string; id: string; duty: RiskDutyDemotion["duty"]; verdict: string }[] = [];
2046
+ for (const o of latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel] ?? [], current)).values()) {
2047
+ const handle = o.artifacts.find((a) => a.handle.kind === "fs")?.handle;
2048
+ if (handle?.kind !== "fs") continue;
2049
+ const dimRaw = (o.data as { dimension?: unknown } | undefined)?.dimension;
2050
+ const dimension = typeof dimRaw === "string" ? dimRaw : "";
2051
+ const perFile: RiskDutyDemotion[] = [];
2052
+ for (const r of verdictRiskRulings(o)) {
2053
+ const authored = risks.get(r.id);
2054
+ // Only a `pass: true` ruling that rulingEffectivePass demotes — never a
2055
+ // genuine `pass: false` (that is already a fail, not a demoted pass).
2056
+ if (r.pass !== true || rulingEffectivePass(r, authored)) continue;
2057
+ if (!evidenceCitesFileLine(r, authored)) {
2058
+ perFile.push({
2059
+ id: r.id,
2060
+ duty: "evidence-format",
2061
+ reason: "mechanics pass without an adjacent file:line citation in evidence",
2062
+ });
2063
+ demotions.push({ dimension, id: r.id, duty: "evidence-format", verdict: handleToString(handle) });
2064
+ }
2065
+ if (!procedureSatisfiesDuty(r, authored)) {
2066
+ perFile.push({
2067
+ id: r.id,
2068
+ duty: "procedure-owner",
2069
+ reason: "verify-at-implement pass without a concrete procedure and owner phase",
2070
+ });
2071
+ demotions.push({ dimension, id: r.id, duty: "procedure-owner", verdict: handleToString(handle) });
2072
+ }
2073
+ }
2074
+ if (perFile.length === 0) continue;
2075
+ try {
2076
+ const abs = isAbsolute(handle.path) ? handle.path : join(cwd, handle.path);
2077
+ const json = JSON.parse(readFileSync(abs, "utf-8")) as Record<string, unknown>;
2078
+ json.risk_duty_demotions = perFile;
2079
+ writeFileSync(abs, JSON.stringify(json, null, 2));
2080
+ } catch {
2081
+ // skip-on-throw: an unparseable/stale verdict file never halts the gate.
2082
+ }
2083
+ }
2084
+ return { kind: "json", artifacts: [], data: { demotions, stage: who } };
2085
+ };
2086
+
2087
+ /**
2088
+ * Stamp duty demotions onto the graded plan's verdicts after `plan-grade`, one
2089
+ * deterministic hop before the gate routes (plan-grade → plan-demote → route).
2090
+ * The code lane re-grades `plans` on `code-verdicts` (mirroring `codeSnapshot`).
2091
+ */
2092
+ const planDemote = demoteDuties("plan-demote", "plans", "plan-verdicts");
2093
+ const codeDemote = demoteDuties("code-demote", "plans", "code-verdicts");
2094
+
2095
+ /**
2096
+ * Deterministic lane-level scope floor — the structural backstop beneath the
2097
+ * LLM quality gates. After build's `implement` lane runs (now dep-gated and, as
2098
+ * of this phase's unpin, concurrent up to the host cap), this checks the working
2099
+ * tree's dirty set against the plan's declared write-set (the union of every
2100
+ * phase's `files:`, twin-expanded via `withTestTwins`): any dirty path the run
2101
+ * wrote that is NOT in `declared`, NOT
2102
+ * pre-existing at the run-start baseline, and NOT under a bookkeeping tree is a
2103
+ * scope violation — a phase escaped the upstream write-scope discipline and
2104
+ * rewrote the wider tree, corrupting (or about to corrupt) a concurrent
2105
+ * sibling's in-flight edit. Fail ⇒ STOP (no fix arm): a scope violation is a
2106
+ * plan-vs-tree drift the agent must reconcile manually, not an auto-fix loop.
2107
+ *
2108
+ * Reads the plan with the SAME inline shape `planCitationCheck(who)` uses —
2109
+ * `latestFsArtifact(state,"plans")` + `readArtifactFile` + `planPhaseRecords` +
2110
+ * Phase 1's `phaseFiles` — NOT Phase 2's `readPlanPhaseRecords(state,cwd,who)`,
2111
+ * because this stage needs the plan HANDLE for the `artifact` field and the
2112
+ * basename-keyed verdict path, which the `who`-attributed helper collapses. The
2113
+ * baseline is the run-start snapshot on the `goal` channel (`goalBaselinePath`,
2114
+ * the same reader `VALIDATE_GOAL_PROMPT` and `COMMIT_BASELINE_PROMPT` use); the
2115
+ * dirty set is `git status --porcelain` (non-repo / git-missing ⇒ empty dirty ⇒
2116
+ * pass — the lane degrades to unguarded rather than failing a non-repo run).
2117
+ * Emits one `{ dimension: "scope" }` verdict, basename-keyed off the plan ⇒
2118
+ * idempotent across the build loop.
2119
+ *
2120
+ * `data` carries BOTH a `pass` boolean AND a `verdict` enum ("pass" | "fail")
2121
+ * that always agree (`verdict: pass ? "pass" : "fail"`). The route is the
2122
+ * established `match("verdict", …)` gate idiom (mirrors `validate`'s own route:
2123
+ * `match("verdict", { commit: "pass" }, …)` — no-match ⇒ STOP, the same fail
2124
+ * behavior). It is deliberately NOT the `defineRoute`/`allDimensionsPass`
2125
+ * pattern the citation floors use: `allDimensionsPass` applies a severity floor
2126
+ * (pass === true || severity low/none), so a failing scope check rated low
2127
+ * severity would silently pass the gate — the exact escape class the lane floor
2128
+ * exists to catch. The `from` form suppresses the `READS_DATA` outputSchema lint,
2129
+ * so no schema is declared on the script stage (matching `slice-check`/
2130
+ * `plan-cite-check`).
2131
+ */
2132
+ const implementScopeCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2133
+ const latest = latestFsArtifact(state, "plans");
2134
+ if (latest?.handle.kind !== "fs") {
2135
+ throw haltPreflight(
2136
+ "implement-scope-check",
2137
+ "implement-scope-check: no plan to scope-check",
2138
+ "implement-scope-check: no fs artifact on the 'plans' channel — implement must run before the scope check",
2139
+ );
2140
+ }
2141
+ const body = readArtifactFile(latest.handle.path, cwd);
2142
+ const records = planPhaseRecords(body, "implement-scope-check", latest.handle.path);
2143
+ // Declared write-set = union of every phase's `files:` (via `phaseFiles`),
2144
+ // expanded with co-located test twins (`withTestTwins`) — a signature change
2145
+ // in a declared file legitimately drags its twin's assertions along.
2146
+ // A `files:`-less plan yields `[]` ⇒ `scopeExcess` returns `[]` ⇒ inert floor.
2147
+ const declared = withTestTwins(records.flatMap((r) => phaseFiles(r.entry)));
2148
+
2149
+ // Run-start baseline (goal channel, role "baseline") + current dirty set —
2150
+ // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
2151
+ const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
2152
+ const dirty = gitDirtyPaths(cwd);
2153
+
2154
+ const excess = scopeExcess(dirty, baseline, declared);
2155
+ const findings = excess.map((path) => ({
2156
+ detail: `Undeclared write ${path} — the working tree is dirty outside the plan's declared write-set (the union of every phase's 'files:'). The implement lane runs sibling phases concurrently in one tree, so a phase that wrote outside its 'files:' has stepped on (or is about to step on) a sibling's in-flight edit. Reconcile the phase's 'files:' with what it actually writes, or move the write into the owning phase.`,
2157
+ where: path,
2158
+ }));
2159
+ const pass = findings.length === 0;
2160
+ const data = {
2161
+ dimension: "scope",
2162
+ pass,
2163
+ verdict: pass ? "pass" : "fail",
2164
+ score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2165
+ severity: pass ? "none" : "high",
2166
+ artifact: handleToString(latest.handle),
2167
+ findings,
2168
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2169
+ };
2170
+ // Basename-keyed, NOT round-stamped (unlike grade's timestamped slug): each
2171
+ // fix-loop round overwrites the file. Deliberate — the route reads the
2172
+ // accumulating channel, and on disk only the latest round's scope verdict
2173
+ // matters; round-stamp here if a consumer ever needs the history.
2174
+ const rel = join(VERDICT_DIR, `implement-scope-check__${basename(latest.handle.path, ".md")}.json`);
2175
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2176
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2177
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2178
+ };
2179
+
2180
+ /**
2181
+ * vet's `implement-scope-check` — the loop-aware scope floor (twin of build's
2182
+ * `implementScopeCheck` above). Deterministic (no LLM): the implement lane may
2183
+ * write ONLY the paths a plan phase declares in its `files:` set; any other dirty
2184
+ * path (not in the run-start baseline, not under `.rpiv/`/`thoughts/`) is excess
2185
+ * and halts before `validate`.
2186
+ *
2187
+ * vet differs from build in ONE place: build's extra `plans` entries are
2188
+ * superseding amendments (`plan-fix` re-publishes the whole plan) so build reads
2189
+ * latest-only; vet's review-fix loop pushes a DISTINCT non-superseding fix plan
2190
+ * per iteration (completing a `produces` stage APPENDS to its named slot, and
2191
+ * backward jumps don't reset channels), so this function builds `declared` as the
2192
+ * UNION of Phase 1's `phaseFiles` over the FULL `state.named.plans` history — a
2193
+ * path a prior iteration's plan legitimately wrote is not excess against the
2194
+ * latest plan. The latest plan's handle is used ONLY for the basename-keyed
2195
+ * verdict path (idempotent across fix rounds) and the `artifact` field.
2196
+ *
2197
+ * Otherwise byte-for-byte `implementScopeCheck` above: the baseline via
2198
+ * `goalBaselinePath` (satisfied now that vet has a `goal` stage), the dirty set
2199
+ * via `git status --porcelain` with explicit `stdio`, the shared `scopeExcess`
2200
+ * core + `parseGitStatusPaths`, and the `dimension:"scope"` verdict
2201
+ * (carrying BOTH `pass` and `verdict` — the route is the `match("verdict", …)`
2202
+ * gate idiom, NOT `allDimensionsPass`, so a fail always halts) written to
2203
+ * `VERDICT_DIR`. Non-repo / git-missing ⇒ empty dirty ⇒ pass (never throws).
2204
+ * Basename-keyed off the latest plan ⇒ idempotent across review-fix rounds.
2205
+ */
2206
+ const implementScopeCheckVet = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2207
+ // Declared set = UNION of `phaseFiles` over EVERY non-failed plan on the channel.
2208
+ // The fs-artifact filter skips failed/unfilled entries (an Output with no fs
2209
+ // handle contributed no plan to read).
2210
+ const { declared, latest } = unionDeclaredWriteSet(state.named.plans ?? [], cwd);
2211
+ if (!latest) {
2212
+ throw haltPreflight(
2213
+ "implement-scope-check",
2214
+ "implement-scope-check: no plan to check",
2215
+ "implement-scope-check: no fs plan artifact on the 'plans' channel — blueprint/implement must run before the scope check",
2216
+ );
2217
+ }
2218
+
2219
+ // Run-start baseline (goal channel, role "baseline") + current dirty set —
2220
+ // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
2221
+ const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
2222
+ const dirty = gitDirtyPaths(cwd);
2223
+
2224
+ // Shared core: subtract the run's bookkeeping dirs (`.rpiv/`,
2225
+ // `thoughts/`) and the run-start baseline; empty-`declared` ⇒ `[]` (degradation
2226
+ // ⇒ inert floor — a fully `files:`-less plan never false-fails). Twin-expanded
2227
+ // like build's floor: a declared file carries its co-located test twin.
2228
+ const excess = scopeExcess(dirty, baseline, withTestTwins([...declared]));
2229
+ const findings = excess.map((p) => ({
2230
+ detail: `${p}: written by the implement lane but not declared in any plan iteration's \`files:\` set. A phase may write only its declared paths (the write-scope rule); declare the path in the owning phase's \`files:\` or drop the write.`,
2231
+ where: p,
2232
+ }));
2233
+ const pass = findings.length === 0;
2234
+ const data = {
2235
+ dimension: "scope",
2236
+ pass,
2237
+ verdict: pass ? "pass" : "fail",
2238
+ score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2239
+ severity: pass ? "none" : "high",
2240
+ artifact: handleToString(latest.handle),
2241
+ findings,
2242
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2243
+ };
2244
+ // Basename-keyed, NOT round-stamped (unlike grade's timestamped slug): each
2245
+ // fix-loop round overwrites the file. Deliberate — the route reads the
2246
+ // accumulating channel, and on disk only the latest round's scope verdict
2247
+ // matters; round-stamp here if a consumer ever needs the history.
2248
+ const rel = join(VERDICT_DIR, `implement-scope-check__${basename(latest.handle.path, ".md")}.json`);
2249
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2250
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2251
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2252
+ };
2253
+
2254
+ /**
2255
+ * One `#### Reconciliation` directive parsed from a plan body: a machine-applicable
2256
+ * `find → replace` against a single test-expectation file. The implement lane records
2257
+ * these in a phase's OWN section when a correct change invalidates a test that lives
2258
+ * in a sibling phase's landed section (which the implementer may NOT edit); `reconcile`
2259
+ * applies them write-restricted to `*.test.*` targets.
2260
+ */
2261
+ interface ReconciliationDirective {
2262
+ /** Repo-root-relative test target (`*.test.*`). */
2263
+ target: string;
2264
+ /** Substring to find (replaced exactly once via `String.replace`). */
2265
+ find: string;
2266
+ /** Replacement string. */
2267
+ replace: string;
2268
+ }
2269
+
2270
+ /** Directive grammar: `` - `<target>`: replace `<find>` → `<replace>` — <rationale> ``.
2271
+ * The `→` (U+2192) separates find/replace; the em-dash `—` (U+2014) + rationale is
2272
+ * optional. Find/replace carry no inner backticks. The two spans are intentionally
2273
+ * asymmetric and MUST NOT be symmetrized: `find` is one-or-more `[^`]+` (an empty
2274
+ * find has no anchored target and `String.replace("")` prepends the replacement on
2275
+ * every run, so the parser rejects it at parse time), while `replace` is
2276
+ * zero-or-more `[^`]*` (an empty replace is a legitimate deletion directive). */
2277
+ const RECONCILE_DIRECTIVE_RE = /^-\s+`([^`]+)`\s*:\s*replace\s+`([^`]+)`\s*→\s*`([^`]*)`\s*(?:—\s+.*)?$/;
2278
+ /** A directive ATTEMPT — `- `<target>`:` — that does not match the full grammar. Used
2279
+ * to surface a malformed directive as a finding rather than silently dropping it. */
2280
+ const RECONCILE_DIRECTIVE_ATTEMPT_RE = /^-\s+`[^`]+`\s*:/;
2281
+
2282
+ /**
2283
+ * Parse every `#### Reconciliation` directive from a plan body. Returns the
2284
+ * well-formed directives AND the malformed attempts (lines that carry the
2285
+ * `- `<target>`:` shape but not the full `replace … → …` grammar); `reconcile`
2286
+ * turns each malformed attempt into a finding so a broken directive is visible,
2287
+ * never silently dropped. Prose list items are ignored. Pure: no I/O, no throw.
2288
+ * A section opens at a `#### Reconciliation` heading and closes at the next
2289
+ * `#{1,4}` heading (so `### Success Criteria` / `## Phase N:` / a sibling
2290
+ * `#### Automated Verification:` all end it).
2291
+ */
2292
+ const reconciliationRecords = (
2293
+ body: string,
2294
+ ): {
2295
+ directives: ReconciliationDirective[];
2296
+ malformed: string[];
2297
+ } => {
2298
+ const directives: ReconciliationDirective[] = [];
2299
+ const malformed: string[] = [];
2300
+ let inSection = false;
2301
+ for (const raw of body.split("\n")) {
2302
+ const line = raw.trimEnd();
2303
+ if (/^####\s+Reconciliation\b/.test(line)) {
2304
+ inSection = true;
2305
+ continue;
2306
+ }
2307
+ // Any other heading ends the section (the open-heading branch above `continue`s,
2308
+ // so this only fires for non-`#### Reconciliation` headings).
2309
+ if (/^#{1,4}\s/.test(line)) {
2310
+ inSection = false;
2311
+ continue;
2312
+ }
2313
+ if (!inSection) continue;
2314
+ const m = RECONCILE_DIRECTIVE_RE.exec(line);
2315
+ if (m) {
2316
+ directives.push({ target: m[1]!.trim(), find: m[2]!, replace: m[3]! });
2317
+ } else if (RECONCILE_DIRECTIVE_ATTEMPT_RE.test(line)) {
2318
+ malformed.push(line.trim());
2319
+ }
2320
+ }
2321
+ return { directives, malformed };
2322
+ };
2323
+
2324
+ /**
2325
+ * The reconcile write-restriction's static allowlist — a conservative test-path
2326
+ * classifier. A directive may apply its `find → replace` ONLY to a co-located test
2327
+ * file (`*.test.{ts,tsx,js,jsx}`); any other target is flagged and left untouched
2328
+ * (fail-closed: golden masters, fixtures, `*.t.ts`, and production sources are NOT
2329
+ * auto-applied). Narrow by design — do not widen it to compensate for a weak
2330
+ * directive (correctness rests on this neither false-failing a legit test edit
2331
+ * nor false-allowing a non-test target).
2332
+ */
2333
+ const TEST_PATH_RE = /\.test\.[tj]sx?$/;
2334
+ const isTestPath = (target: string): boolean => TEST_PATH_RE.test(target);
2335
+
2336
+ /**
2337
+ * Apply each `#### Reconciliation` directive, write-restricted to test-expectation
2338
+ * files (`isTestPath` — reconcile writes ONLY test files; a non-test target is a
2339
+ * finding, left untouched, fail-closed). A present `find` is replaced exactly
2340
+ * once (`String.replace`, first match); an absent `find` whose `replace` is ALSO
2341
+ * absent is a finding (reconcile does not guess); an absent `find` whose `replace`
2342
+ * is already present is the idempotent-re-run no-op (a prior successful apply, no
2343
+ * finding, no write). Paths resolve through `cwd` (`isAbsolute` short-circuit else
2344
+ * `join(cwd, target)`). Fail-soft: a read/apply throw degrades to a finding naming
2345
+ * the target, never a terminal throw. Returns findings in DIRECTIVE order and
2346
+ * performs the side-effecting writes itself (`reconcile` spreads the return).
2347
+ */
2348
+ const applyReconciliationDirectives = (
2349
+ directives: readonly ReconciliationDirective[],
2350
+ cwd: string,
2351
+ ): { detail: string; where: string }[] => {
2352
+ const findings: { detail: string; where: string }[] = [];
2353
+ // Apply directives, write-restricted to test-expectation files.
2354
+ for (const d of directives) {
2355
+ if (!isTestPath(d.target)) {
2356
+ findings.push({
2357
+ detail: `reconcile: directive target ${d.target} is not a test-expectation file (*.test.{ts,tsx,js,jsx}) — reconcile writes only test files; record the directive against a test target or apply the edit in the owning phase`,
2358
+ where: d.target,
2359
+ });
2360
+ continue;
2361
+ }
2362
+ try {
2363
+ const abs = isAbsolute(d.target) ? d.target : join(cwd, d.target);
2364
+ const content = readFileSync(abs, "utf-8");
2365
+ if (content.includes(d.find)) {
2366
+ // `String.replace` with a string pattern replaces the FIRST match exactly once.
2367
+ writeFileSync(abs, content.replace(d.find, d.replace), "utf-8");
2368
+ } else if (d.replace !== "" && content.includes(d.replace)) {
2369
+ // Idempotent re-run: the find is gone but the replacement is present ⇒ the
2370
+ // directive was already applied (e.g. a vet review-fix loop re-running
2371
+ // reconcile). Treated as satisfied — reconcile must not fail on its own
2372
+ // prior successful apply.
2373
+ } else {
2374
+ findings.push({
2375
+ detail: `reconcile: directive find substring not present in ${d.target} (and the replacement is absent — not already applied) — the expected text to replace is absent; the directive is stale or the test no longer matches`,
2376
+ where: d.target,
2377
+ });
2378
+ }
2379
+ } catch (err) {
2380
+ findings.push({
2381
+ detail: `reconcile: could not apply directive to ${d.target} — ${err instanceof Error ? err.message : String(err)}`,
2382
+ where: d.target,
2383
+ });
2384
+ }
2385
+ }
2386
+ return findings;
2387
+ };
2388
+
2389
+ /**
2390
+ * Deterministic post-implement reconciliation — the coherence backstop the
2391
+ * parallel implement lane needs. Sibling phases run concurrently in one tree;
2392
+ * each phase's own `#### Automated Verification:` passed in isolation, but a
2393
+ * phase's correct change can invalidate a test that lives in a SIBLING phase's
2394
+ * landed section (which the implementer may not edit), and the combined tree can
2395
+ * break in ways no single phase's checks surface. `reconcile` runs after the
2396
+ * scope floor (which proved the write-set) and before `validate`:
2397
+ *
2398
+ * 1. reads the latest plan (`latestFsArtifact(state, "plans")` — latest-wins);
2399
+ * 2. parses every `#### Reconciliation` directive — fail-soft (a malformed
2400
+ * directive / unreadable plan degrades to a finding, never a terminal
2401
+ * `FAIL_SCRIPT_THREW` halt — a `produces.script` that throws becomes one);
2402
+ * 3. applies each directive write-restricted to test paths (`isTestPath`); a
2403
+ * present `find` is replaced exactly once (`String.replace`); an absent `find`
2404
+ * whose replacement is ALSO absent is a finding (reconcile does not guess);
2405
+ * 4. appends a timestamped `### Reconciliation Log (<iso>)` under the plan's
2406
+ * `## Synthesis Notes` (best-effort bookkeeping write — non-fatal);
2407
+ * 5. emits one `{ dimension: "reconcile" }` verdict, basename-keyed off the plan
2408
+ * ⇒ idempotent across fix rounds (the verdict file is overwritten each round).
2409
+ *
2410
+ * Reconcile deliberately does NOT re-execute the plan's `#### Automated
2411
+ * Verification:` commands. That re-run (bare `execFileSync`, no shell, exit-0
2412
+ * contract) was measured across the full run history at zero genuine catches and
2413
+ * a 100% false-positive finding rate — stale cross-phase presence probes, agent-
2414
+ * shell-only binaries (`rg`), prose greps — each halting a finished run at a
2415
+ * fail route with no fix arm. The downstream `validate` stage runs the same AV
2416
+ * commands as an agent, with a real shell and the judgment to tell a legitimate
2417
+ * post-rename mismatch from actual plan-vs-tree drift.
2418
+ *
2419
+ * The route is the `match("verdict", …, { from: "reconcile" })` gate idiom — pass ⇒
2420
+ * validate, fail/missing ⇒ STOP (no fallback), mirroring `implementScopeCheck`.
2421
+ * Mirrors `implementScopeCheck`'s `ScriptContext` shape, basename-keyed verdict
2422
+ * path, and `dimension`/`pass`/`verdict`/`score`/`severity` data shape. `reads:
2423
+ * ["plans"]` only — reconcile consumes no run-start `goal` baseline (the scope
2424
+ * floor already proved the write-set; reconcile's own writes are directive targets
2425
+ * + the plan bookkeeping). The `from` form suppresses the READS_DATA outputSchema
2426
+ * lint, so no schema is declared (matching `slice-check`/`plan-cite-check`/
2427
+ * `implement-scope-check`).
2428
+ */
2429
+ const reconcile = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2430
+ const latest = latestFsArtifact(state, "plans");
2431
+ if (latest?.handle.kind !== "fs") {
2432
+ throw haltPreflight(
2433
+ "reconcile",
2434
+ "reconcile: no plan to reconcile",
2435
+ "reconcile: no fs artifact on the 'plans' channel — implement / scope-check must run before reconcile",
2436
+ );
2437
+ }
2438
+ const planPath = latest.handle.path;
2439
+ const planAbs = isAbsolute(planPath) ? planPath : join(cwd, planPath);
2440
+ const findings: { detail: string; where: string }[] = [];
2441
+
2442
+ // Fail-soft read + parse: an unreadable plan or malformed directive degrades
2443
+ // to a finding, never a terminal throw. If the read fails there is nothing to
2444
+ // apply.
2445
+ let body = "";
2446
+ let directives: ReconciliationDirective[] = [];
2447
+ let malformed: string[] = [];
2448
+ try {
2449
+ body = readArtifactFile(planPath, cwd);
2450
+ const parsed = reconciliationRecords(body);
2451
+ directives = parsed.directives;
2452
+ malformed = parsed.malformed;
2453
+ } catch (err) {
2454
+ findings.push({
2455
+ detail: `reconcile: could not read or parse the plan ${planPath} — ${err instanceof Error ? err.message : String(err)}`,
2456
+ where: planPath,
2457
+ });
2458
+ }
2459
+ for (const m of malformed) {
2460
+ findings.push({
2461
+ detail: `reconcile: malformed Reconciliation directive — expected a line of the form: - \`<target>\`: replace \`<find>\` → \`<replace>\` (target/find/replace each backtick-wrapped) — ${m}`,
2462
+ where: "reconciliation-directive",
2463
+ });
2464
+ }
2465
+
2466
+ findings.push(...applyReconciliationDirectives(directives, cwd));
2467
+
2468
+ // Best-effort bookkeeping: append a timestamped log under ## Synthesis Notes.
2469
+ // Non-fatal — a write failure here is silent (the verdict below is the signal).
2470
+ if (body) {
2471
+ try {
2472
+ const stamp = new Date().toISOString();
2473
+ const verdict = findings.length === 0 ? "pass" : "fail";
2474
+ const logBlock = `\n### Reconciliation Log (${stamp})\nApplied ${directives.length} directive(s); ${findings.length} finding(s); verdict: ${verdict}.\n`;
2475
+ const heading = "## Synthesis Notes";
2476
+ const idx = body.indexOf(heading);
2477
+ let updated: string;
2478
+ if (idx >= 0) {
2479
+ const lineEnd = body.indexOf("\n", idx);
2480
+ const at = lineEnd >= 0 ? lineEnd + 1 : body.length;
2481
+ updated = body.slice(0, at) + logBlock + body.slice(at);
2482
+ } else {
2483
+ updated = `${body.replace(/\s+$/, "")}\n${logBlock}`;
2484
+ }
2485
+ writeFileSync(planAbs, updated, "utf-8");
2486
+ } catch {
2487
+ // bookkeeping — ignore
2488
+ }
2489
+ }
2490
+
2491
+ const pass = findings.length === 0;
2492
+ const data = {
2493
+ dimension: "reconcile",
2494
+ pass,
2495
+ verdict: pass ? "pass" : "fail",
2496
+ score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2497
+ severity: pass ? "none" : "high",
2498
+ artifact: handleToString(latest.handle),
2499
+ findings,
2500
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2501
+ };
2502
+ // Basename-keyed off the latest plan ⇒ idempotent across fix rounds (mirrors
2503
+ // implementScopeCheck / planCitationCheck, NOT round-stamped like grade).
2504
+ const rel = join(VERDICT_DIR, `reconcile__${basename(planPath, ".md")}.json`);
2505
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2506
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2507
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2508
+ };
2509
+
1171
2510
  /** A design filename encodes its slice as `…slice-<N>…` — the design-fanout naming convention. */
1172
2511
  const DESIGN_SLICE_RE = /slice-(\d+)/;
1173
2512
 
@@ -1184,8 +2523,8 @@ const DESIGN_SLICE_RE = /slice-(\d+)/;
1184
2523
  * (its documented "latest-wins, same paths" contract, so `subplan`/`synthesize`
1185
2524
  * read the accepted docs). So the newest entry wins, deterministically — throwing
1186
2525
  * 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.)
2526
+ * that once left CONFLICTING designs on the channel is fixed at its source,
2527
+ * so there is no corruption left to fail loud on here.)
1189
2528
  */
1190
2529
  const designPathsBySlice = (state: RunView): Map<number, string> => {
1191
2530
  const bySlice = new Map<number, string>();
@@ -1238,7 +2577,10 @@ const SYNTH_CLUSTER_FANOUT = fanout({
1238
2577
  .map((p) => `--designs ${p}`);
1239
2578
  if (!designs.length) return undefined;
1240
2579
  return {
1241
- prompt: `${designs.join(" ")}${researchFlag} --as-subplan`,
2580
+ // Stamp each cluster's ordinal into its prompt so the partial-mode pass
2581
+ // writes a distinct `_cluster-<k>.md` — a re-dispatched unit must never
2582
+ // reuse a sibling's filename and clobber it. `<k>` matches `id: cluster-<k>`.
2583
+ prompt: `${designs.join(" ")}${researchFlag} --cluster ${i + 1} --as-subplan`,
1242
2584
  label: `cluster ${i + 1} (slices ${cluster.join(",")})`,
1243
2585
  id: `cluster-${i + 1}`,
1244
2586
  };
@@ -1316,8 +2658,10 @@ const gateTier = (state: RunView, verdictChannel: string): GateTier => {
1316
2658
  const phases = channelNumber(state, "plans", "phase_count");
1317
2659
  const severities = new Set<string>();
1318
2660
  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);
2661
+ const v = o.data as { severity?: unknown; findings?: unknown } | undefined;
2662
+ const s = v?.severity;
2663
+ // Anchor-nit clamp: an all-drift-nit verdict must not escalate the tier.
2664
+ if (typeof s === "string") severities.add(anchorNitsOnly(v) ? "low" : s);
1321
2665
  }
1322
2666
  if (
1323
2667
  (slices !== undefined && slices >= TIER_STRICT_MIN_SLICES) ||
@@ -1384,6 +2728,42 @@ const latestVerdictPerDimension = (entries: readonly Output[] = []): Map<string,
1384
2728
  return latest;
1385
2729
  };
1386
2730
 
2731
+ /**
2732
+ * Anchor-drift-nit phrasing, two tiers: only phrasings naming drift itself
2733
+ * count standalone; the location shapes (off-by-N, "is at line N", "line N is
2734
+ * the/a") also match REAL defects ("line 42 is a comment that falsely claims
2735
+ * X", "the loop bound is off by one") and count ONLY alongside citing-context
2736
+ * vocabulary — every observed drift nit has it, real-defect phrasings don't.
2737
+ * Do NOT widen, and do NOT promote a location shape to standalone.
2738
+ */
2739
+ const ANCHOR_NIT_DRIFT_RE = /\bdrifted?\s+~?\d+\s+lines?\b|\bcitation (?:is )?drifted\b/i;
2740
+ const ANCHOR_NIT_LOCATION_RE =
2741
+ /\boff[- ]by[- ](?:one|two|three|\d+)\b|(?::\d+|\bline \d+) is (?:the|a)\b|\bis at line \d+\b/i;
2742
+ const ANCHOR_NIT_CITE_CONTEXT_RE = /\bcit(?:es?|ed|ation)\b|\banchor/i;
2743
+
2744
+ const isAnchorNitDetail = (detail: string): boolean =>
2745
+ ANCHOR_NIT_DRIFT_RE.test(detail) || (ANCHOR_NIT_LOCATION_RE.test(detail) && ANCHOR_NIT_CITE_CONTEXT_RE.test(detail));
2746
+
2747
+ /**
2748
+ * TRUE when a verdict carries ≥1 finding and EVERY finding is an anchor-drift
2749
+ * nit (`isAnchorNitDetail`). Such a verdict is severity-clamped to non-blocking
2750
+ * at the gate fold regardless of the grader's own `severity` — line-number
2751
+ * drift was measured at 34% of all grader findings with zero downstream harm,
2752
+ * and a mis-rated all-nit `medium` verdict buys a full fix round + re-grade
2753
+ * panel that repairs nothing. A verdict mixing a drift nit with ANY other
2754
+ * finding is untouched — the other finding may be the real blocker.
2755
+ */
2756
+ const anchorNitsOnly = (v: { findings?: unknown } | undefined): boolean => {
2757
+ const findings = Array.isArray(v?.findings) ? v.findings : [];
2758
+ return (
2759
+ findings.length > 0 &&
2760
+ findings.every((f) => {
2761
+ const detail = (f as { detail?: unknown } | undefined)?.detail;
2762
+ return typeof detail === "string" && isAnchorNitDetail(detail);
2763
+ })
2764
+ );
2765
+ };
2766
+
1387
2767
  /**
1388
2768
  * The subset of `dimensions` a re-grade must actually re-run, given the latest
1389
2769
  * verdict per dimension accumulated so far. A dimension needs re-grading when it
@@ -1397,18 +2777,216 @@ const latestVerdictPerDimension = (entries: readonly Output[] = []): Map<string,
1397
2777
  * channel + `allDimensionsPass`'s latest-per-dimension fold mean a carried
1398
2778
  * dimension's prior passing verdict still counts at the gate.
1399
2779
  */
1400
- const dimensionsToRegrade = (dimensions: readonly string[], latest: ReadonlyMap<string, Output>): string[] => {
2780
+ const dimensionsToRegrade = (
2781
+ dimensions: readonly string[],
2782
+ latest: ReadonlyMap<string, Output>,
2783
+ risks: ReadonlyMap<string, RiskRecord> = new Map(),
2784
+ ): string[] => {
1401
2785
  return dimensions.filter((d) => {
1402
2786
  const o = latest.get(d);
1403
2787
  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";
2788
+ const v = o.data as { pass?: boolean; severity?: string; findings?: unknown } | undefined;
2789
+ const dimPass = v?.pass === true || v?.severity === "low" || v?.severity === "none" || anchorNitsOnly(v);
1406
2790
  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);
2791
+ return verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
1409
2792
  });
1410
2793
  };
1411
2794
 
2795
+ /**
2796
+ * Coarse line-count backstop for the surgical-fix guard. The subset test
2797
+ * (`touchedSections − HOUSEKEEPING ⊆ cited`) is the binding constraint — do
2798
+ * NOT tighten this to compensate for a weak subset test.
2799
+ */
2800
+ const NON_SURGICAL_DIFF_LINE_THRESHOLD = 60;
2801
+
2802
+ /**
2803
+ * Plan sections amend ALWAYS bumps without the fix touching their meaning —
2804
+ * the pseudo-section `frontmatter` (via the `last_updated` field). Exempt from
2805
+ * the "touched outside cited" test. Starts at `{frontmatter}` only; do not
2806
+ * pre-widen (a genuinely-meaningful bookkeeping section would let a broad amend
2807
+ * pass the subset test by touching it).
2808
+ */
2809
+ const HOUSEKEEPING_SECTIONS: ReadonlySet<string> = new Set(["frontmatter"]);
2810
+
2811
+ /** Directory the snapshot stages copy the pre-fix plan into (basename-keyed). */
2812
+ const PRIOR_DIR = ".rpiv/artifacts/priors";
2813
+
2814
+ /**
2815
+ * Map each line index to its plan-section name: the nearest preceding `## `
2816
+ * heading — `## Phase N: …` normalizes to `phase N` (case-insensitive); any
2817
+ * other heading is lowercased by tail — so touched-section keys and cited-section
2818
+ * keys share one space. The frontmatter block (opening `---` through its closing
2819
+ * `---`) is the pseudo-section `frontmatter`. Lines before the first heading and
2820
+ * outside frontmatter map to `""` (which is neither housekeeping nor a `phase N`
2821
+ * cite, so any change there is treated as out-of-scope).
2822
+ */
2823
+ const sectionIndexOf = (lines: readonly string[]): string[] => {
2824
+ const idx = new Array<string>(lines.length);
2825
+ let current = "";
2826
+ let inFrontmatter = lines[0]?.trim() === "---";
2827
+ for (let i = 0; i < lines.length; i++) {
2828
+ if (inFrontmatter) {
2829
+ idx[i] = "frontmatter";
2830
+ if (i > 0 && lines[i].trim() === "---") inFrontmatter = false;
2831
+ continue;
2832
+ }
2833
+ const m = /^##\s+(.*)$/.exec(lines[i]);
2834
+ if (m) {
2835
+ const ph = /^Phase\s+(\d+)/i.exec(m[1].trim());
2836
+ current = ph ? `phase ${ph[1]}` : m[1].trim().toLowerCase();
2837
+ }
2838
+ idx[i] = current;
2839
+ }
2840
+ return idx;
2841
+ };
2842
+
2843
+ /**
2844
+ * Line-level diff of `prior` vs `current` plan bodies, mapped to plan sections.
2845
+ * Each changed line (a deletion from `prior` OR an insertion in `current` under
2846
+ * an LCS match) is attributed to its nearest preceding `## ` heading in its own
2847
+ * document. Returns the union of touched section keys and a coarse changed-line
2848
+ * count (deletions + insertions). Insertion-tolerant: a 1-line insert does not
2849
+ * mark every trailing line changed (the LCS keeps shared context matched).
2850
+ */
2851
+ const sectionDiff = (prior: string, current: string): { touchedSections: Set<string>; changedLines: number } => {
2852
+ const a = prior.split("\n");
2853
+ const b = current.split("\n");
2854
+ const sa = sectionIndexOf(a);
2855
+ const sb = sectionIndexOf(b);
2856
+ // LCS length table (bottom-up). Plans are a few hundred lines ⇒ O(n·m) trivial.
2857
+ const dp: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
2858
+ for (let i = a.length - 1; i >= 0; i--) {
2859
+ for (let j = b.length - 1; j >= 0; j--) {
2860
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
2861
+ }
2862
+ }
2863
+ const touched = new Set<string>();
2864
+ let changed = 0;
2865
+ let i = 0;
2866
+ let j = 0;
2867
+ while (i < a.length && j < b.length) {
2868
+ if (a[i] === b[j]) {
2869
+ i++;
2870
+ j++;
2871
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
2872
+ touched.add(sa[i]); // a[i] deleted (present in prior, absent in current)
2873
+ changed++;
2874
+ i++;
2875
+ } else {
2876
+ touched.add(sb[j]); // b[j] inserted (present in current, absent in prior)
2877
+ changed++;
2878
+ j++;
2879
+ }
2880
+ }
2881
+ while (i < a.length) {
2882
+ touched.add(sa[i]);
2883
+ changed++;
2884
+ i++;
2885
+ }
2886
+ while (j < b.length) {
2887
+ touched.add(sb[j]);
2888
+ changed++;
2889
+ j++;
2890
+ }
2891
+ return { touchedSections: touched, changedLines: changed };
2892
+ };
2893
+
2894
+ /**
2895
+ * Plan sections cited by the FAILING dimensions' findings — extracted from each
2896
+ * finding's `where` and `detail` (`Phase N` → `phase N`, lowercased). Preferred
2897
+ * `where: "Phase 1 > lane-dock-editor.ts Edit 1"` → `phase 1`; a repo
2898
+ * `path:line`-only `where` (and a detail with no `Phase N`) contributes NO plan
2899
+ * section. Empty when no failing finding carries an extractable plan-section
2900
+ * reference — fail-closed: the caller treats an empty cite set against any
2901
+ * non-housekeeping touched section as out-of-scope (non-surgical).
2902
+ */
2903
+ const citedSections = (latest: ReadonlyMap<string, Output>, pending: readonly string[]): Set<string> => {
2904
+ const cited = new Set<string>();
2905
+ for (const d of pending) {
2906
+ const findings = (latest.get(d)?.data as { findings?: unknown } | undefined)?.findings;
2907
+ if (!Array.isArray(findings)) continue;
2908
+ for (const f of findings) {
2909
+ if (f == null || typeof f !== "object") continue;
2910
+ const where = typeof (f as { where?: unknown }).where === "string" ? (f as { where: string }).where : "";
2911
+ const detail = typeof (f as { detail?: unknown }).detail === "string" ? (f as { detail: string }).detail : "";
2912
+ for (const text of [where, detail]) {
2913
+ for (const m of text.matchAll(/Phase\s+(\d+)/gi)) cited.add(`phase ${m[1]}`);
2914
+ }
2915
+ }
2916
+ }
2917
+ return cited;
2918
+ };
2919
+
2920
+ /**
2921
+ * The prior-role `fs` artifact the snapshot stage published on `priorChannel`
2922
+ * (undefined when the channel carries no prior — round 1 / first re-grade).
2923
+ * Existence of the ENTRY is distinct from readability of the sidecar: an entry
2924
+ * that exists but cannot be read still counts as "prior present" so the caller
2925
+ * fails closed to a FULL roster rather than silently carrying forward.
2926
+ */
2927
+ const priorArtifact = (state: RunView, priorChannel: string): Artifact | undefined => {
2928
+ const entry = state.named[priorChannel]?.at(-1);
2929
+ const prior = entry?.artifacts.find((a) => a.handle.kind === "fs" && a.role === "prior");
2930
+ return prior?.handle.kind === "fs" ? prior : undefined;
2931
+ };
2932
+
2933
+ /**
2934
+ * Read the prior sidecar's bytes off `priorChannel`. Returns `undefined` when
2935
+ * the channel is empty, the prior artifact is not fs, OR the sidecar is
2936
+ * unreadable — the caller treats `undefined` as fail-closed (non-surgical).
2937
+ */
2938
+ const latestPriorContent = (state: RunView, priorChannel: string, cwd: string): string | undefined => {
2939
+ const prior = priorArtifact(state, priorChannel);
2940
+ if (prior?.handle.kind !== "fs") return undefined;
2941
+ try {
2942
+ return readArtifactFile(prior.handle.path, cwd);
2943
+ } catch {
2944
+ return undefined;
2945
+ }
2946
+ };
2947
+
2948
+ /**
2949
+ * True ONLY when a readable prior exists AND the current plan's diff from it
2950
+ * touches ONLY sections a failing finding cited (minus housekeeping) AND the
2951
+ * changed-line count is within the coarse threshold. Every missing signal — no
2952
+ * prior, unreadable sidecar, unreadable current plan, a diff/parse throw, a
2953
+ * touched section no failing finding cited, or an over-threshold diff —
2954
+ * collapses to `false` (fail-closed ⇒ the caller re-grades the full roster
2955
+ * when a prior is present, or carries forward when none is). `pending` is
2956
+ * consumed as-is: whatever `dimensionsToRegrade` ruled still-blocking (after
2957
+ * phase 3's `rulingEffectivePass` clause-3 rewrite) is the set this guard
2958
+ * narrows on.
2959
+ */
2960
+ const isSurgicalFix = (
2961
+ state: RunView,
2962
+ priorChannel: string,
2963
+ cwd: string,
2964
+ target: string,
2965
+ latest: ReadonlyMap<string, Output>,
2966
+ pending: readonly string[],
2967
+ ): boolean => {
2968
+ const prior = latestPriorContent(state, priorChannel, cwd);
2969
+ if (prior === undefined) return false;
2970
+ let current: string;
2971
+ try {
2972
+ current = readArtifactFile(target, cwd);
2973
+ } catch {
2974
+ return false;
2975
+ }
2976
+ let diff: { touchedSections: Set<string>; changedLines: number };
2977
+ try {
2978
+ diff = sectionDiff(prior, current);
2979
+ } catch {
2980
+ return false;
2981
+ }
2982
+ const cited = citedSections(latest, pending);
2983
+ for (const section of diff.touchedSections) {
2984
+ if (HOUSEKEEPING_SECTIONS.has(section)) continue;
2985
+ if (!cited.has(section)) return false;
2986
+ }
2987
+ return diff.changedLines <= NON_SURGICAL_DIFF_LINE_THRESHOLD;
2988
+ };
2989
+
1412
2990
  /**
1413
2991
  * A grade panel: one `grade` session per dimension over the latest artifact on
1414
2992
  * `channel`. Each unit's prompt is the `grade` skill's flags
@@ -1449,13 +3027,13 @@ const gradePanelFanout = (
1449
3027
  channel: string,
1450
3028
  dimensions: readonly string[],
1451
3029
  verdictChannel: string,
1452
- { confirm = false }: { confirm?: boolean } = {},
3030
+ { confirm = false, priorChannel }: { confirm?: boolean; priorChannel?: string } = {},
1453
3031
  ) =>
1454
3032
  fanout({
1455
3033
  source: channel,
1456
3034
  unit: { by: "dimension-list", pattern: "dimensions" },
1457
3035
  max: dimensions.length,
1458
- units: ({ state }) => {
3036
+ units: ({ state, cwd }) => {
1459
3037
  const doc = latestFsArtifact(state, channel);
1460
3038
  if (doc?.handle.kind !== "fs") return [];
1461
3039
  const target = handleToString(doc.handle);
@@ -1465,14 +3043,31 @@ const gradePanelFanout = (
1465
3043
  const goalFlag = goal?.handle.kind === "fs" ? ` --goal ${handleToString(goal.handle)}` : "";
1466
3044
  const roster = gateRoster(gateTier(state, verdictChannel), dimensions);
1467
3045
  const latest = latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel], target));
1468
- const pending = dimensionsToRegrade(roster, latest);
3046
+ const risks = planAuthoredRisks(state, channel);
3047
+ const pending = dimensionsToRegrade(roster, latest, risks);
3048
+ // Delta re-grade fallback guard (plan/code gates only — `priorChannel`
3049
+ // is unset for the slice gate and both confirm panels). When the snapshot
3050
+ // stage published a prior, compare it to the current plan: a SURGICAL
3051
+ // amend (touched only sections a failing finding cited, ≤ threshold
3052
+ // lines) re-grades only the still-pending dimensions; a NON-surgical
3053
+ // amend (broad / out-of-scope / over-threshold / unreadable / unparseable)
3054
+ // re-grades the FULL roster — a broad amend may have regressed a passing
3055
+ // dimension the carry-forward would otherwise trust. With NO prior
3056
+ // (round 1 / first re-grade) the carry-forward applies unchanged. See
3057
+ // `isSurgicalFix` for the fail-closed contract.
3058
+ const surgical =
3059
+ !confirm && priorChannel !== undefined && isSurgicalFix(state, priorChannel, cwd, target, latest, pending);
3060
+ const priorPresent = priorChannel !== undefined && priorArtifact(state, priorChannel) !== undefined;
1469
3061
  const priorFlag = (d: string): string => {
1470
3062
  if (!confirm || !pending.includes(d)) return "";
1471
3063
  const handle = latest.get(d)?.artifacts.find((a) => a.handle.kind === "fs")?.handle;
1472
3064
  return handle ? ` --prior ${handleToString(handle)}` : "";
1473
3065
  };
1474
- // Never emit zero units (empty ⇒ single dimensionless grade fall-through).
1475
- const toGrade = pending.length > 0 ? pending : roster;
3066
+ const carryForward = pending.length > 0 ? pending : roster;
3067
+ // A non-surgical result WITH a prior present re-grades the FULL roster;
3068
+ // with NO prior the carry-forward applies (never an empty unit set —
3069
+ // empty ⇒ single dimensionless grade fall-through).
3070
+ const toGrade = surgical ? carryForward : priorPresent ? roster : carryForward;
1476
3071
  return toGrade.map((d) => ({
1477
3072
  prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}${priorFlag(d)}`,
1478
3073
  label: d,
@@ -1482,11 +3077,15 @@ const gradePanelFanout = (
1482
3077
  });
1483
3078
 
1484
3079
  const SLICE_DIMENSION_FANOUT = gradePanelFanout("slices", SLICE_DIMENSIONS, "slice-verdicts");
1485
- const PLAN_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts");
3080
+ const PLAN_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts", {
3081
+ priorChannel: "plan-snapshot",
3082
+ });
1486
3083
  // The post-splice code gate re-grades the SAME `plans` artifact on its own
1487
3084
  // `code-verdicts` channel, so its carry-forward reads the code gate's verdicts,
1488
3085
  // never the pre-elaborate plan gate's.
1489
- const CODE_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts");
3086
+ const CODE_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts", {
3087
+ priorChannel: "code-snapshot",
3088
+ });
1490
3089
  // The confirm stages re-run the SAME panel machinery on the SAME verdict
1491
3090
  // channel: with the failing dimensions the only ones pending, the panel emits
1492
3091
  // exactly the blocking dimensions — one second judgment each, in confirm mode:
@@ -1520,10 +3119,12 @@ const allDimensionsPass = (entries: readonly Output[] = [], roster?: readonly st
1520
3119
  const member = roster ? new Set(roster) : undefined;
1521
3120
  const latest = new Map<string, boolean>();
1522
3121
  for (const o of entries) {
1523
- const v = o.data as { dimension?: string; pass?: boolean; severity?: string } | undefined;
3122
+ const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
1524
3123
  if (typeof v?.dimension !== "string") continue;
1525
3124
  if (member && !member.has(v.dimension)) continue;
1526
- const lowOrNone = v.severity === "low" || v.severity === "none";
3125
+ // The anchor-nit clamp: an all-drift-nit verdict never blocks, whatever
3126
+ // severity the grader typed (backstop for the citation-resolution rule).
3127
+ const lowOrNone = v.severity === "low" || v.severity === "none" || anchorNitsOnly(v);
1527
3128
  latest.set(v.dimension, v.pass === true || lowOrNone);
1528
3129
  }
1529
3130
  const verdicts = [...latest.values()];
@@ -1539,6 +3140,26 @@ const allDimensionsPass = (entries: readonly Output[] = [], roster?: readonly st
1539
3140
  interface RiskRuling {
1540
3141
  id: string;
1541
3142
  pass: boolean;
3143
+ /**
3144
+ * `mechanics` marks a risk whose `pass` asserts a verified mechanism (a
3145
+ * behavior that holds because code was checked), so a passing ruling MUST
3146
+ * cite the checked `file:line` in `evidence` — an un-evidenced mechanics
3147
+ * pass demotes. Absent on
3148
+ * an ordinary risk ⇒ no evidence duty.
3149
+ */
3150
+ claim_type?: string;
3151
+ /** The `file:line`-shaped citation a mechanics pass must ground itself on. */
3152
+ evidence?: string;
3153
+ /**
3154
+ * `verify-at-implement` marks a risk the panel defers: ruled `pass` ONLY when
3155
+ * a concrete `procedure` + `owner` phase will re-check it at implement/validate
3156
+ * time. Absent ⇒ the risk is judged in this panel, not deferred.
3157
+ */
3158
+ disposition?: string;
3159
+ /** Named command/test the owner phase runs to discharge a deferred risk. */
3160
+ procedure?: string;
3161
+ /** The phase (`n`) that owns the deferred verify step. */
3162
+ owner?: number;
1542
3163
  }
1543
3164
 
1544
3165
  /** The `risk_rulings` a grade verdict emitted (empty when it ruled on none). */
@@ -1547,22 +3168,144 @@ const verdictRiskRulings = (o: Output): RiskRuling[] => {
1547
3168
  if (!Array.isArray(raw)) return [];
1548
3169
  return raw.flatMap((e) => {
1549
3170
  const r = (e ?? {}) as Record<string, unknown>;
1550
- return typeof r.id === "string" ? [{ id: r.id, pass: r.pass === true }] : [];
3171
+ if (typeof r.id !== "string") return [];
3172
+ // Read the duty fields defensively (same typeof-guard idiom as id/pass):
3173
+ // absent on an older/ordinary verdict ⇒ undefined ⇒ the duty helpers no-op.
3174
+ const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
3175
+ const evidence = typeof r.evidence === "string" ? r.evidence : undefined;
3176
+ const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
3177
+ const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
3178
+ const owner = typeof r.owner === "number" ? r.owner : undefined;
3179
+ return [
3180
+ {
3181
+ id: r.id,
3182
+ pass: r.pass === true,
3183
+ ...(claim_type !== undefined ? { claim_type } : {}),
3184
+ ...(evidence !== undefined ? { evidence } : {}),
3185
+ ...(disposition !== undefined ? { disposition } : {}),
3186
+ ...(procedure !== undefined ? { procedure } : {}),
3187
+ ...(owner !== undefined ? { owner } : {}),
3188
+ },
3189
+ ];
1551
3190
  });
1552
3191
  };
1553
3192
 
3193
+ /**
3194
+ * A plan-authored risk flag — the duty shape `synthesize` declares in the plan
3195
+ * frontmatter `risks:` array (`synthesize/SKILL.md:136`: `{ id, claim,
3196
+ * claim_type?, disposition?, procedure?, owner? }`). The prose `claim` is grading
3197
+ * copy, not a duty signal, so it is not carried here. `claim_type: "mechanics"`
3198
+ * and `disposition: "verify-at-implement"` are the two duty TRIGGERS — sourced
3199
+ * from the PLAN (not the ruling) so a panel cannot drop its discharge obligation
3200
+ * by simply omitting the field from its ruling (the dropped-duty bypass).
3201
+ */
3202
+ interface RiskRecord {
3203
+ id: string;
3204
+ claim_type?: string;
3205
+ disposition?: string;
3206
+ procedure?: string;
3207
+ owner?: number;
3208
+ }
3209
+
3210
+ /**
3211
+ * Read the plan-authored risk flags off the latest record on `channel`, keyed
3212
+ * by `id`. The duty triggers live HERE (the plan's `risks:` frontmatter), not on
3213
+ * the grade panel's ruling, so a ruling that drops its discharge field cannot
3214
+ * escape the duty the plan declared (a bare `{ id, pass }` ruling against a
3215
+ * plan-authored `claim_type: "mechanics"` risk still demotes). Reads only
3216
+ * `state.named[channel]` via `latestChannelData` — no `readFileSync`, no
3217
+ * `cwd`, no throw — so the route's `readsData: false` / determinism /
3218
+ * resume-safety contract holds and a resumed run re-evaluates identically.
3219
+ * Degrades to an empty map (fail-open ⇒ no duty ⇒ plain ruling ⇒
3220
+ * `rulingEffectivePass(r) === r.pass`) when `risks:` is absent/non-array/
3221
+ * malformed, mirroring `latestChannelData`'s degrade-to-undefined contract.
3222
+ */
3223
+ const planAuthoredRisks = (state: RunView, channel: string): Map<string, RiskRecord> => {
3224
+ const risks = latestChannelData(state, channel)?.risks;
3225
+ const out = new Map<string, RiskRecord>();
3226
+ if (!Array.isArray(risks)) return out;
3227
+ for (const e of risks) {
3228
+ const r = (e ?? {}) as Record<string, unknown>;
3229
+ if (typeof r.id !== "string") continue;
3230
+ const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
3231
+ const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
3232
+ const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
3233
+ const owner = typeof r.owner === "number" ? r.owner : undefined;
3234
+ const rec: RiskRecord = { id: r.id };
3235
+ if (claim_type !== undefined) rec.claim_type = claim_type;
3236
+ if (disposition !== undefined) rec.disposition = disposition;
3237
+ if (procedure !== undefined) rec.procedure = procedure;
3238
+ if (owner !== undefined) rec.owner = owner;
3239
+ out.set(r.id, rec);
3240
+ }
3241
+ return out;
3242
+ };
3243
+
3244
+ /**
3245
+ * A mechanics-pass ruling's evidence duty: when the plan AUTHORED a
3246
+ * `claim_type: "mechanics"` risk for the ruling's id, a `pass` ruling MUST
3247
+ * cite the checked `file:line` in `evidence` (forces engagement — a pass with
3248
+ * no evidence is an unverified mechanism). The trigger is sourced from the
3249
+ * plan-authored `RiskRecord`, NOT the ruling — so a panel cannot drop the
3250
+ * evidence duty by omitting `claim_type` from its ruling (the dropped-duty
3251
+ * bypass). Reuses `FILE_LINE_CITATION_RE` via `.match()` — NOT `.test()`: the
3252
+ * regex carries the `/g` flag, so `.test()` is stateful across calls
3253
+ * (`lastIndex` advances) and would
3254
+ * intermittently miss a present citation. An id with no authored mechanics
3255
+ * risk carries no evidence duty ⇒ returns `true`.
3256
+ */
3257
+ const evidenceCitesFileLine = (r: RiskRuling, authored?: RiskRecord): boolean => {
3258
+ if (authored?.claim_type !== "mechanics") return true;
3259
+ return typeof r.evidence === "string" && r.evidence.match(FILE_LINE_CITATION_RE) !== null;
3260
+ };
3261
+
3262
+ /**
3263
+ * A deferred-risk's verify-at-implement duty: when the plan AUTHORED a
3264
+ * `disposition: "verify-at-implement"` risk for the ruling's id, a `pass`
3265
+ * ruling MUST carry a concrete `procedure` (the named command/test the owner
3266
+ * phase runs) AND a numeric `owner` phase — a bare "verify later" with no
3267
+ * procedure demotes. The trigger is sourced from the plan-authored
3268
+ * `RiskRecord`, NOT the ruling (the dropped-duty bypass). An id with no
3269
+ * authored verify-at-implement risk is judged in THIS panel, not deferred ⇒
3270
+ * returns `true`.
3271
+ */
3272
+ const procedureSatisfiesDuty = (r: RiskRuling, authored?: RiskRecord): boolean => {
3273
+ if (authored?.disposition !== "verify-at-implement") return true;
3274
+ return typeof r.procedure === "string" && r.procedure.length > 0 && typeof r.owner === "number";
3275
+ };
3276
+
3277
+ /**
3278
+ * The single gate-fold authority: a ruling is effective-pass iff it is a bare
3279
+ * `pass` AND (when the plan authored a mechanics risk for its id) its evidence
3280
+ * cites a `file:line` AND (when the plan authored a verify-at-implement risk
3281
+ * for its id) its procedure+owner discharge the verify duty. `allRiskFlagsPass`,
3282
+ * `dimensionsToRegrade` clause 3, and `confirmDue`'s `riskFail` ALL consult this
3283
+ * — so the three risk folds agree on what "passing" means and a demoted
3284
+ * mechanics/deferred pass blocks the gate AND re-opens its owning dimension
3285
+ * AND counts as blocking for confirm (no incoherent re-grading). For a ruling
3286
+ * whose id the plan authored no duty for (no mechanics/verify-at-implement
3287
+ * risk, no `risks:` at all, or no matching id) every duty no-ops, so
3288
+ * `rulingEffectivePass(r, authored) === r.pass` — prior behavior is preserved.
3289
+ */
3290
+ const rulingEffectivePass = (r: RiskRuling, authored?: RiskRecord): boolean =>
3291
+ r.pass === true && evidenceCitesFileLine(r, authored) && procedureSatisfiesDuty(r, authored);
3292
+
1554
3293
  /**
1555
3294
  * Fold the grade panel's per-flag risk rulings into a gate decision: every
1556
3295
  * plan-authored risk flag the panel ruled on must be ruled PASS (latest ruling
1557
3296
  * per flag wins, mirroring `allDimensionsPass`). A flag ruled `fail` — the
1558
3297
  * 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
3298
+ * self-flagged risk (e.g. an override-vs-env validation mismatch) can no longer
1560
3299
  * ride a green conformance pass into commit. An empty panel (no flag engaged)
1561
3300
  * imposes no constraint; the plan simply declared no risks.
1562
3301
  */
1563
- const allRiskFlagsPass = (entries: readonly Output[] = []): boolean => {
3302
+ const allRiskFlagsPass = (
3303
+ entries: readonly Output[] = [],
3304
+ risks: ReadonlyMap<string, RiskRecord> = new Map(),
3305
+ ): boolean => {
1564
3306
  const latest = new Map<string, boolean>();
1565
- for (const o of entries) for (const r of verdictRiskRulings(o)) latest.set(r.id, r.pass);
3307
+ for (const o of entries)
3308
+ for (const r of verdictRiskRulings(o)) latest.set(r.id, rulingEffectivePass(r, risks.get(r.id)));
1566
3309
  return [...latest.values()].every(Boolean);
1567
3310
  };
1568
3311
 
@@ -1588,23 +3331,47 @@ const allRiskFlagsPass = (entries: readonly Output[] = []): boolean => {
1588
3331
  // `units()` uses, so "skip the re-grade" stays provably equivalent to
1589
3332
  // "re-grade, then pass". The deterministic cite/structure channels fold
1590
3333
  // unfiltered: they re-run every round and carry no tier.
3334
+ // The latest structure verdict carries a `citeDischarged` stamp for the
3335
+ // CURRENT slice map. After a fix for a `remedy: "cite"` fail, the failing
3336
+ // design-readiness verdict is stale (the fix re-sliced to a NEW file) and the
3337
+ // gate's lone dimension has no fresh verdict, so the verdict fold can never
3338
+ // pass — yet the fix is deterministically verifiable: `sliceStructureCheck`
3339
+ // stamps the map basename it verified (demanded seeds present + shape
3340
+ // unchanged, see `citeRemedyDischarged`). Honoring the stamp only for the
3341
+ // current map means it can never carry across a later re-slice.
3342
+ const citeDischargeCoversCurrentMap = (state: RunView): boolean => {
3343
+ const stamp = (state.named["slice-check"]?.at(-1)?.data as { citeDischarged?: unknown } | undefined)?.citeDischarged;
3344
+ const current = latestArtifactPath(state, "slices");
3345
+ return typeof stamp === "string" && current !== undefined && stamp === basename(current);
3346
+ };
1591
3347
  const sliceGatePasses = (state: RunView): boolean => {
1592
3348
  const fresh = freshVerdicts(state.named["slice-verdicts"], latestArtifactPath(state, "slices"));
1593
3349
  const roster = gateRoster(gateTier(state, "slice-verdicts"), SLICE_DIMENSIONS);
1594
- return allDimensionsPass(state.named["slice-check"]) && allDimensionsPass(fresh, roster);
3350
+ if (!allDimensionsPass(state.named["slice-check"])) return false;
3351
+ return allDimensionsPass(fresh, roster) || citeDischargeCoversCurrentMap(state);
1595
3352
  };
3353
+ // The single authority the new `subplan-check` edge consults — the twin of
3354
+ // `sliceGatePasses`, but carrying no LLM-verdict roster or risk flags: the
3355
+ // `subplan-check` floor is the sole (deterministic) dimension on its channel.
3356
+ const subplanGatePasses = (state: RunView): boolean => allDimensionsPass(state.named["subplan-check"]);
1596
3357
  const planGatePasses = (state: RunView): boolean => {
1597
3358
  const fresh = freshVerdicts(state.named["plan-verdicts"], latestArtifactPath(state, "plans"));
1598
3359
  const roster = gateRoster(gateTier(state, "plan-verdicts"), PLAN_DIMENSIONS);
3360
+ const risks = planAuthoredRisks(state, "plans");
1599
3361
  return (
1600
- allDimensionsPass(state.named["plan-cite-check"]) && allDimensionsPass(fresh, roster) && allRiskFlagsPass(fresh)
3362
+ allDimensionsPass(state.named["plan-cite-check"]) &&
3363
+ allDimensionsPass(fresh, roster) &&
3364
+ allRiskFlagsPass(fresh, risks)
1601
3365
  );
1602
3366
  };
1603
3367
  const codeGatePasses = (state: RunView): boolean => {
1604
3368
  const fresh = freshVerdicts(state.named["code-verdicts"], latestArtifactPath(state, "plans"));
1605
3369
  const roster = gateRoster(gateTier(state, "code-verdicts"), PLAN_DIMENSIONS);
3370
+ const risks = planAuthoredRisks(state, "plans");
1606
3371
  return (
1607
- allDimensionsPass(state.named["code-cite-check"]) && allDimensionsPass(fresh, roster) && allRiskFlagsPass(fresh)
3372
+ allDimensionsPass(state.named["code-cite-check"]) &&
3373
+ allDimensionsPass(fresh, roster) &&
3374
+ allRiskFlagsPass(fresh, risks)
1608
3375
  );
1609
3376
  };
1610
3377
 
@@ -1632,12 +3399,15 @@ const confirmDue = (
1632
3399
  ): boolean => {
1633
3400
  const roster = new Set(gateRoster(gateTier(state, verdictChannel), dimensions));
1634
3401
  const fresh = freshVerdicts(state.named[verdictChannel], latestArtifactPath(state, channel));
3402
+ const risks = planAuthoredRisks(state, channel);
1635
3403
  const byDim = new Map<string, { blocking: boolean; count: number }>();
1636
3404
  for (const o of fresh) {
1637
- const v = o.data as { dimension?: string; pass?: boolean; severity?: string } | undefined;
3405
+ const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
1638
3406
  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);
3407
+ // anchorNitsOnly keeps this floor coherent with the other three
3408
+ // severity-fold consumers (gateTier/dimensionsToRegrade/allDimensionsPass).
3409
+ const floored = v.pass === true || v.severity === "low" || v.severity === "none" || anchorNitsOnly(v);
3410
+ const riskFail = verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
1641
3411
  byDim.set(v.dimension, {
1642
3412
  blocking: !floored || riskFail,
1643
3413
  count: (byDim.get(v.dimension)?.count ?? 0) + 1,
@@ -1723,10 +3493,99 @@ const COMMIT_BASELINE_PROMPT: PromptFn = ({ state }) => {
1723
3493
  return baseline ? `/skill:commit --baseline ${baseline}` : "/skill:commit";
1724
3494
  };
1725
3495
 
3496
+ // ===========================================================================
3497
+ // vet — goal → code-review → (blueprint → implement → implement-scope-check
3498
+ // → validate → loop) | commit. Examine existing changes; capture the
3499
+ // brief as a goal artifact, review, and if not approved blueprint a fix
3500
+ // plan, implement it, scope-check it, validate, and re-review. Loops
3501
+ // until approved. NOTE: defined here (after captureGoal /
3502
+ // implementScopeCheckVet) rather than beside polish because its graph
3503
+ // references those later-declared `const`s — the same precedent
3504
+ // buildWorkflow follows (defined after its deps).
3505
+ // ===========================================================================
3506
+
3507
+ const vetWorkflow = defineWorkflow({
3508
+ name: "vet",
3509
+ description:
3510
+ "Examine existing changes for approval; loop a fix cycle if not approved. Best when a diff already exists (yours or a teammate's) and you want a structured review with optional repair. Chain: goal → code-review → (blueprint → implement → implement-scope-check → reconcile → validate → loop) → commit.",
3511
+ start: "goal",
3512
+ stages: {
3513
+ // Capture the user's brief verbatim on its own `goal` channel, and snapshot
3514
+ // the run-start pre-existing-dirty paths (role "baseline"). Reuses build's
3515
+ // `captureGoal` verbatim — no new function — so the scope-check's
3516
+ // `reads: ["plans", "goal"]` resolves a baseline to subtract and the goal md
3517
+ // rides the channel face. `goal` as start publishes the goal-md as
3518
+ // `artifacts[0]`; `code-review` is a plain `produces()` SKILL stage (skill
3519
+ // defaults to its stage key "code-review"), so it inherits that goal-md PATH
3520
+ // as its rolling primary — the same pattern polish's code-review uses,
3521
+ // and the fallback Risk r1's note conceded "likely tolerates a goal-md-path
3522
+ // arg." The goal-md's CONTENT is the brief (`captureGoal` writes
3523
+ // `state.originalInput` into it), so the skill still reaches it.
3524
+ //
3525
+ // NOTE: the plan's r1 resolution made code-review PROMPT-dispatched to
3526
+ // preserve `state.originalInput` byte-for-byte, but that is REVERSED here: a
3527
+ // prompt stage carries NO skill, so the `code-review` contract no longer
3528
+ // attaches its `outputSchema` and the `blockers_count` gate would read
3529
+ // UNVALIDATED data (NaN-route risk, not just a warning). Keeping it a skill
3530
+ // stage keeps `skill="code-review"` → contract schema attaches → validated.
3531
+ goal: produces.script({ run: captureGoal }),
3532
+ "code-review": produces(),
3533
+ blueprint: produces(),
3534
+ // Dep-gated DAG variant: implement phases now
3535
+ // carry `id: phase-<n>` + `deps` derived from each phase's `files:` overlap /
3536
+ // authored `depends_on`, so the host cap may fan them out in parallel.
3537
+ implement: acts({ loop: IMPLEMENT_DAG_FANOUT, reads: ["plans"] }),
3538
+ // Deterministic scope floor (no LLM): the lane may write ONLY the union of
3539
+ // every plan iteration's declared `files:` (vet's loop pushes DISTINCT
3540
+ // non-superseding fix plans, so the declared set is the UNION over the full
3541
+ // `plans` history — `implementScopeCheckVet`). The `from` form suppresses
3542
+ // the READS_DATA outputSchema lint, so no schema is declared, matching
3543
+ // `slice-check`/`plan-cite-check`. Pass → validate; fail/missing → STOP
3544
+ // (no fallback), mirroring build's `validate → commit` route.
3545
+ "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheckVet }),
3546
+ // Deterministic post-implement reconciliation (no LLM) — the SAME `reconcile`
3547
+ // run-function as build (no vet twin): applies every `#### Reconciliation`
3548
+ // directive (write-restricted to test files) + re-runs every per-phase
3549
+ // `#### Automated Verification:` command, fail-soft. Pass ⇒ validate; fail/
3550
+ // missing ⇒ STOP (no fallback). `reads: ["plans"]` only — no run-start goal
3551
+ // baseline. The `from` form suppresses the READS_DATA outputSchema lint.
3552
+ reconcile: produces.script({ reads: ["plans"], run: reconcile }),
3553
+ validate: produces(),
3554
+ commit: acts({ outcome: gitCommitOutcome }),
3555
+ },
3556
+ edges: {
3557
+ goal: "code-review",
3558
+ // Same numeric gate as polish: zero remaining blockers → commit;
3559
+ // any blockers → loop a fix pass through blueprint. The `blockers_count`
3560
+ // field is sourced + validated from the code-review contract.
3561
+ "code-review": gate("blockers_count", { blueprint: gt(0), commit: eq(0) }, "commit"),
3562
+ blueprint: "implement",
3563
+ // Scope-check inserts BEFORE validate, INSIDE the review-fix loop. Pass →
3564
+ // validate; fail/missing terminates (STOP, no fallback). Byte-for-byte
3565
+ // build's route.
3566
+ implement: "implement-scope-check",
3567
+ // Scope-check still gates onward, but now into `reconcile` (not validate):
3568
+ // the coherence backstop runs after the write-set is proven. Pass ⇒
3569
+ // reconcile; fail/missing ⇒ STOP (no fallback).
3570
+ "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
3571
+ // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target /
3572
+ // absent find / failed AV command) or a missing verdict ⇒ STOP (no fix arm —
3573
+ // a reconciliation failure is plan-vs-tree drift the agent reconciles manually).
3574
+ reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
3575
+ // Backward edge: validate → code-review creates the review-fix loop —
3576
+ // UNCHANGED. The scope-check inserts before validate, so a failing scope
3577
+ // verdict halts before re-review, and a passing one flows into validate and
3578
+ // back to code-review exactly as today. Bounded by the runner's default
3579
+ // maxBackwardJumps (2 → at most 3 review iterations).
3580
+ validate: "code-review",
3581
+ commit: "stop",
3582
+ },
3583
+ });
3584
+
1726
3585
  const buildWorkflow = defineWorkflow({
1727
3586
  name: "build",
1728
3587
  description:
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.",
3588
+ "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 → implement-scope-check → reconcile → validate → commit. Research-led; three automated gates plus one human design checkpoint, before design, before code, and after the splice.",
1730
3589
  start: "goal",
1731
3590
  stages: {
1732
3591
  // The user's brief, verbatim, on its own channel — the judgment seams
@@ -1781,6 +3640,13 @@ const buildWorkflow = defineWorkflow({
1781
3640
  loop: SYNTH_CLUSTER_FANOUT,
1782
3641
  outcome: rpivBucketOutcome("subplans"),
1783
3642
  }),
3643
+ // Deterministic cluster-coverage floor between the cluster fanout and the
3644
+ // root merge — the subplan twin of `slice-check`. Reconciles dispatched
3645
+ // `_cluster-<k>` sub-plans against the slice map's promised cluster count +
3646
+ // `sources:` design coverage BEFORE the root merge fans them in, so a lost
3647
+ // or clobbered cluster fails structurally and routes back to `subplan`
3648
+ // rather than silently dropping slices from the merged plan.
3649
+ "subplan-check": produces.script({ reads: [fanin("subplans"), "slices"], run: subplanCoverageCheck }),
1784
3650
  // The root merge reads `research` (threaded as `--research` so cross-slice
1785
3651
  // constraints reach the merge directly, not only via each subplan's
1786
3652
  // refraction) alongside the cluster sub-plans it fans in.
@@ -1797,6 +3663,15 @@ const buildWorkflow = defineWorkflow({
1797
3663
  // --context; `goal` so completeness/correctness anchor on the brief.
1798
3664
  reads: ["plans", "research", "goal"],
1799
3665
  }),
3666
+ // Stamp the duty demotion onto the graded verdicts as legible on-disk data
3667
+ // (a `risk_duty_demotions` array written in place onto each demoted
3668
+ // verdict JSON) one hop BEFORE the gate routes — the gate's route lives on
3669
+ // `plan-demote` so this write-back lands before confirm/`--prior`/amend
3670
+ // read the verdict. Reads `plans` (the plan-authored risk flags) and fans
3671
+ // in the verdicts it just graded. Gate outcomes are unchanged: every fold
3672
+ // consults in-memory `state.named` via `rulingEffectivePass`, never the
3673
+ // rewritten file (the write-back is an additive, read-only signal).
3674
+ "plan-demote": produces.script({ reads: ["plans", fanin("plan-verdicts")], run: planDemote }),
1800
3675
  // One independent second judgment on the blocking dimensions before they
1801
3676
  // buy a fix round (see `confirmDue`). Same panel machinery, same verdict
1802
3677
  // channel — its OWN stage name so a stronger judge model can be pinned to
@@ -1810,8 +3685,23 @@ const buildWorkflow = defineWorkflow({
1810
3685
  "plan-fix": produces({
1811
3686
  skill: "amend",
1812
3687
  outcome: rpivBucketOutcome("plans"),
1813
- reads: ["plans", fanin("plan-verdicts"), fanin("plan-cite-check")],
3688
+ // Lineage threads for completeness-class repairs: `goal` (verbatim brief),
3689
+ // `research` (architecture/precedent findings), `subplans` (per-cluster
3690
+ // sub-plans). `goal`/`research` mirror `plan-confirm`'s reads; `subplans`
3691
+ // mirrors `plan`'s own `reads: ["research", fanin("subplans")]`. `subplans`
3692
+ // is plan-fix-ONLY — by the code gate the plan's completeness is settled, so
3693
+ // code-fix repairs code-shape defects and threads no subplans.
3694
+ reads: ["plans", fanin("plan-verdicts"), fanin("plan-cite-check"), "goal", "research", fanin("subplans")],
1814
3695
  }),
3696
+ // Snapshot the graded plan BEFORE plan-fix amends it — one deterministic
3697
+ // hop inside the existing fix loop (plan-grade/plan-confirm → plan-snapshot
3698
+ // → plan-fix). The re-grade reads the prior off the snapshot's OWN channel
3699
+ // (`plan-snapshot`) to decide whether the amend was surgical (re-grade only
3700
+ // the failing dims) or broad (re-grade the full roster). `produces.script`
3701
+ // rides its stage-name channel, so this publishes to `plan-snapshot`, NOT
3702
+ // `plans` — `latestFsArtifact(state, "plans")` still resolves to the real
3703
+ // (amended) plan.
3704
+ "plan-snapshot": produces.script({ reads: ["plans"], run: planSnapshot }),
1815
3705
  // Elaborate implement-ready code into each phase in parallel (fanout),
1816
3706
  // deterministically splice it back into the plan (code-splice), then
1817
3707
  // re-grade the now code-bearing plan — guarding the blind-splice risk.
@@ -1842,6 +3732,10 @@ const buildWorkflow = defineWorkflow({
1842
3732
  // --context; `goal` so completeness/correctness anchor on the brief.
1843
3733
  reads: ["plans", "research", "goal"],
1844
3734
  }),
3735
+ // The code-gate twin of `plan-demote`: stamp the duty demotion onto the
3736
+ // code-graded verdicts (re-grading `plans` on `code-verdicts`) one hop
3737
+ // before the code gate routes (`code-demote` owns the route body).
3738
+ "code-demote": produces.script({ reads: ["plans", fanin("code-verdicts")], run: codeDemote }),
1845
3739
  // Repair arm for the code gate. Surgical `amend` over the SAME code-bearing
1846
3740
  // plan from the code verdicts — NOT a blind re-elaborate: `elaborate` never
1847
3741
  // sees the findings and can only rewrite a phase's code body, so it cannot fix
@@ -1862,23 +3756,54 @@ const buildWorkflow = defineWorkflow({
1862
3756
  "code-fix": produces({
1863
3757
  skill: "amend",
1864
3758
  outcome: rpivBucketOutcome("plans"),
1865
- reads: ["plans", fanin("code-verdicts"), fanin("code-cite-check")],
3759
+ // Lineage threads for code-shape repairs: `goal`/`research` give amend the
3760
+ // brief + architecture context (mirroring `code-confirm`'s reads). NO
3761
+ // `subplans` — the plan's completeness was settled at the plan gate, so the
3762
+ // code arm only repairs code-shape defects (fabricated edit anchors, drifted
3763
+ // `file:line` citations, cross-phase naming collisions).
3764
+ reads: ["plans", fanin("code-verdicts"), fanin("code-cite-check"), "goal", "research"],
1866
3765
  }),
1867
- implement: acts({ loop: IMPLEMENT_PHASE_FANOUT, reads: ["plans"] }),
3766
+ // Snapshot the graded plan BEFORE code-fix amends it — the code-gate twin
3767
+ // of `plan-snapshot` (code-grade/code-confirm → code-snapshot → code-fix),
3768
+ // publishing the prior on the `code-snapshot` channel.
3769
+ "code-snapshot": produces.script({ reads: ["plans"], run: codeSnapshot }),
3770
+ implement: acts({ loop: IMPLEMENT_DAG_FANOUT, reads: ["plans"] }),
3771
+ // Lane-level scope floor — the structural backstop beneath the quality
3772
+ // gates. After the (now concurrent) implement lane lands, judge the working
3773
+ // tree's dirty set against the plan's declared write-set: any undeclared
3774
+ // write is a phase that escaped the upstream write-scope discipline and
3775
+ // raced on a sibling's in-flight edit. Fail ⇒ STOP (no fix arm). The `from`
3776
+ // form suppresses the READS_DATA outputSchema lint, so no schema is declared
3777
+ // (matching slice-check/plan-cite-check). Reads `goal` for the run-start
3778
+ // baseline that subtracts pre-existing dirt.
3779
+ "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheck }),
3780
+ // Deterministic post-implement reconciliation (no LLM): applies every
3781
+ // `#### Reconciliation` directive (find→replace, write-restricted to test
3782
+ // files) and re-runs every per-phase `#### Automated Verification:`
3783
+ // command, fail-soft — a coherence backstop the parallel implement lane
3784
+ // needs (a phase's correct change can invalidate a sibling's test, and the
3785
+ // combined tree can break in ways no single phase's checks surface). Pass ⇒
3786
+ // validate; fail/missing ⇒ STOP (no fallback). `reads: ["plans"]` only — no
3787
+ // run-start goal baseline (the scope floor already proved the write-set). The
3788
+ // `from` form suppresses the READS_DATA outputSchema lint.
3789
+ reconcile: produces.script({ reads: ["plans"], run: reconcile }),
1868
3790
  validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
1869
3791
  commit: acts({ prompt: COMMIT_BASELINE_PROMPT, outcome: gitCommitOutcome }),
1870
3792
  },
1871
3793
  edges: {
1872
3794
  goal: "research",
1873
3795
  // 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.
3796
+ // "Fresh" input is a research path).
1875
3797
  research: "slice",
1876
3798
  slice: "slice-check",
1877
3799
  // Skip the design-readiness re-grade when the gate is already satisfied — after
1878
3800
  // a `slice-fix` that only cleared the deterministic structure floor (the common
1879
3801
  // 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`.
3802
+ // already passes, so re-grading would only re-roll a flappy judgment. Also
3803
+ // skips after a fix for a `remedy: "cite"` fail once `slice-check` has
3804
+ // deterministically verified the demanded seeds landed on a structurally
3805
+ // unchanged map (the `citeDischarged` stamp — see `citeRemedyDischarged`).
3806
+ // First pass (no verdict yet) ⇒ not satisfied ⇒ into `slice-grade`.
1882
3807
  "slice-check": defineRoute(
1883
3808
  ["slice-design", "slice-grade"],
1884
3809
  ({ state }) => (sliceGatePasses(state) ? "slice-design" : "slice-grade"),
@@ -1895,7 +3820,22 @@ const buildWorkflow = defineWorkflow({
1895
3820
  // Design fanout → consolidated human checkpoint → hierarchical synthesis.
1896
3821
  "slice-design": "design-review",
1897
3822
  "design-review": "subplan",
1898
- subplan: "plan",
3823
+ // Route the cluster fanout through the deterministic coverage floor before
3824
+ // the root merge — the twin of `slice → slice-check`. A pass folds straight
3825
+ // to `plan`; a lost/clobbered cluster routes the backward edge to `subplan`,
3826
+ // bounded by the runner's maxBackwardJumps.
3827
+ subplan: "subplan-check",
3828
+ // Subplan coverage gate. Pass ⇒ root merge. A fail (lost cluster, clobbered
3829
+ // ordinal, tokenless basename, or a slice design absent from every sources:)
3830
+ // routes the backward edge to `subplan` — re-dispatch the cluster fanout,
3831
+ // which re-supplies each cluster's '--cluster <k>'. Bounded by the runner's
3832
+ // maxBackwardJumps. `readsData: false` — the route consults only the
3833
+ // deterministic verdict channel (mirrors the slice-check/plan-cite-check routes).
3834
+ "subplan-check": defineRoute(
3835
+ ["plan", "subplan"],
3836
+ ({ state }) => (subplanGatePasses(state) ? "plan" : "subplan"),
3837
+ { readsData: false },
3838
+ ),
1899
3839
  plan: "plan-cite-check",
1900
3840
  // Skip the quality re-grade straight to `code` when the gate is already
1901
3841
  // satisfied — a `plan-fix` that only cleared the citation floor leaves every
@@ -1908,28 +3848,39 @@ const buildWorkflow = defineWorkflow({
1908
3848
  ({ state }) => (planGatePasses(state) ? "code" : "plan-grade"),
1909
3849
  { readsData: false },
1910
3850
  ),
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"],
3851
+ // Quality gate BEFORE any code. The grade runs at `plan-grade`; the route
3852
+ // lives one hop later on `plan-demote` so the duty-demotion write-back
3853
+ // lands on the verdict JSON BEFORE this fold consults the downstream
3854
+ // readers. `plan-grade` is now a simple always-hop edge to `plan-demote`;
3855
+ // the route body below is the verbatim logic that used to live here.
3856
+ "plan-grade": "plan-demote",
3857
+ // Pass ⇒ code. A dimension's FIRST blocking verdict ⇒ plan-confirm (one
3858
+ // independent second judgment — see `confirmDue`); a confirmed blocker, or
3859
+ // a failure with no dimension blocking (the citation floor alone is red) ⇒
3860
+ // plan-fix, looping back THROUGH the citation floor so the amended plan
3861
+ // re-verifies. Route logic unchanged — merely shifted one hop later so the
3862
+ // demote write-back precedes it.
3863
+ "plan-demote": defineRoute(
3864
+ ["code", "plan-confirm", "plan-snapshot"],
1919
3865
  ({ state }) =>
1920
3866
  planGatePasses(state)
1921
3867
  ? "code"
1922
3868
  : confirmDue(state, "plans", "plan-verdicts", PLAN_DIMENSIONS)
1923
3869
  ? "plan-confirm"
1924
- : "plan-fix",
3870
+ : "plan-snapshot",
1925
3871
  { readsData: false },
1926
3872
  ),
1927
3873
  // After the second judgment the gate re-folds on the latest verdicts: a
1928
3874
  // confirming pass overwrote the flap and clears the gate; a confirming
1929
3875
  // 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
- }),
3876
+ "plan-confirm": defineRoute(
3877
+ ["code", "plan-snapshot"],
3878
+ ({ state }) => (planGatePasses(state) ? "code" : "plan-snapshot"),
3879
+ { readsData: false },
3880
+ ),
3881
+ // The snapshot is one deterministic hop between the grade/confirm route and
3882
+ // the fix — no new backward edge, inside the existing fix loop.
3883
+ "plan-snapshot": "plan-fix",
1933
3884
  "plan-fix": "plan-cite-check",
1934
3885
  code: "code-splice",
1935
3886
  "code-splice": "code-cite-check",
@@ -1941,30 +3892,53 @@ const buildWorkflow = defineWorkflow({
1941
3892
  ({ state }) => (codeGatePasses(state) ? "implement" : "code-grade"),
1942
3893
  { readsData: false },
1943
3894
  ),
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"],
3895
+ // Re-grade the code-bearing plan at `code-grade`; the route lives one hop
3896
+ // later on `code-demote` (the twin of the plan gate's split) so the
3897
+ // duty-demotion write-back lands before this fold. `code-grade` is now a
3898
+ // simple always-hop edge to `code-demote`; the route body below is verbatim.
3899
+ "code-grade": "code-demote",
3900
+ // Pass ⇒ implement. A first blocking verdict ⇒ code-confirm (the plan
3901
+ // gate's confirm contract, on the code-verdicts channel); a confirmed
3902
+ // blocker or cite-floor-only failure ⇒ code-fix. Routes to `code-fix`, NOT
3903
+ // back to `code`: the gate fails on plan-text defects (edit anchors, line
3904
+ // citations, naming) that a per-phase code rewrite cannot reach, so the
3905
+ // surgical arm is the one with authority over them. Route logic unchanged —
3906
+ // merely shifted one hop later. Bounded by the runner's maxBackwardJumps.
3907
+ "code-demote": defineRoute(
3908
+ ["implement", "code-confirm", "code-snapshot"],
1953
3909
  ({ state }) =>
1954
3910
  codeGatePasses(state)
1955
3911
  ? "implement"
1956
3912
  : confirmDue(state, "plans", "code-verdicts", PLAN_DIMENSIONS)
1957
3913
  ? "code-confirm"
1958
- : "code-fix",
3914
+ : "code-snapshot",
1959
3915
  { readsData: false },
1960
3916
  ),
1961
3917
  "code-confirm": defineRoute(
1962
- ["implement", "code-fix"],
1963
- ({ state }) => (codeGatePasses(state) ? "implement" : "code-fix"),
3918
+ ["implement", "code-snapshot"],
3919
+ ({ state }) => (codeGatePasses(state) ? "implement" : "code-snapshot"),
1964
3920
  { readsData: false },
1965
3921
  ),
3922
+ // The code-gate twin of `plan-snapshot → plan-fix`.
3923
+ "code-snapshot": "code-fix",
1966
3924
  "code-fix": "code-cite-check",
1967
- implement: "validate",
3925
+ implement: "implement-scope-check",
3926
+ // Lane-level scope floor gate. Pass ⇒ reconcile (the coherence backstop
3927
+ // runs after the write-set is proven). A `fail` (undeclared write) or a
3928
+ // missing verdict routes to STOP — no fix arm, because a scope violation is
3929
+ // plan-vs-tree drift the agent must reconcile manually (a phase wrote
3930
+ // outside its declared set), not a defect an auto-fix loop can repair. Safe
3931
+ // by construction: the sole path onward is an explicit `verdict: "pass"`.
3932
+ // Sourced from the scope-check's published verdict channel via the `from`
3933
+ // form (the stage key for an outcome-less `produces.script`, per
3934
+ // `resolvePublishName`), which suppresses the READS_DATA outputSchema lint.
3935
+ "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
3936
+ // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target
3937
+ // / absent find / failed AV command) or a missing verdict ⇒ STOP (no fix
3938
+ // arm — a reconciliation failure is plan-vs-tree drift the agent reconciles
3939
+ // manually). Safe by construction: the sole path onward is an explicit
3940
+ // `verdict: "pass"`. Sourced from the reconcile channel via the `from` form.
3941
+ reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
1968
3942
  // Gate commit on validate's own verdict — an unconditional `validate → commit`
1969
3943
  // let a `verdict: fail` (incomplete goal coverage) commit anyway. `match` with
1970
3944
  // no fallback commits ONLY on an explicit `verdict: "pass"`; every other value
@@ -1984,10 +3958,7 @@ const buildWorkflow = defineWorkflow({
1984
3958
  // Exports
1985
3959
  // ===========================================================================
1986
3960
 
1987
- export const builtInWorkflows: readonly Workflow[] = [
1988
- shipWorkflow,
1989
- archWorkflow,
1990
- vetWorkflow,
1991
- polishWorkflow,
1992
- buildWorkflow,
1993
- ];
3961
+ // Position 0 is load-bearing: `build` is the default `/wf` workflow when no
3962
+ // project/user config sets one (resolve-default.ts resolves
3963
+ // `Map.keys().next().value`), so it MUST stay first in this array.
3964
+ export const builtInWorkflows: readonly Workflow[] = [buildWorkflow, vetWorkflow, polishWorkflow];