@juicesharp/rpiv-pi 2.6.3 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/docs/workflows.md +1 -1
  2. package/extensions/rpiv-core/agents.ts +10 -13
  3. package/extensions/rpiv-core/artifact-collector.ts +111 -6
  4. package/extensions/rpiv-core/bash-timeout.ts +12 -2
  5. package/extensions/rpiv-core/built-in-workflows.ts +233 -3514
  6. package/extensions/rpiv-core/built-ins/citations.ts +357 -0
  7. package/extensions/rpiv-core/built-ins/gates.ts +613 -0
  8. package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
  9. package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
  10. package/extensions/rpiv-core/built-ins/index.ts +46 -0
  11. package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
  12. package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
  13. package/extensions/rpiv-core/built-ins/priors.ts +352 -0
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
  15. package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
  16. package/extensions/rpiv-core/built-ins/shared.ts +17 -1
  17. package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
  18. package/extensions/rpiv-core/built-ins/slices.ts +288 -0
  19. package/extensions/rpiv-core/constants.ts +5 -1
  20. package/extensions/rpiv-core/lane-console.ts +9 -2
  21. package/extensions/rpiv-core/lane-list.ts +10 -1
  22. package/extensions/rpiv-core/question-lifecycle.ts +2 -2
  23. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  24. package/extensions/rpiv-core/run-lane-registry.ts +83 -83
  25. package/package.json +2 -2
  26. package/skills/elaborate/SKILL.md +1 -1
  27. package/skills/grade/SKILL.md +1 -1
  28. package/skills/implement/SKILL.md +1 -0
  29. package/skills/plan/SKILL.md +3 -1
  30. package/skills/remediate/SKILL.md +1 -0
  31. package/skills/synthesize/SKILL.md +1 -0
  32. package/skills/validate/SKILL.md +25 -19
  33. package/skills/validate/templates/validation.md +1 -1
@@ -14,55 +14,76 @@
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
+ rulingEffectivePass,
73
+ SHIP_DIMENSION_FANOUT,
74
+ SHIP_DIMENSIONS,
75
+ SLICE_DESIGN_FANOUT,
76
+ SLICE_DIMENSION_FANOUT,
77
+ SYNTH_CLUSTER_FANOUT,
78
+ scopeQuarantine,
79
+ shipGatePasses,
80
+ shipVerdictOutcome,
81
+ sliceGatePasses,
82
+ sliceStructureCheck,
83
+ subplanCoverageCheck,
84
+ subplanGatePasses,
85
+ VALIDATE_GOAL_PROMPT,
86
+ verdictRiskRulings,
66
87
  } from "./built-ins/index.js";
67
88
 
68
89
  // The code-review stage's output schema is no longer declared here — every
@@ -72,3432 +93,116 @@ import {
72
93
  // per workflow. Every workflow with a `code-review` stage — polish AND vet —
73
94
  // routes on the same numeric gate: `gate("blockers_count", { <fix>: gt(0), commit: eq(0) }, "commit")`.
74
95
 
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: across three months, 71 distinct flagged
1050
- * paths yielded ZERO fabrications — the no-match population was resolver
1051
- * limitations (suffix/dep/skipped-tree gaps), meta-plan fixture prose, and one
1052
- * garbled-but-real path — while the blocking tier cost ~8h of fix rounds, two
1053
- * dead ship runs, and one four-round identical-findings churn loop. Blocking
1054
- * severity on the shared structure verdict comes ONLY from
1055
- * `verifyPhaseFilesCoverage` (an undeclared write corrupts dep derivation —
1056
- * that floor stays load-bearing).
1057
- */
1058
- /** Trees a citation must never resolve INTO — vendored deps, build copies, or
1059
- * prior pipeline artifacts (a stale artifact copy would back a fabricated line).
1060
- * `.rpiv` is skipped with one carve-out: the walk re-enters `.rpiv/guidance`
1061
- * (see `buildBasenameIndex`) — the guidance shadow tree is a legitimate,
1062
- * routinely-cited and routinely-edited target, and skipping it made every
1063
- * suffix-form `architecture.md` citation a false "does not exist". */
1064
- const CITATION_WALK_SKIP: ReadonlySet<string> = new Set(["node_modules", ".git", "dist", "coverage", ".rpiv"]);
1065
- /** Backstop so a pathological tree can't stall the deterministic cite floor. */
1066
- const CITATION_WALK_FILE_CAP = 50_000;
1067
-
1068
- /** The lazily-built basename → absolute-path(s) index backing the suffix
1069
- * fallback in `resolveCitationPath`. `truncated` marks a partial walk past
1070
- * `CITATION_WALK_FILE_CAP`, which disables the fallback (uniqueness
1071
- * untrustworthy). */
1072
- type BasenameIndex = { index: Map<string, string[]>; truncated: boolean };
1073
-
1074
- /**
1075
- * Index every source file's basename → its absolute path(s) under `cwd` — the
1076
- * candidate pool behind the suffix fallback in `verifyCitations`. The generative
1077
- * producers (slice/synthesize/elaborate) routinely cite a file by bare basename
1078
- * (`built-in-workflows.ts:1431`) or by a package-relative suffix
1079
- * (`validate/stage-rules.ts:70` for `packages/rpiv-workflow/validate/stage-rules.ts`)
1080
- * — mechanical path-prefix omissions, not fabricated references. The basename
1081
- * keys the candidates; `verifyCitations` narrows them by whole-segment suffix.
1082
- * A UNIQUE match backs the citation; an AMBIGUOUS one stays unresolved — unless
1083
- * one of `verifyCitations`' tiebreaks (the caller's declared-`files:` union,
1084
- * then the nearest preceding prose mention) names exactly one
1085
- * candidate — so the producer must disambiguate with the repo-root-relative
1086
- * path. Skips
1087
- * vendored/generated trees so a citation never resolves to a build copy or a
1088
- * prior artifact. Bounded by the file cap.
1089
- */
1090
- const buildBasenameIndex = (cwd: string): BasenameIndex => {
1091
- // Unreadable dir → empty listing, never a throw from the deterministic floor.
1092
- const listDir = (dir: string) => {
1093
- try {
1094
- return readdirSync(dir, { withFileTypes: true });
1095
- } catch {
1096
- return [];
1097
- }
1098
- };
1099
- const index = new Map<string, string[]>();
1100
- const stack: string[] = [cwd];
1101
- let seen = 0;
1102
- while (stack.length > 0) {
1103
- const dir = stack.pop() as string;
1104
- for (const e of listDir(dir)) {
1105
- if (e.isDirectory()) {
1106
- if (!CITATION_WALK_SKIP.has(e.name)) stack.push(join(dir, e.name));
1107
- // `.rpiv` is skipped for its artifact/run trees (a stale artifact
1108
- // copy must never back a citation), but the guidance shadow tree
1109
- // under it is a first-class citation target the pipeline itself
1110
- // edits — carve it back into the walk (missing dir ⇒ empty listing).
1111
- else if (e.name === ".rpiv") stack.push(join(dir, e.name, "guidance"));
1112
- continue;
1113
- }
1114
- if (!e.isFile()) continue;
1115
- // Past the cap the index is INCOMPLETE, so "exactly one match" can no
1116
- // longer be trusted — mark it truncated and let the caller disable the
1117
- // fallback (strict direct-resolution only) rather than back a possibly
1118
- // wrong file off a partial walk.
1119
- if (++seen > CITATION_WALK_FILE_CAP) return { index, truncated: true };
1120
- const abs = join(dir, e.name);
1121
- const arr = index.get(e.name);
1122
- if (arr) arr.push(abs);
1123
- else index.set(e.name, [abs]);
1124
- }
1125
- }
1126
- return { index, truncated: false };
1127
- };
1128
-
1129
- /** Outcome of resolving a single citation's `path` against `cwd`. `abs` is the
1130
- * one backing file when resolution is unique; `ambiguous` carries the candidate
1131
- * list (absolute paths) when more than one tree file matches, so the caller can
1132
- * render the disambiguation finding text. `undefined` ⇒ no match
1133
- * (does-not-exist). This is the minimal-deviation return shape — a plain
1134
- * `string | undefined` would drop the candidate list the disambiguation finding
1135
- * text depends on. */
1136
- type CitationResolution = { abs: string } | { ambiguous: string[] };
1137
-
1138
- /** Strategy 4 of `resolveCitationPath`: tree files whose REPO-RELATIVE path ends
1139
- * with the cited `path` on WHOLE segments. A bare basename is the one-segment
1140
- * case; a multi-segment citation narrows the basename's candidates at a `/`
1141
- * boundary, so `workflow/validate/x.ts` can never match inside
1142
- * `rpiv-workflow/validate/x.ts`. Compared repo-relative (never against the
1143
- * absolute path) so the checkout directory's own name can never back a citation
1144
- * — `src/utils.ts` must not resolve to `<cwd>/utils.ts` just because the repo
1145
- * happens to be cloned at `/tmp/src`. Reads/writes the shared `indexHolder` so
1146
- * the basename index is built lazily ONCE and shared across citations (the
1147
- * first direct-resolution miss pays the tree walk). */
1148
- const suffixMatchesFor = (path: string, cwd: string, indexHolder: { value: BasenameIndex | undefined }): string[] => {
1149
- indexHolder.value ??= buildBasenameIndex(cwd);
1150
- if (indexHolder.value.truncated) return []; // partial index ⇒ uniqueness untrustworthy ⇒ strict
1151
- const candidates = indexHolder.value.index.get(basename(path)) ?? [];
1152
- if (!path.includes("/")) return candidates;
1153
- const suffix = `/${path}`;
1154
- return candidates.filter((abs) =>
1155
- `/${abs
1156
- .slice(cwd.length + 1)
1157
- .split(sep)
1158
- .join("/")}`.endsWith(suffix),
1159
- );
1160
- };
1161
-
1162
- /** Resolve a citation's `path` to one backing file under `cwd`, encapsulating
1163
- * all four strategies in order: (1) direct — `path` or `cwd/path`; (2,3)
1164
- * dependency probes — `node_modules/<path>` and `node_modules/@<path>` (the
1165
- * latter because the citation regex cannot carry `@`, so a cited
1166
- * `node_modules/@scope/pkg/f.js` parses as `scope/pkg/f.js`); DIRECT probes
1167
- * only — the suffix walk still skips `node_modules` (per `CITATION_WALK_SKIP`),
1168
- * so a bare basename never resolves into a dep; (4) suffix fallback — a UNIQUE
1169
- * tree-file suffix match backs the citation, an AMBIGUOUS one returns the
1170
- * candidate list. PURE: emits no findings and throws never — all finding text
1171
- * lives in `verifyCitations`. The lazily-built basename index is shared across
1172
- * calls via `indexHolder`. */
1173
- const resolveCitationPath = (
1174
- path: string,
1175
- cwd: string,
1176
- indexHolder: { value: BasenameIndex | undefined },
1177
- ): CitationResolution | undefined => {
1178
- // existsSync-then-statSync races a concurrent delete into a throw OUT of the
1179
- // deterministic floor (⇒ FAIL_SCRIPT_THREW) — one guarded probe instead.
1180
- const isTreeFile = (p: string): boolean => {
1181
- try {
1182
- return statSync(p).isFile();
1183
- } catch {
1184
- return false;
1185
- }
1186
- };
1187
- // Strategy 1 — direct.
1188
- const direct = isAbsolute(path) ? path : join(cwd, path);
1189
- if (isTreeFile(direct)) return { abs: direct };
1190
- // Strategies 2 & 3 — dependency probes (lockfile-pinned dep source; the regex
1191
- // cannot carry `@`, so `node_modules/@scope/pkg/f.js` is cited as `scope/pkg/f.js`).
1192
- for (const candidate of [join(cwd, "node_modules", path), join(cwd, "node_modules", `@${path}`)]) {
1193
- if (isTreeFile(candidate)) return { abs: candidate };
1194
- }
1195
- // Strategy 4 — suffix fallback: back the citation iff exactly ONE tree file matches.
1196
- const matches = suffixMatchesFor(path, cwd, indexHolder);
1197
- if (matches.length === 1) return { abs: matches[0] };
1198
- if (matches.length > 1) return { ambiguous: matches };
1199
- return undefined;
1200
- };
1201
-
1202
- /** Example-path namespaces the skill prompts use in illustrative citations
1203
- * (`path/to/file.ext:12`, `packages/x/y.ts:42`). Artifacts quote — and models
1204
- * imitate — these examples in unfenced prose, where the fence skip cannot
1205
- * reach them; a citation under one of these prefixes is documentation shape,
1206
- * never a claim about the tree, and prosecuting one buys a full LLM fix round
1207
- * for zero risk averted (three of f329's floor failures were this class). */
1208
- const PLACEHOLDER_CITATION_PREFIXES: readonly string[] = ["path/to/", "packages/x/"];
1209
-
1210
- /**
1211
- * Proximity tiebreak for a citation left ambiguous by the declared-`files:`
1212
- * intersection: resolve to the candidate whose repo-root-relative path has the
1213
- * nearest PRECEDING prose mention — the common artifact idiom of naming a file
1214
- * once in full, then citing it by bare basename. Prose only: mentions inside
1215
- * YAML frontmatter (`files:` ordering carries no authorial intent — a tie there
1216
- * stays a tie) or fenced spans (example/fixture territory) don't count, and
1217
- * matches are token-bounded so a candidate never back-matches inside a longer
1218
- * path mention (`a/dup.ts` inside `x/a/dup.ts`). Returns the winner's absolute
1219
- * path, or `undefined` — the citation then stays unbacked as before.
1220
- */
1221
- const nearestProseMention = (
1222
- body: string,
1223
- upTo: number,
1224
- candidates: readonly string[],
1225
- cwd: string,
1226
- fenced: readonly [number, number][],
1227
- proseStart: number,
1228
- ): string | undefined => {
1229
- let bestAbs: string | undefined;
1230
- let bestIdx = -1;
1231
- for (const abs of candidates) {
1232
- if (!abs.startsWith(cwd + sep)) continue;
1233
- const rel = abs
1234
- .slice(cwd.length + 1)
1235
- .split(sep)
1236
- .join("/");
1237
- // Walk mentions nearest-first; the first CLEAN one (token-bounded, in
1238
- // prose, outside fences) is this candidate's best — earlier ones can't win.
1239
- let from = upTo - rel.length;
1240
- while (from >= 0) {
1241
- const i = body.lastIndexOf(rel, from);
1242
- if (i < 0 || i < proseStart) break;
1243
- from = i - 1;
1244
- const prev = i > 0 ? (body[i - 1] as string) : "";
1245
- const next = body[i + rel.length] ?? "";
1246
- if (prev !== "" && /[\w.@/-]/.test(prev)) continue;
1247
- if (next !== "" && /[\w-]/.test(next)) continue;
1248
- if (fenced.some(([s, e]) => i >= s && i < e)) continue;
1249
- if (i > bestIdx) {
1250
- bestIdx = i;
1251
- bestAbs = abs;
1252
- }
1253
- break;
1254
- }
1255
- }
1256
- return bestAbs;
1257
- };
1258
-
1259
- const verifyCitations = (body: string, cwd: string, declared?: ReadonlySet<string>): StructureFinding[] => {
1260
- const findings: StructureFinding[] = [];
1261
- const seen = new Set<string>();
1262
- // Fenced text is example/fixture territory, not prose asserting a real
1263
- // file:line — a fenced placeholder shaped like a citation must not fail the
1264
- // floor (it false-failed the very plan that fixes this). Span check, not a
1265
- // placeholder-pattern skip: a REAL citation that merely looks placeholder-ish
1266
- // still verifies when it appears in prose.
1267
- const fenced = fencedSpans(body);
1268
- // Prose begins past the YAML frontmatter: the proximity tiebreak must not
1269
- // read the `files:` array as a mention (its ordering carries no intent — a
1270
- // tie inside the declared set stays a tie).
1271
- let proseStart = 0;
1272
- if (body.startsWith("---\n")) {
1273
- const end = body.indexOf("\n---\n", 3);
1274
- if (end !== -1) proseStart = end + "\n---\n".length;
1275
- }
1276
- // Built lazily and reused across citations — only the first direct-resolution
1277
- // miss pays the tree walk, and only when at least one such citation exists.
1278
- const indexHolder: { value: BasenameIndex | undefined } = { value: undefined };
1279
- for (const m of body.matchAll(FILE_LINE_CITATION_RE)) {
1280
- const [, path, startStr, endStr] = m;
1281
- if (!path || !startStr) continue;
1282
- if (fenced.some(([s, e]) => m.index >= s && m.index < e)) continue;
1283
- if (PLACEHOLDER_CITATION_PREFIXES.some((p) => path.startsWith(p))) continue;
1284
- const key = `${path}:${startStr}${endStr ? `-${endStr}` : ""}`;
1285
- if (seen.has(key)) continue;
1286
- seen.add(key);
1287
- let resolved = resolveCitationPath(path, cwd, indexHolder);
1288
- if (resolved && "ambiguous" in resolved && declared !== undefined) {
1289
- // Declared-write-set tiebreak: when the caller supplies the artifact's own
1290
- // declared `files:` union and exactly ONE ambiguous candidate is in it, the
1291
- // artifact has already named the file it means — resolve there instead of
1292
- // halting the run over a path-prefix omission. A tie INSIDE the declared
1293
- // set (two declared `command.ts` files) stays ambiguous: the citation is
1294
- // then genuinely unreadable even against the artifact's own write-set.
1295
- const declaredMatches = resolved.ambiguous.filter(
1296
- (abs) =>
1297
- abs.startsWith(cwd + sep) &&
1298
- declared.has(
1299
- abs
1300
- .slice(cwd.length + 1)
1301
- .split(sep)
1302
- .join("/"),
1303
- ),
1304
- );
1305
- if (declaredMatches.length === 1) resolved = { abs: declaredMatches[0] };
1306
- }
1307
- if (resolved && "ambiguous" in resolved) {
1308
- // Proximity tiebreak: the nearest preceding prose mention of a
1309
- // candidate's full path names the file the author means.
1310
- const near = nearestProseMention(body, m.index, resolved.ambiguous, cwd, fenced, proseStart);
1311
- if (near !== undefined) resolved = { abs: near };
1312
- }
1313
- if (resolved && "ambiguous" in resolved) {
1314
- // More than one tree file matches — name the candidates so the fix arm can disambiguate.
1315
- const shown = resolved.ambiguous
1316
- .slice(0, 3)
1317
- .map((a) => (a.startsWith(cwd + sep) ? a.slice(cwd.length + 1) : a));
1318
- findings.push({
1319
- 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.`,
1320
- where: key,
1321
- // Every candidate is a REAL tree file — advisory per the tier above.
1322
- advisory: true,
1323
- });
1324
- continue;
1325
- }
1326
- let abs = resolved?.abs;
1327
- if (abs === undefined && declared !== undefined) {
1328
- // Declared-write-set rescue on a NO-MATCH resolution — the ambiguity
1329
- // tiebreak's missing twin (observed live: a declared `.rpiv/guidance/**`
1330
- // file's suffix citation landed here as "does not exist" because the
1331
- // suffix walk skips that tree, and the declared set was never asked).
1332
- // A unique whole-segment suffix match inside the plan's own `files:`
1333
- // names the file the author means: verify against it when it exists on
1334
- // disk; a declared file ABSENT from the tree is a planned CREATE — the
1335
- // citation is a forward reference to planned content, unverifiable at
1336
- // this revision, so it yields no finding.
1337
- const matches = [...declared].filter((d) => d === path || `/${d}`.endsWith(`/${path}`));
1338
- if (matches.length === 1) {
1339
- const cand = join(cwd, matches[0]);
1340
- if (!existsSync(cand)) continue;
1341
- abs = cand;
1342
- }
1343
- }
1344
- if (!abs) {
1345
- findings.push({
1346
- 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.`,
1347
- where: key,
1348
- // Advisory like every citation-resolution finding: the observed
1349
- // no-match population was garbled-but-real paths, skipped-tree
1350
- // files, and fixture prose — the grade panel adjudicates via
1351
- // `--cite-check` instead of the floor blocking on it.
1352
- advisory: true,
1353
- });
1354
- continue;
1355
- }
1356
- // A file that vanishes or turns unreadable between resolution and the read
1357
- // is an unbacked citation, never a throw out of the deterministic floor.
1358
- let lineCount: number;
1359
- try {
1360
- lineCount = readFileSync(abs, "utf-8").split("\n").length;
1361
- } catch {
1362
- findings.push({
1363
- 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.`,
1364
- where: key,
1365
- // The file EXISTS (it resolved) — advisory per the tier above.
1366
- advisory: true,
1367
- });
1368
- continue;
1369
- }
1370
- const high = Math.max(Number(startStr), endStr ? Number(endStr) : 0);
1371
- if (high > lineCount) {
1372
- findings.push({
1373
- 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.`,
1374
- where: key,
1375
- // The file exists; only the ordinate drifted — advisory per the tier above.
1376
- advisory: true,
1377
- });
1378
- }
1379
- }
1380
- return findings;
1381
- };
1382
-
1383
- /** A dispatched sub-plan basename with its `_cluster-<k>` ordinal resolved. */
1384
- type DispatchedCluster = { path: string; k: number };
1385
-
1386
- /**
1387
- * A citation string occurs LIVE in the slice-map text — outside fenced spans
1388
- * and not as half of an `old→new` refresh-note pair. A re-slice's revision
1389
- * note legitimately QUOTES the citations it refreshed (contract: only as
1390
- * arrow pairs or inside a fence — see the slice skill's re-slice mode);
1391
- * treating a quoted old citation as still-live would forfeit every documented
1392
- * refresh's discharge, and treating a quoted new one as present would credit
1393
- * a fix that never touched the live `Draws on` lines.
1394
- */
1395
- const citeOccursLive = (body: string, spans: readonly [number, number][], cite: string): boolean => {
1396
- for (let i = body.indexOf(cite); i !== -1; i = body.indexOf(cite, i + 1)) {
1397
- if (spans.some(([s, e]) => i >= s && i < e)) continue;
1398
- if (body.startsWith("→", i + cite.length)) continue;
1399
- if (body.endsWith("→", i)) continue;
1400
- return true;
1401
- }
1402
- return false;
1403
- };
1404
-
1405
- /**
1406
- * One cite-remedy finding is satisfied by the slice-map text: the demanded
1407
- * seed's path occurs live — line suffixes are stripped before matching,
1408
- * because the fix may cite a corrected range and the citation floor
1409
- * (`verifyCitations`) verifies whatever range it actually wrote. `Draws on`
1410
- * and `Out of scope` both satisfy the remedy, so a live occurrence anywhere
1411
- * in the map is the contract. (The former REFRESH mode — a `stale` drifted
1412
- * line number to replace — was removed with anchor-precision grading: a
1413
- * drifted line number is no longer a finding, so nothing demands a refresh.)
1414
- *
1415
- * A finding without a concrete string `requires` is unverifiable ⇒ not satisfied.
1416
- */
1417
- const citeFindingSatisfied = (
1418
- mapBody: string,
1419
- spans: readonly [number, number][],
1420
- f: { requires?: unknown },
1421
- ): boolean =>
1422
- typeof f.requires === "string" &&
1423
- f.requires.length > 0 &&
1424
- citeOccursLive(mapBody, spans, f.requires.replace(/:\d[-\d,:]*$/, ""));
1425
-
1426
- /**
1427
- * Structural fingerprint of one slice-map round: the `slices` + `coverage`
1428
- * frontmatter it published on the `slices` channel — no file re-read.
1429
- * `undefined` when the round carried no `slices` data; a caller must treat
1430
- * that as "cannot compare", never as "unchanged".
1431
- */
1432
- const sliceShape = (round: Output | undefined): string | undefined => {
1433
- const d = round?.data as { slices?: unknown; coverage?: unknown } | undefined;
1434
- return d?.slices === undefined ? undefined : JSON.stringify({ slices: d.slices, coverage: d.coverage ?? null });
1435
- };
1436
-
1437
- /** The verdict fields the cite-only discharge consults. */
1438
- type CiteRemedyVerdict = {
1439
- pass?: boolean;
1440
- remedy?: string;
1441
- findings?: readonly { requires?: unknown }[];
1442
- };
1443
-
1444
- /**
1445
- * Deterministic discharge of a CITE-ONLY `design-readiness` fail — the middle
1446
- * case between "carry a passing verdict" (impossible on the slice gate: its
1447
- * lone dimension failed) and "buy a full re-grade panel" (wasteful when the
1448
- * grader already named the exact citations to add or refresh). A fix that
1449
- * also restructured forfeits the discharge and takes the normal re-grade.
1450
- */
1451
- const citeRemedyDischarged = (state: RunView, mapBody: string): boolean => {
1452
- const verdict = latestVerdictPerDimension(state.named["slice-verdicts"]).get("design-readiness");
1453
- const v = verdict?.data as CiteRemedyVerdict | undefined;
1454
- if (v?.pass !== false || v.remedy !== "cite") return false;
1455
- // A fix must have LANDED since the verdict — discharging the judged map
1456
- // unchanged would contradict the grader, who read it and found the cites
1457
- // wrong. Basename inequality cannot witness the fix (a re-slice may
1458
- // legitimately edit the map in place); publication order can: the latest
1459
- // `slices` round must postdate the verdict.
1460
- const entries = state.named.slices ?? [];
1461
- const verdictTs = verdict?.meta?.ts;
1462
- const currentTs = entries.at(-1)?.meta?.ts;
1463
- if (typeof verdictTs !== "string" || typeof currentTs !== "string" || currentTs <= verdictTs) return false;
1464
- const findings = Array.isArray(v.findings) ? v.findings : [];
1465
- if (findings.length === 0) return false;
1466
- const spans = fencedSpans(mapBody);
1467
- if (!findings.every((f) => f != null && citeFindingSatisfied(mapBody, spans, f))) return false;
1468
- // Shape must match the round the grader judged — located by publication
1469
- // order, not filename, for the same in-place reason.
1470
- const judged = [...entries].reverse().find((s) => typeof s.meta?.ts === "string" && s.meta.ts <= verdictTs);
1471
- const judgedShape = sliceShape(judged);
1472
- return judgedShape !== undefined && judgedShape === sliceShape(entries.at(-1));
1473
- };
1474
-
1475
- /**
1476
- * Deterministic Phase-1 slice-check — the un-gameable floor beneath the LLM
1477
- * `design-readiness` panel. It enforces the invariants a prose grader cannot
1478
- * reliably hold because it grades the slicer's own self-description:
1479
- * • acyclicity — the `deps` DAG must be cycle-free.
1480
- * • coverage conservation — every coverage unit FROZEN at the first cut
1481
- * (`state.named.slices[0]`) must still be claimed by ≥1 slice's `covers`,
1482
- * so a reslice can only redistribute the brief, never simplify by dropping
1483
- * scope. Anchored to the FIRST cut (not the latest map) so a reslice cannot
1484
- * disable the check by deleting the `coverage:` array — the frozen set is
1485
- * read from round 0.
1486
- * • citation backing — every `file:line` the slice map cites (its `Draws on:`
1487
- * footing, refracted up from research) must resolve against the tree. An
1488
- * unbacked citation is fabricated precision that would otherwise starve or
1489
- * mislead the design pass; the deterministic floor stops it here.
1490
- * Emits one combined `{ dimension: "structure" }` verdict onto the
1491
- * `slice-check` channel AND writes it to an fs artifact so the reslice arm's
1492
- * `reads: [fanin("slice-check")]` projection carries the FINDINGS (not just the
1493
- * pass/fail) into `slice-fix` — the way `amend` receives `--code-verdicts`. The
1494
- * gate route folds the channel `data` with the LLM verdicts.
1495
- * Deterministic ⇒ idempotent across reslice rounds (no flicker, resume-safe): the
1496
- * verdict basename is keyed on the slice-map basename, so a re-run OVERWRITES its
1497
- * own slot rather than duplicating it.
1498
- */
1499
- const sliceStructureCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1500
- const latest = latestFsArtifact(state, "slices");
1501
- if (latest?.handle.kind !== "fs") {
1502
- throw haltPreflight(
1503
- "slice-check",
1504
- "slice-check: no slice map to check",
1505
- "slice-check: no fs artifact on the 'slices' channel — slice must run before the structure check",
1506
- );
1507
- }
1508
- const mapBody = readArtifactFile(latest.handle.path, cwd);
1509
- const records = sliceRecords(mapBody, "slice-check", latest.handle.path);
1510
- const findings: { detail: string; where: string }[] = [];
1511
-
1512
- const cycle = sliceDepCycle(records);
1513
- if (cycle.length > 0) {
1514
- const loop = [...cycle, cycle[0]].join("→");
1515
- findings.push({
1516
- 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.`,
1517
- where: `deps: ${cycle.map((n) => `Slice ${n}`).join(", ")}`,
1518
- });
1519
- }
1520
-
1521
- // Coverage conservation, anchored to the FROZEN units of the first cut.
1522
- const firstFs = state.named.slices?.[0]?.artifacts.find((a) => a.handle.kind === "fs");
1523
- const frozen = firstFs?.handle.kind === "fs" ? sliceCoverageUnits(readArtifactFile(firstFs.handle.path, cwd)) : [];
1524
- if (frozen.length > 0) {
1525
- const covered = new Set(records.flatMap((r) => sliceCovers(r.entry)));
1526
- const dropped = frozen.filter((u) => !covered.has(u.id));
1527
- if (dropped.length > 0) {
1528
- findings.push({
1529
- 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'.`,
1530
- where: `coverage: ${dropped.map((u) => u.id).join(", ")}`,
1531
- });
1532
- }
1533
- }
1534
-
1535
- // Citation backing — every file:line the map cites must resolve.
1536
- findings.push(...verifyCitations(mapBody, cwd));
1537
-
1538
- // Stamp the cite-only discharge ONLY on a green floor: structure clean +
1539
- // citation backing verified + demanded seeds present + shape unchanged is
1540
- // exactly what a fresh design-readiness pass on this map would re-establish,
1541
- // so the `sliceGatePasses` skip stays provably equivalent to "re-grade, then pass".
1542
- const discharge =
1543
- findings.length === 0 && citeRemedyDischarged(state, mapBody)
1544
- ? { citeDischarged: basename(latest.handle.path) }
1545
- : undefined;
1546
- return writeStructureVerdict("slice-check", latest.handle, findings, cwd, discharge);
1547
- };
1548
-
1549
- /**
1550
- * `_<k>` cluster ordinal a partial sub-plan carries in its basename
1551
- * (`<slug>_cluster-<k>.md`), emitted by `synthesize`'s partial mode from the
1552
- * `--cluster <k>` the fanout threads on every cluster unit. The token a
1553
- * `subplan-check` reconciliation keys dispatched sub-plans on. Anchored to the
1554
- * basename TAIL (extension optional — extensionless agent writes happen, see
1555
- * the implement-scope floor precedent) so a name carrying several `_cluster-`
1556
- * tokens binds the trailing one deterministically, not the first match.
1557
- */
1558
- const CLUSTER_TOKEN_RE = /_cluster-(\d+)(?:\.\w+)?$/;
1559
-
1560
- /** The pre-filter cluster count the fanout received — the count
1561
- * `subplanCoverageCheck` reconciles dispatched ordinals against. Delegates to
1562
- * `clusterSliceDag`. */
1563
- const expectedClusterCount = (records: readonly PhaseRecord[]): number => clusterSliceDag(records).length;
1564
-
1565
- /** Slice numbers that have NO design artifact on the `designs` channel — the gap
1566
- * the missing-design preflight halts on (a slice with no design is unrepairable
1567
- * by re-dispatch). */
1568
- const designCoverageGap = (sliceNumbers: Set<number>, designBySlice: Map<number, string>): number[] =>
1569
- [...sliceNumbers].filter((n) => !designBySlice.has(n)).sort((a, b) => a - b);
1570
-
1571
- /** Collect every dispatched sub-plan's `_cluster-<k>` ordinal from the `subplans`
1572
- * channel. The `subplans` slot is a produces-fanout channel: `placeFanoutOutput`
1573
- * pre-sizes it to the round's unit total and overwrites each unit's own index, so
1574
- * with a stable unit set iterating it reflects the latest output per unit — a
1575
- * re-dispatch's fresh artifacts re-evaluate cleanly. (A unit that FAILS on
1576
- * re-dispatch leaves its prior-round output at its index; that stale entry
1577
- * re-reads as current here.) Returns the resolved ordinals AND a `tokenless`
1578
- * finding per basename that carries no `_cluster-<k>` token (the root merge
1579
- * cannot attribute a tokenless sub-plan to a slice-DAG cluster). */
1580
- const dispatchedClusterOrdinals = (
1581
- state: RunView,
1582
- ): { dispatched: DispatchedCluster[]; tokenless: StructureFinding[] } => {
1583
- const dispatched: DispatchedCluster[] = [];
1584
- const tokenless: StructureFinding[] = [];
1585
- for (const out of state.named.subplans ?? []) {
1586
- for (const a of out.artifacts) {
1587
- if (a.handle.kind !== "fs") continue;
1588
- const name = basename(a.handle.path);
1589
- const m = CLUSTER_TOKEN_RE.exec(name);
1590
- if (!m) {
1591
- tokenless.push({
1592
- 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.`,
1593
- where: name,
1594
- });
1595
- continue;
1596
- }
1597
- dispatched.push({ path: handleToString(a.handle), k: Number(m[1]) });
1598
- }
1599
- }
1600
- return { dispatched, tokenless };
1601
- };
1602
-
1603
- /** A finding per `_cluster-<k>` ordinal claimed by MORE THAN ONE dispatched
1604
- * sub-plan — a clobber (not a legitimate re-emit: within one round every unit
1605
- * index is a distinct artifact because the channel is replaced each round, so a
1606
- * shared `<k>` is the lost-cluster collision itself). */
1607
- const clobberedOrdinals = (dispatched: readonly DispatchedCluster[]): StructureFinding[] => {
1608
- const pathsByK = new Map<number, string[]>();
1609
- for (const d of dispatched) {
1610
- const arr = pathsByK.get(d.k);
1611
- if (arr) arr.push(d.path);
1612
- else pathsByK.set(d.k, [d.path]);
1613
- }
1614
- const findings: StructureFinding[] = [];
1615
- for (const [k, paths] of pathsByK) {
1616
- if (paths.length > 1) {
1617
- findings.push({
1618
- 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.`,
1619
- where: `cluster-${k}`,
1620
- });
1621
- }
1622
- }
1623
- return findings;
1624
- };
1625
-
1626
- /** sources-coverage — every slice's design must appear in SOME sub-plan's
1627
- * `sources:`. Reads the covered-slice set off each sub-plan's parsed `sources:`
1628
- * (designs follow the `_slice-<N>` convention) and reconciles it against the full
1629
- * slice map. A sub-plan whose frontmatter does not PARSE gets its own
1630
- * re-dispatchable finding naming the FILE (never a terminal halt — the same
1631
- * stray-colon class `artifact-collector` degrades on); when ANY sub-plan is
1632
- * unparseable, the per-slice reconciliation DEFERS (an unreadable sub-plan's
1633
- * coverage is unknowable; blaming its slices would misdirect the repair). */
1634
- const sourcesCoverageGaps = (state: RunView, cwd: string, sliceNumbers: Set<number>): StructureFinding[] => {
1635
- const findings: StructureFinding[] = [];
1636
- const coveredSlices = new Set<number>();
1637
- let unparseable = false;
1638
- for (const out of state.named.subplans ?? []) {
1639
- for (const a of out.artifacts) {
1640
- if (a.handle.kind !== "fs") continue;
1641
- let frontmatter: unknown;
1642
- try {
1643
- ({ frontmatter } = parseFrontmatter(readArtifactFile(handleToString(a.handle), cwd)));
1644
- } catch {
1645
- unparseable = true;
1646
- findings.push({
1647
- 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:'.`,
1648
- where: basename(a.handle.path),
1649
- });
1650
- continue;
1651
- }
1652
- const fm = frontmatter && typeof frontmatter === "object" ? (frontmatter as Record<string, unknown>) : {};
1653
- const sources = fm.sources;
1654
- if (!Array.isArray(sources)) continue;
1655
- for (const s of sources) {
1656
- if (typeof s !== "string") continue;
1657
- const sm = DESIGN_SLICE_RE.exec(s);
1658
- if (sm) coveredSlices.add(Number(sm[1]));
1659
- }
1660
- }
1661
- }
1662
- if (!unparseable) {
1663
- for (const n of [...sliceNumbers].sort((a, b) => a - b)) {
1664
- if (!coveredSlices.has(n)) {
1665
- findings.push({
1666
- 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:'.`,
1667
- where: `sources: slice ${n}`,
1668
- });
1669
- }
1670
- }
1671
- }
1672
- return findings;
1673
- };
1674
-
1675
- /**
1676
- * Deterministic subplan cluster-coverage floor — the structural backstop between
1677
- * the cluster fanout and the root merge. After `subplan` fans each slice-DAG
1678
- * cluster out to a partial sub-plan, this reconciles what was DISPATCHED against
1679
- * what the slice map PROMISED, before the root `plan` merge fans them in:
1680
- * • cluster-count conservation — the PRE-FILTER cluster count
1681
- * (`clusterSliceDag(sliceRecords(latest slices)).length`) must equal the
1682
- * number of distinct `_cluster-<k>` ordinals the fanout emitted. A re-dispatch
1683
- * that re-clobbered an ordinal (the pre-fix clobber bug — two clusters
1684
- * sharing `<k>`, or a tokenless basename) collapses the distinct count,
1685
- * surfacing as a missing cluster here.
1686
- * • token conformance — every dispatched sub-plan basename MUST carry a
1687
- * `_cluster-<k>` token; a tokenless name means `synthesize` dropped the
1688
- * `--cluster <k>` flag and the merge can't attribute it to a cluster.
1689
- * • duplicate/clobbered ordinal — two dispatched sub-plans sharing the same
1690
- * `<k>` (a clobber, not a legitimate re-emit: `placeFanoutOutput` overwrites
1691
- * each unit's own index in the channel slot, so within one round every unit
1692
- * index is a distinct artifact — a shared `<k>` is a real collision, the
1693
- * lost-cluster bug itself).
1694
- * • sources-coverage — every slice's design must appear in SOME sub-plan's
1695
- * `sources:` (the fanout threads each `--designs <path>` and `synthesize`
1696
- * echoes them into `sources:`). Designs follow the `_slice-<N>` convention, so
1697
- * the covered slice set is read off `sources:` and reconciled against the full
1698
- * slice map; a slice whose design no sub-plan lists is a slice the merge would
1699
- * silently drop. A sub-plan whose frontmatter does not PARSE gets its own
1700
- * re-dispatchable finding naming the FILE (never a `FAIL_SCRIPT_THREW` halt —
1701
- * the same stray-colon class `artifact-collector` degrades on), and the
1702
- * per-slice reconciliation defers until every sub-plan parses, so a parse
1703
- * failure is never mis-blamed on the slices it happened to cover.
1704
- * Preflight: a slice with NO design on the `designs` channel halts LOUD before
1705
- * any reconciliation — the fanout drops (or under-feeds) its cluster pre-dispatch
1706
- * (`if (!designs.length) return undefined`), so re-dispatching `subplan` re-drops
1707
- * it every round until `maxBackwardJumps` exhausts with a diagnostic naming the
1708
- * refused re-entry instead of the cause. The missing design is upstream
1709
- * (`slice-design`/`design-review`) and unreachable from this loop's backward
1710
- * edge; halting here names the actual defect and spends no jump budget.
1711
- * Emits `severity: pass ? "none" : "high"` (load-bearing — the route routes via
1712
- * `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently passes a
1713
- * `pass:false` verdict rated `low`/`none`; a lost cluster MUST rate `high` or it
1714
- * ships). Deliberately NOT the `match("verdict", …)` STOP idiom
1715
- * `implementScopeCheck` uses — a lost cluster IS repairable by re-dispatch, so the
1716
- * floor routes the backward edge to `subplan`, bounded by `maxBackwardJumps`.
1717
- * Deterministic ⇒ idempotent across re-dispatch rounds: the verdict basename is
1718
- * keyed on the slice-map basename, so a re-run OVERWRITES its own slot.
1719
- */
1720
- const subplanCoverageCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1721
- const latestSliceMap = latestFsArtifact(state, "slices");
1722
- if (latestSliceMap?.handle.kind !== "fs") {
1723
- throw haltPreflight(
1724
- "subplan-check",
1725
- "subplan-check: no slice map to reconcile against",
1726
- "subplan-check: no fs artifact on the 'slices' channel — slice must run before the subplan coverage check",
1727
- );
1728
- }
1729
- const mapBody = readArtifactFile(latestSliceMap.handle.path, cwd);
1730
- const records = sliceRecords(mapBody, "subplan-check", latestSliceMap.handle.path);
1731
- // PRE-FILTER expected clusters — the count the fanout RECEIVED, not the
1732
- // post-drop dispatched count. The fanout drops a zero-design cluster
1733
- // (`if (!designs.length) return undefined` in SYNTH_CLUSTER_FANOUT's units);
1734
- // design-review catches those upstream, so a healthy run lands here with
1735
- // pre-filter == dispatched — an invariant the missing-design preflight below
1736
- // enforces loudly rather than assumes.
1737
- const expectedK = expectedClusterCount(records);
1738
- const sliceNumbers = new Set(records.map((r) => r.n));
1739
-
1740
- // A slice with no design cannot be repaired by the backward edge: the fanout
1741
- // drops a zero-design cluster pre-dispatch, so every `subplan` re-dispatch
1742
- // reproduces the identical gap until maxBackwardJumps exhausts blaming the
1743
- // re-entry. Halt loud at the floor instead, naming the upstream cause.
1744
- const designBySlice = designPathsBySlice(state);
1745
- const undesigned = designCoverageGap(sliceNumbers, designBySlice);
1746
- if (undesigned.length > 0) {
1747
- throw haltPreflight(
1748
- "subplan-check",
1749
- `subplan-check: slice(s) ${undesigned.join(", ")} have no design on the 'designs' channel`,
1750
- `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.`,
1751
- );
1752
- }
1753
-
1754
- const { dispatched, tokenless } = dispatchedClusterOrdinals(state);
1755
- const findings: StructureFinding[] = [...tokenless];
1756
- findings.push(...clobberedOrdinals(dispatched));
1757
-
1758
- // Cluster-count conservation — distinct dispatched ordinals vs the pre-filter
1759
- // expected count. A clobber or a never-dispatched cluster both surface here.
1760
- const dispatchedK = new Set(dispatched.map((d) => d.k)).size;
1761
- if (dispatchedK < expectedK) {
1762
- findings.push({
1763
- 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).`,
1764
- where: `clusters (expected ${expectedK}, dispatched ${dispatchedK})`,
1765
- });
1766
- }
1767
-
1768
- findings.push(...sourcesCoverageGaps(state, cwd, sliceNumbers));
1769
-
1770
- return writeStructureVerdict("subplan-check", latestSliceMap.handle, findings, cwd);
1771
- };
1772
-
1773
- /**
1774
- * Slice a plan body into per-phase text keyed by phase number, splitting on
1775
- * `## Phase N:` headings OUTSIDE fenced code blocks (a heading inside a ``` or
1776
- * ~~~ fence is example/fixture text, not a structural phase boundary — mirrors
1777
- * `countHeadingsOutsideFences` so the slice and the derive-check agree). The
1778
- * body for phase N runs from its heading line up to (not including) the next
1779
- * out-of-fence `## Phase M:` heading, or end-of-text for the last phase.
1780
- * Returns a `Map<number, string>` (phase n → body text, heading included).
1781
- */
1782
- const phaseBodySlices = (content: string): Map<number, string> => {
1783
- const lineRe = new RegExp(PLAN_PHASE_RE.source); // drop g/m; per-line test, lastIndex can't drift
1784
- const lines = content.split("\n");
1785
- const openings: { n: number; start: number }[] = [];
1786
- forEachLineOutsideFences(content, (line, i) => {
1787
- const m = lineRe.exec(line);
1788
- if (m?.[1]) openings.push({ n: Number(m[1]), start: i });
1789
- });
1790
- const slices = new Map<number, string>();
1791
- for (let idx = 0; idx < openings.length; idx++) {
1792
- const end = idx + 1 < openings.length ? openings[idx + 1].start : lines.length;
1793
- slices.set(openings[idx].n, lines.slice(openings[idx].start, end).join("\n"));
1794
- }
1795
- return slices;
1796
- };
1797
-
1798
- /** Strip a trailing `:line` or `:line-line` citation suffix from a path token. */
1799
- const stripLineSuffix = (p: string): string => p.replace(/:\d+(?:-\d+)?$/, "");
1800
-
1801
- /** Well-known extensionless filenames — the extension heuristic below would drop
1802
- * them, so an undeclared write to one would silently escape the coverage floor.
1803
- * Recognized bare or as the basename of a path. */
1804
- const EXTENSIONLESS_FILENAME_RE =
1805
- /^(?:Makefile|Dockerfile|Rakefile|Gemfile|Justfile|Procfile|LICENSE|NOTICE|CODEOWNERS)$/;
1806
-
1807
- /** Path-like test mirroring slice-overlap.mjs's `looksLikePath`, applied AFTER
1808
- * stripping a `:line` suffix (the blueprint MODIFY heading — `#### N. path/to/file.ext`
1809
- * with a `:12-30` range appended — carries a line range the bare form rejects).
1810
- * Extensionless recognition is allowlist-only (never "any `/`-bearing token"):
1811
- * prose like `and/or` must not read as a declared write. The extension is
1812
- * bounded to 1–5 chars starting with a letter (mirroring
1813
- * FILE_LINE_CITATION_RE) so a dotted IDENTIFIER never reads as a file — a
1814
- * backticked `deps.finalize` in a phase body cost a live run a blocking
1815
- * coverage finding and a full code-fix round. */
1816
- const isPathLike = (s: string): boolean => {
1817
- if (/\s/.test(s)) return false;
1818
- if (EXTENSIONLESS_FILENAME_RE.test(s.slice(s.lastIndexOf("/") + 1))) return true;
1819
- 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));
1820
- };
1821
-
1822
- /**
1823
- * Extract the edit paths a phase body names, across the three artifact
1824
- * conventions the plan/blueprint/synthesize skills emit, OUTSIDE fenced code
1825
- * blocks (a path inside a ``` fence is a code reference, not a declared write —
1826
- * post-`code-splice` safety, since code-splice folds elaborations' fenced code
1827
- * into the plan and those fenced paths must NOT read as phase writes):
1828
- * • `**File**:` / `**Files**:` — plan/blueprint's per-change file line
1829
- * (a backticked comma-list under `**Files**:`, or a single path under `**File**:`).
1830
- * • `#### N. path/to/file.ext` — blueprint's change subsection heading
1831
- * (may carry a `:line`-range suffix on MODIFY entries — stripped).
1832
- * • `- `path/to/file.ts`` — synthesize's backticked-path list item under
1833
- * `### Changes` (the form `elaborate`/`synthesize` emit).
1834
- * Strips a trailing `:line`/`:line-line` suffix. Mirrors slice-overlap.mjs's
1835
- * `filesOf` + `looksLikePath` and extends them with the synthesize list-item
1836
- * form. Returns a de-duplicated `string[]`.
1837
- */
1838
- const editPathsOfPhase = (phaseBody: string): string[] => {
1839
- const files = new Set<string>();
1840
- const add = (raw: string) => {
1841
- const stripped = stripLineSuffix(raw.replace(/[`*]/g, "").trim());
1842
- if (stripped && isPathLike(stripped)) files.add(stripped);
1843
- };
1844
- // The list-item form is scoped to a Changes section (`### Changes` heading or
1845
- // a `**Changes**:` field line): a backticked bullet elsewhere in the body is
1846
- // a REFERENCE ("mirror `x/state.ts`"), not a declared write — unscoped, those
1847
- // read as coverage gaps and block. Any other heading or `**Field**:` label
1848
- // exits the scope; `**File(s)**:` lines don't flip it (they're the path form
1849
- // themselves and legitimately precede `**Changes**:`).
1850
- let inChanges = false;
1851
- forEachLineOutsideFences(phaseBody, (line) => {
1852
- const heading = line.match(/^#{2,5}\s+(.*)$/);
1853
- if (heading) inChanges = /^changes\b/i.test(heading[1].trim());
1854
- const fm = line.match(/^\*\*Files?\*\*:\s*(.+)$/);
1855
- if (fm) {
1856
- for (const tok of fm[1].split(/[,\s]+/)) add(tok);
1857
- return;
1858
- }
1859
- const label = line.match(/^\*\*([A-Za-z][A-Za-z ]*)\*\*:/);
1860
- if (label?.[1]) inChanges = /^changes$/i.test(label[1].trim());
1861
- const hm = line.match(/^#{3,4}\s+\d+\.\s+(\S+)/);
1862
- if (hm) {
1863
- add(hm[1]);
1864
- return;
1865
- }
1866
- const lm = line.match(/^-\s+`([^`]+)`/);
1867
- if (lm && inChanges) add(lm[1]);
1868
- });
1869
- return [...files];
1870
- };
1871
-
1872
- /**
1873
- * Deterministic plan-time coverage floor: every edit path a phase body NAMES
1874
- * (in `### Changes`/`#### N. path`/`**File**:`) must be DECLARED in that phase's
1875
- * frontmatter `files:` array. An undeclared write is the per-phase attribution
1876
- * gap the dep-gated implement fanout and the lane-level scope floor both need
1877
- * closed upstream — a body edit not in `files:` is invisible to dependency
1878
- * derivation and unattributable under concurrency. PURE: no LLM judgment, never
1879
- * throws (a malformed frontmatter degrades to `[]`). A `files:`-LESS phase
1880
- * (absent key) yields NO findings — empty-set degradation so a legacy/
1881
- * `files:`-less plan never false-fails; a phase that declares `files: []` is
1882
- * checked (every body edit is a gap). Folded into `planCitationCheck(who)` so
1883
- * both the `plan-cite-check` and `code-cite-check` arms emit coverage findings
1884
- * on their shared `dimension: "structure"` verdict — no new stage/channel/route.
1885
- */
1886
- const verifyPhaseFilesCoverage = (content: string, who: string, path: string): { detail: string; where: string }[] => {
1887
- let fm: Record<string, unknown>;
1888
- try {
1889
- const { frontmatter } = parseFrontmatter(content);
1890
- fm = frontmatter as Record<string, unknown>;
1891
- } catch {
1892
- return []; // malformed frontmatter → degrade to no findings, never throw
1893
- }
1894
- const phases = Array.isArray(fm.phases) ? fm.phases : [];
1895
- const entryByN = new Map<number, Record<string, unknown>>();
1896
- phases.forEach((entry, idx) => {
1897
- const e = (entry ?? {}) as Record<string, unknown>;
1898
- const n = typeof e.n === "number" ? e.n : idx + 1;
1899
- entryByN.set(n, e);
1900
- });
1901
- const findings: { detail: string; where: string }[] = [];
1902
- for (const [n, body] of phaseBodySlices(content)) {
1903
- const entry = entryByN.get(n);
1904
- if (!entry) continue; // body phase with no matching frontmatter entry — derive-check's concern, not coverage's
1905
- // `files:` key ABSENT → degradation (legacy plan): skip. Present (even `[]`) → check.
1906
- if (!Array.isArray(entry.files)) continue;
1907
- const declared = new Set(phaseFiles(entry));
1908
- for (const editPath of editPathsOfPhase(body)) {
1909
- if (declared.has(editPath)) continue;
1910
- // Whole-segment suffix tolerance: a body form citing the file by bare
1911
- // basename or partial path (`#### 2. config.ts` for a declared
1912
- // `packages/x/config.ts`) is covered by the declaration — exact-match
1913
- // only made such a heading unfixable except by polluting `files:` with
1914
- // the bare name (which then corrupts dep derivation and the scope
1915
- // floor, the very consumers this floor protects).
1916
- if ([...declared].some((d) => `/${d}`.endsWith(`/${editPath}`) || `/${editPath}`.endsWith(`/${d}`))) continue;
1917
- findings.push({
1918
- 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.`,
1919
- where: `${who} ${path} phase ${n}: ${editPath}`,
1920
- });
1921
- }
1922
- }
1923
- return findings;
1924
- };
1925
-
1926
- /**
1927
- * The union of every phase's declared `files:` across the plan's frontmatter —
1928
- * the disambiguation pool `planCitationCheck` hands `verifyCitations`. A plan's
1929
- * write-set is the one place the plan itself names its files repo-root-relative
1930
- * (the coverage floor enforces exactly that), so it is a deterministic
1931
- * tiebreaker for the ambiguous-suffix findings that would otherwise STOP a
1932
- * loop-less preset (ship) over a bare `messages.ts:18` whose owning file the
1933
- * plan already declares. Degrades to the empty set on malformed frontmatter —
1934
- * never throws out of the deterministic floor.
1935
- */
1936
- const declaredPlanFiles = (content: string): ReadonlySet<string> => {
1937
- let fm: Record<string, unknown>;
1938
- try {
1939
- fm = parseFrontmatter(content).frontmatter as Record<string, unknown>;
1940
- } catch {
1941
- return new Set();
1942
- }
1943
- const phases = Array.isArray(fm.phases) ? fm.phases : [];
1944
- const declared = new Set<string>();
1945
- for (const entry of phases) for (const f of phaseFiles(entry)) declared.add(f);
1946
- return declared;
1947
- };
1948
-
1949
- /**
1950
- * Deterministic citation floor for a synthesized/spliced plan — the plan-scope
1951
- * twin of `sliceStructureCheck`'s citation backing, extending the citation
1952
- * floor past the slice map to the plan and the code-bearing plan (a fabricated `file:line` in
1953
- * the plan misdirects `implement`). Verifies every
1954
- * citation resolves against the working tree and emits a `{ dimension:
1955
- * "structure" }` verdict on `who`'s channel that the gate route folds via
1956
- * `allDimensionsPass`; the matching `<fix>` stage reads `fanin(who)` so the
1957
- * findings DRIVE the amend rather than blind-halt. Reuses `verifyCitations` — no
1958
- * fuzzy wrong-symbol heuristic — threading the plan's declared `files:` union so
1959
- * an ambiguous suffix citation resolves when exactly one candidate is in the
1960
- * plan's own write-set. Basename-keyed ⇒ idempotent across fix rounds.
1961
- */
1962
- const planCitationCheck =
1963
- (who: string) =>
1964
- ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1965
- const latest = latestFsArtifact(state, "plans");
1966
- if (latest?.handle.kind !== "fs") {
1967
- throw haltPreflight(
1968
- who,
1969
- `${who}: no plan to check`,
1970
- `${who}: no fs artifact on the 'plans' channel — the plan must be produced before the citation check`,
1971
- );
1972
- }
1973
- const body = readArtifactFile(latest.handle.path, cwd);
1974
- const findings = verifyCitations(body, cwd, declaredPlanFiles(body));
1975
- // Plan-time coverage floor: a body edit not declared in its phase's `files:`
1976
- // fails structurally, same channel/verdict/route as an unbacked citation.
1977
- findings.push(...verifyPhaseFilesCoverage(body, who, latest.handle.path));
1978
- return writeStructureVerdict(who, latest.handle, findings, cwd);
1979
- };
1980
-
1981
- /**
1982
- * Copy the latest graded plan off `plans` into `.rpiv/artifacts/priors/`
1983
- * basename-keyed, publishing the bytes on the snapshot stage's OWN channel with
1984
- * role `prior` — one deterministic hop BEFORE the matching fix stage inside the
1985
- * existing fix loop (plan-grade/plan-confirm → plan-snapshot → plan-fix; code
1986
- * twin). Overwritten each fix round, so the prior always reflects the
1987
- * pre-CURRENT-fix content; the re-grade reads it via `latestPriorContent` to
1988
- * decide whether the amend was surgical. `who` attributes the halt when no plan
1989
- * is published. `kind: "artifact-md"` is the honest kind — the prior IS a copy
1990
- * of an artifact-md plan body (the kind plans carry under `rpivBucketOutcome`).
1991
- */
1992
- const snapshotLatestPlan =
1993
- (who: string) =>
1994
- ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
1995
- const latest = latestFsArtifact(state, "plans");
1996
- if (latest?.handle.kind !== "fs") {
1997
- throw haltPreflight(
1998
- who,
1999
- `${who}: no plan to snapshot`,
2000
- `${who}: no fs artifact on the 'plans' channel — the plan must be graded before the snapshot stage`,
2001
- );
2002
- }
2003
- const src = isAbsolute(latest.handle.path) ? latest.handle.path : join(cwd, latest.handle.path);
2004
- const priorRel = join(PRIOR_DIR, basename(latest.handle.path));
2005
- mkdirSync(join(cwd, PRIOR_DIR), { recursive: true });
2006
- copyFileSync(src, join(cwd, priorRel));
2007
- return {
2008
- kind: "artifact-md",
2009
- artifacts: [{ handle: { kind: "fs", path: priorRel }, role: "prior" }],
2010
- data: { snapshot_of: handleToString(latest.handle) },
2011
- };
2012
- };
2013
-
2014
- /** Snapshot the graded plan before `plan-fix` amends it (plan gate). */
2015
- const planSnapshot = snapshotLatestPlan("plan-snapshot");
2016
- /** Snapshot the graded plan before `code-fix` amends it (code gate). */
2017
- const codeSnapshot = snapshotLatestPlan("code-snapshot");
2018
-
2019
- /**
2020
- * A duty demotion stamped onto a verdict's on-disk JSON — the legible record
2021
- * that a risk ruling the panel marked `pass: true` was demoted to effective-
2022
- * fail by the evidence or verify-at-implement duty. One entry per FAILING
2023
- * duty (a ruling authored as BOTH mechanics AND verify-at-implement can carry
2024
- * two). `reason` is decision-code-free prose (no run/phase ids, no absolute
2025
- * line numbers) naming the duty that failed, so disk readers (amend, confirm
2026
- * `--prior`) can tell a grader-side demotion from a genuine `pass: false`.
2027
- */
2028
- interface RiskDutyDemotion {
2029
- id: string;
2030
- duty: "evidence-format" | "procedure-owner";
2031
- reason: string;
2032
- }
2033
-
2034
- /**
2035
- * Materialize the duty demotion as legible on-disk data. After a grade round,
2036
- * each latest-per-dimension verdict whose `pass: true` rulings were demoted by
2037
- * the evidence or verify-at-implement duty gets a `risk_duty_demotions` array
2038
- * written onto its on-disk JSON IN PLACE — the one medium amend and confirm's
2039
- * `--prior` read. The verdict's own `pass` is NEVER flipped (every gate fold —
2040
- * `allRiskFlagsPass`/`dimensionsToRegrade`/`confirmDue` — consults
2041
- * `rulingEffectivePass` off in-memory `state.named`, which never re-reads the
2042
- * rewritten file, so gate outcomes are unchanged); the field is an additive,
2043
- * read-only signal for the disk readers.
2044
- *
2045
- * Modeled on `snapshotLatestPlan(who)` (a `ScriptFn` that side-effects AND
2046
- * returns an `Output`): it reads the PLAN-sourced duty triggers
2047
- * (`planAuthoredRisks`), iterates the EXACT verdict set amend keeps + confirm
2048
- * reads (`latestVerdictPerDimension(freshVerdicts(...))`), and rewrites each
2049
- * demoted verdict's fs handle in place. Writes ONLY when ≥1 demotion (a clean
2050
- * grade is a no-op — no needless reformat/mtime churn); each per-file
2051
- * read/parse/write is wrapped so a single unparseable/stale file is skipped
2052
- * (never halts the gate). Returns `{ demotions }` echoing `{dimension, id,
2053
- * duty, verdict}` for journal greppability. `channel` is the plan channel the
2054
- * risks + current artifact live on; `verdictChannel` is the grade's own
2055
- * verdict channel (plan-verdicts / code-verdicts).
2056
- */
2057
- const demoteDuties =
2058
- (who: string, channel: string, verdictChannel: string) =>
2059
- ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2060
- const risks = planAuthoredRisks(state, channel);
2061
- const current = latestArtifactPath(state, channel);
2062
- const demotions: { dimension: string; id: string; duty: RiskDutyDemotion["duty"]; verdict: string }[] = [];
2063
- for (const o of latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel] ?? [], current)).values()) {
2064
- const handle = o.artifacts.find((a) => a.handle.kind === "fs")?.handle;
2065
- if (handle?.kind !== "fs") continue;
2066
- const dimRaw = (o.data as { dimension?: unknown } | undefined)?.dimension;
2067
- const dimension = typeof dimRaw === "string" ? dimRaw : "";
2068
- const perFile: RiskDutyDemotion[] = [];
2069
- for (const r of verdictRiskRulings(o)) {
2070
- const authored = risks.get(r.id);
2071
- // Only a `pass: true` ruling that rulingEffectivePass demotes — never a
2072
- // genuine `pass: false` (that is already a fail, not a demoted pass).
2073
- if (r.pass !== true || rulingEffectivePass(r, authored)) continue;
2074
- if (!evidenceCitesFileLine(r, authored)) {
2075
- perFile.push({
2076
- id: r.id,
2077
- duty: "evidence-format",
2078
- reason: "mechanics pass without an adjacent file:line citation in evidence",
2079
- });
2080
- demotions.push({ dimension, id: r.id, duty: "evidence-format", verdict: handleToString(handle) });
2081
- }
2082
- if (!procedureSatisfiesDuty(r, authored)) {
2083
- perFile.push({
2084
- id: r.id,
2085
- duty: "procedure-owner",
2086
- reason: "verify-at-implement pass without a concrete procedure and owner phase",
2087
- });
2088
- demotions.push({ dimension, id: r.id, duty: "procedure-owner", verdict: handleToString(handle) });
2089
- }
2090
- }
2091
- if (perFile.length === 0) continue;
2092
- try {
2093
- const abs = isAbsolute(handle.path) ? handle.path : join(cwd, handle.path);
2094
- const json = JSON.parse(readFileSync(abs, "utf-8")) as Record<string, unknown>;
2095
- json.risk_duty_demotions = perFile;
2096
- writeFileSync(abs, JSON.stringify(json, null, 2));
2097
- } catch {
2098
- // skip-on-throw: an unparseable/stale verdict file never halts the gate.
2099
- }
2100
- }
2101
- return { kind: "json", artifacts: [], data: { demotions, stage: who } };
2102
- };
2103
-
2104
- /**
2105
- * Stamp duty demotions onto the graded plan's verdicts after `plan-grade`, one
2106
- * deterministic hop before the gate routes (plan-grade → plan-demote → route).
2107
- * The code lane re-grades `plans` on `code-verdicts` (mirroring `codeSnapshot`).
2108
- */
2109
- const planDemote = demoteDuties("plan-demote", "plans", "plan-verdicts");
2110
- const codeDemote = demoteDuties("code-demote", "plans", "code-verdicts");
2111
-
2112
- /**
2113
- * Deterministic lane-level scope floor — the structural backstop beneath the
2114
- * LLM quality gates. After build's `implement` lane runs (now dep-gated and, as
2115
- * of this phase's unpin, concurrent up to the host cap), this checks the working
2116
- * tree's dirty set against the plan's declared write-set (the union of every
2117
- * phase's `files:`, twin-expanded via `withTestTwins`): any dirty path the run
2118
- * wrote that is NOT in `declared`, NOT
2119
- * pre-existing at the run-start baseline, and NOT under a bookkeeping tree is a
2120
- * scope violation — a phase escaped the upstream write-scope discipline and
2121
- * rewrote the wider tree, corrupting (or about to corrupt) a concurrent
2122
- * sibling's in-flight edit. Fail ⇒ STOP (no fix arm): a scope violation is a
2123
- * plan-vs-tree drift the agent must reconcile manually, not an auto-fix loop.
2124
- *
2125
- * Reads the plan with the SAME inline shape `planCitationCheck(who)` uses —
2126
- * `latestFsArtifact(state,"plans")` + `readArtifactFile` + `planPhaseRecords` +
2127
- * Phase 1's `phaseFiles` — NOT Phase 2's `readPlanPhaseRecords(state,cwd,who)`,
2128
- * because this stage needs the plan HANDLE for the `artifact` field and the
2129
- * basename-keyed verdict path, which the `who`-attributed helper collapses. The
2130
- * baseline is the run-start snapshot on the `goal` channel (`goalBaselinePath`,
2131
- * the same reader `VALIDATE_GOAL_PROMPT` and `COMMIT_BASELINE_PROMPT` use); the
2132
- * dirty set is `git status --porcelain` (non-repo / git-missing ⇒ empty dirty ⇒
2133
- * pass — the lane degrades to unguarded rather than failing a non-repo run).
2134
- * Emits one `{ dimension: "scope" }` verdict, basename-keyed off the plan ⇒
2135
- * idempotent across the build loop.
2136
- *
2137
- * `data` carries BOTH a `pass` boolean AND a `verdict` enum ("pass" | "fail")
2138
- * that always agree (`verdict: pass ? "pass" : "fail"`). The route is the
2139
- * established `match("verdict", …)` gate idiom (mirrors `validate`'s own route:
2140
- * `match("verdict", { commit: "pass" }, …)` — no-match ⇒ STOP, the same fail
2141
- * behavior). It is deliberately NOT the `defineRoute`/`allDimensionsPass`
2142
- * pattern the citation floors use: `allDimensionsPass` applies a severity floor
2143
- * (pass === true || severity low/none), so a failing scope check rated low
2144
- * severity would silently pass the gate — the exact escape class the lane floor
2145
- * exists to catch. The `from` form suppresses the `READS_DATA` outputSchema lint,
2146
- * so no schema is declared on the script stage (matching `slice-check`/
2147
- * `plan-cite-check`).
2148
- */
2149
- const implementScopeCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2150
- const latest = latestFsArtifact(state, "plans");
2151
- if (latest?.handle.kind !== "fs") {
2152
- throw haltPreflight(
2153
- "implement-scope-check",
2154
- "implement-scope-check: no plan to scope-check",
2155
- "implement-scope-check: no fs artifact on the 'plans' channel — implement must run before the scope check",
2156
- );
2157
- }
2158
- const body = readArtifactFile(latest.handle.path, cwd);
2159
- const records = planPhaseRecords(body, "implement-scope-check", latest.handle.path);
2160
- // Declared write-set = union of every phase's `files:` (via `phaseFiles`),
2161
- // expanded with co-located test twins (`withTestTwins`) — a signature change
2162
- // in a declared file legitimately drags its twin's assertions along.
2163
- // A `files:`-less plan yields `[]` ⇒ `scopeExcess` returns `[]` ⇒ inert floor.
2164
- const declared = withTestTwins(records.flatMap((r) => phaseFiles(r.entry)));
2165
-
2166
- // Run-start baseline (goal channel, role "baseline") + current dirty set —
2167
- // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
2168
- const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
2169
- const dirty = gitDirtyPaths(cwd);
2170
-
2171
- const excess = scopeExcess(dirty, baseline, declared);
2172
- const findings = excess.map((path) => ({
2173
- 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.`,
2174
- where: path,
2175
- }));
2176
- const pass = findings.length === 0;
2177
- const data = {
2178
- dimension: "scope",
2179
- pass,
2180
- verdict: pass ? "pass" : "fail",
2181
- score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2182
- severity: pass ? "none" : "high",
2183
- artifact: handleToString(latest.handle),
2184
- findings,
2185
- feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2186
- };
2187
- // Basename-keyed, NOT round-stamped (unlike grade's timestamped slug): each
2188
- // fix-loop round overwrites the file. Deliberate — the route reads the
2189
- // accumulating channel, and on disk only the latest round's scope verdict
2190
- // matters; round-stamp here if a consumer ever needs the history.
2191
- const rel = join(VERDICT_DIR, `implement-scope-check__${basename(latest.handle.path, ".md")}.json`);
2192
- mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2193
- writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2194
- return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2195
- };
2196
-
2197
- /**
2198
- * vet's `implement-scope-check` — the loop-aware scope floor (twin of build's
2199
- * `implementScopeCheck` above). Deterministic (no LLM): the implement lane may
2200
- * write ONLY the paths a plan phase declares in its `files:` set; any other dirty
2201
- * path (not in the run-start baseline, not under `.rpiv/`/`thoughts/`) is excess
2202
- * and halts before `validate`.
2203
- *
2204
- * vet differs from build in ONE place: build's extra `plans` entries are
2205
- * superseding amendments (`plan-fix` re-publishes the whole plan) so build reads
2206
- * latest-only; vet's review-fix loop pushes a DISTINCT non-superseding fix plan
2207
- * per iteration (completing a `produces` stage APPENDS to its named slot, and
2208
- * backward jumps don't reset channels), so this function builds `declared` as the
2209
- * UNION of Phase 1's `phaseFiles` over the FULL `state.named.plans` history — a
2210
- * path a prior iteration's plan legitimately wrote is not excess against the
2211
- * latest plan. The latest plan's handle is used ONLY for the basename-keyed
2212
- * verdict path (idempotent across fix rounds) and the `artifact` field.
2213
- *
2214
- * Otherwise byte-for-byte `implementScopeCheck` above: the baseline via
2215
- * `goalBaselinePath` (satisfied now that vet has a `goal` stage), the dirty set
2216
- * via `git status --porcelain` with explicit `stdio`, the shared `scopeExcess`
2217
- * core + `parseGitStatusPaths`, and the `dimension:"scope"` verdict
2218
- * (carrying BOTH `pass` and `verdict` — the route is the `match("verdict", …)`
2219
- * gate idiom, NOT `allDimensionsPass`, so a fail always halts) written to
2220
- * `VERDICT_DIR`. Non-repo / git-missing ⇒ empty dirty ⇒ pass (never throws).
2221
- * Basename-keyed off the latest plan ⇒ idempotent across review-fix rounds.
2222
- */
2223
- const implementScopeCheckVet = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2224
- // Declared set = UNION of `phaseFiles` over EVERY non-failed plan on the channel.
2225
- // The fs-artifact filter skips failed/unfilled entries (an Output with no fs
2226
- // handle contributed no plan to read).
2227
- const { declared, latest } = unionDeclaredWriteSet(state.named.plans ?? [], cwd);
2228
- if (!latest) {
2229
- throw haltPreflight(
2230
- "implement-scope-check",
2231
- "implement-scope-check: no plan to check",
2232
- "implement-scope-check: no fs plan artifact on the 'plans' channel — blueprint/implement must run before the scope check",
2233
- );
2234
- }
2235
-
2236
- // Run-start baseline (goal channel, role "baseline") + current dirty set —
2237
- // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
2238
- const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
2239
- const dirty = gitDirtyPaths(cwd);
2240
-
2241
- // Shared core: subtract the run's bookkeeping dirs (`.rpiv/`,
2242
- // `thoughts/`) and the run-start baseline; empty-`declared` ⇒ `[]` (degradation
2243
- // ⇒ inert floor — a fully `files:`-less plan never false-fails). Twin-expanded
2244
- // like build's floor: a declared file carries its co-located test twin.
2245
- const excess = scopeExcess(dirty, baseline, withTestTwins([...declared]));
2246
- const findings = excess.map((p) => ({
2247
- 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.`,
2248
- where: p,
2249
- }));
2250
- const pass = findings.length === 0;
2251
- const data = {
2252
- dimension: "scope",
2253
- pass,
2254
- verdict: pass ? "pass" : "fail",
2255
- score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2256
- severity: pass ? "none" : "high",
2257
- artifact: handleToString(latest.handle),
2258
- findings,
2259
- feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2260
- };
2261
- // Basename-keyed, NOT round-stamped (unlike grade's timestamped slug): each
2262
- // fix-loop round overwrites the file. Deliberate — the route reads the
2263
- // accumulating channel, and on disk only the latest round's scope verdict
2264
- // matters; round-stamp here if a consumer ever needs the history.
2265
- const rel = join(VERDICT_DIR, `implement-scope-check__${basename(latest.handle.path, ".md")}.json`);
2266
- mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2267
- writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2268
- return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2269
- };
2270
-
2271
- /**
2272
- * One `#### Reconciliation` directive parsed from a plan body: a machine-applicable
2273
- * `find → replace` against a single test-expectation file. The implement lane records
2274
- * these in a phase's OWN section when a correct change invalidates a test that lives
2275
- * in a sibling phase's landed section (which the implementer may NOT edit); `reconcile`
2276
- * applies them write-restricted to `*.test.*` targets.
2277
- */
2278
- interface ReconciliationDirective {
2279
- /** Repo-root-relative test target (`*.test.*`). */
2280
- target: string;
2281
- /** Substring to find (replaced exactly once via `String.replace`). */
2282
- find: string;
2283
- /** Replacement string. */
2284
- replace: string;
2285
- }
2286
-
2287
- /** Directive grammar: `` - `<target>`: replace `<find>` → `<replace>` — <rationale> ``.
2288
- * The `→` (U+2192) separates find/replace; the em-dash `—` (U+2014) + rationale is
2289
- * optional. Find/replace carry no inner backticks. The two spans are intentionally
2290
- * asymmetric and MUST NOT be symmetrized: `find` is one-or-more `[^`]+` (an empty
2291
- * find has no anchored target and `String.replace("")` prepends the replacement on
2292
- * every run, so the parser rejects it at parse time), while `replace` is
2293
- * zero-or-more `[^`]*` (an empty replace is a legitimate deletion directive). */
2294
- const RECONCILE_DIRECTIVE_RE = /^-\s+`([^`]+)`\s*:\s*replace\s+`([^`]+)`\s*→\s*`([^`]*)`\s*(?:—\s+.*)?$/;
2295
- /** A directive ATTEMPT — `- `<target>`:` — that does not match the full grammar. Used
2296
- * to surface a malformed directive as a finding rather than silently dropping it. */
2297
- const RECONCILE_DIRECTIVE_ATTEMPT_RE = /^-\s+`[^`]+`\s*:/;
2298
-
2299
- /**
2300
- * Parse every `#### Reconciliation` directive from a plan body. Returns the
2301
- * well-formed directives AND the malformed attempts (lines that carry the
2302
- * `- `<target>`:` shape but not the full `replace … → …` grammar); `reconcile`
2303
- * turns each malformed attempt into a finding so a broken directive is visible,
2304
- * never silently dropped. Prose list items are ignored. Pure: no I/O, no throw.
2305
- * A section opens at a `#### Reconciliation` heading and closes at the next
2306
- * `#{1,4}` heading (so `### Success Criteria` / `## Phase N:` / a sibling
2307
- * `#### Automated Verification:` all end it).
2308
- */
2309
- const reconciliationRecords = (
2310
- body: string,
2311
- ): {
2312
- directives: ReconciliationDirective[];
2313
- malformed: string[];
2314
- } => {
2315
- const directives: ReconciliationDirective[] = [];
2316
- const malformed: string[] = [];
2317
- let inSection = false;
2318
- for (const raw of body.split("\n")) {
2319
- const line = raw.trimEnd();
2320
- if (/^####\s+Reconciliation\b/.test(line)) {
2321
- inSection = true;
2322
- continue;
2323
- }
2324
- // Any other heading ends the section (the open-heading branch above `continue`s,
2325
- // so this only fires for non-`#### Reconciliation` headings).
2326
- if (/^#{1,4}\s/.test(line)) {
2327
- inSection = false;
2328
- continue;
2329
- }
2330
- if (!inSection) continue;
2331
- const m = RECONCILE_DIRECTIVE_RE.exec(line);
2332
- if (m) {
2333
- directives.push({ target: m[1]!.trim(), find: m[2]!, replace: m[3]! });
2334
- } else if (RECONCILE_DIRECTIVE_ATTEMPT_RE.test(line)) {
2335
- malformed.push(line.trim());
2336
- }
2337
- }
2338
- return { directives, malformed };
2339
- };
2340
-
2341
- const isTestPath = (target: string): boolean => TEST_PATH_RE.test(target);
2342
-
2343
- /**
2344
- * Apply each `#### Reconciliation` directive, write-restricted to test-expectation
2345
- * files (`isTestPath` — reconcile writes ONLY test files; a non-test target is a
2346
- * finding, left untouched, fail-closed). A present `find` is replaced exactly
2347
- * once (`String.replace`, first match); an absent `find` whose `replace` is empty
2348
- * is the idempotent-re-run no-op for a deletion (find-absent is the deletion's
2349
- * success condition — the directive was already applied, no finding, no write); an
2350
- * absent `find` whose non-empty `replace` is ALSO absent is a finding (reconcile
2351
- * does not guess); an absent `find` whose non-empty `replace` is already present is
2352
- * the idempotent-re-run no-op for a substitution (a prior successful apply, no
2353
- * finding, no write). Paths resolve through `cwd` (`isAbsolute` short-circuit else
2354
- * `join(cwd, target)`). Fail-soft: a read/apply throw degrades to a finding naming
2355
- * the target, never a terminal throw. Returns findings in DIRECTIVE order and
2356
- * performs the side-effecting writes itself (`reconcile` spreads the return).
2357
- */
2358
- const applyReconciliationDirectives = (
2359
- directives: readonly ReconciliationDirective[],
2360
- cwd: string,
2361
- ): { detail: string; where: string }[] => {
2362
- const findings: { detail: string; where: string }[] = [];
2363
- // Apply directives, write-restricted to test-expectation files.
2364
- for (const d of directives) {
2365
- if (!isTestPath(d.target)) {
2366
- findings.push({
2367
- 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`,
2368
- where: d.target,
2369
- });
2370
- continue;
2371
- }
2372
- try {
2373
- const abs = isAbsolute(d.target) ? d.target : join(cwd, d.target);
2374
- const content = readFileSync(abs, "utf-8");
2375
- if (content.includes(d.find)) {
2376
- // `String.replace` with a string pattern replaces the FIRST match exactly once.
2377
- writeFileSync(abs, content.replace(d.find, d.replace), "utf-8");
2378
- } else if (d.replace !== "" && content.includes(d.replace)) {
2379
- // Idempotent re-run: the find is gone but the replacement is present ⇒ the
2380
- // directive was already applied (e.g. a vet review-fix loop re-running
2381
- // reconcile). Treated as satisfied — reconcile must not fail on its own
2382
- // prior successful apply.
2383
- } else if (d.replace === "") {
2384
- // Idempotent re-run of a deletion: the find is gone and the replacement is
2385
- // empty ⇒ find-absent is the deletion's success condition (a prior successful
2386
- // apply removed it). Treated as satisfied — reconcile must not fail on its
2387
- // own prior successful apply (e.g. a validate-fix loop re-running reconcile).
2388
- } else {
2389
- findings.push({
2390
- 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`,
2391
- where: d.target,
2392
- });
2393
- }
2394
- } catch (err) {
2395
- findings.push({
2396
- detail: `reconcile: could not apply directive to ${d.target} — ${err instanceof Error ? err.message : String(err)}`,
2397
- where: d.target,
2398
- });
2399
- }
2400
- }
2401
- return findings;
2402
- };
2403
-
2404
- /**
2405
- * Deterministic post-implement reconciliation — the coherence backstop the
2406
- * parallel implement lane needs. Sibling phases run concurrently in one tree;
2407
- * each phase's own `#### Automated Verification:` passed in isolation, but a
2408
- * phase's correct change can invalidate a test that lives in a SIBLING phase's
2409
- * landed section (which the implementer may not edit), and the combined tree can
2410
- * break in ways no single phase's checks surface. `reconcile` runs after the
2411
- * scope floor (which proved the write-set) and before `validate`:
2412
- *
2413
- * 1. reads the latest plan (`latestFsArtifact(state, "plans")` — latest-wins);
2414
- * 2. parses every `#### Reconciliation` directive — fail-soft (a malformed
2415
- * directive / unreadable plan degrades to a finding, never a terminal
2416
- * `FAIL_SCRIPT_THREW` halt — a `produces.script` that throws becomes one);
2417
- * 3. applies each directive write-restricted to test paths (`isTestPath`); a
2418
- * present `find` is replaced exactly once (`String.replace`); an absent `find`
2419
- * whose replacement is ALSO absent is a finding (reconcile does not guess);
2420
- * 4. appends a timestamped `### Reconciliation Log (<iso>)` under the plan's
2421
- * `## Synthesis Notes` (best-effort bookkeeping write — non-fatal);
2422
- * 5. emits one `{ dimension: "reconcile" }` verdict, basename-keyed off the plan
2423
- * ⇒ idempotent across fix rounds (the verdict file is overwritten each round).
2424
- *
2425
- * Reconcile deliberately does NOT re-execute the plan's `#### Automated
2426
- * Verification:` commands. That re-run (bare `execFileSync`, no shell, exit-0
2427
- * contract) was measured across the full run history at zero genuine catches and
2428
- * a 100% false-positive finding rate — stale cross-phase presence probes, agent-
2429
- * shell-only binaries (`rg`), prose greps — each halting a finished run at a
2430
- * fail route with no fix arm. The downstream `validate` stage runs the same AV
2431
- * commands as an agent, with a real shell and the judgment to tell a legitimate
2432
- * post-rename mismatch from actual plan-vs-tree drift.
2433
- *
2434
- * The route is the `match("verdict", …, { from: "reconcile" })` gate idiom — pass ⇒
2435
- * validate, fail/missing ⇒ STOP (no fallback), mirroring `implementScopeCheck`.
2436
- * Mirrors `implementScopeCheck`'s `ScriptContext` shape, basename-keyed verdict
2437
- * path, and `dimension`/`pass`/`verdict`/`score`/`severity` data shape. `reads:
2438
- * ["plans"]` only — reconcile consumes no run-start `goal` baseline (the scope
2439
- * floor already proved the write-set; reconcile's own writes are directive targets
2440
- * + the plan bookkeeping). The `from` form suppresses the READS_DATA outputSchema
2441
- * lint, so no schema is declared (matching `slice-check`/`plan-cite-check`/
2442
- * `implement-scope-check`).
2443
- */
2444
- const reconcile = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
2445
- const latest = latestFsArtifact(state, "plans");
2446
- if (latest?.handle.kind !== "fs") {
2447
- throw haltPreflight(
2448
- "reconcile",
2449
- "reconcile: no plan to reconcile",
2450
- "reconcile: no fs artifact on the 'plans' channel — implement / scope-check must run before reconcile",
2451
- );
2452
- }
2453
- const planPath = latest.handle.path;
2454
- const planAbs = isAbsolute(planPath) ? planPath : join(cwd, planPath);
2455
- const findings: { detail: string; where: string }[] = [];
2456
-
2457
- // Fail-soft read + parse: an unreadable plan or malformed directive degrades
2458
- // to a finding, never a terminal throw. If the read fails there is nothing to
2459
- // apply.
2460
- let body = "";
2461
- let directives: ReconciliationDirective[] = [];
2462
- let malformed: string[] = [];
2463
- try {
2464
- body = readArtifactFile(planPath, cwd);
2465
- const parsed = reconciliationRecords(body);
2466
- directives = parsed.directives;
2467
- malformed = parsed.malformed;
2468
- } catch (err) {
2469
- findings.push({
2470
- detail: `reconcile: could not read or parse the plan ${planPath} — ${err instanceof Error ? err.message : String(err)}`,
2471
- where: planPath,
2472
- });
2473
- }
2474
- for (const m of malformed) {
2475
- findings.push({
2476
- detail: `reconcile: malformed Reconciliation directive — expected a line of the form: - \`<target>\`: replace \`<find>\` → \`<replace>\` (target/find/replace each backtick-wrapped) — ${m}`,
2477
- where: "reconciliation-directive",
2478
- });
2479
- }
2480
-
2481
- findings.push(...applyReconciliationDirectives(directives, cwd));
2482
-
2483
- // Best-effort bookkeeping: append a timestamped log under ## Synthesis Notes.
2484
- // Non-fatal — a write failure here is silent (the verdict below is the signal).
2485
- if (body) {
2486
- try {
2487
- const stamp = new Date().toISOString();
2488
- const verdict = findings.length === 0 ? "pass" : "fail";
2489
- const logBlock = `\n### Reconciliation Log (${stamp})\nApplied ${directives.length} directive(s); ${findings.length} finding(s); verdict: ${verdict}.\n`;
2490
- const heading = "## Synthesis Notes";
2491
- const idx = body.indexOf(heading);
2492
- let updated: string;
2493
- if (idx >= 0) {
2494
- const lineEnd = body.indexOf("\n", idx);
2495
- const at = lineEnd >= 0 ? lineEnd + 1 : body.length;
2496
- updated = body.slice(0, at) + logBlock + body.slice(at);
2497
- } else {
2498
- updated = `${body.replace(/\s+$/, "")}\n${logBlock}`;
2499
- }
2500
- writeFileSync(planAbs, updated, "utf-8");
2501
- } catch {
2502
- // bookkeeping — ignore
2503
- }
2504
- }
2505
-
2506
- const pass = findings.length === 0;
2507
- const data = {
2508
- dimension: "reconcile",
2509
- pass,
2510
- verdict: pass ? "pass" : "fail",
2511
- score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
2512
- severity: pass ? "none" : "high",
2513
- artifact: handleToString(latest.handle),
2514
- findings,
2515
- feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
2516
- };
2517
- // Basename-keyed off the latest plan ⇒ idempotent across fix rounds (mirrors
2518
- // implementScopeCheck / planCitationCheck, NOT round-stamped like grade).
2519
- const rel = join(VERDICT_DIR, `reconcile__${basename(planPath, ".md")}.json`);
2520
- mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
2521
- writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
2522
- return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
2523
- };
2524
-
2525
- /** A design filename encodes its slice as `…slice-<N>…` — the design-fanout naming convention. */
2526
- const DESIGN_SLICE_RE = /slice-(\d+)/;
2527
-
2528
- /**
2529
- * Map slice number → its design artifact path, from the design fanout's published
2530
- * outputs. An identity resolver: it maps an ARTIFACT to a slice NUMBER. It FAILS
2531
- * LOUD only when identity is genuinely UNRESOLVABLE — a design filename that
2532
- * carries no `slice-<N>` token, where a positional `idx + 1` guess would scramble
2533
- * the cluster→design wiring and drop slices.
2534
- *
2535
- * A slice claimed by MORE THAN ONE output is NOT ambiguous: the `designs` channel
2536
- * legitimately accumulates several entries per slice — `slice-design` emits it,
2537
- * then `design-review` re-emits the accepted/edited design on the SAME channel
2538
- * (its documented "latest-wins, same paths" contract, so `subplan`/`synthesize`
2539
- * read the accepted docs). So the newest entry wins, deterministically — throwing
2540
- * on a duplicate would halt every normal run at `subplan`. (The resume re-dispatch
2541
- * that once left CONFLICTING designs on the channel is fixed at its source,
2542
- * so there is no corruption left to fail loud on here.)
2543
- */
2544
- const designPathsBySlice = (state: RunView): Map<number, string> => {
2545
- const bySlice = new Map<number, string>();
2546
- for (const out of state.named.designs ?? []) {
2547
- for (const a of out.artifacts) {
2548
- if (a.handle.kind !== "fs") continue;
2549
- const name = basename(a.handle.path);
2550
- const match = DESIGN_SLICE_RE.exec(name);
2551
- if (!match) {
2552
- throw haltPreflight(
2553
- "designPathsBySlice",
2554
- `designPathsBySlice: design ${name} has no slice number`,
2555
- `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`,
2556
- );
2557
- }
2558
- // Latest design per slice wins — the channel holds multiple entries per
2559
- // slice by design (design-review re-emits), and the newest is authoritative.
2560
- bySlice.set(Number(match[1]), handleToString(a.handle));
2561
- }
2562
- }
2563
- return bySlice;
2564
- };
2565
-
2566
- /**
2567
- * Fan `subplan` out over slice-DAG clusters. Each unit merges ONE cluster's
2568
- * per-slice designs into a sub-plan (`--as-subplan`), so no single pass holds
2569
- * every design — the context-bounding twin of the flat fan-in `synthesize`.
2570
- */
2571
- const SYNTH_CLUSTER_FANOUT = fanout({
2572
- source: "designs",
2573
- unit: { by: "slice-dag-cluster", pattern: "clusters" },
2574
- max: MAX_PHASES,
2575
- units: ({ state, cwd }) => {
2576
- const doc = latestFsArtifact(state, "slices");
2577
- if (doc?.handle.kind !== "fs") return [];
2578
- const records = sliceRecords(readArtifactFile(doc.handle.path, cwd), "SYNTH_CLUSTER_FANOUT", doc.handle.path);
2579
- const designBySlice = designPathsBySlice(state);
2580
- // Thread the research the slices rest on into every cluster's subplan pass,
2581
- // so cross-slice constraints and acceptance criteria reach synthesis DIRECTLY
2582
- // (not only via each design's refraction). `synthesize` accepts `--research`
2583
- // in partial mode; the flat `synthesize` fan-in already received it, but the
2584
- // hierarchical cluster fanout dropped it.
2585
- const research = latestFsArtifact(state, "research");
2586
- const researchFlag = research?.handle.kind === "fs" ? ` --research ${handleToString(research.handle)}` : "";
2587
- return clusterSliceDag(records)
2588
- .map((cluster, i) => {
2589
- const designs = cluster
2590
- .map((n) => designBySlice.get(n))
2591
- .filter((p): p is string => p !== undefined)
2592
- .map((p) => `--designs ${p}`);
2593
- if (!designs.length) return undefined;
2594
- return {
2595
- // Stamp each cluster's ordinal into its prompt so the partial-mode pass
2596
- // writes a distinct `_cluster-<k>.md` — a re-dispatched unit must never
2597
- // reuse a sibling's filename and clobber it. `<k>` matches `id: cluster-<k>`.
2598
- prompt: `${designs.join(" ")}${researchFlag} --cluster ${i + 1} --as-subplan`,
2599
- label: `cluster ${i + 1} (slices ${cluster.join(",")})`,
2600
- id: `cluster-${i + 1}`,
2601
- };
2602
- })
2603
- .filter((u): u is { prompt: string; label: string; id: string } => u !== undefined);
2604
- },
2605
- });
2606
-
2607
- /**
2608
- * The two dimensions the grade panels anchor against the verbatim brief.
2609
- * "Complete" and "correct" MEAN "against what the user asked" — without the
2610
- * goal, completeness grades the plan against the plan's own claims. The other
2611
- * dimensions (and the slice gate's `design-readiness`) deliberately stay
2612
- * goal-blind: fit/actionability/pattern-following judge the artifact against
2613
- * the codebase, and an ambient goal at those seams invites scope inflation.
2614
- */
2615
- const GOAL_DIMENSIONS: ReadonlySet<string> = new Set(["completeness", "correctness"]);
2616
-
2617
- // ---------------------------------------------------------------------------
2618
- // Adaptive gate scaling — tier, roster, verdict freshness.
2619
- // ---------------------------------------------------------------------------
2620
-
2621
- /** Latest `data` record published under `name` (undefined when absent/non-record). */
2622
- const latestChannelData = (state: RunView, name: string): Record<string, unknown> | undefined => {
2623
- const data = state.named[name]?.at(-1)?.data;
2624
- return data !== null && typeof data === "object" && !Array.isArray(data)
2625
- ? (data as Record<string, unknown>)
2626
- : undefined;
2627
- };
2628
-
2629
- /** A finite numeric field off the latest `data` on `name` (undefined otherwise). */
2630
- const channelNumber = (state: RunView, name: string, field: string): number | undefined => {
2631
- const v = latestChannelData(state, name)?.[field];
2632
- return typeof v === "number" && Number.isFinite(v) ? v : undefined;
2633
- };
2634
-
2635
- /** Repo-relative path of the latest fs artifact on `name` (undefined if none). */
2636
- const latestArtifactPath = (state: RunView, name: string): string | undefined => {
2637
- const a = latestFsArtifact(state, name);
2638
- return a?.handle.kind === "fs" ? handleToString(a.handle) : undefined;
2639
- };
2640
-
2641
- /**
2642
- * Gate scrutiny tier, derived ONLY from signals already replayed by the resume
2643
- * fold (the slices/plans channels' frontmatter data and the gate's own verdict
2644
- * severities) — deterministic by construction, so routes and fanout units that
2645
- * consult it stay resume-safe.
2646
- *
2647
- * `risks:` flags are deliberately NOT a tier signal: `synthesize` declares
2648
- * them routinely (observed: 1-phase plans shipping 2-3 flags), so counting
2649
- * them would push every small run out of the light tier. Risk flags are
2650
- * already force-ruled per dimension via `risk_rulings`, and a blocking
2651
- * verdict lifts the tier on its own (below).
2652
- *
2653
- * A missing signal never yields light, and verdict severities are read over
2654
- * the FULL channel history (a stale medium/high is still evidence of a risky
2655
- * run) — ambiguity always resolves toward more scrutiny.
2656
- */
2657
- type GateTier = "light" | "standard" | "strict";
2658
- const TIER_LIGHT_MAX_SLICES = 1;
2659
- const TIER_LIGHT_MAX_PHASES = 2;
2660
- const TIER_STRICT_MIN_SLICES = 5;
2661
- const TIER_STRICT_MIN_PHASES = 6;
2662
-
2663
- /**
2664
- * The dimensions a light-tier run still grades: correctness and completeness
2665
- * are the two whose failures ship real defects (and the two that anchor on the
2666
- * goal); fit/actionability/pattern-following are low-consequence on a
2667
- * one-slice, <=2-phase diff, and `validate` still runs at every tier.
2668
- */
2669
- const LIGHT_ROSTER: ReadonlySet<string> = new Set(["correctness", "completeness"]);
2670
-
2671
- const gateTier = (state: RunView, verdictChannel: string): GateTier => {
2672
- const slices = channelNumber(state, "slices", "slice_count");
2673
- const phases = channelNumber(state, "plans", "phase_count");
2674
- const severities = new Set<string>();
2675
- for (const o of state.named[verdictChannel] ?? []) {
2676
- const v = o.data as { severity?: unknown; findings?: unknown } | undefined;
2677
- const s = v?.severity;
2678
- // Anchor-nit clamp: an all-drift-nit verdict must not escalate the tier.
2679
- if (typeof s === "string") severities.add(anchorNitsOnly(v) ? "low" : s);
2680
- }
2681
- if (
2682
- (slices !== undefined && slices >= TIER_STRICT_MIN_SLICES) ||
2683
- (phases !== undefined && phases >= TIER_STRICT_MIN_PHASES) ||
2684
- severities.has("high")
2685
- ) {
2686
- return "strict";
2687
- }
2688
- if (
2689
- slices !== undefined &&
2690
- slices <= TIER_LIGHT_MAX_SLICES &&
2691
- phases !== undefined &&
2692
- phases <= TIER_LIGHT_MAX_PHASES &&
2693
- !severities.has("medium")
2694
- ) {
2695
- return "light";
2696
- }
2697
- return "standard";
2698
- };
2699
-
2700
- /**
2701
- * The subset of `dimensions` the tier actually grades. Never empty: a
2702
- * dimension list with no light-roster member (the slice gate's lone
2703
- * `design-readiness`) keeps its full list at every tier.
2704
- */
2705
- const gateRoster = (tier: GateTier, dimensions: readonly string[]): readonly string[] => {
2706
- if (tier !== "light") return dimensions;
2707
- const light = dimensions.filter((d) => LIGHT_ROSTER.has(d));
2708
- return light.length > 0 ? light : dimensions;
2709
- };
2710
-
2711
- /**
2712
- * Drop verdicts judged against an artifact the channel has since REPLACED. A
2713
- * grade verdict embeds the `artifact` path it judged; when a fix REGENERATES
2714
- * the artifact (`slice-fix` re-slices to a NEW file) a passing verdict on the
2715
- * old document must not carry forward to a document that was never judged —
2716
- * the carry-forward would otherwise let a regenerated slice map skip its
2717
- * design-readiness judgment entirely. An in-place `amend` keeps the path, so
2718
- * the plan-fix/code-fix carry-forward is unaffected. A verdict without an
2719
- * `artifact` field (older trails, the deterministic structure checks) is kept:
2720
- * matching is the compat default.
2721
- */
2722
- const freshVerdicts = (entries: readonly Output[] = [], currentArtifact?: string): readonly Output[] => {
2723
- if (!currentArtifact) return entries;
2724
- const current = basename(currentArtifact);
2725
- return entries.filter((o) => {
2726
- const a = (o.data as { artifact?: unknown } | undefined)?.artifact;
2727
- return typeof a !== "string" || a.length === 0 || basename(a) === current;
2728
- });
2729
- };
2730
-
2731
- /**
2732
- * Latest verdict per dimension off an accumulated verdict channel — the shared
2733
- * fold under `dimensionsToRegrade` (which dimensions still block) and the
2734
- * confirm panels' `--prior` threading (which verdict file the confirming
2735
- * grader must adjudicate).
2736
- */
2737
- const latestVerdictPerDimension = (entries: readonly Output[] = []): Map<string, Output> => {
2738
- const latest = new Map<string, Output>();
2739
- for (const o of entries) {
2740
- const dim = (o.data as { dimension?: unknown } | undefined)?.dimension;
2741
- if (typeof dim === "string") latest.set(dim, o);
2742
- }
2743
- return latest;
2744
- };
2745
-
2746
- /**
2747
- * Anchor-drift-nit phrasing, two tiers: only phrasings naming drift itself
2748
- * count standalone; the location shapes (off-by-N, "is at line N", "line N is
2749
- * the/a") also match REAL defects ("line 42 is a comment that falsely claims
2750
- * X", "the loop bound is off by one") and count ONLY alongside citing-context
2751
- * vocabulary — every observed drift nit has it, real-defect phrasings don't.
2752
- * Do NOT widen, and do NOT promote a location shape to standalone.
2753
- */
2754
- const ANCHOR_NIT_DRIFT_RE = /\bdrifted?\s+~?\d+\s+lines?\b|\bcitation (?:is )?drifted\b/i;
2755
- const ANCHOR_NIT_LOCATION_RE =
2756
- /\boff[- ]by[- ](?:one|two|three|\d+)\b|(?::\d+|\bline \d+) is (?:the|a)\b|\bis at line \d+\b/i;
2757
- const ANCHOR_NIT_CITE_CONTEXT_RE = /\bcit(?:es?|ed|ation)\b|\banchor/i;
2758
-
2759
- const isAnchorNitDetail = (detail: string): boolean =>
2760
- ANCHOR_NIT_DRIFT_RE.test(detail) || (ANCHOR_NIT_LOCATION_RE.test(detail) && ANCHOR_NIT_CITE_CONTEXT_RE.test(detail));
2761
-
2762
- /**
2763
- * TRUE when a verdict carries ≥1 finding and EVERY finding is an anchor-drift
2764
- * nit (`isAnchorNitDetail`). Such a verdict is severity-clamped to non-blocking
2765
- * at the gate fold regardless of the grader's own `severity` — line-number
2766
- * drift was measured at 34% of all grader findings with zero downstream harm,
2767
- * and a mis-rated all-nit `medium` verdict buys a full fix round + re-grade
2768
- * panel that repairs nothing. A verdict mixing a drift nit with ANY other
2769
- * finding is untouched — the other finding may be the real blocker.
2770
- */
2771
- const anchorNitsOnly = (v: { findings?: unknown } | undefined): boolean => {
2772
- const findings = Array.isArray(v?.findings) ? v.findings : [];
2773
- return (
2774
- findings.length > 0 &&
2775
- findings.every((f) => {
2776
- const detail = (f as { detail?: unknown } | undefined)?.detail;
2777
- return typeof detail === "string" && isAnchorNitDetail(detail);
2778
- })
2779
- );
2780
- };
2781
-
2782
- /**
2783
- * The subset of `dimensions` a re-grade must actually re-run, given the latest
2784
- * verdict per dimension accumulated so far. A dimension needs re-grading when it
2785
- * has NO prior verdict (first pass ⇒ grade every dimension), when its latest
2786
- * verdict fails above the severity floor, or when that verdict ruled any plan
2787
- * risk flag `fail` (the ruling is re-opened by re-grading its owning dimension).
2788
- * A dimension that already passed — dimension AND its risk rulings — is carried
2789
- * forward untouched: re-running it after a surgical fix only re-rolls a free LLM
2790
- * judgment that flaps pass↔fail on an unchanged artifact, manufacturing extra
2791
- * loops (the observed correctness risk-flag flap). The accumulating verdict
2792
- * channel + `allDimensionsPass`'s latest-per-dimension fold mean a carried
2793
- * dimension's prior passing verdict still counts at the gate.
2794
- */
2795
- const dimensionsToRegrade = (
2796
- dimensions: readonly string[],
2797
- latest: ReadonlyMap<string, Output>,
2798
- risks: ReadonlyMap<string, RiskRecord> = new Map(),
2799
- ): string[] => {
2800
- return dimensions.filter((d) => {
2801
- const o = latest.get(d);
2802
- if (!o) return true; // never graded — must grade at least once
2803
- const v = o.data as { pass?: boolean; severity?: string; findings?: unknown } | undefined;
2804
- const dimPass = v?.pass === true || v?.severity === "low" || v?.severity === "none" || anchorNitsOnly(v);
2805
- if (!dimPass) return true;
2806
- return verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
2807
- });
2808
- };
2809
-
2810
- /**
2811
- * Coarse line-count backstop for the surgical-fix guard. The subset test
2812
- * (`touchedSections − HOUSEKEEPING ⊆ cited`) is the binding constraint — do
2813
- * NOT tighten this to compensate for a weak subset test.
2814
- */
2815
- const NON_SURGICAL_DIFF_LINE_THRESHOLD = 60;
2816
-
2817
- /**
2818
- * Plan sections amend ALWAYS bumps without the fix touching their meaning —
2819
- * the pseudo-section `frontmatter` (via the `last_updated` field). Exempt from
2820
- * the "touched outside cited" test. Starts at `{frontmatter}` only; do not
2821
- * pre-widen (a genuinely-meaningful bookkeeping section would let a broad amend
2822
- * pass the subset test by touching it).
2823
- */
2824
- const HOUSEKEEPING_SECTIONS: ReadonlySet<string> = new Set(["frontmatter"]);
2825
-
2826
- /** Directory the snapshot stages copy the pre-fix plan into (basename-keyed). */
2827
- const PRIOR_DIR = ".rpiv/artifacts/priors";
2828
-
2829
- /**
2830
- * Map each line index to its plan-section name: the nearest preceding `## `
2831
- * heading — `## Phase N: …` normalizes to `phase N` (case-insensitive); any
2832
- * other heading is lowercased by tail — so touched-section keys and cited-section
2833
- * keys share one space. The frontmatter block (opening `---` through its closing
2834
- * `---`) is the pseudo-section `frontmatter`. Lines before the first heading and
2835
- * outside frontmatter map to `""` (which is neither housekeeping nor a `phase N`
2836
- * cite, so any change there is treated as out-of-scope).
2837
- */
2838
- const sectionIndexOf = (lines: readonly string[]): string[] => {
2839
- const idx = new Array<string>(lines.length);
2840
- let current = "";
2841
- let inFrontmatter = lines[0]?.trim() === "---";
2842
- for (let i = 0; i < lines.length; i++) {
2843
- if (inFrontmatter) {
2844
- idx[i] = "frontmatter";
2845
- if (i > 0 && lines[i].trim() === "---") inFrontmatter = false;
2846
- continue;
2847
- }
2848
- const m = /^##\s+(.*)$/.exec(lines[i]);
2849
- if (m) {
2850
- const ph = /^Phase\s+(\d+)/i.exec(m[1].trim());
2851
- current = ph ? `phase ${ph[1]}` : m[1].trim().toLowerCase();
2852
- }
2853
- idx[i] = current;
2854
- }
2855
- return idx;
2856
- };
2857
-
2858
- /**
2859
- * Line-level diff of `prior` vs `current` plan bodies, mapped to plan sections.
2860
- * Each changed line (a deletion from `prior` OR an insertion in `current` under
2861
- * an LCS match) is attributed to its nearest preceding `## ` heading in its own
2862
- * document. Returns the union of touched section keys and a coarse changed-line
2863
- * count (deletions + insertions). Insertion-tolerant: a 1-line insert does not
2864
- * mark every trailing line changed (the LCS keeps shared context matched).
2865
- */
2866
- const sectionDiff = (prior: string, current: string): { touchedSections: Set<string>; changedLines: number } => {
2867
- const a = prior.split("\n");
2868
- const b = current.split("\n");
2869
- const sa = sectionIndexOf(a);
2870
- const sb = sectionIndexOf(b);
2871
- // LCS length table (bottom-up). Plans are a few hundred lines ⇒ O(n·m) trivial.
2872
- const dp: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
2873
- for (let i = a.length - 1; i >= 0; i--) {
2874
- for (let j = b.length - 1; j >= 0; j--) {
2875
- dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
2876
- }
2877
- }
2878
- const touched = new Set<string>();
2879
- let changed = 0;
2880
- let i = 0;
2881
- let j = 0;
2882
- while (i < a.length && j < b.length) {
2883
- if (a[i] === b[j]) {
2884
- i++;
2885
- j++;
2886
- } else if (dp[i + 1][j] >= dp[i][j + 1]) {
2887
- touched.add(sa[i]); // a[i] deleted (present in prior, absent in current)
2888
- changed++;
2889
- i++;
2890
- } else {
2891
- touched.add(sb[j]); // b[j] inserted (present in current, absent in prior)
2892
- changed++;
2893
- j++;
2894
- }
2895
- }
2896
- while (i < a.length) {
2897
- touched.add(sa[i]);
2898
- changed++;
2899
- i++;
2900
- }
2901
- while (j < b.length) {
2902
- touched.add(sb[j]);
2903
- changed++;
2904
- j++;
2905
- }
2906
- return { touchedSections: touched, changedLines: changed };
2907
- };
2908
-
2909
- /**
2910
- * Plan sections cited by the FAILING dimensions' findings — extracted from each
2911
- * finding's `where` and `detail` (`Phase N` → `phase N`, lowercased). Preferred
2912
- * `where: "Phase 1 > lane-dock-editor.ts Edit 1"` → `phase 1`; a repo
2913
- * `path:line`-only `where` (and a detail with no `Phase N`) contributes NO plan
2914
- * section. Empty when no failing finding carries an extractable plan-section
2915
- * reference — fail-closed: the caller treats an empty cite set against any
2916
- * non-housekeeping touched section as out-of-scope (non-surgical).
2917
- */
2918
- const citedSections = (latest: ReadonlyMap<string, Output>, pending: readonly string[]): Set<string> => {
2919
- const cited = new Set<string>();
2920
- for (const d of pending) {
2921
- const findings = (latest.get(d)?.data as { findings?: unknown } | undefined)?.findings;
2922
- if (!Array.isArray(findings)) continue;
2923
- for (const f of findings) {
2924
- if (f == null || typeof f !== "object") continue;
2925
- const where = typeof (f as { where?: unknown }).where === "string" ? (f as { where: string }).where : "";
2926
- const detail = typeof (f as { detail?: unknown }).detail === "string" ? (f as { detail: string }).detail : "";
2927
- for (const text of [where, detail]) {
2928
- for (const m of text.matchAll(/Phase\s+(\d+)/gi)) cited.add(`phase ${m[1]}`);
2929
- }
2930
- }
2931
- }
2932
- return cited;
2933
- };
2934
-
2935
- /**
2936
- * The prior-role `fs` artifact the snapshot stage published on `priorChannel`
2937
- * (undefined when the channel carries no prior — round 1 / first re-grade).
2938
- * Existence of the ENTRY is distinct from readability of the sidecar: an entry
2939
- * that exists but cannot be read still counts as "prior present" so the caller
2940
- * fails closed to a FULL roster rather than silently carrying forward.
2941
- */
2942
- const priorArtifact = (state: RunView, priorChannel: string): Artifact | undefined => {
2943
- const entry = state.named[priorChannel]?.at(-1);
2944
- const prior = entry?.artifacts.find((a) => a.handle.kind === "fs" && a.role === "prior");
2945
- return prior?.handle.kind === "fs" ? prior : undefined;
2946
- };
2947
-
2948
- /**
2949
- * Read the prior sidecar's bytes off `priorChannel`. Returns `undefined` when
2950
- * the channel is empty, the prior artifact is not fs, OR the sidecar is
2951
- * unreadable — the caller treats `undefined` as fail-closed (non-surgical).
2952
- */
2953
- const latestPriorContent = (state: RunView, priorChannel: string, cwd: string): string | undefined => {
2954
- const prior = priorArtifact(state, priorChannel);
2955
- if (prior?.handle.kind !== "fs") return undefined;
2956
- try {
2957
- return readArtifactFile(prior.handle.path, cwd);
2958
- } catch {
2959
- return undefined;
2960
- }
2961
- };
96
+ // ===========================================================================
97
+ // polish — architecture-review → blueprint (iterate, per review phase) →
98
+ // implement → validate → code-review → (blueprint loop) | commit
99
+ // For a large architecture review that can't be planned in one pass:
100
+ // plan each review phase sequentially, each plan building on the
101
+ // ones before it, then implement/validate/review the lot.
102
+ // ===========================================================================
2962
103
 
2963
104
  /**
2964
- * True ONLY when a readable prior exists AND the current plan's diff from it
2965
- * touches ONLY sections a failing finding cited (minus housekeeping) AND the
2966
- * changed-line count is within the coarse threshold. Every missing signal — no
2967
- * prior, unreadable sidecar, unreadable current plan, a diff/parse throw, a
2968
- * touched section no failing finding cited, or an over-threshold diff —
2969
- * collapses to `false` (fail-closed ⇒ the caller re-grades the full roster
2970
- * when a prior is present, or carries forward when none is). `pending` is
2971
- * consumed as-is: whatever `dimensionsToRegrade` ruled still-blocking (after
2972
- * phase 3's `rulingEffectivePass` clause-3 rewrite) is the set this guard
2973
- * narrows on.
105
+ * Hand the single validate session EVERY plan from the latest blueprint pass
106
+ * (`latestPlans`). The runner's default rolling-primary — and a plain
107
+ * `reads: ["plans"]`, which only reads `.at(-1)` — would point validate at the
108
+ * LAST plan alone, leaving earlier phases unvalidated. A `prompt` stage owns
109
+ * its whole message, so the `/skill:validate` prefix is explicit.
2974
110
  */
2975
- const isSurgicalFix = (
2976
- state: RunView,
2977
- priorChannel: string,
2978
- cwd: string,
2979
- target: string,
2980
- latest: ReadonlyMap<string, Output>,
2981
- pending: readonly string[],
2982
- ): boolean => {
2983
- const prior = latestPriorContent(state, priorChannel, cwd);
2984
- if (prior === undefined) return false;
2985
- let current: string;
2986
- try {
2987
- current = readArtifactFile(target, cwd);
2988
- } catch {
2989
- return false;
2990
- }
2991
- let diff: { touchedSections: Set<string>; changedLines: number };
2992
- try {
2993
- diff = sectionDiff(prior, current);
2994
- } catch {
2995
- return false;
2996
- }
2997
- const cited = citedSections(latest, pending);
2998
- for (const section of diff.touchedSections) {
2999
- if (HOUSEKEEPING_SECTIONS.has(section)) continue;
3000
- if (!cited.has(section)) return false;
3001
- }
3002
- return diff.changedLines <= NON_SURGICAL_DIFF_LINE_THRESHOLD;
111
+ const VALIDATE_PLANS_PROMPT: PromptFn = ({ state, cwd }) => {
112
+ const paths = latestPlans(state, cwd)
113
+ .flatMap((o) => o.artifacts)
114
+ .filter((a) => a.handle.kind === "fs")
115
+ .map((a) => handleToString(a.handle));
116
+ return `/skill:validate ${paths.join(" ")}`;
3003
117
  };
3004
118
 
3005
- /**
3006
- * A grade panel: one `grade` session per dimension over the latest artifact on
3007
- * `channel`. Each unit's prompt is the `grade` skill's flags
3008
- * (`--dimension <d> --artifact <path>`); the per-dimension verdicts fold via
3009
- * `allDimensionsPass`. Shared by the slice gate (over `slices`) and the plan +
3010
- * code gates (over `plans`), each on its own `verdictChannel`.
3011
- *
3012
- * The panel grades the tier's ROSTER (`gateTier`/`gateRoster`), over verdicts
3013
- * still FRESH for the current artifact (`freshVerdicts`) — a light run grades
3014
- * two dimensions, a regenerated artifact re-grades from scratch. On a re-grade
3015
- * it emits ONLY the dimensions `dimensionsToRegrade` says still need it (the
3016
- * rest carry their prior passing verdict forward) — but never an EMPTY set: an
3017
- * empty `units()` return falls through to a single dimensionless `grade`
3018
- * dispatch, so when nothing needs re-grading we fall back to the full roster.
3019
- * The route into the stage already skips it entirely when the accumulated
3020
- * verdicts clear the gate (see `plan-cite-check`/`code-cite-check`/`slice-check`
3021
- * edges), so this fallback only fires in the degenerate case where a fix left the
3022
- * cite floor red while every dimension passed.
3023
- *
3024
- * `architecture-fit` is the one dimension `grade` requires a `--context` for: it
3025
- * grades the plan against the research the slices rest on. The build flow always
3026
- * front-loads a `research` stage, so we thread the latest `research` artifact in
3027
- * as `--context` for that dimension only; likewise the latest `goal` artifact
3028
- * threads in as `--goal` for the `GOAL_DIMENSIONS` only. Every other dimension
3029
- * (and the slice gate's `design-readiness`, which never grades fit or
3030
- * goal-completeness) gets the bare flags.
3031
- *
3032
- * A CONFIRM panel (`confirm: true`) additionally threads each still-blocking
3033
- * dimension's latest verdict in as `--prior`: the confirming grader must
3034
- * adjudicate the prior round's findings — uphold or refute each with cited
3035
- * evidence — instead of silently out-voting them (a blind second opinion once
3036
- * rationalized past a checkable fact and its pass overwrote a correct fail at
3037
- * the latest-per-dimension fold). Only PENDING dimensions get the flag: in the
3038
- * degenerate full-roster fallback a carried passing verdict has nothing to
3039
- * adjudicate, and a first grade has no prior at all.
3040
- */
3041
- const gradePanelFanout = (
3042
- channel: string,
3043
- dimensions: readonly string[],
3044
- verdictChannel: string,
3045
- { confirm = false, priorChannel }: { confirm?: boolean; priorChannel?: string } = {},
3046
- ) =>
3047
- fanout({
3048
- source: channel,
3049
- unit: { by: "dimension-list", pattern: "dimensions" },
3050
- max: dimensions.length,
3051
- units: ({ state, cwd }) => {
3052
- const doc = latestFsArtifact(state, channel);
3053
- if (doc?.handle.kind !== "fs") return [];
3054
- const target = handleToString(doc.handle);
3055
- const research = latestFsArtifact(state, "research");
3056
- const contextFlag = research?.handle.kind === "fs" ? ` --context ${handleToString(research.handle)}` : "";
3057
- const goal = latestFsArtifact(state, "goal");
3058
- const goalFlag = goal?.handle.kind === "fs" ? ` --goal ${handleToString(goal.handle)}` : "";
3059
- const roster = gateRoster(gateTier(state, verdictChannel), dimensions);
3060
- const latest = latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel], target));
3061
- const risks = planAuthoredRisks(state, channel);
3062
- const pending = dimensionsToRegrade(roster, latest, risks);
3063
- // Delta re-grade fallback guard (plan/code gates only — `priorChannel`
3064
- // is unset for the slice gate and both confirm panels). When the snapshot
3065
- // stage published a prior, compare it to the current plan: a SURGICAL
3066
- // amend (touched only sections a failing finding cited, ≤ threshold
3067
- // lines) re-grades only the still-pending dimensions; a NON-surgical
3068
- // amend (broad / out-of-scope / over-threshold / unreadable / unparseable)
3069
- // re-grades the FULL roster — a broad amend may have regressed a passing
3070
- // dimension the carry-forward would otherwise trust. With NO prior
3071
- // (round 1 / first re-grade) the carry-forward applies unchanged. See
3072
- // `isSurgicalFix` for the fail-closed contract.
3073
- const surgical =
3074
- !confirm && priorChannel !== undefined && isSurgicalFix(state, priorChannel, cwd, target, latest, pending);
3075
- const priorPresent = priorChannel !== undefined && priorArtifact(state, priorChannel) !== undefined;
3076
- const priorFlag = (d: string): string => {
3077
- if (!confirm || !pending.includes(d)) return "";
3078
- const handle = latest.get(d)?.artifacts.find((a) => a.handle.kind === "fs")?.handle;
3079
- return handle ? ` --prior ${handleToString(handle)}` : "";
3080
- };
3081
- const carryForward = pending.length > 0 ? pending : roster;
3082
- // A non-surgical result WITH a prior present re-grades the FULL roster;
3083
- // with NO prior the carry-forward applies (never an empty unit set —
3084
- // empty ⇒ single dimensionless grade fall-through).
3085
- const toGrade = surgical ? carryForward : priorPresent ? roster : carryForward;
3086
- return toGrade.map((d) => ({
3087
- prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}${priorFlag(d)}`,
3088
- label: d,
3089
- id: `${channel}-dim-${d}`,
3090
- }));
3091
- },
3092
- });
3093
-
3094
- const SLICE_DIMENSION_FANOUT = gradePanelFanout("slices", SLICE_DIMENSIONS, "slice-verdicts");
3095
- const PLAN_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts", {
3096
- priorChannel: "plan-snapshot",
3097
- });
3098
- // The post-splice code gate re-grades the SAME `plans` artifact on its own
3099
- // `code-verdicts` channel, so its carry-forward reads the code gate's verdicts,
3100
- // never the pre-elaborate plan gate's.
3101
- const CODE_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts", {
3102
- priorChannel: "code-snapshot",
3103
- });
3104
- // The confirm stages re-run the SAME panel machinery on the SAME verdict
3105
- // channel: with the failing dimensions the only ones pending, the panel emits
3106
- // exactly the blocking dimensions — one second judgment each, in confirm mode:
3107
- // each unit carries the blocking verdict as `--prior`, and the grade skill is
3108
- // contract-bound to rule on every prior finding (uphold, or refute with cited
3109
- // evidence) so a confirming pass records WHY the fail died instead of silently
3110
- // out-voting it at the latest-per-dimension fold.
3111
- // Distinct fanout instances (not aliases) so each stage owns its loop object.
3112
- const PLAN_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts", { confirm: true });
3113
- const CODE_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts", { confirm: true });
3114
-
3115
- /**
3116
- * Ship's grade panel — a bespoke `fanout({...})` mirroring `gradePanelFanout`'s
3117
- * body but binding the roster to `SHIP_DIMENSIONS` DIRECTLY (no
3118
- * `gateRoster(gateTier(...))` wrap) and dropping the confirm / `priorChannel`
3119
- * / surgical-fix machinery ship's single-pass grade does not carry. Kept: the
3120
- * `latestFsArtifact` guard (no plan → no units), the dimension-keyed
3121
- * `--context` (architecture-fit only, sourced from the front-loaded `research`
3122
- * artifact), the `--goal` flag for `GOAL_DIMENSIONS` (completeness/
3123
- * correctness), and the `freshVerdicts` / `latestVerdictPerDimension` /
3124
- * `dimensionsToRegrade` carry-forward so a re-grade emits only still-pending
3125
- * dimensions. Tier-independence is structural: the roster never shrinks, so a
3126
- * light run still grades `architecture-fit`. Ship-only addition: the
3127
- * correctness unit carries `--cite-check <verdict>` when the deterministic
3128
- * citation floor recorded findings — advisory by construction here, since a
3129
- * blocking finding STOPs at the cite gate before grade ever runs — so the
3130
- * grader adjudicates them rather than leaving them unread.
3131
- */
3132
- export const SHIP_DIMENSION_FANOUT = fanout({
3133
- source: "plans",
3134
- unit: { by: "dimension-list", pattern: "dimensions" },
3135
- max: SHIP_DIMENSIONS.length,
3136
- units: ({ state }) => {
3137
- const doc = latestFsArtifact(state, "plans");
3138
- if (doc?.handle.kind !== "fs") return [];
3139
- const target = handleToString(doc.handle);
3140
- const research = latestFsArtifact(state, "research");
3141
- const contextFlag = research?.handle.kind === "fs" ? ` --context ${handleToString(research.handle)}` : "";
3142
- const goal = latestFsArtifact(state, "goal");
3143
- const goalFlag = goal?.handle.kind === "fs" ? ` --goal ${handleToString(goal.handle)}` : "";
3144
- // The floor's findings (advisory by construction — see the fanout doc
3145
- // above) thread as `--cite-check`; no findings ⇒ no flag.
3146
- const cite = latestFsArtifact(state, "plan-cite-check");
3147
- const citeFindings = (state.named["plan-cite-check"]?.at(-1)?.data as { findings?: unknown[] } | undefined)
3148
- ?.findings;
3149
- const citeFlag =
3150
- cite?.handle.kind === "fs" && Array.isArray(citeFindings) && citeFindings.length > 0
3151
- ? ` --cite-check ${handleToString(cite.handle)}`
3152
- : "";
3153
- // Tier-independent roster: SHIP_DIMENSIONS verbatim — never gateRoster(gateTier(...)).
3154
- const roster = SHIP_DIMENSIONS;
3155
- const latest = latestVerdictPerDimension(freshVerdicts(state.named["ship-verdicts"], target));
3156
- const risks = planAuthoredRisks(state, "plans");
3157
- const pending = dimensionsToRegrade(roster, latest, risks);
3158
- const carryForward = pending.length > 0 ? pending : roster;
3159
- return carryForward.map((d) => ({
3160
- prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}${d === "correctness" ? citeFlag : ""}`,
3161
- label: d,
3162
- id: `plans-dim-${d}`,
3163
- }));
119
+ const polishWorkflow = defineWorkflow({
120
+ name: "polish",
121
+ description:
122
+ "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.",
123
+ start: "architecture-review",
124
+ stages: {
125
+ "architecture-review": produces(),
126
+ blueprint: produces({ loop: REVIEW_PHASE_ITERATE }),
127
+ implement: acts({ loop: IMPLEMENT_PLANS_FANOUT, reads: ["plans"] }),
128
+ validate: produces({ prompt: VALIDATE_PLANS_PROMPT }),
129
+ "code-review": produces(),
130
+ commit: acts({ outcome: gitCommitOutcome }),
131
+ },
132
+ edges: {
133
+ "architecture-review": "blueprint",
134
+ blueprint: "implement",
135
+ implement: "validate",
136
+ validate: "code-review",
137
+ // Backward edge: code-review → blueprint re-plans (implement needs a plan).
138
+ // The iterate stage re-runs over every review phase; bounded by the
139
+ // runner's default maxBackwardJumps (3 → up to 4 review iterations).
140
+ "code-review": gate("blockers_count", { blueprint: gt(0), commit: eq(0) }, "commit"),
141
+ commit: "stop",
3164
142
  },
3165
143
  });
3166
144
 
3167
- /**
3168
- * Fold the per-dimension verdicts into a gate decision: keep the latest verdict
3169
- * per dimension (verdicts accumulate across fix loops), require all-pass.
3170
- * Deterministic ⇒ resume-safe for a `readsData: false` route.
3171
- *
3172
- * Severity floor: a verdict whose worst finding is `low`/`none` never blocks the
3173
- * gate, even when the grader set `pass: false` on a nit. `grade` decides `pass`
3174
- * by a free judgment against a prose bar (independent of `severity`), so a
3175
- * marginal dimension can flip pass↔fail across rounds on an unchanged artifact —
3176
- * that flapping, ANDed over a 5-dimension panel, stalled the build gate loops
3177
- * until the backward-jump guard halted them. Flooring on severity reserves a hard
3178
- * fail for `medium`+ findings (the deterministic `slice-check` check emits
3179
- * `high` on a real structural break, so it still blocks). A verdict with no
3180
- * `severity` (an older or replayed grade) falls back to the raw `pass` boolean.
3181
- */
3182
- const allDimensionsPass = (entries: readonly Output[] = [], roster?: readonly string[]): boolean => {
3183
- // Roster-filtered when given: a verdict for a dimension outside the tier's
3184
- // roster (a wider earlier round, a shrunk re-slice) neither blocks nor passes
3185
- // a gate it no longer governs.
3186
- const member = roster ? new Set(roster) : undefined;
3187
- const latest = new Map<string, boolean>();
3188
- for (const o of entries) {
3189
- const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
3190
- if (typeof v?.dimension !== "string") continue;
3191
- if (member && !member.has(v.dimension)) continue;
3192
- // The anchor-nit clamp: an all-drift-nit verdict never blocks, whatever
3193
- // severity the grader typed (backstop for the citation-resolution rule).
3194
- const lowOrNone = v.severity === "low" || v.severity === "none" || anchorNitsOnly(v);
3195
- latest.set(v.dimension, v.pass === true || lowOrNone);
3196
- }
3197
- const verdicts = [...latest.values()];
3198
- return verdicts.length > 0 && verdicts.every(Boolean);
3199
- };
3200
-
3201
- /**
3202
- * One plan-authored risk flag ruled by a grade panel. The plan declares a
3203
- * `risks:` frontmatter array (`{ id, claim }`) — the structured, first-class
3204
- * channel that replaces the old prose-in-a-Notes-section flagging that graders
3205
- * were free to skip. Each grade verdict that engages a flag emits a ruling here.
3206
- */
3207
- interface RiskRuling {
3208
- id: string;
3209
- pass: boolean;
3210
- /**
3211
- * `mechanics` marks a risk whose `pass` asserts a verified mechanism (a
3212
- * behavior that holds because code was checked), so a passing ruling MUST
3213
- * cite the checked `file:line` in `evidence` — an un-evidenced mechanics
3214
- * pass demotes. Absent on
3215
- * an ordinary risk ⇒ no evidence duty.
3216
- */
3217
- claim_type?: string;
3218
- /** The `file:line`-shaped citation a mechanics pass must ground itself on. */
3219
- evidence?: string;
3220
- /**
3221
- * `verify-at-implement` marks a risk the panel defers: ruled `pass` ONLY when
3222
- * a concrete `procedure` + `owner` phase will re-check it at implement/validate
3223
- * time. Absent ⇒ the risk is judged in this panel, not deferred.
3224
- */
3225
- disposition?: string;
3226
- /** Named command/test the owner phase runs to discharge a deferred risk. */
3227
- procedure?: string;
3228
- /** The phase (`n`) that owns the deferred verify step. */
3229
- owner?: number;
3230
- }
3231
-
3232
- /** The `risk_rulings` a grade verdict emitted (empty when it ruled on none). */
3233
- const verdictRiskRulings = (o: Output): RiskRuling[] => {
3234
- const raw = (o.data as { risk_rulings?: unknown } | undefined)?.risk_rulings;
3235
- if (!Array.isArray(raw)) return [];
3236
- return raw.flatMap((e) => {
3237
- const r = (e ?? {}) as Record<string, unknown>;
3238
- if (typeof r.id !== "string") return [];
3239
- // Read the duty fields defensively (same typeof-guard idiom as id/pass):
3240
- // absent on an older/ordinary verdict ⇒ undefined ⇒ the duty helpers no-op.
3241
- const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
3242
- const evidence = typeof r.evidence === "string" ? r.evidence : undefined;
3243
- const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
3244
- const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
3245
- const owner = typeof r.owner === "number" ? r.owner : undefined;
3246
- return [
3247
- {
3248
- id: r.id,
3249
- pass: r.pass === true,
3250
- ...(claim_type !== undefined ? { claim_type } : {}),
3251
- ...(evidence !== undefined ? { evidence } : {}),
3252
- ...(disposition !== undefined ? { disposition } : {}),
3253
- ...(procedure !== undefined ? { procedure } : {}),
3254
- ...(owner !== undefined ? { owner } : {}),
3255
- },
3256
- ];
3257
- });
3258
- };
3259
-
3260
- /**
3261
- * A plan-authored risk flag — the duty shape `synthesize` declares in the plan
3262
- * frontmatter `risks:` array (`synthesize/SKILL.md:136`: `{ id, claim,
3263
- * claim_type?, disposition?, procedure?, owner? }`). The prose `claim` is grading
3264
- * copy, not a duty signal, so it is not carried here. `claim_type: "mechanics"`
3265
- * and `disposition: "verify-at-implement"` are the two duty TRIGGERS — sourced
3266
- * from the PLAN (not the ruling) so a panel cannot drop its discharge obligation
3267
- * by simply omitting the field from its ruling (the dropped-duty bypass).
3268
- */
3269
- interface RiskRecord {
3270
- id: string;
3271
- claim_type?: string;
3272
- disposition?: string;
3273
- procedure?: string;
3274
- owner?: number;
3275
- }
3276
-
3277
- /**
3278
- * Read the plan-authored risk flags off the latest record on `channel`, keyed
3279
- * by `id`. The duty triggers live HERE (the plan's `risks:` frontmatter), not on
3280
- * the grade panel's ruling, so a ruling that drops its discharge field cannot
3281
- * escape the duty the plan declared (a bare `{ id, pass }` ruling against a
3282
- * plan-authored `claim_type: "mechanics"` risk still demotes). Reads only
3283
- * `state.named[channel]` via `latestChannelData` — no `readFileSync`, no
3284
- * `cwd`, no throw — so the route's `readsData: false` / determinism /
3285
- * resume-safety contract holds and a resumed run re-evaluates identically.
3286
- * Degrades to an empty map (fail-open ⇒ no duty ⇒ plain ruling ⇒
3287
- * `rulingEffectivePass(r) === r.pass`) when `risks:` is absent/non-array/
3288
- * malformed, mirroring `latestChannelData`'s degrade-to-undefined contract.
3289
- */
3290
- const planAuthoredRisks = (state: RunView, channel: string): Map<string, RiskRecord> => {
3291
- const risks = latestChannelData(state, channel)?.risks;
3292
- const out = new Map<string, RiskRecord>();
3293
- if (!Array.isArray(risks)) return out;
3294
- for (const e of risks) {
3295
- const r = (e ?? {}) as Record<string, unknown>;
3296
- if (typeof r.id !== "string") continue;
3297
- const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
3298
- const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
3299
- const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
3300
- const owner = typeof r.owner === "number" ? r.owner : undefined;
3301
- const rec: RiskRecord = { id: r.id };
3302
- if (claim_type !== undefined) rec.claim_type = claim_type;
3303
- if (disposition !== undefined) rec.disposition = disposition;
3304
- if (procedure !== undefined) rec.procedure = procedure;
3305
- if (owner !== undefined) rec.owner = owner;
3306
- out.set(r.id, rec);
3307
- }
3308
- return out;
3309
- };
3310
-
3311
- /**
3312
- * A mechanics-pass ruling's evidence duty: when the plan AUTHORED a
3313
- * `claim_type: "mechanics"` risk for the ruling's id, a `pass` ruling MUST
3314
- * cite the checked `file:line` in `evidence` (forces engagement — a pass with
3315
- * no evidence is an unverified mechanism). The trigger is sourced from the
3316
- * plan-authored `RiskRecord`, NOT the ruling — so a panel cannot drop the
3317
- * evidence duty by omitting `claim_type` from its ruling (the dropped-duty
3318
- * bypass). Reuses `FILE_LINE_CITATION_RE` via `.match()` — NOT `.test()`: the
3319
- * regex carries the `/g` flag, so `.test()` is stateful across calls
3320
- * (`lastIndex` advances) and would
3321
- * intermittently miss a present citation. An id with no authored mechanics
3322
- * risk carries no evidence duty ⇒ returns `true`.
3323
- */
3324
- const evidenceCitesFileLine = (r: RiskRuling, authored?: RiskRecord): boolean => {
3325
- if (authored?.claim_type !== "mechanics") return true;
3326
- return typeof r.evidence === "string" && r.evidence.match(FILE_LINE_CITATION_RE) !== null;
3327
- };
3328
-
3329
- /**
3330
- * A deferred-risk's verify-at-implement duty: when the plan AUTHORED a
3331
- * `disposition: "verify-at-implement"` risk for the ruling's id, a `pass`
3332
- * ruling MUST carry a concrete `procedure` (the named command/test the owner
3333
- * phase runs) AND a numeric `owner` phase — a bare "verify later" with no
3334
- * procedure demotes. The trigger is sourced from the plan-authored
3335
- * `RiskRecord`, NOT the ruling (the dropped-duty bypass). An id with no
3336
- * authored verify-at-implement risk is judged in THIS panel, not deferred ⇒
3337
- * returns `true`.
3338
- */
3339
- const procedureSatisfiesDuty = (r: RiskRuling, authored?: RiskRecord): boolean => {
3340
- if (authored?.disposition !== "verify-at-implement") return true;
3341
- return typeof r.procedure === "string" && r.procedure.length > 0 && typeof r.owner === "number";
3342
- };
3343
-
3344
- /**
3345
- * The single gate-fold authority: a ruling is effective-pass iff it is a bare
3346
- * `pass` AND (when the plan authored a mechanics risk for its id) its evidence
3347
- * cites a `file:line` AND (when the plan authored a verify-at-implement risk
3348
- * for its id) its procedure+owner discharge the verify duty. `allRiskFlagsPass`,
3349
- * `dimensionsToRegrade` clause 3, and `confirmDue`'s `riskFail` ALL consult this
3350
- * — so the three risk folds agree on what "passing" means and a demoted
3351
- * mechanics/deferred pass blocks the gate AND re-opens its owning dimension
3352
- * AND counts as blocking for confirm (no incoherent re-grading). For a ruling
3353
- * whose id the plan authored no duty for (no mechanics/verify-at-implement
3354
- * risk, no `risks:` at all, or no matching id) every duty no-ops, so
3355
- * `rulingEffectivePass(r, authored) === r.pass` — prior behavior is preserved.
3356
- */
3357
- const rulingEffectivePass = (r: RiskRuling, authored?: RiskRecord): boolean =>
3358
- r.pass === true && evidenceCitesFileLine(r, authored) && procedureSatisfiesDuty(r, authored);
3359
-
3360
- /**
3361
- * Fold the grade panel's per-flag risk rulings into a gate decision: every
3362
- * plan-authored risk flag the panel ruled on must be ruled PASS (latest ruling
3363
- * per flag wins, mirroring `allDimensionsPass`). A flag ruled `fail` — the
3364
- * grader confirmed the risk is real and unaddressed — blocks the gate, so a
3365
- * self-flagged risk (e.g. an override-vs-env validation mismatch) can no longer
3366
- * ride a green conformance pass into commit. An empty panel (no flag engaged)
3367
- * imposes no constraint; the plan simply declared no risks.
3368
- */
3369
- const allRiskFlagsPass = (
3370
- entries: readonly Output[] = [],
3371
- risks: ReadonlyMap<string, RiskRecord> = new Map(),
3372
- ): boolean => {
3373
- const latest = new Map<string, boolean>();
3374
- for (const o of entries)
3375
- for (const r of verdictRiskRulings(o)) latest.set(r.id, rulingEffectivePass(r, risks.get(r.id)));
3376
- return [...latest.values()].every(Boolean);
3377
- };
3378
-
3379
- /**
3380
- * The three gates' pass predicates — the SINGLE authority each gate consults at
3381
- * BOTH of its seams. A gate is satisfied when its deterministic cite/structure
3382
- * floor is green AND every quality dimension passes (severity-floored) AND — for
3383
- * the plan/code gates — every plan-authored risk flag is ruled pass.
3384
- *
3385
- * Reading the identical predicate at the cite/structure-check edge (which SKIPS
3386
- * the re-grade straight to the next stage) and at the grade edge (which gates
3387
- * forward-vs-fix) makes the skip provably equivalent to "re-grade, then pass",
3388
- * minus the wasted panel: after a fix that only cleared the deterministic floor,
3389
- * the accumulated verdicts already clear the gate, so re-running the LLM panel
3390
- * would at best reproduce them and at worst flap a passing dimension into a
3391
- * spurious fix loop. On the FIRST pass the verdict channel is empty, so
3392
- * `allDimensionsPass` returns false and the edge correctly routes INTO the grade
3393
- * panel. Any regression a fix introduces is still caught downstream: the plan
3394
- * gate by the full first-time `code-grade`, the code gate by `validate`.
3395
- */
3396
- // Each predicate folds the verdicts still FRESH for the channel's current
3397
- // artifact, restricted to the tier's roster — the SAME projections the panel's
3398
- // `units()` uses, so "skip the re-grade" stays provably equivalent to
3399
- // "re-grade, then pass". The deterministic cite/structure channels fold
3400
- // unfiltered: they re-run every round and carry no tier.
3401
- // The latest structure verdict carries a `citeDischarged` stamp for the
3402
- // CURRENT slice map. After a fix for a `remedy: "cite"` fail, the failing
3403
- // design-readiness verdict is stale (the fix re-sliced to a NEW file) and the
3404
- // gate's lone dimension has no fresh verdict, so the verdict fold can never
3405
- // pass — yet the fix is deterministically verifiable: `sliceStructureCheck`
3406
- // stamps the map basename it verified (demanded seeds present + shape
3407
- // unchanged, see `citeRemedyDischarged`). Honoring the stamp only for the
3408
- // current map means it can never carry across a later re-slice.
3409
- const citeDischargeCoversCurrentMap = (state: RunView): boolean => {
3410
- const stamp = (state.named["slice-check"]?.at(-1)?.data as { citeDischarged?: unknown } | undefined)?.citeDischarged;
3411
- const current = latestArtifactPath(state, "slices");
3412
- return typeof stamp === "string" && current !== undefined && stamp === basename(current);
3413
- };
3414
- const sliceGatePasses = (state: RunView): boolean => {
3415
- const fresh = freshVerdicts(state.named["slice-verdicts"], latestArtifactPath(state, "slices"));
3416
- const roster = gateRoster(gateTier(state, "slice-verdicts"), SLICE_DIMENSIONS);
3417
- if (!allDimensionsPass(state.named["slice-check"])) return false;
3418
- return allDimensionsPass(fresh, roster) || citeDischargeCoversCurrentMap(state);
3419
- };
3420
- // The single authority the new `subplan-check` edge consults — the twin of
3421
- // `sliceGatePasses`, but carrying no LLM-verdict roster or risk flags: the
3422
- // `subplan-check` floor is the sole (deterministic) dimension on its channel.
3423
- const subplanGatePasses = (state: RunView): boolean => allDimensionsPass(state.named["subplan-check"]);
3424
- const planGatePasses = (state: RunView): boolean => {
3425
- const fresh = freshVerdicts(state.named["plan-verdicts"], latestArtifactPath(state, "plans"));
3426
- const roster = gateRoster(gateTier(state, "plan-verdicts"), PLAN_DIMENSIONS);
3427
- const risks = planAuthoredRisks(state, "plans");
3428
- return (
3429
- allDimensionsPass(state.named["plan-cite-check"]) &&
3430
- allDimensionsPass(fresh, roster) &&
3431
- allRiskFlagsPass(fresh, risks)
3432
- );
3433
- };
3434
- const codeGatePasses = (state: RunView): boolean => {
3435
- const fresh = freshVerdicts(state.named["code-verdicts"], latestArtifactPath(state, "plans"));
3436
- const roster = gateRoster(gateTier(state, "code-verdicts"), PLAN_DIMENSIONS);
3437
- const risks = planAuthoredRisks(state, "plans");
3438
- return (
3439
- allDimensionsPass(state.named["code-cite-check"]) &&
3440
- allDimensionsPass(fresh, roster) &&
3441
- allRiskFlagsPass(fresh, risks)
3442
- );
3443
- };
145
+ // ===========================================================================
146
+ // build — goal (verbatim-brief capture) → research → slice → slice-check
147
+ // (deterministic floor) → slice-grade (design-readiness, slice-fix loop)
148
+ // → slice-design (fanout) → design-review (one human checkpoint) →
149
+ // subplan (cluster fanout) → plan → plan-grade (plan-fix loop) →
150
+ // code (fanout) → code-splice → code-grade (code-fix loop) →
151
+ // implement → implement-scope-check → reconcile → validate → commit
152
+ // The sliced, panel-gated heavy path: capture the user's brief verbatim as the
153
+ // `goal` channel (the north star the judgment seams — the two grade panels'
154
+ // completeness/correctness dimensions and validate — anchor against), research
155
+ // the brief (so every slice
156
+ // rests on a real, cited footing and the plan gate can grade architecture-fit),
157
+ // decompose it into independent
158
+ // vertical slices, gate that breakdown BEFORE any design so each slice is
159
+ // chewable by one design-slice pass. The gate is two-phase: a DETERMINISTIC
160
+ // floor (`slice-check`) enforces dependency-cycle freedom and brief-coverage
161
+ // conservation (a slice-fix may redistribute the brief, never drop scope to pass),
162
+ // then ONE LLM `design-readiness` judgment reconciles the formerly-opposing
163
+ // split/merge forces. Then design every slice in parallel and pause at ONE
164
+ // consolidated human checkpoint (`design-review`) — the single fan-in seam where
165
+ // every design exists and nothing parallel runs — to accept or adjust the
166
+ // proposed interfaces/data types before synthesis. Then merge hierarchically
167
+ // (per-cluster sub-plans → one plan) so no pass holds every design, gate the
168
+ // plan on quality dimensions BEFORE any code, elaborate code per phase and
169
+ // splice it in, re-grade the code-bearing plan, then implement/validate/commit.
170
+ // ===========================================================================
3444
171
 
3445
172
  /**
3446
- * Ship's grade gate — the tier-independent fold over `SHIP_DIMENSIONS` reading
3447
- * the `ship-verdicts` channel. Satisfied when every ship dimension passes
3448
- * (severity-floored) AND every plan-authored risk flag is ruled pass. Unlike
3449
- * `planGatePasses`/`codeGatePasses` it folds NO deterministic cite channel —
3450
- * ship's `plan-cite-check` gate is routed at its own edge — and binds the
3451
- * roster to `SHIP_DIMENSIONS` verbatim (never `gateRoster(gateTier(...))`), so
3452
- * the gate consults the same fixed set the panel graded.
173
+ * `goal` displaces `research` as build's start stage, and ONLY the start stage
174
+ * receives `originalInput` as its skill arg (`stageEntryArgs` case 1) — a plain
175
+ * `produces()` research would silently receive the rolling primary (the goal
176
+ * FILE PATH) instead of the brief text. A prompt stage owns its whole message,
177
+ * so this rebuilds research's pre-goal dispatch byte-for-byte; the outcome
178
+ * deriver still wires the `research` bucket off the record key (the polish
179
+ * `validate` prompt-stage precedent).
3453
180
  */
3454
- export const shipGatePasses = (state: RunView): boolean => {
3455
- const fresh = freshVerdicts(state.named["ship-verdicts"], latestArtifactPath(state, "plans"));
3456
- const risks = planAuthoredRisks(state, "plans");
3457
- return allDimensionsPass(fresh, SHIP_DIMENSIONS) && allRiskFlagsPass(fresh, risks);
3458
- };
181
+ const RESEARCH_BRIEF_PROMPT: PromptFn = ({ state }) => `/skill:research ${state.originalInput}`;
3459
182
 
3460
183
  /**
3461
- * Confirm-before-block: a dimension's FIRST blocking verdict against the
3462
- * current artifact gets ONE independent second judgment before it buys a fix
3463
- * round. Single-judge verdicts observably flap (pass/score/severity disagree
3464
- * across rolls on a near-unchanged artifact), and a spurious block
3465
- * manufactures an entire grade→fix cycle. Routing to the confirm stage
3466
- * re-runs only the pending dimensions on the same verdict channel;
3467
- * latest-per-dimension wins, so a confirming pass clears the gate and a
3468
- * confirming fail routes to the fix with two agreeing judgments behind it. A
3469
- * blocker already judged twice for this artifact routes straight to the fix —
3470
- * confirmation is one extra opinion, not an unbounded re-roll.
3471
- *
3472
- * No tier guard is needed: a blocking verdict is medium+ by the severity
3473
- * floor, and a medium+ severity already lifts `gateTier` out of light — every
3474
- * run with a genuine blocker has confirm-level scrutiny by construction.
184
+ * ship's research front-load — a LEANER grounding than build's `/skill:research`
185
+ * pass. Bypasses the research skill and bounds the agent to at most TWO targeted
186
+ * `codebase-analyzer` dispatches (sequentially — never parallel, never
187
+ * `run_in_background`) to map only what a lightweight single-phase plan needs to
188
+ * be correct: entry points, the relevant module's shape, and the conventions the
189
+ * implement lane must match. The agent then `Write`s a grounding doc under
190
+ * `.rpiv/artifacts/research/`, where the research bucket collector harvests it —
191
+ * the grade panel's architecture-fit dimension threads it as `--context` exactly
192
+ * as build's research artifact does. A prompt stage (no skill), so the stage
193
+ * name `research` drives outcome derivation (research contract → `research`
194
+ * bucket), exactly as build's `RESEARCH_BRIEF_PROMPT` stage does — the prompt
195
+ * text, not dispatch, is what differs.
3475
196
  */
3476
- const confirmDue = (
3477
- state: RunView,
3478
- channel: string,
3479
- verdictChannel: string,
3480
- dimensions: readonly string[],
3481
- ): boolean => {
3482
- const roster = new Set(gateRoster(gateTier(state, verdictChannel), dimensions));
3483
- const fresh = freshVerdicts(state.named[verdictChannel], latestArtifactPath(state, channel));
3484
- const risks = planAuthoredRisks(state, channel);
3485
- const byDim = new Map<string, { blocking: boolean; count: number }>();
3486
- for (const o of fresh) {
3487
- const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
3488
- if (typeof v?.dimension !== "string" || !roster.has(v.dimension)) continue;
3489
- // anchorNitsOnly keeps this floor coherent with the other three
3490
- // severity-fold consumers (gateTier/dimensionsToRegrade/allDimensionsPass).
3491
- const floored = v.pass === true || v.severity === "low" || v.severity === "none" || anchorNitsOnly(v);
3492
- const riskFail = verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
3493
- byDim.set(v.dimension, {
3494
- blocking: !floored || riskFail,
3495
- count: (byDim.get(v.dimension)?.count ?? 0) + 1,
3496
- });
3497
- }
3498
- const blockers = [...byDim.values()].filter((e) => e.blocking);
3499
- return blockers.length > 0 && blockers.some((e) => e.count < 2);
3500
- };
197
+ const SHIP_RESEARCH_PROMPT: PromptFn = ({ state }) =>
198
+ [
199
+ "Ground this brief for a lightweight ship plan.",
200
+ "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.",
201
+ "",
202
+ `Brief: ${state.originalInput}`,
203
+ "",
204
+ "Then Write a grounding doc under .rpiv/artifacts/research/ (timestamped filename) carrying the findings, and stop.",
205
+ ].join("\n");
3501
206
 
3502
207
  /**
3503
208
  * Verdict channels — grade writes JSON to `.rpiv/artifacts/verdicts/`, so these
@@ -3519,12 +224,6 @@ const planVerdictOutcome = verdictOutcome("plan-verdicts");
3519
224
  // slice-verdicts / plan-verdicts / code-verdicts parallel.
3520
225
  const codeVerdictOutcome = verdictOutcome("code-verdicts");
3521
226
 
3522
- // Ship's grade panel writes its verdicts to a DISTINCT channel (same
3523
- // directory, different artifact basenames) so they never mix with build's
3524
- // plan/code verdicts — named for the workflow, completing the slice-verdicts
3525
- // / plan-verdicts / code-verdicts / ship-verdicts parallel.
3526
- export const shipVerdictOutcome = verdictOutcome("ship-verdicts");
3527
-
3528
227
  /**
3529
228
  * Absolute path to rpiv-pi's bundled deterministic stitch script. Resolved off
3530
229
  * this module's own URL so it points inside the installed package at runtime
@@ -3539,48 +238,6 @@ const STITCH_SCRIPT = join(
3539
238
  "stitch-elaborations.mjs",
3540
239
  );
3541
240
 
3542
- /**
3543
- * Build's validate dispatch: the latest synthesized plan plus the goal and
3544
- * run-start-baseline flags. Sourcing the plan from the NAMED channel (not the
3545
- * rolling primary) is load-bearing: `code-grade` is a produces-fanout, so
3546
- * after the code gate the rolling primary is the LAST VERDICT JSON
3547
- * (`placeFanoutOutput` advances it per unit) and `implement` (acts) leaves it
3548
- * there — a plain `produces()` validate would receive a verdict path as its
3549
- * "plan". A prompt stage owns its whole message, so the `/skill:validate`
3550
- * prefix is explicit (polish precedent).
3551
- *
3552
- * `--baseline` threads the pre-existing-dirty snapshot `goal` captured at run
3553
- * start, so validate judges working-tree scope criteria ("only these files
3554
- * touched") against the RUN'S OWN delta instead of failing on dirt that was
3555
- * on disk before stage one — the same fence the commit dispatch applies. The
3556
- * path comes off the goal channel (this run's snapshot, replayed from the
3557
- * JSONL trail on resume), never a shared file another run could overwrite.
3558
- */
3559
- const VALIDATE_GOAL_PROMPT: PromptFn = ({ state }) => {
3560
- const parts = ["/skill:validate"];
3561
- const plan = latestFsArtifact(state, "plans");
3562
- if (plan?.handle.kind === "fs") parts.push(handleToString(plan.handle));
3563
- const goal = latestFsArtifact(state, "goal");
3564
- if (goal?.handle.kind === "fs") parts.push(`--goal ${handleToString(goal.handle)}`);
3565
- const baseline = goalBaselinePath(state);
3566
- if (baseline) parts.push(`--baseline ${baseline}`);
3567
- return parts.join(" ");
3568
- };
3569
-
3570
- /**
3571
- * Build's commit dispatch: thread the run-start baseline so the commit skill
3572
- * fences pre-existing dirt off the commit — `git-changes.mjs` takes the path
3573
- * as a flag, so there is no fixed rendezvous file for concurrent/repeat runs
3574
- * to clobber. Prompt-dispatched deliberately: the inherited rolling primary
3575
- * (the validation report path) was reaching the skill as a meaningless
3576
- * message-hint argument anyway; owning the message replaces that noise with
3577
- * the one flag the skill actually consumes.
3578
- */
3579
- const COMMIT_BASELINE_PROMPT: PromptFn = ({ state }) => {
3580
- const baseline = goalBaselinePath(state);
3581
- return baseline ? `/skill:commit --baseline ${baseline}` : "/skill:commit";
3582
- };
3583
-
3584
241
  // ===========================================================================
3585
242
  // vet — goal → code-review → (blueprint → implement → implement-scope-check
3586
243
  // → validate → loop) | commit. Examine existing changes; capture the
@@ -3592,6 +249,40 @@ const COMMIT_BASELINE_PROMPT: PromptFn = ({ state }) => {
3592
249
  // buildWorkflow follows (defined after its deps).
3593
250
  // ===========================================================================
3594
251
 
252
+ /**
253
+ * Scope-floor gate factory — build and vet wire IDENTICAL tiered routes; a
254
+ * factory (not one shared EdgeFn) so each workflow's route-note symbol never
255
+ * aliases the other's. Branches on the floor's tiered `ScopeVerdict`:
256
+ * "pass" AND tracked "excess" continue to `reconcile` — the floor demotes
257
+ * tracked excess to downstream adjudication (build threads the verdict to
258
+ * validate via `--scope`; vet's review loop sees the whole diff) instead of
259
+ * halting, the citation-floor precedent (demote where a remedy or adjudicator
260
+ * exists). "untracked-only" takes the deterministic `scope-quarantine` arm.
261
+ * Anything else — a missing or corrupt verdict — terminates ("stop" with a
262
+ * route note): the integrity clause every de-halting change has preserved.
263
+ * A `match` cannot send two enum values to one target, hence `defineRoute`;
264
+ * `readsData: false` — the route consults the stage's published channel, not
265
+ * its projected output (matching the other deterministic-floor routes).
266
+ */
267
+ const scopeFloorGate = (): EdgeFn => {
268
+ const route: EdgeFn = defineRoute(
269
+ ["reconcile", "scope-quarantine", "stop"],
270
+ ({ state }) => {
271
+ const verdict = (state.named["implement-scope-check"]?.at(-1)?.data as { verdict?: unknown } | undefined)
272
+ ?.verdict;
273
+ if (verdict === "untracked-only") return "scope-quarantine";
274
+ if (verdict === "pass" || verdict === "excess") return "reconcile";
275
+ setRouteNote(
276
+ route,
277
+ `implement-scope-check verdict ${JSON.stringify(verdict ?? null)} is not a ScopeVerdict — terminated (integrity stop)`,
278
+ );
279
+ return "stop";
280
+ },
281
+ { readsData: false },
282
+ );
283
+ return route;
284
+ };
285
+
3595
286
  const vetWorkflow = defineWorkflow({
3596
287
  name: "vet",
3597
288
  description:
@@ -3628,9 +319,14 @@ const vetWorkflow = defineWorkflow({
3628
319
  // non-superseding fix plans, so the declared set is the UNION over the full
3629
320
  // `plans` history — `implementScopeCheckVet`). The `from` form suppresses
3630
321
  // the READS_DATA outputSchema lint, so no schema is declared, matching
3631
- // `slice-check`/`plan-cite-check`. Pass → validate; fail/missing → STOP
3632
- // (no fallback), mirroring build's `validate → commit` route.
322
+ // `slice-check`/`plan-cite-check`. Tiered route (scopeFloorGate): pass and
323
+ // tracked excess → reconcile (the review loop adjudicates the recorded
324
+ // findings), untracked-only → scope-quarantine, missing verdict → STOP.
3633
325
  "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheckVet }),
326
+ // Deterministic remedy arm for the untracked-only tier: move (never
327
+ // delete) run-created untracked excess under .rpiv/tmp/scope-quarantine/
328
+ // and publish a manifest, then re-enter the floor — see scopeQuarantine.
329
+ "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
3634
330
  // Deterministic post-implement reconciliation (no LLM) — the SAME `reconcile`
3635
331
  // run-function as build (no vet twin): applies every `#### Reconciliation`
3636
332
  // directive (write-restricted to test files) + re-runs every per-phase
@@ -3652,10 +348,17 @@ const vetWorkflow = defineWorkflow({
3652
348
  // validate; fail/missing terminates (STOP, no fallback). Byte-for-byte
3653
349
  // build's route.
3654
350
  implement: "implement-scope-check",
3655
- // Scope-check still gates onward, but now into `reconcile` (not validate):
3656
- // the coherence backstop runs after the write-set is proven. Pass ⇒
3657
- // reconcile; fail/missing ⇒ STOP (no fallback).
3658
- "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
351
+ // Scope-check still gates onward into `reconcile` (not validate): the
352
+ // coherence backstop runs after the write-set is judged. Tiered route —
353
+ // see scopeFloorGate: pass/excess ⇒ reconcile, untracked-only ⇒ the
354
+ // quarantine arm, missing/corrupt verdict ⇒ STOP.
355
+ "implement-scope-check": scopeFloorGate(),
356
+ // Deterministic re-entry after the quarantine arm: a plain string edge
357
+ // (non-counted, mirroring build's validate-fix hop) with guaranteed
358
+ // progress — quarantined paths leave the dirty set, so the re-check
359
+ // either passes or reveals tracked drift. At most one quarantine hop per
360
+ // gate entry; no new loop budget.
361
+ "scope-quarantine": "implement-scope-check",
3659
362
  // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target /
3660
363
  // absent find / failed AV command) or a missing verdict ⇒ STOP (no fix arm —
3661
364
  // a reconciliation failure is plan-vs-tree drift the agent reconciles manually).
@@ -3859,12 +562,17 @@ const buildWorkflow = defineWorkflow({
3859
562
  // Lane-level scope floor — the structural backstop beneath the quality
3860
563
  // gates. After the (now concurrent) implement lane lands, judge the working
3861
564
  // tree's dirty set against the plan's declared write-set: any undeclared
3862
- // write is a phase that escaped the upstream write-scope discipline and
3863
- // raced on a sibling's in-flight edit. Fail ⇒ STOP (no fix arm). The `from`
3864
- // form suppresses the READS_DATA outputSchema lint, so no schema is declared
3865
- // (matching slice-check/plan-cite-check). Reads `goal` for the run-start
3866
- // baseline that subtracts pre-existing dirt.
565
+ // write is a phase that escaped the upstream write-scope discipline. Tiered
566
+ // route (scopeFloorGate): untracked-only excess ⇒ the deterministic
567
+ // quarantine arm; tracked excess ⇒ recorded and adjudicated by validate
568
+ // (threaded via --scope); missing verdict ⇒ STOP. No schema is declared
569
+ // (matching slice-check/plan-cite-check — the route reads the channel).
570
+ // Reads `goal` for the run-start baseline that subtracts pre-existing dirt.
3867
571
  "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheck }),
572
+ // Deterministic remedy arm for the untracked-only tier: move (never
573
+ // delete) run-created untracked excess under .rpiv/tmp/scope-quarantine/
574
+ // and publish a manifest, then re-enter the floor — see scopeQuarantine.
575
+ "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
3868
576
  // Deterministic post-implement reconciliation (no LLM): applies every
3869
577
  // `#### Reconciliation` directive (find→replace, write-restricted to test
3870
578
  // files) and re-runs every per-phase `#### Automated Verification:`
@@ -4020,16 +728,21 @@ const buildWorkflow = defineWorkflow({
4020
728
  "code-snapshot": "code-fix",
4021
729
  "code-fix": "code-cite-check",
4022
730
  implement: "implement-scope-check",
4023
- // Lane-level scope floor gate. Pass ⇒ reconcile (the coherence backstop
4024
- // runs after the write-set is proven). A `fail` (undeclared write) or a
4025
- // missing verdict routes to STOP — no fix arm, because a scope violation is
4026
- // plan-vs-tree drift the agent must reconcile manually (a phase wrote
4027
- // outside its declared set), not a defect an auto-fix loop can repair. Safe
4028
- // by construction: the sole path onward is an explicit `verdict: "pass"`.
4029
- // Sourced from the scope-check's published verdict channel via the `from`
4030
- // form (the stage key for an outcome-less `produces.script`, per
4031
- // `resolvePublishName`), which suppresses the READS_DATA outputSchema lint.
4032
- "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
731
+ // Lane-level scope floor gate — tiered, see scopeFloorGate: pass AND
732
+ // tracked excess ⇒ reconcile (excess findings ride the verdict channel and
733
+ // validate adjudicates them via the --scope thread — the citation floor's
734
+ // demote-and-adjudicate precedent); untracked-only ⇒ the deterministic
735
+ // scope-quarantine arm; a missing/corrupt verdict ⇒ STOP (integrity
736
+ // clause). Sourced from the scope-check's published verdict channel (the
737
+ // stage key for an outcome-less `produces.script`, per
738
+ // `resolvePublishName`); `readsData: false` suppresses the outputSchema lint.
739
+ "implement-scope-check": scopeFloorGate(),
740
+ // Deterministic re-entry after the quarantine arm: a plain string edge
741
+ // (non-counted, mirroring validate-fix's hop) with guaranteed progress —
742
+ // quarantined paths leave the dirty set, so the re-check either passes or
743
+ // reveals tracked drift. At most one quarantine hop per gate entry; no new
744
+ // loop budget.
745
+ "scope-quarantine": "implement-scope-check",
4033
746
  // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target
4034
747
  // / absent find / failed AV command) or a missing verdict ⇒ STOP (no fix
4035
748
  // arm — a reconciliation failure is plan-vs-tree drift the agent reconciles
@@ -4151,7 +864,7 @@ const shipGradeGate: EdgeFn = defineRoute(
4151
864
  const shipWorkflow = defineWorkflow({
4152
865
  name: "ship",
4153
866
  description:
4154
- "Ship, unsliced: capture the verbatim brief as a goal artifact → ground it with at most two targeted codebase-analyzer dispatches (no /skill:research) → one lightweight quick-plan pass → deterministic citation floor (fabricated paths and coverage gaps stop; ambiguity and line drift pass as advisory findings the grade panel adjudicates) → single tier-independent quality gate (correctness/completeness/architecture-fit, stop-on-fail) → implement → implement-scope-check → reconcile → validate → commit. Every gate terminates the run on fail; no fix loops.",
867
+ "Ship, unsliced: capture the verbatim brief as a goal artifact → ground it with at most two targeted codebase-analyzer dispatches (no /skill:research) → one lightweight quick-plan pass → deterministic citation floor (files: coverage gaps stop; citation-resolution findings are advisory and adjudicated by the grade panel) → single tier-independent quality gate (correctness/completeness/architecture-fit, stop-on-fail) → implement → implement-scope-check → reconcile → validate → commit. Every gate terminates the run on fail; no fix loops.",
4155
868
  start: "goal",
4156
869
  stages: {
4157
870
  // build's verbatim goal capture — the brief on its own channel, plus the
@@ -4175,10 +888,10 @@ const shipWorkflow = defineWorkflow({
4175
888
  // explicitly instead of silently inheriting the drop.
4176
889
  plan: produces({ skill: "quick-plan", reads: ["research", "goal"] }),
4177
890
  // Deterministic citation floor BEFORE the LLM gate — build's verifier
4178
- // verbatim. A fabricated `file:line` (resolving to NOTHING) or a `files:`
4179
- // coverage gap fails structurally and STOPs the run; advisory findings
4180
- // (ambiguity/drift — see verifyCitations' tier) rate `low`, pass the gate,
4181
- // and reach the grade panel's correctness unit as `--cite-check`.
891
+ // verbatim. Only a `files:` coverage gap fails structurally and STOPs the
892
+ // run; every citation-resolution finding (unresolved path, ambiguity,
893
+ // drift) is advisory — rates `low`, passes the gate, and reaches the
894
+ // grade panel's correctness unit as `--cite-check` for adjudication.
4182
895
  "plan-cite-check": produces.script({ reads: ["plans"], run: planCitationCheck("plan-cite-check") }),
4183
896
  // Single PRE-implement grade over the fixed three-dimension roster
4184
897
  // (SHIP_DIMENSION_FANOUT — tier-independent, no confirm/snapshot arms);
@@ -4212,10 +925,14 @@ const shipWorkflow = defineWorkflow({
4212
925
  "plan-cite-check": shipCiteGate,
4213
926
  grade: shipGradeGate,
4214
927
  implement: "implement-scope-check",
4215
- // Scope floor gate — build's route verbatim: the sole path onward is an
4216
- // explicit `verdict: "pass"`; a fail (undeclared write) or a missing
4217
- // verdict is terminal STOP. Sourced from the stage's own channel via the
4218
- // `from` form (suppresses the READS_DATA outputSchema lint).
928
+ // Scope floor gate — DELIBERATELY NOT build/vet's tiered scopeFloorGate:
929
+ // ship's identity is stop-on-fail with no fix loops, so the sole path
930
+ // onward stays an explicit `verdict: "pass"`. The floor's tiered
931
+ // "untracked-only"/"excess" verdicts (which build quarantines/adjudicates)
932
+ // are terminal here like any other red gate — the match's no-branch note
933
+ // names the value, and the agent hand-repairs and re-invokes. Sourced from
934
+ // the stage's own channel via the `from` form (suppresses the READS_DATA
935
+ // outputSchema lint).
4219
936
  "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
4220
937
  // Reconciliation gate — build's route verbatim: pass ⇒ validate;
4221
938
  // fail/missing ⇒ STOP (plan-vs-tree drift the agent reconciles manually).
@@ -4236,6 +953,8 @@ const shipWorkflow = defineWorkflow({
4236
953
  // Exports
4237
954
  // ===========================================================================
4238
955
 
956
+ export { SHIP_DIMENSION_FANOUT, SHIP_DIMENSIONS, shipGatePasses, shipVerdictOutcome } from "./built-ins/index.js";
957
+
4239
958
  // Position 0 is load-bearing: `build` is the default `/wf` workflow when no
4240
959
  // project/user config sets one (resolve-default.ts resolves
4241
960
  // `Map.keys().next().value`), so it MUST stay first in this array.