@juicesharp/rpiv-pi 2.13.4 → 2.13.6

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 (29) hide show
  1. package/README.md +1 -1
  2. package/extensions/rpiv-core/agents-allowlist.ts +47 -0
  3. package/extensions/rpiv-core/agents-inject.ts +151 -0
  4. package/extensions/rpiv-core/agents-manifest.ts +102 -0
  5. package/extensions/rpiv-core/agents-sync.ts +405 -0
  6. package/extensions/rpiv-core/agents-types.ts +115 -0
  7. package/extensions/rpiv-core/agents.ts +35 -773
  8. package/extensions/rpiv-core/built-in-workflows.ts +13 -1426
  9. package/extensions/rpiv-core/built-ins/citations.ts +1 -1
  10. package/extensions/rpiv-core/built-ins/gate-passes.ts +498 -0
  11. package/extensions/rpiv-core/built-ins/gate-rosters.ts +275 -0
  12. package/extensions/rpiv-core/built-ins/gates.ts +34 -951
  13. package/extensions/rpiv-core/built-ins/index.ts +5 -3
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +1 -1
  15. package/extensions/rpiv-core/built-ins/slice-checks.ts +3 -3
  16. package/extensions/rpiv-core/built-ins/verdict-core.ts +202 -0
  17. package/extensions/rpiv-core/outcome-derivation.ts +2 -1
  18. package/extensions/rpiv-core/pi-compat.ts +59 -0
  19. package/extensions/rpiv-core/run-lane-registry.ts +28 -225
  20. package/extensions/rpiv-core/run-lane-types.ts +240 -0
  21. package/extensions/rpiv-core/sdk-workflow-host.ts +46 -18
  22. package/extensions/rpiv-core/workflows/build.ts +695 -0
  23. package/extensions/rpiv-core/workflows/polish.ts +62 -0
  24. package/extensions/rpiv-core/workflows/shared.ts +300 -0
  25. package/extensions/rpiv-core/workflows/ship.ts +329 -0
  26. package/extensions/rpiv-core/workflows/vet.ts +133 -0
  27. package/package.json +3 -2
  28. package/skills/_shared/stitch-elaborations.mjs +1 -1
  29. package/skills/elaborate/_helpers/validate-workflow-invariant.mjs +7 -5
@@ -1,970 +1,53 @@
1
1
  /**
2
- * The deterministic gate layer the built-in workflows' quality gates consult:
3
- * dimension rosters, tier machinery, verdict folds, risk-duty folds, and the
4
- * per-gate pass predicates. Pure state-reading folds — no fs I/O, no LLM.
2
+ * Conservation facade over the gates layer split — `verdict-core.ts` (rosters
3
+ * + verdict micro-folds) → `gate-rosters.ts` (tier machinery + risk-duty
4
+ * folds) → `gate-passes.ts` (pass predicates + progress hooks). Re-exports
5
+ * the exact pre-split 36-symbol surface, grouped by source module, so every
6
+ * consumer — the built-in workflows, the composition test's deep imports,
7
+ * the graph-attached movers — keeps its `./gates.js` specifier unchanged.
8
+ * Zero logic lives here: pure named re-exports, no `export *`; new gate code
9
+ * lands in the layer that owns it and is surfaced here by name.
5
10
  */
6
- import { basename } from "node:path";
7
- import { handleToString, type Output, type ProgressValue, type RunView } from "@juicesharp/rpiv-workflow/registration";
8
- import { FILE_LINE_CITATION_RE, latestFsArtifact } from "./shared.js";
9
-
10
- /**
11
- * The single LLM dimension the EARLY gate grades the slice map against — before
12
- * any design. `design-readiness` asks the one question the whole gate exists to
13
- * answer: is each slice chewable by ONE `design-slice` pass? It subsumes the old
14
- * four-way panel (right-sizing + vertical-shape + design-readiness + the
15
- * contract-ownership half of independence) into one holistic judgment — taking
16
- * its own name from that design-readiness member, the dominant sub-aspect — so
17
- * the formerly-opposing split-pressure (right-sizing) and merge-pressure
18
- * (vertical-shape) forces are reconciled by ONE grader instead of two blind
19
- * panelists that ping-pong the reslice loop. The structural floor that was the
20
- * other half of independence — dependency-cycle freedom — plus brief-coverage
21
- * conservation are enforced DETERMINISTICALLY by `slice-check`, not graded
22
- * here. Mirrors the `design-readiness` rubric row in the `grade` skill.
23
- */
24
- const SLICE_DIMENSIONS = ["design-readiness"] as const;
25
-
26
- /**
27
- * Quality dimensions the LATER gate grades the synthesized plan against.
28
- * Includes `architecture-fit`: build front-loads a `research` stage, so the
29
- * research artifact is always present to feed that dimension's `--context`
30
- * (threaded in by `gradePanelFanout` for this one dimension).
31
- */
32
- const PLAN_DIMENSIONS = [
33
- "completeness",
34
- "correctness",
35
- "actionability",
36
- "pattern-following",
37
- "architecture-fit",
38
- ] as const;
39
-
40
- /**
41
- * The FIXED three-dimension roster ship's grade panel grades — the bespoke,
42
- * tier-independent counterpart of `PLAN_DIMENSIONS`. Ship is a lightweight
43
- * preset: it front-loads `research` (so `architecture-fit` always has its
44
- * `--context`) and grades a trimmed, always-on set regardless of run shape.
45
- * `SHIP_DIMENSION_FANOUT` and `shipGatePasses` bind this roster DIRECTLY — no
46
- * `gateRoster(gateTier(...))` wrap — so a single-phase ship run still grades
47
- * `architecture-fit`, the dimension a tiered gate would drop in the light
48
- * roster. Order mirrors `PLAN_DIMENSIONS` (goal-anchored dimensions first,
49
- * fit last) so the emitted units stay stable.
50
- */
51
- export const SHIP_DIMENSIONS = ["completeness", "correctness", "architecture-fit"] as const;
52
-
53
- /**
54
- * The plan-authored risk-flag ruling unit, split OUT of `correctness` so the
55
- * two judgments run as concurrent panel members instead of one serial judge.
56
- * Across 175 build panels the correctness unit finished last in 140 (80%), at
57
- * 2.2× the median sibling with no flags and no prior, and the risk-ruling +
58
- * prior-adjudication duties added ~1.7 min on top (4.9 → 6.6 min p50) — the
59
- * panel's wall time IS the correctness unit's. This dimension rules every
60
- * `risks:` flag (the mechanics-evidence and verify-at-implement duties move
61
- * with it, see the `grade` skill), adjudicates its OWN prior rulings on a
62
- * re-grade, and emits `risk_rulings` — the field every risk fold reads
63
- * (`allRiskFlagsPass`, `dimensionsToRegrade` clause 3, `confirmDue`,
64
- * `demoteDuties`, amend's cite derivation). Correctness keeps only its
65
- * semantic three-class findings. Dispatched ONLY when the graded channel's
66
- * latest record declares `risks:` (`panelRoster`) — a plan with no flags
67
- * pays for no unit — and at EVERY tier when it does (the light roster used to
68
- * rule risks through its correctness member; the duty follows the split). A
69
- * legacy trail whose correctness verdicts still carry `risk_rulings` folds
70
- * unchanged: every risk fold is dimension-agnostic.
71
- */
72
- export const RISK_DIMENSION = "risk-rulings" as const;
73
-
74
- /**
75
- * The two dimensions the grade panels anchor against the verbatim brief.
76
- * "Complete" and "correct" MEAN "against what the user asked" — without the
77
- * goal, completeness grades the plan against the plan's own claims. The other
78
- * dimensions (and the slice gate's `design-readiness`) deliberately stay
79
- * goal-blind: fit/actionability/pattern-following judge the artifact against
80
- * the codebase, and an ambient goal at those seams invites scope inflation.
81
- */
82
- const GOAL_DIMENSIONS: ReadonlySet<string> = new Set(["completeness", "correctness"]);
83
-
84
- // ---------------------------------------------------------------------------
85
- // Adaptive gate scaling — tier, roster, verdict freshness.
86
- // ---------------------------------------------------------------------------
87
-
88
- /** Latest `data` record published under `name` (undefined when absent/non-record). */
89
- const latestChannelData = (state: RunView, name: string): Record<string, unknown> | undefined => {
90
- const data = state.named[name]?.at(-1)?.data;
91
- return data !== null && typeof data === "object" && !Array.isArray(data)
92
- ? (data as Record<string, unknown>)
93
- : undefined;
94
- };
95
-
96
- /** A finite numeric field off the latest `data` on `name` (undefined otherwise). */
97
- const channelNumber = (state: RunView, name: string, field: string): number | undefined => {
98
- const v = latestChannelData(state, name)?.[field];
99
- return typeof v === "number" && Number.isFinite(v) ? v : undefined;
100
- };
101
-
102
- /** Repo-relative path of the latest fs artifact on `name` (undefined if none). */
103
- const latestArtifactPath = (state: RunView, name: string): string | undefined => {
104
- const a = latestFsArtifact(state, name);
105
- return a?.handle.kind === "fs" ? handleToString(a.handle) : undefined;
106
- };
107
-
108
- /**
109
- * Gate scrutiny tier, derived ONLY from signals already replayed by the resume
110
- * fold (the slices/plans channels' frontmatter data and the gate's own verdict
111
- * severities) — deterministic by construction, so routes and fanout units that
112
- * consult it stay resume-safe.
113
- *
114
- * `risks:` flags are deliberately NOT a tier signal: `synthesize` declares
115
- * them routinely (observed: 1-phase plans shipping 2-3 flags), so counting
116
- * them would push every small run out of the light tier. Risk flags are
117
- * already force-ruled per dimension via `risk_rulings`, and a blocking
118
- * verdict lifts the tier on its own (below).
119
- *
120
- * A missing signal never yields light, and verdict severities are read over
121
- * the FULL channel history (a stale medium/high is still evidence of a risky
122
- * run) — ambiguity always resolves toward more scrutiny.
123
- */
124
- type GateTier = "light" | "standard" | "strict";
125
- const TIER_LIGHT_MAX_SLICES = 1;
126
- const TIER_LIGHT_MAX_PHASES = 2;
127
- const TIER_STRICT_MIN_SLICES = 5;
128
- const TIER_STRICT_MIN_PHASES = 6;
129
-
130
- /**
131
- * The dimensions a light-tier run still grades: correctness and completeness
132
- * are the two whose failures ship real defects (and the two that anchor on the
133
- * goal); fit/actionability/pattern-following are low-consequence on a
134
- * one-slice, <=2-phase diff, and `validate` still runs at every tier.
135
- */
136
- const LIGHT_ROSTER: ReadonlySet<string> = new Set(["correctness", "completeness"]);
137
-
138
- const gateTier = (state: RunView, verdictChannel: string): GateTier => {
139
- const slices = channelNumber(state, "slices", "slice_count");
140
- const phases = channelNumber(state, "plans", "phase_count");
141
- const severities = new Set<string>();
142
- for (const o of state.named[verdictChannel] ?? []) {
143
- const v = o.data as { severity?: unknown; findings?: unknown } | undefined;
144
- const s = v?.severity;
145
- // Anchor-nit clamp: an all-drift-nit verdict must not escalate the tier.
146
- // Deliberately NOT `verdictBlocks` — this fold arbitrates severity VALUES,
147
- // not blocking; the clamp lowers the recorded value only.
148
- if (typeof s === "string") severities.add(anchorNitsOnly(v) ? "low" : s);
149
- }
150
- if (
151
- (slices !== undefined && slices >= TIER_STRICT_MIN_SLICES) ||
152
- (phases !== undefined && phases >= TIER_STRICT_MIN_PHASES) ||
153
- severities.has("high")
154
- ) {
155
- return "strict";
156
- }
157
- if (
158
- slices !== undefined &&
159
- slices <= TIER_LIGHT_MAX_SLICES &&
160
- phases !== undefined &&
161
- phases <= TIER_LIGHT_MAX_PHASES &&
162
- !severities.has("medium")
163
- ) {
164
- return "light";
165
- }
166
- return "standard";
167
- };
168
-
169
- /**
170
- * The subset of `dimensions` the tier actually grades. Never empty: a
171
- * dimension list with no light-roster member (the slice gate's lone
172
- * `design-readiness`) keeps its full list at every tier.
173
- */
174
- const gateRoster = (tier: GateTier, dimensions: readonly string[]): readonly string[] => {
175
- if (tier !== "light") return dimensions;
176
- const light = dimensions.filter((d) => LIGHT_ROSTER.has(d));
177
- return light.length > 0 ? light : dimensions;
178
- };
179
-
180
- /**
181
- * The roster a panel over `channel` actually dispatches and its gate actually
182
- * folds: the tier roster (`gateRoster(gateTier(...))`) plus the
183
- * `RISK_DIMENSION` unit whenever the channel's latest record declares
184
- * `risks:` — at every tier, never otherwise. ONE construction site shared by
185
- * the panel's `units()`, the gate predicates, `confirmDue`, and the progress
186
- * hook, so "dispatch", "fold", "confirm", and "lap complete" can never
187
- * disagree on whether the risk unit is a roster member. A roster that never
188
- * declares risks (the slice gate over `slices`) is unchanged. Idempotent over
189
- * a `dimensions` list that already names the risk dimension.
190
- */
191
- const panelRoster = (
192
- state: RunView,
193
- channel: string,
194
- verdictChannel: string,
195
- dimensions: readonly string[],
196
- ): readonly string[] => {
197
- const roster = gateRoster(gateTier(state, verdictChannel), dimensions);
198
- if (roster.includes(RISK_DIMENSION) || planAuthoredRisks(state, channel).size === 0) return roster;
199
- return [...roster, RISK_DIMENSION];
200
- };
201
-
202
- /**
203
- * Ship's tier-independent twin of `panelRoster`: `SHIP_DIMENSIONS` verbatim
204
- * (never `gateRoster(gateTier(...))`) plus the risk unit when the plan
205
- * declares `risks:`. Bound by the ship panel, `shipGatePasses`, and ship's
206
- * stop note alike.
207
- */
208
- const shipRoster = (state: RunView): readonly string[] =>
209
- planAuthoredRisks(state, "plans").size === 0 ? SHIP_DIMENSIONS : [...SHIP_DIMENSIONS, RISK_DIMENSION];
210
-
211
- /**
212
- * Drop verdicts judged against an artifact the channel has since REPLACED. A
213
- * grade verdict embeds the `artifact` path it judged; when a fix REGENERATES
214
- * the artifact (`slice-fix` re-slices to a NEW file) a passing verdict on the
215
- * old document must not carry forward to a document that was never judged —
216
- * the carry-forward would otherwise let a regenerated slice map skip its
217
- * design-readiness judgment entirely. An in-place `amend` keeps the path, so
218
- * the plan-fix/code-fix carry-forward is unaffected. A verdict without an
219
- * `artifact` field (older trails, the deterministic structure checks) is kept:
220
- * matching is the compat default.
221
- */
222
- const freshVerdicts = (entries: readonly Output[] = [], currentArtifact?: string): readonly Output[] => {
223
- if (!currentArtifact) return entries;
224
- const current = basename(currentArtifact);
225
- return entries.filter((o) => {
226
- const a = (o.data as { artifact?: unknown } | undefined)?.artifact;
227
- return typeof a !== "string" || a.length === 0 || basename(a) === current;
228
- });
229
- };
230
-
231
- /**
232
- * Latest verdict per dimension off an accumulated verdict channel — the shared
233
- * fold under `dimensionsToRegrade` (which dimensions still block) and the
234
- * confirm panels' `--prior` threading (which verdict file the confirming
235
- * grader must adjudicate).
236
- */
237
- const latestVerdictPerDimension = (entries: readonly Output[] = []): Map<string, Output> => {
238
- const latest = new Map<string, Output>();
239
- for (const o of entries) {
240
- const dim = (o.data as { dimension?: unknown } | undefined)?.dimension;
241
- if (typeof dim === "string") latest.set(dim, o);
242
- }
243
- return latest;
244
- };
245
-
246
- /**
247
- * Anchor-drift-nit phrasing, two tiers: only phrasings naming drift itself
248
- * count standalone; the location shapes (off-by-N, "is at line N", "line N is
249
- * the/a") also match REAL defects ("line 42 is a comment that falsely claims
250
- * X", "the loop bound is off by one") and count ONLY alongside citing-context
251
- * vocabulary — every observed drift nit has it, real-defect phrasings don't.
252
- * Do NOT widen, and do NOT promote a location shape to standalone.
253
- */
254
- const ANCHOR_NIT_DRIFT_RE = /\bdrifted?\s+~?\d+\s+lines?\b|\bcitation (?:is )?drifted\b/i;
255
- const ANCHOR_NIT_LOCATION_RE =
256
- /\boff[- ]by[- ](?:one|two|three|\d+)\b|(?::\d+|\bline \d+) is (?:the|a)\b|\bis at line \d+\b/i;
257
- const ANCHOR_NIT_CITE_CONTEXT_RE = /\bcit(?:es?|ed|ation)\b|\banchor/i;
258
-
259
- const isAnchorNitDetail = (detail: string): boolean =>
260
- ANCHOR_NIT_DRIFT_RE.test(detail) || (ANCHOR_NIT_LOCATION_RE.test(detail) && ANCHOR_NIT_CITE_CONTEXT_RE.test(detail));
261
-
262
- /**
263
- * TRUE when a verdict carries ≥1 finding and EVERY finding is an anchor-drift
264
- * nit (`isAnchorNitDetail`). Such a verdict is severity-clamped to non-blocking
265
- * at the gate fold regardless of the grader's own `severity` — line-number
266
- * drift was measured at 34% of all grader findings with zero downstream harm,
267
- * and a mis-rated all-nit `medium` verdict buys a full fix round + re-grade
268
- * panel that repairs nothing. A verdict mixing a drift nit with ANY other
269
- * finding is untouched — the other finding may be the real blocker.
270
- */
271
- const anchorNitsOnly = (v: { findings?: unknown } | undefined): boolean => {
272
- const findings = Array.isArray(v?.findings) ? v.findings : [];
273
- return (
274
- findings.length > 0 &&
275
- findings.every((f) => {
276
- const detail = (f as { detail?: unknown } | undefined)?.detail;
277
- return typeof detail === "string" && isAnchorNitDetail(detail);
278
- })
279
- );
280
- };
281
-
282
- /**
283
- * The shared verdict shape every blocking fold reads: `pass` (the grader's
284
- * free-judgment boolean), `severity` (the graded bar — `low`/`none` never
285
- * block), and `findings` (the anchor-nit clamp's input). Consumers narrow
286
- * further at their own cast (`allDimensionsPass` also reads `dimension`), so
287
- * the dead-unit sentinel shape — a dimension label with none of these
288
- * fields — still satisfies it.
289
- */
290
- type VerdictRecord = { pass?: boolean; severity?: string; findings?: unknown };
291
-
292
- /**
293
- * The ONE blocking predicate over a grade verdict's own fields: a verdict
294
- * blocks UNLESS its `pass` is `true`, its severity sits at the `low`/`none`
295
- * floor, or the anchor-nit clamp applies (every finding a drift nit).
296
- * `dimensionsToRegrade`, `allDimensionsPass`, `confirmDue`, and ship's
297
- * `shipGradeStopNote` all fold through this single definition, so the
298
- * re-grade list, the gate folds, the confirm arm, and the stop note can
299
- * never drift apart (each site used to hand-roll the same disjunction).
300
- * Deliberately RISK-BLIND: `risk_rulings` compose ON TOP only where owed
301
- * (`confirmDue`), never folded in here. A record with none of the three
302
- * exits — a dimension-bearing sentinel, an older bare trail — reads
303
- * BLOCKING: fail-safe, same direction as a failed verdict.
304
- */
305
- const verdictBlocks = (v: VerdictRecord | undefined): boolean =>
306
- !(v?.pass === true || v?.severity === "low" || v?.severity === "none" || anchorNitsOnly(v));
307
-
308
- /**
309
- * The subset of `dimensions` a re-grade must actually re-run, given the latest
310
- * verdict per dimension accumulated so far. A dimension needs re-grading when it
311
- * has NO prior verdict (first pass ⇒ grade every dimension), when its latest
312
- * verdict fails above the severity floor, or when that verdict ruled any plan
313
- * risk flag `fail` (the ruling is re-opened by re-grading its owning dimension).
314
- * A dimension that already passed — dimension AND its risk rulings — is carried
315
- * forward untouched: re-running it after a surgical fix only re-rolls a free LLM
316
- * judgment that flaps pass↔fail on an unchanged artifact, manufacturing extra
317
- * loops (the observed correctness risk-flag flap). The accumulating verdict
318
- * channel + `allDimensionsPass`'s latest-per-dimension fold mean a carried
319
- * dimension's prior passing verdict still counts at the gate.
320
- */
321
- const dimensionsToRegrade = (
322
- dimensions: readonly string[],
323
- latest: ReadonlyMap<string, Output>,
324
- risks: ReadonlyMap<string, RiskRecord> = new Map(),
325
- ): string[] => {
326
- return dimensions.filter((d) => {
327
- const o = latest.get(d);
328
- if (!o) return true; // never graded — must grade at least once
329
- const v = o.data as VerdictRecord | undefined;
330
- if (verdictBlocks(v)) return true;
331
- return verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
332
- });
333
- };
334
-
335
- /**
336
- * Fold the per-dimension verdicts into a gate decision: keep the latest verdict
337
- * per dimension (verdicts accumulate across fix loops), require all-pass.
338
- * Deterministic ⇒ resume-safe for a `readsData: false` route.
339
- *
340
- * Severity floor: a verdict whose worst finding is `low`/`none` never blocks the
341
- * gate, even when the grader set `pass: false` on a nit. `grade` decides `pass`
342
- * by a free judgment against a prose bar (independent of `severity`), so a
343
- * marginal dimension can flip pass↔fail across rounds on an unchanged artifact —
344
- * that flapping, ANDed over a 5-dimension panel, stalled the build gate loops
345
- * until the backward-jump guard halted them. Flooring on severity reserves a hard
346
- * fail for `medium`+ findings (the deterministic `slice-check` check emits
347
- * `high` on a real structural break, so it still blocks). A verdict with no
348
- * `severity` (an older or replayed grade) falls back to the raw `pass` boolean.
349
- *
350
- * SENTINELS: a failed-unit sentinel the fanout fold placed carries
351
- * `data.dimension` when the dead unit was labeled (grade panels label each
352
- * dimension unit with the dimension it grades). Such an entry registers here
353
- * with no `pass`/`severity` — it reads BLOCKING. That is the fix for the
354
- * three intentional behaviors that composed into the dead-unit gate pass:
355
- * (1) a collected soft-halt is a PERMANENT skip — the dead unit contributes
356
- * no verdict, only its sentinel; (2) the fold places the sentinel BY INDEX,
357
- * overwriting whatever the slot held from prior rounds — the stale round-1
358
- * fail the gate should have blocked on was erased from the channel;
359
- * (3) a sentinel with NO dimension is skipped by this fold — absence is not
360
- * failure — so the gate folded only the four surviving passes and routed
361
- * onward. The dimension field closes all three: the unresolved dimension now
362
- * reads as its own latest, blocking entry. (Mirror: an UNFILLED slot — infra
363
- * death, no row — leaves the stale entry in place and also blocks;
364
- * `unitFailedDimensions` distinguishes the dead-unit shape for routing.)
365
- */
366
- const allDimensionsPass = (entries: readonly Output[] = [], roster?: readonly string[]): boolean => {
367
- // Roster-filtered when given: a verdict for a dimension outside the tier's
368
- // roster (a wider earlier round, a shrunk re-slice) neither blocks nor passes
369
- // a gate it no longer governs.
370
- const member = roster ? new Set(roster) : undefined;
371
- const latest = new Map<string, boolean>();
372
- for (const o of entries) {
373
- const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
374
- if (typeof v?.dimension !== "string") continue;
375
- if (member && !member.has(v.dimension)) continue;
376
- // The shared blocking predicate keeps every severity fold on one
377
- // definition of "blocking" (the anchor-nit clamp backstops the
378
- // citation-resolution rule: an all-drift-nit verdict never blocks,
379
- // whatever severity the grader typed).
380
- latest.set(v.dimension, !verdictBlocks(v));
381
- }
382
- const verdicts = [...latest.values()];
383
- return verdicts.length > 0 && verdicts.every(Boolean);
384
- };
385
-
386
- /**
387
- * The rule core under every whole-lap progress declaration: map the
388
- * blocking-dimension counts of the COMPLETED rounds behind the current one
389
- * (oldest first) plus the current round's own count to ONE ProgressValue.
390
- *
391
- * [] ⇒ "unknown" — nothing completed behind the current
392
- * round (the first lap): counted, never
393
- * waived.
394
- * < min(earlier) ⇒ "improved" — the blocking set strictly shrank past
395
- * EVERY earlier round's best; no score
396
- * tiebreak — the count is the whole signal.
397
- * > last(earlier) ⇒ "regressed" — grew past the immediately previous round.
398
- * otherwise ⇒ "unchanged" — flat or between: counted.
399
- *
400
- * Deliberately coarse: the waiver buys one extra lap only when the panel's
401
- * blocking set strictly shrank past every completed round, so flat, flapping,
402
- * or partially-improving trails keep counting toward the backward-jump cap.
403
- * Pure arithmetic over counts — no state, no channel reads — so the lane
404
- * instances and the replay harnesses share one definition of "a lap
405
- * improved".
406
- */
407
- const progressFromRoundCounts = (earlier: readonly number[], current: number): ProgressValue => {
408
- if (earlier.length === 0) return "unknown";
409
- if (current < Math.min(...earlier)) return "improved";
410
- if (current > earlier[earlier.length - 1]) return "regressed";
411
- return "unchanged";
412
- };
413
-
414
- /**
415
- * The whole-lap progress hook factory — the `progress` the quality-panel lanes
416
- * declare on EVERY stage the backward-jump guard can re-enter (grade /
417
- * fix-or-confirm / snapshot per lane). One instance per lane, shared by the
418
- * lane's re-entered destinations, so a lap reads as ONE unit: the hook derives
419
- * a round's blocking count by folding the lane's OWN verdict channel exactly
420
- * the way its gate does — latest verdict per dimension over the entries still
421
- * fresh for the current artifact — and counts blocking dimensions through the
422
- * shared `verdictBlocks` predicate over the tier roster (`gateRoster(gateTier(
423
- * state, verdictChannel), dimensions)`, computed once per call and applied to
424
- * every round uniformly).
425
- *
426
- * ROUND DELINEATION — two modes:
427
- *
428
- * snapshot mode (`options.snapshotChannel` set — the plan/code lanes, whose
429
- * fixes AMEND the plan in place so the artifact basename never changes):
430
- * rounds are cut at each snapshot row's `meta.ts` (ISO-8601 compares
431
- * lexicographically); a cut is a COMPLETED earlier round iff the verdict
432
- * channel grew strictly past it — the last cut with nothing after it is the
433
- * CURRENT round, excluded from the earlier set. The current round folds the
434
- * WHOLE channel (carry-forward: a dimension not re-graded keeps its latest
435
- * prior verdict — the same cumulative fold the gate itself reads).
436
- *
437
- * basename mode (no snapshotChannel — the slice lane, whose fixes RE-SLICE
438
- * to a new file): rounds are maximal runs of entries sharing
439
- * `basename(data.artifact)`; earlier = every group but the last, current =
440
- * the last group's fold. A regenerated artifact re-grades from scratch, so a
441
- * healthy basename group carries the full roster; an in-place amend keeps
442
- * the basename, so amended rounds merge — degradation is toward counting,
443
- * never toward a spurious waiver.
444
- *
445
- * FAIL-SAFE: a roster dimension with NO verdict in the current round's fold ⇒
446
- * "unknown" (the round is incomplete — never waive on missing evidence); an
447
- * entry without a string `meta.ts` lands in every earlier snapshot cut and in
448
- * the current fold, so a malformed trail degrades toward counting. Pure
449
- * channel history — no module state, no file reads, no model calls — so the
450
- * hook is resume-safe by construction (the resume fold replays the same
451
- * channels into `state.named`).
452
- */
453
- const panelProgress =
454
- (
455
- verdictChannel: string,
456
- dimensions: readonly string[],
457
- { snapshotChannel, artifactChannel }: { snapshotChannel?: string; artifactChannel?: string } = {},
458
- ) =>
459
- (state: RunView): ProgressValue => {
460
- // The artifact channel is where `risks:` lives, so a lane that names it
461
- // folds the risk unit into its roster exactly as its panel and gate do;
462
- // a lane without one (no plan channel to declare risks on) keeps the
463
- // tier roster.
464
- const roster =
465
- artifactChannel !== undefined
466
- ? panelRoster(state, artifactChannel, verdictChannel, dimensions)
467
- : gateRoster(gateTier(state, verdictChannel), dimensions);
468
- const entries = state.named[verdictChannel] ?? [];
469
- const currentArtifact = artifactChannel !== undefined ? latestArtifactPath(state, artifactChannel) : undefined;
470
- const foldRound = (rows: readonly Output[]): ReadonlyMap<string, Output> =>
471
- latestVerdictPerDimension(freshVerdicts(rows, currentArtifact));
472
- const countBlocking = (fold: ReadonlyMap<string, Output>): number => {
473
- let blocking = 0;
474
- for (const d of roster) {
475
- const o = fold.get(d);
476
- if (o !== undefined && verdictBlocks(o.data as VerdictRecord)) blocking += 1;
477
- }
478
- return blocking;
479
- };
480
- // An entry with no string ts reads as "" — it joins every earlier snapshot
481
- // cut (never after one), so a malformed trail can only INFLATE earlier
482
- // counts: toward counting, never toward a waiver.
483
- const tsOf = (o: Output): string => {
484
- const ts = o.meta?.ts;
485
- return typeof ts === "string" ? ts : "";
486
- };
487
- const earlierCounts: number[] = [];
488
- let currentRows: readonly Output[] = [];
489
- if (snapshotChannel !== undefined) {
490
- for (const snap of state.named[snapshotChannel] ?? []) {
491
- const cut = snap.meta?.ts;
492
- if (typeof cut !== "string") continue;
493
- // A cut the channel never grew strictly past is the CURRENT round,
494
- // not a completed earlier one.
495
- if (!entries.some((o) => tsOf(o) > cut)) continue;
496
- earlierCounts.push(countBlocking(foldRound(entries.filter((o) => tsOf(o) <= cut))));
497
- }
498
- currentRows = entries;
499
- } else {
500
- const groups: { key: string | undefined; rows: Output[] }[] = [];
501
- for (const o of entries) {
502
- const a = (o.data as { artifact?: unknown } | undefined)?.artifact;
503
- const key = typeof a === "string" && a.length > 0 ? basename(a) : undefined;
504
- const last = groups.at(-1);
505
- // An entry with no artifact continues the current group — the same
506
- // compat default freshVerdicts applies; merging rounds degrades
507
- // toward counting.
508
- if (last !== undefined && (key === undefined || last.key === key)) last.rows.push(o);
509
- else groups.push({ key, rows: [o] });
510
- }
511
- for (const g of groups.slice(0, -1)) earlierCounts.push(countBlocking(foldRound(g.rows)));
512
- currentRows = groups.at(-1)?.rows ?? [];
513
- }
514
- const currentFold = foldRound(currentRows);
515
- // An incomplete current round is "unknown" — the roster must be fully
516
- // adjudicated before the lap can claim progress.
517
- for (const d of roster) if (!currentFold.has(d)) return "unknown";
518
- return progressFromRoundCounts(earlierCounts, countBlocking(currentFold));
519
- };
520
-
521
- /**
522
- * One plan-authored risk flag ruled by a grade panel. The plan declares a
523
- * `risks:` frontmatter array (`{ id, claim }`) — the structured, first-class
524
- * channel that replaces the old prose-in-a-Notes-section flagging that graders
525
- * were free to skip. Each grade verdict that engages a flag emits a ruling here.
526
- */
527
- interface RiskRuling {
528
- id: string;
529
- pass: boolean;
530
- /**
531
- * `mechanics` marks a risk whose `pass` asserts a verified mechanism (a
532
- * behavior that holds because code was checked), so a passing ruling MUST
533
- * cite the checked `file:line` in `evidence` — an un-evidenced mechanics
534
- * pass demotes. Absent on
535
- * an ordinary risk ⇒ no evidence duty.
536
- */
537
- claim_type?: string;
538
- /** The `file:line`-shaped citation a mechanics pass must ground itself on. */
539
- evidence?: string;
540
- /**
541
- * `verify-at-implement` marks a risk the panel defers: ruled `pass` ONLY when
542
- * a concrete `procedure` + `owner` phase will re-check it at implement/validate
543
- * time. Absent ⇒ the risk is judged in this panel, not deferred.
544
- */
545
- disposition?: string;
546
- /** Named command/test the owner phase runs to discharge a deferred risk. */
547
- procedure?: string;
548
- /** The phase (`n`) that owns the deferred verify step. */
549
- owner?: number;
550
- }
551
-
552
- /** The `risk_rulings` a grade verdict emitted (empty when it ruled on none). */
553
- const verdictRiskRulings = (o: Output): RiskRuling[] => {
554
- const raw = (o.data as { risk_rulings?: unknown } | undefined)?.risk_rulings;
555
- if (!Array.isArray(raw)) return [];
556
- return raw.flatMap((e) => {
557
- const r = (e ?? {}) as Record<string, unknown>;
558
- if (typeof r.id !== "string") return [];
559
- // Read the duty fields defensively (same typeof-guard idiom as id/pass):
560
- // absent on an older/ordinary verdict ⇒ undefined ⇒ the duty helpers no-op.
561
- const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
562
- const evidence = typeof r.evidence === "string" ? r.evidence : undefined;
563
- const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
564
- const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
565
- const owner = typeof r.owner === "number" ? r.owner : undefined;
566
- return [
567
- {
568
- id: r.id,
569
- pass: r.pass === true,
570
- ...(claim_type !== undefined ? { claim_type } : {}),
571
- ...(evidence !== undefined ? { evidence } : {}),
572
- ...(disposition !== undefined ? { disposition } : {}),
573
- ...(procedure !== undefined ? { procedure } : {}),
574
- ...(owner !== undefined ? { owner } : {}),
575
- },
576
- ];
577
- });
578
- };
579
-
580
- /**
581
- * A plan-authored risk flag — the duty shape `synthesize` declares in the plan
582
- * frontmatter `risks:` array (`synthesize/SKILL.md:136`: `{ id, claim,
583
- * claim_type?, disposition?, procedure?, owner? }`). The prose `claim` is grading
584
- * copy, not a duty signal, so it is not carried here. `claim_type: "mechanics"`
585
- * and `disposition: "verify-at-implement"` are the two duty TRIGGERS — sourced
586
- * from the PLAN (not the ruling) so a panel cannot drop its discharge obligation
587
- * by simply omitting the field from its ruling (the dropped-duty bypass).
588
- */
589
- interface RiskRecord {
590
- id: string;
591
- claim_type?: string;
592
- disposition?: string;
593
- procedure?: string;
594
- owner?: number;
595
- }
596
-
597
- /**
598
- * Read the plan-authored risk flags off the latest record on `channel`, keyed
599
- * by `id`. The duty triggers live HERE (the plan's `risks:` frontmatter), not on
600
- * the grade panel's ruling, so a ruling that drops its discharge field cannot
601
- * escape the duty the plan declared (a bare `{ id, pass }` ruling against a
602
- * plan-authored `claim_type: "mechanics"` risk still demotes). Reads only
603
- * `state.named[channel]` via `latestChannelData` — no `readFileSync`, no
604
- * `cwd`, no throw — so the route's `readsData: false` / determinism /
605
- * resume-safety contract holds and a resumed run re-evaluates identically.
606
- * Degrades to an empty map (fail-open ⇒ no duty ⇒ plain ruling ⇒
607
- * `rulingEffectivePass(r) === r.pass`) when `risks:` is absent/non-array/
608
- * malformed, mirroring `latestChannelData`'s degrade-to-undefined contract.
609
- */
610
- const planAuthoredRisks = (state: RunView, channel: string): Map<string, RiskRecord> => {
611
- const risks = latestChannelData(state, channel)?.risks;
612
- const out = new Map<string, RiskRecord>();
613
- if (!Array.isArray(risks)) return out;
614
- for (const e of risks) {
615
- const r = (e ?? {}) as Record<string, unknown>;
616
- if (typeof r.id !== "string") continue;
617
- const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
618
- const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
619
- const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
620
- const owner = typeof r.owner === "number" ? r.owner : undefined;
621
- const rec: RiskRecord = { id: r.id };
622
- if (claim_type !== undefined) rec.claim_type = claim_type;
623
- if (disposition !== undefined) rec.disposition = disposition;
624
- if (procedure !== undefined) rec.procedure = procedure;
625
- if (owner !== undefined) rec.owner = owner;
626
- out.set(r.id, rec);
627
- }
628
- return out;
629
- };
630
-
631
- /**
632
- * A mechanics-pass ruling's evidence duty: when the plan AUTHORED a
633
- * `claim_type: "mechanics"` risk for the ruling's id, a `pass` ruling MUST
634
- * cite the checked `file:line` in `evidence` (forces engagement — a pass with
635
- * no evidence is an unverified mechanism). The trigger is sourced from the
636
- * plan-authored `RiskRecord`, NOT the ruling — so a panel cannot drop the
637
- * evidence duty by omitting `claim_type` from its ruling (the dropped-duty
638
- * bypass). Reuses `FILE_LINE_CITATION_RE` via `.match()` — NOT `.test()`: the
639
- * regex carries the `/g` flag, so `.test()` is stateful across calls
640
- * (`lastIndex` advances) and would
641
- * intermittently miss a present citation. An id with no authored mechanics
642
- * risk carries no evidence duty ⇒ returns `true`.
643
- */
644
- const evidenceCitesFileLine = (r: RiskRuling, authored?: RiskRecord): boolean => {
645
- if (authored?.claim_type !== "mechanics") return true;
646
- return typeof r.evidence === "string" && r.evidence.match(FILE_LINE_CITATION_RE) !== null;
647
- };
648
-
649
- /**
650
- * A deferred-risk's verify-at-implement duty: when the plan AUTHORED a
651
- * `disposition: "verify-at-implement"` risk for the ruling's id, a `pass`
652
- * ruling MUST carry a concrete `procedure` (the named command/test the owner
653
- * phase runs) AND a numeric `owner` phase — a bare "verify later" with no
654
- * procedure demotes. The trigger is sourced from the plan-authored
655
- * `RiskRecord`, NOT the ruling (the dropped-duty bypass). An id with no
656
- * authored verify-at-implement risk is judged in THIS panel, not deferred ⇒
657
- * returns `true`.
658
- */
659
- const procedureSatisfiesDuty = (r: RiskRuling, authored?: RiskRecord): boolean => {
660
- if (authored?.disposition !== "verify-at-implement") return true;
661
- return typeof r.procedure === "string" && r.procedure.length > 0 && typeof r.owner === "number";
662
- };
663
-
664
- /**
665
- * The single gate-fold authority: a ruling is effective-pass iff it is a bare
666
- * `pass` AND (when the plan authored a mechanics risk for its id) its evidence
667
- * cites a `file:line` AND (when the plan authored a verify-at-implement risk
668
- * for its id) its procedure+owner discharge the verify duty. `allRiskFlagsPass`,
669
- * `dimensionsToRegrade` clause 3, and `confirmDue`'s `riskFail` ALL consult this
670
- * — so the three risk folds agree on what "passing" means and a demoted
671
- * mechanics/deferred pass blocks the gate AND re-opens its owning dimension
672
- * AND counts as blocking for confirm (no incoherent re-grading). For a ruling
673
- * whose id the plan authored no duty for (no mechanics/verify-at-implement
674
- * risk, no `risks:` at all, or no matching id) every duty no-ops, so
675
- * `rulingEffectivePass(r, authored) === r.pass` — prior behavior is preserved.
676
- */
677
- const rulingEffectivePass = (r: RiskRuling, authored?: RiskRecord): boolean =>
678
- r.pass === true && evidenceCitesFileLine(r, authored) && procedureSatisfiesDuty(r, authored);
679
-
680
- /**
681
- * Fold the grade panel's per-flag risk rulings into a gate decision: every
682
- * plan-authored risk flag the panel ruled on must be ruled PASS (latest ruling
683
- * per flag wins, mirroring `allDimensionsPass`). A flag ruled `fail` — the
684
- * grader confirmed the risk is real and unaddressed — blocks the gate, so a
685
- * self-flagged risk (e.g. an override-vs-env validation mismatch) can no longer
686
- * ride a green conformance pass into commit. An empty panel (no flag engaged)
687
- * imposes no constraint; the plan simply declared no risks.
688
- */
689
- const allRiskFlagsPass = (
690
- entries: readonly Output[] = [],
691
- risks: ReadonlyMap<string, RiskRecord> = new Map(),
692
- ): boolean => {
693
- const latest = new Map<string, boolean>();
694
- for (const o of entries)
695
- for (const r of verdictRiskRulings(o)) latest.set(r.id, rulingEffectivePass(r, risks.get(r.id)));
696
- return [...latest.values()].every(Boolean);
697
- };
698
-
699
- /**
700
- * The three gates' pass predicates — the SINGLE authority each gate consults at
701
- * BOTH of its seams. A gate is satisfied when its deterministic cite/structure
702
- * floor is green AND every quality dimension passes (severity-floored) AND — for
703
- * the plan/code gates — every plan-authored risk flag is ruled pass.
704
- *
705
- * Reading the identical predicate at the cite/structure-check edge (which SKIPS
706
- * the re-grade straight to the next stage) and at the grade edge (which gates
707
- * forward-vs-fix) makes the skip provably equivalent to "re-grade, then pass",
708
- * minus the wasted panel: after a fix that only cleared the deterministic floor,
709
- * the accumulated verdicts already clear the gate, so re-running the LLM panel
710
- * would at best reproduce them and at worst flap a passing dimension into a
711
- * spurious fix loop. On the FIRST pass the verdict channel is empty, so
712
- * `allDimensionsPass` returns false and the edge correctly routes INTO the grade
713
- * panel. Any regression a fix introduces is still caught downstream: the plan
714
- * gate by the full first-time `code-grade`, the code gate by `validate`.
715
- */
716
- // Each predicate folds the verdicts still FRESH for the channel's current
717
- // artifact, restricted to the tier's roster — the SAME projections the panel's
718
- // `units()` uses, so "skip the re-grade" stays provably equivalent to
719
- // "re-grade, then pass". The deterministic cite/structure channels fold
720
- // unfiltered: they re-run every round and carry no tier.
721
- // The latest structure verdict carries a `citeDischarged` stamp for the
722
- // CURRENT slice map. After a fix for a `remedy: "cite"` fail, the failing
723
- // design-readiness verdict is stale (the fix re-sliced to a NEW file) and the
724
- // gate's lone dimension has no fresh verdict, so the verdict fold can never
725
- // pass — yet the fix is deterministically verifiable: `sliceStructureCheck`
726
- // stamps the map basename it verified (demanded seeds present + shape
727
- // unchanged, see `citeRemedyDischarged`). Honoring the stamp only for the
728
- // current map means it can never carry across a later re-slice.
729
- const citeDischargeCoversCurrentMap = (state: RunView): boolean => {
730
- const stamp = (state.named["slice-check"]?.at(-1)?.data as { citeDischarged?: unknown } | undefined)?.citeDischarged;
731
- const current = latestArtifactPath(state, "slices");
732
- return typeof stamp === "string" && current !== undefined && stamp === basename(current);
733
- };
734
- const sliceGatePasses = (state: RunView): boolean => {
735
- const fresh = freshVerdicts(state.named["slice-verdicts"], latestArtifactPath(state, "slices"));
736
- const roster = gateRoster(gateTier(state, "slice-verdicts"), SLICE_DIMENSIONS);
737
- if (!allDimensionsPass(state.named["slice-check"])) return false;
738
- return allDimensionsPass(fresh, roster) || citeDischargeCoversCurrentMap(state);
739
- };
740
-
741
- /**
742
- * The verdict fields the seed-only cite classification consults — the ONE
743
- * spelling shared by the route predicate (`seedOnlyCiteFail`), the discharge
744
- * stamp (`citeRemedyDischarged`), and the seed-lift stage, so all three agree
745
- * on what a "seed-only cite fail" is. `where` rides the findings for the
746
- * lift stage's slice-target parse; the classification itself reads only
747
- * `requires`.
748
- */
749
- type SeedOnlyVerdict = {
750
- pass?: boolean;
751
- remedy?: string;
752
- findings?: readonly { requires?: unknown; where?: unknown }[];
753
- };
754
-
755
- /**
756
- * A verdict is a SEED-ONLY cite fail when it failed, its `remedy` is `"cite"`
757
- * or absent (an omitted marker must not divert a pure-bookkeeping fail into
758
- * the structural re-cut arm), it carries at least one finding, and EVERY
759
- * finding demands a concrete string `requires` seed. A finding without a
760
- * `requires` is unverifiable — a verdict mixing one in is a structural
761
- * demand and takes the normal fix arm, exactly as a `remedy` naming another
762
- * repair would.
763
- */
764
- const seedOnlyFindings = (v: SeedOnlyVerdict | undefined): boolean => {
765
- if (v?.pass !== false) return false;
766
- if (v.remedy !== undefined && v.remedy !== "cite") return false;
767
- const findings = Array.isArray(v.findings) ? v.findings : [];
768
- return (
769
- findings.length > 0 && findings.every((f) => f != null && typeof f.requires === "string" && f.requires.length > 0)
770
- );
771
- };
772
-
773
- /**
774
- * The seed-only classification over the run state: the LATEST
775
- * `design-readiness` verdict (via `latestVerdictPerDimension` — deliberately
776
- * the same consultation `citeRemedyDischarged` makes, not a fresh-verdict
777
- * filter) is a seed-only cite fail. The `slice-grade` edge consults this to
778
- * route the deterministic seed lift instead of the structural fix arm.
779
- */
780
- const seedOnlyCiteFail = (state: RunView): boolean =>
781
- seedOnlyFindings(
782
- latestVerdictPerDimension(state.named["slice-verdicts"]).get("design-readiness")?.data as
783
- | SeedOnlyVerdict
784
- | undefined,
785
- );
786
-
787
- /**
788
- * Stuck detection for the seed-lift loop: the gate still fails, the verdict is
789
- * seed-only, and the LATEST post-verdict fix publication is the seed lift
790
- * itself — no later re-slice has superseded it. A lift that already ran and
791
- * still left the gate red cannot be helped by re-grading (the verdict is
792
- * unchanged) or re-lifting (the dedup makes the second lift a no-op), so the
793
- * `slice-check` edge routes the structural fix arm instead of another panel.
794
- * Timestamps are the channel-tail `meta.ts` comparison (ISO-8601 compares
795
- * lexicographically); a missing timestamp reads not-stuck — the fail-closed
796
- * direction here is the ordinary re-grade, never a stuck loop.
797
- */
798
- const seedLiftStuck = (state: RunView): boolean => {
799
- if (sliceGatePasses(state)) return false;
800
- if (!seedOnlyCiteFail(state)) return false;
801
- const verdictTs = latestVerdictPerDimension(state.named["slice-verdicts"]).get("design-readiness")?.meta?.ts;
802
- const liftTs = state.named["slice-seed-lift"]?.at(-1)?.meta?.ts;
803
- const resliceTs = state.named.slices?.at(-1)?.meta?.ts;
804
- if (typeof verdictTs !== "string" || typeof liftTs !== "string" || liftTs <= verdictTs) return false;
805
- return typeof resliceTs !== "string" || liftTs > resliceTs;
806
- };
807
-
808
- // The single authority the new `subplan-check` edge consults — the twin of
809
- // `sliceGatePasses`, but carrying no LLM-verdict roster or risk flags: the
810
- // `subplan-check` floor is the sole (deterministic) dimension on its channel.
811
- const subplanGatePasses = (state: RunView): boolean => allDimensionsPass(state.named["subplan-check"]);
812
- const planGatePasses = (state: RunView): boolean => {
813
- const fresh = freshVerdicts(state.named["plan-verdicts"], latestArtifactPath(state, "plans"));
814
- const roster = panelRoster(state, "plans", "plan-verdicts", PLAN_DIMENSIONS);
815
- const risks = planAuthoredRisks(state, "plans");
816
- return (
817
- allDimensionsPass(state.named["plan-cite-check"]) &&
818
- allDimensionsPass(fresh, roster) &&
819
- allRiskFlagsPass(fresh, risks)
820
- );
821
- };
822
- const codeGatePasses = (state: RunView): boolean => {
823
- const fresh = freshVerdicts(state.named["code-verdicts"], latestArtifactPath(state, "plans"));
824
- const roster = panelRoster(state, "plans", "code-verdicts", PLAN_DIMENSIONS);
825
- const risks = planAuthoredRisks(state, "plans");
826
- return (
827
- allDimensionsPass(state.named["code-cite-check"]) &&
828
- allDimensionsPass(fresh, roster) &&
829
- allRiskFlagsPass(fresh, risks)
830
- );
831
- };
832
-
833
- /**
834
- * Ship's grade gate — the tier-independent fold over `SHIP_DIMENSIONS` reading
835
- * the `ship-verdicts` channel. Satisfied when every ship dimension passes
836
- * (severity-floored) AND every plan-authored risk flag is ruled pass. Unlike
837
- * `planGatePasses`/`codeGatePasses` it folds NO deterministic cite channel —
838
- * ship's `plan-cite-check` gate is routed at its own edge — and binds the
839
- * roster to `shipRoster` (`SHIP_DIMENSIONS` verbatim plus the risk unit when
840
- * the plan declares `risks:` — never `gateRoster(gateTier(...))`), so the gate
841
- * consults the same fixed set the panel graded, and a dead risk unit's
842
- * dimension-bearing sentinel blocks instead of vanishing behind a vacuous
843
- * `allRiskFlagsPass`.
844
- */
845
- export const shipGatePasses = (state: RunView): boolean => {
846
- const fresh = freshVerdicts(state.named["ship-verdicts"], latestArtifactPath(state, "plans"));
847
- const risks = planAuthoredRisks(state, "plans");
848
- return allDimensionsPass(fresh, shipRoster(state)) && allRiskFlagsPass(fresh, risks);
849
- };
850
-
851
- /**
852
- * Confirm-before-block, severity-gated: a dimension's FRESH blocking verdict
853
- * against the current artifact gets ONE independent second judgment before it
854
- * buys a fix round — but only when the second opinion is worth its price. Run
855
- * telemetry over the whole runs corpus measured the confirm arms at ~13:1 and
856
- * ~10:1 onward-to-fix vs overturn: ~90% of confirms added 4–7 minutes and an
857
- * extra grade session before the fix that was going to happen anyway. So a
858
- * fresh blocker (the dimension's previous fresh verdict, if any, did not
859
- * block — a repeated block routes straight to the fix: confirmation is one
860
- * extra opinion, not an unbounded re-roll) confirms only in the three shapes
861
- * where the insurance has real expected value:
862
- *
863
- * - a HIGH-severity blocker — the expensive class: its fix round is the
864
- * broadest, so a spurious high deserves one adversarial check before it
865
- * buys that;
866
- * - a RISK-ruling blocker (a `pass: false` ruling or a duty-demoted pass) —
867
- * the confirm's uphold-or-refute-with-evidence contract is the designed
868
- * remedy for an un-grounded ruling, and `amend` legitimately re-emits
869
- * UNCHANGED for a demotions-only verdict, so routing that class to the
870
- * fix instead would lap an unchanged plan against an unchanged lazy
871
- * judgment until the backward-jump guard halted it;
872
- * - a FLAP — the dimension previously passed and now blocks on the same
873
- * artifact (a broad re-grade regressing a carried pass), i.e. the exact
874
- * single-judge instability the confirm exists to adjudicate.
875
- *
876
- * A first-time MEDIUM finding-driven blocker routes straight to the fix:
877
- * amend is surgical and cheap (observed under a minute), and the delta
878
- * re-grade guard keeps the re-judgment narrow — a wrong medium now costs one
879
- * lean fix lap instead of every medium costing a confirm session.
880
- *
881
- * No tier guard is needed: a blocking verdict is medium+ by the severity
882
- * floor, and a medium+ severity already lifts `gateTier` out of light — every
883
- * run with a genuine blocker has confirm-level scrutiny by construction.
884
- */
885
- const confirmDue = (
886
- state: RunView,
887
- channel: string,
888
- verdictChannel: string,
889
- dimensions: readonly string[],
890
- ): boolean => {
891
- const roster = new Set(panelRoster(state, channel, verdictChannel, dimensions));
892
- const fresh = freshVerdicts(state.named[verdictChannel], latestArtifactPath(state, channel));
893
- const risks = planAuthoredRisks(state, channel);
894
- const byDim = new Map<string, { blocking: boolean; confirmWorthy: boolean; prevBlocking?: boolean }>();
895
- for (const o of fresh) {
896
- const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
897
- if (typeof v?.dimension !== "string" || !roster.has(v.dimension)) continue;
898
- const riskFail = verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
899
- // `verdictBlocks` keeps this fold coherent with the other severity-fold
900
- // consumers (dimensionsToRegrade/allDimensionsPass/shipGradeStopNote);
901
- // risk composes ON TOP — the predicate itself is risk-blind.
902
- const blocking = verdictBlocks(v) || riskFail;
903
- const prev = byDim.get(v.dimension);
904
- byDim.set(v.dimension, {
905
- blocking, // the latest verdict decides whether the dimension currently blocks
906
- confirmWorthy: blocking && (v.severity === "high" || riskFail),
907
- prevBlocking: prev?.blocking,
908
- });
909
- }
910
- return [...byDim.values()].some(
911
- (e) => e.blocking && e.prevBlocking !== true && (e.confirmWorthy || e.prevBlocking === false),
912
- );
913
- };
914
-
915
- /**
916
- * Roster dimensions whose latest FRESH verdict entry is a failed sentinel —
917
- * the dead-unit routing signal. A dimension-bearing sentinel means the unit
918
- * grading that dimension soft-halted (after its re-dispatch, when the panel
919
- * wires one) and left "unresolved" as the dimension's channel state; route
920
- * bodies convert it into the fix arm with a unit-failed note instead of
921
- * letting the fold's absence-is-not-failure default — or a confirm divert —
922
- * decide. Pure state reads — resume-safe for `readsData: false` routes. A
923
- * sentinel survives `freshVerdicts` (no `artifact` field — the compat
924
- * default), so regenerating the artifact cannot launder a dead unit.
925
- */
926
- export const unitFailedDimensions = (
927
- state: RunView,
928
- channel: string,
929
- verdictChannel: string,
930
- dimensions: readonly string[],
931
- ): string[] => {
932
- const fresh = freshVerdicts(state.named[verdictChannel], latestArtifactPath(state, channel));
933
- const latest = latestVerdictPerDimension(fresh);
934
- return dimensions.filter((d) => latest.get(d)?.kind === "failed");
935
- };
936
11
 
937
12
  export {
938
13
  allDimensionsPass,
939
- anchorNitsOnly,
940
14
  codeGatePasses,
941
15
  confirmDue,
942
16
  dimensionsToRegrade,
943
- evidenceCitesFileLine,
944
- freshVerdicts,
945
- GOAL_DIMENSIONS,
946
- gateRoster,
947
- gateTier,
948
- latestArtifactPath,
949
- latestVerdictPerDimension,
950
- PLAN_DIMENSIONS,
951
17
  panelProgress,
952
- panelRoster,
953
- planAuthoredRisks,
954
18
  planGatePasses,
955
- procedureSatisfiesDuty,
956
19
  progressFromRoundCounts,
957
- type RiskRecord,
958
- rulingEffectivePass,
959
20
  type SeedOnlyVerdict,
960
- SLICE_DIMENSIONS,
961
21
  seedLiftStuck,
962
22
  seedOnlyCiteFail,
963
23
  seedOnlyFindings,
964
- shipRoster,
24
+ shipGatePasses,
965
25
  sliceGatePasses,
966
26
  subplanGatePasses,
27
+ unitFailedDimensions,
28
+ } from "./gate-passes.js";
29
+ export {
30
+ evidenceCitesFileLine,
31
+ gateRoster,
32
+ gateTier,
33
+ panelRoster,
34
+ planAuthoredRisks,
35
+ procedureSatisfiesDuty,
36
+ type RiskRecord,
37
+ rulingEffectivePass,
38
+ shipRoster,
39
+ verdictRiskRulings,
40
+ } from "./gate-rosters.js";
41
+ export {
42
+ anchorNitsOnly,
43
+ freshVerdicts,
44
+ GOAL_DIMENSIONS,
45
+ latestArtifactPath,
46
+ latestVerdictPerDimension,
47
+ PLAN_DIMENSIONS,
48
+ RISK_DIMENSION,
49
+ SHIP_DIMENSIONS,
50
+ SLICE_DIMENSIONS,
967
51
  type VerdictRecord,
968
52
  verdictBlocks,
969
- verdictRiskRulings,
970
- };
53
+ } from "./verdict-core.js";