@juicesharp/rpiv-pi 2.6.4 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/docs/skills.md +1 -1
  2. package/extensions/rpiv-core/agents.ts +10 -13
  3. package/extensions/rpiv-core/artifact-collector.ts +111 -6
  4. package/extensions/rpiv-core/bash-timeout.ts +12 -2
  5. package/extensions/rpiv-core/built-in-workflows.ts +329 -3528
  6. package/extensions/rpiv-core/built-ins/citations.ts +357 -0
  7. package/extensions/rpiv-core/built-ins/gates.ts +613 -0
  8. package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
  9. package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
  10. package/extensions/rpiv-core/built-ins/index.ts +47 -0
  11. package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
  12. package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
  13. package/extensions/rpiv-core/built-ins/priors.ts +352 -0
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
  15. package/extensions/rpiv-core/built-ins/remediation.ts +96 -0
  16. package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
  17. package/extensions/rpiv-core/built-ins/shared.ts +17 -1
  18. package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
  19. package/extensions/rpiv-core/built-ins/slices.ts +288 -0
  20. package/extensions/rpiv-core/constants.ts +5 -1
  21. package/extensions/rpiv-core/lane-console.ts +9 -2
  22. package/extensions/rpiv-core/lane-list.ts +10 -1
  23. package/extensions/rpiv-core/question-lifecycle.ts +2 -2
  24. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  25. package/extensions/rpiv-core/run-lane-registry.ts +83 -83
  26. package/package.json +2 -2
  27. package/skills/elaborate/SKILL.md +1 -1
  28. package/skills/implement/SKILL.md +1 -0
  29. package/skills/plan/SKILL.md +3 -1
  30. package/skills/remediate/SKILL.md +18 -15
  31. package/skills/synthesize/SKILL.md +1 -0
  32. package/skills/validate/SKILL.md +26 -19
  33. package/skills/validate/templates/validation.md +1 -1
@@ -14,55 +14,77 @@
14
14
  */
15
15
 
16
16
  import { execFileSync } from "node:child_process";
17
- import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
18
- import { basename, dirname, isAbsolute, join, sep } from "node:path";
17
+ import { dirname, isAbsolute, join } from "node:path";
19
18
  import { fileURLToPath } from "node:url";
20
- import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
21
19
  import {
22
- type Artifact,
23
20
  acts,
24
21
  defineRoute,
25
22
  defineWorkflow,
26
23
  directoryPathCollector,
27
24
  type EdgeFn,
28
25
  eq,
29
- type FanoutContext,
30
26
  fanin,
31
- fanout,
32
27
  gate,
33
28
  gitCommitOutcome,
34
29
  gt,
35
30
  handleToString,
36
- iterate,
37
31
  jsonBodyParser,
38
32
  match,
39
- type Output,
40
33
  type PromptFn,
41
34
  produces,
42
35
  type RunView,
43
- type ScriptContext,
44
36
  setRouteNote,
45
- type Unit,
46
37
  type Workflow,
47
38
  } from "@juicesharp/rpiv-workflow/registration";
48
39
  import { rpivBucketOutcome } from "./artifact-collector.js";
49
40
  import {
50
- countHeadingsOutsideFences,
51
- FILE_LINE_CITATION_RE,
52
- type FsArtifact,
53
- fencedSpans,
54
- forEachLineOutsideFences,
41
+ allDimensionsPass,
42
+ anchorNitsOnly,
43
+ CODE_CONFIRM_FANOUT,
44
+ CODE_DIMENSION_FANOUT,
45
+ COMMIT_BASELINE_PROMPT,
46
+ captureGoal,
47
+ codeDemote,
48
+ codeGatePasses,
49
+ codeSnapshot,
50
+ confirmDue,
51
+ FRONTMATTER_PHASE_FANOUT,
52
+ freshVerdicts,
55
53
  haltPreflight,
54
+ IMPLEMENT_DAG_FANOUT,
55
+ IMPLEMENT_PLANS_FANOUT,
56
+ implementScopeCheck,
57
+ implementScopeCheckVet,
58
+ latestArtifactPath,
56
59
  latestFsArtifact,
57
- MAX_PHASES,
58
- type PhaseRecord,
59
- readArtifactFile,
60
- type StructureFinding,
61
- TEST_PATH_RE,
62
- VERDICT_DIR,
63
- VERDICT_FAIL_SCORE,
64
- VERDICT_PASS_SCORE,
65
- writeStructureVerdict,
60
+ latestPlans,
61
+ latestVerdictPerDimension,
62
+ PLAN_CONFIRM_FANOUT,
63
+ PLAN_DIMENSION_FANOUT,
64
+ PLAN_DIMENSIONS,
65
+ planAuthoredRisks,
66
+ planCitationCheck,
67
+ planDemote,
68
+ planGatePasses,
69
+ planSnapshot,
70
+ REVIEW_PHASE_ITERATE,
71
+ reconcile,
72
+ remediationOutcome,
73
+ rulingEffectivePass,
74
+ SHIP_DIMENSION_FANOUT,
75
+ SHIP_DIMENSIONS,
76
+ SLICE_DESIGN_FANOUT,
77
+ SLICE_DIMENSION_FANOUT,
78
+ SYNTH_CLUSTER_FANOUT,
79
+ scopeQuarantine,
80
+ shipGatePasses,
81
+ shipVerdictOutcome,
82
+ sliceGatePasses,
83
+ sliceStructureCheck,
84
+ subplanCoverageCheck,
85
+ subplanGatePasses,
86
+ VALIDATE_GOAL_PROMPT,
87
+ verdictRiskRulings,
66
88
  } from "./built-ins/index.js";
67
89
 
68
90
  // The code-review stage's output schema is no longer declared here — every
@@ -72,3420 +94,116 @@ import {
72
94
  // per workflow. Every workflow with a `code-review` stage — polish AND vet —
73
95
  // routes on the same numeric gate: `gate("blockers_count", { <fix>: gt(0), commit: eq(0) }, "commit")`.
74
96
 
75
- /**
76
- * `## Phase N:` headings — the source of truth a plan's `phases:` frontmatter
77
- * array is derived from. Used to verify that derived array, not to enumerate
78
- * (enumeration reads the typed `phases:` array).
79
- */
80
- const PLAN_PHASE_RE = /^## Phase (\d+):/gm;
81
-
82
- /**
83
- * Parse a plan's `phases:` frontmatter into records, derive-checked against the
84
- * body's `## Phase N:` headings — the source of truth both the single-plan
85
- * (`FRONTMATTER_PHASE_FANOUT`) and multi-plan (`PLANS_PHASE_FANOUT`) fanouts
86
- * share. A length mismatch means the producer's rebuild step was skipped or the
87
- * array went stale; throw rather than dispatch a wrong unit list. `who`/`path`
88
- * shape the diagnostic.
89
- */
90
- const planPhaseRecords = (content: string, who: string, path: string): readonly PhaseRecord[] => {
91
- const { frontmatter } = parseFrontmatter(content);
92
- const fm = frontmatter as Record<string, unknown>;
93
- const raw = fm.phases;
94
- const phases = Array.isArray(raw) ? raw : [];
95
- const headingCount = countHeadingsOutsideFences(content, PLAN_PHASE_RE);
96
- if (phases.length !== headingCount) {
97
- throw haltPreflight(
98
- who,
99
- `${who}: plan ${path} has mismatched phases`,
100
- `${who}: plan ${path} frontmatter phases (${phases.length}) ≠ '## Phase N:' headings (${headingCount}) — the derived array is stale against the body`,
101
- );
102
- }
103
- // The REQUIRED scalar `phase_count` must equal the derived phase count — it
104
- // drives the fanout unit count. Fire only when the file declares
105
- // plan-ness (has phases OR a phase_count) so a genuinely empty / non-plan file
106
- // still degrades to [] (the existing "neither phases nor headings" path); a plan
107
- // that declares phases but omits phase_count THROWS (the field is contract-required).
108
- if ((phases.length > 0 || fm.phase_count !== undefined) && fm.phase_count !== phases.length) {
109
- throw haltPreflight(
110
- who,
111
- `${who}: plan ${path} has invalid phase_count`,
112
- `${who}: plan ${path} frontmatter phase_count (${String(fm.phase_count)}) ≠ phases length (${phases.length}) — rebuild phase_count from the '## Phase N:' headings`,
113
- );
114
- }
115
- return phases.map((entry, index) => {
116
- const e = (entry ?? {}) as Record<string, unknown>;
117
- return {
118
- entry: e,
119
- n: typeof e.n === "number" ? e.n : index + 1,
120
- title: typeof e.title === "string" ? e.title : "",
121
- index,
122
- total: phases.length,
123
- };
124
- });
125
- };
126
-
127
- /**
128
- * Read the latest plan published to the named `"plans"` channel and parse its
129
- * `phases:` frontmatter into records — the shared read/halt body both
130
- * `FRONTMATTER_PHASE_FANOUT` and `IMPLEMENT_DAG_FANOUT` source from. Returns
131
- * `null` when no fs plan is published (each caller degrades to `[]`); throws
132
- * the two `haltPreflight` diagnostics (plan-not-found, exceeds `MAX_PHASES`)
133
- * attributed to `who`. `promptPath` is the plan handle's string form, so each
134
- * fanout emits the same `${promptPath} Phase N:` prompt arg.
135
- */
136
- const readPlanPhaseRecords = (
137
- state: RunView,
138
- cwd: string,
139
- who: string,
140
- ): { records: readonly PhaseRecord[]; promptPath: string } | null => {
141
- const plan = latestFsArtifact(state, "plans");
142
- if (plan?.handle.kind !== "fs") return null;
143
- const path = plan.handle.path;
144
- let content: string;
145
- try {
146
- content = readArtifactFile(path, cwd);
147
- } catch (err) {
148
- throw haltPreflight(
149
- who,
150
- `${who}: plan file not found`,
151
- `${who}: could not read ${path} — ${err instanceof Error ? err.message : String(err)}`,
152
- );
153
- }
154
- const records = planPhaseRecords(content, who, path);
155
- if (records.length > MAX_PHASES) {
156
- throw haltPreflight(
157
- who,
158
- `${who}: plan ${path} exceeds phase limit`,
159
- `${who}: plan ${path} declares ${records.length} phases — exceeds MAX_PHASES (${MAX_PHASES}); split into smaller plans`,
160
- );
161
- }
162
- const promptPath = handleToString(plan.handle);
163
- return { records, promptPath };
164
- };
165
-
166
- /**
167
- * Union the per-phase `files:` write-set declared across the FULL `plans`
168
- * channel history. vet's review-fix loop appends a DISTINCT non-superseding fix
169
- * plan per iteration (a `produces` stage APPENDS to its named slot, and backward
170
- * jumps don't reset channels), so a path a prior plan legitimately wrote is not
171
- * excess against the latest plan — hence the union, not latest-only.
172
- *
173
- * Reads every fs artifact in every plan via `planPhaseRecords` + `phaseFiles`,
174
- * skipping unreadable/unparseable plans (the union stays the sum of the
175
- * parseable ones; a plan too malformed to parse is a `plan-cite-check`/
176
- * `plan-fix` concern, not scope). `latest` is the FIRST fs artifact of the LAST
177
- * plan carrying one (mirrors `latestFsArtifact`'s last-channel-entry / first-fs-
178
- * artifact resolution) — it keys the basename-keyed verdict path + `artifact`
179
- * field.
180
- */
181
- const unionDeclaredWriteSet = (
182
- plans: readonly Output[],
183
- cwd: string,
184
- ): { declared: Set<string>; latest: FsArtifact | undefined } => {
185
- const declared = new Set<string>();
186
- let latest: FsArtifact | undefined;
187
- for (const out of plans) {
188
- // Per plan, capture its FIRST fs artifact as the `latest` candidate so the
189
- // LAST plan with an fs artifact wins (mirrors `latestFsArtifact`'s
190
- // `.at(-1)?.artifacts.find(kind==="fs")` — last channel entry, first fs
191
- // artifact in it — which keys the verdict path + `artifact` field).
192
- let firstFsInPlan: FsArtifact | undefined;
193
- for (const a of out.artifacts) {
194
- if (a.handle.kind !== "fs") continue; // fs-artifact filter
195
- if (!firstFsInPlan) firstFsInPlan = a as FsArtifact;
196
- const path = a.handle.path;
197
- try {
198
- const content = readArtifactFile(path, cwd);
199
- for (const r of planPhaseRecords(content, "implement-scope-check", path)) {
200
- for (const f of phaseFiles(r.entry)) declared.add(f);
201
- }
202
- } catch {
203
- // Unreadable/unparseable plan: don't widen the declared set on error —
204
- // the union stays the sum of the parseable plans. (A plan so malformed
205
- // it can't be parsed is a `plan-cite-check`/`plan-fix` concern, not scope.)
206
- }
207
- }
208
- if (firstFsInPlan) latest = firstFsInPlan;
209
- }
210
- return { declared, latest };
211
- };
212
-
213
- /**
214
- * Fan `implement` out over the structured `phases:` frontmatter array of the
215
- * latest plan published to the named `"plans"` channel. Sourcing from the named
216
- * channel (not the rolling primary) makes the stage's `reads: ["plans"]`
217
- * declaration semantically honest. Used by every workflow whose `implement`
218
- * inherits one plan (build/vet); polish's accumulating multi-plan
219
- * variant is `PLANS_PHASE_FANOUT`.
220
- */
221
- const FRONTMATTER_PHASE_FANOUT = fanout({
222
- source: "plans",
223
- unit: { by: "frontmatter-array", pattern: "phases" },
224
- max: MAX_PHASES,
225
- units: ({ state, cwd }) => {
226
- const read = readPlanPhaseRecords(state, cwd, "FRONTMATTER_PHASE_FANOUT");
227
- if (!read) return [];
228
- const { records, promptPath } = read;
229
- return records.map((r) => ({
230
- prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
231
- label: `phase ${r.index + 1}/${r.total}`,
232
- }));
233
- },
234
- });
235
-
236
- /**
237
- * Derive the directed `deps` edges for ONE implement phase under the dep-gated
238
- * DAG fanout (`IMPLEMENT_DAG_FANOUT`). Edges point strictly downward (toward
239
- * LOWER phase numbers), so the graph is acyclic by construction. Two clauses:
240
- *
241
- * - clause A (self declares a `files:` write-set): `self` depends on every
242
- * LOWER phase whose declared `files:` shares ≥1 entry, UNIONED with `self`'s
243
- * explicit `depends_on` (semantic ordering not visible in `files:`).
244
- * - clause B (self declares NO `files:`): `self` conflicts with EVERY lower
245
- * phase → full chain (a write-set-less phase's writes are unknown, so it
246
- * cannot be proven independent of anything below it). This is the
247
- * empty-set degradation that keeps a legacy / `files:`-less plan serial at
248
- * any cap (one phase per Kahn wave).
249
- *
250
- * Returns `phase-<n>` unit ids, sorted ascending. Reads `phaseFiles`
251
- * and `phaseDeps` — both defined later textually, but only inside this
252
- * runtime closure, so no TDZ (same pattern as `sliceDeps`).
253
- */
254
- const implementPhaseDeps = (records: readonly PhaseRecord[], self: PhaseRecord): string[] => {
255
- // Twin-expanded (`withTestTwins`) so a phase declaring `x.ts` conflicts with
256
- // one declaring `x.test.ts` — the production phase's implicit twin write would
257
- // otherwise race a concurrent sibling that owns the test explicitly.
258
- const selfFiles = withTestTwins(phaseFiles(self.entry));
259
- const explicit = phaseDeps(self.entry);
260
- const ns = new Set<number>();
261
- for (const e of explicit) if (e < self.n) ns.add(e);
262
- if (selfFiles.length === 0) {
263
- // clause B — unknown write-set ⇒ conflict with every lower phase.
264
- for (const r of records) if (r.n < self.n) ns.add(r.n);
265
- } else {
266
- // clause A — overlap on ≥1 declared write path.
267
- for (const r of records) {
268
- if (r.n >= self.n) continue;
269
- const rFiles = withTestTwins(phaseFiles(r.entry));
270
- if (rFiles.some((f) => selfFiles.includes(f))) ns.add(r.n);
271
- }
272
- }
273
- return [...ns].sort((a, b) => a - b).map((n) => `phase-${n}`);
274
- };
275
-
276
- /**
277
- * Dep-gated DAG variant of `FRONTMATTER_PHASE_FANOUT` — `implement`'s twin that
278
- * emits per-phase `id`/`deps` edges so the wave scheduler orders phases by their
279
- * declared write-set overlap + explicit `depends_on`. The spread idiom inherits
280
- * `source`/`unit`/`max`/`onCap`/`result`/`kind` verbatim from the base; the new
281
- * `units` closure emits the SAME `prompt`/`label` strings AND adds
282
- * `id: \`phase-${r.n}\`` + `deps: implementPhaseDeps(records, r)`. NO
283
- * `depArtifactFlag` — implement phases feed each other through the working tree
284
- * (not published artifacts), so `deps` drive ONLY wave ordering. NO
285
- * `concurrency` property is set (the spread overrides only `units`), so the loop
286
- * inherits the host cap and phases fan out concurrently, bounded by `deps`.
287
- */
288
- const IMPLEMENT_DAG_FANOUT = {
289
- ...FRONTMATTER_PHASE_FANOUT,
290
- units: ({ state, cwd }: FanoutContext) => {
291
- const read = readPlanPhaseRecords(state, cwd, "IMPLEMENT_DAG_FANOUT");
292
- if (!read) return [];
293
- const { records, promptPath } = read;
294
- return records.map((r) => ({
295
- prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
296
- label: `phase ${r.index + 1}/${r.total}`,
297
- id: `phase-${r.n}`,
298
- deps: implementPhaseDeps(records, r),
299
- }));
300
- },
301
- };
302
-
303
- // ===========================================================================
304
- // polish — architecture-review → blueprint (iterate, per review phase) →
305
- // implement → validate → code-review → (blueprint loop) | commit
306
- // For a large architecture review that can't be planned in one pass:
307
- // plan each review phase sequentially, each plan building on the
308
- // ones before it, then implement/validate/review the lot.
309
- // ===========================================================================
310
-
311
- /**
312
- * `### Phase N — name` headings — the source of truth the review's `phases:`
313
- * frontmatter array is derived from. Used to verify that derived array, not to
314
- * enumerate (enumeration reads the typed `phases:` array).
315
- */
316
- const REVIEW_PHASE_RE = /^### Phase (\d+) — (.+)$/gm;
317
-
318
- /** Number of structured `phases` in the latest architecture review's frontmatter (0 if none). */
319
- const reviewPhaseCount = (state: RunView, cwd: string): number => {
320
- const review = latestFsArtifact(state, "architecture-reviews");
321
- if (review?.handle.kind !== "fs") return 0;
322
- const { frontmatter } = parseFrontmatter(readArtifactFile(review.handle.path, cwd));
323
- const raw = (frontmatter as Record<string, unknown>).phases;
324
- return Array.isArray(raw) ? raw.length : 0;
325
- };
326
-
327
- /**
328
- * The plans from the most recent blueprint pass. blueprint's iterate stage
329
- * pushes one `Output` per review phase into `state.named["plans"]`; on a
330
- * corrective loop it re-plans every phase, so keep only the last `phaseCount`
331
- * (the review's phase count) and drop the stale generation. Shared by the
332
- * implement fanout and the validate prompt so both see the same plan set.
333
- */
334
- const latestPlans = (state: RunView, cwd: string): readonly Output[] => {
335
- const plans = state.named.plans ?? [];
336
- const phaseCount = reviewPhaseCount(state, cwd);
337
- return phaseCount > 0 && plans.length > phaseCount ? plans.slice(-phaseCount) : plans;
338
- };
339
-
340
- /** Phase number for a `phases:` entry, falling back to its 1-based position. */
341
- const phaseNum = (entry: unknown, index: number): number => {
342
- const n = (entry as { n?: unknown } | undefined)?.n;
343
- return typeof n === "number" ? n : index + 1;
344
- };
345
-
346
- /** `depends_on` phase numbers an entry declares (empty when absent). */
347
- const phaseDeps = (entry: unknown): number[] => {
348
- const raw = (entry as { depends_on?: unknown } | undefined)?.depends_on;
349
- return Array.isArray(raw) ? raw.filter((d): d is number => typeof d === "number") : [];
350
- };
351
-
352
- /** The repo-root-relative paths a phase entry declares it creates/edits (its
353
- * `files:` array — `[]` when absent). The open-schema twin of `phaseDeps`,
354
- * read straight off `PhaseRecord.entry` so `planPhaseRecords` preserves the new
355
- * key unchanged. Consumed by the plan-time coverage floor
356
- * (`verifyPhaseFilesCoverage`) and, in a later phase, the dep-gated implement
357
- * fanout (`implementPhaseDeps`). */
358
- const phaseFiles = (entry: unknown): string[] => {
359
- const raw = (entry as { files?: unknown } | undefined)?.files;
360
- return Array.isArray(raw) ? raw.filter((f): f is string => typeof f === "string") : [];
361
- };
362
-
363
- /**
364
- * Expand a declared write-set with each production file's co-located test twin
365
- * (`x.ts → x.test.ts`, likewise tsx/js/jsx). This monorepo's tests are
366
- * compile-coupled siblings — widening a declared file's signature forces the
367
- * mechanical follow-up edit in its twin — so requiring every plan author,
368
- * elaborator, and grader to re-declare the twin is paperwork the convention
369
- * already guarantees (a live run STOPPED at the scope floor over exactly this:
370
- * a declared `lane-switcher.ts` signature change whose five-assertion twin fix
371
- * was undeclared prose). Applied at BOTH consumers of the declared set — the
372
- * DAG conflict fold (`implementPhaseDeps`) and the scope floors — so the
373
- * planner and the floor can never disagree; on the DAG side it also closes the
374
- * latent race where phases declaring `x.ts` and `x.test.ts` counted as
375
- * disjoint yet predictably collide. Asymmetric by design: declaring a TEST
376
- * file licenses nothing extra — production writes remain the act that must be
377
- * declared, and a write to a non-twin test still fails the floor. A file
378
- * already matching `TEST_PATH_RE` maps to itself (no `x.test.test.ts`).
379
- */
380
- const withTestTwins = (files: readonly string[]): string[] => {
381
- const out = new Set(files);
382
- for (const f of files) {
383
- if (TEST_PATH_RE.test(f)) continue;
384
- const twin = f.replace(/\.([tj]sx?)$/, ".test.$1");
385
- if (twin !== f) out.add(twin);
386
- }
387
- return [...out];
388
- };
389
-
390
- /**
391
- * Per-review-phase blueprint generator (the `iterate` dual of
392
- * FRONTMATTER_PHASE_FANOUT). One blueprint pass per review phase, enumerating the
393
- * review's structured `phases:` array (derived by architecture-review from its
394
- * `### Phase N — name` headings). blueprint writes its own natural plan file; the
395
- * `plans` collector captures whatever path it announces.
396
- *
397
- * Each phase reads only the plans of the phases it `depends_on` (vs. every prior
398
- * plan) — accurate context, and the seam a future scheduler could parallelize on.
399
- * `blast_radius`/`effort` tag the label. Absent `depends_on` falls back to all
400
- * prior plans.
401
- *
402
- * Guards (first call): the array's length must equal the `### Phase N — name`
403
- * heading count (stale derive), and every `depends_on` must reference an earlier
404
- * phase (exists, no self/forward/cyclic edge against body order).
405
- */
406
- const REVIEW_PHASE_ITERATE = iterate({
407
- source: "architecture-reviews",
408
- unit: { by: "frontmatter-array", pattern: "phases" },
409
- max: MAX_PHASES,
410
- next: ({ artifact, state, accumulated, cwd }) => {
411
- // Source the review from the named registry — robust to corrective re-entry,
412
- // where the rolling primary is the latest code-review doc, not the review.
413
- const review = latestFsArtifact(state, "architecture-reviews") ?? artifact;
414
- if (review?.handle.kind !== "fs") return null;
415
- const reviewPath = review.handle.path; // captured: narrowing is lost inside nested closures below
416
- const content = readArtifactFile(reviewPath, cwd);
417
- const { frontmatter } = parseFrontmatter(content);
418
- const raw = (frontmatter as Record<string, unknown>).phases;
419
- const phases = Array.isArray(raw) ? raw : [];
420
- const i = accumulated.length;
421
- if (i === 0) {
422
- const headingCount = countHeadingsOutsideFences(content, REVIEW_PHASE_RE);
423
- if (phases.length !== headingCount) {
424
- throw haltPreflight(
425
- "REVIEW_PHASE_ITERATE",
426
- `REVIEW_PHASE_ITERATE: review ${reviewPath} has mismatched phases`,
427
- `REVIEW_PHASE_ITERATE: review ${reviewPath} frontmatter phases (${phases.length}) ≠ '### Phase N —' headings (${headingCount}) — the derived array is stale against the body`,
428
- );
429
- }
430
- const indexByN = new Map(phases.map((e, idx) => [phaseNum(e, idx), idx]));
431
- phases.forEach((e, idx) => {
432
- for (const d of phaseDeps(e)) {
433
- const di = indexByN.get(d);
434
- if (di === undefined)
435
- throw haltPreflight(
436
- "REVIEW_PHASE_ITERATE",
437
- `REVIEW_PHASE_ITERATE: review ${reviewPath} has invalid depends_on`,
438
- `REVIEW_PHASE_ITERATE: review ${reviewPath} phase ${phaseNum(e, idx)} depends_on ${d}, which is not a declared phase`,
439
- );
440
- if (di >= idx)
441
- throw haltPreflight(
442
- "REVIEW_PHASE_ITERATE",
443
- `REVIEW_PHASE_ITERATE: review ${reviewPath} has cyclic dependency`,
444
- `REVIEW_PHASE_ITERATE: review ${reviewPath} phase ${phaseNum(e, idx)} depends_on ${d}, which is not an earlier phase (self/forward/cyclic dependency)`,
445
- );
446
- }
447
- });
448
- }
449
- if (i >= phases.length) return null; // every phase planned → terminate
450
- const entry = (phases[i] ?? {}) as { title?: unknown; blast_radius?: unknown; effort?: unknown };
451
- const n = phaseNum(entry, i);
452
- const title = typeof entry.title === "string" ? entry.title : "";
453
-
454
- // accumulated[j] is phase j's output — map each prior phase number to its plans.
455
- const priorByN = new Map<number, string[]>();
456
- accumulated.forEach((o, j) => {
457
- const paths = o.artifacts.filter((a) => a.handle.kind === "fs").map((a) => handleToString(a.handle));
458
- if (paths.length) priorByN.set(phaseNum(phases[j], j), paths);
459
- });
460
- const deps = phaseDeps(phases[i]);
461
- const prior = deps.length ? deps.flatMap((d) => priorByN.get(d) ?? []) : [...priorByN.values()].flat();
462
- // On a corrective pass the latest code-review is in `reviews`; fold its blockers in.
463
- const feedback = latestFsArtifact(state, "reviews");
464
-
465
- let prompt = `${handleToString(review.handle)} Implement Phase ${n}: ${title}`;
466
- if (prior.length)
467
- prompt += `\nPrior phase plans (read first; build on them, don't duplicate): ${prior.join(", ")}`;
468
- if (feedback?.handle.kind === "fs")
469
- prompt += `\nAddress the blockers in the latest code review: ${handleToString(feedback.handle)}`;
470
- const tags = [entry.effort, entry.blast_radius].filter((t): t is string => typeof t === "string");
471
- let label = `phase ${i + 1}/${phases.length} — ${title}`;
472
- if (tags.length) label += ` [${tags.join(", ")}]`;
473
- return { prompt, label, id: `phase-${n}` };
474
- },
475
- });
476
-
477
- /**
478
- * Fan implement out over the `phases:` array of EVERY plan in the latest
479
- * blueprint pass (see `latestPlans` for the corrective-loop dedup), so blueprint
480
- * keeps its natural timestamped filenames. The single-plan
481
- * `FRONTMATTER_PHASE_FANOUT` is the same over one inherited plan; both share
482
- * `planPhaseRecords`. MAX_PHASES is enforced on the aggregate unit count, since
483
- * polish fans one implement pass over the whole plan set.
484
- */
485
- const PLANS_PHASE_FANOUT = fanout({
486
- source: "plans",
487
- unit: { by: "frontmatter-array", pattern: "phases" },
488
- max: MAX_PHASES,
489
- units: ({ state, cwd }) => {
490
- const units: Unit[] = [];
491
- for (const out of latestPlans(state, cwd)) {
492
- for (const a of out.artifacts) {
493
- if (a.handle.kind !== "fs") continue;
494
- const path = a.handle.path;
495
- const content = readArtifactFile(path, cwd);
496
- const promptPath = handleToString(a.handle);
497
- for (const r of planPhaseRecords(content, "PLANS_PHASE_FANOUT", path)) {
498
- units.push({
499
- prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
500
- label: `${basename(path)} P${r.n}`,
501
- });
502
- }
503
- }
504
- }
505
- if (units.length > MAX_PHASES) {
506
- throw haltPreflight(
507
- "PLANS_PHASE_FANOUT",
508
- `PLANS_PHASE_FANOUT: phase limit exceeded`,
509
- `PLANS_PHASE_FANOUT: ${units.length} phases exceeds MAX_PHASES (${MAX_PHASES})`,
510
- );
511
- }
512
- return units;
513
- },
514
- });
515
-
516
- /** `implement`'s serial twin of `PLANS_PHASE_FANOUT` (polish's multi-plan variant) — serialized (`concurrency: 1`) because the fanout's units share a working tree and their write-sets are unknown, so the scheduler cannot derive dep edges (no scope floor guards it). */
517
- const IMPLEMENT_PLANS_FANOUT = { ...PLANS_PHASE_FANOUT, concurrency: 1 };
518
-
519
- /**
520
- * Hand the single validate session EVERY plan from the latest blueprint pass
521
- * (`latestPlans`). The runner's default rolling-primary — and a plain
522
- * `reads: ["plans"]`, which only reads `.at(-1)` — would point validate at the
523
- * LAST plan alone, leaving earlier phases unvalidated. A `prompt` stage owns
524
- * its whole message, so the `/skill:validate` prefix is explicit.
525
- */
526
- const VALIDATE_PLANS_PROMPT: PromptFn = ({ state, cwd }) => {
527
- const paths = latestPlans(state, cwd)
528
- .flatMap((o) => o.artifacts)
529
- .filter((a) => a.handle.kind === "fs")
530
- .map((a) => handleToString(a.handle));
531
- return `/skill:validate ${paths.join(" ")}`;
532
- };
533
-
534
- const polishWorkflow = defineWorkflow({
535
- name: "polish",
536
- description:
537
- "Architecture-review-driven polish: review → per-phase blueprint (sequential, accumulating) → implement → validate → code-review → commit. Best when a large architecture review can't be planned in one pass and each phase's plan must build on the ones before it.",
538
- start: "architecture-review",
539
- stages: {
540
- "architecture-review": produces(),
541
- blueprint: produces({ loop: REVIEW_PHASE_ITERATE }),
542
- implement: acts({ loop: IMPLEMENT_PLANS_FANOUT, reads: ["plans"] }),
543
- validate: produces({ prompt: VALIDATE_PLANS_PROMPT }),
544
- "code-review": produces(),
545
- commit: acts({ outcome: gitCommitOutcome }),
546
- },
547
- edges: {
548
- "architecture-review": "blueprint",
549
- blueprint: "implement",
550
- implement: "validate",
551
- validate: "code-review",
552
- // Backward edge: code-review → blueprint re-plans (implement needs a plan).
553
- // The iterate stage re-runs over every review phase; bounded by the
554
- // runner's default maxBackwardJumps (3 → up to 4 review iterations).
555
- "code-review": gate("blockers_count", { blueprint: gt(0), commit: eq(0) }, "commit"),
556
- commit: "stop",
557
- },
558
- });
559
-
560
- // ===========================================================================
561
- // build — goal (verbatim-brief capture) → research → slice → slice-check
562
- // (deterministic floor) → slice-grade (design-readiness, slice-fix loop)
563
- // → slice-design (fanout) → design-review (one human checkpoint) →
564
- // subplan (cluster fanout) → plan → plan-grade (plan-fix loop) →
565
- // code (fanout) → code-splice → code-grade (code-fix loop) →
566
- // implement → implement-scope-check → reconcile → validate → commit
567
- // The sliced, panel-gated heavy path: capture the user's brief verbatim as the
568
- // `goal` channel (the north star the judgment seams — the two grade panels'
569
- // completeness/correctness dimensions and validate — anchor against), research
570
- // the brief (so every slice
571
- // rests on a real, cited footing and the plan gate can grade architecture-fit),
572
- // decompose it into independent
573
- // vertical slices, gate that breakdown BEFORE any design so each slice is
574
- // chewable by one design-slice pass. The gate is two-phase: a DETERMINISTIC
575
- // floor (`slice-check`) enforces dependency-cycle freedom and brief-coverage
576
- // conservation (a slice-fix may redistribute the brief, never drop scope to pass),
577
- // then ONE LLM `design-readiness` judgment reconciles the formerly-opposing
578
- // split/merge forces. Then design every slice in parallel and pause at ONE
579
- // consolidated human checkpoint (`design-review`) — the single fan-in seam where
580
- // every design exists and nothing parallel runs — to accept or adjust the
581
- // proposed interfaces/data types before synthesis. Then merge hierarchically
582
- // (per-cluster sub-plans → one plan) so no pass holds every design, gate the
583
- // plan on quality dimensions BEFORE any code, elaborate code per phase and
584
- // splice it in, re-grade the code-bearing plan, then implement/validate/commit.
585
- // ===========================================================================
586
-
587
- /**
588
- * The single LLM dimension the EARLY gate grades the slice map against — before
589
- * any design. `design-readiness` asks the one question the whole gate exists to
590
- * answer: is each slice chewable by ONE `design-slice` pass? It subsumes the old
591
- * four-way panel (right-sizing + vertical-shape + design-readiness + the
592
- * contract-ownership half of independence) into one holistic judgment — taking
593
- * its own name from that design-readiness member, the dominant sub-aspect — so
594
- * the formerly-opposing split-pressure (right-sizing) and merge-pressure
595
- * (vertical-shape) forces are reconciled by ONE grader instead of two blind
596
- * panelists that ping-pong the reslice loop. The structural floor that was the
597
- * other half of independence — dependency-cycle freedom — plus brief-coverage
598
- * conservation are enforced DETERMINISTICALLY by `slice-check`, not graded
599
- * here. Mirrors the `design-readiness` rubric row in the `grade` skill.
600
- */
601
- const SLICE_DIMENSIONS = ["design-readiness"] as const;
602
-
603
- /**
604
- * Quality dimensions the LATER gate grades the synthesized plan against.
605
- * Includes `architecture-fit`: build front-loads a `research` stage, so the
606
- * research artifact is always present to feed that dimension's `--context`
607
- * (threaded in by `gradePanelFanout` for this one dimension).
608
- */
609
- const PLAN_DIMENSIONS = [
610
- "completeness",
611
- "correctness",
612
- "actionability",
613
- "pattern-following",
614
- "architecture-fit",
615
- ] as const;
616
-
617
- /**
618
- * The FIXED three-dimension roster ship's grade panel grades — the bespoke,
619
- * tier-independent counterpart of `PLAN_DIMENSIONS`. Ship is a lightweight
620
- * preset: it front-loads `research` (so `architecture-fit` always has its
621
- * `--context`) and grades a trimmed, always-on set regardless of run shape.
622
- * `SHIP_DIMENSION_FANOUT` and `shipGatePasses` bind this roster DIRECTLY — no
623
- * `gateRoster(gateTier(...))` wrap — so a single-phase ship run still grades
624
- * `architecture-fit`, the dimension a tiered gate would drop in the light
625
- * roster. Order mirrors `PLAN_DIMENSIONS` (goal-anchored dimensions first,
626
- * fit last) so the emitted units stay stable.
627
- */
628
- export const SHIP_DIMENSIONS = ["completeness", "correctness", "architecture-fit"] as const;
629
-
630
- /** Bucket directory the goal capture writes into — build's verbatim-brief channel. */
631
- const GOAL_DIR = ".rpiv/artifacts/goal";
632
-
633
- /**
634
- * Capture the user's brief VERBATIM as build's `goal` channel — the north-star
635
- * artifact the judgment seams anchor against (the grade panels'
636
- * completeness/correctness dimensions and `validate`). A script stage (no LLM)
637
- * so nothing refracts the wording: `research` carries the goal's intent,
638
- * grounded and expanded, but explicit user constraints ("keep it minimal",
639
- * "don't touch auth") routinely don't survive that refraction — the raw file
640
- * is the only artifact that holds them. The body is the brief byte-for-byte;
641
- * added frontmatter or headers would pollute "the user's exact words".
642
- *
643
- * Publishes under its record key (`goal`): a script stage may not carry an
644
- * `outcome` (`script-with-outcome` is a load error) and needs none — the
645
- * returned envelope IS the output. Timestamped filename so concurrent/repeat
646
- * runs never collide; on resume the recorded path replays from the JSONL
647
- * trail, so the fanout `units()` closures reading the channel stay
648
- * deterministic.
649
- */
650
- const captureGoal = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
651
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
652
- const rel = join(GOAL_DIR, `goal-${stamp}.md`);
653
- mkdirSync(join(cwd, GOAL_DIR), { recursive: true });
654
- writeFileSync(join(cwd, rel), state.originalInput, "utf-8");
655
- // Snapshot the paths ALREADY dirty before the run touched anything — the
656
- // validate stage judges working-tree scope criteria against the run's own
657
- // delta, and the commit skill fences these paths off its commit. Timestamped
658
- // like the goal file itself (concurrent/repeat runs never read each other's
659
- // snapshot — there is NO fixed rendezvous path) and published on the goal
660
- // channel with role "baseline", so the JSONL trail carries the exact path to
661
- // every consumer and replays it deterministically on resume. Best-effort: a
662
- // non-repo / git-unavailable cwd writes an empty snapshot, so consumers
663
- // degrade to baseline-less behavior rather than failing the goal capture.
664
- const baselineRel = join(GOAL_DIR, `baseline-${stamp}.json`);
665
- writeCommitBaseline(cwd, baselineRel);
666
- return {
667
- kind: "md",
668
- // Order is load-bearing: `latestFsArtifact(state, "goal")` takes the FIRST
669
- // fs artifact — the goal md stays the channel's face (grade --goal flags,
670
- // rolling primary); the baseline rides behind it under its role.
671
- artifacts: [
672
- { handle: { kind: "fs", path: rel } },
673
- { handle: { kind: "fs", path: baselineRel }, role: "baseline" },
674
- ],
675
- data: {},
676
- };
677
- };
678
-
679
- /** Parse `git status --porcelain`/`--short` output into dirty paths. Strips the
680
- * 2-char `XY` status prefix and resolves rename targets (`XY old -> new` → `new`),
681
- * so the two output forms (`--porcelain`, `--short`) normalize identically. A
682
- * porcelain line is always `XY <path>` or `XY <old> -> <new>`; blank lines drop. */
683
- const parseGitStatusPaths = (out: string): string[] =>
684
- out
685
- .split("\n")
686
- .filter((l) => l.trim() !== "")
687
- .map((l) => {
688
- const rest = l.slice(3).trim();
689
- const arrow = rest.indexOf(" -> ");
690
- return arrow >= 0 ? rest.slice(arrow + 4).trim() : rest;
691
- });
692
-
693
- /** Record the paths dirty before the run to `rel` (best-effort; empty on any git failure). */
694
- const writeCommitBaseline = (cwd: string, rel: string): void => {
695
- let paths: string[] = [];
696
- try {
697
- // stdio: stderr ignored — without this, git's "fatal: not a git repository"
698
- // leaks to the parent's stderr even though the catch treats it as a
699
- // supported silent degrade (best-effort baseline, empty on failure).
700
- // -uall: git collapses an untracked directory to one `dir/` entry by
701
- // default, so a phase's brand-new files under a new directory would never
702
- // string-match their `files:` declarations at the scope floor. Enumerate
703
- // every file; the baseline and both scope checks MUST share this flag or
704
- // their path universes diverge.
705
- const out = execFileSync("git", ["status", "--short", "--untracked-files=all"], {
706
- cwd,
707
- encoding: "utf-8",
708
- stdio: ["ignore", "pipe", "ignore"],
709
- });
710
- paths = parseGitStatusPaths(out);
711
- } catch {
712
- paths = [];
713
- }
714
- mkdirSync(dirname(join(cwd, rel)), { recursive: true });
715
- writeFileSync(join(cwd, rel), JSON.stringify({ paths }, null, 2), "utf-8");
716
- };
717
-
718
- /** The run-start pre-existing-dirty snapshot riding the goal channel (role "baseline"). */
719
- const goalBaselinePath = (state: RunView): string | undefined => {
720
- const a = state.named.goal?.at(-1)?.artifacts.find((x) => x.role === "baseline" && x.handle.kind === "fs");
721
- return a ? handleToString(a.handle) : undefined;
722
- };
723
-
724
- /**
725
- * Read the run-start pre-existing-dirty baseline off the goal channel's
726
- * "baseline" artifact: the `{ paths }` JSON the baseline writer records. Best-
727
- * effort — `[]` on no path (no `goal` stage), an unreadable file, or a `paths`
728
- * value that isn't a string array, so the scope floor degrades to baseline-less
729
- * (nothing subtracted) rather than throwing.
730
- */
731
- const readGoalBaseline = (path: string | undefined, cwd: string): string[] => {
732
- if (!path) return [];
733
- try {
734
- const parsed = JSON.parse(readArtifactFile(path, cwd)) as { paths?: unknown };
735
- const p = parsed.paths;
736
- return Array.isArray(p) ? p.filter((x): x is string => typeof x === "string") : [];
737
- } catch {
738
- return [];
739
- }
740
- };
741
-
742
- /**
743
- * Current dirty-path set via `git status --porcelain` (rename targets resolved by
744
- * the shared parser). Best-effort — `[]` on a non-repo / git-missing tree (the
745
- * scope floor degrades to unguarded rather than failing a non-repo run; the
746
- * catch treats that as a supported silent degrade). stdio: stderr is ignored,
747
- * otherwise git's "fatal: not a git repository" leaks to the parent's stderr
748
- * despite the catch. `-uall` enumerates untracked files individually (a collapsed
749
- * `newdir/` entry can never string-match a declared `files:` path) — the
750
- * baseline writer and both scope checks MUST share this flag or their path
751
- * universes diverge.
752
- */
753
- const gitDirtyPaths = (cwd: string): string[] => {
754
- try {
755
- const out = execFileSync("git", ["status", "--porcelain", "--untracked-files=all"], {
756
- cwd,
757
- encoding: "utf-8",
758
- stdio: ["ignore", "pipe", "ignore"],
759
- });
760
- return parseGitStatusPaths(out);
761
- } catch {
762
- return [];
763
- }
764
- };
765
-
766
- /** Paths under these run-bookkeeping trees are NEVER a scope violation — the run
767
- * legitimately writes its artifacts/notes/trails here regardless of phase scope. */
768
- const SCOPE_BOOKKEEPING_DIRS: ReadonlySet<string> = new Set([".rpiv", "thoughts"]);
769
-
770
- /**
771
- * The lane-level scope floor's pure core. Returns the dirty paths that are NOT
772
- * explained by the run's declared write-set: a path is excess when it is outside
773
- * `declared`, was NOT dirty at the run-start `baseline`, and is NOT under a
774
- * bookkeeping tree (`.rpiv/`, `thoughts/`). The `implement` lane declared-set is
775
- * the union of its plan's per-phase `files:`; `validate`'s whole-repo
776
- * build/test writes are owned by a later stage, never by a phase.
777
- *
778
- * Empty `declared` ⇒ `[]` (degradation): a `files:`-less plan is serial-by-
779
- * construction under the DAG fanout's missing-`files:` clause (full dep chain ⇒
780
- * one phase per wave), so there is no concurrent sibling to corrupt and nothing
781
- * to guard — the floor returns no excess and never false-fails a legacy plan.
782
- * `validate`'s whole-repo writes are out of scope here regardless: they belong
783
- * to `validate`, which runs AFTER this gate, so the lane's dirty set never
784
- * carries them at the scope-check's read time.
785
- *
786
- * This is deliberately LANE-level, not per-phase: under concurrency, a dirty
787
- * path cannot be attributed to the specific phase that wrote it, so per-phase
788
- * enforcement would be unsound. The per-phase discipline is enforced upstream
789
- * by the plan-authoring write-scope rule + the plan-time coverage floor;
790
- * this lane floor is the structural backstop that catches a phase that escaped
791
- * upstream discipline. Returns one entry per excess path.
792
- */
793
- const scopeExcess = (dirty: readonly string[], baseline: readonly string[], declared: readonly string[]): string[] => {
794
- if (declared.length === 0) return [];
795
- const declaredSet = new Set(declared);
796
- const baselineSet = new Set(baseline);
797
- const excess: string[] = [];
798
- for (const path of dirty) {
799
- if (declaredSet.has(path) || baselineSet.has(path)) continue;
800
- const top = path.split("/")[0];
801
- if (SCOPE_BOOKKEEPING_DIRS.has(top)) continue;
802
- excess.push(path);
803
- }
804
- return excess;
805
- };
806
-
807
- /**
808
- * `goal` displaces `research` as build's start stage, and ONLY the start stage
809
- * receives `originalInput` as its skill arg (`stageEntryArgs` case 1) — a plain
810
- * `produces()` research would silently receive the rolling primary (the goal
811
- * FILE PATH) instead of the brief text. A prompt stage owns its whole message,
812
- * so this rebuilds research's pre-goal dispatch byte-for-byte; the outcome
813
- * deriver still wires the `research` bucket off the record key (the polish
814
- * `validate` prompt-stage precedent).
815
- */
816
- const RESEARCH_BRIEF_PROMPT: PromptFn = ({ state }) => `/skill:research ${state.originalInput}`;
817
-
818
- /**
819
- * ship's research front-load — a LEANER grounding than build's `/skill:research`
820
- * pass. Bypasses the research skill and bounds the agent to at most TWO targeted
821
- * `codebase-analyzer` dispatches (sequentially — never parallel, never
822
- * `run_in_background`) to map only what a lightweight single-phase plan needs to
823
- * be correct: entry points, the relevant module's shape, and the conventions the
824
- * implement lane must match. The agent then `Write`s a grounding doc under
825
- * `.rpiv/artifacts/research/`, where the research bucket collector harvests it —
826
- * the grade panel's architecture-fit dimension threads it as `--context` exactly
827
- * as build's research artifact does. A prompt stage (no skill), so the stage
828
- * name `research` drives outcome derivation (research contract → `research`
829
- * bucket), exactly as build's `RESEARCH_BRIEF_PROMPT` stage does — the prompt
830
- * text, not dispatch, is what differs.
831
- */
832
- const SHIP_RESEARCH_PROMPT: PromptFn = ({ state }) =>
833
- [
834
- "Ground this brief for a lightweight ship plan.",
835
- "Do NOT dispatch /skill:research. Instead dispatch at most TWO targeted codebase-analyzer subagents (sequentially — never parallel, never run_in_background) to map only what a single-phase plan needs to be correct: entry points, the relevant module's shape, and the conventions the implement lane must match.",
836
- "",
837
- `Brief: ${state.originalInput}`,
838
- "",
839
- "Then Write a grounding doc under .rpiv/artifacts/research/ (timestamped filename) carrying the findings, and stop.",
840
- ].join("\n");
841
-
842
- /** `## Slice N:` headings — the source of truth a slice map's `slices:` array is derived from. */
843
- const SLICE_HEADING_RE = /^## Slice (\d+):/gm;
844
-
845
- /**
846
- * Parse a slice map's `slices:` frontmatter into `{ n, title }` records,
847
- * derive-checked against the body's `## Slice N:` headings and the required
848
- * `slice_count` scalar — the slices twin of `planPhaseRecords`. A mismatch means
849
- * the producer's rebuild was skipped or the array went stale; throw rather than
850
- * dispatch a wrong unit list.
851
- */
852
- const sliceRecords = (content: string, who: string, path: string): readonly PhaseRecord[] => {
853
- const { frontmatter } = parseFrontmatter(content);
854
- const fm = frontmatter as Record<string, unknown>;
855
- const raw = fm.slices;
856
- const slices = Array.isArray(raw) ? raw : [];
857
- const headingCount = countHeadingsOutsideFences(content, SLICE_HEADING_RE);
858
- if (slices.length !== headingCount) {
859
- throw haltPreflight(
860
- who,
861
- `${who}: slice map ${path} has mismatched slices`,
862
- `${who}: slice map ${path} frontmatter slices (${slices.length}) ≠ '## Slice N:' headings (${headingCount}) — the derived array is stale against the body`,
863
- );
864
- }
865
- if ((slices.length > 0 || fm.slice_count !== undefined) && fm.slice_count !== slices.length) {
866
- throw haltPreflight(
867
- who,
868
- `${who}: slice map ${path} has invalid slice_count`,
869
- `${who}: slice map ${path} frontmatter slice_count (${String(fm.slice_count)}) ≠ slices length (${slices.length}) — rebuild slice_count from the '## Slice N:' headings`,
870
- );
871
- }
872
- return slices.map((entry, index) => {
873
- const e = (entry ?? {}) as Record<string, unknown>;
874
- return {
875
- entry: e,
876
- n: typeof e.n === "number" ? e.n : index + 1,
877
- title: typeof e.title === "string" ? e.title : "",
878
- index,
879
- total: slices.length,
880
- };
881
- });
882
- };
883
-
884
- // Relocated ABOVE SLICE_DESIGN_FANOUT (deleted from its old location below) so it sits
885
- // above its first textual reference. (No TDZ today even unrelocated — `sliceDeps` is only
886
- // read inside the `units` runtime closure, which runs at dispatch, not module-eval — but
887
- // placing it above the fanout keeps the read-order obvious and matches `clusterSliceDag`'s
888
- // existing use below.)
889
- /** The slice-number deps a slice-map entry declares (empty when absent). */
890
- const sliceDeps = (entry: Record<string, unknown>): number[] => {
891
- const raw = entry.deps;
892
- return Array.isArray(raw) ? raw.filter((d): d is number => typeof d === "number") : [];
893
- };
894
-
895
- /** Fan `design-slice` out over the latest slice map's `slices:` array — one design
896
- * session per slice, dependency-ordered. `deps` (slice-N unit ids) drive the wave
897
- * scheduler; `depArtifactFlag` injects each completed dependency's design path as
898
- * `--upstream <path>` so a dependent slice reads its dependency's decided Key Interfaces. */
899
- const SLICE_DESIGN_FANOUT = fanout({
900
- source: "slices",
901
- unit: { by: "frontmatter-array", pattern: "slices" },
902
- max: MAX_PHASES,
903
- depArtifactFlag: "--upstream",
904
- units: ({ state, cwd }) => {
905
- const doc = latestFsArtifact(state, "slices");
906
- if (doc?.handle.kind !== "fs") return [];
907
- const path = doc.handle.path;
908
- const promptPath = handleToString(doc.handle);
909
- return sliceRecords(readArtifactFile(path, cwd), "SLICE_DESIGN_FANOUT", path).map((r) => ({
910
- prompt: `${promptPath} Slice ${r.n}: ${r.title}`.trimEnd(),
911
- label: `slice ${r.index + 1}/${r.total}`,
912
- id: `slice-${r.n}`,
913
- deps: sliceDeps(r.entry).map((n) => `slice-${n}`), // directed edges → unit ids (slice-N)
914
- }));
915
- },
916
- });
917
-
918
- /** Max slices per synth cluster — a context-budget proxy; oversized DAG components split by this. */
919
- const MAX_CLUSTER_SLICES = 6;
920
-
921
- /**
922
- * Group slices into clusters = connected components of the `deps` DAG (a slice
923
- * and everything it transitively depends on / that depends on it land together),
924
- * so coupled slices reconcile inside ONE subplan pass and only cross-cluster
925
- * seams reach the root. Components larger than `MAX_CLUSTER_SLICES` are chunked
926
- * (by slice number) to bound each pass's context. Returns clusters of slice
927
- * numbers, each sorted ascending; components ordered by their smallest slice.
928
- */
929
- const clusterSliceDag = (records: readonly PhaseRecord[]): number[][] => {
930
- const ns = records.map((r) => r.n);
931
- const parent = new Map<number, number>(ns.map((n) => [n, n]));
932
- const find = (x: number): number => {
933
- let root = x;
934
- while (parent.get(root) !== root) root = parent.get(root) ?? root;
935
- let cur = x;
936
- while (parent.get(cur) !== root) {
937
- const next = parent.get(cur) ?? root;
938
- parent.set(cur, root);
939
- cur = next;
940
- }
941
- return root;
942
- };
943
- const union = (a: number, b: number): void => {
944
- const ra = find(a);
945
- const rb = find(b);
946
- if (ra !== rb) parent.set(ra, rb);
947
- };
948
- for (const r of records) for (const d of sliceDeps(r.entry)) if (parent.has(d)) union(r.n, d);
949
- const byRoot = new Map<number, number[]>();
950
- for (const n of ns) {
951
- const root = find(n);
952
- const arr = byRoot.get(root);
953
- if (arr) arr.push(n);
954
- else byRoot.set(root, [n]);
955
- }
956
- const clusters: number[][] = [];
957
- for (const comp of [...byRoot.values()].sort((a, b) => (a[0] ?? 0) - (b[0] ?? 0))) {
958
- const sorted = [...comp].sort((a, b) => a - b);
959
- for (let i = 0; i < sorted.length; i += MAX_CLUSTER_SLICES) {
960
- clusters.push(sorted.slice(i, i + MAX_CLUSTER_SLICES));
961
- }
962
- }
963
- return clusters;
964
- };
965
-
966
- /**
967
- * A directed dependency cycle in the slice DAG (`A→B→…→A`), returned as the slice
968
- * numbers on the cycle; empty when acyclic. `clusterSliceDag` groups by the
969
- * UNDIRECTED connected component, which a directed cycle survives — so the
970
- * design-readiness gate needs this separate directed check. A cycle is the true
971
- * independence defect (slices in a cycle cannot be designed independently); the
972
- * deterministic floor catches it without an LLM coin-flip.
973
- */
974
- const sliceDepCycle = (records: readonly PhaseRecord[]): number[] => {
975
- const deps = new Map<number, number[]>(records.map((r) => [r.n, sliceDeps(r.entry)]));
976
- const WHITE = 0;
977
- const GRAY = 1;
978
- const BLACK = 2;
979
- const color = new Map<number, number>();
980
- const stack: number[] = [];
981
- let cycle: number[] = [];
982
- const visit = (n: number): boolean => {
983
- color.set(n, GRAY);
984
- stack.push(n);
985
- for (const d of deps.get(n) ?? []) {
986
- if (!deps.has(d)) continue; // a dangling dep is a derive/numbering concern, not a cycle
987
- const c = color.get(d) ?? WHITE;
988
- if (c === GRAY) {
989
- cycle = stack.slice(stack.indexOf(d));
990
- return true;
991
- }
992
- if (c === WHITE && visit(d)) return true;
993
- }
994
- stack.pop();
995
- color.set(n, BLACK);
996
- return false;
997
- };
998
- for (const r of records) if ((color.get(r.n) ?? WHITE) === WHITE && visit(r.n)) break;
999
- return cycle;
1000
- };
1001
-
1002
- /**
1003
- * One frozen coverage unit — the brief's ID'd decomposition, set once at the
1004
- * first (human-confirmed) cut and conserved across every reslice. The conserved
1005
- * quantity the gate was missing: a reslice may REDISTRIBUTE units across slices,
1006
- * never DROP one — which is what closes the "pass by simplifying / shrinking
1007
- * scope" escape hatch the sizing dimensions can't see.
1008
- */
1009
- interface CoverageUnit {
1010
- id: string;
1011
- brief: string;
1012
- }
1013
-
1014
- /** Parse a slice map's `coverage:` frontmatter into `{ id, brief }` units (empty when absent). */
1015
- const sliceCoverageUnits = (content: string): CoverageUnit[] => {
1016
- const { frontmatter } = parseFrontmatter(content);
1017
- const raw = (frontmatter as Record<string, unknown>).coverage;
1018
- if (!Array.isArray(raw)) return [];
1019
- return raw.flatMap((e) => {
1020
- const o = (e ?? {}) as Record<string, unknown>;
1021
- return typeof o.id === "string" ? [{ id: o.id, brief: typeof o.brief === "string" ? o.brief : "" }] : [];
1022
- });
1023
- };
1024
-
1025
- /** The coverage-unit ids a slice entry claims to deliver (its `covers:` array). */
1026
- const sliceCovers = (entry: Record<string, unknown>): string[] => {
1027
- const raw = entry.covers;
1028
- return Array.isArray(raw) ? raw.filter((c): c is string => typeof c === "string") : [];
1029
- };
1030
-
1031
- /**
1032
- * Verify every `file:line` citation in `body` resolves against the working tree:
1033
- * the cited file must exist AND carry at least the cited line (a range's high end).
1034
- * A path that misses direct (repo-root/absolute) resolution falls back to the
1035
- * tree file whose path ends with it on whole segments — bare basenames and
1036
- * package-relative forms both back the citation iff exactly ONE tree file
1037
- * matches; an ambiguous suffix stays unresolved (the finding names the
1038
- * candidates so the fix arm can disambiguate) unless one of two tiebreaks names
1039
- * a single candidate: the caller's declared-`files:` union, then the nearest
1040
- * preceding prose mention of a candidate's full path. A bare `path` with no
1041
- * `:line` is not checked (the contract is "verifiable line numbers, or omit
1042
- * them"). Returns one finding per bad citation.
1043
- *
1044
- * EVERY finding this verifier emits is ADVISORY (`StructureFinding.advisory`):
1045
- * an advisory-only structure verdict rates `low`, which the gates'
1046
- * `allDimensionsPass` severity floor rides through, so citation-resolution
1047
- * findings are recorded on the trail — and handed to the ship grade panel via
1048
- * `--cite-check` for symbol-level adjudication — but never stop a run. The
1049
- * run-history audit forced this: three months of flagged paths held zero
1050
- * fabrications, while blocking on them cost hours of fix rounds and dead runs
1051
- * (details in the 2.6.x changelog). Blocking severity on the shared structure
1052
- * verdict comes ONLY from `verifyPhaseFilesCoverage` (an undeclared write
1053
- * corrupts dep derivation — that floor stays load-bearing).
1054
- */
1055
- /** Trees a citation must never resolve INTO — vendored deps, build copies, or
1056
- * prior pipeline artifacts (a stale artifact copy would back a fabricated line).
1057
- * `.rpiv` is skipped with one carve-out: the walk re-enters `.rpiv/guidance`
1058
- * (see `buildBasenameIndex`) — the guidance shadow tree is a legitimate,
1059
- * routinely-cited and routinely-edited target, and skipping it made every
1060
- * suffix-form `architecture.md` citation a false "does not exist". */
1061
- const CITATION_WALK_SKIP: ReadonlySet<string> = new Set(["node_modules", ".git", "dist", "coverage", ".rpiv"]);
1062
- /** Backstop so a pathological tree can't stall the deterministic cite floor. */
1063
- const CITATION_WALK_FILE_CAP = 50_000;
1064
-
1065
- /** The lazily-built basename → absolute-path(s) index backing the suffix
1066
- * fallback in `resolveCitationPath`. `truncated` marks a partial walk past
1067
- * `CITATION_WALK_FILE_CAP`, which disables the fallback (uniqueness
1068
- * untrustworthy). */
1069
- type BasenameIndex = { index: Map<string, string[]>; truncated: boolean };
1070
-
1071
- /**
1072
- * Index every source file's basename → its absolute path(s) under `cwd` — the
1073
- * candidate pool behind the suffix fallback in `verifyCitations`. The generative
1074
- * producers (slice/synthesize/elaborate) routinely cite a file by bare basename
1075
- * (`built-in-workflows.ts:1431`) or by a package-relative suffix
1076
- * (`validate/stage-rules.ts:70` for `packages/rpiv-workflow/validate/stage-rules.ts`)
1077
- * — mechanical path-prefix omissions, not fabricated references. The basename
1078
- * keys the candidates; `verifyCitations` narrows them by whole-segment suffix.
1079
- * A UNIQUE match backs the citation; an AMBIGUOUS one stays unresolved — unless
1080
- * one of `verifyCitations`' tiebreaks (the caller's declared-`files:` union,
1081
- * then the nearest preceding prose mention) names exactly one
1082
- * candidate — so the producer must disambiguate with the repo-root-relative
1083
- * path. Skips
1084
- * vendored/generated trees so a citation never resolves to a build copy or a
1085
- * prior artifact. Bounded by the file cap.
1086
- */
1087
- const buildBasenameIndex = (cwd: string): BasenameIndex => {
1088
- // Unreadable dir → empty listing, never a throw from the deterministic floor.
1089
- const listDir = (dir: string) => {
1090
- try {
1091
- return readdirSync(dir, { withFileTypes: true });
1092
- } catch {
1093
- return [];
1094
- }
1095
- };
1096
- const index = new Map<string, string[]>();
1097
- const stack: string[] = [cwd];
1098
- let seen = 0;
1099
- while (stack.length > 0) {
1100
- const dir = stack.pop() as string;
1101
- for (const e of listDir(dir)) {
1102
- if (e.isDirectory()) {
1103
- if (!CITATION_WALK_SKIP.has(e.name)) stack.push(join(dir, e.name));
1104
- // The guidance carve-out — see CITATION_WALK_SKIP's note. A missing
1105
- // guidance dir degrades to an empty listing.
1106
- else if (e.name === ".rpiv") stack.push(join(dir, e.name, "guidance"));
1107
- continue;
1108
- }
1109
- if (!e.isFile()) continue;
1110
- // Past the cap the index is INCOMPLETE, so "exactly one match" can no
1111
- // longer be trusted — mark it truncated and let the caller disable the
1112
- // fallback (strict direct-resolution only) rather than back a possibly
1113
- // wrong file off a partial walk.
1114
- if (++seen > CITATION_WALK_FILE_CAP) return { index, truncated: true };
1115
- const abs = join(dir, e.name);
1116
- const arr = index.get(e.name);
1117
- if (arr) arr.push(abs);
1118
- else index.set(e.name, [abs]);
1119
- }
1120
- }
1121
- return { index, truncated: false };
1122
- };
1123
-
1124
- /** Outcome of resolving a single citation's `path` against `cwd`. `abs` is the
1125
- * one backing file when resolution is unique; `ambiguous` carries the candidate
1126
- * list (absolute paths) when more than one tree file matches, so the caller can
1127
- * render the disambiguation finding text. `undefined` ⇒ no match
1128
- * (does-not-exist). This is the minimal-deviation return shape — a plain
1129
- * `string | undefined` would drop the candidate list the disambiguation finding
1130
- * text depends on. */
1131
- type CitationResolution = { abs: string } | { ambiguous: string[] };
1132
-
1133
- /** Strategy 4 of `resolveCitationPath`: tree files whose REPO-RELATIVE path ends
1134
- * with the cited `path` on WHOLE segments. A bare basename is the one-segment
1135
- * case; a multi-segment citation narrows the basename's candidates at a `/`
1136
- * boundary, so `workflow/validate/x.ts` can never match inside
1137
- * `rpiv-workflow/validate/x.ts`. Compared repo-relative (never against the
1138
- * absolute path) so the checkout directory's own name can never back a citation
1139
- * — `src/utils.ts` must not resolve to `<cwd>/utils.ts` just because the repo
1140
- * happens to be cloned at `/tmp/src`. Reads/writes the shared `indexHolder` so
1141
- * the basename index is built lazily ONCE and shared across citations (the
1142
- * first direct-resolution miss pays the tree walk). */
1143
- const suffixMatchesFor = (path: string, cwd: string, indexHolder: { value: BasenameIndex | undefined }): string[] => {
1144
- indexHolder.value ??= buildBasenameIndex(cwd);
1145
- if (indexHolder.value.truncated) return []; // partial index ⇒ uniqueness untrustworthy ⇒ strict
1146
- const candidates = indexHolder.value.index.get(basename(path)) ?? [];
1147
- if (!path.includes("/")) return candidates;
1148
- const suffix = `/${path}`;
1149
- return candidates.filter((abs) =>
1150
- `/${abs
1151
- .slice(cwd.length + 1)
1152
- .split(sep)
1153
- .join("/")}`.endsWith(suffix),
1154
- );
1155
- };
1156
-
1157
- /** Resolve a citation's `path` to one backing file under `cwd`, encapsulating
1158
- * all four strategies in order: (1) direct — `path` or `cwd/path`; (2,3)
1159
- * dependency probes — `node_modules/<path>` and `node_modules/@<path>` (the
1160
- * latter because the citation regex cannot carry `@`, so a cited
1161
- * `node_modules/@scope/pkg/f.js` parses as `scope/pkg/f.js`); DIRECT probes
1162
- * only — the suffix walk still skips `node_modules` (per `CITATION_WALK_SKIP`),
1163
- * so a bare basename never resolves into a dep; (4) suffix fallback — a UNIQUE
1164
- * tree-file suffix match backs the citation, an AMBIGUOUS one returns the
1165
- * candidate list. PURE: emits no findings and throws never — all finding text
1166
- * lives in `verifyCitations`. The lazily-built basename index is shared across
1167
- * calls via `indexHolder`. */
1168
- const resolveCitationPath = (
1169
- path: string,
1170
- cwd: string,
1171
- indexHolder: { value: BasenameIndex | undefined },
1172
- ): CitationResolution | undefined => {
1173
- // existsSync-then-statSync races a concurrent delete into a throw OUT of the
1174
- // deterministic floor (⇒ FAIL_SCRIPT_THREW) — one guarded probe instead.
1175
- const isTreeFile = (p: string): boolean => {
1176
- try {
1177
- return statSync(p).isFile();
1178
- } catch {
1179
- return false;
1180
- }
1181
- };
1182
- // Strategy 1 — direct.
1183
- const direct = isAbsolute(path) ? path : join(cwd, path);
1184
- if (isTreeFile(direct)) return { abs: direct };
1185
- // Strategies 2 & 3 — dependency probes (lockfile-pinned dep source; the regex
1186
- // cannot carry `@`, so `node_modules/@scope/pkg/f.js` is cited as `scope/pkg/f.js`).
1187
- for (const candidate of [join(cwd, "node_modules", path), join(cwd, "node_modules", `@${path}`)]) {
1188
- if (isTreeFile(candidate)) return { abs: candidate };
1189
- }
1190
- // Strategy 4 — suffix fallback: back the citation iff exactly ONE tree file matches.
1191
- const matches = suffixMatchesFor(path, cwd, indexHolder);
1192
- if (matches.length === 1) return { abs: matches[0] };
1193
- if (matches.length > 1) return { ambiguous: matches };
1194
- return undefined;
1195
- };
1196
-
1197
- /** Example-path namespaces the skill prompts use in illustrative citations
1198
- * (`path/to/file.ext:12`, `packages/x/y.ts:42`). Artifacts quote — and models
1199
- * imitate — these examples in unfenced prose, where the fence skip cannot
1200
- * reach them; a citation under one of these prefixes is documentation shape,
1201
- * never a claim about the tree, and prosecuting one buys a full LLM fix round
1202
- * for zero risk averted (three of f329's floor failures were this class). */
1203
- const PLACEHOLDER_CITATION_PREFIXES: readonly string[] = ["path/to/", "packages/x/"];
1204
-
1205
- /**
1206
- * Proximity tiebreak for a citation left ambiguous by the declared-`files:`
1207
- * intersection: resolve to the candidate whose repo-root-relative path has the
1208
- * nearest PRECEDING prose mention — the common artifact idiom of naming a file
1209
- * once in full, then citing it by bare basename. Prose only: mentions inside
1210
- * YAML frontmatter (`files:` ordering carries no authorial intent — a tie there
1211
- * stays a tie) or fenced spans (example/fixture territory) don't count, and
1212
- * matches are token-bounded so a candidate never back-matches inside a longer
1213
- * path mention (`a/dup.ts` inside `x/a/dup.ts`). Returns the winner's absolute
1214
- * path, or `undefined` — the citation then stays unbacked as before.
1215
- */
1216
- const nearestProseMention = (
1217
- body: string,
1218
- upTo: number,
1219
- candidates: readonly string[],
1220
- cwd: string,
1221
- fenced: readonly [number, number][],
1222
- proseStart: number,
1223
- ): string | undefined => {
1224
- let bestAbs: string | undefined;
1225
- let bestIdx = -1;
1226
- for (const abs of candidates) {
1227
- if (!abs.startsWith(cwd + sep)) continue;
1228
- const rel = abs
1229
- .slice(cwd.length + 1)
1230
- .split(sep)
1231
- .join("/");
1232
- // Walk mentions nearest-first; the first CLEAN one (token-bounded, in
1233
- // prose, outside fences) is this candidate's best — earlier ones can't win.
1234
- let from = upTo - rel.length;
1235
- while (from >= 0) {
1236
- const i = body.lastIndexOf(rel, from);
1237
- if (i < 0 || i < proseStart) break;
1238
- from = i - 1;
1239
- const prev = i > 0 ? (body[i - 1] as string) : "";
1240
- const next = body[i + rel.length] ?? "";
1241
- if (prev !== "" && /[\w.@/-]/.test(prev)) continue;
1242
- if (next !== "" && /[\w-]/.test(next)) continue;
1243
- if (fenced.some(([s, e]) => i >= s && i < e)) continue;
1244
- if (i > bestIdx) {
1245
- bestIdx = i;
1246
- bestAbs = abs;
1247
- }
1248
- break;
1249
- }
1250
- }
1251
- return bestAbs;
1252
- };
1253
-
1254
- const verifyCitations = (body: string, cwd: string, declared?: ReadonlySet<string>): StructureFinding[] => {
1255
- const findings: StructureFinding[] = [];
1256
- const seen = new Set<string>();
1257
- // Fenced text is example/fixture territory, not prose asserting a real
1258
- // file:line — a fenced placeholder shaped like a citation must not fail the
1259
- // floor (it false-failed the very plan that fixes this). Span check, not a
1260
- // placeholder-pattern skip: a REAL citation that merely looks placeholder-ish
1261
- // still verifies when it appears in prose.
1262
- const fenced = fencedSpans(body);
1263
- // Prose begins past the YAML frontmatter: the proximity tiebreak must not
1264
- // read the `files:` array as a mention (its ordering carries no intent — a
1265
- // tie inside the declared set stays a tie).
1266
- let proseStart = 0;
1267
- if (body.startsWith("---\n")) {
1268
- const end = body.indexOf("\n---\n", 3);
1269
- if (end !== -1) proseStart = end + "\n---\n".length;
1270
- }
1271
- // Built lazily and reused across citations — only the first direct-resolution
1272
- // miss pays the tree walk, and only when at least one such citation exists.
1273
- const indexHolder: { value: BasenameIndex | undefined } = { value: undefined };
1274
- for (const m of body.matchAll(FILE_LINE_CITATION_RE)) {
1275
- const [, path, startStr, endStr] = m;
1276
- if (!path || !startStr) continue;
1277
- if (fenced.some(([s, e]) => m.index >= s && m.index < e)) continue;
1278
- if (PLACEHOLDER_CITATION_PREFIXES.some((p) => path.startsWith(p))) continue;
1279
- const key = `${path}:${startStr}${endStr ? `-${endStr}` : ""}`;
1280
- if (seen.has(key)) continue;
1281
- seen.add(key);
1282
- let resolved = resolveCitationPath(path, cwd, indexHolder);
1283
- if (resolved && "ambiguous" in resolved && declared !== undefined) {
1284
- // Declared-write-set tiebreak: when the caller supplies the artifact's own
1285
- // declared `files:` union and exactly ONE ambiguous candidate is in it, the
1286
- // artifact has already named the file it means — resolve there instead of
1287
- // halting the run over a path-prefix omission. A tie INSIDE the declared
1288
- // set (two declared `command.ts` files) stays ambiguous: the citation is
1289
- // then genuinely unreadable even against the artifact's own write-set.
1290
- const declaredMatches = resolved.ambiguous.filter(
1291
- (abs) =>
1292
- abs.startsWith(cwd + sep) &&
1293
- declared.has(
1294
- abs
1295
- .slice(cwd.length + 1)
1296
- .split(sep)
1297
- .join("/"),
1298
- ),
1299
- );
1300
- if (declaredMatches.length === 1) resolved = { abs: declaredMatches[0] };
1301
- }
1302
- if (resolved && "ambiguous" in resolved) {
1303
- // Proximity tiebreak: the nearest preceding prose mention of a
1304
- // candidate's full path names the file the author means.
1305
- const near = nearestProseMention(body, m.index, resolved.ambiguous, cwd, fenced, proseStart);
1306
- if (near !== undefined) resolved = { abs: near };
1307
- }
1308
- if (resolved && "ambiguous" in resolved) {
1309
- // More than one tree file matches — name the candidates so the fix arm can disambiguate.
1310
- const shown = resolved.ambiguous
1311
- .slice(0, 3)
1312
- .map((a) => (a.startsWith(cwd + sep) ? a.slice(cwd.length + 1) : a));
1313
- findings.push({
1314
- 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.`,
1315
- where: key,
1316
- // Every candidate is a REAL tree file — advisory per the tier above.
1317
- advisory: true,
1318
- });
1319
- continue;
1320
- }
1321
- let abs = resolved?.abs;
1322
- if (abs === undefined && declared !== undefined) {
1323
- // Declared-write-set rescue on a NO-MATCH resolution — the ambiguity
1324
- // tiebreak's missing twin. A unique whole-segment suffix match inside
1325
- // the plan's own `files:` names the file the author means: verify
1326
- // against it when it exists on disk; a declared file ABSENT from the
1327
- // tree is a planned CREATE — the citation is a forward reference to
1328
- // planned content, unverifiable at this revision, so no finding.
1329
- const matches = [...declared].filter((d) => d === path || `/${d}`.endsWith(`/${path}`));
1330
- if (matches.length === 1) {
1331
- const cand = join(cwd, matches[0]);
1332
- if (!existsSync(cand)) continue;
1333
- abs = cand;
1334
- }
1335
- }
1336
- if (!abs) {
1337
- findings.push({
1338
- 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.`,
1339
- where: key,
1340
- // Advisory like every citation-resolution finding — see the tier
1341
- // note in the function header.
1342
- advisory: true,
1343
- });
1344
- continue;
1345
- }
1346
- // A file that vanishes or turns unreadable between resolution and the read
1347
- // is an unbacked citation, never a throw out of the deterministic floor.
1348
- let lineCount: number;
1349
- try {
1350
- lineCount = readFileSync(abs, "utf-8").split("\n").length;
1351
- } catch {
1352
- findings.push({
1353
- detail: `Unbacked citation ${key} — ${path} resolved but could not be read at this revision. A file:line citation must be verifiable, or the line numbers must be omitted. Fix the path (repo-root-relative) or drop the citation.`,
1354
- where: key,
1355
- // The file EXISTS (it resolved) — advisory per the tier above.
1356
- advisory: true,
1357
- });
1358
- continue;
1359
- }
1360
- const high = Math.max(Number(startStr), endStr ? Number(endStr) : 0);
1361
- if (high > lineCount) {
1362
- findings.push({
1363
- detail: `Unbacked citation ${key} — ${path} has ${lineCount} lines, so line ${high} matches no version of the file. A file:line citation must be verifiable, or the line numbers must be omitted. Correct the range or drop the line numbers.`,
1364
- where: key,
1365
- // The file exists; only the ordinate drifted — advisory per the tier above.
1366
- advisory: true,
1367
- });
1368
- }
1369
- }
1370
- return findings;
1371
- };
1372
-
1373
- /** A dispatched sub-plan basename with its `_cluster-<k>` ordinal resolved. */
1374
- type DispatchedCluster = { path: string; k: number };
1375
-
1376
- /**
1377
- * A citation string occurs LIVE in the slice-map text — outside fenced spans
1378
- * and not as half of an `old→new` refresh-note pair. A re-slice's revision
1379
- * note legitimately QUOTES the citations it refreshed (contract: only as
1380
- * arrow pairs or inside a fence — see the slice skill's re-slice mode);
1381
- * treating a quoted old citation as still-live would forfeit every documented
1382
- * refresh's discharge, and treating a quoted new one as present would credit
1383
- * a fix that never touched the live `Draws on` lines.
1384
- */
1385
- const citeOccursLive = (body: string, spans: readonly [number, number][], cite: string): boolean => {
1386
- for (let i = body.indexOf(cite); i !== -1; i = body.indexOf(cite, i + 1)) {
1387
- if (spans.some(([s, e]) => i >= s && i < e)) continue;
1388
- if (body.startsWith("→", i + cite.length)) continue;
1389
- if (body.endsWith("→", i)) continue;
1390
- return true;
1391
- }
1392
- return false;
1393
- };
1394
-
1395
- /**
1396
- * One cite-remedy finding is satisfied by the slice-map text: the demanded
1397
- * seed's path occurs live — line suffixes are stripped before matching,
1398
- * because the fix may cite a corrected range and the citation floor
1399
- * (`verifyCitations`) verifies whatever range it actually wrote. `Draws on`
1400
- * and `Out of scope` both satisfy the remedy, so a live occurrence anywhere
1401
- * in the map is the contract. (The former REFRESH mode — a `stale` drifted
1402
- * line number to replace — was removed with anchor-precision grading: a
1403
- * drifted line number is no longer a finding, so nothing demands a refresh.)
1404
- *
1405
- * A finding without a concrete string `requires` is unverifiable ⇒ not satisfied.
1406
- */
1407
- const citeFindingSatisfied = (
1408
- mapBody: string,
1409
- spans: readonly [number, number][],
1410
- f: { requires?: unknown },
1411
- ): boolean =>
1412
- typeof f.requires === "string" &&
1413
- f.requires.length > 0 &&
1414
- citeOccursLive(mapBody, spans, f.requires.replace(/:\d[-\d,:]*$/, ""));
1415
-
1416
- /**
1417
- * Structural fingerprint of one slice-map round: the `slices` + `coverage`
1418
- * frontmatter it published on the `slices` channel — no file re-read.
1419
- * `undefined` when the round carried no `slices` data; a caller must treat
1420
- * that as "cannot compare", never as "unchanged".
1421
- */
1422
- const sliceShape = (round: Output | undefined): string | undefined => {
1423
- const d = round?.data as { slices?: unknown; coverage?: unknown } | undefined;
1424
- return d?.slices === undefined ? undefined : JSON.stringify({ slices: d.slices, coverage: d.coverage ?? null });
1425
- };
1426
-
1427
- /** The verdict fields the cite-only discharge consults. */
1428
- type CiteRemedyVerdict = {
1429
- pass?: boolean;
1430
- remedy?: string;
1431
- findings?: readonly { requires?: unknown }[];
1432
- };
1433
-
1434
- /**
1435
- * Deterministic discharge of a CITE-ONLY `design-readiness` fail — the middle
1436
- * case between "carry a passing verdict" (impossible on the slice gate: its
1437
- * lone dimension failed) and "buy a full re-grade panel" (wasteful when the
1438
- * grader already named the exact citations to add or refresh). A fix that
1439
- * also restructured forfeits the discharge and takes the normal re-grade.
1440
- */
1441
- const citeRemedyDischarged = (state: RunView, mapBody: string): boolean => {
1442
- const verdict = latestVerdictPerDimension(state.named["slice-verdicts"]).get("design-readiness");
1443
- const v = verdict?.data as CiteRemedyVerdict | undefined;
1444
- if (v?.pass !== false || v.remedy !== "cite") return false;
1445
- // A fix must have LANDED since the verdict — discharging the judged map
1446
- // unchanged would contradict the grader, who read it and found the cites
1447
- // wrong. Basename inequality cannot witness the fix (a re-slice may
1448
- // legitimately edit the map in place); publication order can: the latest
1449
- // `slices` round must postdate the verdict.
1450
- const entries = state.named.slices ?? [];
1451
- const verdictTs = verdict?.meta?.ts;
1452
- const currentTs = entries.at(-1)?.meta?.ts;
1453
- if (typeof verdictTs !== "string" || typeof currentTs !== "string" || currentTs <= verdictTs) return false;
1454
- const findings = Array.isArray(v.findings) ? v.findings : [];
1455
- if (findings.length === 0) return false;
1456
- const spans = fencedSpans(mapBody);
1457
- if (!findings.every((f) => f != null && citeFindingSatisfied(mapBody, spans, f))) return false;
1458
- // Shape must match the round the grader judged — located by publication
1459
- // order, not filename, for the same in-place reason.
1460
- const judged = [...entries].reverse().find((s) => typeof s.meta?.ts === "string" && s.meta.ts <= verdictTs);
1461
- const judgedShape = sliceShape(judged);
1462
- return judgedShape !== undefined && judgedShape === sliceShape(entries.at(-1));
1463
- };
1464
-
1465
- /**
1466
- * Deterministic Phase-1 slice-check — the un-gameable floor beneath the LLM
1467
- * `design-readiness` panel. It enforces the invariants a prose grader cannot
1468
- * reliably hold because it grades the slicer's own self-description:
1469
- * • acyclicity — the `deps` DAG must be cycle-free.
1470
- * • coverage conservation — every coverage unit FROZEN at the first cut
1471
- * (`state.named.slices[0]`) must still be claimed by ≥1 slice's `covers`,
1472
- * so a reslice can only redistribute the brief, never simplify by dropping
1473
- * scope. Anchored to the FIRST cut (not the latest map) so a reslice cannot
1474
- * disable the check by deleting the `coverage:` array — the frozen set is
1475
- * read from round 0.
1476
- * • citation backing — every `file:line` the slice map cites (its `Draws on:`
1477
- * footing, refracted up from research) must resolve against the tree. An
1478
- * unbacked citation is fabricated precision that would otherwise starve or
1479
- * mislead the design pass; the deterministic floor stops it here.
1480
- * Emits one combined `{ dimension: "structure" }` verdict onto the
1481
- * `slice-check` channel AND writes it to an fs artifact so the reslice arm's
1482
- * `reads: [fanin("slice-check")]` projection carries the FINDINGS (not just the
1483
- * pass/fail) into `slice-fix` — the way `amend` receives `--code-verdicts`. The
1484
- * gate route folds the channel `data` with the LLM verdicts.
1485
- * Deterministic ⇒ idempotent across reslice rounds (no flicker, resume-safe): the
1486
- * verdict basename is keyed on the slice-map basename, so a re-run OVERWRITES its
1487
- * own slot rather than duplicating it.
1488
- */
1489
- const sliceStructureCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1490
- const latest = latestFsArtifact(state, "slices");
1491
- if (latest?.handle.kind !== "fs") {
1492
- throw haltPreflight(
1493
- "slice-check",
1494
- "slice-check: no slice map to check",
1495
- "slice-check: no fs artifact on the 'slices' channel — slice must run before the structure check",
1496
- );
1497
- }
1498
- const mapBody = readArtifactFile(latest.handle.path, cwd);
1499
- const records = sliceRecords(mapBody, "slice-check", latest.handle.path);
1500
- const findings: { detail: string; where: string }[] = [];
1501
-
1502
- const cycle = sliceDepCycle(records);
1503
- if (cycle.length > 0) {
1504
- const loop = [...cycle, cycle[0]].join("→");
1505
- findings.push({
1506
- detail: `Dependency cycle ${loop} — slices in a cycle cannot be designed independently. Break it: merge the cycle into one slice, or invert one edge so a shared contract has a single owning slice.`,
1507
- where: `deps: ${cycle.map((n) => `Slice ${n}`).join(", ")}`,
1508
- });
1509
- }
1510
-
1511
- // Coverage conservation, anchored to the FROZEN units of the first cut.
1512
- const firstFs = state.named.slices?.[0]?.artifacts.find((a) => a.handle.kind === "fs");
1513
- const frozen = firstFs?.handle.kind === "fs" ? sliceCoverageUnits(readArtifactFile(firstFs.handle.path, cwd)) : [];
1514
- if (frozen.length > 0) {
1515
- const covered = new Set(records.flatMap((r) => sliceCovers(r.entry)));
1516
- const dropped = frozen.filter((u) => !covered.has(u.id));
1517
- if (dropped.length > 0) {
1518
- findings.push({
1519
- detail: `Coverage regression — ${dropped.length} brief unit(s) frozen at the first cut are no longer claimed by any slice's 'covers': ${dropped.map((u) => `${u.id} (${u.brief})`).join("; ")}. A reslice must redistribute every unit across slices, never drop one. Re-add the dropped unit(s) to an owning slice's 'covers'.`,
1520
- where: `coverage: ${dropped.map((u) => u.id).join(", ")}`,
1521
- });
1522
- }
1523
- }
1524
-
1525
- // Citation backing — every file:line the map cites must resolve.
1526
- findings.push(...verifyCitations(mapBody, cwd));
1527
-
1528
- // Stamp the cite-only discharge ONLY on a green floor: structure clean +
1529
- // citation backing verified + demanded seeds present + shape unchanged is
1530
- // exactly what a fresh design-readiness pass on this map would re-establish,
1531
- // so the `sliceGatePasses` skip stays provably equivalent to "re-grade, then pass".
1532
- const discharge =
1533
- findings.length === 0 && citeRemedyDischarged(state, mapBody)
1534
- ? { citeDischarged: basename(latest.handle.path) }
1535
- : undefined;
1536
- return writeStructureVerdict("slice-check", latest.handle, findings, cwd, discharge);
1537
- };
1538
-
1539
- /**
1540
- * `_<k>` cluster ordinal a partial sub-plan carries in its basename
1541
- * (`<slug>_cluster-<k>.md`), emitted by `synthesize`'s partial mode from the
1542
- * `--cluster <k>` the fanout threads on every cluster unit. The token a
1543
- * `subplan-check` reconciliation keys dispatched sub-plans on. Anchored to the
1544
- * basename TAIL (extension optional — extensionless agent writes happen, see
1545
- * the implement-scope floor precedent) so a name carrying several `_cluster-`
1546
- * tokens binds the trailing one deterministically, not the first match.
1547
- */
1548
- const CLUSTER_TOKEN_RE = /_cluster-(\d+)(?:\.\w+)?$/;
1549
-
1550
- /** The pre-filter cluster count the fanout received — the count
1551
- * `subplanCoverageCheck` reconciles dispatched ordinals against. Delegates to
1552
- * `clusterSliceDag`. */
1553
- const expectedClusterCount = (records: readonly PhaseRecord[]): number => clusterSliceDag(records).length;
1554
-
1555
- /** Slice numbers that have NO design artifact on the `designs` channel — the gap
1556
- * the missing-design preflight halts on (a slice with no design is unrepairable
1557
- * by re-dispatch). */
1558
- const designCoverageGap = (sliceNumbers: Set<number>, designBySlice: Map<number, string>): number[] =>
1559
- [...sliceNumbers].filter((n) => !designBySlice.has(n)).sort((a, b) => a - b);
1560
-
1561
- /** Collect every dispatched sub-plan's `_cluster-<k>` ordinal from the `subplans`
1562
- * channel. The `subplans` slot is a produces-fanout channel: `placeFanoutOutput`
1563
- * pre-sizes it to the round's unit total and overwrites each unit's own index, so
1564
- * with a stable unit set iterating it reflects the latest output per unit — a
1565
- * re-dispatch's fresh artifacts re-evaluate cleanly. (A unit that FAILS on
1566
- * re-dispatch leaves its prior-round output at its index; that stale entry
1567
- * re-reads as current here.) Returns the resolved ordinals AND a `tokenless`
1568
- * finding per basename that carries no `_cluster-<k>` token (the root merge
1569
- * cannot attribute a tokenless sub-plan to a slice-DAG cluster). */
1570
- const dispatchedClusterOrdinals = (
1571
- state: RunView,
1572
- ): { dispatched: DispatchedCluster[]; tokenless: StructureFinding[] } => {
1573
- const dispatched: DispatchedCluster[] = [];
1574
- const tokenless: StructureFinding[] = [];
1575
- for (const out of state.named.subplans ?? []) {
1576
- for (const a of out.artifacts) {
1577
- if (a.handle.kind !== "fs") continue;
1578
- const name = basename(a.handle.path);
1579
- const m = CLUSTER_TOKEN_RE.exec(name);
1580
- if (!m) {
1581
- tokenless.push({
1582
- 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.`,
1583
- where: name,
1584
- });
1585
- continue;
1586
- }
1587
- dispatched.push({ path: handleToString(a.handle), k: Number(m[1]) });
1588
- }
1589
- }
1590
- return { dispatched, tokenless };
1591
- };
1592
-
1593
- /** A finding per `_cluster-<k>` ordinal claimed by MORE THAN ONE dispatched
1594
- * sub-plan — a clobber (not a legitimate re-emit: within one round every unit
1595
- * index is a distinct artifact because the channel is replaced each round, so a
1596
- * shared `<k>` is the lost-cluster collision itself). */
1597
- const clobberedOrdinals = (dispatched: readonly DispatchedCluster[]): StructureFinding[] => {
1598
- const pathsByK = new Map<number, string[]>();
1599
- for (const d of dispatched) {
1600
- const arr = pathsByK.get(d.k);
1601
- if (arr) arr.push(d.path);
1602
- else pathsByK.set(d.k, [d.path]);
1603
- }
1604
- const findings: StructureFinding[] = [];
1605
- for (const [k, paths] of pathsByK) {
1606
- if (paths.length > 1) {
1607
- findings.push({
1608
- 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.`,
1609
- where: `cluster-${k}`,
1610
- });
1611
- }
1612
- }
1613
- return findings;
1614
- };
1615
-
1616
- /** sources-coverage — every slice's design must appear in SOME sub-plan's
1617
- * `sources:`. Reads the covered-slice set off each sub-plan's parsed `sources:`
1618
- * (designs follow the `_slice-<N>` convention) and reconciles it against the full
1619
- * slice map. A sub-plan whose frontmatter does not PARSE gets its own
1620
- * re-dispatchable finding naming the FILE (never a terminal halt — the same
1621
- * stray-colon class `artifact-collector` degrades on); when ANY sub-plan is
1622
- * unparseable, the per-slice reconciliation DEFERS (an unreadable sub-plan's
1623
- * coverage is unknowable; blaming its slices would misdirect the repair). */
1624
- const sourcesCoverageGaps = (state: RunView, cwd: string, sliceNumbers: Set<number>): StructureFinding[] => {
1625
- const findings: StructureFinding[] = [];
1626
- const coveredSlices = new Set<number>();
1627
- let unparseable = false;
1628
- for (const out of state.named.subplans ?? []) {
1629
- for (const a of out.artifacts) {
1630
- if (a.handle.kind !== "fs") continue;
1631
- let frontmatter: unknown;
1632
- try {
1633
- ({ frontmatter } = parseFrontmatter(readArtifactFile(handleToString(a.handle), cwd)));
1634
- } catch {
1635
- unparseable = true;
1636
- findings.push({
1637
- 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:'.`,
1638
- where: basename(a.handle.path),
1639
- });
1640
- continue;
1641
- }
1642
- const fm = frontmatter && typeof frontmatter === "object" ? (frontmatter as Record<string, unknown>) : {};
1643
- const sources = fm.sources;
1644
- if (!Array.isArray(sources)) continue;
1645
- for (const s of sources) {
1646
- if (typeof s !== "string") continue;
1647
- const sm = DESIGN_SLICE_RE.exec(s);
1648
- if (sm) coveredSlices.add(Number(sm[1]));
1649
- }
1650
- }
1651
- }
1652
- if (!unparseable) {
1653
- for (const n of [...sliceNumbers].sort((a, b) => a - b)) {
1654
- if (!coveredSlices.has(n)) {
1655
- findings.push({
1656
- 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:'.`,
1657
- where: `sources: slice ${n}`,
1658
- });
1659
- }
1660
- }
1661
- }
1662
- return findings;
1663
- };
1664
-
1665
- /**
1666
- * Deterministic subplan cluster-coverage floor — the structural backstop between
1667
- * the cluster fanout and the root merge. After `subplan` fans each slice-DAG
1668
- * cluster out to a partial sub-plan, this reconciles what was DISPATCHED against
1669
- * what the slice map PROMISED, before the root `plan` merge fans them in:
1670
- * • cluster-count conservation — the PRE-FILTER cluster count
1671
- * (`clusterSliceDag(sliceRecords(latest slices)).length`) must equal the
1672
- * number of distinct `_cluster-<k>` ordinals the fanout emitted. A re-dispatch
1673
- * that re-clobbered an ordinal (the pre-fix clobber bug — two clusters
1674
- * sharing `<k>`, or a tokenless basename) collapses the distinct count,
1675
- * surfacing as a missing cluster here.
1676
- * • token conformance — every dispatched sub-plan basename MUST carry a
1677
- * `_cluster-<k>` token; a tokenless name means `synthesize` dropped the
1678
- * `--cluster <k>` flag and the merge can't attribute it to a cluster.
1679
- * • duplicate/clobbered ordinal — two dispatched sub-plans sharing the same
1680
- * `<k>` (a clobber, not a legitimate re-emit: `placeFanoutOutput` overwrites
1681
- * each unit's own index in the channel slot, so within one round every unit
1682
- * index is a distinct artifact — a shared `<k>` is a real collision, the
1683
- * lost-cluster bug itself).
1684
- * • sources-coverage — every slice's design must appear in SOME sub-plan's
1685
- * `sources:` (the fanout threads each `--designs <path>` and `synthesize`
1686
- * echoes them into `sources:`). Designs follow the `_slice-<N>` convention, so
1687
- * the covered slice set is read off `sources:` and reconciled against the full
1688
- * slice map; a slice whose design no sub-plan lists is a slice the merge would
1689
- * silently drop. A sub-plan whose frontmatter does not PARSE gets its own
1690
- * re-dispatchable finding naming the FILE (never a `FAIL_SCRIPT_THREW` halt —
1691
- * the same stray-colon class `artifact-collector` degrades on), and the
1692
- * per-slice reconciliation defers until every sub-plan parses, so a parse
1693
- * failure is never mis-blamed on the slices it happened to cover.
1694
- * Preflight: a slice with NO design on the `designs` channel halts LOUD before
1695
- * any reconciliation — the fanout drops (or under-feeds) its cluster pre-dispatch
1696
- * (`if (!designs.length) return undefined`), so re-dispatching `subplan` re-drops
1697
- * it every round until `maxBackwardJumps` exhausts with a diagnostic naming the
1698
- * refused re-entry instead of the cause. The missing design is upstream
1699
- * (`slice-design`/`design-review`) and unreachable from this loop's backward
1700
- * edge; halting here names the actual defect and spends no jump budget.
1701
- * Emits `severity: pass ? "none" : "high"` (load-bearing — the route routes via
1702
- * `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently passes a
1703
- * `pass:false` verdict rated `low`/`none`; a lost cluster MUST rate `high` or it
1704
- * ships). Deliberately NOT the `match("verdict", …)` STOP idiom
1705
- * `implementScopeCheck` uses — a lost cluster IS repairable by re-dispatch, so the
1706
- * floor routes the backward edge to `subplan`, bounded by `maxBackwardJumps`.
1707
- * Deterministic ⇒ idempotent across re-dispatch rounds: the verdict basename is
1708
- * keyed on the slice-map basename, so a re-run OVERWRITES its own slot.
1709
- */
1710
- const subplanCoverageCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1711
- const latestSliceMap = latestFsArtifact(state, "slices");
1712
- if (latestSliceMap?.handle.kind !== "fs") {
1713
- throw haltPreflight(
1714
- "subplan-check",
1715
- "subplan-check: no slice map to reconcile against",
1716
- "subplan-check: no fs artifact on the 'slices' channel — slice must run before the subplan coverage check",
1717
- );
1718
- }
1719
- const mapBody = readArtifactFile(latestSliceMap.handle.path, cwd);
1720
- const records = sliceRecords(mapBody, "subplan-check", latestSliceMap.handle.path);
1721
- // PRE-FILTER expected clusters — the count the fanout RECEIVED, not the
1722
- // post-drop dispatched count. The fanout drops a zero-design cluster
1723
- // (`if (!designs.length) return undefined` in SYNTH_CLUSTER_FANOUT's units);
1724
- // design-review catches those upstream, so a healthy run lands here with
1725
- // pre-filter == dispatched — an invariant the missing-design preflight below
1726
- // enforces loudly rather than assumes.
1727
- const expectedK = expectedClusterCount(records);
1728
- const sliceNumbers = new Set(records.map((r) => r.n));
1729
-
1730
- // A slice with no design cannot be repaired by the backward edge: the fanout
1731
- // drops a zero-design cluster pre-dispatch, so every `subplan` re-dispatch
1732
- // reproduces the identical gap until maxBackwardJumps exhausts blaming the
1733
- // re-entry. Halt loud at the floor instead, naming the upstream cause.
1734
- const designBySlice = designPathsBySlice(state);
1735
- const undesigned = designCoverageGap(sliceNumbers, designBySlice);
1736
- if (undesigned.length > 0) {
1737
- throw haltPreflight(
1738
- "subplan-check",
1739
- `subplan-check: slice(s) ${undesigned.join(", ")} have no design on the 'designs' channel`,
1740
- `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.`,
1741
- );
1742
- }
1743
-
1744
- const { dispatched, tokenless } = dispatchedClusterOrdinals(state);
1745
- const findings: StructureFinding[] = [...tokenless];
1746
- findings.push(...clobberedOrdinals(dispatched));
1747
-
1748
- // Cluster-count conservation — distinct dispatched ordinals vs the pre-filter
1749
- // expected count. A clobber or a never-dispatched cluster both surface here.
1750
- const dispatchedK = new Set(dispatched.map((d) => d.k)).size;
1751
- if (dispatchedK < expectedK) {
1752
- findings.push({
1753
- 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).`,
1754
- where: `clusters (expected ${expectedK}, dispatched ${dispatchedK})`,
1755
- });
1756
- }
1757
-
1758
- findings.push(...sourcesCoverageGaps(state, cwd, sliceNumbers));
1759
-
1760
- return writeStructureVerdict("subplan-check", latestSliceMap.handle, findings, cwd);
1761
- };
1762
-
1763
- /**
1764
- * Slice a plan body into per-phase text keyed by phase number, splitting on
1765
- * `## Phase N:` headings OUTSIDE fenced code blocks (a heading inside a ``` or
1766
- * ~~~ fence is example/fixture text, not a structural phase boundary — mirrors
1767
- * `countHeadingsOutsideFences` so the slice and the derive-check agree). The
1768
- * body for phase N runs from its heading line up to (not including) the next
1769
- * out-of-fence `## Phase M:` heading, or end-of-text for the last phase.
1770
- * Returns a `Map<number, string>` (phase n → body text, heading included).
1771
- */
1772
- const phaseBodySlices = (content: string): Map<number, string> => {
1773
- const lineRe = new RegExp(PLAN_PHASE_RE.source); // drop g/m; per-line test, lastIndex can't drift
1774
- const lines = content.split("\n");
1775
- const openings: { n: number; start: number }[] = [];
1776
- forEachLineOutsideFences(content, (line, i) => {
1777
- const m = lineRe.exec(line);
1778
- if (m?.[1]) openings.push({ n: Number(m[1]), start: i });
1779
- });
1780
- const slices = new Map<number, string>();
1781
- for (let idx = 0; idx < openings.length; idx++) {
1782
- const end = idx + 1 < openings.length ? openings[idx + 1].start : lines.length;
1783
- slices.set(openings[idx].n, lines.slice(openings[idx].start, end).join("\n"));
1784
- }
1785
- return slices;
1786
- };
1787
-
1788
- /** Strip a trailing `:line` or `:line-line` citation suffix from a path token. */
1789
- const stripLineSuffix = (p: string): string => p.replace(/:\d+(?:-\d+)?$/, "");
1790
-
1791
- /** Well-known extensionless filenames — the extension heuristic below would drop
1792
- * them, so an undeclared write to one would silently escape the coverage floor.
1793
- * Recognized bare or as the basename of a path. */
1794
- const EXTENSIONLESS_FILENAME_RE =
1795
- /^(?:Makefile|Dockerfile|Rakefile|Gemfile|Justfile|Procfile|LICENSE|NOTICE|CODEOWNERS)$/;
1796
-
1797
- /** Path-like test mirroring slice-overlap.mjs's `looksLikePath`, applied AFTER
1798
- * stripping a `:line` suffix (the blueprint MODIFY heading — `#### N. path/to/file.ext`
1799
- * with a `:12-30` range appended — carries a line range the bare form rejects).
1800
- * Extensionless recognition is allowlist-only (never "any `/`-bearing token"):
1801
- * prose like `and/or` must not read as a declared write. The extension is
1802
- * bounded to 1–5 chars starting with a letter (mirroring FILE_LINE_CITATION_RE)
1803
- * so a dotted IDENTIFIER (`deps.finalize` — an observed false coverage
1804
- * finding) never reads as a file. */
1805
- const isPathLike = (s: string): boolean => {
1806
- if (/\s/.test(s)) return false;
1807
- if (EXTENSIONLESS_FILENAME_RE.test(s.slice(s.lastIndexOf("/") + 1))) return true;
1808
- return /\.[A-Za-z][A-Za-z0-9]{0,4}$/.test(s) && (s.includes("/") || /^[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}$/.test(s));
1809
- };
1810
-
1811
- /**
1812
- * Extract the edit paths a phase body names, across the three artifact
1813
- * conventions the plan/blueprint/synthesize skills emit, OUTSIDE fenced code
1814
- * blocks (a path inside a ``` fence is a code reference, not a declared write —
1815
- * post-`code-splice` safety, since code-splice folds elaborations' fenced code
1816
- * into the plan and those fenced paths must NOT read as phase writes):
1817
- * • `**File**:` / `**Files**:` — plan/blueprint's per-change file line
1818
- * (a backticked comma-list under `**Files**:`, or a single path under `**File**:`).
1819
- * • `#### N. path/to/file.ext` — blueprint's change subsection heading
1820
- * (may carry a `:line`-range suffix on MODIFY entries — stripped).
1821
- * • `- `path/to/file.ts`` — synthesize's backticked-path list item under
1822
- * `### Changes` (the form `elaborate`/`synthesize` emit).
1823
- * Strips a trailing `:line`/`:line-line` suffix. Mirrors slice-overlap.mjs's
1824
- * `filesOf` + `looksLikePath` and extends them with the synthesize list-item
1825
- * form. Returns a de-duplicated `string[]`.
1826
- */
1827
- const editPathsOfPhase = (phaseBody: string): string[] => {
1828
- const files = new Set<string>();
1829
- const add = (raw: string) => {
1830
- const stripped = stripLineSuffix(raw.replace(/[`*]/g, "").trim());
1831
- if (stripped && isPathLike(stripped)) files.add(stripped);
1832
- };
1833
- // The list-item form is scoped to a Changes section (`### Changes` heading or
1834
- // a `**Changes**:` field line): a backticked bullet elsewhere in the body is
1835
- // a REFERENCE ("mirror `x/state.ts`"), not a declared write — unscoped, those
1836
- // read as coverage gaps and block. Any other heading or `**Field**:` label
1837
- // exits the scope; `**File(s)**:` lines don't flip it (they're the path form
1838
- // themselves and legitimately precede `**Changes**:`).
1839
- let inChanges = false;
1840
- forEachLineOutsideFences(phaseBody, (line) => {
1841
- const heading = line.match(/^#{2,5}\s+(.*)$/);
1842
- if (heading) inChanges = /^changes\b/i.test(heading[1].trim());
1843
- const fm = line.match(/^\*\*Files?\*\*:\s*(.+)$/);
1844
- if (fm) {
1845
- for (const tok of fm[1].split(/[,\s]+/)) add(tok);
1846
- return;
1847
- }
1848
- const label = line.match(/^\*\*([A-Za-z][A-Za-z ]*)\*\*:/);
1849
- if (label?.[1]) inChanges = /^changes$/i.test(label[1].trim());
1850
- const hm = line.match(/^#{3,4}\s+\d+\.\s+(\S+)/);
1851
- if (hm) {
1852
- add(hm[1]);
1853
- return;
1854
- }
1855
- const lm = line.match(/^-\s+`([^`]+)`/);
1856
- if (lm && inChanges) add(lm[1]);
1857
- });
1858
- return [...files];
1859
- };
1860
-
1861
- /**
1862
- * Deterministic plan-time coverage floor: every edit path a phase body NAMES
1863
- * (in `### Changes`/`#### N. path`/`**File**:`) must be DECLARED in that phase's
1864
- * frontmatter `files:` array. An undeclared write is the per-phase attribution
1865
- * gap the dep-gated implement fanout and the lane-level scope floor both need
1866
- * closed upstream — a body edit not in `files:` is invisible to dependency
1867
- * derivation and unattributable under concurrency. PURE: no LLM judgment, never
1868
- * throws (a malformed frontmatter degrades to `[]`). A `files:`-LESS phase
1869
- * (absent key) yields NO findings — empty-set degradation so a legacy/
1870
- * `files:`-less plan never false-fails; a phase that declares `files: []` is
1871
- * checked (every body edit is a gap). Folded into `planCitationCheck(who)` so
1872
- * both the `plan-cite-check` and `code-cite-check` arms emit coverage findings
1873
- * on their shared `dimension: "structure"` verdict — no new stage/channel/route.
1874
- */
1875
- const verifyPhaseFilesCoverage = (content: string, who: string, path: string): { detail: string; where: string }[] => {
1876
- let fm: Record<string, unknown>;
1877
- try {
1878
- const { frontmatter } = parseFrontmatter(content);
1879
- fm = frontmatter as Record<string, unknown>;
1880
- } catch {
1881
- return []; // malformed frontmatter → degrade to no findings, never throw
1882
- }
1883
- const phases = Array.isArray(fm.phases) ? fm.phases : [];
1884
- const entryByN = new Map<number, Record<string, unknown>>();
1885
- phases.forEach((entry, idx) => {
1886
- const e = (entry ?? {}) as Record<string, unknown>;
1887
- const n = typeof e.n === "number" ? e.n : idx + 1;
1888
- entryByN.set(n, e);
1889
- });
1890
- const findings: { detail: string; where: string }[] = [];
1891
- for (const [n, body] of phaseBodySlices(content)) {
1892
- const entry = entryByN.get(n);
1893
- if (!entry) continue; // body phase with no matching frontmatter entry — derive-check's concern, not coverage's
1894
- // `files:` key ABSENT → degradation (legacy plan): skip. Present (even `[]`) → check.
1895
- if (!Array.isArray(entry.files)) continue;
1896
- const declared = new Set(phaseFiles(entry));
1897
- for (const editPath of editPathsOfPhase(body)) {
1898
- if (declared.has(editPath)) continue;
1899
- // Whole-segment suffix tolerance: a body form citing the file by bare
1900
- // basename or partial path (`#### 2. config.ts` for a declared
1901
- // `packages/x/config.ts`) is covered by the declaration — exact-match
1902
- // only was fixable solely by polluting `files:` with the bare name,
1903
- // corrupting the very dep derivation this floor protects.
1904
- if ([...declared].some((d) => `/${d}`.endsWith(`/${editPath}`) || `/${editPath}`.endsWith(`/${d}`))) continue;
1905
- findings.push({
1906
- 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.`,
1907
- where: `${who} ${path} phase ${n}: ${editPath}`,
1908
- });
1909
- }
1910
- }
1911
- return findings;
1912
- };
1913
-
1914
- /**
1915
- * The union of every phase's declared `files:` across the plan's frontmatter —
1916
- * the disambiguation pool `planCitationCheck` hands `verifyCitations`. A plan's
1917
- * write-set is the one place the plan itself names its files repo-root-relative
1918
- * (the coverage floor enforces exactly that), so it is a deterministic
1919
- * tiebreaker for the ambiguous-suffix findings that would otherwise STOP a
1920
- * loop-less preset (ship) over a bare `messages.ts:18` whose owning file the
1921
- * plan already declares. Degrades to the empty set on malformed frontmatter —
1922
- * never throws out of the deterministic floor.
1923
- */
1924
- const declaredPlanFiles = (content: string): ReadonlySet<string> => {
1925
- let fm: Record<string, unknown>;
1926
- try {
1927
- fm = parseFrontmatter(content).frontmatter as Record<string, unknown>;
1928
- } catch {
1929
- return new Set();
1930
- }
1931
- const phases = Array.isArray(fm.phases) ? fm.phases : [];
1932
- const declared = new Set<string>();
1933
- for (const entry of phases) for (const f of phaseFiles(entry)) declared.add(f);
1934
- return declared;
1935
- };
1936
-
1937
- /**
1938
- * Deterministic citation floor for a synthesized/spliced plan — the plan-scope
1939
- * twin of `sliceStructureCheck`'s citation backing, extending the citation
1940
- * floor past the slice map to the plan and the code-bearing plan (a fabricated `file:line` in
1941
- * the plan misdirects `implement`). Verifies every
1942
- * citation resolves against the working tree and emits a `{ dimension:
1943
- * "structure" }` verdict on `who`'s channel that the gate route folds via
1944
- * `allDimensionsPass`; the matching `<fix>` stage reads `fanin(who)` so the
1945
- * findings DRIVE the amend rather than blind-halt. Reuses `verifyCitations` — no
1946
- * fuzzy wrong-symbol heuristic — threading the plan's declared `files:` union so
1947
- * an ambiguous suffix citation resolves when exactly one candidate is in the
1948
- * plan's own write-set. Basename-keyed ⇒ idempotent across fix rounds.
1949
- */
1950
- const planCitationCheck =
1951
- (who: string) =>
1952
- ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1953
- const latest = latestFsArtifact(state, "plans");
1954
- if (latest?.handle.kind !== "fs") {
1955
- throw haltPreflight(
1956
- who,
1957
- `${who}: no plan to check`,
1958
- `${who}: no fs artifact on the 'plans' channel — the plan must be produced before the citation check`,
1959
- );
1960
- }
1961
- const body = readArtifactFile(latest.handle.path, cwd);
1962
- const findings = verifyCitations(body, cwd, declaredPlanFiles(body));
1963
- // Plan-time coverage floor: a body edit not declared in its phase's `files:`
1964
- // fails structurally, same channel/verdict/route as an unbacked citation.
1965
- findings.push(...verifyPhaseFilesCoverage(body, who, latest.handle.path));
1966
- return writeStructureVerdict(who, latest.handle, findings, cwd);
1967
- };
1968
-
1969
- /**
1970
- * Copy the latest graded plan off `plans` into `.rpiv/artifacts/priors/`
1971
- * basename-keyed, publishing the bytes on the snapshot stage's OWN channel with
1972
- * role `prior` — one deterministic hop BEFORE the matching fix stage inside the
1973
- * existing fix loop (plan-grade/plan-confirm → plan-snapshot → plan-fix; code
1974
- * twin). Overwritten each fix round, so the prior always reflects the
1975
- * pre-CURRENT-fix content; the re-grade reads it via `latestPriorContent` to
1976
- * decide whether the amend was surgical. `who` attributes the halt when no plan
1977
- * is published. `kind: "artifact-md"` is the honest kind — the prior IS a copy
1978
- * of an artifact-md plan body (the kind plans carry under `rpivBucketOutcome`).
1979
- */
1980
- const snapshotLatestPlan =
1981
- (who: string) =>
1982
- ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1983
- const latest = latestFsArtifact(state, "plans");
1984
- if (latest?.handle.kind !== "fs") {
1985
- throw haltPreflight(
1986
- who,
1987
- `${who}: no plan to snapshot`,
1988
- `${who}: no fs artifact on the 'plans' channel — the plan must be graded before the snapshot stage`,
1989
- );
1990
- }
1991
- const src = isAbsolute(latest.handle.path) ? latest.handle.path : join(cwd, latest.handle.path);
1992
- const priorRel = join(PRIOR_DIR, basename(latest.handle.path));
1993
- mkdirSync(join(cwd, PRIOR_DIR), { recursive: true });
1994
- copyFileSync(src, join(cwd, priorRel));
1995
- return {
1996
- kind: "artifact-md",
1997
- artifacts: [{ handle: { kind: "fs", path: priorRel }, role: "prior" }],
1998
- data: { snapshot_of: handleToString(latest.handle) },
1999
- };
2000
- };
2001
-
2002
- /** Snapshot the graded plan before `plan-fix` amends it (plan gate). */
2003
- const planSnapshot = snapshotLatestPlan("plan-snapshot");
2004
- /** Snapshot the graded plan before `code-fix` amends it (code gate). */
2005
- const codeSnapshot = snapshotLatestPlan("code-snapshot");
2006
-
2007
- /**
2008
- * A duty demotion stamped onto a verdict's on-disk JSON — the legible record
2009
- * that a risk ruling the panel marked `pass: true` was demoted to effective-
2010
- * fail by the evidence or verify-at-implement duty. One entry per FAILING
2011
- * duty (a ruling authored as BOTH mechanics AND verify-at-implement can carry
2012
- * two). `reason` is decision-code-free prose (no run/phase ids, no absolute
2013
- * line numbers) naming the duty that failed, so disk readers (amend, confirm
2014
- * `--prior`) can tell a grader-side demotion from a genuine `pass: false`.
2015
- */
2016
- interface RiskDutyDemotion {
2017
- id: string;
2018
- duty: "evidence-format" | "procedure-owner";
2019
- reason: string;
2020
- }
2021
-
2022
- /**
2023
- * Materialize the duty demotion as legible on-disk data. After a grade round,
2024
- * each latest-per-dimension verdict whose `pass: true` rulings were demoted by
2025
- * the evidence or verify-at-implement duty gets a `risk_duty_demotions` array
2026
- * written onto its on-disk JSON IN PLACE — the one medium amend and confirm's
2027
- * `--prior` read. The verdict's own `pass` is NEVER flipped (every gate fold —
2028
- * `allRiskFlagsPass`/`dimensionsToRegrade`/`confirmDue` — consults
2029
- * `rulingEffectivePass` off in-memory `state.named`, which never re-reads the
2030
- * rewritten file, so gate outcomes are unchanged); the field is an additive,
2031
- * read-only signal for the disk readers.
2032
- *
2033
- * Modeled on `snapshotLatestPlan(who)` (a `ScriptFn` that side-effects AND
2034
- * returns an `Output`): it reads the PLAN-sourced duty triggers
2035
- * (`planAuthoredRisks`), iterates the EXACT verdict set amend keeps + confirm
2036
- * reads (`latestVerdictPerDimension(freshVerdicts(...))`), and rewrites each
2037
- * demoted verdict's fs handle in place. Writes ONLY when ≥1 demotion (a clean
2038
- * grade is a no-op — no needless reformat/mtime churn); each per-file
2039
- * read/parse/write is wrapped so a single unparseable/stale file is skipped
2040
- * (never halts the gate). Returns `{ demotions }` echoing `{dimension, id,
2041
- * duty, verdict}` for journal greppability. `channel` is the plan channel the
2042
- * risks + current artifact live on; `verdictChannel` is the grade's own
2043
- * verdict channel (plan-verdicts / code-verdicts).
2044
- */
2045
- const demoteDuties =
2046
- (who: string, channel: string, verdictChannel: string) =>
2047
- ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2048
- const risks = planAuthoredRisks(state, channel);
2049
- const current = latestArtifactPath(state, channel);
2050
- const demotions: { dimension: string; id: string; duty: RiskDutyDemotion["duty"]; verdict: string }[] = [];
2051
- for (const o of latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel] ?? [], current)).values()) {
2052
- const handle = o.artifacts.find((a) => a.handle.kind === "fs")?.handle;
2053
- if (handle?.kind !== "fs") continue;
2054
- const dimRaw = (o.data as { dimension?: unknown } | undefined)?.dimension;
2055
- const dimension = typeof dimRaw === "string" ? dimRaw : "";
2056
- const perFile: RiskDutyDemotion[] = [];
2057
- for (const r of verdictRiskRulings(o)) {
2058
- const authored = risks.get(r.id);
2059
- // Only a `pass: true` ruling that rulingEffectivePass demotes — never a
2060
- // genuine `pass: false` (that is already a fail, not a demoted pass).
2061
- if (r.pass !== true || rulingEffectivePass(r, authored)) continue;
2062
- if (!evidenceCitesFileLine(r, authored)) {
2063
- perFile.push({
2064
- id: r.id,
2065
- duty: "evidence-format",
2066
- reason: "mechanics pass without an adjacent file:line citation in evidence",
2067
- });
2068
- demotions.push({ dimension, id: r.id, duty: "evidence-format", verdict: handleToString(handle) });
2069
- }
2070
- if (!procedureSatisfiesDuty(r, authored)) {
2071
- perFile.push({
2072
- id: r.id,
2073
- duty: "procedure-owner",
2074
- reason: "verify-at-implement pass without a concrete procedure and owner phase",
2075
- });
2076
- demotions.push({ dimension, id: r.id, duty: "procedure-owner", verdict: handleToString(handle) });
2077
- }
2078
- }
2079
- if (perFile.length === 0) continue;
2080
- try {
2081
- const abs = isAbsolute(handle.path) ? handle.path : join(cwd, handle.path);
2082
- const json = JSON.parse(readFileSync(abs, "utf-8")) as Record<string, unknown>;
2083
- json.risk_duty_demotions = perFile;
2084
- writeFileSync(abs, JSON.stringify(json, null, 2));
2085
- } catch {
2086
- // skip-on-throw: an unparseable/stale verdict file never halts the gate.
2087
- }
2088
- }
2089
- return { kind: "json", artifacts: [], data: { demotions, stage: who } };
2090
- };
2091
-
2092
- /**
2093
- * Stamp duty demotions onto the graded plan's verdicts after `plan-grade`, one
2094
- * deterministic hop before the gate routes (plan-grade → plan-demote → route).
2095
- * The code lane re-grades `plans` on `code-verdicts` (mirroring `codeSnapshot`).
2096
- */
2097
- const planDemote = demoteDuties("plan-demote", "plans", "plan-verdicts");
2098
- const codeDemote = demoteDuties("code-demote", "plans", "code-verdicts");
2099
-
2100
- /**
2101
- * Deterministic lane-level scope floor — the structural backstop beneath the
2102
- * LLM quality gates. After build's `implement` lane runs (now dep-gated and, as
2103
- * of this phase's unpin, concurrent up to the host cap), this checks the working
2104
- * tree's dirty set against the plan's declared write-set (the union of every
2105
- * phase's `files:`, twin-expanded via `withTestTwins`): any dirty path the run
2106
- * wrote that is NOT in `declared`, NOT
2107
- * pre-existing at the run-start baseline, and NOT under a bookkeeping tree is a
2108
- * scope violation — a phase escaped the upstream write-scope discipline and
2109
- * rewrote the wider tree, corrupting (or about to corrupt) a concurrent
2110
- * sibling's in-flight edit. Fail ⇒ STOP (no fix arm): a scope violation is a
2111
- * plan-vs-tree drift the agent must reconcile manually, not an auto-fix loop.
2112
- *
2113
- * Reads the plan with the SAME inline shape `planCitationCheck(who)` uses —
2114
- * `latestFsArtifact(state,"plans")` + `readArtifactFile` + `planPhaseRecords` +
2115
- * Phase 1's `phaseFiles` — NOT Phase 2's `readPlanPhaseRecords(state,cwd,who)`,
2116
- * because this stage needs the plan HANDLE for the `artifact` field and the
2117
- * basename-keyed verdict path, which the `who`-attributed helper collapses. The
2118
- * baseline is the run-start snapshot on the `goal` channel (`goalBaselinePath`,
2119
- * the same reader `VALIDATE_GOAL_PROMPT` and `COMMIT_BASELINE_PROMPT` use); the
2120
- * dirty set is `git status --porcelain` (non-repo / git-missing ⇒ empty dirty ⇒
2121
- * pass — the lane degrades to unguarded rather than failing a non-repo run).
2122
- * Emits one `{ dimension: "scope" }` verdict, basename-keyed off the plan ⇒
2123
- * idempotent across the build loop.
2124
- *
2125
- * `data` carries BOTH a `pass` boolean AND a `verdict` enum ("pass" | "fail")
2126
- * that always agree (`verdict: pass ? "pass" : "fail"`). The route is the
2127
- * established `match("verdict", …)` gate idiom (mirrors `validate`'s own route:
2128
- * `match("verdict", { commit: "pass" }, …)` — no-match ⇒ STOP, the same fail
2129
- * behavior). It is deliberately NOT the `defineRoute`/`allDimensionsPass`
2130
- * pattern the citation floors use: `allDimensionsPass` applies a severity floor
2131
- * (pass === true || severity low/none), so a failing scope check rated low
2132
- * severity would silently pass the gate — the exact escape class the lane floor
2133
- * exists to catch. The `from` form suppresses the `READS_DATA` outputSchema lint,
2134
- * so no schema is declared on the script stage (matching `slice-check`/
2135
- * `plan-cite-check`).
2136
- */
2137
- const implementScopeCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2138
- const latest = latestFsArtifact(state, "plans");
2139
- if (latest?.handle.kind !== "fs") {
2140
- throw haltPreflight(
2141
- "implement-scope-check",
2142
- "implement-scope-check: no plan to scope-check",
2143
- "implement-scope-check: no fs artifact on the 'plans' channel — implement must run before the scope check",
2144
- );
2145
- }
2146
- const body = readArtifactFile(latest.handle.path, cwd);
2147
- const records = planPhaseRecords(body, "implement-scope-check", latest.handle.path);
2148
- // Declared write-set = union of every phase's `files:` (via `phaseFiles`),
2149
- // expanded with co-located test twins (`withTestTwins`) — a signature change
2150
- // in a declared file legitimately drags its twin's assertions along.
2151
- // A `files:`-less plan yields `[]` ⇒ `scopeExcess` returns `[]` ⇒ inert floor.
2152
- const declared = withTestTwins(records.flatMap((r) => phaseFiles(r.entry)));
2153
-
2154
- // Run-start baseline (goal channel, role "baseline") + current dirty set —
2155
- // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
2156
- const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
2157
- const dirty = gitDirtyPaths(cwd);
2158
-
2159
- const excess = scopeExcess(dirty, baseline, declared);
2160
- const findings = excess.map((path) => ({
2161
- 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.`,
2162
- where: path,
2163
- }));
2164
- const pass = findings.length === 0;
2165
- const data = {
2166
- dimension: "scope",
2167
- pass,
2168
- verdict: pass ? "pass" : "fail",
2169
- score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2170
- severity: pass ? "none" : "high",
2171
- artifact: handleToString(latest.handle),
2172
- findings,
2173
- feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2174
- };
2175
- // Basename-keyed, NOT round-stamped (unlike grade's timestamped slug): each
2176
- // fix-loop round overwrites the file. Deliberate — the route reads the
2177
- // accumulating channel, and on disk only the latest round's scope verdict
2178
- // matters; round-stamp here if a consumer ever needs the history.
2179
- const rel = join(VERDICT_DIR, `implement-scope-check__${basename(latest.handle.path, ".md")}.json`);
2180
- mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2181
- writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2182
- return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2183
- };
2184
-
2185
- /**
2186
- * vet's `implement-scope-check` — the loop-aware scope floor (twin of build's
2187
- * `implementScopeCheck` above). Deterministic (no LLM): the implement lane may
2188
- * write ONLY the paths a plan phase declares in its `files:` set; any other dirty
2189
- * path (not in the run-start baseline, not under `.rpiv/`/`thoughts/`) is excess
2190
- * and halts before `validate`.
2191
- *
2192
- * vet differs from build in ONE place: build's extra `plans` entries are
2193
- * superseding amendments (`plan-fix` re-publishes the whole plan) so build reads
2194
- * latest-only; vet's review-fix loop pushes a DISTINCT non-superseding fix plan
2195
- * per iteration (completing a `produces` stage APPENDS to its named slot, and
2196
- * backward jumps don't reset channels), so this function builds `declared` as the
2197
- * UNION of Phase 1's `phaseFiles` over the FULL `state.named.plans` history — a
2198
- * path a prior iteration's plan legitimately wrote is not excess against the
2199
- * latest plan. The latest plan's handle is used ONLY for the basename-keyed
2200
- * verdict path (idempotent across fix rounds) and the `artifact` field.
2201
- *
2202
- * Otherwise byte-for-byte `implementScopeCheck` above: the baseline via
2203
- * `goalBaselinePath` (satisfied now that vet has a `goal` stage), the dirty set
2204
- * via `git status --porcelain` with explicit `stdio`, the shared `scopeExcess`
2205
- * core + `parseGitStatusPaths`, and the `dimension:"scope"` verdict
2206
- * (carrying BOTH `pass` and `verdict` — the route is the `match("verdict", …)`
2207
- * gate idiom, NOT `allDimensionsPass`, so a fail always halts) written to
2208
- * `VERDICT_DIR`. Non-repo / git-missing ⇒ empty dirty ⇒ pass (never throws).
2209
- * Basename-keyed off the latest plan ⇒ idempotent across review-fix rounds.
2210
- */
2211
- const implementScopeCheckVet = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2212
- // Declared set = UNION of `phaseFiles` over EVERY non-failed plan on the channel.
2213
- // The fs-artifact filter skips failed/unfilled entries (an Output with no fs
2214
- // handle contributed no plan to read).
2215
- const { declared, latest } = unionDeclaredWriteSet(state.named.plans ?? [], cwd);
2216
- if (!latest) {
2217
- throw haltPreflight(
2218
- "implement-scope-check",
2219
- "implement-scope-check: no plan to check",
2220
- "implement-scope-check: no fs plan artifact on the 'plans' channel — blueprint/implement must run before the scope check",
2221
- );
2222
- }
2223
-
2224
- // Run-start baseline (goal channel, role "baseline") + current dirty set —
2225
- // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
2226
- const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
2227
- const dirty = gitDirtyPaths(cwd);
2228
-
2229
- // Shared core: subtract the run's bookkeeping dirs (`.rpiv/`,
2230
- // `thoughts/`) and the run-start baseline; empty-`declared` ⇒ `[]` (degradation
2231
- // ⇒ inert floor — a fully `files:`-less plan never false-fails). Twin-expanded
2232
- // like build's floor: a declared file carries its co-located test twin.
2233
- const excess = scopeExcess(dirty, baseline, withTestTwins([...declared]));
2234
- const findings = excess.map((p) => ({
2235
- 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.`,
2236
- where: p,
2237
- }));
2238
- const pass = findings.length === 0;
2239
- const data = {
2240
- dimension: "scope",
2241
- pass,
2242
- verdict: pass ? "pass" : "fail",
2243
- score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2244
- severity: pass ? "none" : "high",
2245
- artifact: handleToString(latest.handle),
2246
- findings,
2247
- feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2248
- };
2249
- // Basename-keyed, NOT round-stamped (unlike grade's timestamped slug): each
2250
- // fix-loop round overwrites the file. Deliberate — the route reads the
2251
- // accumulating channel, and on disk only the latest round's scope verdict
2252
- // matters; round-stamp here if a consumer ever needs the history.
2253
- const rel = join(VERDICT_DIR, `implement-scope-check__${basename(latest.handle.path, ".md")}.json`);
2254
- mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2255
- writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2256
- return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2257
- };
2258
-
2259
- /**
2260
- * One `#### Reconciliation` directive parsed from a plan body: a machine-applicable
2261
- * `find → replace` against a single test-expectation file. The implement lane records
2262
- * these in a phase's OWN section when a correct change invalidates a test that lives
2263
- * in a sibling phase's landed section (which the implementer may NOT edit); `reconcile`
2264
- * applies them write-restricted to `*.test.*` targets.
2265
- */
2266
- interface ReconciliationDirective {
2267
- /** Repo-root-relative test target (`*.test.*`). */
2268
- target: string;
2269
- /** Substring to find (replaced exactly once via `String.replace`). */
2270
- find: string;
2271
- /** Replacement string. */
2272
- replace: string;
2273
- }
2274
-
2275
- /** Directive grammar: `` - `<target>`: replace `<find>` → `<replace>` — <rationale> ``.
2276
- * The `→` (U+2192) separates find/replace; the em-dash `—` (U+2014) + rationale is
2277
- * optional. Find/replace carry no inner backticks. The two spans are intentionally
2278
- * asymmetric and MUST NOT be symmetrized: `find` is one-or-more `[^`]+` (an empty
2279
- * find has no anchored target and `String.replace("")` prepends the replacement on
2280
- * every run, so the parser rejects it at parse time), while `replace` is
2281
- * zero-or-more `[^`]*` (an empty replace is a legitimate deletion directive). */
2282
- const RECONCILE_DIRECTIVE_RE = /^-\s+`([^`]+)`\s*:\s*replace\s+`([^`]+)`\s*→\s*`([^`]*)`\s*(?:—\s+.*)?$/;
2283
- /** A directive ATTEMPT — `- `<target>`:` — that does not match the full grammar. Used
2284
- * to surface a malformed directive as a finding rather than silently dropping it. */
2285
- const RECONCILE_DIRECTIVE_ATTEMPT_RE = /^-\s+`[^`]+`\s*:/;
2286
-
2287
- /**
2288
- * Parse every `#### Reconciliation` directive from a plan body. Returns the
2289
- * well-formed directives AND the malformed attempts (lines that carry the
2290
- * `- `<target>`:` shape but not the full `replace … → …` grammar); `reconcile`
2291
- * turns each malformed attempt into a finding so a broken directive is visible,
2292
- * never silently dropped. Prose list items are ignored. Pure: no I/O, no throw.
2293
- * A section opens at a `#### Reconciliation` heading and closes at the next
2294
- * `#{1,4}` heading (so `### Success Criteria` / `## Phase N:` / a sibling
2295
- * `#### Automated Verification:` all end it).
2296
- */
2297
- const reconciliationRecords = (
2298
- body: string,
2299
- ): {
2300
- directives: ReconciliationDirective[];
2301
- malformed: string[];
2302
- } => {
2303
- const directives: ReconciliationDirective[] = [];
2304
- const malformed: string[] = [];
2305
- let inSection = false;
2306
- for (const raw of body.split("\n")) {
2307
- const line = raw.trimEnd();
2308
- if (/^####\s+Reconciliation\b/.test(line)) {
2309
- inSection = true;
2310
- continue;
2311
- }
2312
- // Any other heading ends the section (the open-heading branch above `continue`s,
2313
- // so this only fires for non-`#### Reconciliation` headings).
2314
- if (/^#{1,4}\s/.test(line)) {
2315
- inSection = false;
2316
- continue;
2317
- }
2318
- if (!inSection) continue;
2319
- const m = RECONCILE_DIRECTIVE_RE.exec(line);
2320
- if (m) {
2321
- directives.push({ target: m[1]!.trim(), find: m[2]!, replace: m[3]! });
2322
- } else if (RECONCILE_DIRECTIVE_ATTEMPT_RE.test(line)) {
2323
- malformed.push(line.trim());
2324
- }
2325
- }
2326
- return { directives, malformed };
2327
- };
2328
-
2329
- const isTestPath = (target: string): boolean => TEST_PATH_RE.test(target);
2330
-
2331
- /**
2332
- * Apply each `#### Reconciliation` directive, write-restricted to test-expectation
2333
- * files (`isTestPath` — reconcile writes ONLY test files; a non-test target is a
2334
- * finding, left untouched, fail-closed). A present `find` is replaced exactly
2335
- * once (`String.replace`, first match); an absent `find` whose `replace` is empty
2336
- * is the idempotent-re-run no-op for a deletion (find-absent is the deletion's
2337
- * success condition — the directive was already applied, no finding, no write); an
2338
- * absent `find` whose non-empty `replace` is ALSO absent is a finding (reconcile
2339
- * does not guess); an absent `find` whose non-empty `replace` is already present is
2340
- * the idempotent-re-run no-op for a substitution (a prior successful apply, no
2341
- * finding, no write). Paths resolve through `cwd` (`isAbsolute` short-circuit else
2342
- * `join(cwd, target)`). Fail-soft: a read/apply throw degrades to a finding naming
2343
- * the target, never a terminal throw. Returns findings in DIRECTIVE order and
2344
- * performs the side-effecting writes itself (`reconcile` spreads the return).
2345
- */
2346
- const applyReconciliationDirectives = (
2347
- directives: readonly ReconciliationDirective[],
2348
- cwd: string,
2349
- ): { detail: string; where: string }[] => {
2350
- const findings: { detail: string; where: string }[] = [];
2351
- // Apply directives, write-restricted to test-expectation files.
2352
- for (const d of directives) {
2353
- if (!isTestPath(d.target)) {
2354
- findings.push({
2355
- 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`,
2356
- where: d.target,
2357
- });
2358
- continue;
2359
- }
2360
- try {
2361
- const abs = isAbsolute(d.target) ? d.target : join(cwd, d.target);
2362
- const content = readFileSync(abs, "utf-8");
2363
- if (content.includes(d.find)) {
2364
- // `String.replace` with a string pattern replaces the FIRST match exactly once.
2365
- writeFileSync(abs, content.replace(d.find, d.replace), "utf-8");
2366
- } else if (d.replace !== "" && content.includes(d.replace)) {
2367
- // Idempotent re-run: the find is gone but the replacement is present ⇒ the
2368
- // directive was already applied (e.g. a vet review-fix loop re-running
2369
- // reconcile). Treated as satisfied — reconcile must not fail on its own
2370
- // prior successful apply.
2371
- } else if (d.replace === "") {
2372
- // Idempotent re-run of a deletion: the find is gone and the replacement is
2373
- // empty ⇒ find-absent is the deletion's success condition (a prior successful
2374
- // apply removed it). Treated as satisfied — reconcile must not fail on its
2375
- // own prior successful apply (e.g. a validate-fix loop re-running reconcile).
2376
- } else {
2377
- findings.push({
2378
- 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`,
2379
- where: d.target,
2380
- });
2381
- }
2382
- } catch (err) {
2383
- findings.push({
2384
- detail: `reconcile: could not apply directive to ${d.target} — ${err instanceof Error ? err.message : String(err)}`,
2385
- where: d.target,
2386
- });
2387
- }
2388
- }
2389
- return findings;
2390
- };
2391
-
2392
- /**
2393
- * Deterministic post-implement reconciliation — the coherence backstop the
2394
- * parallel implement lane needs. Sibling phases run concurrently in one tree;
2395
- * each phase's own `#### Automated Verification:` passed in isolation, but a
2396
- * phase's correct change can invalidate a test that lives in a SIBLING phase's
2397
- * landed section (which the implementer may not edit), and the combined tree can
2398
- * break in ways no single phase's checks surface. `reconcile` runs after the
2399
- * scope floor (which proved the write-set) and before `validate`:
2400
- *
2401
- * 1. reads the latest plan (`latestFsArtifact(state, "plans")` — latest-wins);
2402
- * 2. parses every `#### Reconciliation` directive — fail-soft (a malformed
2403
- * directive / unreadable plan degrades to a finding, never a terminal
2404
- * `FAIL_SCRIPT_THREW` halt — a `produces.script` that throws becomes one);
2405
- * 3. applies each directive write-restricted to test paths (`isTestPath`); a
2406
- * present `find` is replaced exactly once (`String.replace`); an absent `find`
2407
- * whose replacement is ALSO absent is a finding (reconcile does not guess);
2408
- * 4. appends a timestamped `### Reconciliation Log (<iso>)` under the plan's
2409
- * `## Synthesis Notes` (best-effort bookkeeping write — non-fatal);
2410
- * 5. emits one `{ dimension: "reconcile" }` verdict, basename-keyed off the plan
2411
- * ⇒ idempotent across fix rounds (the verdict file is overwritten each round).
2412
- *
2413
- * Reconcile deliberately does NOT re-execute the plan's `#### Automated
2414
- * Verification:` commands. That re-run (bare `execFileSync`, no shell, exit-0
2415
- * contract) was measured across the full run history at zero genuine catches and
2416
- * a 100% false-positive finding rate — stale cross-phase presence probes, agent-
2417
- * shell-only binaries (`rg`), prose greps — each halting a finished run at a
2418
- * fail route with no fix arm. The downstream `validate` stage runs the same AV
2419
- * commands as an agent, with a real shell and the judgment to tell a legitimate
2420
- * post-rename mismatch from actual plan-vs-tree drift.
2421
- *
2422
- * The route is the `match("verdict", …, { from: "reconcile" })` gate idiom — pass ⇒
2423
- * validate, fail/missing ⇒ STOP (no fallback), mirroring `implementScopeCheck`.
2424
- * Mirrors `implementScopeCheck`'s `ScriptContext` shape, basename-keyed verdict
2425
- * path, and `dimension`/`pass`/`verdict`/`score`/`severity` data shape. `reads:
2426
- * ["plans"]` only — reconcile consumes no run-start `goal` baseline (the scope
2427
- * floor already proved the write-set; reconcile's own writes are directive targets
2428
- * + the plan bookkeeping). The `from` form suppresses the READS_DATA outputSchema
2429
- * lint, so no schema is declared (matching `slice-check`/`plan-cite-check`/
2430
- * `implement-scope-check`).
2431
- */
2432
- const reconcile = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2433
- const latest = latestFsArtifact(state, "plans");
2434
- if (latest?.handle.kind !== "fs") {
2435
- throw haltPreflight(
2436
- "reconcile",
2437
- "reconcile: no plan to reconcile",
2438
- "reconcile: no fs artifact on the 'plans' channel — implement / scope-check must run before reconcile",
2439
- );
2440
- }
2441
- const planPath = latest.handle.path;
2442
- const planAbs = isAbsolute(planPath) ? planPath : join(cwd, planPath);
2443
- const findings: { detail: string; where: string }[] = [];
2444
-
2445
- // Fail-soft read + parse: an unreadable plan or malformed directive degrades
2446
- // to a finding, never a terminal throw. If the read fails there is nothing to
2447
- // apply.
2448
- let body = "";
2449
- let directives: ReconciliationDirective[] = [];
2450
- let malformed: string[] = [];
2451
- try {
2452
- body = readArtifactFile(planPath, cwd);
2453
- const parsed = reconciliationRecords(body);
2454
- directives = parsed.directives;
2455
- malformed = parsed.malformed;
2456
- } catch (err) {
2457
- findings.push({
2458
- detail: `reconcile: could not read or parse the plan ${planPath} — ${err instanceof Error ? err.message : String(err)}`,
2459
- where: planPath,
2460
- });
2461
- }
2462
- for (const m of malformed) {
2463
- findings.push({
2464
- detail: `reconcile: malformed Reconciliation directive — expected a line of the form: - \`<target>\`: replace \`<find>\` → \`<replace>\` (target/find/replace each backtick-wrapped) — ${m}`,
2465
- where: "reconciliation-directive",
2466
- });
2467
- }
2468
-
2469
- findings.push(...applyReconciliationDirectives(directives, cwd));
2470
-
2471
- // Best-effort bookkeeping: append a timestamped log under ## Synthesis Notes.
2472
- // Non-fatal — a write failure here is silent (the verdict below is the signal).
2473
- if (body) {
2474
- try {
2475
- const stamp = new Date().toISOString();
2476
- const verdict = findings.length === 0 ? "pass" : "fail";
2477
- const logBlock = `\n### Reconciliation Log (${stamp})\nApplied ${directives.length} directive(s); ${findings.length} finding(s); verdict: ${verdict}.\n`;
2478
- const heading = "## Synthesis Notes";
2479
- const idx = body.indexOf(heading);
2480
- let updated: string;
2481
- if (idx >= 0) {
2482
- const lineEnd = body.indexOf("\n", idx);
2483
- const at = lineEnd >= 0 ? lineEnd + 1 : body.length;
2484
- updated = body.slice(0, at) + logBlock + body.slice(at);
2485
- } else {
2486
- updated = `${body.replace(/\s+$/, "")}\n${logBlock}`;
2487
- }
2488
- writeFileSync(planAbs, updated, "utf-8");
2489
- } catch {
2490
- // bookkeeping — ignore
2491
- }
2492
- }
2493
-
2494
- const pass = findings.length === 0;
2495
- const data = {
2496
- dimension: "reconcile",
2497
- pass,
2498
- verdict: pass ? "pass" : "fail",
2499
- score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2500
- severity: pass ? "none" : "high",
2501
- artifact: handleToString(latest.handle),
2502
- findings,
2503
- feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2504
- };
2505
- // Basename-keyed off the latest plan ⇒ idempotent across fix rounds (mirrors
2506
- // implementScopeCheck / planCitationCheck, NOT round-stamped like grade).
2507
- const rel = join(VERDICT_DIR, `reconcile__${basename(planPath, ".md")}.json`);
2508
- mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2509
- writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2510
- return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2511
- };
2512
-
2513
- /** A design filename encodes its slice as `…slice-<N>…` — the design-fanout naming convention. */
2514
- const DESIGN_SLICE_RE = /slice-(\d+)/;
2515
-
2516
- /**
2517
- * Map slice number → its design artifact path, from the design fanout's published
2518
- * outputs. An identity resolver: it maps an ARTIFACT to a slice NUMBER. It FAILS
2519
- * LOUD only when identity is genuinely UNRESOLVABLE — a design filename that
2520
- * carries no `slice-<N>` token, where a positional `idx + 1` guess would scramble
2521
- * the cluster→design wiring and drop slices.
2522
- *
2523
- * A slice claimed by MORE THAN ONE output is NOT ambiguous: the `designs` channel
2524
- * legitimately accumulates several entries per slice — `slice-design` emits it,
2525
- * then `design-review` re-emits the accepted/edited design on the SAME channel
2526
- * (its documented "latest-wins, same paths" contract, so `subplan`/`synthesize`
2527
- * read the accepted docs). So the newest entry wins, deterministically — throwing
2528
- * on a duplicate would halt every normal run at `subplan`. (The resume re-dispatch
2529
- * that once left CONFLICTING designs on the channel is fixed at its source,
2530
- * so there is no corruption left to fail loud on here.)
2531
- */
2532
- const designPathsBySlice = (state: RunView): Map<number, string> => {
2533
- const bySlice = new Map<number, string>();
2534
- for (const out of state.named.designs ?? []) {
2535
- for (const a of out.artifacts) {
2536
- if (a.handle.kind !== "fs") continue;
2537
- const name = basename(a.handle.path);
2538
- const match = DESIGN_SLICE_RE.exec(name);
2539
- if (!match) {
2540
- throw haltPreflight(
2541
- "designPathsBySlice",
2542
- `designPathsBySlice: design ${name} has no slice number`,
2543
- `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`,
2544
- );
2545
- }
2546
- // Latest design per slice wins — the channel holds multiple entries per
2547
- // slice by design (design-review re-emits), and the newest is authoritative.
2548
- bySlice.set(Number(match[1]), handleToString(a.handle));
2549
- }
2550
- }
2551
- return bySlice;
2552
- };
2553
-
2554
- /**
2555
- * Fan `subplan` out over slice-DAG clusters. Each unit merges ONE cluster's
2556
- * per-slice designs into a sub-plan (`--as-subplan`), so no single pass holds
2557
- * every design — the context-bounding twin of the flat fan-in `synthesize`.
2558
- */
2559
- const SYNTH_CLUSTER_FANOUT = fanout({
2560
- source: "designs",
2561
- unit: { by: "slice-dag-cluster", pattern: "clusters" },
2562
- max: MAX_PHASES,
2563
- units: ({ state, cwd }) => {
2564
- const doc = latestFsArtifact(state, "slices");
2565
- if (doc?.handle.kind !== "fs") return [];
2566
- const records = sliceRecords(readArtifactFile(doc.handle.path, cwd), "SYNTH_CLUSTER_FANOUT", doc.handle.path);
2567
- const designBySlice = designPathsBySlice(state);
2568
- // Thread the research the slices rest on into every cluster's subplan pass,
2569
- // so cross-slice constraints and acceptance criteria reach synthesis DIRECTLY
2570
- // (not only via each design's refraction). `synthesize` accepts `--research`
2571
- // in partial mode; the flat `synthesize` fan-in already received it, but the
2572
- // hierarchical cluster fanout dropped it.
2573
- const research = latestFsArtifact(state, "research");
2574
- const researchFlag = research?.handle.kind === "fs" ? ` --research ${handleToString(research.handle)}` : "";
2575
- return clusterSliceDag(records)
2576
- .map((cluster, i) => {
2577
- const designs = cluster
2578
- .map((n) => designBySlice.get(n))
2579
- .filter((p): p is string => p !== undefined)
2580
- .map((p) => `--designs ${p}`);
2581
- if (!designs.length) return undefined;
2582
- return {
2583
- // Stamp each cluster's ordinal into its prompt so the partial-mode pass
2584
- // writes a distinct `_cluster-<k>.md` — a re-dispatched unit must never
2585
- // reuse a sibling's filename and clobber it. `<k>` matches `id: cluster-<k>`.
2586
- prompt: `${designs.join(" ")}${researchFlag} --cluster ${i + 1} --as-subplan`,
2587
- label: `cluster ${i + 1} (slices ${cluster.join(",")})`,
2588
- id: `cluster-${i + 1}`,
2589
- };
2590
- })
2591
- .filter((u): u is { prompt: string; label: string; id: string } => u !== undefined);
2592
- },
2593
- });
2594
-
2595
- /**
2596
- * The two dimensions the grade panels anchor against the verbatim brief.
2597
- * "Complete" and "correct" MEAN "against what the user asked" — without the
2598
- * goal, completeness grades the plan against the plan's own claims. The other
2599
- * dimensions (and the slice gate's `design-readiness`) deliberately stay
2600
- * goal-blind: fit/actionability/pattern-following judge the artifact against
2601
- * the codebase, and an ambient goal at those seams invites scope inflation.
2602
- */
2603
- const GOAL_DIMENSIONS: ReadonlySet<string> = new Set(["completeness", "correctness"]);
2604
-
2605
- // ---------------------------------------------------------------------------
2606
- // Adaptive gate scaling — tier, roster, verdict freshness.
2607
- // ---------------------------------------------------------------------------
2608
-
2609
- /** Latest `data` record published under `name` (undefined when absent/non-record). */
2610
- const latestChannelData = (state: RunView, name: string): Record<string, unknown> | undefined => {
2611
- const data = state.named[name]?.at(-1)?.data;
2612
- return data !== null && typeof data === "object" && !Array.isArray(data)
2613
- ? (data as Record<string, unknown>)
2614
- : undefined;
2615
- };
2616
-
2617
- /** A finite numeric field off the latest `data` on `name` (undefined otherwise). */
2618
- const channelNumber = (state: RunView, name: string, field: string): number | undefined => {
2619
- const v = latestChannelData(state, name)?.[field];
2620
- return typeof v === "number" && Number.isFinite(v) ? v : undefined;
2621
- };
2622
-
2623
- /** Repo-relative path of the latest fs artifact on `name` (undefined if none). */
2624
- const latestArtifactPath = (state: RunView, name: string): string | undefined => {
2625
- const a = latestFsArtifact(state, name);
2626
- return a?.handle.kind === "fs" ? handleToString(a.handle) : undefined;
2627
- };
2628
-
2629
- /**
2630
- * Gate scrutiny tier, derived ONLY from signals already replayed by the resume
2631
- * fold (the slices/plans channels' frontmatter data and the gate's own verdict
2632
- * severities) — deterministic by construction, so routes and fanout units that
2633
- * consult it stay resume-safe.
2634
- *
2635
- * `risks:` flags are deliberately NOT a tier signal: `synthesize` declares
2636
- * them routinely (observed: 1-phase plans shipping 2-3 flags), so counting
2637
- * them would push every small run out of the light tier. Risk flags are
2638
- * already force-ruled per dimension via `risk_rulings`, and a blocking
2639
- * verdict lifts the tier on its own (below).
2640
- *
2641
- * A missing signal never yields light, and verdict severities are read over
2642
- * the FULL channel history (a stale medium/high is still evidence of a risky
2643
- * run) — ambiguity always resolves toward more scrutiny.
2644
- */
2645
- type GateTier = "light" | "standard" | "strict";
2646
- const TIER_LIGHT_MAX_SLICES = 1;
2647
- const TIER_LIGHT_MAX_PHASES = 2;
2648
- const TIER_STRICT_MIN_SLICES = 5;
2649
- const TIER_STRICT_MIN_PHASES = 6;
2650
-
2651
- /**
2652
- * The dimensions a light-tier run still grades: correctness and completeness
2653
- * are the two whose failures ship real defects (and the two that anchor on the
2654
- * goal); fit/actionability/pattern-following are low-consequence on a
2655
- * one-slice, <=2-phase diff, and `validate` still runs at every tier.
2656
- */
2657
- const LIGHT_ROSTER: ReadonlySet<string> = new Set(["correctness", "completeness"]);
2658
-
2659
- const gateTier = (state: RunView, verdictChannel: string): GateTier => {
2660
- const slices = channelNumber(state, "slices", "slice_count");
2661
- const phases = channelNumber(state, "plans", "phase_count");
2662
- const severities = new Set<string>();
2663
- for (const o of state.named[verdictChannel] ?? []) {
2664
- const v = o.data as { severity?: unknown; findings?: unknown } | undefined;
2665
- const s = v?.severity;
2666
- // Anchor-nit clamp: an all-drift-nit verdict must not escalate the tier.
2667
- if (typeof s === "string") severities.add(anchorNitsOnly(v) ? "low" : s);
2668
- }
2669
- if (
2670
- (slices !== undefined && slices >= TIER_STRICT_MIN_SLICES) ||
2671
- (phases !== undefined && phases >= TIER_STRICT_MIN_PHASES) ||
2672
- severities.has("high")
2673
- ) {
2674
- return "strict";
2675
- }
2676
- if (
2677
- slices !== undefined &&
2678
- slices <= TIER_LIGHT_MAX_SLICES &&
2679
- phases !== undefined &&
2680
- phases <= TIER_LIGHT_MAX_PHASES &&
2681
- !severities.has("medium")
2682
- ) {
2683
- return "light";
2684
- }
2685
- return "standard";
2686
- };
2687
-
2688
- /**
2689
- * The subset of `dimensions` the tier actually grades. Never empty: a
2690
- * dimension list with no light-roster member (the slice gate's lone
2691
- * `design-readiness`) keeps its full list at every tier.
2692
- */
2693
- const gateRoster = (tier: GateTier, dimensions: readonly string[]): readonly string[] => {
2694
- if (tier !== "light") return dimensions;
2695
- const light = dimensions.filter((d) => LIGHT_ROSTER.has(d));
2696
- return light.length > 0 ? light : dimensions;
2697
- };
2698
-
2699
- /**
2700
- * Drop verdicts judged against an artifact the channel has since REPLACED. A
2701
- * grade verdict embeds the `artifact` path it judged; when a fix REGENERATES
2702
- * the artifact (`slice-fix` re-slices to a NEW file) a passing verdict on the
2703
- * old document must not carry forward to a document that was never judged —
2704
- * the carry-forward would otherwise let a regenerated slice map skip its
2705
- * design-readiness judgment entirely. An in-place `amend` keeps the path, so
2706
- * the plan-fix/code-fix carry-forward is unaffected. A verdict without an
2707
- * `artifact` field (older trails, the deterministic structure checks) is kept:
2708
- * matching is the compat default.
2709
- */
2710
- const freshVerdicts = (entries: readonly Output[] = [], currentArtifact?: string): readonly Output[] => {
2711
- if (!currentArtifact) return entries;
2712
- const current = basename(currentArtifact);
2713
- return entries.filter((o) => {
2714
- const a = (o.data as { artifact?: unknown } | undefined)?.artifact;
2715
- return typeof a !== "string" || a.length === 0 || basename(a) === current;
2716
- });
2717
- };
2718
-
2719
- /**
2720
- * Latest verdict per dimension off an accumulated verdict channel — the shared
2721
- * fold under `dimensionsToRegrade` (which dimensions still block) and the
2722
- * confirm panels' `--prior` threading (which verdict file the confirming
2723
- * grader must adjudicate).
2724
- */
2725
- const latestVerdictPerDimension = (entries: readonly Output[] = []): Map<string, Output> => {
2726
- const latest = new Map<string, Output>();
2727
- for (const o of entries) {
2728
- const dim = (o.data as { dimension?: unknown } | undefined)?.dimension;
2729
- if (typeof dim === "string") latest.set(dim, o);
2730
- }
2731
- return latest;
2732
- };
2733
-
2734
- /**
2735
- * Anchor-drift-nit phrasing, two tiers: only phrasings naming drift itself
2736
- * count standalone; the location shapes (off-by-N, "is at line N", "line N is
2737
- * the/a") also match REAL defects ("line 42 is a comment that falsely claims
2738
- * X", "the loop bound is off by one") and count ONLY alongside citing-context
2739
- * vocabulary — every observed drift nit has it, real-defect phrasings don't.
2740
- * Do NOT widen, and do NOT promote a location shape to standalone.
2741
- */
2742
- const ANCHOR_NIT_DRIFT_RE = /\bdrifted?\s+~?\d+\s+lines?\b|\bcitation (?:is )?drifted\b/i;
2743
- const ANCHOR_NIT_LOCATION_RE =
2744
- /\boff[- ]by[- ](?:one|two|three|\d+)\b|(?::\d+|\bline \d+) is (?:the|a)\b|\bis at line \d+\b/i;
2745
- const ANCHOR_NIT_CITE_CONTEXT_RE = /\bcit(?:es?|ed|ation)\b|\banchor/i;
2746
-
2747
- const isAnchorNitDetail = (detail: string): boolean =>
2748
- ANCHOR_NIT_DRIFT_RE.test(detail) || (ANCHOR_NIT_LOCATION_RE.test(detail) && ANCHOR_NIT_CITE_CONTEXT_RE.test(detail));
2749
-
2750
- /**
2751
- * TRUE when a verdict carries ≥1 finding and EVERY finding is an anchor-drift
2752
- * nit (`isAnchorNitDetail`). Such a verdict is severity-clamped to non-blocking
2753
- * at the gate fold regardless of the grader's own `severity` — line-number
2754
- * drift was measured at 34% of all grader findings with zero downstream harm,
2755
- * and a mis-rated all-nit `medium` verdict buys a full fix round + re-grade
2756
- * panel that repairs nothing. A verdict mixing a drift nit with ANY other
2757
- * finding is untouched — the other finding may be the real blocker.
2758
- */
2759
- const anchorNitsOnly = (v: { findings?: unknown } | undefined): boolean => {
2760
- const findings = Array.isArray(v?.findings) ? v.findings : [];
2761
- return (
2762
- findings.length > 0 &&
2763
- findings.every((f) => {
2764
- const detail = (f as { detail?: unknown } | undefined)?.detail;
2765
- return typeof detail === "string" && isAnchorNitDetail(detail);
2766
- })
2767
- );
2768
- };
2769
-
2770
- /**
2771
- * The subset of `dimensions` a re-grade must actually re-run, given the latest
2772
- * verdict per dimension accumulated so far. A dimension needs re-grading when it
2773
- * has NO prior verdict (first pass ⇒ grade every dimension), when its latest
2774
- * verdict fails above the severity floor, or when that verdict ruled any plan
2775
- * risk flag `fail` (the ruling is re-opened by re-grading its owning dimension).
2776
- * A dimension that already passed — dimension AND its risk rulings — is carried
2777
- * forward untouched: re-running it after a surgical fix only re-rolls a free LLM
2778
- * judgment that flaps pass↔fail on an unchanged artifact, manufacturing extra
2779
- * loops (the observed correctness risk-flag flap). The accumulating verdict
2780
- * channel + `allDimensionsPass`'s latest-per-dimension fold mean a carried
2781
- * dimension's prior passing verdict still counts at the gate.
2782
- */
2783
- const dimensionsToRegrade = (
2784
- dimensions: readonly string[],
2785
- latest: ReadonlyMap<string, Output>,
2786
- risks: ReadonlyMap<string, RiskRecord> = new Map(),
2787
- ): string[] => {
2788
- return dimensions.filter((d) => {
2789
- const o = latest.get(d);
2790
- if (!o) return true; // never graded — must grade at least once
2791
- const v = o.data as { pass?: boolean; severity?: string; findings?: unknown } | undefined;
2792
- const dimPass = v?.pass === true || v?.severity === "low" || v?.severity === "none" || anchorNitsOnly(v);
2793
- if (!dimPass) return true;
2794
- return verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
2795
- });
2796
- };
2797
-
2798
- /**
2799
- * Coarse line-count backstop for the surgical-fix guard. The subset test
2800
- * (`touchedSections − HOUSEKEEPING ⊆ cited`) is the binding constraint — do
2801
- * NOT tighten this to compensate for a weak subset test.
2802
- */
2803
- const NON_SURGICAL_DIFF_LINE_THRESHOLD = 60;
2804
-
2805
- /**
2806
- * Plan sections amend ALWAYS bumps without the fix touching their meaning —
2807
- * the pseudo-section `frontmatter` (via the `last_updated` field). Exempt from
2808
- * the "touched outside cited" test. Starts at `{frontmatter}` only; do not
2809
- * pre-widen (a genuinely-meaningful bookkeeping section would let a broad amend
2810
- * pass the subset test by touching it).
2811
- */
2812
- const HOUSEKEEPING_SECTIONS: ReadonlySet<string> = new Set(["frontmatter"]);
2813
-
2814
- /** Directory the snapshot stages copy the pre-fix plan into (basename-keyed). */
2815
- const PRIOR_DIR = ".rpiv/artifacts/priors";
2816
-
2817
- /**
2818
- * Map each line index to its plan-section name: the nearest preceding `## `
2819
- * heading — `## Phase N: …` normalizes to `phase N` (case-insensitive); any
2820
- * other heading is lowercased by tail — so touched-section keys and cited-section
2821
- * keys share one space. The frontmatter block (opening `---` through its closing
2822
- * `---`) is the pseudo-section `frontmatter`. Lines before the first heading and
2823
- * outside frontmatter map to `""` (which is neither housekeeping nor a `phase N`
2824
- * cite, so any change there is treated as out-of-scope).
2825
- */
2826
- const sectionIndexOf = (lines: readonly string[]): string[] => {
2827
- const idx = new Array<string>(lines.length);
2828
- let current = "";
2829
- let inFrontmatter = lines[0]?.trim() === "---";
2830
- for (let i = 0; i < lines.length; i++) {
2831
- if (inFrontmatter) {
2832
- idx[i] = "frontmatter";
2833
- if (i > 0 && lines[i].trim() === "---") inFrontmatter = false;
2834
- continue;
2835
- }
2836
- const m = /^##\s+(.*)$/.exec(lines[i]);
2837
- if (m) {
2838
- const ph = /^Phase\s+(\d+)/i.exec(m[1].trim());
2839
- current = ph ? `phase ${ph[1]}` : m[1].trim().toLowerCase();
2840
- }
2841
- idx[i] = current;
2842
- }
2843
- return idx;
2844
- };
2845
-
2846
- /**
2847
- * Line-level diff of `prior` vs `current` plan bodies, mapped to plan sections.
2848
- * Each changed line (a deletion from `prior` OR an insertion in `current` under
2849
- * an LCS match) is attributed to its nearest preceding `## ` heading in its own
2850
- * document. Returns the union of touched section keys and a coarse changed-line
2851
- * count (deletions + insertions). Insertion-tolerant: a 1-line insert does not
2852
- * mark every trailing line changed (the LCS keeps shared context matched).
2853
- */
2854
- const sectionDiff = (prior: string, current: string): { touchedSections: Set<string>; changedLines: number } => {
2855
- const a = prior.split("\n");
2856
- const b = current.split("\n");
2857
- const sa = sectionIndexOf(a);
2858
- const sb = sectionIndexOf(b);
2859
- // LCS length table (bottom-up). Plans are a few hundred lines ⇒ O(n·m) trivial.
2860
- const dp: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
2861
- for (let i = a.length - 1; i >= 0; i--) {
2862
- for (let j = b.length - 1; j >= 0; j--) {
2863
- dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
2864
- }
2865
- }
2866
- const touched = new Set<string>();
2867
- let changed = 0;
2868
- let i = 0;
2869
- let j = 0;
2870
- while (i < a.length && j < b.length) {
2871
- if (a[i] === b[j]) {
2872
- i++;
2873
- j++;
2874
- } else if (dp[i + 1][j] >= dp[i][j + 1]) {
2875
- touched.add(sa[i]); // a[i] deleted (present in prior, absent in current)
2876
- changed++;
2877
- i++;
2878
- } else {
2879
- touched.add(sb[j]); // b[j] inserted (present in current, absent in prior)
2880
- changed++;
2881
- j++;
2882
- }
2883
- }
2884
- while (i < a.length) {
2885
- touched.add(sa[i]);
2886
- changed++;
2887
- i++;
2888
- }
2889
- while (j < b.length) {
2890
- touched.add(sb[j]);
2891
- changed++;
2892
- j++;
2893
- }
2894
- return { touchedSections: touched, changedLines: changed };
2895
- };
2896
-
2897
- /**
2898
- * Plan sections cited by the FAILING dimensions' findings — extracted from each
2899
- * finding's `where` and `detail` (`Phase N` → `phase N`, lowercased). Preferred
2900
- * `where: "Phase 1 > lane-dock-editor.ts Edit 1"` → `phase 1`; a repo
2901
- * `path:line`-only `where` (and a detail with no `Phase N`) contributes NO plan
2902
- * section. Empty when no failing finding carries an extractable plan-section
2903
- * reference — fail-closed: the caller treats an empty cite set against any
2904
- * non-housekeeping touched section as out-of-scope (non-surgical).
2905
- */
2906
- const citedSections = (latest: ReadonlyMap<string, Output>, pending: readonly string[]): Set<string> => {
2907
- const cited = new Set<string>();
2908
- for (const d of pending) {
2909
- const findings = (latest.get(d)?.data as { findings?: unknown } | undefined)?.findings;
2910
- if (!Array.isArray(findings)) continue;
2911
- for (const f of findings) {
2912
- if (f == null || typeof f !== "object") continue;
2913
- const where = typeof (f as { where?: unknown }).where === "string" ? (f as { where: string }).where : "";
2914
- const detail = typeof (f as { detail?: unknown }).detail === "string" ? (f as { detail: string }).detail : "";
2915
- for (const text of [where, detail]) {
2916
- for (const m of text.matchAll(/Phase\s+(\d+)/gi)) cited.add(`phase ${m[1]}`);
2917
- }
2918
- }
2919
- }
2920
- return cited;
2921
- };
2922
-
2923
- /**
2924
- * The prior-role `fs` artifact the snapshot stage published on `priorChannel`
2925
- * (undefined when the channel carries no prior — round 1 / first re-grade).
2926
- * Existence of the ENTRY is distinct from readability of the sidecar: an entry
2927
- * that exists but cannot be read still counts as "prior present" so the caller
2928
- * fails closed to a FULL roster rather than silently carrying forward.
2929
- */
2930
- const priorArtifact = (state: RunView, priorChannel: string): Artifact | undefined => {
2931
- const entry = state.named[priorChannel]?.at(-1);
2932
- const prior = entry?.artifacts.find((a) => a.handle.kind === "fs" && a.role === "prior");
2933
- return prior?.handle.kind === "fs" ? prior : undefined;
2934
- };
2935
-
2936
- /**
2937
- * Read the prior sidecar's bytes off `priorChannel`. Returns `undefined` when
2938
- * the channel is empty, the prior artifact is not fs, OR the sidecar is
2939
- * unreadable — the caller treats `undefined` as fail-closed (non-surgical).
2940
- */
2941
- const latestPriorContent = (state: RunView, priorChannel: string, cwd: string): string | undefined => {
2942
- const prior = priorArtifact(state, priorChannel);
2943
- if (prior?.handle.kind !== "fs") return undefined;
2944
- try {
2945
- return readArtifactFile(prior.handle.path, cwd);
2946
- } catch {
2947
- return undefined;
2948
- }
2949
- };
97
+ // ===========================================================================
98
+ // polish — architecture-review → blueprint (iterate, per review phase) →
99
+ // implement → validate → code-review → (blueprint loop) | commit
100
+ // For a large architecture review that can't be planned in one pass:
101
+ // plan each review phase sequentially, each plan building on the
102
+ // ones before it, then implement/validate/review the lot.
103
+ // ===========================================================================
2950
104
 
2951
105
  /**
2952
- * True ONLY when a readable prior exists AND the current plan's diff from it
2953
- * touches ONLY sections a failing finding cited (minus housekeeping) AND the
2954
- * changed-line count is within the coarse threshold. Every missing signal — no
2955
- * prior, unreadable sidecar, unreadable current plan, a diff/parse throw, a
2956
- * touched section no failing finding cited, or an over-threshold diff —
2957
- * collapses to `false` (fail-closed ⇒ the caller re-grades the full roster
2958
- * when a prior is present, or carries forward when none is). `pending` is
2959
- * consumed as-is: whatever `dimensionsToRegrade` ruled still-blocking (after
2960
- * phase 3's `rulingEffectivePass` clause-3 rewrite) is the set this guard
2961
- * narrows on.
106
+ * Hand the single validate session EVERY plan from the latest blueprint pass
107
+ * (`latestPlans`). The runner's default rolling-primary — and a plain
108
+ * `reads: ["plans"]`, which only reads `.at(-1)` — would point validate at the
109
+ * LAST plan alone, leaving earlier phases unvalidated. A `prompt` stage owns
110
+ * its whole message, so the `/skill:validate` prefix is explicit.
2962
111
  */
2963
- const isSurgicalFix = (
2964
- state: RunView,
2965
- priorChannel: string,
2966
- cwd: string,
2967
- target: string,
2968
- latest: ReadonlyMap<string, Output>,
2969
- pending: readonly string[],
2970
- ): boolean => {
2971
- const prior = latestPriorContent(state, priorChannel, cwd);
2972
- if (prior === undefined) return false;
2973
- let current: string;
2974
- try {
2975
- current = readArtifactFile(target, cwd);
2976
- } catch {
2977
- return false;
2978
- }
2979
- let diff: { touchedSections: Set<string>; changedLines: number };
2980
- try {
2981
- diff = sectionDiff(prior, current);
2982
- } catch {
2983
- return false;
2984
- }
2985
- const cited = citedSections(latest, pending);
2986
- for (const section of diff.touchedSections) {
2987
- if (HOUSEKEEPING_SECTIONS.has(section)) continue;
2988
- if (!cited.has(section)) return false;
2989
- }
2990
- return diff.changedLines <= NON_SURGICAL_DIFF_LINE_THRESHOLD;
112
+ const VALIDATE_PLANS_PROMPT: PromptFn = ({ state, cwd }) => {
113
+ const paths = latestPlans(state, cwd)
114
+ .flatMap((o) => o.artifacts)
115
+ .filter((a) => a.handle.kind === "fs")
116
+ .map((a) => handleToString(a.handle));
117
+ return `/skill:validate ${paths.join(" ")}`;
2991
118
  };
2992
119
 
2993
- /**
2994
- * A grade panel: one `grade` session per dimension over the latest artifact on
2995
- * `channel`. Each unit's prompt is the `grade` skill's flags
2996
- * (`--dimension <d> --artifact <path>`); the per-dimension verdicts fold via
2997
- * `allDimensionsPass`. Shared by the slice gate (over `slices`) and the plan +
2998
- * code gates (over `plans`), each on its own `verdictChannel`.
2999
- *
3000
- * The panel grades the tier's ROSTER (`gateTier`/`gateRoster`), over verdicts
3001
- * still FRESH for the current artifact (`freshVerdicts`) — a light run grades
3002
- * two dimensions, a regenerated artifact re-grades from scratch. On a re-grade
3003
- * it emits ONLY the dimensions `dimensionsToRegrade` says still need it (the
3004
- * rest carry their prior passing verdict forward) — but never an EMPTY set: an
3005
- * empty `units()` return falls through to a single dimensionless `grade`
3006
- * dispatch, so when nothing needs re-grading we fall back to the full roster.
3007
- * The route into the stage already skips it entirely when the accumulated
3008
- * verdicts clear the gate (see `plan-cite-check`/`code-cite-check`/`slice-check`
3009
- * edges), so this fallback only fires in the degenerate case where a fix left the
3010
- * cite floor red while every dimension passed.
3011
- *
3012
- * `architecture-fit` is the one dimension `grade` requires a `--context` for: it
3013
- * grades the plan against the research the slices rest on. The build flow always
3014
- * front-loads a `research` stage, so we thread the latest `research` artifact in
3015
- * as `--context` for that dimension only; likewise the latest `goal` artifact
3016
- * threads in as `--goal` for the `GOAL_DIMENSIONS` only. Every other dimension
3017
- * (and the slice gate's `design-readiness`, which never grades fit or
3018
- * goal-completeness) gets the bare flags.
3019
- *
3020
- * A CONFIRM panel (`confirm: true`) additionally threads each still-blocking
3021
- * dimension's latest verdict in as `--prior`: the confirming grader must
3022
- * adjudicate the prior round's findings — uphold or refute each with cited
3023
- * evidence — instead of silently out-voting them (a blind second opinion once
3024
- * rationalized past a checkable fact and its pass overwrote a correct fail at
3025
- * the latest-per-dimension fold). Only PENDING dimensions get the flag: in the
3026
- * degenerate full-roster fallback a carried passing verdict has nothing to
3027
- * adjudicate, and a first grade has no prior at all.
3028
- */
3029
- const gradePanelFanout = (
3030
- channel: string,
3031
- dimensions: readonly string[],
3032
- verdictChannel: string,
3033
- { confirm = false, priorChannel }: { confirm?: boolean; priorChannel?: string } = {},
3034
- ) =>
3035
- fanout({
3036
- source: channel,
3037
- unit: { by: "dimension-list", pattern: "dimensions" },
3038
- max: dimensions.length,
3039
- units: ({ state, cwd }) => {
3040
- const doc = latestFsArtifact(state, channel);
3041
- if (doc?.handle.kind !== "fs") return [];
3042
- const target = handleToString(doc.handle);
3043
- const research = latestFsArtifact(state, "research");
3044
- const contextFlag = research?.handle.kind === "fs" ? ` --context ${handleToString(research.handle)}` : "";
3045
- const goal = latestFsArtifact(state, "goal");
3046
- const goalFlag = goal?.handle.kind === "fs" ? ` --goal ${handleToString(goal.handle)}` : "";
3047
- const roster = gateRoster(gateTier(state, verdictChannel), dimensions);
3048
- const latest = latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel], target));
3049
- const risks = planAuthoredRisks(state, channel);
3050
- const pending = dimensionsToRegrade(roster, latest, risks);
3051
- // Delta re-grade fallback guard (plan/code gates only — `priorChannel`
3052
- // is unset for the slice gate and both confirm panels). When the snapshot
3053
- // stage published a prior, compare it to the current plan: a SURGICAL
3054
- // amend (touched only sections a failing finding cited, ≤ threshold
3055
- // lines) re-grades only the still-pending dimensions; a NON-surgical
3056
- // amend (broad / out-of-scope / over-threshold / unreadable / unparseable)
3057
- // re-grades the FULL roster — a broad amend may have regressed a passing
3058
- // dimension the carry-forward would otherwise trust. With NO prior
3059
- // (round 1 / first re-grade) the carry-forward applies unchanged. See
3060
- // `isSurgicalFix` for the fail-closed contract.
3061
- const surgical =
3062
- !confirm && priorChannel !== undefined && isSurgicalFix(state, priorChannel, cwd, target, latest, pending);
3063
- const priorPresent = priorChannel !== undefined && priorArtifact(state, priorChannel) !== undefined;
3064
- const priorFlag = (d: string): string => {
3065
- if (!confirm || !pending.includes(d)) return "";
3066
- const handle = latest.get(d)?.artifacts.find((a) => a.handle.kind === "fs")?.handle;
3067
- return handle ? ` --prior ${handleToString(handle)}` : "";
3068
- };
3069
- const carryForward = pending.length > 0 ? pending : roster;
3070
- // A non-surgical result WITH a prior present re-grades the FULL roster;
3071
- // with NO prior the carry-forward applies (never an empty unit set —
3072
- // empty ⇒ single dimensionless grade fall-through).
3073
- const toGrade = surgical ? carryForward : priorPresent ? roster : carryForward;
3074
- return toGrade.map((d) => ({
3075
- prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}${priorFlag(d)}`,
3076
- label: d,
3077
- id: `${channel}-dim-${d}`,
3078
- }));
3079
- },
3080
- });
3081
-
3082
- const SLICE_DIMENSION_FANOUT = gradePanelFanout("slices", SLICE_DIMENSIONS, "slice-verdicts");
3083
- const PLAN_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts", {
3084
- priorChannel: "plan-snapshot",
3085
- });
3086
- // The post-splice code gate re-grades the SAME `plans` artifact on its own
3087
- // `code-verdicts` channel, so its carry-forward reads the code gate's verdicts,
3088
- // never the pre-elaborate plan gate's.
3089
- const CODE_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts", {
3090
- priorChannel: "code-snapshot",
3091
- });
3092
- // The confirm stages re-run the SAME panel machinery on the SAME verdict
3093
- // channel: with the failing dimensions the only ones pending, the panel emits
3094
- // exactly the blocking dimensions — one second judgment each, in confirm mode:
3095
- // each unit carries the blocking verdict as `--prior`, and the grade skill is
3096
- // contract-bound to rule on every prior finding (uphold, or refute with cited
3097
- // evidence) so a confirming pass records WHY the fail died instead of silently
3098
- // out-voting it at the latest-per-dimension fold.
3099
- // Distinct fanout instances (not aliases) so each stage owns its loop object.
3100
- const PLAN_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts", { confirm: true });
3101
- const CODE_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts", { confirm: true });
3102
-
3103
- /**
3104
- * Ship's grade panel — a bespoke `fanout({...})` mirroring `gradePanelFanout`'s
3105
- * body but binding the roster to `SHIP_DIMENSIONS` DIRECTLY (no
3106
- * `gateRoster(gateTier(...))` wrap) and dropping the confirm / `priorChannel`
3107
- * / surgical-fix machinery ship's single-pass grade does not carry. Kept: the
3108
- * `latestFsArtifact` guard (no plan → no units), the dimension-keyed
3109
- * `--context` (architecture-fit only, sourced from the front-loaded `research`
3110
- * artifact), the `--goal` flag for `GOAL_DIMENSIONS` (completeness/
3111
- * correctness), and the `freshVerdicts` / `latestVerdictPerDimension` /
3112
- * `dimensionsToRegrade` carry-forward so a re-grade emits only still-pending
3113
- * dimensions. Tier-independence is structural: the roster never shrinks, so a
3114
- * light run still grades `architecture-fit`. Ship-only addition: the
3115
- * correctness unit carries `--cite-check <verdict>` when the deterministic
3116
- * citation floor recorded findings — advisory by construction here, since a
3117
- * blocking finding STOPs at the cite gate before grade ever runs — so the
3118
- * grader adjudicates them rather than leaving them unread.
3119
- */
3120
- export const SHIP_DIMENSION_FANOUT = fanout({
3121
- source: "plans",
3122
- unit: { by: "dimension-list", pattern: "dimensions" },
3123
- max: SHIP_DIMENSIONS.length,
3124
- units: ({ state }) => {
3125
- const doc = latestFsArtifact(state, "plans");
3126
- if (doc?.handle.kind !== "fs") return [];
3127
- const target = handleToString(doc.handle);
3128
- const research = latestFsArtifact(state, "research");
3129
- const contextFlag = research?.handle.kind === "fs" ? ` --context ${handleToString(research.handle)}` : "";
3130
- const goal = latestFsArtifact(state, "goal");
3131
- const goalFlag = goal?.handle.kind === "fs" ? ` --goal ${handleToString(goal.handle)}` : "";
3132
- // The floor's findings (advisory by construction — see the fanout doc
3133
- // above) thread as `--cite-check`; no findings ⇒ no flag.
3134
- const cite = latestFsArtifact(state, "plan-cite-check");
3135
- const citeFindings = (state.named["plan-cite-check"]?.at(-1)?.data as { findings?: unknown[] } | undefined)
3136
- ?.findings;
3137
- const citeFlag =
3138
- cite?.handle.kind === "fs" && Array.isArray(citeFindings) && citeFindings.length > 0
3139
- ? ` --cite-check ${handleToString(cite.handle)}`
3140
- : "";
3141
- // Tier-independent roster: SHIP_DIMENSIONS verbatim — never gateRoster(gateTier(...)).
3142
- const roster = SHIP_DIMENSIONS;
3143
- const latest = latestVerdictPerDimension(freshVerdicts(state.named["ship-verdicts"], target));
3144
- const risks = planAuthoredRisks(state, "plans");
3145
- const pending = dimensionsToRegrade(roster, latest, risks);
3146
- const carryForward = pending.length > 0 ? pending : roster;
3147
- return carryForward.map((d) => ({
3148
- prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}${d === "correctness" ? citeFlag : ""}`,
3149
- label: d,
3150
- id: `plans-dim-${d}`,
3151
- }));
120
+ const polishWorkflow = defineWorkflow({
121
+ name: "polish",
122
+ description:
123
+ "Architecture-review-driven polish: review → per-phase blueprint (sequential, accumulating) → implement → validate → code-review → commit. Best when a large architecture review can't be planned in one pass and each phase's plan must build on the ones before it.",
124
+ start: "architecture-review",
125
+ stages: {
126
+ "architecture-review": produces(),
127
+ blueprint: produces({ loop: REVIEW_PHASE_ITERATE }),
128
+ implement: acts({ loop: IMPLEMENT_PLANS_FANOUT, reads: ["plans"] }),
129
+ validate: produces({ prompt: VALIDATE_PLANS_PROMPT }),
130
+ "code-review": produces(),
131
+ commit: acts({ outcome: gitCommitOutcome }),
132
+ },
133
+ edges: {
134
+ "architecture-review": "blueprint",
135
+ blueprint: "implement",
136
+ implement: "validate",
137
+ validate: "code-review",
138
+ // Backward edge: code-review → blueprint re-plans (implement needs a plan).
139
+ // The iterate stage re-runs over every review phase; bounded by the
140
+ // runner's default maxBackwardJumps (3 → up to 4 review iterations).
141
+ "code-review": gate("blockers_count", { blueprint: gt(0), commit: eq(0) }, "commit"),
142
+ commit: "stop",
3152
143
  },
3153
144
  });
3154
145
 
3155
- /**
3156
- * Fold the per-dimension verdicts into a gate decision: keep the latest verdict
3157
- * per dimension (verdicts accumulate across fix loops), require all-pass.
3158
- * Deterministic ⇒ resume-safe for a `readsData: false` route.
3159
- *
3160
- * Severity floor: a verdict whose worst finding is `low`/`none` never blocks the
3161
- * gate, even when the grader set `pass: false` on a nit. `grade` decides `pass`
3162
- * by a free judgment against a prose bar (independent of `severity`), so a
3163
- * marginal dimension can flip pass↔fail across rounds on an unchanged artifact —
3164
- * that flapping, ANDed over a 5-dimension panel, stalled the build gate loops
3165
- * until the backward-jump guard halted them. Flooring on severity reserves a hard
3166
- * fail for `medium`+ findings (the deterministic `slice-check` check emits
3167
- * `high` on a real structural break, so it still blocks). A verdict with no
3168
- * `severity` (an older or replayed grade) falls back to the raw `pass` boolean.
3169
- */
3170
- const allDimensionsPass = (entries: readonly Output[] = [], roster?: readonly string[]): boolean => {
3171
- // Roster-filtered when given: a verdict for a dimension outside the tier's
3172
- // roster (a wider earlier round, a shrunk re-slice) neither blocks nor passes
3173
- // a gate it no longer governs.
3174
- const member = roster ? new Set(roster) : undefined;
3175
- const latest = new Map<string, boolean>();
3176
- for (const o of entries) {
3177
- const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
3178
- if (typeof v?.dimension !== "string") continue;
3179
- if (member && !member.has(v.dimension)) continue;
3180
- // The anchor-nit clamp: an all-drift-nit verdict never blocks, whatever
3181
- // severity the grader typed (backstop for the citation-resolution rule).
3182
- const lowOrNone = v.severity === "low" || v.severity === "none" || anchorNitsOnly(v);
3183
- latest.set(v.dimension, v.pass === true || lowOrNone);
3184
- }
3185
- const verdicts = [...latest.values()];
3186
- return verdicts.length > 0 && verdicts.every(Boolean);
3187
- };
3188
-
3189
- /**
3190
- * One plan-authored risk flag ruled by a grade panel. The plan declares a
3191
- * `risks:` frontmatter array (`{ id, claim }`) — the structured, first-class
3192
- * channel that replaces the old prose-in-a-Notes-section flagging that graders
3193
- * were free to skip. Each grade verdict that engages a flag emits a ruling here.
3194
- */
3195
- interface RiskRuling {
3196
- id: string;
3197
- pass: boolean;
3198
- /**
3199
- * `mechanics` marks a risk whose `pass` asserts a verified mechanism (a
3200
- * behavior that holds because code was checked), so a passing ruling MUST
3201
- * cite the checked `file:line` in `evidence` — an un-evidenced mechanics
3202
- * pass demotes. Absent on
3203
- * an ordinary risk ⇒ no evidence duty.
3204
- */
3205
- claim_type?: string;
3206
- /** The `file:line`-shaped citation a mechanics pass must ground itself on. */
3207
- evidence?: string;
3208
- /**
3209
- * `verify-at-implement` marks a risk the panel defers: ruled `pass` ONLY when
3210
- * a concrete `procedure` + `owner` phase will re-check it at implement/validate
3211
- * time. Absent ⇒ the risk is judged in this panel, not deferred.
3212
- */
3213
- disposition?: string;
3214
- /** Named command/test the owner phase runs to discharge a deferred risk. */
3215
- procedure?: string;
3216
- /** The phase (`n`) that owns the deferred verify step. */
3217
- owner?: number;
3218
- }
3219
-
3220
- /** The `risk_rulings` a grade verdict emitted (empty when it ruled on none). */
3221
- const verdictRiskRulings = (o: Output): RiskRuling[] => {
3222
- const raw = (o.data as { risk_rulings?: unknown } | undefined)?.risk_rulings;
3223
- if (!Array.isArray(raw)) return [];
3224
- return raw.flatMap((e) => {
3225
- const r = (e ?? {}) as Record<string, unknown>;
3226
- if (typeof r.id !== "string") return [];
3227
- // Read the duty fields defensively (same typeof-guard idiom as id/pass):
3228
- // absent on an older/ordinary verdict ⇒ undefined ⇒ the duty helpers no-op.
3229
- const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
3230
- const evidence = typeof r.evidence === "string" ? r.evidence : undefined;
3231
- const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
3232
- const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
3233
- const owner = typeof r.owner === "number" ? r.owner : undefined;
3234
- return [
3235
- {
3236
- id: r.id,
3237
- pass: r.pass === true,
3238
- ...(claim_type !== undefined ? { claim_type } : {}),
3239
- ...(evidence !== undefined ? { evidence } : {}),
3240
- ...(disposition !== undefined ? { disposition } : {}),
3241
- ...(procedure !== undefined ? { procedure } : {}),
3242
- ...(owner !== undefined ? { owner } : {}),
3243
- },
3244
- ];
3245
- });
3246
- };
3247
-
3248
- /**
3249
- * A plan-authored risk flag — the duty shape `synthesize` declares in the plan
3250
- * frontmatter `risks:` array (`synthesize/SKILL.md:136`: `{ id, claim,
3251
- * claim_type?, disposition?, procedure?, owner? }`). The prose `claim` is grading
3252
- * copy, not a duty signal, so it is not carried here. `claim_type: "mechanics"`
3253
- * and `disposition: "verify-at-implement"` are the two duty TRIGGERS — sourced
3254
- * from the PLAN (not the ruling) so a panel cannot drop its discharge obligation
3255
- * by simply omitting the field from its ruling (the dropped-duty bypass).
3256
- */
3257
- interface RiskRecord {
3258
- id: string;
3259
- claim_type?: string;
3260
- disposition?: string;
3261
- procedure?: string;
3262
- owner?: number;
3263
- }
3264
-
3265
- /**
3266
- * Read the plan-authored risk flags off the latest record on `channel`, keyed
3267
- * by `id`. The duty triggers live HERE (the plan's `risks:` frontmatter), not on
3268
- * the grade panel's ruling, so a ruling that drops its discharge field cannot
3269
- * escape the duty the plan declared (a bare `{ id, pass }` ruling against a
3270
- * plan-authored `claim_type: "mechanics"` risk still demotes). Reads only
3271
- * `state.named[channel]` via `latestChannelData` — no `readFileSync`, no
3272
- * `cwd`, no throw — so the route's `readsData: false` / determinism /
3273
- * resume-safety contract holds and a resumed run re-evaluates identically.
3274
- * Degrades to an empty map (fail-open ⇒ no duty ⇒ plain ruling ⇒
3275
- * `rulingEffectivePass(r) === r.pass`) when `risks:` is absent/non-array/
3276
- * malformed, mirroring `latestChannelData`'s degrade-to-undefined contract.
3277
- */
3278
- const planAuthoredRisks = (state: RunView, channel: string): Map<string, RiskRecord> => {
3279
- const risks = latestChannelData(state, channel)?.risks;
3280
- const out = new Map<string, RiskRecord>();
3281
- if (!Array.isArray(risks)) return out;
3282
- for (const e of risks) {
3283
- const r = (e ?? {}) as Record<string, unknown>;
3284
- if (typeof r.id !== "string") continue;
3285
- const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
3286
- const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
3287
- const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
3288
- const owner = typeof r.owner === "number" ? r.owner : undefined;
3289
- const rec: RiskRecord = { id: r.id };
3290
- if (claim_type !== undefined) rec.claim_type = claim_type;
3291
- if (disposition !== undefined) rec.disposition = disposition;
3292
- if (procedure !== undefined) rec.procedure = procedure;
3293
- if (owner !== undefined) rec.owner = owner;
3294
- out.set(r.id, rec);
3295
- }
3296
- return out;
3297
- };
3298
-
3299
- /**
3300
- * A mechanics-pass ruling's evidence duty: when the plan AUTHORED a
3301
- * `claim_type: "mechanics"` risk for the ruling's id, a `pass` ruling MUST
3302
- * cite the checked `file:line` in `evidence` (forces engagement — a pass with
3303
- * no evidence is an unverified mechanism). The trigger is sourced from the
3304
- * plan-authored `RiskRecord`, NOT the ruling — so a panel cannot drop the
3305
- * evidence duty by omitting `claim_type` from its ruling (the dropped-duty
3306
- * bypass). Reuses `FILE_LINE_CITATION_RE` via `.match()` — NOT `.test()`: the
3307
- * regex carries the `/g` flag, so `.test()` is stateful across calls
3308
- * (`lastIndex` advances) and would
3309
- * intermittently miss a present citation. An id with no authored mechanics
3310
- * risk carries no evidence duty ⇒ returns `true`.
3311
- */
3312
- const evidenceCitesFileLine = (r: RiskRuling, authored?: RiskRecord): boolean => {
3313
- if (authored?.claim_type !== "mechanics") return true;
3314
- return typeof r.evidence === "string" && r.evidence.match(FILE_LINE_CITATION_RE) !== null;
3315
- };
3316
-
3317
- /**
3318
- * A deferred-risk's verify-at-implement duty: when the plan AUTHORED a
3319
- * `disposition: "verify-at-implement"` risk for the ruling's id, a `pass`
3320
- * ruling MUST carry a concrete `procedure` (the named command/test the owner
3321
- * phase runs) AND a numeric `owner` phase — a bare "verify later" with no
3322
- * procedure demotes. The trigger is sourced from the plan-authored
3323
- * `RiskRecord`, NOT the ruling (the dropped-duty bypass). An id with no
3324
- * authored verify-at-implement risk is judged in THIS panel, not deferred ⇒
3325
- * returns `true`.
3326
- */
3327
- const procedureSatisfiesDuty = (r: RiskRuling, authored?: RiskRecord): boolean => {
3328
- if (authored?.disposition !== "verify-at-implement") return true;
3329
- return typeof r.procedure === "string" && r.procedure.length > 0 && typeof r.owner === "number";
3330
- };
3331
-
3332
- /**
3333
- * The single gate-fold authority: a ruling is effective-pass iff it is a bare
3334
- * `pass` AND (when the plan authored a mechanics risk for its id) its evidence
3335
- * cites a `file:line` AND (when the plan authored a verify-at-implement risk
3336
- * for its id) its procedure+owner discharge the verify duty. `allRiskFlagsPass`,
3337
- * `dimensionsToRegrade` clause 3, and `confirmDue`'s `riskFail` ALL consult this
3338
- * — so the three risk folds agree on what "passing" means and a demoted
3339
- * mechanics/deferred pass blocks the gate AND re-opens its owning dimension
3340
- * AND counts as blocking for confirm (no incoherent re-grading). For a ruling
3341
- * whose id the plan authored no duty for (no mechanics/verify-at-implement
3342
- * risk, no `risks:` at all, or no matching id) every duty no-ops, so
3343
- * `rulingEffectivePass(r, authored) === r.pass` — prior behavior is preserved.
3344
- */
3345
- const rulingEffectivePass = (r: RiskRuling, authored?: RiskRecord): boolean =>
3346
- r.pass === true && evidenceCitesFileLine(r, authored) && procedureSatisfiesDuty(r, authored);
3347
-
3348
- /**
3349
- * Fold the grade panel's per-flag risk rulings into a gate decision: every
3350
- * plan-authored risk flag the panel ruled on must be ruled PASS (latest ruling
3351
- * per flag wins, mirroring `allDimensionsPass`). A flag ruled `fail` — the
3352
- * grader confirmed the risk is real and unaddressed — blocks the gate, so a
3353
- * self-flagged risk (e.g. an override-vs-env validation mismatch) can no longer
3354
- * ride a green conformance pass into commit. An empty panel (no flag engaged)
3355
- * imposes no constraint; the plan simply declared no risks.
3356
- */
3357
- const allRiskFlagsPass = (
3358
- entries: readonly Output[] = [],
3359
- risks: ReadonlyMap<string, RiskRecord> = new Map(),
3360
- ): boolean => {
3361
- const latest = new Map<string, boolean>();
3362
- for (const o of entries)
3363
- for (const r of verdictRiskRulings(o)) latest.set(r.id, rulingEffectivePass(r, risks.get(r.id)));
3364
- return [...latest.values()].every(Boolean);
3365
- };
3366
-
3367
- /**
3368
- * The three gates' pass predicates — the SINGLE authority each gate consults at
3369
- * BOTH of its seams. A gate is satisfied when its deterministic cite/structure
3370
- * floor is green AND every quality dimension passes (severity-floored) AND — for
3371
- * the plan/code gates — every plan-authored risk flag is ruled pass.
3372
- *
3373
- * Reading the identical predicate at the cite/structure-check edge (which SKIPS
3374
- * the re-grade straight to the next stage) and at the grade edge (which gates
3375
- * forward-vs-fix) makes the skip provably equivalent to "re-grade, then pass",
3376
- * minus the wasted panel: after a fix that only cleared the deterministic floor,
3377
- * the accumulated verdicts already clear the gate, so re-running the LLM panel
3378
- * would at best reproduce them and at worst flap a passing dimension into a
3379
- * spurious fix loop. On the FIRST pass the verdict channel is empty, so
3380
- * `allDimensionsPass` returns false and the edge correctly routes INTO the grade
3381
- * panel. Any regression a fix introduces is still caught downstream: the plan
3382
- * gate by the full first-time `code-grade`, the code gate by `validate`.
3383
- */
3384
- // Each predicate folds the verdicts still FRESH for the channel's current
3385
- // artifact, restricted to the tier's roster — the SAME projections the panel's
3386
- // `units()` uses, so "skip the re-grade" stays provably equivalent to
3387
- // "re-grade, then pass". The deterministic cite/structure channels fold
3388
- // unfiltered: they re-run every round and carry no tier.
3389
- // The latest structure verdict carries a `citeDischarged` stamp for the
3390
- // CURRENT slice map. After a fix for a `remedy: "cite"` fail, the failing
3391
- // design-readiness verdict is stale (the fix re-sliced to a NEW file) and the
3392
- // gate's lone dimension has no fresh verdict, so the verdict fold can never
3393
- // pass — yet the fix is deterministically verifiable: `sliceStructureCheck`
3394
- // stamps the map basename it verified (demanded seeds present + shape
3395
- // unchanged, see `citeRemedyDischarged`). Honoring the stamp only for the
3396
- // current map means it can never carry across a later re-slice.
3397
- const citeDischargeCoversCurrentMap = (state: RunView): boolean => {
3398
- const stamp = (state.named["slice-check"]?.at(-1)?.data as { citeDischarged?: unknown } | undefined)?.citeDischarged;
3399
- const current = latestArtifactPath(state, "slices");
3400
- return typeof stamp === "string" && current !== undefined && stamp === basename(current);
3401
- };
3402
- const sliceGatePasses = (state: RunView): boolean => {
3403
- const fresh = freshVerdicts(state.named["slice-verdicts"], latestArtifactPath(state, "slices"));
3404
- const roster = gateRoster(gateTier(state, "slice-verdicts"), SLICE_DIMENSIONS);
3405
- if (!allDimensionsPass(state.named["slice-check"])) return false;
3406
- return allDimensionsPass(fresh, roster) || citeDischargeCoversCurrentMap(state);
3407
- };
3408
- // The single authority the new `subplan-check` edge consults — the twin of
3409
- // `sliceGatePasses`, but carrying no LLM-verdict roster or risk flags: the
3410
- // `subplan-check` floor is the sole (deterministic) dimension on its channel.
3411
- const subplanGatePasses = (state: RunView): boolean => allDimensionsPass(state.named["subplan-check"]);
3412
- const planGatePasses = (state: RunView): boolean => {
3413
- const fresh = freshVerdicts(state.named["plan-verdicts"], latestArtifactPath(state, "plans"));
3414
- const roster = gateRoster(gateTier(state, "plan-verdicts"), PLAN_DIMENSIONS);
3415
- const risks = planAuthoredRisks(state, "plans");
3416
- return (
3417
- allDimensionsPass(state.named["plan-cite-check"]) &&
3418
- allDimensionsPass(fresh, roster) &&
3419
- allRiskFlagsPass(fresh, risks)
3420
- );
3421
- };
3422
- const codeGatePasses = (state: RunView): boolean => {
3423
- const fresh = freshVerdicts(state.named["code-verdicts"], latestArtifactPath(state, "plans"));
3424
- const roster = gateRoster(gateTier(state, "code-verdicts"), PLAN_DIMENSIONS);
3425
- const risks = planAuthoredRisks(state, "plans");
3426
- return (
3427
- allDimensionsPass(state.named["code-cite-check"]) &&
3428
- allDimensionsPass(fresh, roster) &&
3429
- allRiskFlagsPass(fresh, risks)
3430
- );
3431
- };
146
+ // ===========================================================================
147
+ // build — goal (verbatim-brief capture) → research → slice → slice-check
148
+ // (deterministic floor) → slice-grade (design-readiness, slice-fix loop)
149
+ // → slice-design (fanout) → design-review (one human checkpoint) →
150
+ // subplan (cluster fanout) → plan → plan-grade (plan-fix loop) →
151
+ // code (fanout) → code-splice → code-grade (code-fix loop) →
152
+ // implement → implement-scope-check → reconcile → validate → commit
153
+ // The sliced, panel-gated heavy path: capture the user's brief verbatim as the
154
+ // `goal` channel (the north star the judgment seams — the two grade panels'
155
+ // completeness/correctness dimensions and validate — anchor against), research
156
+ // the brief (so every slice
157
+ // rests on a real, cited footing and the plan gate can grade architecture-fit),
158
+ // decompose it into independent
159
+ // vertical slices, gate that breakdown BEFORE any design so each slice is
160
+ // chewable by one design-slice pass. The gate is two-phase: a DETERMINISTIC
161
+ // floor (`slice-check`) enforces dependency-cycle freedom and brief-coverage
162
+ // conservation (a slice-fix may redistribute the brief, never drop scope to pass),
163
+ // then ONE LLM `design-readiness` judgment reconciles the formerly-opposing
164
+ // split/merge forces. Then design every slice in parallel and pause at ONE
165
+ // consolidated human checkpoint (`design-review`) — the single fan-in seam where
166
+ // every design exists and nothing parallel runs — to accept or adjust the
167
+ // proposed interfaces/data types before synthesis. Then merge hierarchically
168
+ // (per-cluster sub-plans → one plan) so no pass holds every design, gate the
169
+ // plan on quality dimensions BEFORE any code, elaborate code per phase and
170
+ // splice it in, re-grade the code-bearing plan, then implement/validate/commit.
171
+ // ===========================================================================
3432
172
 
3433
173
  /**
3434
- * Ship's grade gate — the tier-independent fold over `SHIP_DIMENSIONS` reading
3435
- * the `ship-verdicts` channel. Satisfied when every ship dimension passes
3436
- * (severity-floored) AND every plan-authored risk flag is ruled pass. Unlike
3437
- * `planGatePasses`/`codeGatePasses` it folds NO deterministic cite channel —
3438
- * ship's `plan-cite-check` gate is routed at its own edge — and binds the
3439
- * roster to `SHIP_DIMENSIONS` verbatim (never `gateRoster(gateTier(...))`), so
3440
- * the gate consults the same fixed set the panel graded.
174
+ * `goal` displaces `research` as build's start stage, and ONLY the start stage
175
+ * receives `originalInput` as its skill arg (`stageEntryArgs` case 1) — a plain
176
+ * `produces()` research would silently receive the rolling primary (the goal
177
+ * FILE PATH) instead of the brief text. A prompt stage owns its whole message,
178
+ * so this rebuilds research's pre-goal dispatch byte-for-byte; the outcome
179
+ * deriver still wires the `research` bucket off the record key (the polish
180
+ * `validate` prompt-stage precedent).
3441
181
  */
3442
- export const shipGatePasses = (state: RunView): boolean => {
3443
- const fresh = freshVerdicts(state.named["ship-verdicts"], latestArtifactPath(state, "plans"));
3444
- const risks = planAuthoredRisks(state, "plans");
3445
- return allDimensionsPass(fresh, SHIP_DIMENSIONS) && allRiskFlagsPass(fresh, risks);
3446
- };
182
+ const RESEARCH_BRIEF_PROMPT: PromptFn = ({ state }) => `/skill:research ${state.originalInput}`;
3447
183
 
3448
184
  /**
3449
- * Confirm-before-block: a dimension's FIRST blocking verdict against the
3450
- * current artifact gets ONE independent second judgment before it buys a fix
3451
- * round. Single-judge verdicts observably flap (pass/score/severity disagree
3452
- * across rolls on a near-unchanged artifact), and a spurious block
3453
- * manufactures an entire grade→fix cycle. Routing to the confirm stage
3454
- * re-runs only the pending dimensions on the same verdict channel;
3455
- * latest-per-dimension wins, so a confirming pass clears the gate and a
3456
- * confirming fail routes to the fix with two agreeing judgments behind it. A
3457
- * blocker already judged twice for this artifact routes straight to the fix —
3458
- * confirmation is one extra opinion, not an unbounded re-roll.
3459
- *
3460
- * No tier guard is needed: a blocking verdict is medium+ by the severity
3461
- * floor, and a medium+ severity already lifts `gateTier` out of light — every
3462
- * run with a genuine blocker has confirm-level scrutiny by construction.
185
+ * ship's research front-load — a LEANER grounding than build's `/skill:research`
186
+ * pass. Bypasses the research skill and bounds the agent to at most TWO targeted
187
+ * `codebase-analyzer` dispatches (sequentially — never parallel, never
188
+ * `run_in_background`) to map only what a lightweight single-phase plan needs to
189
+ * be correct: entry points, the relevant module's shape, and the conventions the
190
+ * implement lane must match. The agent then `Write`s a grounding doc under
191
+ * `.rpiv/artifacts/research/`, where the research bucket collector harvests it —
192
+ * the grade panel's architecture-fit dimension threads it as `--context` exactly
193
+ * as build's research artifact does. A prompt stage (no skill), so the stage
194
+ * name `research` drives outcome derivation (research contract → `research`
195
+ * bucket), exactly as build's `RESEARCH_BRIEF_PROMPT` stage does — the prompt
196
+ * text, not dispatch, is what differs.
3463
197
  */
3464
- const confirmDue = (
3465
- state: RunView,
3466
- channel: string,
3467
- verdictChannel: string,
3468
- dimensions: readonly string[],
3469
- ): boolean => {
3470
- const roster = new Set(gateRoster(gateTier(state, verdictChannel), dimensions));
3471
- const fresh = freshVerdicts(state.named[verdictChannel], latestArtifactPath(state, channel));
3472
- const risks = planAuthoredRisks(state, channel);
3473
- const byDim = new Map<string, { blocking: boolean; count: number }>();
3474
- for (const o of fresh) {
3475
- const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
3476
- if (typeof v?.dimension !== "string" || !roster.has(v.dimension)) continue;
3477
- // anchorNitsOnly keeps this floor coherent with the other three
3478
- // severity-fold consumers (gateTier/dimensionsToRegrade/allDimensionsPass).
3479
- const floored = v.pass === true || v.severity === "low" || v.severity === "none" || anchorNitsOnly(v);
3480
- const riskFail = verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
3481
- byDim.set(v.dimension, {
3482
- blocking: !floored || riskFail,
3483
- count: (byDim.get(v.dimension)?.count ?? 0) + 1,
3484
- });
3485
- }
3486
- const blockers = [...byDim.values()].filter((e) => e.blocking);
3487
- return blockers.length > 0 && blockers.some((e) => e.count < 2);
3488
- };
198
+ const SHIP_RESEARCH_PROMPT: PromptFn = ({ state }) =>
199
+ [
200
+ "Ground this brief for a lightweight ship plan.",
201
+ "Do NOT dispatch /skill:research. Instead dispatch at most TWO targeted codebase-analyzer subagents (sequentially — never parallel, never run_in_background) to map only what a single-phase plan needs to be correct: entry points, the relevant module's shape, and the conventions the implement lane must match.",
202
+ "",
203
+ `Brief: ${state.originalInput}`,
204
+ "",
205
+ "Then Write a grounding doc under .rpiv/artifacts/research/ (timestamped filename) carrying the findings, and stop.",
206
+ ].join("\n");
3489
207
 
3490
208
  /**
3491
209
  * Verdict channels — grade writes JSON to `.rpiv/artifacts/verdicts/`, so these
@@ -3507,12 +225,6 @@ const planVerdictOutcome = verdictOutcome("plan-verdicts");
3507
225
  // slice-verdicts / plan-verdicts / code-verdicts parallel.
3508
226
  const codeVerdictOutcome = verdictOutcome("code-verdicts");
3509
227
 
3510
- // Ship's grade panel writes its verdicts to a DISTINCT channel (same
3511
- // directory, different artifact basenames) so they never mix with build's
3512
- // plan/code verdicts — named for the workflow, completing the slice-verdicts
3513
- // / plan-verdicts / code-verdicts / ship-verdicts parallel.
3514
- export const shipVerdictOutcome = verdictOutcome("ship-verdicts");
3515
-
3516
228
  /**
3517
229
  * Absolute path to rpiv-pi's bundled deterministic stitch script. Resolved off
3518
230
  * this module's own URL so it points inside the installed package at runtime
@@ -3527,48 +239,6 @@ const STITCH_SCRIPT = join(
3527
239
  "stitch-elaborations.mjs",
3528
240
  );
3529
241
 
3530
- /**
3531
- * Build's validate dispatch: the latest synthesized plan plus the goal and
3532
- * run-start-baseline flags. Sourcing the plan from the NAMED channel (not the
3533
- * rolling primary) is load-bearing: `code-grade` is a produces-fanout, so
3534
- * after the code gate the rolling primary is the LAST VERDICT JSON
3535
- * (`placeFanoutOutput` advances it per unit) and `implement` (acts) leaves it
3536
- * there — a plain `produces()` validate would receive a verdict path as its
3537
- * "plan". A prompt stage owns its whole message, so the `/skill:validate`
3538
- * prefix is explicit (polish precedent).
3539
- *
3540
- * `--baseline` threads the pre-existing-dirty snapshot `goal` captured at run
3541
- * start, so validate judges working-tree scope criteria ("only these files
3542
- * touched") against the RUN'S OWN delta instead of failing on dirt that was
3543
- * on disk before stage one — the same fence the commit dispatch applies. The
3544
- * path comes off the goal channel (this run's snapshot, replayed from the
3545
- * JSONL trail on resume), never a shared file another run could overwrite.
3546
- */
3547
- const VALIDATE_GOAL_PROMPT: PromptFn = ({ state }) => {
3548
- const parts = ["/skill:validate"];
3549
- const plan = latestFsArtifact(state, "plans");
3550
- if (plan?.handle.kind === "fs") parts.push(handleToString(plan.handle));
3551
- const goal = latestFsArtifact(state, "goal");
3552
- if (goal?.handle.kind === "fs") parts.push(`--goal ${handleToString(goal.handle)}`);
3553
- const baseline = goalBaselinePath(state);
3554
- if (baseline) parts.push(`--baseline ${baseline}`);
3555
- return parts.join(" ");
3556
- };
3557
-
3558
- /**
3559
- * Build's commit dispatch: thread the run-start baseline so the commit skill
3560
- * fences pre-existing dirt off the commit — `git-changes.mjs` takes the path
3561
- * as a flag, so there is no fixed rendezvous file for concurrent/repeat runs
3562
- * to clobber. Prompt-dispatched deliberately: the inherited rolling primary
3563
- * (the validation report path) was reaching the skill as a meaningless
3564
- * message-hint argument anyway; owning the message replaces that noise with
3565
- * the one flag the skill actually consumes.
3566
- */
3567
- const COMMIT_BASELINE_PROMPT: PromptFn = ({ state }) => {
3568
- const baseline = goalBaselinePath(state);
3569
- return baseline ? `/skill:commit --baseline ${baseline}` : "/skill:commit";
3570
- };
3571
-
3572
242
  // ===========================================================================
3573
243
  // vet — goal → code-review → (blueprint → implement → implement-scope-check
3574
244
  // → validate → loop) | commit. Examine existing changes; capture the
@@ -3580,6 +250,40 @@ const COMMIT_BASELINE_PROMPT: PromptFn = ({ state }) => {
3580
250
  // buildWorkflow follows (defined after its deps).
3581
251
  // ===========================================================================
3582
252
 
253
+ /**
254
+ * Scope-floor gate factory — build and vet wire IDENTICAL tiered routes; a
255
+ * factory (not one shared EdgeFn) so each workflow's route-note symbol never
256
+ * aliases the other's. Branches on the floor's tiered `ScopeVerdict`:
257
+ * "pass" AND tracked "excess" continue to `reconcile` — the floor demotes
258
+ * tracked excess to downstream adjudication (build threads the verdict to
259
+ * validate via `--scope`; vet's review loop sees the whole diff) instead of
260
+ * halting, the citation-floor precedent (demote where a remedy or adjudicator
261
+ * exists). "untracked-only" takes the deterministic `scope-quarantine` arm.
262
+ * Anything else — a missing or corrupt verdict — terminates ("stop" with a
263
+ * route note): the integrity clause every de-halting change has preserved.
264
+ * A `match` cannot send two enum values to one target, hence `defineRoute`;
265
+ * `readsData: false` — the route consults the stage's published channel, not
266
+ * its projected output (matching the other deterministic-floor routes).
267
+ */
268
+ const scopeFloorGate = (): EdgeFn => {
269
+ const route: EdgeFn = defineRoute(
270
+ ["reconcile", "scope-quarantine", "stop"],
271
+ ({ state }) => {
272
+ const verdict = (state.named["implement-scope-check"]?.at(-1)?.data as { verdict?: unknown } | undefined)
273
+ ?.verdict;
274
+ if (verdict === "untracked-only") return "scope-quarantine";
275
+ if (verdict === "pass" || verdict === "excess") return "reconcile";
276
+ setRouteNote(
277
+ route,
278
+ `implement-scope-check verdict ${JSON.stringify(verdict ?? null)} is not a ScopeVerdict — terminated (integrity stop)`,
279
+ );
280
+ return "stop";
281
+ },
282
+ { readsData: false },
283
+ );
284
+ return route;
285
+ };
286
+
3583
287
  const vetWorkflow = defineWorkflow({
3584
288
  name: "vet",
3585
289
  description:
@@ -3616,9 +320,14 @@ const vetWorkflow = defineWorkflow({
3616
320
  // non-superseding fix plans, so the declared set is the UNION over the full
3617
321
  // `plans` history — `implementScopeCheckVet`). The `from` form suppresses
3618
322
  // the READS_DATA outputSchema lint, so no schema is declared, matching
3619
- // `slice-check`/`plan-cite-check`. Pass → validate; fail/missing → STOP
3620
- // (no fallback), mirroring build's `validate → commit` route.
323
+ // `slice-check`/`plan-cite-check`. Tiered route (scopeFloorGate): pass and
324
+ // tracked excess → reconcile (the review loop adjudicates the recorded
325
+ // findings), untracked-only → scope-quarantine, missing verdict → STOP.
3621
326
  "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheckVet }),
327
+ // Deterministic remedy arm for the untracked-only tier: move (never
328
+ // delete) run-created untracked excess under .rpiv/tmp/scope-quarantine/
329
+ // and publish a manifest, then re-enter the floor — see scopeQuarantine.
330
+ "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
3622
331
  // Deterministic post-implement reconciliation (no LLM) — the SAME `reconcile`
3623
332
  // run-function as build (no vet twin): applies every `#### Reconciliation`
3624
333
  // directive (write-restricted to test files) + re-runs every per-phase
@@ -3640,10 +349,17 @@ const vetWorkflow = defineWorkflow({
3640
349
  // validate; fail/missing terminates (STOP, no fallback). Byte-for-byte
3641
350
  // build's route.
3642
351
  implement: "implement-scope-check",
3643
- // Scope-check still gates onward, but now into `reconcile` (not validate):
3644
- // the coherence backstop runs after the write-set is proven. Pass ⇒
3645
- // reconcile; fail/missing ⇒ STOP (no fallback).
3646
- "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
352
+ // Scope-check still gates onward into `reconcile` (not validate): the
353
+ // coherence backstop runs after the write-set is judged. Tiered route —
354
+ // see scopeFloorGate: pass/excess ⇒ reconcile, untracked-only ⇒ the
355
+ // quarantine arm, missing/corrupt verdict ⇒ STOP.
356
+ "implement-scope-check": scopeFloorGate(),
357
+ // Deterministic re-entry after the quarantine arm: a plain string edge
358
+ // (non-counted, mirroring build's validate-fix hop) with guaranteed
359
+ // progress — quarantined paths leave the dirty set, so the re-check
360
+ // either passes or reveals tracked drift. At most one quarantine hop per
361
+ // gate entry; no new loop budget.
362
+ "scope-quarantine": "implement-scope-check",
3647
363
  // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target /
3648
364
  // absent find / failed AV command) or a missing verdict ⇒ STOP (no fix arm —
3649
365
  // a reconciliation failure is plan-vs-tree drift the agent reconciles manually).
@@ -3658,6 +374,78 @@ const vetWorkflow = defineWorkflow({
3658
374
  },
3659
375
  });
3660
376
 
377
+ /**
378
+ * Build's validate gate — classifies a failing verdict BEFORE routing to the
379
+ * repair arm. `remediate`'s work-list is contractually the report's `pass:
380
+ * false` risk rulings plus its structured `blockers:` entries; a `verdict:
381
+ * fail` carrying NEITHER (run 2026-08-22_12-14-12-64eb: two whole-plan gate
382
+ * failures recorded only in report prose) has no handle the arm may act on,
383
+ * so routing it to `validate-fix` buys a provably futile lap — the arm
384
+ * drift-escapes without an edit and the unchanged tree re-validates to the
385
+ * identical verdict until the backward-jump guard halts the run. Such a fail
386
+ * now STOPs at the gate with a route note naming why (the ship-gate
387
+ * `setRouteNote` pattern; a noted decision stop records as a halt). The
388
+ * repair-arm authority rule the slice gate learned the same way: a gate may
389
+ * only loop into an arm whose authority covers the failure class.
390
+ *
391
+ * Reads the `validation` channel (validate's contract-derived publish bucket
392
+ * — a prompt stage owns its message and can't inherit its contract's output
393
+ * schema, so the gate folds the channel, never the raw stage output). A
394
+ * missing/unexpected verdict stays terminal STOP, exactly as the `match` it
395
+ * replaces — un-anticipated data can never route INTO commit OR the repair arm.
396
+ */
397
+ const validateGate: EdgeFn = defineRoute(
398
+ ["commit", "validate-fix", "stop"],
399
+ ({ state }) => {
400
+ const latest = state.named.validation?.at(-1);
401
+ const data = latest?.data as { verdict?: unknown; blockers?: unknown } | undefined;
402
+ if (data?.verdict === "pass") return "commit";
403
+ if (data?.verdict !== "fail") {
404
+ setRouteNote(
405
+ validateGate,
406
+ `validate verdict ${JSON.stringify(data?.verdict ?? null)} matched no branch — terminated (no fallback)`,
407
+ );
408
+ return "stop";
409
+ }
410
+ // Remediable handles: `pass: false` risk rulings (the arm's original
411
+ // work-list) + structured `blockers:` entries (whole-plan gate failures
412
+ // the validate skill attributes with a runnable command + in-delta file).
413
+ const failedRulings = latest ? verdictRiskRulings(latest).filter((r) => !r.pass).length : 0;
414
+ const blockers = Array.isArray(data.blockers) ? data.blockers.length : 0;
415
+ if (failedRulings + blockers > 0) return "validate-fix";
416
+ setRouteNote(
417
+ validateGate,
418
+ "validate failed with no remediable handle (no pass:false risk ruling, no blockers entry) — the remediation arm cannot act; fix manually or revise the plan",
419
+ );
420
+ return "stop";
421
+ },
422
+ { readsData: false },
423
+ );
424
+
425
+ /**
426
+ * Build's repair-arm progress gate — the deterministic no-op backstop. The
427
+ * `remediation` channel carries `remediationOutcome`'s `{ changed }` (a
428
+ * git-only tree digest snapshotted around the `validate-fix` stage): an
429
+ * unchanged tree makes the re-validate lap provably futile (validate's
430
+ * verdict is a function of the tree), so it STOPs with a note instead of
431
+ * burning a backward-jump on an identical verdict. Only an explicit
432
+ * `changed: false` stops — a missing signal (non-repo, git failure, absent
433
+ * channel) proceeds, the worktree-digest degrade doctrine.
434
+ */
435
+ const validateFixGate: EdgeFn = defineRoute(
436
+ ["implement-scope-check", "stop"],
437
+ ({ state }) => {
438
+ const data = state.named.remediation?.at(-1)?.data as { changed?: unknown } | undefined;
439
+ if (data?.changed !== false) return "implement-scope-check";
440
+ setRouteNote(
441
+ validateFixGate,
442
+ "remediation left the working tree unchanged — re-validating cannot change the verdict; fix manually or revise the plan",
443
+ );
444
+ return "stop";
445
+ },
446
+ { readsData: false },
447
+ );
448
+
3661
449
  const buildWorkflow = defineWorkflow({
3662
450
  name: "build",
3663
451
  description:
@@ -3847,12 +635,17 @@ const buildWorkflow = defineWorkflow({
3847
635
  // Lane-level scope floor — the structural backstop beneath the quality
3848
636
  // gates. After the (now concurrent) implement lane lands, judge the working
3849
637
  // tree's dirty set against the plan's declared write-set: any undeclared
3850
- // write is a phase that escaped the upstream write-scope discipline and
3851
- // raced on a sibling's in-flight edit. Fail ⇒ STOP (no fix arm). The `from`
3852
- // form suppresses the READS_DATA outputSchema lint, so no schema is declared
3853
- // (matching slice-check/plan-cite-check). Reads `goal` for the run-start
3854
- // baseline that subtracts pre-existing dirt.
638
+ // write is a phase that escaped the upstream write-scope discipline. Tiered
639
+ // route (scopeFloorGate): untracked-only excess ⇒ the deterministic
640
+ // quarantine arm; tracked excess ⇒ recorded and adjudicated by validate
641
+ // (threaded via --scope); missing verdict ⇒ STOP. No schema is declared
642
+ // (matching slice-check/plan-cite-check — the route reads the channel).
643
+ // Reads `goal` for the run-start baseline that subtracts pre-existing dirt.
3855
644
  "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheck }),
645
+ // Deterministic remedy arm for the untracked-only tier: move (never
646
+ // delete) run-created untracked excess under .rpiv/tmp/scope-quarantine/
647
+ // and publish a manifest, then re-enter the floor — see scopeQuarantine.
648
+ "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
3856
649
  // Deterministic post-implement reconciliation (no LLM): applies every
3857
650
  // `#### Reconciliation` directive (find→replace, write-restricted to test
3858
651
  // files) and re-runs every per-phase `#### Automated Verification:`
@@ -3864,15 +657,17 @@ const buildWorkflow = defineWorkflow({
3864
657
  // `from` form suppresses the READS_DATA outputSchema lint.
3865
658
  reconcile: produces.script({ reads: ["plans"], run: reconcile }),
3866
659
  validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
3867
- // Repair arm the validate gate dispatches on a `verdict: "fail"`. `acts()`
3868
- // (not `produces()`) because remediate is `side-effect`/`code-mutation` (the
3869
- // tools twin of `implement`: re-runs verification commands via `Bash(*)` and
3870
- // edits the working tree) — NOT produced-validating and NOT routed-on (its
3871
- // edge is deterministic), so it owns no outcome. `reads: ["plans","validation"]`
3872
- // ⇒ `stageEntryArgs` derives `--plans <plan> --validation <latest-report>`;
660
+ // Repair arm the validate gate dispatches on a remediable `verdict: "fail"`.
661
+ // `acts()` (not `produces()`) because remediate is `side-effect`/`code-mutation`
662
+ // (the tools twin of `implement`: re-runs verification commands via `Bash(*)`
663
+ // and edits the working tree). `reads: ["plans","validation"]` ⇒
664
+ // `stageEntryArgs` derives `--plans <plan> --validation <latest-report>`;
3873
665
  // `validation` is validate's own publish bucket, so validate-fix always reads
3874
- // the latest failing report.
3875
- "validate-fix": acts({ skill: "remediate", reads: ["plans", "validation"] }),
666
+ // the latest failing report. `remediationOutcome` publishes the deterministic
667
+ // did-anything-change digest verdict on the `remediation` channel (the
668
+ // `commit`/`gitCommitOutcome` pattern) — the arm's OWN edge folds it, so a
669
+ // no-op remediation stops instead of re-validating an unchanged tree.
670
+ "validate-fix": acts({ skill: "remediate", reads: ["plans", "validation"], outcome: remediationOutcome }),
3876
671
  commit: acts({ prompt: COMMIT_BASELINE_PROMPT, outcome: gitCommitOutcome }),
3877
672
  },
3878
673
  edges: {
@@ -4008,45 +803,45 @@ const buildWorkflow = defineWorkflow({
4008
803
  "code-snapshot": "code-fix",
4009
804
  "code-fix": "code-cite-check",
4010
805
  implement: "implement-scope-check",
4011
- // Lane-level scope floor gate. Pass ⇒ reconcile (the coherence backstop
4012
- // runs after the write-set is proven). A `fail` (undeclared write) or a
4013
- // missing verdict routes to STOP — no fix arm, because a scope violation is
4014
- // plan-vs-tree drift the agent must reconcile manually (a phase wrote
4015
- // outside its declared set), not a defect an auto-fix loop can repair. Safe
4016
- // by construction: the sole path onward is an explicit `verdict: "pass"`.
4017
- // Sourced from the scope-check's published verdict channel via the `from`
4018
- // form (the stage key for an outcome-less `produces.script`, per
4019
- // `resolvePublishName`), which suppresses the READS_DATA outputSchema lint.
4020
- "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
806
+ // Lane-level scope floor gate — tiered, see scopeFloorGate: pass AND
807
+ // tracked excess ⇒ reconcile (excess findings ride the verdict channel and
808
+ // validate adjudicates them via the --scope thread — the citation floor's
809
+ // demote-and-adjudicate precedent); untracked-only ⇒ the deterministic
810
+ // scope-quarantine arm; a missing/corrupt verdict ⇒ STOP (integrity
811
+ // clause). Sourced from the scope-check's published verdict channel (the
812
+ // stage key for an outcome-less `produces.script`, per
813
+ // `resolvePublishName`); `readsData: false` suppresses the outputSchema lint.
814
+ "implement-scope-check": scopeFloorGate(),
815
+ // Deterministic re-entry after the quarantine arm: a plain string edge
816
+ // (non-counted, mirroring validate-fix's hop) with guaranteed progress —
817
+ // quarantined paths leave the dirty set, so the re-check either passes or
818
+ // reveals tracked drift. At most one quarantine hop per gate entry; no new
819
+ // loop budget.
820
+ "scope-quarantine": "implement-scope-check",
4021
821
  // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target
4022
822
  // / absent find / failed AV command) or a missing verdict ⇒ STOP (no fix
4023
823
  // arm — a reconciliation failure is plan-vs-tree drift the agent reconciles
4024
824
  // manually). Safe by construction: the sole path onward is an explicit
4025
825
  // `verdict: "pass"`. Sourced from the reconcile channel via the `from` form.
4026
826
  reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
4027
- // Gate commit on validate's own verdict — an unconditional `validate → commit`
4028
- // let a `verdict: fail` (incomplete goal coverage) commit anyway. Now the
4029
- // gate splits: `pass` ⇒ commit; `fail` ⇒ validate-fix (the repair arm above,
4030
- // which re-runs the failing `verify-at-implement` risk-ruling procedures and
4031
- // surgically fixes the tree, then re-enters at implement-scope-check to
4032
- // re-reconcile + re-validate — bounded by the per-destination backward-jump
4033
- // budget). Deliberately NOT a `fallback`: a missing/unexpected verdict stays
4034
- // terminal STOP, so un-anticipated data can never route INTO commit OR the
4035
- // repair arm. Safe by construction: the sole path to commit is an explicit
4036
- // pass. The `match` branch key (`validate-fix`) doubles as the reachability/
4037
- // stage declaration, so naming it both routes `fail` and declares the stage
4038
- // reachable. Sourced from validate's published verdict channel
4039
- // (`from: "validation"` — the bucket its contract's `artifactKind` derives) —
4040
- // a prompt stage owns its message and can't inherit its contract's output
4041
- // schema, so route on the channel, not the raw (un-validated) stage output.
4042
- validate: match("verdict", { commit: "pass", "validate-fix": "fail" }, { from: "validation" }),
4043
- // Deterministic re-entry after the repair arm: remediate's code-mutation is
4044
- // followed by a fresh scope check → reconcile → validate pass, so a fix is
4045
- // re-verified end-to-end before the gate re-folds. A non-counted edge (a
4046
- // deterministic hop into the loop body), so it never trips a backward-jump
4047
- // budget on its own — the budget-consuming decision edge is the validate
4048
- // gate's `validate-fix` branch above.
4049
- "validate-fix": "implement-scope-check",
827
+ // Gate commit on validate's own verdict — see `validateGate`. `pass` ⇒
828
+ // commit; a `fail` WITH remediable handles (a `pass: false` risk ruling or a
829
+ // structured `blockers:` entry) ⇒ validate-fix, which re-enters at
830
+ // implement-scope-check to re-reconcile + re-validate — bounded by the
831
+ // per-destination backward-jump budget; a `fail` with NO handle ⇒ STOP with
832
+ // a route note (the repair arm cannot act on prose-only failures — looping
833
+ // it re-validated an unchanged tree until the guard halted the run).
834
+ // A missing/unexpected verdict stays terminal STOP, so un-anticipated data
835
+ // can never route INTO commit OR the repair arm. Safe by construction: the
836
+ // sole path to commit is an explicit pass.
837
+ validate: validateGate,
838
+ // Re-entry after the repair arm: remediate's code-mutation is followed by a
839
+ // fresh scope check → reconcile → validate pass, so a fix is re-verified
840
+ // end-to-end before the gate re-folds. Now a decision edge (`validateFixGate`
841
+ // folds the `remediation` channel's deterministic digest verdict): a
842
+ // remediation that changed nothing STOPs here — progress is verified, not
843
+ // assumed — while a real fix proceeds into the loop body.
844
+ "validate-fix": validateFixGate,
4050
845
  commit: "stop",
4051
846
  },
4052
847
  });
@@ -4200,10 +995,14 @@ const shipWorkflow = defineWorkflow({
4200
995
  "plan-cite-check": shipCiteGate,
4201
996
  grade: shipGradeGate,
4202
997
  implement: "implement-scope-check",
4203
- // Scope floor gate — build's route verbatim: the sole path onward is an
4204
- // explicit `verdict: "pass"`; a fail (undeclared write) or a missing
4205
- // verdict is terminal STOP. Sourced from the stage's own channel via the
4206
- // `from` form (suppresses the READS_DATA outputSchema lint).
998
+ // Scope floor gate — DELIBERATELY NOT build/vet's tiered scopeFloorGate:
999
+ // ship's identity is stop-on-fail with no fix loops, so the sole path
1000
+ // onward stays an explicit `verdict: "pass"`. The floor's tiered
1001
+ // "untracked-only"/"excess" verdicts (which build quarantines/adjudicates)
1002
+ // are terminal here like any other red gate — the match's no-branch note
1003
+ // names the value, and the agent hand-repairs and re-invokes. Sourced from
1004
+ // the stage's own channel via the `from` form (suppresses the READS_DATA
1005
+ // outputSchema lint).
4207
1006
  "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
4208
1007
  // Reconciliation gate — build's route verbatim: pass ⇒ validate;
4209
1008
  // fail/missing ⇒ STOP (plan-vs-tree drift the agent reconciles manually).
@@ -4224,6 +1023,8 @@ const shipWorkflow = defineWorkflow({
4224
1023
  // Exports
4225
1024
  // ===========================================================================
4226
1025
 
1026
+ export { SHIP_DIMENSION_FANOUT, SHIP_DIMENSIONS, shipGatePasses, shipVerdictOutcome } from "./built-ins/index.js";
1027
+
4227
1028
  // Position 0 is load-bearing: `build` is the default `/wf` workflow when no
4228
1029
  // project/user config sets one (resolve-default.ts resolves
4229
1030
  // `Map.keys().next().value`), so it MUST stay first in this array.