@juicesharp/rpiv-pi 2.6.4 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/extensions/rpiv-core/agents.ts +10 -13
  2. package/extensions/rpiv-core/artifact-collector.ts +111 -6
  3. package/extensions/rpiv-core/bash-timeout.ts +12 -2
  4. package/extensions/rpiv-core/built-in-workflows.ts +228 -3497
  5. package/extensions/rpiv-core/built-ins/citations.ts +357 -0
  6. package/extensions/rpiv-core/built-ins/gates.ts +613 -0
  7. package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
  8. package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
  9. package/extensions/rpiv-core/built-ins/index.ts +46 -0
  10. package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
  11. package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
  12. package/extensions/rpiv-core/built-ins/priors.ts +352 -0
  13. package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
  14. package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
  15. package/extensions/rpiv-core/built-ins/shared.ts +17 -1
  16. package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
  17. package/extensions/rpiv-core/built-ins/slices.ts +288 -0
  18. package/extensions/rpiv-core/constants.ts +5 -1
  19. package/extensions/rpiv-core/lane-console.ts +9 -2
  20. package/extensions/rpiv-core/lane-list.ts +10 -1
  21. package/extensions/rpiv-core/question-lifecycle.ts +2 -2
  22. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  23. package/extensions/rpiv-core/run-lane-registry.ts +83 -83
  24. package/package.json +2 -2
  25. package/skills/elaborate/SKILL.md +1 -1
  26. package/skills/implement/SKILL.md +1 -0
  27. package/skills/plan/SKILL.md +3 -1
  28. package/skills/remediate/SKILL.md +1 -0
  29. package/skills/synthesize/SKILL.md +1 -0
  30. package/skills/validate/SKILL.md +25 -19
  31. package/skills/validate/templates/validation.md +1 -1
@@ -0,0 +1,613 @@
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.
5
+ */
6
+ import { basename } from "node:path";
7
+ import { handleToString, type Output, 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 two dimensions the grade panels anchor against the verbatim brief.
55
+ * "Complete" and "correct" MEAN "against what the user asked" — without the
56
+ * goal, completeness grades the plan against the plan's own claims. The other
57
+ * dimensions (and the slice gate's `design-readiness`) deliberately stay
58
+ * goal-blind: fit/actionability/pattern-following judge the artifact against
59
+ * the codebase, and an ambient goal at those seams invites scope inflation.
60
+ */
61
+ const GOAL_DIMENSIONS: ReadonlySet<string> = new Set(["completeness", "correctness"]);
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Adaptive gate scaling — tier, roster, verdict freshness.
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /** Latest `data` record published under `name` (undefined when absent/non-record). */
68
+ const latestChannelData = (state: RunView, name: string): Record<string, unknown> | undefined => {
69
+ const data = state.named[name]?.at(-1)?.data;
70
+ return data !== null && typeof data === "object" && !Array.isArray(data)
71
+ ? (data as Record<string, unknown>)
72
+ : undefined;
73
+ };
74
+
75
+ /** A finite numeric field off the latest `data` on `name` (undefined otherwise). */
76
+ const channelNumber = (state: RunView, name: string, field: string): number | undefined => {
77
+ const v = latestChannelData(state, name)?.[field];
78
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
79
+ };
80
+
81
+ /** Repo-relative path of the latest fs artifact on `name` (undefined if none). */
82
+ const latestArtifactPath = (state: RunView, name: string): string | undefined => {
83
+ const a = latestFsArtifact(state, name);
84
+ return a?.handle.kind === "fs" ? handleToString(a.handle) : undefined;
85
+ };
86
+
87
+ /**
88
+ * Gate scrutiny tier, derived ONLY from signals already replayed by the resume
89
+ * fold (the slices/plans channels' frontmatter data and the gate's own verdict
90
+ * severities) — deterministic by construction, so routes and fanout units that
91
+ * consult it stay resume-safe.
92
+ *
93
+ * `risks:` flags are deliberately NOT a tier signal: `synthesize` declares
94
+ * them routinely (observed: 1-phase plans shipping 2-3 flags), so counting
95
+ * them would push every small run out of the light tier. Risk flags are
96
+ * already force-ruled per dimension via `risk_rulings`, and a blocking
97
+ * verdict lifts the tier on its own (below).
98
+ *
99
+ * A missing signal never yields light, and verdict severities are read over
100
+ * the FULL channel history (a stale medium/high is still evidence of a risky
101
+ * run) — ambiguity always resolves toward more scrutiny.
102
+ */
103
+ type GateTier = "light" | "standard" | "strict";
104
+ const TIER_LIGHT_MAX_SLICES = 1;
105
+ const TIER_LIGHT_MAX_PHASES = 2;
106
+ const TIER_STRICT_MIN_SLICES = 5;
107
+ const TIER_STRICT_MIN_PHASES = 6;
108
+
109
+ /**
110
+ * The dimensions a light-tier run still grades: correctness and completeness
111
+ * are the two whose failures ship real defects (and the two that anchor on the
112
+ * goal); fit/actionability/pattern-following are low-consequence on a
113
+ * one-slice, <=2-phase diff, and `validate` still runs at every tier.
114
+ */
115
+ const LIGHT_ROSTER: ReadonlySet<string> = new Set(["correctness", "completeness"]);
116
+
117
+ const gateTier = (state: RunView, verdictChannel: string): GateTier => {
118
+ const slices = channelNumber(state, "slices", "slice_count");
119
+ const phases = channelNumber(state, "plans", "phase_count");
120
+ const severities = new Set<string>();
121
+ for (const o of state.named[verdictChannel] ?? []) {
122
+ const v = o.data as { severity?: unknown; findings?: unknown } | undefined;
123
+ const s = v?.severity;
124
+ // Anchor-nit clamp: an all-drift-nit verdict must not escalate the tier.
125
+ if (typeof s === "string") severities.add(anchorNitsOnly(v) ? "low" : s);
126
+ }
127
+ if (
128
+ (slices !== undefined && slices >= TIER_STRICT_MIN_SLICES) ||
129
+ (phases !== undefined && phases >= TIER_STRICT_MIN_PHASES) ||
130
+ severities.has("high")
131
+ ) {
132
+ return "strict";
133
+ }
134
+ if (
135
+ slices !== undefined &&
136
+ slices <= TIER_LIGHT_MAX_SLICES &&
137
+ phases !== undefined &&
138
+ phases <= TIER_LIGHT_MAX_PHASES &&
139
+ !severities.has("medium")
140
+ ) {
141
+ return "light";
142
+ }
143
+ return "standard";
144
+ };
145
+
146
+ /**
147
+ * The subset of `dimensions` the tier actually grades. Never empty: a
148
+ * dimension list with no light-roster member (the slice gate's lone
149
+ * `design-readiness`) keeps its full list at every tier.
150
+ */
151
+ const gateRoster = (tier: GateTier, dimensions: readonly string[]): readonly string[] => {
152
+ if (tier !== "light") return dimensions;
153
+ const light = dimensions.filter((d) => LIGHT_ROSTER.has(d));
154
+ return light.length > 0 ? light : dimensions;
155
+ };
156
+
157
+ /**
158
+ * Drop verdicts judged against an artifact the channel has since REPLACED. A
159
+ * grade verdict embeds the `artifact` path it judged; when a fix REGENERATES
160
+ * the artifact (`slice-fix` re-slices to a NEW file) a passing verdict on the
161
+ * old document must not carry forward to a document that was never judged —
162
+ * the carry-forward would otherwise let a regenerated slice map skip its
163
+ * design-readiness judgment entirely. An in-place `amend` keeps the path, so
164
+ * the plan-fix/code-fix carry-forward is unaffected. A verdict without an
165
+ * `artifact` field (older trails, the deterministic structure checks) is kept:
166
+ * matching is the compat default.
167
+ */
168
+ const freshVerdicts = (entries: readonly Output[] = [], currentArtifact?: string): readonly Output[] => {
169
+ if (!currentArtifact) return entries;
170
+ const current = basename(currentArtifact);
171
+ return entries.filter((o) => {
172
+ const a = (o.data as { artifact?: unknown } | undefined)?.artifact;
173
+ return typeof a !== "string" || a.length === 0 || basename(a) === current;
174
+ });
175
+ };
176
+
177
+ /**
178
+ * Latest verdict per dimension off an accumulated verdict channel — the shared
179
+ * fold under `dimensionsToRegrade` (which dimensions still block) and the
180
+ * confirm panels' `--prior` threading (which verdict file the confirming
181
+ * grader must adjudicate).
182
+ */
183
+ const latestVerdictPerDimension = (entries: readonly Output[] = []): Map<string, Output> => {
184
+ const latest = new Map<string, Output>();
185
+ for (const o of entries) {
186
+ const dim = (o.data as { dimension?: unknown } | undefined)?.dimension;
187
+ if (typeof dim === "string") latest.set(dim, o);
188
+ }
189
+ return latest;
190
+ };
191
+
192
+ /**
193
+ * Anchor-drift-nit phrasing, two tiers: only phrasings naming drift itself
194
+ * count standalone; the location shapes (off-by-N, "is at line N", "line N is
195
+ * the/a") also match REAL defects ("line 42 is a comment that falsely claims
196
+ * X", "the loop bound is off by one") and count ONLY alongside citing-context
197
+ * vocabulary — every observed drift nit has it, real-defect phrasings don't.
198
+ * Do NOT widen, and do NOT promote a location shape to standalone.
199
+ */
200
+ const ANCHOR_NIT_DRIFT_RE = /\bdrifted?\s+~?\d+\s+lines?\b|\bcitation (?:is )?drifted\b/i;
201
+ const ANCHOR_NIT_LOCATION_RE =
202
+ /\boff[- ]by[- ](?:one|two|three|\d+)\b|(?::\d+|\bline \d+) is (?:the|a)\b|\bis at line \d+\b/i;
203
+ const ANCHOR_NIT_CITE_CONTEXT_RE = /\bcit(?:es?|ed|ation)\b|\banchor/i;
204
+
205
+ const isAnchorNitDetail = (detail: string): boolean =>
206
+ ANCHOR_NIT_DRIFT_RE.test(detail) || (ANCHOR_NIT_LOCATION_RE.test(detail) && ANCHOR_NIT_CITE_CONTEXT_RE.test(detail));
207
+
208
+ /**
209
+ * TRUE when a verdict carries ≥1 finding and EVERY finding is an anchor-drift
210
+ * nit (`isAnchorNitDetail`). Such a verdict is severity-clamped to non-blocking
211
+ * at the gate fold regardless of the grader's own `severity` — line-number
212
+ * drift was measured at 34% of all grader findings with zero downstream harm,
213
+ * and a mis-rated all-nit `medium` verdict buys a full fix round + re-grade
214
+ * panel that repairs nothing. A verdict mixing a drift nit with ANY other
215
+ * finding is untouched — the other finding may be the real blocker.
216
+ */
217
+ const anchorNitsOnly = (v: { findings?: unknown } | undefined): boolean => {
218
+ const findings = Array.isArray(v?.findings) ? v.findings : [];
219
+ return (
220
+ findings.length > 0 &&
221
+ findings.every((f) => {
222
+ const detail = (f as { detail?: unknown } | undefined)?.detail;
223
+ return typeof detail === "string" && isAnchorNitDetail(detail);
224
+ })
225
+ );
226
+ };
227
+
228
+ /**
229
+ * The subset of `dimensions` a re-grade must actually re-run, given the latest
230
+ * verdict per dimension accumulated so far. A dimension needs re-grading when it
231
+ * has NO prior verdict (first pass ⇒ grade every dimension), when its latest
232
+ * verdict fails above the severity floor, or when that verdict ruled any plan
233
+ * risk flag `fail` (the ruling is re-opened by re-grading its owning dimension).
234
+ * A dimension that already passed — dimension AND its risk rulings — is carried
235
+ * forward untouched: re-running it after a surgical fix only re-rolls a free LLM
236
+ * judgment that flaps pass↔fail on an unchanged artifact, manufacturing extra
237
+ * loops (the observed correctness risk-flag flap). The accumulating verdict
238
+ * channel + `allDimensionsPass`'s latest-per-dimension fold mean a carried
239
+ * dimension's prior passing verdict still counts at the gate.
240
+ */
241
+ const dimensionsToRegrade = (
242
+ dimensions: readonly string[],
243
+ latest: ReadonlyMap<string, Output>,
244
+ risks: ReadonlyMap<string, RiskRecord> = new Map(),
245
+ ): string[] => {
246
+ return dimensions.filter((d) => {
247
+ const o = latest.get(d);
248
+ if (!o) return true; // never graded — must grade at least once
249
+ const v = o.data as { pass?: boolean; severity?: string; findings?: unknown } | undefined;
250
+ const dimPass = v?.pass === true || v?.severity === "low" || v?.severity === "none" || anchorNitsOnly(v);
251
+ if (!dimPass) return true;
252
+ return verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
253
+ });
254
+ };
255
+
256
+ /**
257
+ * Fold the per-dimension verdicts into a gate decision: keep the latest verdict
258
+ * per dimension (verdicts accumulate across fix loops), require all-pass.
259
+ * Deterministic ⇒ resume-safe for a `readsData: false` route.
260
+ *
261
+ * Severity floor: a verdict whose worst finding is `low`/`none` never blocks the
262
+ * gate, even when the grader set `pass: false` on a nit. `grade` decides `pass`
263
+ * by a free judgment against a prose bar (independent of `severity`), so a
264
+ * marginal dimension can flip pass↔fail across rounds on an unchanged artifact —
265
+ * that flapping, ANDed over a 5-dimension panel, stalled the build gate loops
266
+ * until the backward-jump guard halted them. Flooring on severity reserves a hard
267
+ * fail for `medium`+ findings (the deterministic `slice-check` check emits
268
+ * `high` on a real structural break, so it still blocks). A verdict with no
269
+ * `severity` (an older or replayed grade) falls back to the raw `pass` boolean.
270
+ */
271
+ const allDimensionsPass = (entries: readonly Output[] = [], roster?: readonly string[]): boolean => {
272
+ // Roster-filtered when given: a verdict for a dimension outside the tier's
273
+ // roster (a wider earlier round, a shrunk re-slice) neither blocks nor passes
274
+ // a gate it no longer governs.
275
+ const member = roster ? new Set(roster) : undefined;
276
+ const latest = new Map<string, boolean>();
277
+ for (const o of entries) {
278
+ const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
279
+ if (typeof v?.dimension !== "string") continue;
280
+ if (member && !member.has(v.dimension)) continue;
281
+ // The anchor-nit clamp: an all-drift-nit verdict never blocks, whatever
282
+ // severity the grader typed (backstop for the citation-resolution rule).
283
+ const lowOrNone = v.severity === "low" || v.severity === "none" || anchorNitsOnly(v);
284
+ latest.set(v.dimension, v.pass === true || lowOrNone);
285
+ }
286
+ const verdicts = [...latest.values()];
287
+ return verdicts.length > 0 && verdicts.every(Boolean);
288
+ };
289
+
290
+ /**
291
+ * One plan-authored risk flag ruled by a grade panel. The plan declares a
292
+ * `risks:` frontmatter array (`{ id, claim }`) — the structured, first-class
293
+ * channel that replaces the old prose-in-a-Notes-section flagging that graders
294
+ * were free to skip. Each grade verdict that engages a flag emits a ruling here.
295
+ */
296
+ interface RiskRuling {
297
+ id: string;
298
+ pass: boolean;
299
+ /**
300
+ * `mechanics` marks a risk whose `pass` asserts a verified mechanism (a
301
+ * behavior that holds because code was checked), so a passing ruling MUST
302
+ * cite the checked `file:line` in `evidence` — an un-evidenced mechanics
303
+ * pass demotes. Absent on
304
+ * an ordinary risk ⇒ no evidence duty.
305
+ */
306
+ claim_type?: string;
307
+ /** The `file:line`-shaped citation a mechanics pass must ground itself on. */
308
+ evidence?: string;
309
+ /**
310
+ * `verify-at-implement` marks a risk the panel defers: ruled `pass` ONLY when
311
+ * a concrete `procedure` + `owner` phase will re-check it at implement/validate
312
+ * time. Absent ⇒ the risk is judged in this panel, not deferred.
313
+ */
314
+ disposition?: string;
315
+ /** Named command/test the owner phase runs to discharge a deferred risk. */
316
+ procedure?: string;
317
+ /** The phase (`n`) that owns the deferred verify step. */
318
+ owner?: number;
319
+ }
320
+
321
+ /** The `risk_rulings` a grade verdict emitted (empty when it ruled on none). */
322
+ const verdictRiskRulings = (o: Output): RiskRuling[] => {
323
+ const raw = (o.data as { risk_rulings?: unknown } | undefined)?.risk_rulings;
324
+ if (!Array.isArray(raw)) return [];
325
+ return raw.flatMap((e) => {
326
+ const r = (e ?? {}) as Record<string, unknown>;
327
+ if (typeof r.id !== "string") return [];
328
+ // Read the duty fields defensively (same typeof-guard idiom as id/pass):
329
+ // absent on an older/ordinary verdict ⇒ undefined ⇒ the duty helpers no-op.
330
+ const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
331
+ const evidence = typeof r.evidence === "string" ? r.evidence : undefined;
332
+ const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
333
+ const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
334
+ const owner = typeof r.owner === "number" ? r.owner : undefined;
335
+ return [
336
+ {
337
+ id: r.id,
338
+ pass: r.pass === true,
339
+ ...(claim_type !== undefined ? { claim_type } : {}),
340
+ ...(evidence !== undefined ? { evidence } : {}),
341
+ ...(disposition !== undefined ? { disposition } : {}),
342
+ ...(procedure !== undefined ? { procedure } : {}),
343
+ ...(owner !== undefined ? { owner } : {}),
344
+ },
345
+ ];
346
+ });
347
+ };
348
+
349
+ /**
350
+ * A plan-authored risk flag — the duty shape `synthesize` declares in the plan
351
+ * frontmatter `risks:` array (`synthesize/SKILL.md:136`: `{ id, claim,
352
+ * claim_type?, disposition?, procedure?, owner? }`). The prose `claim` is grading
353
+ * copy, not a duty signal, so it is not carried here. `claim_type: "mechanics"`
354
+ * and `disposition: "verify-at-implement"` are the two duty TRIGGERS — sourced
355
+ * from the PLAN (not the ruling) so a panel cannot drop its discharge obligation
356
+ * by simply omitting the field from its ruling (the dropped-duty bypass).
357
+ */
358
+ interface RiskRecord {
359
+ id: string;
360
+ claim_type?: string;
361
+ disposition?: string;
362
+ procedure?: string;
363
+ owner?: number;
364
+ }
365
+
366
+ /**
367
+ * Read the plan-authored risk flags off the latest record on `channel`, keyed
368
+ * by `id`. The duty triggers live HERE (the plan's `risks:` frontmatter), not on
369
+ * the grade panel's ruling, so a ruling that drops its discharge field cannot
370
+ * escape the duty the plan declared (a bare `{ id, pass }` ruling against a
371
+ * plan-authored `claim_type: "mechanics"` risk still demotes). Reads only
372
+ * `state.named[channel]` via `latestChannelData` — no `readFileSync`, no
373
+ * `cwd`, no throw — so the route's `readsData: false` / determinism /
374
+ * resume-safety contract holds and a resumed run re-evaluates identically.
375
+ * Degrades to an empty map (fail-open ⇒ no duty ⇒ plain ruling ⇒
376
+ * `rulingEffectivePass(r) === r.pass`) when `risks:` is absent/non-array/
377
+ * malformed, mirroring `latestChannelData`'s degrade-to-undefined contract.
378
+ */
379
+ const planAuthoredRisks = (state: RunView, channel: string): Map<string, RiskRecord> => {
380
+ const risks = latestChannelData(state, channel)?.risks;
381
+ const out = new Map<string, RiskRecord>();
382
+ if (!Array.isArray(risks)) return out;
383
+ for (const e of risks) {
384
+ const r = (e ?? {}) as Record<string, unknown>;
385
+ if (typeof r.id !== "string") continue;
386
+ const claim_type = typeof r.claim_type === "string" ? r.claim_type : undefined;
387
+ const disposition = typeof r.disposition === "string" ? r.disposition : undefined;
388
+ const procedure = typeof r.procedure === "string" ? r.procedure : undefined;
389
+ const owner = typeof r.owner === "number" ? r.owner : undefined;
390
+ const rec: RiskRecord = { id: r.id };
391
+ if (claim_type !== undefined) rec.claim_type = claim_type;
392
+ if (disposition !== undefined) rec.disposition = disposition;
393
+ if (procedure !== undefined) rec.procedure = procedure;
394
+ if (owner !== undefined) rec.owner = owner;
395
+ out.set(r.id, rec);
396
+ }
397
+ return out;
398
+ };
399
+
400
+ /**
401
+ * A mechanics-pass ruling's evidence duty: when the plan AUTHORED a
402
+ * `claim_type: "mechanics"` risk for the ruling's id, a `pass` ruling MUST
403
+ * cite the checked `file:line` in `evidence` (forces engagement — a pass with
404
+ * no evidence is an unverified mechanism). The trigger is sourced from the
405
+ * plan-authored `RiskRecord`, NOT the ruling — so a panel cannot drop the
406
+ * evidence duty by omitting `claim_type` from its ruling (the dropped-duty
407
+ * bypass). Reuses `FILE_LINE_CITATION_RE` via `.match()` — NOT `.test()`: the
408
+ * regex carries the `/g` flag, so `.test()` is stateful across calls
409
+ * (`lastIndex` advances) and would
410
+ * intermittently miss a present citation. An id with no authored mechanics
411
+ * risk carries no evidence duty ⇒ returns `true`.
412
+ */
413
+ const evidenceCitesFileLine = (r: RiskRuling, authored?: RiskRecord): boolean => {
414
+ if (authored?.claim_type !== "mechanics") return true;
415
+ return typeof r.evidence === "string" && r.evidence.match(FILE_LINE_CITATION_RE) !== null;
416
+ };
417
+
418
+ /**
419
+ * A deferred-risk's verify-at-implement duty: when the plan AUTHORED a
420
+ * `disposition: "verify-at-implement"` risk for the ruling's id, a `pass`
421
+ * ruling MUST carry a concrete `procedure` (the named command/test the owner
422
+ * phase runs) AND a numeric `owner` phase — a bare "verify later" with no
423
+ * procedure demotes. The trigger is sourced from the plan-authored
424
+ * `RiskRecord`, NOT the ruling (the dropped-duty bypass). An id with no
425
+ * authored verify-at-implement risk is judged in THIS panel, not deferred ⇒
426
+ * returns `true`.
427
+ */
428
+ const procedureSatisfiesDuty = (r: RiskRuling, authored?: RiskRecord): boolean => {
429
+ if (authored?.disposition !== "verify-at-implement") return true;
430
+ return typeof r.procedure === "string" && r.procedure.length > 0 && typeof r.owner === "number";
431
+ };
432
+
433
+ /**
434
+ * The single gate-fold authority: a ruling is effective-pass iff it is a bare
435
+ * `pass` AND (when the plan authored a mechanics risk for its id) its evidence
436
+ * cites a `file:line` AND (when the plan authored a verify-at-implement risk
437
+ * for its id) its procedure+owner discharge the verify duty. `allRiskFlagsPass`,
438
+ * `dimensionsToRegrade` clause 3, and `confirmDue`'s `riskFail` ALL consult this
439
+ * — so the three risk folds agree on what "passing" means and a demoted
440
+ * mechanics/deferred pass blocks the gate AND re-opens its owning dimension
441
+ * AND counts as blocking for confirm (no incoherent re-grading). For a ruling
442
+ * whose id the plan authored no duty for (no mechanics/verify-at-implement
443
+ * risk, no `risks:` at all, or no matching id) every duty no-ops, so
444
+ * `rulingEffectivePass(r, authored) === r.pass` — prior behavior is preserved.
445
+ */
446
+ const rulingEffectivePass = (r: RiskRuling, authored?: RiskRecord): boolean =>
447
+ r.pass === true && evidenceCitesFileLine(r, authored) && procedureSatisfiesDuty(r, authored);
448
+
449
+ /**
450
+ * Fold the grade panel's per-flag risk rulings into a gate decision: every
451
+ * plan-authored risk flag the panel ruled on must be ruled PASS (latest ruling
452
+ * per flag wins, mirroring `allDimensionsPass`). A flag ruled `fail` — the
453
+ * grader confirmed the risk is real and unaddressed — blocks the gate, so a
454
+ * self-flagged risk (e.g. an override-vs-env validation mismatch) can no longer
455
+ * ride a green conformance pass into commit. An empty panel (no flag engaged)
456
+ * imposes no constraint; the plan simply declared no risks.
457
+ */
458
+ const allRiskFlagsPass = (
459
+ entries: readonly Output[] = [],
460
+ risks: ReadonlyMap<string, RiskRecord> = new Map(),
461
+ ): boolean => {
462
+ const latest = new Map<string, boolean>();
463
+ for (const o of entries)
464
+ for (const r of verdictRiskRulings(o)) latest.set(r.id, rulingEffectivePass(r, risks.get(r.id)));
465
+ return [...latest.values()].every(Boolean);
466
+ };
467
+
468
+ /**
469
+ * The three gates' pass predicates — the SINGLE authority each gate consults at
470
+ * BOTH of its seams. A gate is satisfied when its deterministic cite/structure
471
+ * floor is green AND every quality dimension passes (severity-floored) AND — for
472
+ * the plan/code gates — every plan-authored risk flag is ruled pass.
473
+ *
474
+ * Reading the identical predicate at the cite/structure-check edge (which SKIPS
475
+ * the re-grade straight to the next stage) and at the grade edge (which gates
476
+ * forward-vs-fix) makes the skip provably equivalent to "re-grade, then pass",
477
+ * minus the wasted panel: after a fix that only cleared the deterministic floor,
478
+ * the accumulated verdicts already clear the gate, so re-running the LLM panel
479
+ * would at best reproduce them and at worst flap a passing dimension into a
480
+ * spurious fix loop. On the FIRST pass the verdict channel is empty, so
481
+ * `allDimensionsPass` returns false and the edge correctly routes INTO the grade
482
+ * panel. Any regression a fix introduces is still caught downstream: the plan
483
+ * gate by the full first-time `code-grade`, the code gate by `validate`.
484
+ */
485
+ // Each predicate folds the verdicts still FRESH for the channel's current
486
+ // artifact, restricted to the tier's roster — the SAME projections the panel's
487
+ // `units()` uses, so "skip the re-grade" stays provably equivalent to
488
+ // "re-grade, then pass". The deterministic cite/structure channels fold
489
+ // unfiltered: they re-run every round and carry no tier.
490
+ // The latest structure verdict carries a `citeDischarged` stamp for the
491
+ // CURRENT slice map. After a fix for a `remedy: "cite"` fail, the failing
492
+ // design-readiness verdict is stale (the fix re-sliced to a NEW file) and the
493
+ // gate's lone dimension has no fresh verdict, so the verdict fold can never
494
+ // pass — yet the fix is deterministically verifiable: `sliceStructureCheck`
495
+ // stamps the map basename it verified (demanded seeds present + shape
496
+ // unchanged, see `citeRemedyDischarged`). Honoring the stamp only for the
497
+ // current map means it can never carry across a later re-slice.
498
+ const citeDischargeCoversCurrentMap = (state: RunView): boolean => {
499
+ const stamp = (state.named["slice-check"]?.at(-1)?.data as { citeDischarged?: unknown } | undefined)?.citeDischarged;
500
+ const current = latestArtifactPath(state, "slices");
501
+ return typeof stamp === "string" && current !== undefined && stamp === basename(current);
502
+ };
503
+ const sliceGatePasses = (state: RunView): boolean => {
504
+ const fresh = freshVerdicts(state.named["slice-verdicts"], latestArtifactPath(state, "slices"));
505
+ const roster = gateRoster(gateTier(state, "slice-verdicts"), SLICE_DIMENSIONS);
506
+ if (!allDimensionsPass(state.named["slice-check"])) return false;
507
+ return allDimensionsPass(fresh, roster) || citeDischargeCoversCurrentMap(state);
508
+ };
509
+ // The single authority the new `subplan-check` edge consults — the twin of
510
+ // `sliceGatePasses`, but carrying no LLM-verdict roster or risk flags: the
511
+ // `subplan-check` floor is the sole (deterministic) dimension on its channel.
512
+ const subplanGatePasses = (state: RunView): boolean => allDimensionsPass(state.named["subplan-check"]);
513
+ const planGatePasses = (state: RunView): boolean => {
514
+ const fresh = freshVerdicts(state.named["plan-verdicts"], latestArtifactPath(state, "plans"));
515
+ const roster = gateRoster(gateTier(state, "plan-verdicts"), PLAN_DIMENSIONS);
516
+ const risks = planAuthoredRisks(state, "plans");
517
+ return (
518
+ allDimensionsPass(state.named["plan-cite-check"]) &&
519
+ allDimensionsPass(fresh, roster) &&
520
+ allRiskFlagsPass(fresh, risks)
521
+ );
522
+ };
523
+ const codeGatePasses = (state: RunView): boolean => {
524
+ const fresh = freshVerdicts(state.named["code-verdicts"], latestArtifactPath(state, "plans"));
525
+ const roster = gateRoster(gateTier(state, "code-verdicts"), PLAN_DIMENSIONS);
526
+ const risks = planAuthoredRisks(state, "plans");
527
+ return (
528
+ allDimensionsPass(state.named["code-cite-check"]) &&
529
+ allDimensionsPass(fresh, roster) &&
530
+ allRiskFlagsPass(fresh, risks)
531
+ );
532
+ };
533
+
534
+ /**
535
+ * Ship's grade gate — the tier-independent fold over `SHIP_DIMENSIONS` reading
536
+ * the `ship-verdicts` channel. Satisfied when every ship dimension passes
537
+ * (severity-floored) AND every plan-authored risk flag is ruled pass. Unlike
538
+ * `planGatePasses`/`codeGatePasses` it folds NO deterministic cite channel —
539
+ * ship's `plan-cite-check` gate is routed at its own edge — and binds the
540
+ * roster to `SHIP_DIMENSIONS` verbatim (never `gateRoster(gateTier(...))`), so
541
+ * the gate consults the same fixed set the panel graded.
542
+ */
543
+ export const shipGatePasses = (state: RunView): boolean => {
544
+ const fresh = freshVerdicts(state.named["ship-verdicts"], latestArtifactPath(state, "plans"));
545
+ const risks = planAuthoredRisks(state, "plans");
546
+ return allDimensionsPass(fresh, SHIP_DIMENSIONS) && allRiskFlagsPass(fresh, risks);
547
+ };
548
+
549
+ /**
550
+ * Confirm-before-block: a dimension's FIRST blocking verdict against the
551
+ * current artifact gets ONE independent second judgment before it buys a fix
552
+ * round. Single-judge verdicts observably flap (pass/score/severity disagree
553
+ * across rolls on a near-unchanged artifact), and a spurious block
554
+ * manufactures an entire grade→fix cycle. Routing to the confirm stage
555
+ * re-runs only the pending dimensions on the same verdict channel;
556
+ * latest-per-dimension wins, so a confirming pass clears the gate and a
557
+ * confirming fail routes to the fix with two agreeing judgments behind it. A
558
+ * blocker already judged twice for this artifact routes straight to the fix —
559
+ * confirmation is one extra opinion, not an unbounded re-roll.
560
+ *
561
+ * No tier guard is needed: a blocking verdict is medium+ by the severity
562
+ * floor, and a medium+ severity already lifts `gateTier` out of light — every
563
+ * run with a genuine blocker has confirm-level scrutiny by construction.
564
+ */
565
+ const confirmDue = (
566
+ state: RunView,
567
+ channel: string,
568
+ verdictChannel: string,
569
+ dimensions: readonly string[],
570
+ ): boolean => {
571
+ const roster = new Set(gateRoster(gateTier(state, verdictChannel), dimensions));
572
+ const fresh = freshVerdicts(state.named[verdictChannel], latestArtifactPath(state, channel));
573
+ const risks = planAuthoredRisks(state, channel);
574
+ const byDim = new Map<string, { blocking: boolean; count: number }>();
575
+ for (const o of fresh) {
576
+ const v = o.data as { dimension?: string; pass?: boolean; severity?: string; findings?: unknown } | undefined;
577
+ if (typeof v?.dimension !== "string" || !roster.has(v.dimension)) continue;
578
+ // anchorNitsOnly keeps this floor coherent with the other three
579
+ // severity-fold consumers (gateTier/dimensionsToRegrade/allDimensionsPass).
580
+ const floored = v.pass === true || v.severity === "low" || v.severity === "none" || anchorNitsOnly(v);
581
+ const riskFail = verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id)));
582
+ byDim.set(v.dimension, {
583
+ blocking: !floored || riskFail,
584
+ count: (byDim.get(v.dimension)?.count ?? 0) + 1,
585
+ });
586
+ }
587
+ const blockers = [...byDim.values()].filter((e) => e.blocking);
588
+ return blockers.length > 0 && blockers.some((e) => e.count < 2);
589
+ };
590
+
591
+ export {
592
+ allDimensionsPass,
593
+ anchorNitsOnly,
594
+ codeGatePasses,
595
+ confirmDue,
596
+ dimensionsToRegrade,
597
+ evidenceCitesFileLine,
598
+ freshVerdicts,
599
+ GOAL_DIMENSIONS,
600
+ gateRoster,
601
+ gateTier,
602
+ latestArtifactPath,
603
+ latestVerdictPerDimension,
604
+ PLAN_DIMENSIONS,
605
+ planAuthoredRisks,
606
+ planGatePasses,
607
+ procedureSatisfiesDuty,
608
+ rulingEffectivePass,
609
+ SLICE_DIMENSIONS,
610
+ sliceGatePasses,
611
+ subplanGatePasses,
612
+ verdictRiskRulings,
613
+ };