@juicesharp/rpiv-pi 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +121 -271
  2. package/agents/scope-tracer.md +1 -1
  3. package/docs/agents.md +70 -0
  4. package/docs/architecture.md +136 -0
  5. package/docs/lanes.md +82 -0
  6. package/docs/models-config.md +200 -0
  7. package/docs/skills.md +86 -0
  8. package/docs/workflows.md +109 -0
  9. package/extensions/rpiv-core/bash-timeout.ts +16 -0
  10. package/extensions/rpiv-core/built-in-workflows.ts +2363 -278
  11. package/extensions/rpiv-core/guidance.ts +35 -19
  12. package/extensions/rpiv-core/lane-list.ts +5 -29
  13. package/extensions/rpiv-core/lane-progress.ts +5 -76
  14. package/extensions/rpiv-core/models-config.ts +35 -0
  15. package/extensions/rpiv-core/run-lane-registry.ts +0 -65
  16. package/extensions/rpiv-core/sdk-workflow-host.ts +4 -0
  17. package/extensions/rpiv-core/workflow-execution-host.ts +24 -7
  18. package/package.json +7 -3
  19. package/skills/amend/SKILL.md +7 -3
  20. package/skills/annotate-guidance/SKILL.md +2 -3
  21. package/skills/annotate-inline/SKILL.md +1 -3
  22. package/skills/architecture-review/SKILL.md +5 -4
  23. package/skills/blueprint/SKILL.md +14 -6
  24. package/skills/changelog/SKILL.md +1 -0
  25. package/skills/commit/SKILL.md +1 -0
  26. package/skills/design/SKILL.md +8 -5
  27. package/skills/design-review/SKILL.md +2 -1
  28. package/skills/design-slice/SKILL.md +2 -1
  29. package/skills/discover/SKILL.md +3 -4
  30. package/skills/elaborate/SKILL.md +17 -5
  31. package/skills/elaborate/_helpers/validate-workflow-invariant.mjs +88 -0
  32. package/skills/explore/SKILL.md +1 -0
  33. package/skills/frontend-design/SKILL.md +1 -0
  34. package/skills/grade/SKILL.md +20 -3
  35. package/skills/implement/SKILL.md +10 -2
  36. package/skills/plan/SKILL.md +10 -6
  37. package/skills/research/SKILL.md +14 -12
  38. package/skills/resume-handoff/SKILL.md +2 -1
  39. package/skills/revise/SKILL.md +1 -0
  40. package/skills/slice/SKILL.md +3 -2
  41. package/skills/synthesize/SKILL.md +16 -7
  42. package/skills/validate/SKILL.md +2 -1
@@ -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,
@@ -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,6 +218,103 @@ 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
@@ -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,16 +339,87 @@ 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
+ * `implement`'s serial twin of `FRONTMATTER_PHASE_FANOUT`, for plans that do NOT
343
+ * declare a per-phase write set. `concurrency: 1` serializes the units in the
344
+ * plan's (topological) phase order — the safe model when a fanout's units share a
345
+ * working tree AND their write-sets are unknown (so the scheduler cannot derive
346
+ * dep edges and the lane has no scope floor to guard it). `elaborate` keeps the
347
+ * parallel fanout: it writes ISOLATED per-phase docs.
348
+ *
349
+ * When a plan DOES declare per-phase `files:`, prefer `IMPLEMENT_DAG_FANOUT`:
350
+ * its `implementPhaseDeps` derives dep edges from write-set overlap (units with
351
+ * disjoint `files:` run concurrently; a `files:`-less phase conflicts with every
352
+ * lower phase, degrading to the full chain — one phase per wave — so the
353
+ * all-`files:`-less plan stays serial at any cap), and a lane-level scope floor
354
+ * guards the declared set. Used today by ship/arch (vet moves to the DAG variant
355
+ * once it carries `files:`); `IMPLEMENT_DAG_FANOUT`'s `concurrency: 1` is dropped
356
+ * once build's scope floor lands.
231
357
  */
232
358
  const IMPLEMENT_PHASE_FANOUT = { ...FRONTMATTER_PHASE_FANOUT, concurrency: 1 };
233
359
 
360
+ /**
361
+ * Derive the directed `deps` edges for ONE implement phase under the dep-gated
362
+ * DAG fanout (`IMPLEMENT_DAG_FANOUT`). Edges point strictly downward (toward
363
+ * LOWER phase numbers), so the graph is acyclic by construction. Two clauses:
364
+ *
365
+ * - clause A (self declares a `files:` write-set): `self` depends on every
366
+ * LOWER phase whose declared `files:` shares ≥1 entry, UNIONED with `self`'s
367
+ * explicit `depends_on` (semantic ordering not visible in `files:`).
368
+ * - clause B (self declares NO `files:`): `self` conflicts with EVERY lower
369
+ * phase → full chain (a write-set-less phase's writes are unknown, so it
370
+ * cannot be proven independent of anything below it). This is the
371
+ * empty-set degradation that keeps a legacy / `files:`-less plan serial at
372
+ * any cap (one phase per Kahn wave).
373
+ *
374
+ * Returns `phase-<n>` unit ids, sorted ascending. Reads `phaseFiles`
375
+ * and `phaseDeps` — both defined later textually, but only inside this
376
+ * runtime closure, so no TDZ (same pattern as `sliceDeps`).
377
+ */
378
+ const implementPhaseDeps = (records: readonly PhaseRecord[], self: PhaseRecord): string[] => {
379
+ const selfFiles = phaseFiles(self.entry);
380
+ const explicit = phaseDeps(self.entry);
381
+ const ns = new Set<number>();
382
+ for (const e of explicit) if (e < self.n) ns.add(e);
383
+ if (selfFiles.length === 0) {
384
+ // clause B — unknown write-set ⇒ conflict with every lower phase.
385
+ for (const r of records) if (r.n < self.n) ns.add(r.n);
386
+ } else {
387
+ // clause A — overlap on ≥1 declared write path.
388
+ for (const r of records) {
389
+ if (r.n >= self.n) continue;
390
+ const rFiles = phaseFiles(r.entry);
391
+ if (rFiles.some((f) => selfFiles.includes(f))) ns.add(r.n);
392
+ }
393
+ }
394
+ return [...ns].sort((a, b) => a - b).map((n) => `phase-${n}`);
395
+ };
396
+
397
+ /**
398
+ * Dep-gated DAG variant of `FRONTMATTER_PHASE_FANOUT` — `implement`'s twin that
399
+ * emits per-phase `id`/`deps` edges so the wave scheduler orders phases by their
400
+ * declared write-set overlap + explicit `depends_on`. The spread idiom inherits
401
+ * `source`/`unit`/`max`/`onCap`/`result`/`kind` verbatim from the base; the new
402
+ * `units` closure emits the SAME `prompt`/`label` strings AND adds
403
+ * `id: \`phase-${r.n}\`` + `deps: implementPhaseDeps(records, r)`. NO
404
+ * `depArtifactFlag` — implement phases feed each other through the working tree
405
+ * (not published artifacts), so `deps` drive ONLY wave ordering. `concurrency: 1`
406
+ * keeps it serial/inert here; the host cap is not inherited.
407
+ */
408
+ const IMPLEMENT_DAG_FANOUT = {
409
+ ...FRONTMATTER_PHASE_FANOUT,
410
+ units: ({ state, cwd }: FanoutContext) => {
411
+ const read = readPlanPhaseRecords(state, cwd, "IMPLEMENT_DAG_FANOUT");
412
+ if (!read) return [];
413
+ const { records, promptPath } = read;
414
+ return records.map((r) => ({
415
+ prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
416
+ label: `phase ${r.index + 1}/${r.total}`,
417
+ id: `phase-${r.n}`,
418
+ deps: implementPhaseDeps(records, r),
419
+ }));
420
+ },
421
+ };
422
+
234
423
  // ===========================================================================
235
424
  // ship — blueprint → implement → validate → commit
236
425
  // ===========================================================================
@@ -291,41 +480,6 @@ const archWorkflow = defineWorkflow({
291
480
  },
292
481
  });
293
482
 
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
- // ===========================================================================
299
-
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",
326
- },
327
- });
328
-
329
483
  // ===========================================================================
330
484
  // polish — architecture-review → blueprint (iterate, per review phase) →
331
485
  // implement → validate → code-review → (blueprint loop) | commit
@@ -375,6 +529,17 @@ const phaseDeps = (entry: unknown): number[] => {
375
529
  return Array.isArray(raw) ? raw.filter((d): d is number => typeof d === "number") : [];
376
530
  };
377
531
 
532
+ /** The repo-root-relative paths a phase entry declares it creates/edits (its
533
+ * `files:` array — `[]` when absent). The open-schema twin of `phaseDeps`,
534
+ * read straight off `PhaseRecord.entry` so `planPhaseRecords` preserves the new
535
+ * key unchanged. Consumed by the plan-time coverage floor
536
+ * (`verifyPhaseFilesCoverage`) and, in a later phase, the dep-gated implement
537
+ * fanout (`implementPhaseDeps`). */
538
+ const phaseFiles = (entry: unknown): string[] => {
539
+ const raw = (entry as { files?: unknown } | undefined)?.files;
540
+ return Array.isArray(raw) ? raw.filter((f): f is string => typeof f === "string") : [];
541
+ };
542
+
378
543
  /**
379
544
  * Per-review-phase blueprint generator (the `iterate` dual of
380
545
  * FRONTMATTER_PHASE_FANOUT). One blueprint pass per review phase, enumerating the
@@ -652,19 +817,38 @@ const captureGoal = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
652
817
  };
653
818
  };
654
819
 
820
+ /** Parse `git status --porcelain`/`--short` output into dirty paths. Strips the
821
+ * 2-char `XY` status prefix and resolves rename targets (`XY old -> new` → `new`),
822
+ * so the two output forms (`--porcelain`, `--short`) normalize identically. A
823
+ * porcelain line is always `XY <path>` or `XY <old> -> <new>`; blank lines drop. */
824
+ const parseGitStatusPaths = (out: string): string[] =>
825
+ out
826
+ .split("\n")
827
+ .filter((l) => l.trim() !== "")
828
+ .map((l) => {
829
+ const rest = l.slice(3).trim();
830
+ const arrow = rest.indexOf(" -> ");
831
+ return arrow >= 0 ? rest.slice(arrow + 4).trim() : rest;
832
+ });
833
+
655
834
  /** Record the paths dirty before the run to `rel` (best-effort; empty on any git failure). */
656
835
  const writeCommitBaseline = (cwd: string, rel: string): void => {
657
836
  let paths: string[] = [];
658
837
  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
- });
838
+ // stdio: stderr ignored — without this, git's "fatal: not a git repository"
839
+ // leaks to the parent's stderr even though the catch treats it as a
840
+ // supported silent degrade (best-effort baseline, empty on failure).
841
+ // -uall: git collapses an untracked directory to one `dir/` entry by
842
+ // default, so a phase's brand-new files under a new directory would never
843
+ // string-match their `files:` declarations at the scope floor. Enumerate
844
+ // every file; the baseline and both scope checks MUST share this flag or
845
+ // their path universes diverge.
846
+ const out = execFileSync("git", ["status", "--short", "--untracked-files=all"], {
847
+ cwd,
848
+ encoding: "utf-8",
849
+ stdio: ["ignore", "pipe", "ignore"],
850
+ });
851
+ paths = parseGitStatusPaths(out);
668
852
  } catch {
669
853
  paths = [];
670
854
  }
@@ -678,6 +862,89 @@ const goalBaselinePath = (state: RunView): string | undefined => {
678
862
  return a ? handleToString(a.handle) : undefined;
679
863
  };
680
864
 
865
+ /**
866
+ * Read the run-start pre-existing-dirty baseline off the goal channel's
867
+ * "baseline" artifact: the `{ paths }` JSON the baseline writer records. Best-
868
+ * effort — `[]` on no path (no `goal` stage), an unreadable file, or a `paths`
869
+ * value that isn't a string array, so the scope floor degrades to baseline-less
870
+ * (nothing subtracted) rather than throwing.
871
+ */
872
+ const readGoalBaseline = (path: string | undefined, cwd: string): string[] => {
873
+ if (!path) return [];
874
+ try {
875
+ const parsed = JSON.parse(readArtifactFile(path, cwd)) as { paths?: unknown };
876
+ const p = parsed.paths;
877
+ return Array.isArray(p) ? p.filter((x): x is string => typeof x === "string") : [];
878
+ } catch {
879
+ return [];
880
+ }
881
+ };
882
+
883
+ /**
884
+ * Current dirty-path set via `git status --porcelain` (rename targets resolved by
885
+ * the shared parser). Best-effort — `[]` on a non-repo / git-missing tree (the
886
+ * scope floor degrades to unguarded rather than failing a non-repo run; the
887
+ * catch treats that as a supported silent degrade). stdio: stderr is ignored,
888
+ * otherwise git's "fatal: not a git repository" leaks to the parent's stderr
889
+ * despite the catch. `-uall` enumerates untracked files individually (a collapsed
890
+ * `newdir/` entry can never string-match a declared `files:` path) — the
891
+ * baseline writer and both scope checks MUST share this flag or their path
892
+ * universes diverge.
893
+ */
894
+ const gitDirtyPaths = (cwd: string): string[] => {
895
+ try {
896
+ const out = execFileSync("git", ["status", "--porcelain", "--untracked-files=all"], {
897
+ cwd,
898
+ encoding: "utf-8",
899
+ stdio: ["ignore", "pipe", "ignore"],
900
+ });
901
+ return parseGitStatusPaths(out);
902
+ } catch {
903
+ return [];
904
+ }
905
+ };
906
+
907
+ /** Paths under these run-bookkeeping trees are NEVER a scope violation — the run
908
+ * legitimately writes its artifacts/notes/trails here regardless of phase scope. */
909
+ const SCOPE_BOOKKEEPING_DIRS: ReadonlySet<string> = new Set([".rpiv", "thoughts"]);
910
+
911
+ /**
912
+ * The lane-level scope floor's pure core. Returns the dirty paths that are NOT
913
+ * explained by the run's declared write-set: a path is excess when it is outside
914
+ * `declared`, was NOT dirty at the run-start `baseline`, and is NOT under a
915
+ * bookkeeping tree (`.rpiv/`, `thoughts/`). The `implement` lane declared-set is
916
+ * the union of its plan's per-phase `files:`; `validate`'s whole-repo
917
+ * build/test writes are owned by a later stage, never by a phase.
918
+ *
919
+ * Empty `declared` ⇒ `[]` (degradation): a `files:`-less plan is serial-by-
920
+ * construction under the DAG fanout's missing-`files:` clause (full dep chain ⇒
921
+ * one phase per wave), so there is no concurrent sibling to corrupt and nothing
922
+ * to guard — the floor returns no excess and never false-fails a legacy plan.
923
+ * `validate`'s whole-repo writes are out of scope here regardless: they belong
924
+ * to `validate`, which runs AFTER this gate, so the lane's dirty set never
925
+ * carries them at the scope-check's read time.
926
+ *
927
+ * This is deliberately LANE-level, not per-phase: under concurrency, a dirty
928
+ * path cannot be attributed to the specific phase that wrote it, so per-phase
929
+ * enforcement would be unsound. The per-phase discipline is enforced upstream
930
+ * by the plan-authoring write-scope rule + the plan-time coverage floor;
931
+ * this lane floor is the structural backstop that catches a phase that escaped
932
+ * upstream discipline. Returns one entry per excess path.
933
+ */
934
+ const scopeExcess = (dirty: readonly string[], baseline: readonly string[], declared: readonly string[]): string[] => {
935
+ if (declared.length === 0) return [];
936
+ const declaredSet = new Set(declared);
937
+ const baselineSet = new Set(baseline);
938
+ const excess: string[] = [];
939
+ for (const path of dirty) {
940
+ if (declaredSet.has(path) || baselineSet.has(path)) continue;
941
+ const top = path.split("/")[0];
942
+ if (SCOPE_BOOKKEEPING_DIRS.has(top)) continue;
943
+ excess.push(path);
944
+ }
945
+ return excess;
946
+ };
947
+
681
948
  /**
682
949
  * `goal` displaces `research` as build's start stage, and ONLY the start stage
683
950
  * receives `originalInput` as its skill arg (`stageEntryArgs` case 1) — a plain
@@ -880,6 +1147,10 @@ const sliceCovers = (entry: Record<string, unknown>): string[] => {
880
1147
 
881
1148
  /** The verdict directory the deterministic checks and the LLM grade panel share. */
882
1149
  const VERDICT_DIR = ".rpiv/artifacts/verdicts";
1150
+ /** Binary verdict score: a clean pass. The gate keys off `severity`, never this number. */
1151
+ const VERDICT_PASS_SCORE = 100;
1152
+ /** Binary verdict score: at least one finding. The gate keys off `severity`, never this number. */
1153
+ const VERDICT_FAIL_SCORE = 0;
883
1154
 
884
1155
  /**
885
1156
  * A `path:line` (or `path:line-line`) citation in an artifact's prose. Requires a
@@ -915,6 +1186,12 @@ const CITATION_WALK_SKIP: ReadonlySet<string> = new Set(["node_modules", ".git",
915
1186
  /** Backstop so a pathological tree can't stall the deterministic cite floor. */
916
1187
  const CITATION_WALK_FILE_CAP = 50_000;
917
1188
 
1189
+ /** The lazily-built basename → absolute-path(s) index backing the suffix
1190
+ * fallback in `resolveCitationPath`. `truncated` marks a partial walk past
1191
+ * `CITATION_WALK_FILE_CAP`, which disables the fallback (uniqueness
1192
+ * untrustworthy). */
1193
+ type BasenameIndex = { index: Map<string, string[]>; truncated: boolean };
1194
+
918
1195
  /**
919
1196
  * Index every source file's basename → its absolute path(s) under `cwd` — the
920
1197
  * candidate pool behind the suffix fallback in `verifyCitations`. The generative
@@ -928,7 +1205,7 @@ const CITATION_WALK_FILE_CAP = 50_000;
928
1205
  * vendored/generated trees so a citation never resolves to a build copy or a
929
1206
  * prior artifact. Bounded by the file cap.
930
1207
  */
931
- const buildBasenameIndex = (cwd: string): { index: Map<string, string[]>; truncated: boolean } => {
1208
+ const buildBasenameIndex = (cwd: string): BasenameIndex => {
932
1209
  // Unreadable dir → empty listing, never a throw from the deterministic floor.
933
1210
  const listDir = (dir: string) => {
934
1211
  try {
@@ -962,59 +1239,149 @@ const buildBasenameIndex = (cwd: string): { index: Map<string, string[]>; trunca
962
1239
  return { index, truncated: false };
963
1240
  };
964
1241
 
1242
+ /** Outcome of resolving a single citation's `path` against `cwd`. `abs` is the
1243
+ * one backing file when resolution is unique; `ambiguous` carries the candidate
1244
+ * list (absolute paths) when more than one tree file matches, so the caller can
1245
+ * render the disambiguation finding text. `undefined` ⇒ no match
1246
+ * (does-not-exist). This is the minimal-deviation return shape — a plain
1247
+ * `string | undefined` would drop the candidate list the disambiguation finding
1248
+ * text depends on. */
1249
+ type CitationResolution = { abs: string } | { ambiguous: string[] };
1250
+
1251
+ /** Strategy 4 of `resolveCitationPath`: tree files whose REPO-RELATIVE path ends
1252
+ * with the cited `path` on WHOLE segments. A bare basename is the one-segment
1253
+ * case; a multi-segment citation narrows the basename's candidates at a `/`
1254
+ * boundary, so `workflow/validate/x.ts` can never match inside
1255
+ * `rpiv-workflow/validate/x.ts`. Compared repo-relative (never against the
1256
+ * absolute path) so the checkout directory's own name can never back a citation
1257
+ * — `src/utils.ts` must not resolve to `<cwd>/utils.ts` just because the repo
1258
+ * happens to be cloned at `/tmp/src`. Reads/writes the shared `indexHolder` so
1259
+ * the basename index is built lazily ONCE and shared across citations (the
1260
+ * first direct-resolution miss pays the tree walk). */
1261
+ const suffixMatchesFor = (path: string, cwd: string, indexHolder: { value: BasenameIndex | undefined }): string[] => {
1262
+ indexHolder.value ??= buildBasenameIndex(cwd);
1263
+ if (indexHolder.value.truncated) return []; // partial index ⇒ uniqueness untrustworthy ⇒ strict
1264
+ const candidates = indexHolder.value.index.get(basename(path)) ?? [];
1265
+ if (!path.includes("/")) return candidates;
1266
+ const suffix = `/${path}`;
1267
+ return candidates.filter((abs) =>
1268
+ `/${abs
1269
+ .slice(cwd.length + 1)
1270
+ .split(sep)
1271
+ .join("/")}`.endsWith(suffix),
1272
+ );
1273
+ };
1274
+
1275
+ /** Resolve a citation's `path` to one backing file under `cwd`, encapsulating
1276
+ * all four strategies in order: (1) direct — `path` or `cwd/path`; (2,3)
1277
+ * dependency probes — `node_modules/<path>` and `node_modules/@<path>` (the
1278
+ * latter because the citation regex cannot carry `@`, so a cited
1279
+ * `node_modules/@scope/pkg/f.js` parses as `scope/pkg/f.js`); DIRECT probes
1280
+ * only — the suffix walk still skips `node_modules` (per `CITATION_WALK_SKIP`),
1281
+ * so a bare basename never resolves into a dep; (4) suffix fallback — a UNIQUE
1282
+ * tree-file suffix match backs the citation, an AMBIGUOUS one returns the
1283
+ * candidate list. PURE: emits no findings and throws never — all finding text
1284
+ * lives in `verifyCitations`. The lazily-built basename index is shared across
1285
+ * calls via `indexHolder`. */
1286
+ const resolveCitationPath = (
1287
+ path: string,
1288
+ cwd: string,
1289
+ indexHolder: { value: BasenameIndex | undefined },
1290
+ ): CitationResolution | undefined => {
1291
+ // Strategy 1 — direct.
1292
+ const direct = isAbsolute(path) ? path : join(cwd, path);
1293
+ if (existsSync(direct) && statSync(direct).isFile()) return { abs: direct };
1294
+ // Strategies 2 & 3 — dependency probes (lockfile-pinned dep source; the regex
1295
+ // cannot carry `@`, so `node_modules/@scope/pkg/f.js` is cited as `scope/pkg/f.js`).
1296
+ for (const candidate of [join(cwd, "node_modules", path), join(cwd, "node_modules", `@${path}`)]) {
1297
+ if (existsSync(candidate) && statSync(candidate).isFile()) return { abs: candidate };
1298
+ }
1299
+ // Strategy 4 — suffix fallback: back the citation iff exactly ONE tree file matches.
1300
+ const matches = suffixMatchesFor(path, cwd, indexHolder);
1301
+ if (matches.length === 1) return { abs: matches[0] };
1302
+ if (matches.length > 1) return { ambiguous: matches };
1303
+ return undefined;
1304
+ };
1305
+
1306
+ /**
1307
+ * Character-offset spans of fenced code blocks (delimiter lines included), an
1308
+ * unterminated fence running to end-of-text. Mirrors the `inFence`/`fenceLen`
1309
+ * toggle `countHeadingsOutsideFences` carries so every fence-aware scan agrees
1310
+ * on the same boundaries.
1311
+ */
1312
+ const fencedSpans = (content: string): [number, number][] => {
1313
+ const spans: [number, number][] = [];
1314
+ let inFence = false;
1315
+ let fenceLen = 0;
1316
+ let fenceChar = "";
1317
+ let spanStart = 0;
1318
+ let offset = 0;
1319
+ for (const line of content.split("\n")) {
1320
+ const lineEnd = offset + line.length + 1; // +1 for the split-consumed \n
1321
+ const fence = FENCE_LINE_RE.exec(line);
1322
+ if (fence) {
1323
+ if (!inFence) {
1324
+ inFence = true;
1325
+ fenceLen = fence[1].length;
1326
+ fenceChar = fence[1][0];
1327
+ spanStart = offset;
1328
+ } else if (closesFence(line, fence, fenceChar, fenceLen)) {
1329
+ inFence = false;
1330
+ fenceLen = 0;
1331
+ fenceChar = "";
1332
+ spans.push([spanStart, lineEnd]);
1333
+ }
1334
+ }
1335
+ offset = lineEnd;
1336
+ }
1337
+ if (inFence) spans.push([spanStart, offset]);
1338
+ return spans;
1339
+ };
1340
+
1341
+ /** Example-path namespaces the skill prompts use in illustrative citations
1342
+ * (`path/to/file.ext:12`, `packages/x/y.ts:42`). Artifacts quote — and models
1343
+ * imitate — these examples in unfenced prose, where the fence skip cannot
1344
+ * reach them; a citation under one of these prefixes is documentation shape,
1345
+ * never a claim about the tree, and prosecuting one buys a full LLM fix round
1346
+ * for zero risk averted (three of f329's floor failures were this class). */
1347
+ const PLACEHOLDER_CITATION_PREFIXES: readonly string[] = ["path/to/", "packages/x/"];
1348
+
965
1349
  const verifyCitations = (body: string, cwd: string): { detail: string; where: string }[] => {
966
1350
  const findings: { detail: string; where: string }[] = [];
967
1351
  const seen = new Set<string>();
1352
+ // Fenced text is example/fixture territory, not prose asserting a real
1353
+ // file:line — a fenced placeholder shaped like a citation must not fail the
1354
+ // floor (it false-failed the very plan that fixes this). Span check, not a
1355
+ // placeholder-pattern skip: a REAL citation that merely looks placeholder-ish
1356
+ // still verifies when it appears in prose.
1357
+ const fenced = fencedSpans(body);
968
1358
  // Built lazily and reused across citations — only the first direct-resolution
969
1359
  // 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
- };
1360
+ const indexHolder: { value: BasenameIndex | undefined } = { value: undefined };
991
1361
  for (const m of body.matchAll(FILE_LINE_CITATION_RE)) {
992
1362
  const [, path, startStr, endStr] = m;
993
1363
  if (!path || !startStr) continue;
1364
+ if (fenced.some(([s, e]) => m.index >= s && m.index < e)) continue;
1365
+ if (PLACEHOLDER_CITATION_PREFIXES.some((p) => path.startsWith(p))) continue;
994
1366
  const key = `${path}:${startStr}${endStr ? `-${endStr}` : ""}`;
995
1367
  if (seen.has(key)) continue;
996
1368
  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
- }
1369
+ const resolved = resolveCitationPath(path, cwd, indexHolder);
1370
+ if (resolved && "ambiguous" in resolved) {
1371
+ // More than one tree file matches — name the candidates so the fix arm can disambiguate.
1372
+ const shown = resolved.ambiguous
1373
+ .slice(0, 3)
1374
+ .map((a) => (a.startsWith(cwd + sep) ? a.slice(cwd.length + 1) : a));
1375
+ findings.push({
1376
+ 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.`,
1377
+ where: key,
1378
+ });
1379
+ continue;
1014
1380
  }
1381
+ const abs = resolved?.abs;
1015
1382
  if (!abs) {
1016
1383
  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.`,
1384
+ 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
1385
  where: key,
1019
1386
  });
1020
1387
  continue;
@@ -1042,6 +1409,53 @@ const verifyCitations = (body: string, cwd: string): { detail: string; where: st
1042
1409
  return findings;
1043
1410
  };
1044
1411
 
1412
+ /** A structure-dimension finding — the shared shape the deterministic verdict
1413
+ * checks emit (`detail` is the actionable message, `where` locates the defect). */
1414
+ type StructureFinding = { detail: string; where: string };
1415
+
1416
+ /** A dispatched sub-plan basename with its `_cluster-<k>` ordinal resolved. */
1417
+ type DispatchedCluster = { path: string; k: number };
1418
+
1419
+ /** An `fs` artifact handle (the only handle kind the verdict checks operate on). */
1420
+ type FsHandle = { kind: "fs"; path: string };
1421
+
1422
+ /**
1423
+ * Write the shared `{ dimension: "structure" }` verdict and publish it on an fs
1424
+ * artifact. The three deterministic structure checks (`sliceStructureCheck`,
1425
+ * `subplanCoverageCheck`, `planCitationCheck`) all emit the SAME verdict shape
1426
+ * and basename-keyed JSON write, so it lives here once. `who` is the channel
1427
+ * prefix folded into the basename (so a re-run OVERWRITES its own slot —
1428
+ * idempotent across fix/reslice/re-dispatch rounds); `handle` is the artifact
1429
+ * the check inspected (serialized into `data.artifact` and basename-keyed).
1430
+ *
1431
+ * The `severity: pass ? "none" : "high"` floor is load-bearing: the gate routes
1432
+ * via `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently
1433
+ * passes a `pass:false` verdict rated `low`/`none`; a structural defect MUST
1434
+ * rate `high` or it ships. The `score` is the binary verdict scale (100 = clean,
1435
+ * 0 = finding; the gate keys off `severity`, never this number).
1436
+ */
1437
+ const writeStructureVerdict = (
1438
+ who: string,
1439
+ handle: FsHandle,
1440
+ findings: StructureFinding[],
1441
+ cwd: string,
1442
+ ): Omit<Output, "meta"> => {
1443
+ const pass = findings.length === 0;
1444
+ const data = {
1445
+ dimension: "structure",
1446
+ pass,
1447
+ score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
1448
+ severity: pass ? "none" : "high",
1449
+ artifact: handleToString(handle),
1450
+ findings,
1451
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
1452
+ };
1453
+ const rel = join(VERDICT_DIR, `${who}__${basename(handle.path, ".md")}.json`);
1454
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
1455
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
1456
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
1457
+ };
1458
+
1045
1459
  /**
1046
1460
  * Deterministic Phase-1 slice-check — the un-gameable floor beneath the LLM
1047
1461
  * `design-readiness` panel. It enforces the invariants a prose grader cannot
@@ -1105,118 +1519,1213 @@ const sliceStructureCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"
1105
1519
  // Citation backing — every file:line the map cites must resolve.
1106
1520
  findings.push(...verifyCitations(mapBody, cwd));
1107
1521
 
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
- };
1522
+ return writeStructureVerdict("slice-check", latest.handle, findings, cwd);
1129
1523
  };
1130
1524
 
1131
1525
  /**
1132
- * Deterministic citation floor for a synthesized/spliced plan — the plan-scope
1133
- * twin of `sliceStructureCheck`'s citation backing, extending finding 6 past the
1134
- * slice map to the plan and the code-bearing plan (a fabricated `file:line` in
1135
- * the plan misdirects `implement`, exactly the #103 class). Verifies every
1136
- * citation resolves against the working tree and emits a `{ dimension:
1137
- * "structure" }` verdict on `who`'s channel that the gate route folds via
1138
- * `allDimensionsPass`; the matching `<fix>` stage reads `fanin(who)` so the
1139
- * findings DRIVE the amend rather than blind-halt. Reuses `verifyCitations` — no
1140
- * fuzzy wrong-symbol heuristic. Basename-keyed ⇒ idempotent across fix rounds.
1141
- */
1142
- const planCitationCheck =
1143
- (who: string) =>
1144
- ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1145
- const latest = latestFsArtifact(state, "plans");
1146
- if (latest?.handle.kind !== "fs") {
1147
- throw haltPreflight(
1148
- who,
1149
- `${who}: no plan to check`,
1150
- `${who}: no fs artifact on the 'plans' channel — the plan must be produced before the citation check`,
1151
- );
1152
- }
1153
- const body = readArtifactFile(latest.handle.path, cwd);
1154
- const findings = verifyCitations(body, cwd);
1155
- const pass = findings.length === 0;
1156
- const data = {
1157
- dimension: "structure",
1158
- pass,
1159
- score: pass ? 100 : 0,
1160
- severity: pass ? "none" : "high",
1161
- artifact: handleToString(latest.handle),
1162
- findings,
1163
- feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
1164
- };
1165
- const rel = join(VERDICT_DIR, `${who}__${basename(latest.handle.path, ".md")}.json`);
1166
- mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
1167
- writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
1168
- return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
1169
- };
1170
-
1171
- /** A design filename encodes its slice as `…slice-<N>…` — the design-fanout naming convention. */
1172
- const DESIGN_SLICE_RE = /slice-(\d+)/;
1173
-
1174
- /**
1175
- * Map slice number → its design artifact path, from the design fanout's published
1176
- * outputs. An identity resolver: it maps an ARTIFACT to a slice NUMBER. It FAILS
1177
- * LOUD only when identity is genuinely UNRESOLVABLE — a design filename that
1178
- * carries no `slice-<N>` token, where a positional `idx + 1` guess would scramble
1179
- * the cluster→design wiring and drop slices.
1180
- *
1181
- * A slice claimed by MORE THAN ONE output is NOT ambiguous: the `designs` channel
1182
- * legitimately accumulates several entries per slice — `slice-design` emits it,
1183
- * then `design-review` re-emits the accepted/edited design on the SAME channel
1184
- * (its documented "latest-wins, same paths" contract, so `subplan`/`synthesize`
1185
- * read the accepted docs). So the newest entry wins, deterministically — throwing
1186
- * on a duplicate would halt every normal run at `subplan`. (The resume re-dispatch
1187
- * that once left CONFLICTING designs on the channel is fixed at its source —
1188
- * finding 7 — so there is no corruption left to fail loud on here.)
1526
+ * `_<k>` cluster ordinal a partial sub-plan carries in its basename
1527
+ * (`<slug>_cluster-<k>.md`), emitted by `synthesize`'s partial mode from the
1528
+ * `--cluster <k>` the fanout threads on every cluster unit. The token a
1529
+ * `subplan-check` reconciliation keys dispatched sub-plans on. Anchored to the
1530
+ * basename TAIL (extension optional — extensionless agent writes happen, see
1531
+ * the implement-scope floor precedent) so a name carrying several `_cluster-`
1532
+ * tokens binds the trailing one deterministically, not the first match.
1189
1533
  */
1190
- const designPathsBySlice = (state: RunView): Map<number, string> => {
1191
- const bySlice = new Map<number, string>();
1192
- for (const out of state.named.designs ?? []) {
1534
+ const CLUSTER_TOKEN_RE = /_cluster-(\d+)(?:\.\w+)?$/;
1535
+
1536
+ /** The pre-filter cluster count the fanout received — the count
1537
+ * `subplanCoverageCheck` reconciles dispatched ordinals against. Delegates to
1538
+ * `clusterSliceDag`. */
1539
+ const expectedClusterCount = (records: readonly PhaseRecord[]): number => clusterSliceDag(records).length;
1540
+
1541
+ /** Slice numbers that have NO design artifact on the `designs` channel — the gap
1542
+ * the missing-design preflight halts on (a slice with no design is unrepairable
1543
+ * by re-dispatch). */
1544
+ const designCoverageGap = (sliceNumbers: Set<number>, designBySlice: Map<number, string>): number[] =>
1545
+ [...sliceNumbers].filter((n) => !designBySlice.has(n)).sort((a, b) => a - b);
1546
+
1547
+ /** Collect every dispatched sub-plan's `_cluster-<k>` ordinal from the `subplans`
1548
+ * channel. The `subplans` slot is a produces-fanout channel: `placeFanoutOutput`
1549
+ * pre-sizes it to the round's unit total and overwrites each unit's own index, so
1550
+ * with a stable unit set iterating it reflects the latest output per unit — a
1551
+ * re-dispatch's fresh artifacts re-evaluate cleanly. (A unit that FAILS on
1552
+ * re-dispatch leaves its prior-round output at its index; that stale entry
1553
+ * re-reads as current here.) Returns the resolved ordinals AND a `tokenless`
1554
+ * finding per basename that carries no `_cluster-<k>` token (the root merge
1555
+ * cannot attribute a tokenless sub-plan to a slice-DAG cluster). */
1556
+ const dispatchedClusterOrdinals = (
1557
+ state: RunView,
1558
+ ): { dispatched: DispatchedCluster[]; tokenless: StructureFinding[] } => {
1559
+ const dispatched: DispatchedCluster[] = [];
1560
+ const tokenless: StructureFinding[] = [];
1561
+ for (const out of state.named.subplans ?? []) {
1193
1562
  for (const a of out.artifacts) {
1194
1563
  if (a.handle.kind !== "fs") continue;
1195
1564
  const name = basename(a.handle.path);
1196
- const match = DESIGN_SLICE_RE.exec(name);
1197
- if (!match) {
1198
- throw haltPreflight(
1199
- "designPathsBySlice",
1200
- `designPathsBySlice: design ${name} has no slice number`,
1201
- `designPathsBySlice: design artifact ${a.handle.path} carries no 'slice-<N>' token — cannot resolve which slice it designs; a positional guess would mis-route the cluster→design mapping and drop slices`,
1202
- );
1565
+ const m = CLUSTER_TOKEN_RE.exec(name);
1566
+ if (!m) {
1567
+ tokenless.push({
1568
+ 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.`,
1569
+ where: name,
1570
+ });
1571
+ continue;
1203
1572
  }
1204
- // Latest design per slice wins — the channel holds multiple entries per
1205
- // slice by design (design-review re-emits), and the newest is authoritative.
1206
- bySlice.set(Number(match[1]), handleToString(a.handle));
1573
+ dispatched.push({ path: handleToString(a.handle), k: Number(m[1]) });
1207
1574
  }
1208
1575
  }
1209
- return bySlice;
1576
+ return { dispatched, tokenless };
1210
1577
  };
1211
1578
 
1212
- /**
1213
- * Fan `subplan` out over slice-DAG clusters. Each unit merges ONE cluster's
1214
- * per-slice designs into a sub-plan (`--as-subplan`), so no single pass holds
1215
- * every design — the context-bounding twin of the flat fan-in `synthesize`.
1216
- */
1217
- const SYNTH_CLUSTER_FANOUT = fanout({
1218
- source: "designs",
1219
- unit: { by: "slice-dag-cluster", pattern: "clusters" },
1579
+ /** A finding per `_cluster-<k>` ordinal claimed by MORE THAN ONE dispatched
1580
+ * sub-plan — a clobber (not a legitimate re-emit: within one round every unit
1581
+ * index is a distinct artifact because the channel is replaced each round, so a
1582
+ * shared `<k>` is the lost-cluster collision itself). */
1583
+ const clobberedOrdinals = (dispatched: readonly DispatchedCluster[]): StructureFinding[] => {
1584
+ const pathsByK = new Map<number, string[]>();
1585
+ for (const d of dispatched) {
1586
+ const arr = pathsByK.get(d.k);
1587
+ if (arr) arr.push(d.path);
1588
+ else pathsByK.set(d.k, [d.path]);
1589
+ }
1590
+ const findings: StructureFinding[] = [];
1591
+ for (const [k, paths] of pathsByK) {
1592
+ if (paths.length > 1) {
1593
+ findings.push({
1594
+ 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.`,
1595
+ where: `cluster-${k}`,
1596
+ });
1597
+ }
1598
+ }
1599
+ return findings;
1600
+ };
1601
+
1602
+ /** sources-coverage — every slice's design must appear in SOME sub-plan's
1603
+ * `sources:`. Reads the covered-slice set off each sub-plan's parsed `sources:`
1604
+ * (designs follow the `_slice-<N>` convention) and reconciles it against the full
1605
+ * slice map. A sub-plan whose frontmatter does not PARSE gets its own
1606
+ * re-dispatchable finding naming the FILE (never a terminal halt — the same
1607
+ * stray-colon class `artifact-collector` degrades on); when ANY sub-plan is
1608
+ * unparseable, the per-slice reconciliation DEFERS (an unreadable sub-plan's
1609
+ * coverage is unknowable; blaming its slices would misdirect the repair). */
1610
+ const sourcesCoverageGaps = (state: RunView, cwd: string, sliceNumbers: Set<number>): StructureFinding[] => {
1611
+ const findings: StructureFinding[] = [];
1612
+ const coveredSlices = new Set<number>();
1613
+ let unparseable = false;
1614
+ for (const out of state.named.subplans ?? []) {
1615
+ for (const a of out.artifacts) {
1616
+ if (a.handle.kind !== "fs") continue;
1617
+ let frontmatter: unknown;
1618
+ try {
1619
+ ({ frontmatter } = parseFrontmatter(readArtifactFile(handleToString(a.handle), cwd)));
1620
+ } catch {
1621
+ unparseable = true;
1622
+ findings.push({
1623
+ 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:'.`,
1624
+ where: basename(a.handle.path),
1625
+ });
1626
+ continue;
1627
+ }
1628
+ const fm = frontmatter && typeof frontmatter === "object" ? (frontmatter as Record<string, unknown>) : {};
1629
+ const sources = fm.sources;
1630
+ if (!Array.isArray(sources)) continue;
1631
+ for (const s of sources) {
1632
+ if (typeof s !== "string") continue;
1633
+ const sm = DESIGN_SLICE_RE.exec(s);
1634
+ if (sm) coveredSlices.add(Number(sm[1]));
1635
+ }
1636
+ }
1637
+ }
1638
+ if (!unparseable) {
1639
+ for (const n of [...sliceNumbers].sort((a, b) => a - b)) {
1640
+ if (!coveredSlices.has(n)) {
1641
+ findings.push({
1642
+ 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:'.`,
1643
+ where: `sources: slice ${n}`,
1644
+ });
1645
+ }
1646
+ }
1647
+ }
1648
+ return findings;
1649
+ };
1650
+
1651
+ /**
1652
+ * Deterministic subplan cluster-coverage floor — the structural backstop between
1653
+ * the cluster fanout and the root merge. After `subplan` fans each slice-DAG
1654
+ * cluster out to a partial sub-plan, this reconciles what was DISPATCHED against
1655
+ * what the slice map PROMISED, before the root `plan` merge fans them in:
1656
+ * • cluster-count conservation — the PRE-FILTER cluster count
1657
+ * (`clusterSliceDag(sliceRecords(latest slices)).length`) must equal the
1658
+ * number of distinct `_cluster-<k>` ordinals the fanout emitted. A re-dispatch
1659
+ * that re-clobbered an ordinal (the pre-fix clobber bug — two clusters
1660
+ * sharing `<k>`, or a tokenless basename) collapses the distinct count,
1661
+ * surfacing as a missing cluster here.
1662
+ * • token conformance — every dispatched sub-plan basename MUST carry a
1663
+ * `_cluster-<k>` token; a tokenless name means `synthesize` dropped the
1664
+ * `--cluster <k>` flag and the merge can't attribute it to a cluster.
1665
+ * • duplicate/clobbered ordinal — two dispatched sub-plans sharing the same
1666
+ * `<k>` (a clobber, not a legitimate re-emit: `placeFanoutOutput` overwrites
1667
+ * each unit's own index in the channel slot, so within one round every unit
1668
+ * index is a distinct artifact — a shared `<k>` is a real collision, the
1669
+ * lost-cluster bug itself).
1670
+ * • sources-coverage — every slice's design must appear in SOME sub-plan's
1671
+ * `sources:` (the fanout threads each `--designs <path>` and `synthesize`
1672
+ * echoes them into `sources:`). Designs follow the `_slice-<N>` convention, so
1673
+ * the covered slice set is read off `sources:` and reconciled against the full
1674
+ * slice map; a slice whose design no sub-plan lists is a slice the merge would
1675
+ * silently drop. A sub-plan whose frontmatter does not PARSE gets its own
1676
+ * re-dispatchable finding naming the FILE (never a `FAIL_SCRIPT_THREW` halt —
1677
+ * the same stray-colon class `artifact-collector` degrades on), and the
1678
+ * per-slice reconciliation defers until every sub-plan parses, so a parse
1679
+ * failure is never mis-blamed on the slices it happened to cover.
1680
+ * Preflight: a slice with NO design on the `designs` channel halts LOUD before
1681
+ * any reconciliation — the fanout drops (or under-feeds) its cluster pre-dispatch
1682
+ * (`if (!designs.length) return undefined`), so re-dispatching `subplan` re-drops
1683
+ * it every round until `maxBackwardJumps` exhausts with a diagnostic naming the
1684
+ * refused re-entry instead of the cause. The missing design is upstream
1685
+ * (`slice-design`/`design-review`) and unreachable from this loop's backward
1686
+ * edge; halting here names the actual defect and spends no jump budget.
1687
+ * Emits `severity: pass ? "none" : "high"` (load-bearing — the route routes via
1688
+ * `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently passes a
1689
+ * `pass:false` verdict rated `low`/`none`; a lost cluster MUST rate `high` or it
1690
+ * ships). Deliberately NOT the `match("verdict", …)` STOP idiom
1691
+ * `implementScopeCheck` uses — a lost cluster IS repairable by re-dispatch, so the
1692
+ * floor routes the backward edge to `subplan`, bounded by `maxBackwardJumps`.
1693
+ * Deterministic ⇒ idempotent across re-dispatch rounds: the verdict basename is
1694
+ * keyed on the slice-map basename, so a re-run OVERWRITES its own slot.
1695
+ */
1696
+ const subplanCoverageCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1697
+ const latestSliceMap = latestFsArtifact(state, "slices");
1698
+ if (latestSliceMap?.handle.kind !== "fs") {
1699
+ throw haltPreflight(
1700
+ "subplan-check",
1701
+ "subplan-check: no slice map to reconcile against",
1702
+ "subplan-check: no fs artifact on the 'slices' channel — slice must run before the subplan coverage check",
1703
+ );
1704
+ }
1705
+ const mapBody = readArtifactFile(latestSliceMap.handle.path, cwd);
1706
+ const records = sliceRecords(mapBody, "subplan-check", latestSliceMap.handle.path);
1707
+ // PRE-FILTER expected clusters — the count the fanout RECEIVED, not the
1708
+ // post-drop dispatched count. The fanout drops a zero-design cluster
1709
+ // (`if (!designs.length) return undefined` in SYNTH_CLUSTER_FANOUT's units);
1710
+ // design-review catches those upstream, so a healthy run lands here with
1711
+ // pre-filter == dispatched — an invariant the missing-design preflight below
1712
+ // enforces loudly rather than assumes.
1713
+ const expectedK = expectedClusterCount(records);
1714
+ const sliceNumbers = new Set(records.map((r) => r.n));
1715
+
1716
+ // A slice with no design cannot be repaired by the backward edge: the fanout
1717
+ // drops a zero-design cluster pre-dispatch, so every `subplan` re-dispatch
1718
+ // reproduces the identical gap until maxBackwardJumps exhausts blaming the
1719
+ // re-entry. Halt loud at the floor instead, naming the upstream cause.
1720
+ const designBySlice = designPathsBySlice(state);
1721
+ const undesigned = designCoverageGap(sliceNumbers, designBySlice);
1722
+ if (undesigned.length > 0) {
1723
+ throw haltPreflight(
1724
+ "subplan-check",
1725
+ `subplan-check: slice(s) ${undesigned.join(", ")} have no design on the 'designs' channel`,
1726
+ `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.`,
1727
+ );
1728
+ }
1729
+
1730
+ const { dispatched, tokenless } = dispatchedClusterOrdinals(state);
1731
+ const findings: StructureFinding[] = [...tokenless];
1732
+ findings.push(...clobberedOrdinals(dispatched));
1733
+
1734
+ // Cluster-count conservation — distinct dispatched ordinals vs the pre-filter
1735
+ // expected count. A clobber or a never-dispatched cluster both surface here.
1736
+ const dispatchedK = new Set(dispatched.map((d) => d.k)).size;
1737
+ if (dispatchedK < expectedK) {
1738
+ findings.push({
1739
+ 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).`,
1740
+ where: `clusters (expected ${expectedK}, dispatched ${dispatchedK})`,
1741
+ });
1742
+ }
1743
+
1744
+ findings.push(...sourcesCoverageGaps(state, cwd, sliceNumbers));
1745
+
1746
+ return writeStructureVerdict("subplan-check", latestSliceMap.handle, findings, cwd);
1747
+ };
1748
+
1749
+ /**
1750
+ * Slice a plan body into per-phase text keyed by phase number, splitting on
1751
+ * `## Phase N:` headings OUTSIDE fenced code blocks (a heading inside a ``` or
1752
+ * ~~~ fence is example/fixture text, not a structural phase boundary — mirrors
1753
+ * `countHeadingsOutsideFences` so the slice and the derive-check agree). The
1754
+ * body for phase N runs from its heading line up to (not including) the next
1755
+ * out-of-fence `## Phase M:` heading, or end-of-text for the last phase.
1756
+ * Returns a `Map<number, string>` (phase n → body text, heading included).
1757
+ */
1758
+ const phaseBodySlices = (content: string): Map<number, string> => {
1759
+ const lineRe = new RegExp(PLAN_PHASE_RE.source); // drop g/m; per-line test, lastIndex can't drift
1760
+ const lines = content.split("\n");
1761
+ const openings: { n: number; start: number }[] = [];
1762
+ forEachLineOutsideFences(content, (line, i) => {
1763
+ const m = lineRe.exec(line);
1764
+ if (m?.[1]) openings.push({ n: Number(m[1]), start: i });
1765
+ });
1766
+ const slices = new Map<number, string>();
1767
+ for (let idx = 0; idx < openings.length; idx++) {
1768
+ const end = idx + 1 < openings.length ? openings[idx + 1].start : lines.length;
1769
+ slices.set(openings[idx].n, lines.slice(openings[idx].start, end).join("\n"));
1770
+ }
1771
+ return slices;
1772
+ };
1773
+
1774
+ /** Strip a trailing `:line` or `:line-line` citation suffix from a path token. */
1775
+ const stripLineSuffix = (p: string): string => p.replace(/:\d+(?:-\d+)?$/, "");
1776
+
1777
+ /** Well-known extensionless filenames — the extension heuristic below would drop
1778
+ * them, so an undeclared write to one would silently escape the coverage floor.
1779
+ * Recognized bare or as the basename of a path. */
1780
+ const EXTENSIONLESS_FILENAME_RE =
1781
+ /^(?:Makefile|Dockerfile|Rakefile|Gemfile|Justfile|Procfile|LICENSE|NOTICE|CODEOWNERS)$/;
1782
+
1783
+ /** Path-like test mirroring slice-overlap.mjs's `looksLikePath`, applied AFTER
1784
+ * stripping a `:line` suffix (the blueprint MODIFY heading — `#### N. path/to/file.ext`
1785
+ * with a `:12-30` range appended — carries a line range the bare form rejects).
1786
+ * Extensionless recognition is allowlist-only (never "any `/`-bearing token"):
1787
+ * prose like `and/or` must not read as a declared write. */
1788
+ const isPathLike = (s: string): boolean => {
1789
+ if (/\s/.test(s)) return false;
1790
+ if (EXTENSIONLESS_FILENAME_RE.test(s.slice(s.lastIndexOf("/") + 1))) return true;
1791
+ return /\.[A-Za-z0-9]+$/.test(s) && (s.includes("/") || /^[\w.-]+\.[A-Za-z0-9]+$/.test(s));
1792
+ };
1793
+
1794
+ /**
1795
+ * Extract the edit paths a phase body names, across the three artifact
1796
+ * conventions the plan/blueprint/synthesize skills emit, OUTSIDE fenced code
1797
+ * blocks (a path inside a ``` fence is a code reference, not a declared write —
1798
+ * post-`code-splice` safety, since code-splice folds elaborations' fenced code
1799
+ * into the plan and those fenced paths must NOT read as phase writes):
1800
+ * • `**File**:` / `**Files**:` — plan/blueprint's per-change file line
1801
+ * (a backticked comma-list under `**Files**:`, or a single path under `**File**:`).
1802
+ * • `#### N. path/to/file.ext` — blueprint's change subsection heading
1803
+ * (may carry a `:line`-range suffix on MODIFY entries — stripped).
1804
+ * • `- `path/to/file.ts`` — synthesize's backticked-path list item under
1805
+ * `### Changes` (the form `elaborate`/`synthesize` emit).
1806
+ * Strips a trailing `:line`/`:line-line` suffix. Mirrors slice-overlap.mjs's
1807
+ * `filesOf` + `looksLikePath` and extends them with the synthesize list-item
1808
+ * form. Returns a de-duplicated `string[]`.
1809
+ */
1810
+ const editPathsOfPhase = (phaseBody: string): string[] => {
1811
+ const files = new Set<string>();
1812
+ const add = (raw: string) => {
1813
+ const stripped = stripLineSuffix(raw.replace(/[`*]/g, "").trim());
1814
+ if (stripped && isPathLike(stripped)) files.add(stripped);
1815
+ };
1816
+ forEachLineOutsideFences(phaseBody, (line) => {
1817
+ const fm = line.match(/^\*\*Files?\*\*:\s*(.+)$/);
1818
+ if (fm) {
1819
+ for (const tok of fm[1].split(/[,\s]+/)) add(tok);
1820
+ return;
1821
+ }
1822
+ const hm = line.match(/^#{3,4}\s+\d+\.\s+(\S+)/);
1823
+ if (hm) {
1824
+ add(hm[1]);
1825
+ return;
1826
+ }
1827
+ const lm = line.match(/^-\s+`([^`]+)`/);
1828
+ if (lm) add(lm[1]);
1829
+ });
1830
+ return [...files];
1831
+ };
1832
+
1833
+ /**
1834
+ * Deterministic plan-time coverage floor: every edit path a phase body NAMES
1835
+ * (in `### Changes`/`#### N. path`/`**File**:`) must be DECLARED in that phase's
1836
+ * frontmatter `files:` array. An undeclared write is the per-phase attribution
1837
+ * gap the dep-gated implement fanout and the lane-level scope floor both need
1838
+ * closed upstream — a body edit not in `files:` is invisible to dependency
1839
+ * derivation and unattributable under concurrency. PURE: no LLM judgment, never
1840
+ * throws (a malformed frontmatter degrades to `[]`). A `files:`-LESS phase
1841
+ * (absent key) yields NO findings — empty-set degradation so a legacy/
1842
+ * `files:`-less plan never false-fails; a phase that declares `files: []` is
1843
+ * checked (every body edit is a gap). Folded into `planCitationCheck(who)` so
1844
+ * both the `plan-cite-check` and `code-cite-check` arms emit coverage findings
1845
+ * on their shared `dimension: "structure"` verdict — no new stage/channel/route.
1846
+ */
1847
+ const verifyPhaseFilesCoverage = (content: string, who: string, path: string): { detail: string; where: string }[] => {
1848
+ let fm: Record<string, unknown>;
1849
+ try {
1850
+ const { frontmatter } = parseFrontmatter(content);
1851
+ fm = frontmatter as Record<string, unknown>;
1852
+ } catch {
1853
+ return []; // malformed frontmatter → degrade to no findings, never throw
1854
+ }
1855
+ const phases = Array.isArray(fm.phases) ? fm.phases : [];
1856
+ const entryByN = new Map<number, Record<string, unknown>>();
1857
+ phases.forEach((entry, idx) => {
1858
+ const e = (entry ?? {}) as Record<string, unknown>;
1859
+ const n = typeof e.n === "number" ? e.n : idx + 1;
1860
+ entryByN.set(n, e);
1861
+ });
1862
+ const findings: { detail: string; where: string }[] = [];
1863
+ for (const [n, body] of phaseBodySlices(content)) {
1864
+ const entry = entryByN.get(n);
1865
+ if (!entry) continue; // body phase with no matching frontmatter entry — derive-check's concern, not coverage's
1866
+ // `files:` key ABSENT → degradation (legacy plan): skip. Present (even `[]`) → check.
1867
+ if (!Array.isArray(entry.files)) continue;
1868
+ const declared = new Set(phaseFiles(entry));
1869
+ for (const editPath of editPathsOfPhase(body)) {
1870
+ if (declared.has(editPath)) continue;
1871
+ findings.push({
1872
+ 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.`,
1873
+ where: `${who} ${path} phase ${n}: ${editPath}`,
1874
+ });
1875
+ }
1876
+ }
1877
+ return findings;
1878
+ };
1879
+
1880
+ /**
1881
+ * Deterministic citation floor for a synthesized/spliced plan — the plan-scope
1882
+ * twin of `sliceStructureCheck`'s citation backing, extending the citation
1883
+ * floor past the slice map to the plan and the code-bearing plan (a fabricated `file:line` in
1884
+ * the plan misdirects `implement`). Verifies every
1885
+ * citation resolves against the working tree and emits a `{ dimension:
1886
+ * "structure" }` verdict on `who`'s channel that the gate route folds via
1887
+ * `allDimensionsPass`; the matching `<fix>` stage reads `fanin(who)` so the
1888
+ * findings DRIVE the amend rather than blind-halt. Reuses `verifyCitations` — no
1889
+ * fuzzy wrong-symbol heuristic. Basename-keyed ⇒ idempotent across fix rounds.
1890
+ */
1891
+ const planCitationCheck =
1892
+ (who: string) =>
1893
+ ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1894
+ const latest = latestFsArtifact(state, "plans");
1895
+ if (latest?.handle.kind !== "fs") {
1896
+ throw haltPreflight(
1897
+ who,
1898
+ `${who}: no plan to check`,
1899
+ `${who}: no fs artifact on the 'plans' channel — the plan must be produced before the citation check`,
1900
+ );
1901
+ }
1902
+ const body = readArtifactFile(latest.handle.path, cwd);
1903
+ const findings = verifyCitations(body, cwd);
1904
+ // Plan-time coverage floor: a body edit not declared in its phase's `files:`
1905
+ // fails structurally, same channel/verdict/route as an unbacked citation.
1906
+ findings.push(...verifyPhaseFilesCoverage(body, who, latest.handle.path));
1907
+ // AV exit-0 contract floor: an Automated Verification line reconcile's
1908
+ // deterministic re-run can never honor (stdin-reading grep, absence-assertion
1909
+ // prose, out-of-scope Biome paths, unparseable span) fails HERE — into the
1910
+ // plan-fix loop — instead of at reconcile, whose fail route is STOP.
1911
+ findings.push(...verifyAvCommandContract(body));
1912
+ return writeStructureVerdict(who, latest.handle, findings, cwd);
1913
+ };
1914
+
1915
+ /**
1916
+ * Copy the latest graded plan off `plans` into `.rpiv/artifacts/priors/`
1917
+ * basename-keyed, publishing the bytes on the snapshot stage's OWN channel with
1918
+ * role `prior` — one deterministic hop BEFORE the matching fix stage inside the
1919
+ * existing fix loop (plan-grade/plan-confirm → plan-snapshot → plan-fix; code
1920
+ * twin). Overwritten each fix round, so the prior always reflects the
1921
+ * pre-CURRENT-fix content; the re-grade reads it via `latestPriorContent` to
1922
+ * decide whether the amend was surgical. `who` attributes the halt when no plan
1923
+ * is published. `kind: "artifact-md"` is the honest kind — the prior IS a copy
1924
+ * of an artifact-md plan body (the kind plans carry under `rpivBucketOutcome`).
1925
+ */
1926
+ const snapshotLatestPlan =
1927
+ (who: string) =>
1928
+ ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1929
+ const latest = latestFsArtifact(state, "plans");
1930
+ if (latest?.handle.kind !== "fs") {
1931
+ throw haltPreflight(
1932
+ who,
1933
+ `${who}: no plan to snapshot`,
1934
+ `${who}: no fs artifact on the 'plans' channel — the plan must be graded before the snapshot stage`,
1935
+ );
1936
+ }
1937
+ const src = isAbsolute(latest.handle.path) ? latest.handle.path : join(cwd, latest.handle.path);
1938
+ const priorRel = join(PRIOR_DIR, basename(latest.handle.path));
1939
+ mkdirSync(join(cwd, PRIOR_DIR), { recursive: true });
1940
+ copyFileSync(src, join(cwd, priorRel));
1941
+ return {
1942
+ kind: "artifact-md",
1943
+ artifacts: [{ handle: { kind: "fs", path: priorRel }, role: "prior" }],
1944
+ data: { snapshot_of: handleToString(latest.handle) },
1945
+ };
1946
+ };
1947
+
1948
+ /** Snapshot the graded plan before `plan-fix` amends it (plan gate). */
1949
+ const planSnapshot = snapshotLatestPlan("plan-snapshot");
1950
+ /** Snapshot the graded plan before `code-fix` amends it (code gate). */
1951
+ const codeSnapshot = snapshotLatestPlan("code-snapshot");
1952
+
1953
+ /**
1954
+ * A duty demotion stamped onto a verdict's on-disk JSON — the legible record
1955
+ * that a risk ruling the panel marked `pass: true` was demoted to effective-
1956
+ * fail by the evidence or verify-at-implement duty. One entry per FAILING
1957
+ * duty (a ruling authored as BOTH mechanics AND verify-at-implement can carry
1958
+ * two). `reason` is decision-code-free prose (no run/phase ids, no absolute
1959
+ * line numbers) naming the duty that failed, so disk readers (amend, confirm
1960
+ * `--prior`) can tell a grader-side demotion from a genuine `pass: false`.
1961
+ */
1962
+ interface RiskDutyDemotion {
1963
+ id: string;
1964
+ duty: "evidence-format" | "procedure-owner";
1965
+ reason: string;
1966
+ }
1967
+
1968
+ /**
1969
+ * Materialize the duty demotion as legible on-disk data. After a grade round,
1970
+ * each latest-per-dimension verdict whose `pass: true` rulings were demoted by
1971
+ * the evidence or verify-at-implement duty gets a `risk_duty_demotions` array
1972
+ * written onto its on-disk JSON IN PLACE — the one medium amend and confirm's
1973
+ * `--prior` read. The verdict's own `pass` is NEVER flipped (every gate fold —
1974
+ * `allRiskFlagsPass`/`dimensionsToRegrade`/`confirmDue` — consults
1975
+ * `rulingEffectivePass` off in-memory `state.named`, which never re-reads the
1976
+ * rewritten file, so gate outcomes are unchanged); the field is an additive,
1977
+ * read-only signal for the disk readers.
1978
+ *
1979
+ * Modeled on `snapshotLatestPlan(who)` (a `ScriptFn` that side-effects AND
1980
+ * returns an `Output`): it reads the PLAN-sourced duty triggers
1981
+ * (`planAuthoredRisks`), iterates the EXACT verdict set amend keeps + confirm
1982
+ * reads (`latestVerdictPerDimension(freshVerdicts(...))`), and rewrites each
1983
+ * demoted verdict's fs handle in place. Writes ONLY when ≥1 demotion (a clean
1984
+ * grade is a no-op — no needless reformat/mtime churn); each per-file
1985
+ * read/parse/write is wrapped so a single unparseable/stale file is skipped
1986
+ * (never halts the gate). Returns `{ demotions }` echoing `{dimension, id,
1987
+ * duty, verdict}` for journal greppability. `channel` is the plan channel the
1988
+ * risks + current artifact live on; `verdictChannel` is the grade's own
1989
+ * verdict channel (plan-verdicts / code-verdicts).
1990
+ */
1991
+ const demoteDuties =
1992
+ (who: string, channel: string, verdictChannel: string) =>
1993
+ ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1994
+ const risks = planAuthoredRisks(state, channel);
1995
+ const current = latestArtifactPath(state, channel);
1996
+ const demotions: { dimension: string; id: string; duty: RiskDutyDemotion["duty"]; verdict: string }[] = [];
1997
+ for (const o of latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel] ?? [], current)).values()) {
1998
+ const handle = o.artifacts.find((a) => a.handle.kind === "fs")?.handle;
1999
+ if (handle?.kind !== "fs") continue;
2000
+ const dimRaw = (o.data as { dimension?: unknown } | undefined)?.dimension;
2001
+ const dimension = typeof dimRaw === "string" ? dimRaw : "";
2002
+ const perFile: RiskDutyDemotion[] = [];
2003
+ for (const r of verdictRiskRulings(o)) {
2004
+ const authored = risks.get(r.id);
2005
+ // Only a `pass: true` ruling that rulingEffectivePass demotes — never a
2006
+ // genuine `pass: false` (that is already a fail, not a demoted pass).
2007
+ if (r.pass !== true || rulingEffectivePass(r, authored)) continue;
2008
+ if (!evidenceCitesFileLine(r, authored)) {
2009
+ perFile.push({
2010
+ id: r.id,
2011
+ duty: "evidence-format",
2012
+ reason: "mechanics pass without an adjacent file:line citation in evidence",
2013
+ });
2014
+ demotions.push({ dimension, id: r.id, duty: "evidence-format", verdict: handleToString(handle) });
2015
+ }
2016
+ if (!procedureSatisfiesDuty(r, authored)) {
2017
+ perFile.push({
2018
+ id: r.id,
2019
+ duty: "procedure-owner",
2020
+ reason: "verify-at-implement pass without a concrete procedure and owner phase",
2021
+ });
2022
+ demotions.push({ dimension, id: r.id, duty: "procedure-owner", verdict: handleToString(handle) });
2023
+ }
2024
+ }
2025
+ if (perFile.length === 0) continue;
2026
+ try {
2027
+ const abs = isAbsolute(handle.path) ? handle.path : join(cwd, handle.path);
2028
+ const json = JSON.parse(readFileSync(abs, "utf-8")) as Record<string, unknown>;
2029
+ json.risk_duty_demotions = perFile;
2030
+ writeFileSync(abs, JSON.stringify(json, null, 2));
2031
+ } catch {
2032
+ // skip-on-throw: an unparseable/stale verdict file never halts the gate.
2033
+ }
2034
+ }
2035
+ return { kind: "json", artifacts: [], data: { demotions, stage: who } };
2036
+ };
2037
+
2038
+ /**
2039
+ * Stamp duty demotions onto the graded plan's verdicts after `plan-grade`, one
2040
+ * deterministic hop before the gate routes (plan-grade → plan-demote → route).
2041
+ * The code lane re-grades `plans` on `code-verdicts` (mirroring `codeSnapshot`).
2042
+ */
2043
+ const planDemote = demoteDuties("plan-demote", "plans", "plan-verdicts");
2044
+ const codeDemote = demoteDuties("code-demote", "plans", "code-verdicts");
2045
+
2046
+ /**
2047
+ * Deterministic lane-level scope floor — the structural backstop beneath the
2048
+ * LLM quality gates. After build's `implement` lane runs (now dep-gated and, as
2049
+ * of this phase's unpin, concurrent up to the host cap), this checks the working
2050
+ * tree's dirty set against the plan's declared write-set (the union of every
2051
+ * phase's `files:`): any dirty path the run wrote that is NOT in `declared`, NOT
2052
+ * pre-existing at the run-start baseline, and NOT under a bookkeeping tree is a
2053
+ * scope violation — a phase escaped the upstream write-scope discipline and
2054
+ * rewrote the wider tree, corrupting (or about to corrupt) a concurrent
2055
+ * sibling's in-flight edit. Fail ⇒ STOP (no fix arm): a scope violation is a
2056
+ * plan-vs-tree drift the agent must reconcile manually, not an auto-fix loop.
2057
+ *
2058
+ * Reads the plan with the SAME inline shape `planCitationCheck(who)` uses —
2059
+ * `latestFsArtifact(state,"plans")` + `readArtifactFile` + `planPhaseRecords` +
2060
+ * Phase 1's `phaseFiles` — NOT Phase 2's `readPlanPhaseRecords(state,cwd,who)`,
2061
+ * because this stage needs the plan HANDLE for the `artifact` field and the
2062
+ * basename-keyed verdict path, which the `who`-attributed helper collapses. The
2063
+ * baseline is the run-start snapshot on the `goal` channel (`goalBaselinePath`,
2064
+ * the same reader `VALIDATE_GOAL_PROMPT` and `COMMIT_BASELINE_PROMPT` use); the
2065
+ * dirty set is `git status --porcelain` (non-repo / git-missing ⇒ empty dirty ⇒
2066
+ * pass — the lane degrades to unguarded rather than failing a non-repo run).
2067
+ * Emits one `{ dimension: "scope" }` verdict, basename-keyed off the plan ⇒
2068
+ * idempotent across the build loop.
2069
+ *
2070
+ * `data` carries BOTH a `pass` boolean AND a `verdict` enum ("pass" | "fail")
2071
+ * that always agree (`verdict: pass ? "pass" : "fail"`). The route is the
2072
+ * established `match("verdict", …)` gate idiom (mirrors `validate`'s own route:
2073
+ * `match("verdict", { commit: "pass" }, …)` — no-match ⇒ STOP, the same fail
2074
+ * behavior). It is deliberately NOT the `defineRoute`/`allDimensionsPass`
2075
+ * pattern the citation floors use: `allDimensionsPass` applies a severity floor
2076
+ * (pass === true || severity low/none), so a failing scope check rated low
2077
+ * severity would silently pass the gate — the exact escape class the lane floor
2078
+ * exists to catch. The `from` form suppresses the `READS_DATA` outputSchema lint,
2079
+ * so no schema is declared on the script stage (matching `slice-check`/
2080
+ * `plan-cite-check`).
2081
+ */
2082
+ const implementScopeCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2083
+ const latest = latestFsArtifact(state, "plans");
2084
+ if (latest?.handle.kind !== "fs") {
2085
+ throw haltPreflight(
2086
+ "implement-scope-check",
2087
+ "implement-scope-check: no plan to scope-check",
2088
+ "implement-scope-check: no fs artifact on the 'plans' channel — implement must run before the scope check",
2089
+ );
2090
+ }
2091
+ const body = readArtifactFile(latest.handle.path, cwd);
2092
+ const records = planPhaseRecords(body, "implement-scope-check", latest.handle.path);
2093
+ // Declared write-set = union of every phase's `files:` (via `phaseFiles`).
2094
+ // A `files:`-less plan yields `[]` ⇒ `scopeExcess` returns `[]` ⇒ inert floor.
2095
+ const declared = records.flatMap((r) => phaseFiles(r.entry));
2096
+
2097
+ // Run-start baseline (goal channel, role "baseline") + current dirty set —
2098
+ // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
2099
+ const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
2100
+ const dirty = gitDirtyPaths(cwd);
2101
+
2102
+ const excess = scopeExcess(dirty, baseline, declared);
2103
+ const findings = excess.map((path) => ({
2104
+ 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.`,
2105
+ where: path,
2106
+ }));
2107
+ const pass = findings.length === 0;
2108
+ const data = {
2109
+ dimension: "scope",
2110
+ pass,
2111
+ verdict: pass ? "pass" : "fail",
2112
+ score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2113
+ severity: pass ? "none" : "high",
2114
+ artifact: handleToString(latest.handle),
2115
+ findings,
2116
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2117
+ };
2118
+ // Basename-keyed, NOT round-stamped (unlike grade's timestamped slug): each
2119
+ // fix-loop round overwrites the file. Deliberate — the route reads the
2120
+ // accumulating channel, and on disk only the latest round's scope verdict
2121
+ // matters; round-stamp here if a consumer ever needs the history.
2122
+ const rel = join(VERDICT_DIR, `implement-scope-check__${basename(latest.handle.path, ".md")}.json`);
2123
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2124
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2125
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2126
+ };
2127
+
2128
+ /**
2129
+ * vet's `implement-scope-check` — the loop-aware scope floor (twin of build's
2130
+ * `implementScopeCheck` above). Deterministic (no LLM): the implement lane may
2131
+ * write ONLY the paths a plan phase declares in its `files:` set; any other dirty
2132
+ * path (not in the run-start baseline, not under `.rpiv/`/`thoughts/`) is excess
2133
+ * and halts before `validate`.
2134
+ *
2135
+ * vet differs from build in ONE place: build's extra `plans` entries are
2136
+ * superseding amendments (`plan-fix` re-publishes the whole plan) so build reads
2137
+ * latest-only; vet's review-fix loop pushes a DISTINCT non-superseding fix plan
2138
+ * per iteration (completing a `produces` stage APPENDS to its named slot, and
2139
+ * backward jumps don't reset channels), so this function builds `declared` as the
2140
+ * UNION of Phase 1's `phaseFiles` over the FULL `state.named.plans` history — a
2141
+ * path a prior iteration's plan legitimately wrote is not excess against the
2142
+ * latest plan. The latest plan's handle is used ONLY for the basename-keyed
2143
+ * verdict path (idempotent across fix rounds) and the `artifact` field.
2144
+ *
2145
+ * Otherwise byte-for-byte `implementScopeCheck` above: the baseline via
2146
+ * `goalBaselinePath` (satisfied now that vet has a `goal` stage), the dirty set
2147
+ * via `git status --porcelain` with explicit `stdio`, the shared `scopeExcess`
2148
+ * core + `parseGitStatusPaths`, and the `dimension:"scope"` verdict
2149
+ * (carrying BOTH `pass` and `verdict` — the route is the `match("verdict", …)`
2150
+ * gate idiom, NOT `allDimensionsPass`, so a fail always halts) written to
2151
+ * `VERDICT_DIR`. Non-repo / git-missing ⇒ empty dirty ⇒ pass (never throws).
2152
+ * Basename-keyed off the latest plan ⇒ idempotent across review-fix rounds.
2153
+ */
2154
+ const implementScopeCheckVet = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2155
+ // Declared set = UNION of `phaseFiles` over EVERY non-failed plan on the channel.
2156
+ // The fs-artifact filter skips failed/unfilled entries (an Output with no fs
2157
+ // handle contributed no plan to read).
2158
+ const { declared, latest } = unionDeclaredWriteSet(state.named.plans ?? [], cwd);
2159
+ if (!latest) {
2160
+ throw haltPreflight(
2161
+ "implement-scope-check",
2162
+ "implement-scope-check: no plan to check",
2163
+ "implement-scope-check: no fs plan artifact on the 'plans' channel — blueprint/implement must run before the scope check",
2164
+ );
2165
+ }
2166
+
2167
+ // Run-start baseline (goal channel, role "baseline") + current dirty set —
2168
+ // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
2169
+ const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
2170
+ const dirty = gitDirtyPaths(cwd);
2171
+
2172
+ // Shared core: subtract the run's bookkeeping dirs (`.rpiv/`,
2173
+ // `thoughts/`) and the run-start baseline; empty-`declared` ⇒ `[]` (degradation
2174
+ // ⇒ inert floor — a fully `files:`-less plan never false-fails).
2175
+ const excess = scopeExcess(dirty, baseline, [...declared]);
2176
+ const findings = excess.map((p) => ({
2177
+ 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.`,
2178
+ where: p,
2179
+ }));
2180
+ const pass = findings.length === 0;
2181
+ const data = {
2182
+ dimension: "scope",
2183
+ pass,
2184
+ verdict: pass ? "pass" : "fail",
2185
+ score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2186
+ severity: pass ? "none" : "high",
2187
+ artifact: handleToString(latest.handle),
2188
+ findings,
2189
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2190
+ };
2191
+ // Basename-keyed, NOT round-stamped (unlike grade's timestamped slug): each
2192
+ // fix-loop round overwrites the file. Deliberate — the route reads the
2193
+ // accumulating channel, and on disk only the latest round's scope verdict
2194
+ // matters; round-stamp here if a consumer ever needs the history.
2195
+ const rel = join(VERDICT_DIR, `implement-scope-check__${basename(latest.handle.path, ".md")}.json`);
2196
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2197
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2198
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2199
+ };
2200
+
2201
+ /**
2202
+ * One `#### Reconciliation` directive parsed from a plan body: a machine-applicable
2203
+ * `find → replace` against a single test-expectation file. The implement lane records
2204
+ * these in a phase's OWN section when a correct change invalidates a test that lives
2205
+ * in a sibling phase's landed section (which the implementer may NOT edit); `reconcile`
2206
+ * applies them write-restricted to `*.test.*` targets.
2207
+ */
2208
+ interface ReconciliationDirective {
2209
+ /** Repo-root-relative test target (`*.test.*`). */
2210
+ target: string;
2211
+ /** Substring to find (replaced exactly once via `String.replace`). */
2212
+ find: string;
2213
+ /** Replacement string. */
2214
+ replace: string;
2215
+ }
2216
+
2217
+ /** Directive grammar: `` - `<target>`: replace `<find>` → `<replace>` — <rationale> ``.
2218
+ * The `→` (U+2192) separates find/replace; the em-dash `—` (U+2014) + rationale is
2219
+ * optional. Find/replace carry no inner backticks. The two spans are intentionally
2220
+ * asymmetric and MUST NOT be symmetrized: `find` is one-or-more `[^`]+` (an empty
2221
+ * find has no anchored target and `String.replace("")` prepends the replacement on
2222
+ * every run, so the parser rejects it at parse time), while `replace` is
2223
+ * zero-or-more `[^`]*` (an empty replace is a legitimate deletion directive). */
2224
+ const RECONCILE_DIRECTIVE_RE = /^-\s+`([^`]+)`\s*:\s*replace\s+`([^`]+)`\s*→\s*`([^`]*)`\s*(?:—\s+.*)?$/;
2225
+ /** A directive ATTEMPT — `- `<target>`:` — that does not match the full grammar. Used
2226
+ * to surface a malformed directive as a finding rather than silently dropping it. */
2227
+ const RECONCILE_DIRECTIVE_ATTEMPT_RE = /^-\s+`[^`]+`\s*:/;
2228
+
2229
+ /**
2230
+ * Parse every `#### Reconciliation` directive from a plan body. Returns the
2231
+ * well-formed directives AND the malformed attempts (lines that carry the
2232
+ * `- `<target>`:` shape but not the full `replace … → …` grammar); `reconcile`
2233
+ * turns each malformed attempt into a finding so a broken directive is visible,
2234
+ * never silently dropped. Prose list items are ignored. Pure: no I/O, no throw.
2235
+ * A section opens at a `#### Reconciliation` heading and closes at the next
2236
+ * `#{1,4}` heading (so `### Success Criteria` / `## Phase N:` / a sibling
2237
+ * `#### Automated Verification:` all end it).
2238
+ */
2239
+ const reconciliationRecords = (
2240
+ body: string,
2241
+ ): {
2242
+ directives: ReconciliationDirective[];
2243
+ malformed: string[];
2244
+ } => {
2245
+ const directives: ReconciliationDirective[] = [];
2246
+ const malformed: string[] = [];
2247
+ let inSection = false;
2248
+ for (const raw of body.split("\n")) {
2249
+ const line = raw.trimEnd();
2250
+ if (/^####\s+Reconciliation\b/.test(line)) {
2251
+ inSection = true;
2252
+ continue;
2253
+ }
2254
+ // Any other heading ends the section (the open-heading branch above `continue`s,
2255
+ // so this only fires for non-`#### Reconciliation` headings).
2256
+ if (/^#{1,4}\s/.test(line)) {
2257
+ inSection = false;
2258
+ continue;
2259
+ }
2260
+ if (!inSection) continue;
2261
+ const m = RECONCILE_DIRECTIVE_RE.exec(line);
2262
+ if (m) {
2263
+ directives.push({ target: m[1]!.trim(), find: m[2]!, replace: m[3]! });
2264
+ } else if (RECONCILE_DIRECTIVE_ATTEMPT_RE.test(line)) {
2265
+ malformed.push(line.trim());
2266
+ }
2267
+ }
2268
+ return { directives, malformed };
2269
+ };
2270
+
2271
+ /** Checkbox-AV line: `- [ ] `<command>`` or `- [x] `<command>``. The first
2272
+ * backtick-wrapped span is the command; prose backticks after it are ignored. */
2273
+ const AV_COMMAND_LINE_RE = /^-\s+\[[ xX]\]\s*`([^`]+)`/;
2274
+
2275
+ /**
2276
+ * Extract every per-phase `#### Automated Verification:` line from a plan body —
2277
+ * both `- [ ]` (pending) and `- [x]` (checked) — as `{ command, tail }`:
2278
+ * `command` is the first backtick span (the ONLY part `reconcile` executes),
2279
+ * `tail` is the prose after it (never executed — `verifyAvCommandContract`
2280
+ * lints it for semantics the exit-0 re-run cannot honor). A section opens at a
2281
+ * `#### Automated Verification:` heading and closes at the next `#{1,4}` heading.
2282
+ * Pure: no I/O, no throw.
2283
+ */
2284
+ const planVerificationRecords = (body: string): { command: string; tail: string }[] => {
2285
+ const records: { command: string; tail: string }[] = [];
2286
+ let inSection = false;
2287
+ for (const raw of body.split("\n")) {
2288
+ const line = raw.trimEnd();
2289
+ if (/^####\s+Automated Verification\b/.test(line)) {
2290
+ inSection = true;
2291
+ continue;
2292
+ }
2293
+ if (/^#{1,4}\s/.test(line)) {
2294
+ inSection = false;
2295
+ continue;
2296
+ }
2297
+ if (!inSection) continue;
2298
+ const m = AV_COMMAND_LINE_RE.exec(line);
2299
+ if (m) records.push({ command: m[1]!.trim(), tail: line.slice(m[0]!.length) });
2300
+ }
2301
+ return records;
2302
+ };
2303
+
2304
+ /** The command strings alone — `reconcile` re-runs each via `execFileSync`, fail-soft. */
2305
+ const planVerificationCommands = (body: string): string[] => planVerificationRecords(body).map((r) => r.command);
2306
+
2307
+ /**
2308
+ * The reconcile write-restriction's static allowlist — a conservative test-path
2309
+ * classifier. A directive may apply its `find → replace` ONLY to a co-located test
2310
+ * file (`*.test.{ts,tsx,js,jsx}`); any other target is flagged and left untouched
2311
+ * (fail-closed: golden masters, fixtures, `*.t.ts`, and production sources are NOT
2312
+ * auto-applied). Narrow by design — do not widen it to compensate for a weak
2313
+ * directive (correctness rests on this neither false-failing a legit test edit
2314
+ * nor false-allowing a non-test target).
2315
+ */
2316
+ const TEST_PATH_RE = /\.test\.[tj]sx?$/;
2317
+ const isTestPath = (target: string): boolean => TEST_PATH_RE.test(target);
2318
+
2319
+ /**
2320
+ * Split an AV command string into `{ exe, args }` for `execFileSync`, honoring
2321
+ * single/double quotes (so `grep -niE "a|b" x` tokenizes with the quotes stripped
2322
+ * and `node -e "process.exit(1)"` keeps `process.exit(1)` as one arg). Returns
2323
+ * `null` for an empty/whitespace command or an unterminated quote (caller flags
2324
+ * it). Minimal — no globbing, env expansion, or shell operators; AV commands are
2325
+ * simple invocations.
2326
+ */
2327
+ const parseShellCommand = (cmd: string): { exe: string; args: string[] } | null => {
2328
+ const tokens: string[] = [];
2329
+ let cur = "";
2330
+ let quote: '"' | "'" | null = null;
2331
+ for (let i = 0; i < cmd.length; i++) {
2332
+ const ch = cmd[i]!;
2333
+ if (quote) {
2334
+ if (ch === quote) quote = null;
2335
+ else cur += ch;
2336
+ } else if (ch === '"' || ch === "'") {
2337
+ quote = ch;
2338
+ } else if (/\s/.test(ch)) {
2339
+ if (cur !== "") {
2340
+ tokens.push(cur);
2341
+ cur = "";
2342
+ }
2343
+ } else {
2344
+ cur += ch;
2345
+ }
2346
+ }
2347
+ if (quote) return null; // unterminated quote — unparseable
2348
+ if (cur !== "") tokens.push(cur);
2349
+ const [exe, ...args] = tokens;
2350
+ return exe ? { exe, args } : null;
2351
+ };
2352
+
2353
+ /** grep-family executables: exit 1 on zero matches AND read stdin when no file
2354
+ * operand is given — both directly at odds with reconcile's exit-0/no-stdin
2355
+ * re-run harness, hence the two grep-specific lint rules below. */
2356
+ const AV_GREP_FAMILY = new Set(["grep", "egrep", "fgrep", "ggrep", "rg"]);
2357
+ /** grep-family flags that CONSUME the next token (so it is not a file operand). */
2358
+ const AV_GREP_VALUE_FLAGS = new Set([
2359
+ "-e",
2360
+ "--regexp",
2361
+ "-f",
2362
+ "--file",
2363
+ "-m",
2364
+ "--max-count",
2365
+ "-A",
2366
+ "-B",
2367
+ "-C",
2368
+ "--include",
2369
+ "--exclude",
2370
+ "--exclude-dir",
2371
+ "-g",
2372
+ "--glob",
2373
+ "-t",
2374
+ "--type",
2375
+ ]);
2376
+ /** Absence-assertion prose on a grep-family AV line — "success" is grep exit 1,
2377
+ * the exact inverse of the exit-0 contract. Deliberately a short literal list
2378
+ * of observed absence phrases, not a general negation detector. */
2379
+ const AV_ABSENCE_PROSE_RE = /returns nothing|no matches|no occurrences|is gone|must be gone/i;
2380
+ /** Extensions Biome's config COULD scope (biome.json includes *.ts/*.js + site
2381
+ * css/html). Fail-open: flag a Biome runner only when NO forwarded path can be
2382
+ * in scope (e.g. all-markdown) — "No files were processed" exits 1 under
2383
+ * `--error-on-warnings` regardless of tree state. */
2384
+ const AV_BIOME_SCOPED_PATH_RE = /\.(?:ts|tsx|js|jsx|mjs|cjs|css|html|json|jsonc)$/i;
2385
+
2386
+ /**
2387
+ * Plan-time lint of `#### Automated Verification:` lines against `reconcile`'s
2388
+ * execution contract: reconcile re-runs ONLY the first backtick span of each
2389
+ * checkbox line via `execFileSync` — arg-array (no shell), stdin ignored, exit 0
2390
+ * the sole pass signal — so prose qualifiers around the span never execute.
2391
+ * Folded into `planCitationCheck` (both the `plan-cite-check` and
2392
+ * `code-cite-check` arms) so a violating AV line fails INTO the plan-fix loop,
2393
+ * not at `reconcile` where the route is STOP with no fix arm (an AV line
2394
+ * correct as prose but unsatisfiable as an exit-0 command would halt there).
2395
+ * Narrow by design — each rule targets an observed
2396
+ * false-class, fail-open otherwise; do NOT widen into a general shell linter:
2397
+ * 1. unparseable command (unterminated quote / empty) — reconcile would flag
2398
+ * it anyway; surfacing it here buys a fix round instead of a halt;
2399
+ * 2. grep-family with no file operand — under reconcile's stdin-ignored
2400
+ * harness it scans an empty stream and exits 1 regardless of tree state
2401
+ * (the file argument usually sits in prose OUTSIDE the span);
2402
+ * 3. grep-family whose prose tail asserts absence ("returns nothing") —
2403
+ * success-by-absence IS grep exit 1, the inverse of the contract;
2404
+ * 4. a Biome runner whose forwarded paths are all outside Biome's possible
2405
+ * scope — "No files were processed" exits 1 under `--error-on-warnings`.
2406
+ */
2407
+ const verifyAvCommandContract = (body: string): { detail: string; where: string }[] => {
2408
+ const findings: { detail: string; where: string }[] = [];
2409
+ for (const { command, tail } of planVerificationRecords(body)) {
2410
+ const parsed = parseShellCommand(command);
2411
+ if (!parsed) {
2412
+ findings.push({
2413
+ detail: `Automated Verification command is unparseable under reconcile's tokenizer (empty or unterminated quote) — \`${command}\`. Reconcile re-runs the first backtick span verbatim via execFileSync; rewrite the span as a single well-quoted command.`,
2414
+ where: command,
2415
+ });
2416
+ continue;
2417
+ }
2418
+ const exe = parsed.exe.split("/").pop() ?? parsed.exe;
2419
+ if (AV_GREP_FAMILY.has(exe)) {
2420
+ // Count file operands: tokens that are not flags and not a value a flag
2421
+ // consumed. With -e/-f the pattern arrives via flag, so EVERY remaining
2422
+ // operand is a file; otherwise the first operand is the pattern.
2423
+ let patternViaFlag = false;
2424
+ const operands: string[] = [];
2425
+ for (let i = 0; i < parsed.args.length; i++) {
2426
+ const a = parsed.args[i]!;
2427
+ if (a === "--") {
2428
+ operands.push(...parsed.args.slice(i + 1));
2429
+ break;
2430
+ }
2431
+ if (a.startsWith("-")) {
2432
+ if (a === "-e" || a === "--regexp" || a === "-f" || a === "--file") patternViaFlag = true;
2433
+ if (AV_GREP_VALUE_FLAGS.has(a)) i++;
2434
+ continue; // `--include=*.ts` style is self-contained
2435
+ }
2436
+ operands.push(a);
2437
+ }
2438
+ const fileOperands = patternViaFlag ? operands.length : operands.length - 1;
2439
+ if (fileOperands < 1) {
2440
+ findings.push({
2441
+ detail: `Automated Verification \`${command}\` names no file operand — reconcile re-runs it with stdin ignored, so it scans an empty stream and exits non-zero regardless of the tree. Put the target path INSIDE the backtick span (prose like "over \`<file>\`" is never executed).`,
2442
+ where: command,
2443
+ });
2444
+ }
2445
+ if (AV_ABSENCE_PROSE_RE.test(tail)) {
2446
+ findings.push({
2447
+ detail: `Automated Verification \`${command}\` asserts absence in prose ("${AV_ABSENCE_PROSE_RE.exec(tail)?.[0]}") — grep exits 1 on zero matches, so this line's success IS a non-zero exit and reconcile will always fail it. Restate it as a command that exits 0 on success (e.g. a \`node -e\` probe) or move it to Manual Verification.`,
2448
+ where: command,
2449
+ });
2450
+ }
2451
+ }
2452
+ // Biome runners: `npm run check:files -- <paths>` / `npx biome check <paths>`.
2453
+ const isCheckFiles = exe === "npm" && parsed.args[0] === "run" && parsed.args[1] === "check:files";
2454
+ const isBiome = (exe === "npx" && parsed.args[0] === "biome") || exe === "biome";
2455
+ if (isCheckFiles || isBiome) {
2456
+ const paths = parsed.args.filter((a) => !a.startsWith("-") && /[\\/.]/.test(a));
2457
+ // Flag ONLY when every forwarded path carries an out-of-scope extension —
2458
+ // a directory operand (no extension) may legitimately scope, so fail open.
2459
+ if (
2460
+ paths.length > 0 &&
2461
+ paths.every((p) => /\.[a-z\d]+$/i.test(p)) &&
2462
+ !paths.some((p) => AV_BIOME_SCOPED_PATH_RE.test(p))
2463
+ ) {
2464
+ findings.push({
2465
+ detail: `Automated Verification \`${command}\` passes Biome only paths outside its configured scope (biome.json covers code files, not e.g. markdown) — Biome reports "No files were processed" and exits non-zero under --error-on-warnings, so reconcile will always fail it. Drop the line for doc-only phases or include an in-scope path.`,
2466
+ where: command,
2467
+ });
2468
+ }
2469
+ }
2470
+ }
2471
+ return findings;
2472
+ };
2473
+
2474
+ /**
2475
+ * Apply each `#### Reconciliation` directive, write-restricted to test-expectation
2476
+ * files (`isTestPath` — reconcile writes ONLY test files; a non-test target is a
2477
+ * finding, left untouched, fail-closed). A present `find` is replaced exactly
2478
+ * once (`String.replace`, first match); an absent `find` whose `replace` is ALSO
2479
+ * absent is a finding (reconcile does not guess); an absent `find` whose `replace`
2480
+ * is already present is the idempotent-re-run no-op (a prior successful apply, no
2481
+ * finding, no write). Paths resolve through `cwd` (`isAbsolute` short-circuit else
2482
+ * `join(cwd, target)`). Fail-soft: a read/apply throw degrades to a finding naming
2483
+ * the target, never a terminal throw. Returns findings in DIRECTIVE order and
2484
+ * performs the side-effecting writes itself (`reconcile` spreads the return).
2485
+ */
2486
+ const applyReconciliationDirectives = (
2487
+ directives: readonly ReconciliationDirective[],
2488
+ cwd: string,
2489
+ ): { detail: string; where: string }[] => {
2490
+ const findings: { detail: string; where: string }[] = [];
2491
+ // Apply directives, write-restricted to test-expectation files.
2492
+ for (const d of directives) {
2493
+ if (!isTestPath(d.target)) {
2494
+ findings.push({
2495
+ 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`,
2496
+ where: d.target,
2497
+ });
2498
+ continue;
2499
+ }
2500
+ try {
2501
+ const abs = isAbsolute(d.target) ? d.target : join(cwd, d.target);
2502
+ const content = readFileSync(abs, "utf-8");
2503
+ if (content.includes(d.find)) {
2504
+ // `String.replace` with a string pattern replaces the FIRST match exactly once.
2505
+ writeFileSync(abs, content.replace(d.find, d.replace), "utf-8");
2506
+ } else if (d.replace !== "" && content.includes(d.replace)) {
2507
+ // Idempotent re-run: the find is gone but the replacement is present ⇒ the
2508
+ // directive was already applied (e.g. a vet review-fix loop re-running
2509
+ // reconcile). Treated as satisfied — reconcile must not fail on its own
2510
+ // prior successful apply.
2511
+ } else {
2512
+ findings.push({
2513
+ 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`,
2514
+ where: d.target,
2515
+ });
2516
+ }
2517
+ } catch (err) {
2518
+ findings.push({
2519
+ detail: `reconcile: could not apply directive to ${d.target} — ${err instanceof Error ? err.message : String(err)}`,
2520
+ where: d.target,
2521
+ });
2522
+ }
2523
+ }
2524
+ return findings;
2525
+ };
2526
+
2527
+ /**
2528
+ * Re-run every per-phase `#### Automated Verification:` command via `execFileSync`
2529
+ * — arg-array (no shell), stdin ignored, exit 0 expected. An unparseable command
2530
+ * (`parseShellCommand` ⇒ null) is a finding naming it; a non-zero exit or throw is
2531
+ * a finding naming it (fail-soft — reconcile never throws on AV failure; a thrown
2532
+ * command degrades to the same non-zero finding). Returns findings in COMMAND
2533
+ * order. `reconcile` spreads the return into its findings array.
2534
+ */
2535
+ const rerunAvCommands = (commands: readonly string[], cwd: string): { detail: string; where: string }[] => {
2536
+ const findings: { detail: string; where: string }[] = [];
2537
+ // Re-run every per-phase AV command (fail-soft: non-zero/throw ⇒ a finding).
2538
+ for (const cmd of commands) {
2539
+ const parsed = parseShellCommand(cmd);
2540
+ if (!parsed) {
2541
+ findings.push({
2542
+ detail: `reconcile: Automated Verification command unparseable — \`${cmd}\``,
2543
+ where: cmd,
2544
+ });
2545
+ continue;
2546
+ }
2547
+ try {
2548
+ execFileSync(parsed.exe, parsed.args, {
2549
+ cwd,
2550
+ encoding: "utf-8",
2551
+ stdio: ["ignore", "pipe", "pipe"],
2552
+ });
2553
+ } catch {
2554
+ findings.push({
2555
+ detail: `reconcile: Automated Verification command failed (non-zero) — \`${cmd}\``,
2556
+ where: cmd,
2557
+ });
2558
+ }
2559
+ }
2560
+ return findings;
2561
+ };
2562
+
2563
+ /**
2564
+ * Deterministic post-implement reconciliation — the coherence backstop the
2565
+ * parallel implement lane needs. Sibling phases run concurrently in one tree;
2566
+ * each phase's own `#### Automated Verification:` passed in isolation, but a
2567
+ * phase's correct change can invalidate a test that lives in a SIBLING phase's
2568
+ * landed section (which the implementer may not edit), and the combined tree can
2569
+ * break in ways no single phase's checks surface. `reconcile` runs after the
2570
+ * scope floor (which proved the write-set) and before `validate`:
2571
+ *
2572
+ * 1. reads the latest plan (`latestFsArtifact(state, "plans")` — latest-wins);
2573
+ * 2. parses every `#### Reconciliation` directive + every per-phase
2574
+ * `#### Automated Verification:` command — fail-soft (a malformed directive
2575
+ * / unreadable plan degrades to a finding, never a terminal `FAIL_SCRIPT_THREW`
2576
+ * halt — a `produces.script` that throws becomes one);
2577
+ * 3. applies each directive write-restricted to test paths (`isTestPath`); a
2578
+ * present `find` is replaced exactly once (`String.replace`); an absent `find`
2579
+ * whose replacement is ALSO absent is a finding (reconcile does not guess);
2580
+ * 4. re-runs every AV command via `execFileSync` (fail-soft: non-zero/throw ⇒ a
2581
+ * finding naming the command);
2582
+ * 5. appends a timestamped `### Reconciliation Log (<iso>)` under the plan's
2583
+ * `## Synthesis Notes` (best-effort bookkeeping write — non-fatal);
2584
+ * 6. emits one `{ dimension: "reconcile" }` verdict, basename-keyed off the plan
2585
+ * ⇒ idempotent across fix rounds (the verdict file is overwritten each round).
2586
+ *
2587
+ * The route is the `match("verdict", …, { from: "reconcile" })` gate idiom — pass ⇒
2588
+ * validate, fail/missing ⇒ STOP (no fallback), mirroring `implementScopeCheck`.
2589
+ * Mirrors `implementScopeCheck`'s `ScriptContext` shape, basename-keyed verdict
2590
+ * path, and `dimension`/`pass`/`verdict`/`score`/`severity` data shape. `reads:
2591
+ * ["plans"]` only — reconcile consumes no run-start `goal` baseline (the scope
2592
+ * floor already proved the write-set; reconcile's own writes are directive targets
2593
+ * + the plan bookkeeping). The `from` form suppresses the READS_DATA outputSchema
2594
+ * lint, so no schema is declared (matching `slice-check`/`plan-cite-check`/
2595
+ * `implement-scope-check`).
2596
+ */
2597
+ const reconcile = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2598
+ const latest = latestFsArtifact(state, "plans");
2599
+ if (latest?.handle.kind !== "fs") {
2600
+ throw haltPreflight(
2601
+ "reconcile",
2602
+ "reconcile: no plan to reconcile",
2603
+ "reconcile: no fs artifact on the 'plans' channel — implement / scope-check must run before reconcile",
2604
+ );
2605
+ }
2606
+ const planPath = latest.handle.path;
2607
+ const planAbs = isAbsolute(planPath) ? planPath : join(cwd, planPath);
2608
+ const findings: { detail: string; where: string }[] = [];
2609
+
2610
+ // Fail-soft read + parse: an unreadable plan, malformed directive, or broken AV
2611
+ // section degrades to a finding, never a terminal throw. If the read fails there
2612
+ // is nothing to apply or re-run.
2613
+ let body = "";
2614
+ let directives: ReconciliationDirective[] = [];
2615
+ let malformed: string[] = [];
2616
+ let commands: string[] = [];
2617
+ try {
2618
+ body = readArtifactFile(planPath, cwd);
2619
+ const parsed = reconciliationRecords(body);
2620
+ directives = parsed.directives;
2621
+ malformed = parsed.malformed;
2622
+ commands = planVerificationCommands(body);
2623
+ } catch (err) {
2624
+ findings.push({
2625
+ detail: `reconcile: could not read or parse the plan ${planPath} — ${err instanceof Error ? err.message : String(err)}`,
2626
+ where: planPath,
2627
+ });
2628
+ }
2629
+ for (const m of malformed) {
2630
+ findings.push({
2631
+ detail: `reconcile: malformed Reconciliation directive — expected a line of the form: - \`<target>\`: replace \`<find>\` → \`<replace>\` (target/find/replace each backtick-wrapped) — ${m}`,
2632
+ where: "reconciliation-directive",
2633
+ });
2634
+ }
2635
+
2636
+ findings.push(...applyReconciliationDirectives(directives, cwd), ...rerunAvCommands(commands, cwd));
2637
+
2638
+ // Best-effort bookkeeping: append a timestamped log under ## Synthesis Notes.
2639
+ // Non-fatal — a write failure here is silent (the verdict below is the signal).
2640
+ if (body) {
2641
+ try {
2642
+ const stamp = new Date().toISOString();
2643
+ const verdict = findings.length === 0 ? "pass" : "fail";
2644
+ const logBlock = `\n### Reconciliation Log (${stamp})\nApplied ${directives.length} directive(s); ${findings.length} finding(s); verdict: ${verdict}.\n`;
2645
+ const heading = "## Synthesis Notes";
2646
+ const idx = body.indexOf(heading);
2647
+ let updated: string;
2648
+ if (idx >= 0) {
2649
+ const lineEnd = body.indexOf("\n", idx);
2650
+ const at = lineEnd >= 0 ? lineEnd + 1 : body.length;
2651
+ updated = body.slice(0, at) + logBlock + body.slice(at);
2652
+ } else {
2653
+ updated = `${body.replace(/\s+$/, "")}\n${logBlock}`;
2654
+ }
2655
+ writeFileSync(planAbs, updated, "utf-8");
2656
+ } catch {
2657
+ // bookkeeping — ignore
2658
+ }
2659
+ }
2660
+
2661
+ const pass = findings.length === 0;
2662
+ const data = {
2663
+ dimension: "reconcile",
2664
+ pass,
2665
+ verdict: pass ? "pass" : "fail",
2666
+ score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2667
+ severity: pass ? "none" : "high",
2668
+ artifact: handleToString(latest.handle),
2669
+ findings,
2670
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2671
+ };
2672
+ // Basename-keyed off the latest plan ⇒ idempotent across fix rounds (mirrors
2673
+ // implementScopeCheck / planCitationCheck, NOT round-stamped like grade).
2674
+ const rel = join(VERDICT_DIR, `reconcile__${basename(planPath, ".md")}.json`);
2675
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2676
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2677
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2678
+ };
2679
+
2680
+ /** A design filename encodes its slice as `…slice-<N>…` — the design-fanout naming convention. */
2681
+ const DESIGN_SLICE_RE = /slice-(\d+)/;
2682
+
2683
+ /**
2684
+ * Map slice number → its design artifact path, from the design fanout's published
2685
+ * outputs. An identity resolver: it maps an ARTIFACT to a slice NUMBER. It FAILS
2686
+ * LOUD only when identity is genuinely UNRESOLVABLE — a design filename that
2687
+ * carries no `slice-<N>` token, where a positional `idx + 1` guess would scramble
2688
+ * the cluster→design wiring and drop slices.
2689
+ *
2690
+ * A slice claimed by MORE THAN ONE output is NOT ambiguous: the `designs` channel
2691
+ * legitimately accumulates several entries per slice — `slice-design` emits it,
2692
+ * then `design-review` re-emits the accepted/edited design on the SAME channel
2693
+ * (its documented "latest-wins, same paths" contract, so `subplan`/`synthesize`
2694
+ * read the accepted docs). So the newest entry wins, deterministically — throwing
2695
+ * on a duplicate would halt every normal run at `subplan`. (The resume re-dispatch
2696
+ * that once left CONFLICTING designs on the channel is fixed at its source,
2697
+ * so there is no corruption left to fail loud on here.)
2698
+ */
2699
+ const designPathsBySlice = (state: RunView): Map<number, string> => {
2700
+ const bySlice = new Map<number, string>();
2701
+ for (const out of state.named.designs ?? []) {
2702
+ for (const a of out.artifacts) {
2703
+ if (a.handle.kind !== "fs") continue;
2704
+ const name = basename(a.handle.path);
2705
+ const match = DESIGN_SLICE_RE.exec(name);
2706
+ if (!match) {
2707
+ throw haltPreflight(
2708
+ "designPathsBySlice",
2709
+ `designPathsBySlice: design ${name} has no slice number`,
2710
+ `designPathsBySlice: design artifact ${a.handle.path} carries no 'slice-<N>' token — cannot resolve which slice it designs; a positional guess would mis-route the cluster→design mapping and drop slices`,
2711
+ );
2712
+ }
2713
+ // Latest design per slice wins — the channel holds multiple entries per
2714
+ // slice by design (design-review re-emits), and the newest is authoritative.
2715
+ bySlice.set(Number(match[1]), handleToString(a.handle));
2716
+ }
2717
+ }
2718
+ return bySlice;
2719
+ };
2720
+
2721
+ /**
2722
+ * Fan `subplan` out over slice-DAG clusters. Each unit merges ONE cluster's
2723
+ * per-slice designs into a sub-plan (`--as-subplan`), so no single pass holds
2724
+ * every design — the context-bounding twin of the flat fan-in `synthesize`.
2725
+ */
2726
+ const SYNTH_CLUSTER_FANOUT = fanout({
2727
+ source: "designs",
2728
+ unit: { by: "slice-dag-cluster", pattern: "clusters" },
1220
2729
  max: MAX_PHASES,
1221
2730
  units: ({ state, cwd }) => {
1222
2731
  const doc = latestFsArtifact(state, "slices");
@@ -1238,7 +2747,10 @@ const SYNTH_CLUSTER_FANOUT = fanout({
1238
2747
  .map((p) => `--designs ${p}`);
1239
2748
  if (!designs.length) return undefined;
1240
2749
  return {
1241
- prompt: `${designs.join(" ")}${researchFlag} --as-subplan`,
2750
+ // Stamp each cluster's ordinal into its prompt so the partial-mode pass
2751
+ // writes a distinct `_cluster-<k>.md` — a re-dispatched unit must never
2752
+ // reuse a sibling's filename and clobber it. `<k>` matches `id: cluster-<k>`.
2753
+ prompt: `${designs.join(" ")}${researchFlag} --cluster ${i + 1} --as-subplan`,
1242
2754
  label: `cluster ${i + 1} (slices ${cluster.join(",")})`,
1243
2755
  id: `cluster-${i + 1}`,
1244
2756
  };
@@ -1397,18 +2909,216 @@ const latestVerdictPerDimension = (entries: readonly Output[] = []): Map<string,
1397
2909
  * channel + `allDimensionsPass`'s latest-per-dimension fold mean a carried
1398
2910
  * dimension's prior passing verdict still counts at the gate.
1399
2911
  */
1400
- const dimensionsToRegrade = (dimensions: readonly string[], latest: ReadonlyMap<string, Output>): string[] => {
2912
+ const dimensionsToRegrade = (
2913
+ dimensions: readonly string[],
2914
+ latest: ReadonlyMap<string, Output>,
2915
+ risks: ReadonlyMap<string, RiskRecord> = new Map(),
2916
+ ): string[] => {
1401
2917
  return dimensions.filter((d) => {
1402
2918
  const o = latest.get(d);
1403
2919
  if (!o) return true; // never graded — must grade at least once
1404
2920
  const v = o.data as { pass?: boolean; severity?: string } | undefined;
1405
2921
  const dimPass = v?.pass === true || v?.severity === "low" || v?.severity === "none";
1406
2922
  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);
2923
+ return verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
1409
2924
  });
1410
2925
  };
1411
2926
 
2927
+ /**
2928
+ * Coarse line-count backstop for the surgical-fix guard. The subset test
2929
+ * (`touchedSections − HOUSEKEEPING ⊆ cited`) is the binding constraint — do
2930
+ * NOT tighten this to compensate for a weak subset test.
2931
+ */
2932
+ const NON_SURGICAL_DIFF_LINE_THRESHOLD = 60;
2933
+
2934
+ /**
2935
+ * Plan sections amend ALWAYS bumps without the fix touching their meaning —
2936
+ * the pseudo-section `frontmatter` (via the `last_updated` field). Exempt from
2937
+ * the "touched outside cited" test. Starts at `{frontmatter}` only; do not
2938
+ * pre-widen (a genuinely-meaningful bookkeeping section would let a broad amend
2939
+ * pass the subset test by touching it).
2940
+ */
2941
+ const HOUSEKEEPING_SECTIONS: ReadonlySet<string> = new Set(["frontmatter"]);
2942
+
2943
+ /** Directory the snapshot stages copy the pre-fix plan into (basename-keyed). */
2944
+ const PRIOR_DIR = ".rpiv/artifacts/priors";
2945
+
2946
+ /**
2947
+ * Map each line index to its plan-section name: the nearest preceding `## `
2948
+ * heading — `## Phase N: …` normalizes to `phase N` (case-insensitive); any
2949
+ * other heading is lowercased by tail — so touched-section keys and cited-section
2950
+ * keys share one space. The frontmatter block (opening `---` through its closing
2951
+ * `---`) is the pseudo-section `frontmatter`. Lines before the first heading and
2952
+ * outside frontmatter map to `""` (which is neither housekeeping nor a `phase N`
2953
+ * cite, so any change there is treated as out-of-scope).
2954
+ */
2955
+ const sectionIndexOf = (lines: readonly string[]): string[] => {
2956
+ const idx = new Array<string>(lines.length);
2957
+ let current = "";
2958
+ let inFrontmatter = lines[0]?.trim() === "---";
2959
+ for (let i = 0; i < lines.length; i++) {
2960
+ if (inFrontmatter) {
2961
+ idx[i] = "frontmatter";
2962
+ if (i > 0 && lines[i].trim() === "---") inFrontmatter = false;
2963
+ continue;
2964
+ }
2965
+ const m = /^##\s+(.*)$/.exec(lines[i]);
2966
+ if (m) {
2967
+ const ph = /^Phase\s+(\d+)/i.exec(m[1].trim());
2968
+ current = ph ? `phase ${ph[1]}` : m[1].trim().toLowerCase();
2969
+ }
2970
+ idx[i] = current;
2971
+ }
2972
+ return idx;
2973
+ };
2974
+
2975
+ /**
2976
+ * Line-level diff of `prior` vs `current` plan bodies, mapped to plan sections.
2977
+ * Each changed line (a deletion from `prior` OR an insertion in `current` under
2978
+ * an LCS match) is attributed to its nearest preceding `## ` heading in its own
2979
+ * document. Returns the union of touched section keys and a coarse changed-line
2980
+ * count (deletions + insertions). Insertion-tolerant: a 1-line insert does not
2981
+ * mark every trailing line changed (the LCS keeps shared context matched).
2982
+ */
2983
+ const sectionDiff = (prior: string, current: string): { touchedSections: Set<string>; changedLines: number } => {
2984
+ const a = prior.split("\n");
2985
+ const b = current.split("\n");
2986
+ const sa = sectionIndexOf(a);
2987
+ const sb = sectionIndexOf(b);
2988
+ // LCS length table (bottom-up). Plans are a few hundred lines ⇒ O(n·m) trivial.
2989
+ const dp: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
2990
+ for (let i = a.length - 1; i >= 0; i--) {
2991
+ for (let j = b.length - 1; j >= 0; j--) {
2992
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
2993
+ }
2994
+ }
2995
+ const touched = new Set<string>();
2996
+ let changed = 0;
2997
+ let i = 0;
2998
+ let j = 0;
2999
+ while (i < a.length && j < b.length) {
3000
+ if (a[i] === b[j]) {
3001
+ i++;
3002
+ j++;
3003
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
3004
+ touched.add(sa[i]); // a[i] deleted (present in prior, absent in current)
3005
+ changed++;
3006
+ i++;
3007
+ } else {
3008
+ touched.add(sb[j]); // b[j] inserted (present in current, absent in prior)
3009
+ changed++;
3010
+ j++;
3011
+ }
3012
+ }
3013
+ while (i < a.length) {
3014
+ touched.add(sa[i]);
3015
+ changed++;
3016
+ i++;
3017
+ }
3018
+ while (j < b.length) {
3019
+ touched.add(sb[j]);
3020
+ changed++;
3021
+ j++;
3022
+ }
3023
+ return { touchedSections: touched, changedLines: changed };
3024
+ };
3025
+
3026
+ /**
3027
+ * Plan sections cited by the FAILING dimensions' findings — extracted from each
3028
+ * finding's `where` and `detail` (`Phase N` → `phase N`, lowercased). Preferred
3029
+ * `where: "Phase 1 > lane-dock-editor.ts Edit 1"` → `phase 1`; a repo
3030
+ * `path:line`-only `where` (and a detail with no `Phase N`) contributes NO plan
3031
+ * section. Empty when no failing finding carries an extractable plan-section
3032
+ * reference — fail-closed: the caller treats an empty cite set against any
3033
+ * non-housekeeping touched section as out-of-scope (non-surgical).
3034
+ */
3035
+ const citedSections = (latest: ReadonlyMap<string, Output>, pending: readonly string[]): Set<string> => {
3036
+ const cited = new Set<string>();
3037
+ for (const d of pending) {
3038
+ const findings = (latest.get(d)?.data as { findings?: unknown } | undefined)?.findings;
3039
+ if (!Array.isArray(findings)) continue;
3040
+ for (const f of findings) {
3041
+ if (f == null || typeof f !== "object") continue;
3042
+ const where = typeof (f as { where?: unknown }).where === "string" ? (f as { where: string }).where : "";
3043
+ const detail = typeof (f as { detail?: unknown }).detail === "string" ? (f as { detail: string }).detail : "";
3044
+ for (const text of [where, detail]) {
3045
+ for (const m of text.matchAll(/Phase\s+(\d+)/gi)) cited.add(`phase ${m[1]}`);
3046
+ }
3047
+ }
3048
+ }
3049
+ return cited;
3050
+ };
3051
+
3052
+ /**
3053
+ * The prior-role `fs` artifact the snapshot stage published on `priorChannel`
3054
+ * (undefined when the channel carries no prior — round 1 / first re-grade).
3055
+ * Existence of the ENTRY is distinct from readability of the sidecar: an entry
3056
+ * that exists but cannot be read still counts as "prior present" so the caller
3057
+ * fails closed to a FULL roster rather than silently carrying forward.
3058
+ */
3059
+ const priorArtifact = (state: RunView, priorChannel: string): Artifact | undefined => {
3060
+ const entry = state.named[priorChannel]?.at(-1);
3061
+ const prior = entry?.artifacts.find((a) => a.handle.kind === "fs" && a.role === "prior");
3062
+ return prior?.handle.kind === "fs" ? prior : undefined;
3063
+ };
3064
+
3065
+ /**
3066
+ * Read the prior sidecar's bytes off `priorChannel`. Returns `undefined` when
3067
+ * the channel is empty, the prior artifact is not fs, OR the sidecar is
3068
+ * unreadable — the caller treats `undefined` as fail-closed (non-surgical).
3069
+ */
3070
+ const latestPriorContent = (state: RunView, priorChannel: string, cwd: string): string | undefined => {
3071
+ const prior = priorArtifact(state, priorChannel);
3072
+ if (prior?.handle.kind !== "fs") return undefined;
3073
+ try {
3074
+ return readArtifactFile(prior.handle.path, cwd);
3075
+ } catch {
3076
+ return undefined;
3077
+ }
3078
+ };
3079
+
3080
+ /**
3081
+ * True ONLY when a readable prior exists AND the current plan's diff from it
3082
+ * touches ONLY sections a failing finding cited (minus housekeeping) AND the
3083
+ * changed-line count is within the coarse threshold. Every missing signal — no
3084
+ * prior, unreadable sidecar, unreadable current plan, a diff/parse throw, a
3085
+ * touched section no failing finding cited, or an over-threshold diff —
3086
+ * collapses to `false` (fail-closed ⇒ the caller re-grades the full roster
3087
+ * when a prior is present, or carries forward when none is). `pending` is
3088
+ * consumed as-is: whatever `dimensionsToRegrade` ruled still-blocking (after
3089
+ * phase 3's `rulingEffectivePass` clause-3 rewrite) is the set this guard
3090
+ * narrows on.
3091
+ */
3092
+ const isSurgicalFix = (
3093
+ state: RunView,
3094
+ priorChannel: string,
3095
+ cwd: string,
3096
+ target: string,
3097
+ latest: ReadonlyMap<string, Output>,
3098
+ pending: readonly string[],
3099
+ ): boolean => {
3100
+ const prior = latestPriorContent(state, priorChannel, cwd);
3101
+ if (prior === undefined) return false;
3102
+ let current: string;
3103
+ try {
3104
+ current = readArtifactFile(target, cwd);
3105
+ } catch {
3106
+ return false;
3107
+ }
3108
+ let diff: { touchedSections: Set<string>; changedLines: number };
3109
+ try {
3110
+ diff = sectionDiff(prior, current);
3111
+ } catch {
3112
+ return false;
3113
+ }
3114
+ const cited = citedSections(latest, pending);
3115
+ for (const section of diff.touchedSections) {
3116
+ if (HOUSEKEEPING_SECTIONS.has(section)) continue;
3117
+ if (!cited.has(section)) return false;
3118
+ }
3119
+ return diff.changedLines <= NON_SURGICAL_DIFF_LINE_THRESHOLD;
3120
+ };
3121
+
1412
3122
  /**
1413
3123
  * A grade panel: one `grade` session per dimension over the latest artifact on
1414
3124
  * `channel`. Each unit's prompt is the `grade` skill's flags
@@ -1449,13 +3159,13 @@ const gradePanelFanout = (
1449
3159
  channel: string,
1450
3160
  dimensions: readonly string[],
1451
3161
  verdictChannel: string,
1452
- { confirm = false }: { confirm?: boolean } = {},
3162
+ { confirm = false, priorChannel }: { confirm?: boolean; priorChannel?: string } = {},
1453
3163
  ) =>
1454
3164
  fanout({
1455
3165
  source: channel,
1456
3166
  unit: { by: "dimension-list", pattern: "dimensions" },
1457
3167
  max: dimensions.length,
1458
- units: ({ state }) => {
3168
+ units: ({ state, cwd }) => {
1459
3169
  const doc = latestFsArtifact(state, channel);
1460
3170
  if (doc?.handle.kind !== "fs") return [];
1461
3171
  const target = handleToString(doc.handle);
@@ -1465,14 +3175,31 @@ const gradePanelFanout = (
1465
3175
  const goalFlag = goal?.handle.kind === "fs" ? ` --goal ${handleToString(goal.handle)}` : "";
1466
3176
  const roster = gateRoster(gateTier(state, verdictChannel), dimensions);
1467
3177
  const latest = latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel], target));
1468
- const pending = dimensionsToRegrade(roster, latest);
3178
+ const risks = planAuthoredRisks(state, channel);
3179
+ const pending = dimensionsToRegrade(roster, latest, risks);
3180
+ // Delta re-grade fallback guard (plan/code gates only — `priorChannel`
3181
+ // is unset for the slice gate and both confirm panels). When the snapshot
3182
+ // stage published a prior, compare it to the current plan: a SURGICAL
3183
+ // amend (touched only sections a failing finding cited, ≤ threshold
3184
+ // lines) re-grades only the still-pending dimensions; a NON-surgical
3185
+ // amend (broad / out-of-scope / over-threshold / unreadable / unparseable)
3186
+ // re-grades the FULL roster — a broad amend may have regressed a passing
3187
+ // dimension the carry-forward would otherwise trust. With NO prior
3188
+ // (round 1 / first re-grade) the carry-forward applies unchanged. See
3189
+ // `isSurgicalFix` for the fail-closed contract.
3190
+ const surgical =
3191
+ !confirm && priorChannel !== undefined && isSurgicalFix(state, priorChannel, cwd, target, latest, pending);
3192
+ const priorPresent = priorChannel !== undefined && priorArtifact(state, priorChannel) !== undefined;
1469
3193
  const priorFlag = (d: string): string => {
1470
3194
  if (!confirm || !pending.includes(d)) return "";
1471
3195
  const handle = latest.get(d)?.artifacts.find((a) => a.handle.kind === "fs")?.handle;
1472
3196
  return handle ? ` --prior ${handleToString(handle)}` : "";
1473
3197
  };
1474
- // Never emit zero units (empty ⇒ single dimensionless grade fall-through).
1475
- const toGrade = pending.length > 0 ? pending : roster;
3198
+ const carryForward = pending.length > 0 ? pending : roster;
3199
+ // A non-surgical result WITH a prior present re-grades the FULL roster;
3200
+ // with NO prior the carry-forward applies (never an empty unit set —
3201
+ // empty ⇒ single dimensionless grade fall-through).
3202
+ const toGrade = surgical ? carryForward : priorPresent ? roster : carryForward;
1476
3203
  return toGrade.map((d) => ({
1477
3204
  prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}${priorFlag(d)}`,
1478
3205
  label: d,
@@ -1482,11 +3209,15 @@ const gradePanelFanout = (
1482
3209
  });
1483
3210
 
1484
3211
  const SLICE_DIMENSION_FANOUT = gradePanelFanout("slices", SLICE_DIMENSIONS, "slice-verdicts");
1485
- const PLAN_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts");
3212
+ const PLAN_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts", {
3213
+ priorChannel: "plan-snapshot",
3214
+ });
1486
3215
  // The post-splice code gate re-grades the SAME `plans` artifact on its own
1487
3216
  // `code-verdicts` channel, so its carry-forward reads the code gate's verdicts,
1488
3217
  // never the pre-elaborate plan gate's.
1489
- const CODE_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts");
3218
+ const CODE_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts", {
3219
+ priorChannel: "code-snapshot",
3220
+ });
1490
3221
  // The confirm stages re-run the SAME panel machinery on the SAME verdict
1491
3222
  // channel: with the failing dimensions the only ones pending, the panel emits
1492
3223
  // exactly the blocking dimensions — one second judgment each, in confirm mode:
@@ -1539,6 +3270,26 @@ const allDimensionsPass = (entries: readonly Output[] = [], roster?: readonly st
1539
3270
  interface RiskRuling {
1540
3271
  id: string;
1541
3272
  pass: boolean;
3273
+ /**
3274
+ * `mechanics` marks a risk whose `pass` asserts a verified mechanism (a
3275
+ * behavior that holds because code was checked), so a passing ruling MUST
3276
+ * cite the checked `file:line` in `evidence` — an un-evidenced mechanics
3277
+ * pass demotes. Absent on
3278
+ * an ordinary risk ⇒ no evidence duty.
3279
+ */
3280
+ claim_type?: string;
3281
+ /** The `file:line`-shaped citation a mechanics pass must ground itself on. */
3282
+ evidence?: string;
3283
+ /**
3284
+ * `verify-at-implement` marks a risk the panel defers: ruled `pass` ONLY when
3285
+ * a concrete `procedure` + `owner` phase will re-check it at implement/validate
3286
+ * time. Absent ⇒ the risk is judged in this panel, not deferred.
3287
+ */
3288
+ disposition?: string;
3289
+ /** Named command/test the owner phase runs to discharge a deferred risk. */
3290
+ procedure?: string;
3291
+ /** The phase (`n`) that owns the deferred verify step. */
3292
+ owner?: number;
1542
3293
  }
1543
3294
 
1544
3295
  /** The `risk_rulings` a grade verdict emitted (empty when it ruled on none). */
@@ -1547,22 +3298,144 @@ const verdictRiskRulings = (o: Output): RiskRuling[] => {
1547
3298
  if (!Array.isArray(raw)) return [];
1548
3299
  return raw.flatMap((e) => {
1549
3300
  const r = (e ?? {}) as Record<string, unknown>;
1550
- return typeof r.id === "string" ? [{ id: r.id, pass: r.pass === true }] : [];
3301
+ if (typeof r.id !== "string") return [];
3302
+ // Read the duty fields defensively (same typeof-guard idiom as id/pass):
3303
+ // absent on an older/ordinary verdict ⇒ undefined ⇒ the duty helpers no-op.
3304
+ const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
3305
+ const evidence = typeof r.evidence === "string" ? r.evidence : undefined;
3306
+ const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
3307
+ const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
3308
+ const owner = typeof r.owner === "number" ? r.owner : undefined;
3309
+ return [
3310
+ {
3311
+ id: r.id,
3312
+ pass: r.pass === true,
3313
+ ...(claim_type !== undefined ? { claim_type } : {}),
3314
+ ...(evidence !== undefined ? { evidence } : {}),
3315
+ ...(disposition !== undefined ? { disposition } : {}),
3316
+ ...(procedure !== undefined ? { procedure } : {}),
3317
+ ...(owner !== undefined ? { owner } : {}),
3318
+ },
3319
+ ];
1551
3320
  });
1552
3321
  };
1553
3322
 
3323
+ /**
3324
+ * A plan-authored risk flag — the duty shape `synthesize` declares in the plan
3325
+ * frontmatter `risks:` array (`synthesize/SKILL.md:136`: `{ id, claim,
3326
+ * claim_type?, disposition?, procedure?, owner? }`). The prose `claim` is grading
3327
+ * copy, not a duty signal, so it is not carried here. `claim_type: "mechanics"`
3328
+ * and `disposition: "verify-at-implement"` are the two duty TRIGGERS — sourced
3329
+ * from the PLAN (not the ruling) so a panel cannot drop its discharge obligation
3330
+ * by simply omitting the field from its ruling (the dropped-duty bypass).
3331
+ */
3332
+ interface RiskRecord {
3333
+ id: string;
3334
+ claim_type?: string;
3335
+ disposition?: string;
3336
+ procedure?: string;
3337
+ owner?: number;
3338
+ }
3339
+
3340
+ /**
3341
+ * Read the plan-authored risk flags off the latest record on `channel`, keyed
3342
+ * by `id`. The duty triggers live HERE (the plan's `risks:` frontmatter), not on
3343
+ * the grade panel's ruling, so a ruling that drops its discharge field cannot
3344
+ * escape the duty the plan declared (a bare `{ id, pass }` ruling against a
3345
+ * plan-authored `claim_type: "mechanics"` risk still demotes). Reads only
3346
+ * `state.named[channel]` via `latestChannelData` — no `readFileSync`, no
3347
+ * `cwd`, no throw — so the route's `readsData: false` / determinism /
3348
+ * resume-safety contract holds and a resumed run re-evaluates identically.
3349
+ * Degrades to an empty map (fail-open ⇒ no duty ⇒ plain ruling ⇒
3350
+ * `rulingEffectivePass(r) === r.pass`) when `risks:` is absent/non-array/
3351
+ * malformed, mirroring `latestChannelData`'s degrade-to-undefined contract.
3352
+ */
3353
+ const planAuthoredRisks = (state: RunView, channel: string): Map<string, RiskRecord> => {
3354
+ const risks = latestChannelData(state, channel)?.risks;
3355
+ const out = new Map<string, RiskRecord>();
3356
+ if (!Array.isArray(risks)) return out;
3357
+ for (const e of risks) {
3358
+ const r = (e ?? {}) as Record<string, unknown>;
3359
+ if (typeof r.id !== "string") continue;
3360
+ const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
3361
+ const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
3362
+ const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
3363
+ const owner = typeof r.owner === "number" ? r.owner : undefined;
3364
+ const rec: RiskRecord = { id: r.id };
3365
+ if (claim_type !== undefined) rec.claim_type = claim_type;
3366
+ if (disposition !== undefined) rec.disposition = disposition;
3367
+ if (procedure !== undefined) rec.procedure = procedure;
3368
+ if (owner !== undefined) rec.owner = owner;
3369
+ out.set(r.id, rec);
3370
+ }
3371
+ return out;
3372
+ };
3373
+
3374
+ /**
3375
+ * A mechanics-pass ruling's evidence duty: when the plan AUTHORED a
3376
+ * `claim_type: "mechanics"` risk for the ruling's id, a `pass` ruling MUST
3377
+ * cite the checked `file:line` in `evidence` (forces engagement — a pass with
3378
+ * no evidence is an unverified mechanism). The trigger is sourced from the
3379
+ * plan-authored `RiskRecord`, NOT the ruling — so a panel cannot drop the
3380
+ * evidence duty by omitting `claim_type` from its ruling (the dropped-duty
3381
+ * bypass). Reuses `FILE_LINE_CITATION_RE` via `.match()` — NOT `.test()`: the
3382
+ * regex carries the `/g` flag, so `.test()` is stateful across calls
3383
+ * (`lastIndex` advances) and would
3384
+ * intermittently miss a present citation. An id with no authored mechanics
3385
+ * risk carries no evidence duty ⇒ returns `true`.
3386
+ */
3387
+ const evidenceCitesFileLine = (r: RiskRuling, authored?: RiskRecord): boolean => {
3388
+ if (authored?.claim_type !== "mechanics") return true;
3389
+ return typeof r.evidence === "string" && r.evidence.match(FILE_LINE_CITATION_RE) !== null;
3390
+ };
3391
+
3392
+ /**
3393
+ * A deferred-risk's verify-at-implement duty: when the plan AUTHORED a
3394
+ * `disposition: "verify-at-implement"` risk for the ruling's id, a `pass`
3395
+ * ruling MUST carry a concrete `procedure` (the named command/test the owner
3396
+ * phase runs) AND a numeric `owner` phase — a bare "verify later" with no
3397
+ * procedure demotes. The trigger is sourced from the plan-authored
3398
+ * `RiskRecord`, NOT the ruling (the dropped-duty bypass). An id with no
3399
+ * authored verify-at-implement risk is judged in THIS panel, not deferred ⇒
3400
+ * returns `true`.
3401
+ */
3402
+ const procedureSatisfiesDuty = (r: RiskRuling, authored?: RiskRecord): boolean => {
3403
+ if (authored?.disposition !== "verify-at-implement") return true;
3404
+ return typeof r.procedure === "string" && r.procedure.length > 0 && typeof r.owner === "number";
3405
+ };
3406
+
3407
+ /**
3408
+ * The single gate-fold authority: a ruling is effective-pass iff it is a bare
3409
+ * `pass` AND (when the plan authored a mechanics risk for its id) its evidence
3410
+ * cites a `file:line` AND (when the plan authored a verify-at-implement risk
3411
+ * for its id) its procedure+owner discharge the verify duty. `allRiskFlagsPass`,
3412
+ * `dimensionsToRegrade` clause 3, and `confirmDue`'s `riskFail` ALL consult this
3413
+ * — so the three risk folds agree on what "passing" means and a demoted
3414
+ * mechanics/deferred pass blocks the gate AND re-opens its owning dimension
3415
+ * AND counts as blocking for confirm (no incoherent re-grading). For a ruling
3416
+ * whose id the plan authored no duty for (no mechanics/verify-at-implement
3417
+ * risk, no `risks:` at all, or no matching id) every duty no-ops, so
3418
+ * `rulingEffectivePass(r, authored) === r.pass` — prior behavior is preserved.
3419
+ */
3420
+ const rulingEffectivePass = (r: RiskRuling, authored?: RiskRecord): boolean =>
3421
+ r.pass === true && evidenceCitesFileLine(r, authored) && procedureSatisfiesDuty(r, authored);
3422
+
1554
3423
  /**
1555
3424
  * Fold the grade panel's per-flag risk rulings into a gate decision: every
1556
3425
  * plan-authored risk flag the panel ruled on must be ruled PASS (latest ruling
1557
3426
  * per flag wins, mirroring `allDimensionsPass`). A flag ruled `fail` — the
1558
3427
  * 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
3428
+ * self-flagged risk (e.g. an override-vs-env validation mismatch) can no longer
1560
3429
  * ride a green conformance pass into commit. An empty panel (no flag engaged)
1561
3430
  * imposes no constraint; the plan simply declared no risks.
1562
3431
  */
1563
- const allRiskFlagsPass = (entries: readonly Output[] = []): boolean => {
3432
+ const allRiskFlagsPass = (
3433
+ entries: readonly Output[] = [],
3434
+ risks: ReadonlyMap<string, RiskRecord> = new Map(),
3435
+ ): boolean => {
1564
3436
  const latest = new Map<string, boolean>();
1565
- for (const o of entries) for (const r of verdictRiskRulings(o)) latest.set(r.id, r.pass);
3437
+ for (const o of entries)
3438
+ for (const r of verdictRiskRulings(o)) latest.set(r.id, rulingEffectivePass(r, risks.get(r.id)));
1566
3439
  return [...latest.values()].every(Boolean);
1567
3440
  };
1568
3441
 
@@ -1593,18 +3466,28 @@ const sliceGatePasses = (state: RunView): boolean => {
1593
3466
  const roster = gateRoster(gateTier(state, "slice-verdicts"), SLICE_DIMENSIONS);
1594
3467
  return allDimensionsPass(state.named["slice-check"]) && allDimensionsPass(fresh, roster);
1595
3468
  };
3469
+ // The single authority the new `subplan-check` edge consults — the twin of
3470
+ // `sliceGatePasses`, but carrying no LLM-verdict roster or risk flags: the
3471
+ // `subplan-check` floor is the sole (deterministic) dimension on its channel.
3472
+ const subplanGatePasses = (state: RunView): boolean => allDimensionsPass(state.named["subplan-check"]);
1596
3473
  const planGatePasses = (state: RunView): boolean => {
1597
3474
  const fresh = freshVerdicts(state.named["plan-verdicts"], latestArtifactPath(state, "plans"));
1598
3475
  const roster = gateRoster(gateTier(state, "plan-verdicts"), PLAN_DIMENSIONS);
3476
+ const risks = planAuthoredRisks(state, "plans");
1599
3477
  return (
1600
- allDimensionsPass(state.named["plan-cite-check"]) && allDimensionsPass(fresh, roster) && allRiskFlagsPass(fresh)
3478
+ allDimensionsPass(state.named["plan-cite-check"]) &&
3479
+ allDimensionsPass(fresh, roster) &&
3480
+ allRiskFlagsPass(fresh, risks)
1601
3481
  );
1602
3482
  };
1603
3483
  const codeGatePasses = (state: RunView): boolean => {
1604
3484
  const fresh = freshVerdicts(state.named["code-verdicts"], latestArtifactPath(state, "plans"));
1605
3485
  const roster = gateRoster(gateTier(state, "code-verdicts"), PLAN_DIMENSIONS);
3486
+ const risks = planAuthoredRisks(state, "plans");
1606
3487
  return (
1607
- allDimensionsPass(state.named["code-cite-check"]) && allDimensionsPass(fresh, roster) && allRiskFlagsPass(fresh)
3488
+ allDimensionsPass(state.named["code-cite-check"]) &&
3489
+ allDimensionsPass(fresh, roster) &&
3490
+ allRiskFlagsPass(fresh, risks)
1608
3491
  );
1609
3492
  };
1610
3493
 
@@ -1632,12 +3515,13 @@ const confirmDue = (
1632
3515
  ): boolean => {
1633
3516
  const roster = new Set(gateRoster(gateTier(state, verdictChannel), dimensions));
1634
3517
  const fresh = freshVerdicts(state.named[verdictChannel], latestArtifactPath(state, channel));
3518
+ const risks = planAuthoredRisks(state, channel);
1635
3519
  const byDim = new Map<string, { blocking: boolean; count: number }>();
1636
3520
  for (const o of fresh) {
1637
3521
  const v = o.data as { dimension?: string; pass?: boolean; severity?: string } | undefined;
1638
3522
  if (typeof v?.dimension !== "string" || !roster.has(v.dimension)) continue;
1639
3523
  const floored = v.pass === true || v.severity === "low" || v.severity === "none";
1640
- const riskFail = verdictRiskRulings(o).some((r) => !r.pass);
3524
+ const riskFail = verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
1641
3525
  byDim.set(v.dimension, {
1642
3526
  blocking: !floored || riskFail,
1643
3527
  count: (byDim.get(v.dimension)?.count ?? 0) + 1,
@@ -1723,6 +3607,95 @@ const COMMIT_BASELINE_PROMPT: PromptFn = ({ state }) => {
1723
3607
  return baseline ? `/skill:commit --baseline ${baseline}` : "/skill:commit";
1724
3608
  };
1725
3609
 
3610
+ // ===========================================================================
3611
+ // vet — goal → code-review → (blueprint → implement → implement-scope-check
3612
+ // → validate → loop) | commit. Examine existing changes; capture the
3613
+ // brief as a goal artifact, review, and if not approved blueprint a fix
3614
+ // plan, implement it, scope-check it, validate, and re-review. Loops
3615
+ // until approved. NOTE: defined here (after captureGoal /
3616
+ // implementScopeCheckVet) rather than beside ship/arch because its graph
3617
+ // references those later-declared `const`s — the same precedent
3618
+ // buildWorkflow follows (defined after its deps).
3619
+ // ===========================================================================
3620
+
3621
+ const vetWorkflow = defineWorkflow({
3622
+ name: "vet",
3623
+ description:
3624
+ "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 → validate → loop) → commit.",
3625
+ start: "goal",
3626
+ stages: {
3627
+ // Capture the user's brief verbatim on its own `goal` channel, and snapshot
3628
+ // the run-start pre-existing-dirty paths (role "baseline"). Reuses build's
3629
+ // `captureGoal` verbatim — no new function — so the scope-check's
3630
+ // `reads: ["plans", "goal"]` resolves a baseline to subtract and the goal md
3631
+ // rides the channel face. `goal` as start publishes the goal-md as
3632
+ // `artifacts[0]`; `code-review` is a plain `produces()` SKILL stage (skill
3633
+ // defaults to its stage key "code-review"), so it inherits that goal-md PATH
3634
+ // as its rolling primary — the same pattern arch/polish's code-review uses,
3635
+ // and the fallback Risk r1's note conceded "likely tolerates a goal-md-path
3636
+ // arg." The goal-md's CONTENT is the brief (`captureGoal` writes
3637
+ // `state.originalInput` into it), so the skill still reaches it.
3638
+ //
3639
+ // NOTE: the plan's r1 resolution made code-review PROMPT-dispatched to
3640
+ // preserve `state.originalInput` byte-for-byte, but that is REVERSED here: a
3641
+ // prompt stage carries NO skill, so the `code-review` contract no longer
3642
+ // attaches its `outputSchema` and the `blockers_count` gate would read
3643
+ // UNVALIDATED data (NaN-route risk, not just a warning). Keeping it a skill
3644
+ // stage keeps `skill="code-review"` → contract schema attaches → validated.
3645
+ goal: produces.script({ run: captureGoal }),
3646
+ "code-review": produces(),
3647
+ blueprint: produces(),
3648
+ // Dep-gated DAG variant: implement phases now
3649
+ // carry `id: phase-<n>` + `deps` derived from each phase's `files:` overlap /
3650
+ // authored `depends_on`, so the host cap may fan them out in parallel.
3651
+ implement: acts({ loop: IMPLEMENT_DAG_FANOUT, reads: ["plans"] }),
3652
+ // Deterministic scope floor (no LLM): the lane may write ONLY the union of
3653
+ // every plan iteration's declared `files:` (vet's loop pushes DISTINCT
3654
+ // non-superseding fix plans, so the declared set is the UNION over the full
3655
+ // `plans` history — `implementScopeCheckVet`). The `from` form suppresses
3656
+ // the READS_DATA outputSchema lint, so no schema is declared, matching
3657
+ // `slice-check`/`plan-cite-check`. Pass → validate; fail/missing → STOP
3658
+ // (no fallback), mirroring build's `validate → commit` route.
3659
+ "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheckVet }),
3660
+ // Deterministic post-implement reconciliation (no LLM) — the SAME `reconcile`
3661
+ // run-function as build (no vet twin): applies every `#### Reconciliation`
3662
+ // directive (write-restricted to test files) + re-runs every per-phase
3663
+ // `#### Automated Verification:` command, fail-soft. Pass ⇒ validate; fail/
3664
+ // missing ⇒ STOP (no fallback). `reads: ["plans"]` only — no run-start goal
3665
+ // baseline. The `from` form suppresses the READS_DATA outputSchema lint.
3666
+ reconcile: produces.script({ reads: ["plans"], run: reconcile }),
3667
+ validate: produces(),
3668
+ commit: acts({ outcome: gitCommitOutcome }),
3669
+ },
3670
+ edges: {
3671
+ goal: "code-review",
3672
+ // Same numeric gate as build/arch/polish: zero remaining blockers → commit;
3673
+ // any blockers → loop a fix pass through blueprint. The `blockers_count`
3674
+ // field is sourced + validated from the code-review contract.
3675
+ "code-review": gate("blockers_count", { blueprint: gt(0), commit: eq(0) }, "commit"),
3676
+ blueprint: "implement",
3677
+ // Scope-check inserts BEFORE validate, INSIDE the review-fix loop. Pass →
3678
+ // validate; fail/missing terminates (STOP, no fallback). Byte-for-byte
3679
+ // build's route.
3680
+ implement: "implement-scope-check",
3681
+ // Scope-check still gates onward, but now into `reconcile` (not validate):
3682
+ // the coherence backstop runs after the write-set is proven. Pass ⇒
3683
+ // reconcile; fail/missing ⇒ STOP (no fallback).
3684
+ "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
3685
+ // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target /
3686
+ // absent find / failed AV command) or a missing verdict ⇒ STOP (no fix arm —
3687
+ // a reconciliation failure is plan-vs-tree drift the agent reconciles manually).
3688
+ reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
3689
+ // Backward edge: validate → code-review creates the review-fix loop —
3690
+ // UNCHANGED. The scope-check inserts before validate, so a failing scope
3691
+ // verdict halts before re-review, and a passing one flows into validate and
3692
+ // back to code-review exactly as today. Bounded by the runner's default
3693
+ // maxBackwardJumps (2 → at most 3 review iterations).
3694
+ validate: "code-review",
3695
+ commit: "stop",
3696
+ },
3697
+ });
3698
+
1726
3699
  const buildWorkflow = defineWorkflow({
1727
3700
  name: "build",
1728
3701
  description:
@@ -1781,6 +3754,13 @@ const buildWorkflow = defineWorkflow({
1781
3754
  loop: SYNTH_CLUSTER_FANOUT,
1782
3755
  outcome: rpivBucketOutcome("subplans"),
1783
3756
  }),
3757
+ // Deterministic cluster-coverage floor between the cluster fanout and the
3758
+ // root merge — the subplan twin of `slice-check`. Reconciles dispatched
3759
+ // `_cluster-<k>` sub-plans against the slice map's promised cluster count +
3760
+ // `sources:` design coverage BEFORE the root merge fans them in, so a lost
3761
+ // or clobbered cluster fails structurally and routes back to `subplan`
3762
+ // rather than silently dropping slices from the merged plan.
3763
+ "subplan-check": produces.script({ reads: [fanin("subplans"), "slices"], run: subplanCoverageCheck }),
1784
3764
  // The root merge reads `research` (threaded as `--research` so cross-slice
1785
3765
  // constraints reach the merge directly, not only via each subplan's
1786
3766
  // refraction) alongside the cluster sub-plans it fans in.
@@ -1797,6 +3777,15 @@ const buildWorkflow = defineWorkflow({
1797
3777
  // --context; `goal` so completeness/correctness anchor on the brief.
1798
3778
  reads: ["plans", "research", "goal"],
1799
3779
  }),
3780
+ // Stamp the duty demotion onto the graded verdicts as legible on-disk data
3781
+ // (a `risk_duty_demotions` array written in place onto each demoted
3782
+ // verdict JSON) one hop BEFORE the gate routes — the gate's route lives on
3783
+ // `plan-demote` so this write-back lands before confirm/`--prior`/amend
3784
+ // read the verdict. Reads `plans` (the plan-authored risk flags) and fans
3785
+ // in the verdicts it just graded. Gate outcomes are unchanged: every fold
3786
+ // consults in-memory `state.named` via `rulingEffectivePass`, never the
3787
+ // rewritten file (the write-back is an additive, read-only signal).
3788
+ "plan-demote": produces.script({ reads: ["plans", fanin("plan-verdicts")], run: planDemote }),
1800
3789
  // One independent second judgment on the blocking dimensions before they
1801
3790
  // buy a fix round (see `confirmDue`). Same panel machinery, same verdict
1802
3791
  // channel — its OWN stage name so a stronger judge model can be pinned to
@@ -1810,8 +3799,23 @@ const buildWorkflow = defineWorkflow({
1810
3799
  "plan-fix": produces({
1811
3800
  skill: "amend",
1812
3801
  outcome: rpivBucketOutcome("plans"),
1813
- reads: ["plans", fanin("plan-verdicts"), fanin("plan-cite-check")],
3802
+ // Lineage threads for completeness-class repairs: `goal` (verbatim brief),
3803
+ // `research` (architecture/precedent findings), `subplans` (per-cluster
3804
+ // sub-plans). `goal`/`research` mirror `plan-confirm`'s reads; `subplans`
3805
+ // mirrors `plan`'s own `reads: ["research", fanin("subplans")]`. `subplans`
3806
+ // is plan-fix-ONLY — by the code gate the plan's completeness is settled, so
3807
+ // code-fix repairs code-shape defects and threads no subplans.
3808
+ reads: ["plans", fanin("plan-verdicts"), fanin("plan-cite-check"), "goal", "research", fanin("subplans")],
1814
3809
  }),
3810
+ // Snapshot the graded plan BEFORE plan-fix amends it — one deterministic
3811
+ // hop inside the existing fix loop (plan-grade/plan-confirm → plan-snapshot
3812
+ // → plan-fix). The re-grade reads the prior off the snapshot's OWN channel
3813
+ // (`plan-snapshot`) to decide whether the amend was surgical (re-grade only
3814
+ // the failing dims) or broad (re-grade the full roster). `produces.script`
3815
+ // rides its stage-name channel, so this publishes to `plan-snapshot`, NOT
3816
+ // `plans` — `latestFsArtifact(state, "plans")` still resolves to the real
3817
+ // (amended) plan.
3818
+ "plan-snapshot": produces.script({ reads: ["plans"], run: planSnapshot }),
1815
3819
  // Elaborate implement-ready code into each phase in parallel (fanout),
1816
3820
  // deterministically splice it back into the plan (code-splice), then
1817
3821
  // re-grade the now code-bearing plan — guarding the blind-splice risk.
@@ -1842,6 +3846,10 @@ const buildWorkflow = defineWorkflow({
1842
3846
  // --context; `goal` so completeness/correctness anchor on the brief.
1843
3847
  reads: ["plans", "research", "goal"],
1844
3848
  }),
3849
+ // The code-gate twin of `plan-demote`: stamp the duty demotion onto the
3850
+ // code-graded verdicts (re-grading `plans` on `code-verdicts`) one hop
3851
+ // before the code gate routes (`code-demote` owns the route body).
3852
+ "code-demote": produces.script({ reads: ["plans", fanin("code-verdicts")], run: codeDemote }),
1845
3853
  // Repair arm for the code gate. Surgical `amend` over the SAME code-bearing
1846
3854
  // plan from the code verdicts — NOT a blind re-elaborate: `elaborate` never
1847
3855
  // sees the findings and can only rewrite a phase's code body, so it cannot fix
@@ -1862,9 +3870,37 @@ const buildWorkflow = defineWorkflow({
1862
3870
  "code-fix": produces({
1863
3871
  skill: "amend",
1864
3872
  outcome: rpivBucketOutcome("plans"),
1865
- reads: ["plans", fanin("code-verdicts"), fanin("code-cite-check")],
3873
+ // Lineage threads for code-shape repairs: `goal`/`research` give amend the
3874
+ // brief + architecture context (mirroring `code-confirm`'s reads). NO
3875
+ // `subplans` — the plan's completeness was settled at the plan gate, so the
3876
+ // code arm only repairs code-shape defects (fabricated edit anchors, drifted
3877
+ // `file:line` citations, cross-phase naming collisions).
3878
+ reads: ["plans", fanin("code-verdicts"), fanin("code-cite-check"), "goal", "research"],
1866
3879
  }),
1867
- implement: acts({ loop: IMPLEMENT_PHASE_FANOUT, reads: ["plans"] }),
3880
+ // Snapshot the graded plan BEFORE code-fix amends it — the code-gate twin
3881
+ // of `plan-snapshot` (code-grade/code-confirm → code-snapshot → code-fix),
3882
+ // publishing the prior on the `code-snapshot` channel.
3883
+ "code-snapshot": produces.script({ reads: ["plans"], run: codeSnapshot }),
3884
+ implement: acts({ loop: IMPLEMENT_DAG_FANOUT, reads: ["plans"] }),
3885
+ // Lane-level scope floor — the structural backstop beneath the quality
3886
+ // gates. After the (now concurrent) implement lane lands, judge the working
3887
+ // tree's dirty set against the plan's declared write-set: any undeclared
3888
+ // write is a phase that escaped the upstream write-scope discipline and
3889
+ // raced on a sibling's in-flight edit. Fail ⇒ STOP (no fix arm). The `from`
3890
+ // form suppresses the READS_DATA outputSchema lint, so no schema is declared
3891
+ // (matching slice-check/plan-cite-check). Reads `goal` for the run-start
3892
+ // baseline that subtracts pre-existing dirt.
3893
+ "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheck }),
3894
+ // Deterministic post-implement reconciliation (no LLM): applies every
3895
+ // `#### Reconciliation` directive (find→replace, write-restricted to test
3896
+ // files) and re-runs every per-phase `#### Automated Verification:`
3897
+ // command, fail-soft — a coherence backstop the parallel implement lane
3898
+ // needs (a phase's correct change can invalidate a sibling's test, and the
3899
+ // combined tree can break in ways no single phase's checks surface). Pass ⇒
3900
+ // validate; fail/missing ⇒ STOP (no fallback). `reads: ["plans"]` only — no
3901
+ // run-start goal baseline (the scope floor already proved the write-set). The
3902
+ // `from` form suppresses the READS_DATA outputSchema lint.
3903
+ reconcile: produces.script({ reads: ["plans"], run: reconcile }),
1868
3904
  validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
1869
3905
  commit: acts({ prompt: COMMIT_BASELINE_PROMPT, outcome: gitCommitOutcome }),
1870
3906
  },
@@ -1895,7 +3931,22 @@ const buildWorkflow = defineWorkflow({
1895
3931
  // Design fanout → consolidated human checkpoint → hierarchical synthesis.
1896
3932
  "slice-design": "design-review",
1897
3933
  "design-review": "subplan",
1898
- subplan: "plan",
3934
+ // Route the cluster fanout through the deterministic coverage floor before
3935
+ // the root merge — the twin of `slice → slice-check`. A pass folds straight
3936
+ // to `plan`; a lost/clobbered cluster routes the backward edge to `subplan`,
3937
+ // bounded by the runner's maxBackwardJumps.
3938
+ subplan: "subplan-check",
3939
+ // Subplan coverage gate. Pass ⇒ root merge. A fail (lost cluster, clobbered
3940
+ // ordinal, tokenless basename, or a slice design absent from every sources:)
3941
+ // routes the backward edge to `subplan` — re-dispatch the cluster fanout,
3942
+ // which re-supplies each cluster's '--cluster <k>'. Bounded by the runner's
3943
+ // maxBackwardJumps. `readsData: false` — the route consults only the
3944
+ // deterministic verdict channel (mirrors the slice-check/plan-cite-check routes).
3945
+ "subplan-check": defineRoute(
3946
+ ["plan", "subplan"],
3947
+ ({ state }) => (subplanGatePasses(state) ? "plan" : "subplan"),
3948
+ { readsData: false },
3949
+ ),
1899
3950
  plan: "plan-cite-check",
1900
3951
  // Skip the quality re-grade straight to `code` when the gate is already
1901
3952
  // satisfied — a `plan-fix` that only cleared the citation floor leaves every
@@ -1908,28 +3959,39 @@ const buildWorkflow = defineWorkflow({
1908
3959
  ({ state }) => (planGatePasses(state) ? "code" : "plan-grade"),
1909
3960
  { readsData: false },
1910
3961
  ),
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"],
3962
+ // Quality gate BEFORE any code. The grade runs at `plan-grade`; the route
3963
+ // lives one hop later on `plan-demote` so the duty-demotion write-back
3964
+ // lands on the verdict JSON BEFORE this fold consults the downstream
3965
+ // readers. `plan-grade` is now a simple always-hop edge to `plan-demote`;
3966
+ // the route body below is the verbatim logic that used to live here.
3967
+ "plan-grade": "plan-demote",
3968
+ // Pass ⇒ code. A dimension's FIRST blocking verdict ⇒ plan-confirm (one
3969
+ // independent second judgment — see `confirmDue`); a confirmed blocker, or
3970
+ // a failure with no dimension blocking (the citation floor alone is red) ⇒
3971
+ // plan-fix, looping back THROUGH the citation floor so the amended plan
3972
+ // re-verifies. Route logic unchanged — merely shifted one hop later so the
3973
+ // demote write-back precedes it.
3974
+ "plan-demote": defineRoute(
3975
+ ["code", "plan-confirm", "plan-snapshot"],
1919
3976
  ({ state }) =>
1920
3977
  planGatePasses(state)
1921
3978
  ? "code"
1922
3979
  : confirmDue(state, "plans", "plan-verdicts", PLAN_DIMENSIONS)
1923
3980
  ? "plan-confirm"
1924
- : "plan-fix",
3981
+ : "plan-snapshot",
1925
3982
  { readsData: false },
1926
3983
  ),
1927
3984
  // After the second judgment the gate re-folds on the latest verdicts: a
1928
3985
  // confirming pass overwrote the flap and clears the gate; a confirming
1929
3986
  // 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
- }),
3987
+ "plan-confirm": defineRoute(
3988
+ ["code", "plan-snapshot"],
3989
+ ({ state }) => (planGatePasses(state) ? "code" : "plan-snapshot"),
3990
+ { readsData: false },
3991
+ ),
3992
+ // The snapshot is one deterministic hop between the grade/confirm route and
3993
+ // the fix — no new backward edge, inside the existing fix loop.
3994
+ "plan-snapshot": "plan-fix",
1933
3995
  "plan-fix": "plan-cite-check",
1934
3996
  code: "code-splice",
1935
3997
  "code-splice": "code-cite-check",
@@ -1941,30 +4003,53 @@ const buildWorkflow = defineWorkflow({
1941
4003
  ({ state }) => (codeGatePasses(state) ? "implement" : "code-grade"),
1942
4004
  { readsData: false },
1943
4005
  ),
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"],
4006
+ // Re-grade the code-bearing plan at `code-grade`; the route lives one hop
4007
+ // later on `code-demote` (the twin of the plan gate's split) so the
4008
+ // duty-demotion write-back lands before this fold. `code-grade` is now a
4009
+ // simple always-hop edge to `code-demote`; the route body below is verbatim.
4010
+ "code-grade": "code-demote",
4011
+ // Pass ⇒ implement. A first blocking verdict ⇒ code-confirm (the plan
4012
+ // gate's confirm contract, on the code-verdicts channel); a confirmed
4013
+ // blocker or cite-floor-only failure ⇒ code-fix. Routes to `code-fix`, NOT
4014
+ // back to `code`: the gate fails on plan-text defects (edit anchors, line
4015
+ // citations, naming) that a per-phase code rewrite cannot reach, so the
4016
+ // surgical arm is the one with authority over them. Route logic unchanged —
4017
+ // merely shifted one hop later. Bounded by the runner's maxBackwardJumps.
4018
+ "code-demote": defineRoute(
4019
+ ["implement", "code-confirm", "code-snapshot"],
1953
4020
  ({ state }) =>
1954
4021
  codeGatePasses(state)
1955
4022
  ? "implement"
1956
4023
  : confirmDue(state, "plans", "code-verdicts", PLAN_DIMENSIONS)
1957
4024
  ? "code-confirm"
1958
- : "code-fix",
4025
+ : "code-snapshot",
1959
4026
  { readsData: false },
1960
4027
  ),
1961
4028
  "code-confirm": defineRoute(
1962
- ["implement", "code-fix"],
1963
- ({ state }) => (codeGatePasses(state) ? "implement" : "code-fix"),
4029
+ ["implement", "code-snapshot"],
4030
+ ({ state }) => (codeGatePasses(state) ? "implement" : "code-snapshot"),
1964
4031
  { readsData: false },
1965
4032
  ),
4033
+ // The code-gate twin of `plan-snapshot → plan-fix`.
4034
+ "code-snapshot": "code-fix",
1966
4035
  "code-fix": "code-cite-check",
1967
- implement: "validate",
4036
+ implement: "implement-scope-check",
4037
+ // Lane-level scope floor gate. Pass ⇒ reconcile (the coherence backstop
4038
+ // runs after the write-set is proven). A `fail` (undeclared write) or a
4039
+ // missing verdict routes to STOP — no fix arm, because a scope violation is
4040
+ // plan-vs-tree drift the agent must reconcile manually (a phase wrote
4041
+ // outside its declared set), not a defect an auto-fix loop can repair. Safe
4042
+ // by construction: the sole path onward is an explicit `verdict: "pass"`.
4043
+ // Sourced from the scope-check's published verdict channel via the `from`
4044
+ // form (the stage key for an outcome-less `produces.script`, per
4045
+ // `resolvePublishName`), which suppresses the READS_DATA outputSchema lint.
4046
+ "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
4047
+ // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target
4048
+ // / absent find / failed AV command) or a missing verdict ⇒ STOP (no fix
4049
+ // arm — a reconciliation failure is plan-vs-tree drift the agent reconciles
4050
+ // manually). Safe by construction: the sole path onward is an explicit
4051
+ // `verdict: "pass"`. Sourced from the reconcile channel via the `from` form.
4052
+ reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
1968
4053
  // Gate commit on validate's own verdict — an unconditional `validate → commit`
1969
4054
  // let a `verdict: fail` (incomplete goal coverage) commit anyway. `match` with
1970
4055
  // no fallback commits ONLY on an explicit `verdict: "pass"`; every other value