@juicesharp/rpiv-pi 2.9.0 → 2.10.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/extensions/rpiv-core/artifact-collector.ts +30 -7
  2. package/extensions/rpiv-core/built-in-workflows.ts +222 -70
  3. package/extensions/rpiv-core/built-ins/citations.ts +9 -0
  4. package/extensions/rpiv-core/built-ins/design.ts +64 -0
  5. package/extensions/rpiv-core/built-ins/elaboration.ts +53 -0
  6. package/extensions/rpiv-core/built-ins/gates.ts +282 -12
  7. package/extensions/rpiv-core/built-ins/grade-panel.ts +54 -26
  8. package/extensions/rpiv-core/built-ins/index.ts +20 -1
  9. package/extensions/rpiv-core/built-ins/markdown-fence.ts +26 -1
  10. package/extensions/rpiv-core/built-ins/plan-phases.ts +8 -0
  11. package/extensions/rpiv-core/built-ins/priors.ts +9 -2
  12. package/extensions/rpiv-core/built-ins/remediation.ts +60 -7
  13. package/extensions/rpiv-core/built-ins/scope-checks.ts +74 -11
  14. package/extensions/rpiv-core/built-ins/shared.ts +5 -3
  15. package/extensions/rpiv-core/built-ins/slice-checks.ts +164 -28
  16. package/extensions/rpiv-core/built-ins/slices.ts +44 -13
  17. package/extensions/rpiv-core/built-ins/verdict-collector.ts +207 -0
  18. package/extensions/rpiv-core/built-ins/verdict-outcome.ts +36 -0
  19. package/extensions/rpiv-core/lane-list.ts +10 -1
  20. package/extensions/rpiv-core/lane-progress.ts +1 -1
  21. package/extensions/rpiv-core/lane-usage.ts +1 -1
  22. package/extensions/rpiv-core/models-picker.ts +4 -3
  23. package/extensions/rpiv-core/run-lane-registry.ts +1 -2
  24. package/extensions/rpiv-core/sdk-workflow-host.ts +20 -4
  25. package/extensions/rpiv-core/session-hooks.ts +1 -1
  26. package/package.json +4 -3
  27. package/skills/_shared/stitch-elaborations.mjs +282 -21
  28. package/skills/acceptance/SKILL.md +3 -2
  29. package/skills/amend/SKILL.md +5 -5
  30. package/skills/design-slice/SKILL.md +5 -0
  31. package/skills/elaborate/SKILL.md +10 -3
  32. package/skills/grade/SKILL.md +13 -10
  33. package/skills/validate/SKILL.md +14 -0
@@ -3,12 +3,13 @@
3
3
  * (acyclicity, coverage conservation, citation backing) and the subplan
4
4
  * cluster-coverage check between the cluster fanout and the root merge.
5
5
  */
6
- import { basename } from "node:path";
6
+ import { writeFileSync } from "node:fs";
7
+ import { basename, isAbsolute, join } from "node:path";
7
8
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
9
  import { handleToString, type Output, type RunView, type ScriptContext } from "@juicesharp/rpiv-workflow/registration";
9
10
  import { verifyCitations } from "./citations.js";
10
- import { latestVerdictPerDimension } from "./gates.js";
11
- import { fencedSpans } from "./markdown-fence.js";
11
+ import { latestVerdictPerDimension, type SeedOnlyVerdict, seedOnlyFindings } from "./gates.js";
12
+ import { fencedSpans, forEachLineOutsideFences } from "./markdown-fence.js";
12
13
  import {
13
14
  haltPreflight,
14
15
  latestFsArtifact,
@@ -81,12 +82,9 @@ const sliceShape = (round: Output | undefined): string | undefined => {
81
82
  return d?.slices === undefined ? undefined : JSON.stringify({ slices: d.slices, coverage: d.coverage ?? null });
82
83
  };
83
84
 
84
- /** The verdict fields the cite-only discharge consults. */
85
- type CiteRemedyVerdict = {
86
- pass?: boolean;
87
- remedy?: string;
88
- findings?: readonly { requires?: unknown }[];
89
- };
85
+ /** The verdict fields the cite-only discharge consults live in gates.ts as
86
+ * `SeedOnlyVerdict` — the one spelling the classification, the discharge, and
87
+ * the seed lift share. */
90
88
 
91
89
  /**
92
90
  * Deterministic discharge of a CITE-ONLY `design-readiness` fail — the middle
@@ -94,26 +92,38 @@ type CiteRemedyVerdict = {
94
92
  * lone dimension failed) and "buy a full re-grade panel" (wasteful when the
95
93
  * grader already named the exact citations to add or refresh). A fix that
96
94
  * also restructured forfeits the discharge and takes the normal re-grade.
95
+ * The seed-only classification (`seedOnlyFindings`) accepts a `remedy` that
96
+ * is `"cite"` or absent — the judge-omits-the-marker leak is closed
97
+ * engine-side by the findings' own shape — and subsumes the zero-findings
98
+ * guard (a seed-only verdict carries ≥ 1 finding by definition).
97
99
  */
98
100
  const citeRemedyDischarged = (state: RunView, mapBody: string): boolean => {
99
101
  const verdict = latestVerdictPerDimension(state.named["slice-verdicts"]).get("design-readiness");
100
- const v = verdict?.data as CiteRemedyVerdict | undefined;
101
- if (v?.pass !== false || v.remedy !== "cite") return false;
102
+ const v = verdict?.data as SeedOnlyVerdict | undefined;
103
+ if (!seedOnlyFindings(v)) return false;
102
104
  // A fix must have LANDED since the verdict — discharging the judged map
103
105
  // unchanged would contradict the grader, who read it and found the cites
104
106
  // wrong. Basename inequality cannot witness the fix (a re-slice may
105
107
  // legitimately edit the map in place); publication order can: the latest
106
- // `slices` round must postdate the verdict.
108
+ // `slices` round OR seed-lift entry must postdate the verdict (the lift
109
+ // amends the map in place and publishes on its own channel, so it can be
110
+ // the sole witness with no `slices` round after the verdict).
107
111
  const entries = state.named.slices ?? [];
112
+ const liftEntries = state.named["slice-seed-lift"] ?? [];
108
113
  const verdictTs = verdict?.meta?.ts;
109
- const currentTs = entries.at(-1)?.meta?.ts;
110
- if (typeof verdictTs !== "string" || typeof currentTs !== "string" || currentTs <= verdictTs) return false;
111
- const findings = Array.isArray(v.findings) ? v.findings : [];
112
- if (findings.length === 0) return false;
114
+ const witnessTails = [entries.at(-1)?.meta?.ts, liftEntries.at(-1)?.meta?.ts].filter(
115
+ (ts): ts is string => typeof ts === "string",
116
+ );
117
+ const witnessTs = witnessTails.length > 0 ? witnessTails.reduce((a, b) => (a > b ? a : b)) : undefined;
118
+ if (typeof verdictTs !== "string" || witnessTs === undefined || witnessTs <= verdictTs) return false;
119
+ const rawFindings = v?.findings;
120
+ const findings = Array.isArray(rawFindings) ? rawFindings : [];
113
121
  const spans = fencedSpans(mapBody);
114
122
  if (!findings.every((f) => f != null && citeFindingSatisfied(mapBody, spans, f))) return false;
115
123
  // Shape must match the round the grader judged — located by publication
116
- // order, not filename, for the same in-place reason.
124
+ // order, not filename, for the same in-place reason. A lift-only witness
125
+ // leaves the judged round as the latest `slices` entry, so the comparison
126
+ // is the round to itself: shape-conserved by construction.
117
127
  const judged = [...entries].reverse().find((s) => typeof s.meta?.ts === "string" && s.meta.ts <= verdictTs);
118
128
  const judgedShape = sliceShape(judged);
119
129
  return judgedShape !== undefined && judgedShape === sliceShape(entries.at(-1));
@@ -154,7 +164,7 @@ const sliceStructureCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"
154
164
  }
155
165
  const mapBody = readArtifactFile(latest.handle.path, cwd);
156
166
  const records = sliceRecords(mapBody, "slice-check", latest.handle.path);
157
- const findings: { detail: string; where: string }[] = [];
167
+ const findings: StructureFinding[] = [];
158
168
 
159
169
  const cycle = sliceDepCycle(records);
160
170
  if (cycle.length > 0) {
@@ -182,17 +192,138 @@ const sliceStructureCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"
182
192
  // Citation backing — every file:line the map cites must resolve.
183
193
  findings.push(...verifyCitations(mapBody, cwd));
184
194
 
185
- // Stamp the cite-only discharge ONLY on a green floor: structure clean +
186
- // citation backing verified + demanded seeds present + shape unchanged is
187
- // exactly what a fresh design-readiness pass on this map would re-establish,
188
- // so the `sliceGatePasses` skip stays provably equivalent to "re-grade, then pass".
195
+ // Stamp the cite-only discharge ONLY when the floor's findings are all
196
+ // advisory (an empty set included): structure clean, every citation
197
+ // verified or advisory-only, demanded seeds present, and shape unchanged is
198
+ // exactly what a fresh design-readiness pass on this map would
199
+ // re-establish, so the `sliceGatePasses` skip stays provably equivalent to
200
+ // "re-grade, then pass". The floor mirrors the routing severity floor — a
201
+ // `low` advisory-only verdict passes `allDimensionsPass` — so an advisory
202
+ // resolver limitation can no longer zero the stamp and buy the re-grade
203
+ // panel the stamp exists to skip. A BLOCKING finding (cycle, dropped
204
+ // coverage) still withholds — fail-closed.
189
205
  const discharge =
190
- findings.length === 0 && citeRemedyDischarged(state, mapBody)
206
+ findings.every((f) => f.advisory === true) && citeRemedyDischarged(state, mapBody)
191
207
  ? { citeDischarged: basename(latest.handle.path) }
192
208
  : undefined;
193
209
  return writeStructureVerdict("slice-check", latest.handle, findings, cwd, discharge);
194
210
  };
195
211
 
212
+ /** A `## Slice N:` section heading — the target a cite-remedy finding's
213
+ * `where` names, and the section delimiter the seed lift walks. */
214
+ const SLICE_HEADING_RE = /^##\s+Slice\s+(\d+)/;
215
+
216
+ /** The `Draws on:` line the seed lift appends a demanded seed to. */
217
+ const DRAWS_ON_LINE_RE = /^\s*\*\*Draws on:\*\*/;
218
+
219
+ /**
220
+ * One cite-remedy seed the lift acted on: the demanded `requires` citation,
221
+ * the slice section it targeted, and — for a refused seed — why (the lift
222
+ * refuses rather than guess where a seed belongs; a refused seed leaves the
223
+ * discharge unsatisfied and the loop takes the structural fix arm).
224
+ */
225
+ type SeedLiftRecord = {
226
+ requires: string;
227
+ slice?: number;
228
+ reason?: "no-slice-heading" | "no-draws-on-line";
229
+ };
230
+
231
+ /**
232
+ * Deterministic seed lift — the engine-owned half of the cite remedy. A
233
+ * seed-only `design-readiness` fail (every finding demanding a concrete
234
+ * `requires` citation) names EXACTLY the seeds to append; re-cutting the
235
+ * whole map through the structural fix arm for them is a full LLM re-slice
236
+ * plus re-grade that repairs nothing the verdict actually flagged. This
237
+ * stage appends each demanded seed to its finding's named slice section's
238
+ * `Draws on:` line, in place, and publishes the amended map as its row
239
+ * artifact on its OWN stage channel (a script stage structurally cannot
240
+ * carry an outcome, and none is needed: `latestFsArtifact(state, "slices")`
241
+ * still resolves the same path, now carrying the amended bytes — the
242
+ * plan-snapshot precedent for an in-place side-effecting script stage).
243
+ * The re-run `slice-check` stamps `citeDischarged` when every seed landed on
244
+ * a structurally unchanged map, so the gate folds green without a re-grade.
245
+ *
246
+ * Refusal semantics: a seed whose `where` names no `## Slice N:` heading, or
247
+ * whose slice section carries no `Draws on:` line, is recorded `skipped`
248
+ * with its reason and the map is left unchanged for it — never guessed onto
249
+ * another slice. A seed already satisfied on the evolving body is not
250
+ * re-appended (the discharge's own satisfaction test — dedup by
251
+ * construction, so the post-lift every-seed-satisfied conjunct holds).
252
+ *
253
+ * Misroute guard: no map, or a latest verdict that is not seed-only, halts
254
+ * loud via `haltPreflight` — this stage is reachable only from the seed-only
255
+ * branch of the `slice-grade` route, so anything else is a wiring bug.
256
+ */
257
+ const sliceSeedLift = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
258
+ const latest = latestFsArtifact(state, "slices");
259
+ if (latest?.handle.kind !== "fs") {
260
+ throw haltPreflight(
261
+ "slice-seed-lift",
262
+ "slice-seed-lift: no slice map to lift seeds onto",
263
+ "slice-seed-lift: no fs artifact on the 'slices' channel — slice must run before the seed lift",
264
+ );
265
+ }
266
+ const verdict = latestVerdictPerDimension(state.named["slice-verdicts"]).get("design-readiness");
267
+ const v = verdict?.data as SeedOnlyVerdict | undefined;
268
+ if (!seedOnlyFindings(v)) {
269
+ throw haltPreflight(
270
+ "slice-seed-lift",
271
+ "slice-seed-lift: latest design-readiness verdict is not seed-only",
272
+ "slice-seed-lift: the slice-grade route dispatched the seed lift, but the latest design-readiness verdict is not a seed-only cite fail (pass false, remedy cite-or-absent, every finding carrying a concrete requires). This is a routing/wiring defect — investigate it; do not hand-edit the slice map to work around it",
273
+ );
274
+ }
275
+ const mapPath = latest.handle.path;
276
+ let body = readArtifactFile(mapPath, cwd);
277
+ const lines = body.split("\n");
278
+ const rawFindings = v?.findings;
279
+ const findings = (Array.isArray(rawFindings) ? rawFindings : []).filter(
280
+ (f): f is { requires?: unknown; where?: unknown } => f != null,
281
+ );
282
+ const lifted: SeedLiftRecord[] = [];
283
+ const skipped: SeedLiftRecord[] = [];
284
+ for (const f of findings) {
285
+ const requires = typeof f.requires === "string" ? f.requires : "";
286
+ if (requires.length === 0) continue; // unreachable past the guard; kept fail-soft
287
+ // Dedup on the EVOLVING body: a seed already satisfied (the discharge's
288
+ // own test) is never re-appended.
289
+ if (citeFindingSatisfied(body, fencedSpans(body), f)) continue;
290
+ const where = typeof f.where === "string" ? f.where : "";
291
+ const heading = SLICE_HEADING_RE.exec(where);
292
+ if (!heading) {
293
+ skipped.push({ requires, reason: "no-slice-heading" });
294
+ continue;
295
+ }
296
+ const slice = Number(heading[1]);
297
+ // Locate the `Draws on:` line inside the `## Slice N:` section — the
298
+ // section spans to the next `## Slice` heading or end of body, and the
299
+ // walk is fence-aware (a fenced example line is never a real target).
300
+ let drawsOn: number | undefined;
301
+ let inTarget = false;
302
+ forEachLineOutsideFences(body, (line, index) => {
303
+ if (drawsOn !== undefined) return;
304
+ const h = SLICE_HEADING_RE.exec(line);
305
+ if (h) {
306
+ inTarget = Number(h[1]) === slice;
307
+ return;
308
+ }
309
+ if (inTarget && DRAWS_ON_LINE_RE.test(line)) drawsOn = index;
310
+ });
311
+ if (drawsOn === undefined) {
312
+ skipped.push({ requires, slice, reason: "no-draws-on-line" });
313
+ continue;
314
+ }
315
+ lines[drawsOn] = `${lines[drawsOn]}, ${requires}`;
316
+ body = lines.join("\n");
317
+ lifted.push({ requires, slice });
318
+ }
319
+ writeFileSync(isAbsolute(mapPath) ? mapPath : join(cwd, mapPath), body, "utf-8");
320
+ return {
321
+ kind: "json",
322
+ artifacts: [{ handle: { kind: "fs", path: mapPath } }],
323
+ data: { lifted, skipped },
324
+ };
325
+ };
326
+
196
327
  /**
197
328
  * `_<k>` cluster ordinal a partial sub-plan carries in its basename
198
329
  * (`<slug>_cluster-<k>.md`), emitted by `synthesize`'s partial mode from the
@@ -351,7 +482,9 @@ const sourcesCoverageGaps = (state: RunView, cwd: string, sliceNumbers: Set<numb
351
482
  * Preflight: a slice with NO design on the `designs` channel halts LOUD before
352
483
  * any reconciliation — the fanout drops (or under-feeds) its cluster pre-dispatch
353
484
  * (`if (!designs.length) return undefined`), so re-dispatching `subplan` re-drops
354
- * it every round until `maxBackwardJumps` exhausts with a diagnostic naming the
485
+ * it every round until the re-entry budgets exhaust (the `maxBackwardJumps`
486
+ * cap, default 3, or the absolute `maxLaps` ceiling, default 8 — both fresh
487
+ * per invocation) with a diagnostic naming the
355
488
  * refused re-entry instead of the cause. The missing design is upstream
356
489
  * (`slice-design`/`design-review`) and unreachable from this loop's backward
357
490
  * edge; halting here names the actual defect and spends no jump budget.
@@ -360,7 +493,9 @@ const sourcesCoverageGaps = (state: RunView, cwd: string, sliceNumbers: Set<numb
360
493
  * `pass:false` verdict rated `low`/`none`; a lost cluster MUST rate `high` or it
361
494
  * ships). Deliberately NOT the `match("verdict", …)` STOP idiom
362
495
  * `implementScopeCheck` uses — a lost cluster IS repairable by re-dispatch, so the
363
- * floor routes the backward edge to `subplan`, bounded by `maxBackwardJumps`.
496
+ * floor routes the backward edge to `subplan`, bounded by `maxBackwardJumps`
497
+ * (default 3) under the absolute `maxLaps` ceiling (default 8; both budgets
498
+ * fresh per invocation).
364
499
  * Deterministic ⇒ idempotent across re-dispatch rounds: the verdict basename is
365
500
  * keyed on the slice-map basename, so a re-run OVERWRITES its own slot.
366
501
  */
@@ -386,8 +521,9 @@ const subplanCoverageCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta
386
521
 
387
522
  // A slice with no design cannot be repaired by the backward edge: the fanout
388
523
  // drops a zero-design cluster pre-dispatch, so every `subplan` re-dispatch
389
- // reproduces the identical gap until maxBackwardJumps exhausts blaming the
390
- // re-entry. Halt loud at the floor instead, naming the upstream cause.
524
+ // reproduces the identical gap until the re-entry budgets exhaust (the
525
+ // maxBackwardJumps cap, default 3, or the absolute maxLaps ceiling, default
526
+ // 8) blaming the re-entry. Halt loud at the floor instead, naming the upstream cause.
391
527
  const designBySlice = designPathsBySlice(state);
392
528
  const undesigned = designCoverageGap(sliceNumbers, designBySlice);
393
529
  if (undesigned.length > 0) {
@@ -417,4 +553,4 @@ const subplanCoverageCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta
417
553
  return writeStructureVerdict("subplan-check", latestSliceMap.handle, findings, cwd);
418
554
  };
419
555
 
420
- export { sliceStructureCheck, subplanCoverageCheck };
556
+ export { sliceSeedLift, sliceStructureCheck, subplanCoverageCheck };
@@ -70,6 +70,11 @@ const SLICE_DESIGN_FANOUT = fanout({
70
70
  max: MAX_PHASES,
71
71
  depArtifactFlag: "--upstream",
72
72
  haltWhenAllFailed: true,
73
+ // A design the contract refuses (`filename_slice` ≠ `matches` — see design.ts)
74
+ // gets the in-session validation retry, then ONE fresh re-dispatch, so a
75
+ // hand-composed filename drift is repaired while the lane still owns it —
76
+ // never discovered five stages later at `subplan`.
77
+ retryHaltedUnits: 1,
73
78
  units: ({ state, cwd }) => {
74
79
  const doc = latestFsArtifact(state, "slices");
75
80
  if (doc?.handle.kind !== "fs") return [];
@@ -200,12 +205,38 @@ const sliceCovers = (entry: Record<string, unknown>): string[] => {
200
205
  /** A design filename encodes its slice as `…slice-<N>…` — the design-fanout naming convention. */
201
206
  const DESIGN_SLICE_RE = /slice-(\d+)/;
202
207
 
208
+ /** A positive integer, or a string spelling one (`slice_n: "3"` survives a quoted scalar). */
209
+ const positiveInt = (v: unknown): number | undefined => {
210
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : Number.NaN;
211
+ return Number.isInteger(n) && n > 0 ? n : undefined;
212
+ };
213
+
214
+ /**
215
+ * The slice number a design artifact identifies as its own. The AUTHORITY is
216
+ * the frontmatter `slice_n` the design-slice skill stamps — `frontmatterParser`
217
+ * lifts it onto the channel as `output.data`, so it reaches here without a
218
+ * file read. The filename's `slice-<N>` token is the same fact re-spelled by
219
+ * hand (a lane once dropped it while `slice_n` was right), so it is the
220
+ * FALLBACK for an entry whose data carries no `slice_n` — a parser-less
221
+ * re-emit or a hand-published channel entry. `undefined` when neither resolves.
222
+ *
223
+ * `data` is the output's PRIMARY artifact's frontmatter (`frontmatterParser`
224
+ * reads `ctx.artifacts[0]`), so a caller passes it only for that artifact.
225
+ */
226
+ const designSliceOf = (data: unknown, path: string): number | undefined => {
227
+ const fromData = positiveInt((data as Record<string, unknown> | null | undefined)?.slice_n);
228
+ if (fromData !== undefined) return fromData;
229
+ const match = DESIGN_SLICE_RE.exec(basename(path));
230
+ return match ? Number(match[1]) : undefined;
231
+ };
232
+
203
233
  /**
204
234
  * Map slice number → its design artifact path, from the design fanout's published
205
- * outputs. An identity resolver: it maps an ARTIFACT to a slice NUMBER. It FAILS
206
- * LOUD only when identity is genuinely UNRESOLVABLE — a design filename that
207
- * carries no `slice-<N>` token, where a positional `idx + 1` guess would scramble
208
- * the cluster→design wiring and drop slices.
235
+ * outputs. An identity resolver: it maps an ARTIFACT to a slice NUMBER via
236
+ * `designSliceOf` (frontmatter `slice_n` first, filename token second). It FAILS
237
+ * LOUD only when identity is genuinely UNRESOLVABLE — neither carrier names a
238
+ * slice — where a positional `idx + 1` guess would scramble the cluster→design
239
+ * wiring and drop slices.
209
240
  *
210
241
  * A slice claimed by MORE THAN ONE output is NOT ambiguous: the `designs` channel
211
242
  * legitimately accumulates several entries per slice — `slice-design` emits it,
@@ -219,21 +250,20 @@ const DESIGN_SLICE_RE = /slice-(\d+)/;
219
250
  const designPathsBySlice = (state: RunView): Map<number, string> => {
220
251
  const bySlice = new Map<number, string>();
221
252
  for (const out of state.named.designs ?? []) {
222
- for (const a of out.artifacts) {
223
- if (a.handle.kind !== "fs") continue;
224
- const name = basename(a.handle.path);
225
- const match = DESIGN_SLICE_RE.exec(name);
226
- if (!match) {
253
+ out.artifacts.forEach((a, i) => {
254
+ if (a.handle.kind !== "fs") return;
255
+ const n = designSliceOf(i === 0 ? out.data : undefined, a.handle.path);
256
+ if (n === undefined) {
227
257
  throw haltPreflight(
228
258
  "designPathsBySlice",
229
- `designPathsBySlice: design ${name} has no slice number`,
230
- `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`,
259
+ `designPathsBySlice: design ${basename(a.handle.path)} has no slice number`,
260
+ `designPathsBySlice: design artifact ${a.handle.path} carries no frontmatter 'slice_n' and no 'slice-<N>' filename token — cannot resolve which slice it designs; a positional guess would mis-route the cluster→design mapping and drop slices`,
231
261
  );
232
262
  }
233
263
  // Latest design per slice wins — the channel holds multiple entries per
234
264
  // slice by design (design-review re-emits), and the newest is authoritative.
235
- bySlice.set(Number(match[1]), handleToString(a.handle));
236
- }
265
+ bySlice.set(n, handleToString(a.handle));
266
+ });
237
267
  }
238
268
  return bySlice;
239
269
  };
@@ -283,6 +313,7 @@ export {
283
313
  clusterSliceDag,
284
314
  DESIGN_SLICE_RE,
285
315
  designPathsBySlice,
316
+ designSliceOf,
286
317
  SLICE_DESIGN_FANOUT,
287
318
  SYNTH_CLUSTER_FANOUT,
288
319
  sliceCoverageUnits,
@@ -0,0 +1,207 @@
1
+ /**
2
+ * verdict-collector — the disk-first collector behind every grade/confirm
3
+ * stage's verdict channel. The grade skill writes its verdict JSON to
4
+ * `<VERDICT_DIR>/<artifact-basename>__<dimension>__<slug>.json` (grade skill
5
+ * step 6's naming contract), so the FILESYSTEM is the primary channel: a unit
6
+ * collects the newest `<basename>__<dimension>__*.json` written since its
7
+ * snapshot — prior rounds (listed at snapshot time) and sibling dimensions
8
+ * (different name prefix) are excluded by construction, and a mangled or
9
+ * typo'd transcript announcement can never hide a verdict that exists.
10
+ *
11
+ * Three arms, in order, all three missing ⇒ ONE composite fatal naming them:
12
+ * 1. DISK — the listing above (requires the determined name: the graded
13
+ * artifact's basename, off `sourceChannel`, plus the unit's label as the
14
+ * dimension; without both, this arm is skipped — no loose disk glob,
15
+ * which would collect a sibling dimension's verdict).
16
+ * 2. TEXT — `transcriptPathCollector`, pattern tightened to the determined
17
+ * name when known, else today's loose directory pattern. Inherits the
18
+ * text+tool-arguments widening (collectors/text-scan.ts), tool-args
19
+ * narrowed to write/edit calls (a read of the prior round's verdict is not
20
+ * a collection).
21
+ * 3. WRITE ARGS — a `toolCallCollector` arm matching `write`/`edit` calls whose
22
+ * `input.path` sits under the verdict dir (tightened to the determined
23
+ * name when known); the last write wins.
24
+ *
25
+ * Determined-name tightness: with `(basename, dimension)` known, a text or
26
+ * tool-args announcement of a DIFFERENT dimension's or a different artifact's
27
+ * verdict is not collected. With `unitLabel` absent (a non-panel wiring), the
28
+ * collector degrades to the loose pattern + widening — never fataling on
29
+ * shapes the prior directory collector accepted.
30
+ */
31
+
32
+ import { readdirSync, statSync } from "node:fs";
33
+ import { basename, join } from "node:path";
34
+ import {
35
+ type Artifact,
36
+ type ArtifactCollector,
37
+ type CollectContext,
38
+ defineCollector,
39
+ fs as fsHandle,
40
+ type RunView,
41
+ toolCallCollector,
42
+ transcriptPathCollector,
43
+ } from "@juicesharp/rpiv-workflow/registration";
44
+ import { latestFsArtifact } from "./shared.js";
45
+
46
+ /** The verdict dir listing at unit start — filename → mtimeMs. `undefined`
47
+ * when the dir was absent/unreadable (fail-soft: everything present then
48
+ * reads as new; the arm still cannot throw). */
49
+ export type VerdictSnapshot = Map<string, number> | undefined;
50
+
51
+ export interface VerdictCollectorOpts {
52
+ /** cwd-relative verdict directory (`.rpiv/artifacts/verdicts`). */
53
+ dir: string;
54
+ /**
55
+ * The channel carrying the artifact under judgment — resolves the verdict
56
+ * filename's `<basename>__` segment (the graded artifact's basename without
57
+ * extension) for determined-name collection. Optional: without it (or with
58
+ * no fs artifact on the channel) the collector runs its loose degradation.
59
+ */
60
+ sourceChannel?: string;
61
+ }
62
+
63
+ const escapeRegex = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
64
+
65
+ /** Pi's file-writing tools (`write`, `edit`) by name — the single spelling
66
+ * shared by the text arm's `match` filter and the write-args arm below. The Pi tool-name literal
67
+ * stays in this convention layer (never in rpiv-workflow's host-agnostic
68
+ * collectors); the structural `{ name }` param is assignable to
69
+ * `(tc: ToolCall) => boolean` under contravariance, so no `ToolCall`
70
+ * import is needed. */
71
+ const isWriteTool = (tc: { name: string }): boolean => tc.name === "write" || tc.name === "edit";
72
+
73
+ /** The graded artifact's basename without extension, off the source channel
74
+ * (undefined when no channel / no fs artifact). */
75
+ const gradedBasename = (state: RunView, sourceChannel: string | undefined): string | undefined => {
76
+ if (!sourceChannel) return undefined;
77
+ const doc = latestFsArtifact(state, sourceChannel);
78
+ return doc?.handle.kind === "fs" ? basename(doc.handle.path).replace(/\.[^.]+$/, "") : undefined;
79
+ };
80
+
81
+ /** Absolute paths under cwd collapse to cwd-relative (write tool inputs carry
82
+ * absolute paths); anything else passes through unchanged. */
83
+ const normalized = (cwd: string, path: string): string => {
84
+ const prefix = `${cwd}/`;
85
+ return path.startsWith(prefix) ? path.slice(prefix.length) : path;
86
+ };
87
+
88
+ /** Arm 1 — the disk listing: `<prefix>*.json` entries NEW since the snapshot
89
+ * (absent from the listing, or mtime moved), newest first (mtime, tie broken
90
+ * by name descending — the slug is a timestamp). `undefined` when the prefix
91
+ * is unknown, the dir is absent, or nothing is new. Never throws. */
92
+ const collectFromDisk = (
93
+ ctx: CollectContext<VerdictSnapshot>,
94
+ dir: string,
95
+ prefix: string | undefined,
96
+ ): string | undefined => {
97
+ if (prefix === undefined) return undefined;
98
+ try {
99
+ const abs = join(ctx.cwd, dir);
100
+ const candidates: Array<{ name: string; mtime: number }> = [];
101
+ for (const name of readdirSync(abs)) {
102
+ if (!name.endsWith(".json") || !name.startsWith(prefix)) continue;
103
+ const mtime = statSync(join(abs, name)).mtimeMs;
104
+ const known = ctx.snapshot?.get(name);
105
+ if (known !== undefined && mtime <= known) continue; // prior round — listed at snapshot
106
+ candidates.push({ name, mtime });
107
+ }
108
+ if (candidates.length === 0) return undefined;
109
+ candidates.sort((a, b) => (a.mtime !== b.mtime ? b.mtime - a.mtime : a.name < b.name ? 1 : -1));
110
+ return `${dir}/${candidates[0]!.name}`;
111
+ } catch {
112
+ return undefined; // no dir / unreadable — the arm misses
113
+ }
114
+ };
115
+
116
+ /** Arm 1's discriminator applied to a tool-arg path: `false` when the file was
117
+ * listed at snapshot and its mtime has not moved (a prior round the unit
118
+ * merely named — a failed edit, a read-back — is not a collection). */
119
+ const writtenSinceSnapshot = (ctx: CollectContext<VerdictSnapshot>, raw: unknown): boolean => {
120
+ if (typeof raw !== "string") return false;
121
+ const p = normalized(ctx.cwd, raw);
122
+ const known = ctx.snapshot?.get(basename(p));
123
+ if (known === undefined) return true;
124
+ try {
125
+ return statSync(join(ctx.cwd, p)).mtimeMs > known;
126
+ } catch {
127
+ return true; // gone since snapshot — not a stale prior round
128
+ }
129
+ };
130
+
131
+ /** Arm 2's pattern: tightened to the determined name when both segments are
132
+ * known, else today's loose directory pattern (the `directoryPathCollector`
133
+ * idiom over the verdict dir). */
134
+ const transcriptPattern = (dir: string, determined: string | undefined): RegExp =>
135
+ determined !== undefined
136
+ ? new RegExp(String.raw`${escapeRegex(dir)}/${escapeRegex(determined)}[\w.-]+\.json`, "g")
137
+ : new RegExp(String.raw`${escapeRegex(dir)}/[\w.-]+\.json`, "g");
138
+
139
+ /** Arm 3 — write tool-calls whose `input.path` sits under the verdict dir
140
+ * (tightened to the determined name when known); last write wins. */
141
+ const lastWriteUnderDir = async (
142
+ ctx: CollectContext<VerdictSnapshot>,
143
+ dir: string,
144
+ determined: string | undefined,
145
+ ): Promise<Artifact | undefined> => {
146
+ const writes = toolCallCollector({
147
+ match: (tc) => {
148
+ if (!isWriteTool(tc) || !writtenSinceSnapshot(ctx, tc.input.path)) return false;
149
+ const raw = tc.input.path;
150
+ if (typeof raw !== "string") return false;
151
+ const p = normalized(ctx.cwd, raw);
152
+ if (!p.includes(`${dir}/`)) return false;
153
+ return determined === undefined || basename(p).startsWith(determined);
154
+ },
155
+ toArtifact: (tc) => {
156
+ const raw = tc.input.path;
157
+ return typeof raw === "string" ? { handle: fsHandle(normalized(ctx.cwd, raw)), role: "primary" } : undefined;
158
+ },
159
+ });
160
+ const scanned = await writes.collect(ctx);
161
+ return scanned.kind === "ok" && scanned.artifacts.length > 0
162
+ ? scanned.artifacts[scanned.artifacts.length - 1]
163
+ : undefined;
164
+ };
165
+
166
+ /** Build the disk-first verdict collector. */
167
+ export function verdictCollector(opts: VerdictCollectorOpts): ArtifactCollector<VerdictSnapshot> {
168
+ const { dir, sourceChannel } = opts;
169
+ return defineCollector<VerdictSnapshot>({
170
+ snapshot: (ctx) => {
171
+ try {
172
+ const listing = new Map<string, number>();
173
+ for (const name of readdirSync(join(ctx.cwd, dir))) {
174
+ if (!name.endsWith(".json")) continue;
175
+ listing.set(name, statSync(join(ctx.cwd, dir, name)).mtimeMs);
176
+ }
177
+ return listing;
178
+ } catch {
179
+ return undefined; // absent/unreadable at snapshot time — fail-soft
180
+ }
181
+ },
182
+ collect: async (ctx) => {
183
+ const stem = gradedBasename(ctx.state, sourceChannel);
184
+ const dimension = ctx.unitLabel;
185
+ const determined = stem !== undefined && dimension !== undefined ? `${stem}__${dimension}__` : undefined;
186
+ // Arm 1: disk.
187
+ const rel = collectFromDisk(ctx, dir, determined);
188
+ if (rel !== undefined) return { kind: "ok", artifacts: [{ handle: fsHandle(rel), role: "primary" }] };
189
+ // Arm 2: transcript text (pattern tightened when determined; tool-args
190
+ // narrowed to write/edit calls on paths written since the snapshot).
191
+ const scanned = await transcriptPathCollector({
192
+ pattern: transcriptPattern(dir, determined),
193
+ match: (tc) => isWriteTool(tc) && writtenSinceSnapshot(ctx, tc.input.path),
194
+ }).collect(ctx);
195
+ if (scanned.kind === "ok" && scanned.artifacts.length > 0) return scanned;
196
+ // Arm 3: write tool-call arguments.
197
+ const written = await lastWriteUnderDir(ctx, dir, determined);
198
+ if (written !== undefined) return { kind: "ok", artifacts: [written] };
199
+ // All three missed — ONE composite fatal naming every attempted surface.
200
+ const scope = determined !== undefined ? `${dir}/${determined}*.json` : `${dir}/*.json`;
201
+ return {
202
+ kind: "fatal",
203
+ message: `${ctx.skill}: no verdict collected — ${scope} new since snapshot, assistant text, and write tool-call arguments all missed`,
204
+ };
205
+ },
206
+ });
207
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * verdict-outcome — the verdict channel factory every grade/confirm stage
3
+ * shares: `name` is the `state.named` channel the stage's verdicts publish
4
+ * under (slice-verdicts / plan-verdicts / code-verdicts / ship-verdicts), and
5
+ * `sourceChannel` is the channel carrying the artifact under judgment — the
6
+ * disk-first verdict collector resolves the verdict filename's
7
+ * `<basename>__` segment from it. The parser MUST stay — by reference, the
8
+ * parser itself, never a wrapper: when a stage declares no parser, the
9
+ * extraction fallback publishes `data = artifacts` (the raw `Artifact[]` as
10
+ * channel data), which the gate folds' latestChannelData reads and the
11
+ * contract-schema validation both reject.
12
+ *
13
+ * Collection is DISK-FIRST (the grade skill's `<basename>__<dimension>__*.json`
14
+ * naming contract): the newest verdict file written since the unit's snapshot
15
+ * wins; the transcript scan (text + write tool-arguments) is the fallback, and
16
+ * a single composite fatal fires only when all three surfaces miss.
17
+ *
18
+ * Main's shared-instance shape: the factory's returned objects are STATELESS
19
+ * per dispatch (the disk snapshot is captured by the runner per stage-unit and
20
+ * threaded through `ctx`, never stored on the collector), so a grade stage and
21
+ * its confirm twin may share one instance per channel.
22
+ */
23
+
24
+ import { jsonBodyParser, type Outcome } from "@juicesharp/rpiv-workflow/registration";
25
+ import { VERDICT_DIR } from "./shared.js";
26
+ import { verdictCollector } from "./verdict-collector.js";
27
+
28
+ /**
29
+ * The verdict outcome factory: one instance per channel, over the channel
30
+ * carrying the artifact it grades.
31
+ */
32
+ export const verdictOutcome = (name: string, sourceChannel: string): Outcome<unknown, "json", unknown> => ({
33
+ name,
34
+ collector: verdictCollector({ dir: VERDICT_DIR, sourceChannel }),
35
+ parser: jsonBodyParser,
36
+ });
@@ -458,7 +458,10 @@ export function renderLiveOutputBorder(theme: Theme, width: number): string {
458
458
  * and ≤1 line by construction so the console's constant-height invariant holds. Its
459
459
  * outcome can legitimately diverge from the lane chip (the accepted
460
460
  * `droppedFailureRows` divergence: recap reads "completed" off the trail while the
461
- * chip shows ✗ failed).
461
+ * chip shows ✗ failed). `routingNotes`, when the recap carries them, render as
462
+ * dim parts between the artifact-arrow parts and the `⚠` reason — the
463
+ * honest pass-through floors' deferral notes, visible without claiming a line
464
+ * of their own.
462
465
  */
463
466
  export function renderRecap(theme: Theme, width: number, runId: string): string[] {
464
467
  const recap = getLane(runId)?.recap;
@@ -469,6 +472,12 @@ export function renderRecap(theme: Theme, width: number, runId: string): string[
469
472
  parts.push(theme.fg("muted", `→ ${displayArtifact(recap.artifacts[n - 1])}`));
470
473
  if (n > 1) parts.push(theme.fg("dim", `+${n - 1} more`));
471
474
  }
475
+ // Route-note recap — dim parts, ordered after the artifact-arrow parts and
476
+ // before the `⚠` failure-reason part (one part per note). The notes ride the
477
+ // SAME joined-and-truncated single line, so the console's constant-height
478
+ // invariant holds; a stop's note never appears here — the stopped refinement
479
+ // already renders it once as the `⚠` failureReason.
480
+ for (const note of recap.routingNotes ?? []) parts.push(theme.fg("dim", note));
472
481
  // Failure reason only for a non-completed outcome that carries one.
473
482
  if (recap.outcome !== "completed" && recap.failureReason) {
474
483
  parts.push(theme.fg("warning", `⚠ ${recap.failureReason}`));
@@ -194,7 +194,7 @@ export async function registerLaneProgress(): Promise<void> {
194
194
  units: info.units ? { done: 0, total: info.units.length } : undefined,
195
195
  });
196
196
  },
197
- // NEW — the previously-missing half of the bracket. Materialize a per-unit
197
+ // Materialize a per-unit
198
198
  // sub-row (label + running) for fan-out units ONLY. The host publishes the
199
199
  // live session separately (setCurrentSession at this index); both upsert the
200
200
  // same key in either order. The lifecycle bus is the sole cross-package channel.
@@ -33,7 +33,7 @@ export interface LaneUsage {
33
33
  /** Scalar cost, USD (`SessionStats.cost`). Optional — surfaced when present. */
34
34
  cost?: number;
35
35
  /** Context-window fill %, or `null` if unknown post-compaction
36
- * (`SessionStats.contextUsage.percent`). Optional — Slice 3 renders `CH%`. */
36
+ * (`SessionStats.contextUsage.percent`). Optional — the lane progress UI renders `CH%`. */
37
37
  percent?: number | null;
38
38
  }
39
39