Skip to main content

candor_classify/
gate.rs

1//! ⟨0.24⟩ THE GATE — SPEC §6.2 matching over an ALREADY-ACCUMULATED signature, and the ONLY copy of
2//! that matching in the stable toolchain.
3//!
4//! **THE SEAM.** [`GateInput`] is the boundary between *what produced the signature* and *what §6.2
5//! does with it*. Every field is already accumulated: this module runs no fixpoint, opens no file and
6//! consults no scan state, so the same matching code serves both routes in —
7//!
8//!   - `candor-scan … --policy <f>` builds a `GateInput` from the classifier's transitive accumulators
9//!     (`crate::gate::policy_violations`, which is now a thin wrapper);
10//!   - `candor-query gate --report <loc> --policy <f>` (SPEC §3.1 ⟨0.24⟩) builds one from a WRITTEN
11//!     report and nothing else.
12//!
13//! That split is the whole point of §3.1 ⟨0.24⟩: until it existed the gate was reachable only THROUGH
14//! the classifier, so a defect in the gate and a defect in the classifier were indistinguishable from
15//! any test that could be written. Do NOT re-implement the matching on the report side — the §6.2
16//! clause that mandates the verb was written about exactly that mistake.
17
18use crate::policy::{literal_allowed, reason_class_matches, scope_matches, scope_matches_permitted,
19                    ParsedPolicy, PolicyRule};
20use candor_report::GateViolation;
21use std::collections::{BTreeSet, HashMap};
22
23/// ⟨0.20⟩ The `Net` destination classes an fn reaches (transitive) — the SINGLE derivation shared by the
24/// report's `netClass` field (candor-scan's writer) and the gate: an exact host-literal match
25/// ([`crate::net_dest_class`]) for the visible hosts, plus the fail-closed `unknown-host` when the Net
26/// surface is masked (`incomplete` has Net) OR carries no visible host (a runtime endpoint). Call only
27/// for an fn known to have Net; returns sorted.
28///
29/// It lives beside the gate rather than in the scanner because the report field and the gate filter MUST
30/// be the same set: `gate --report` reads `netClass` off the wire and the scan derives it here, and the
31/// §3.1 ⟨0.24⟩ byte-equivalence obligation is exactly the claim that those two agree.
32pub fn net_classes_of<E: AsRef<str> + Ord>(
33    q: &str,
34    hostsacc: &HashMap<String, BTreeSet<String>>,
35    incompleteacc: &HashMap<String, BTreeSet<E>>,
36    partners: &BTreeSet<String>,
37) -> Vec<String> {
38    let mut classes: BTreeSet<String> = hostsacc
39        .get(q)
40        .into_iter()
41        .flatten()
42        .map(|h| crate::net_dest_class(h, partners).to_string())
43        .collect();
44    let masked = incompleteacc.get(q).is_some_and(|s| s.iter().any(|e| e.as_ref() == "Net"));
45    let no_hosts = hostsacc.get(q).map(|s| s.is_empty()).unwrap_or(true);
46    if masked || no_hosts {
47        classes.insert("unknown-host".to_string());
48    }
49    classes.into_iter().collect()
50}
51
52/// ⟨0.24⟩ THE GATE'S INPUT — one signature per function, every field already TRANSITIVE.
53///
54/// `E` is the effect-name representation: `&'static str` on the scan route (the classifier's interned
55/// vocabulary) and `String` on the report route (the wire's names, taken VERBATIM — a report naming an
56/// effect this build's vocabulary does not list must still trip a `pure` rule, so the names are never
57/// filtered through a known-effect allowlist on the way in).
58pub struct GateInput<'a, E: AsRef<str> + Ord> {
59    /// Every function the gate ranges over, in the caller's order.
60    pub all: &'a [String],
61    /// Per fn, the TRANSITIVE effect set — the model's `S`, with candor's `Unknown` marker carried as a
62    /// member (this engine's encoding of `D ≠ ∅`).
63    pub inferred: &'a HashMap<String, BTreeSet<E>>,
64    /// The call graph AS-EFF-009 walks.
65    pub calls: &'a HashMap<String, BTreeSet<String>>,
66    /// Per fn, the TRANSITIVE literal surface AS-EFF-008 certifies against.
67    pub hosts: &'a HashMap<String, BTreeSet<String>>,
68    pub cmds: &'a HashMap<String, BTreeSet<String>>,
69    pub paths: &'a HashMap<String, BTreeSet<String>>,
70    pub tables: &'a HashMap<String, BTreeSet<String>>,
71    /// Per fn, the effects whose literal surface is structurally INCOMPLETE — the AS-EFF-008 fail-closed
72    /// marker, without which a benign visible literal masks an invisible forbidden endpoint.
73    pub surface_incomplete: &'a HashMap<String, BTreeSet<E>>,
74    /// Per fn, the TRANSITIVE reason-class tokens — the model's `D` (§6.2 ⟨0.19⟩). The Unknown EFFECT
75    /// propagates along the call graph, so its REASON must too: else `deny E Unknown[reflect]` at a
76    /// caller inheriting Unknown from a reflect-caused callee sees no class and does NOT fire.
77    pub reason_classes: &'a HashMap<String, BTreeSet<String>>,
78    /// Per `Net`-bearing fn, its ⟨0.20⟩ destination classes, ALREADY derived — by [`net_classes_of`] on
79    /// the scan route, read verbatim from the report's `netClass` on the report route. Absent ⇒ empty.
80    pub net_classes: &'a HashMap<String, Vec<String>>,
81}
82
83/// ⟨0.24⟩ ONE `(rule, function)` THE GATE COULD NOT EVALUATE — SPEC §3.1: *"a rule FIRES on a function
84/// only where the match is evidenced by that function's own entry, and is WITHHELD exactly where it is
85/// not. Withholding is per `(rule, function)`, never whole-policy."*
86///
87/// A withheld pair is NOT a tolerated one. Tolerating means the evidence was read and did not match;
88/// withholding means there was no evidence to read, and the two must not arrive at a consumer wearing the
89/// same face. The caller decides the disposition — a violation elsewhere dominates (exit 1, disclose), a
90/// sole withholding is a refusal (exit 2) — but it can only do that if the fact reaches it, which is why
91/// this rides out of [`gate`] beside the violations instead of being logged here.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct Withheld {
94    /// The rule's source line, verbatim (`PolicyRule::raw`).
95    pub rule: String,
96    /// The function the rule could not be evaluated ON. The same rule may fire on another.
97    pub func: String,
98    /// Which narrowing filter had nothing to read — `"Unknown"` or `"Net"`.
99    pub filter: &'static str,
100}
101
102/// ⟨0.24⟩ What [`gate`] returns: the violations it is SURE of, and the `(rule, function)` pairs it
103/// WITHHELD. Both halves travel, because the verdict is both (SPEC §3.1).
104#[derive(Debug, Default)]
105pub struct GateOutcome {
106    /// Sorted by (rule, detail).
107    pub violations: Vec<GateViolation>,
108    /// Sorted by (rule, func). Empty on every policy whose filters the signature can answer.
109    pub withheld: Vec<Withheld>,
110    /// ⟨0.27⟩ SPEC §4 — the RAW TEXT of every rule whose SCOPE bound no function, sorted. A rule that
111    /// bound nothing was evaluated and matched nothing, so it cannot have caught anything; scoring it as
112    /// satisfied makes a one-character typo in a layer name a permanently green gate. This is a
113    /// DISCLOSURE beside the verdict, never a new verdict: the caller prints it and MUST NOT let it
114    /// change the exit code (a zero-match rule is legitimate when one policy is shared across repos).
115    pub zero_match: Vec<String>,
116}
117
118/// ⟨0.24⟩ What one §6.2 `deny`/`pure` rule DOES to one function's signature — see [`rule_hits`].
119pub struct RuleHits<'a> {
120    /// The effects this rule CHARGES on this function, after both narrowing filters. Empty ⇒ the rule
121    /// does not fire here, which is what the disclosure calls PASSING.
122    pub hits: Vec<&'a str>,
123    /// The filters — `"Unknown"` / `"Net"` — that had no evidence to read, in that order. The hit was
124    /// dropped from `hits` AND the fact rides out, because dropping it silently is the mirror defect.
125    pub withheld: Vec<&'static str>,
126}
127
128/// ⟨0.24⟩ WHAT ONE §6.2 `deny`/`pure` RULE DOES TO ONE FUNCTION'S SIGNATURE — the firing decision,
129/// extracted so it has exactly one implementation.
130///
131/// **WHY IT IS A FUNCTION NOW.** It was inline in [`gate`], and the provable-purity disclosure
132/// ([`crate::policy::unverified_hole_rule`]) carried its own second copy that asked a coarser question:
133/// "does the rule NAME an effect this function has?", computed from `r.effects` alone. That copy could
134/// not see a narrowing filter, so it disagreed with the gate on exactly the rules the ⟨0.24⟩ rung added
135/// — and the disagreement ran the LOSING way. A hole is a function that PASSES its rule while `Unknown`,
136/// so a rule the gate TOLERATES (`deny Unknown[reflect]` over an `indirect` hole) was read by the
137/// disclosure as a violation-that-isn't and dropped from the output: `unverified` printed **"every
138/// function in a pure/deny layer is PROVABLY clean ✓"** over a function the gate had just declined to
139/// clear. MEASURED 2026-07-28 on a one-function crate; reachable with NO alias in play, one layer below
140/// the alias-widening defect `ea0df4f` closed.
141///
142/// The caller does the SCOPE test and owns the disposition of `withheld`; this answers only "given that
143/// this rule governs this function, what does it charge, and what could it not evaluate?".
144///
145/// `reason_classes` is the ACCUMULATED (post-fixpoint) class set — `None`/empty means the signature
146/// carries none, which is NOT determinable and is withheld, never floored. `net_classes` is the fn's
147/// ⟨0.20⟩ destination classes, likewise already derived.
148pub fn rule_hits<'a>(
149    r: &PolicyRule,
150    effects: &[&'a str],
151    reason_classes: Option<&BTreeSet<String>>,
152    net_classes: &[String],
153) -> RuleHits<'a> {
154    let mut withheld: Vec<&'static str> = Vec::new();
155    let mut hits: Vec<&str> = if r.effects.is_empty() {
156        // `pure` — every EFFECT, but NOT `Unknown`: the §4 trust marker is not an effect
157        // (AS-EFF-003's concern; `deny Unknown <scope>` is the explicit knob). The reference
158        // engine and the deep backend exclude it identically — this engine wrongly counted an
159        // Unknown-only fn as a `pure` violation until 2026-07-09 (a cross-engine verdict split
160        // on the same policy file).
161        effects.iter().copied().filter(|e| *e != "Unknown").collect()
162    } else {
163        effects.iter().copied().filter(|e| r.effects.contains(e)).collect()
164    };
165    // Reason-scoped Unknown: a `deny E Unknown[classes]` (non-empty filter) keeps its Unknown hit
166    // ONLY for a fn whose TRANSITIVE reason classes include one of those classes; else tolerate it
167    // (wrong reason-class). Concrete effects in `hits` are untouched — only Unknown is scoped.
168    if hits.contains(&"Unknown") && !r.unknown_classes.is_empty() {
169        let want: BTreeSet<&str> = r.unknown_classes.iter().map(|c| c.token()).collect();
170        // An Unknown with NO recorded reason is `unresolved` (conservative — stays in
171        // `[*]`/`[unresolved]`). THIS IS A NET, NOT A ROUTE. It is per FUNCTION and keys on the
172        // ABSENCE of a class set, so any other reason on the same function hides whatever it was
173        // covering — which is how a reasonless chained-dep `Unknown` went ungated on every consumer
174        // that also had a reason of its own. That case now CONTRIBUTES `unresolved` where the
175        // signature is BUILT (candor-scan's `reason_class_direct`; `gate_input_from_report` on the
176        // report route) instead of arriving here by absence. What is left for the absence arm is
177        // the RELEASE-mode gap: the writer's §4 invariant is a `debug_assert`, so a future path
178        // that puts `Unknown` into `direct` with no reason fails closed here rather than escaping
179        // the gate. Not dead — it is pinned by
180        // `reason_scoped_unknown_gate_fires_on_match_tolerates_mismatch`.
181        //
182        // ⟨0.24⟩ The rule itself lives in `crate::policy::reason_class_matches` because
183        // `unverified --class` must select over exactly the set this gate scopes over: a gate and
184        // the disclosure naming the holes that gate did not prove, disagreeing, is the defect.
185        //
186        // ⟨0.24⟩ **BUT THE FLOOR IS ASKED FIRST, AND SEPARATELY — SPEC §3.1.** `reason_class_matches`
187        // answers "could this rule apply?", and its absence/empty arm floors at `unresolved` so a
188        // hole nobody classified never slips out of a filter that names its own class. That is the
189        // right fail-closed default for a MATCHER and the WRONG basis for a FIRING: read as grounds
190        // to emit a violation it asserts a reason NOBODY RECORDED. The two questions shared this one
191        // helper safely only while the report route's refusal short-circuited before `gate()` ran;
192        // `8b97e5c` removed that short-circuit (correctly — a certain violation must reach the
193        // document) and the identical constant, on identical data, became a FABRICATION.
194        //
195        // MEASURED 2026-07-28, `deny Unknown[unresolved] app.opaque` over an entry with `inferred:
196        // ["Unknown"]` and no `direct`, no `unknownWhy`, no `calls`: exit 1 with a violation record
197        // in `--gate-json`, for a function whose determinable class set is EMPTY. The record was
198        // self-refuting — it carried no `reasonClass` key at all, because the floor exists only
199        // inside the predicate and never in the data.
200        //
201        // So the three-way split. NOT determinable ⇒ **WITHHELD**: the hit is dropped AND the pair
202        // rides out to the caller, because dropping it silently is the mirror defect (a narrowed
203        // filter tolerating for lack of evidence is the fail-open this whole rung exists to close).
204        // Determinable ⇒ the shared matcher decides, unchanged, and the `Some(cs)` arm it lands on
205        // is the only one a firing may rest on.
206        //
207        // THE MIRROR IS PINNED, because this is where an under-report gets introduced: an entry
208        // whose `unresolved` is INHERITED — a `calls` edge to a reasonless direct `Unknown` — has a
209        // determinable set of `{unresolved}` (contributed at the ENTRY, before the fixpoint) and
210        // MUST still fire. That is `R1_EXPECT["unresolved"]`'s `app.a_reasonless_only`, and
211        // `a_withheld_unknown_filter_does_not_take_the_inherited_one_with_it` beside it.
212        let classes = reason_classes;
213        let determinable = classes.is_some_and(|cs| !cs.is_empty());
214        if !determinable {
215            hits.retain(|e| *e != "Unknown");
216            withheld.push("Unknown");
217        } else if !reason_class_matches(classes, &want) {
218            hits.retain(|e| *e != "Unknown");
219        }
220    }
221    // Net destination-class: a `deny Net[dest…]` (non-empty filter) keeps its Net hit ONLY for a fn
222    // reaching one of those destination classes; else tolerate (only asserted-safe destinations).
223    // Fail-closed: a masked surface / a Net with no visible host is unknown-host (net_classes_of).
224    //
225    // ⟨0.24⟩ SAME THREE-WAY SPLIT AS THE REASON FILTER, and this side is where the shape is easiest
226    // to see because it never fabricated: with no destination classes to read, `any()` over the
227    // empty set is false and the Net hit was DROPPED — the *other* half of the same defect, an
228    // absence-keyed relaxation of a fail-closed gate. Silently tolerating and silently charging are
229    // the two ways to answer a question the evidence cannot settle; WITHHOLDING is the third, and
230    // the only one that stays true. Costs nothing on a signature this engine produced:
231    // `net_classes_of` floors every Net-bearing fn at `unknown-host`, so an empty set here means
232    // "this producer did not carry the field", never "this function reaches nothing".
233    if hits.contains(&"Net") && !r.net_classes.is_empty() {
234        let fn_net = net_classes;
235        if fn_net.is_empty() {
236            hits.retain(|e| *e != "Net");
237            withheld.push("Net");
238        } else if !fn_net.iter().any(|c| r.net_classes.contains(c)) {
239            hits.retain(|e| *e != "Net");
240        }
241    }
242    RuleHits { hits, withheld }
243}
244
245
246/// Apply a parsed §6.2 policy to an already-accumulated signature. THE ONLY matching code in the stable
247/// toolchain — `candor-scan --policy` and `candor-query gate --report` both land here, which is what
248/// makes "the same verdict from the same signature" a property of the code rather than of two
249/// consistent authors. Returns the violations, sorted by (rule, detail), AND the withheld pairs.
250pub fn gate<E: AsRef<str> + Ord>(p: &ParsedPolicy, gi: &GateInput<E>) -> GateOutcome {
251    let empty: BTreeSet<E> = BTreeSet::new();
252    let no_classes: Vec<String> = Vec::new();
253    let mut out = Vec::new();
254    let mut withheld: Vec<Withheld> = Vec::new();
255    // ONE VERDICT PER (rule, function), whatever the caller's enumeration. `all` is a list of UNITS on
256    // the scan route, and two units can share one qualified name — `#[cfg(unix)] fn f` beside
257    // `#[cfg(not(unix))] fn f` is the everyday case. Their signatures were already merged into one
258    // `inferred` entry keyed by that name, so the gate saw ONE signature and reported it TWICE: two
259    // byte-identical `GateViolation` records, an inflated `N policy violation(s)` count, and a
260    // `--gate-json` document that could not be equal to the one the ⟨0.24⟩ report route produces (a
261    // report is keyed by name, so the duplicate is not reachable there). FOUND BY the §3.1 byte-equality
262    // obligation, on 15 of 90 rows over ebman/pgman/the candor workspace — which is the whole argument
263    // for the verb: no end-to-end test could have separated this from a classifier defect.
264    let mut seen_fn: std::collections::HashSet<&str> = std::collections::HashSet::new();
265    for q in gi.all {
266        if !seen_fn.insert(q.as_str()) {
267            continue;
268        }
269        let inf = gi.inferred.get(q).unwrap_or(&empty);
270        // Materialized ONCE per function rather than per (function, rule): `rule_hits` is generic over
271        // nothing, so the two routes' effect representations (`&'static str` interned / `String` off the
272        // wire) converge here instead of inside the matcher.
273        let effs: Vec<&str> = inf.iter().map(AsRef::as_ref).collect();
274        // AS-EFF-006 — deny/pure: forbidden effects in the transitive set.
275        for r in &p.rules {
276            if let Some(s) = &r.scope {
277                if !scope_matches(q, s) {
278                    continue;
279                }
280            }
281            // ONE implementation of the firing decision, shared with the provable-purity disclosure
282            // ([`crate::policy::unverified_hole_rule`]) — see [`rule_hits`] for what the second copy cost.
283            let RuleHits { hits, withheld: wh } = rule_hits(
284                r,
285                &effs,
286                gi.reason_classes.get(q),
287                gi.net_classes.get(q).map(Vec::as_slice).unwrap_or(&no_classes),
288            );
289            for filter in wh {
290                withheld.push(Withheld { rule: r.raw.clone(), func: q.clone(), filter });
291            }
292            if !hits.is_empty() {
293                // §6.2: when Unknown is denied, report ALL reason classes on the fn (transitive), so the
294                // consumer sees every reason the strict gate bit — not just the class the rule matched.
295                let reason_class = if hits.contains(&"Unknown") {
296                    gi.reason_classes.get(q).map(|cs| cs.iter().cloned().collect()).unwrap_or_default()
297                } else {
298                    Vec::new()
299                };
300                // ⟨0.20⟩ when Net is denied, report ALL of the fn's destination classes (transitive).
301                let net_class = if hits.contains(&"Net") {
302                    gi.net_classes.get(q).cloned().unwrap_or_default()
303                } else {
304                    Vec::new()
305                };
306                out.push(GateViolation {
307                    rule: "AS-EFF-006".into(),
308                    func: q.clone(),
309                    effects: hits.iter().map(|s| s.to_string()).collect(),
310                    detail: format!("`{q}` performs {{ {} }}, forbidden by policy: `{}`", hits.join(", "), r.raw),
311                    reason_class,
312                    net_class,
313                });
314            }
315        }
316        // AS-EFF-008 — literal allowlists over the transitive literal surfaces.
317        for r in &p.allow_rules {
318            if let Some(s) = &r.scope {
319                if !scope_matches(q, s) {
320                    continue;
321                }
322            }
323            if !inf.iter().any(|e| e.as_ref() == r.effect) {
324                continue;
325            }
326            let lits = match r.effect {
327                // `Llm` ⟨0.13⟩ rides the Net host surface (SPEC §1) — `allow Llm <host>` certifies the same
328                // captured hosts as `allow Net`, restricted to the MODEL hosts (a model call's host WAS
329                // captured as a Net literal). Matches candor-java's checkAllowlist("Llm", hostFixpoint, …).
330                "Net" | "Llm" => gi.hosts.get(q),
331                "Exec" => gi.cmds.get(q),
332                "Db" => gi.tables.get(q),
333                _ => gi.paths.get(q),
334            };
335            // An INCOMPLETE surface (a structurally-invisible reach) can't be certified even with visible
336            // hosts — else a benign literal masks the invisible forbidden endpoint (the masking evasion).
337            // `Llm` keys off the NET incompleteness (it rides the Net host literal): a runtime/masked model
338            // host that fails-closes Net must fail-close `allow Llm` too (incompleteAsLlm in candor-java).
339            let inc_key = if r.effect == "Llm" { "Net" } else { r.effect };
340            let surface_incomplete =
341                gi.surface_incomplete.get(q).is_some_and(|s| s.iter().any(|e| e.as_ref() == inc_key));
342            match lits {
343                Some(ls) if !ls.is_empty() && !surface_incomplete => {
344                    let bad: Vec<&str> =
345                        ls.iter().filter(|l| !literal_allowed(r.effect, l, &r.literals)).map(String::as_str).collect();
346                    if !bad.is_empty() {
347                        out.push(GateViolation {
348                            rule: "AS-EFF-008".into(),
349                            func: q.clone(),
350                            effects: vec![r.effect.to_string()],
351                            detail: format!("`{q}` reaches {{ {} }} outside the allowlist: `{}`", bad.join(", "), r.raw),
352                            ..Default::default()
353                        });
354                    }
355                }
356                _ => out.push(GateViolation {
357                    rule: "AS-EFF-008".into(),
358                    func: q.clone(),
359                    effects: vec![r.effect.to_string()],
360                    detail: format!("`{q}` performs {} with no visible literal — the surface cannot be certified: `{}`", r.effect, r.raw),
361                    ..Default::default()
362                }),
363            }
364        }
365        // AS-EFF-009 — layering: no fn in scope A may transitively reach scope B.
366        for r in &p.layer_rules {
367            if !scope_matches(q, &r.from) {
368                continue;
369            }
370            let mut seen: BTreeSet<&str> = BTreeSet::new();
371            let mut stack: Vec<&str> =
372                gi.calls.get(q).map(|cs| cs.iter().map(String::as_str).collect()).unwrap_or_default();
373            let mut hit: Option<&str> = None;
374            while let Some(n) = stack.pop() {
375                if !seen.insert(n) {
376                    continue;
377                }
378                if scope_matches(n, &r.to) {
379                    hit = Some(n);
380                    break;
381                }
382                if let Some(cs) = gi.calls.get(n) {
383                    stack.extend(cs.iter().map(String::as_str));
384                }
385            }
386            if let Some(h) = hit {
387                out.push(GateViolation {
388                    rule: "AS-EFF-009".into(),
389                    func: q.clone(),
390                    effects: Vec::new(), // a layer-flow has no single effect
391                    detail: format!("`{q}` reaches into a forbidden layer (via `{h}`): `{}`", r.raw),
392                    ..Default::default()
393                });
394            }
395        }
396        // ⟨0.29⟩ AS-EFF-011 — `only A -> B …`: a fn in A may reach A and the listed scopes, NOTHING else.
397        //
398        // The same walk as `forbid` above with the test INVERTED, and the inversion is the point rather
399        // than the code. `forbid` fails OPEN — what you did not prohibit is permitted — so a leaf package
400        // can only be protected by enumerating what it must not reach, and that list does not cover a
401        // package added tomorrow. `only` fails SAFE: the dependency you forgot to permit is a violation,
402        // loudly, on the day it appears.
403        //
404        // THE WALK STOPS AT A PERMITTED SCOPE. A permitted callee's own dependencies are governed by the
405        // rules about IT; descending past it would make `only` demand the transitive closure of everything
406        // you permit, which is the same enumeration-that-rots one level down. `from` IS descended through
407        // — a fn in A calling another fn in A that reaches infra is still A reaching infra.
408        for r in &p.only_rules {
409            if !scope_matches(q, &r.from) {
410                continue;
411            }
412            let mut seen: BTreeSet<&str> = BTreeSet::new();
413            let mut stack: Vec<&str> =
414                gi.calls.get(q).map(|cs| cs.iter().map(String::as_str).collect()).unwrap_or_default();
415            let mut hit: Option<&str> = None;
416            while let Some(n) = stack.pop() {
417                if !seen.insert(n) {
418                    continue;
419                }
420                // ⟨0.29⟩ EXACT segment match on a PERMITTED scope — see `scope_matches_permitted`. The
421                // shared prefix matcher is fail-CLOSED for every other rule kind and fail-OPEN here.
422                if r.to.iter().any(|t| scope_matches_permitted(n, t)) {
423                    continue; // permitted, and its own callees are not this rule's business
424                }
425                if !scope_matches(n, &r.from) {
426                    hit = Some(n);
427                    break;
428                }
429                if let Some(cs) = gi.calls.get(n) {
430                    stack.extend(cs.iter().map(String::as_str));
431                }
432            }
433            if let Some(h) = hit {
434                out.push(GateViolation {
435                    // ⟨0.29⟩ ITS OWN CODE, not `forbid`'s. A rule code is the handle a CI suppression, a
436                    // dashboard link and an alert filter key on, and these two are opposite constructs —
437                    // must-not-reach versus must-be-on-the-list. Sharing 009 would make every existing
438                    // `forbid` suppression silently start muting `only` violations its author never
439                    // accepted: a fail-open change to an operator's config, made by us and invisible to
440                    // them, which is the argument this form is built on turned on the tool.
441                    rule: "AS-EFF-011".into(),
442                    func: q.clone(),
443                    effects: Vec::new(),
444                    detail: format!(
445                        "`{q}` reaches `{h}`, which this permission rule does not permit: `{}`",
446                        r.raw
447                    ),
448                    ..Default::default()
449                });
450            }
451        }
452    }
453    // Sort by (rule, detail) — identical order to the old rendered-line sort (the "[rule] detail" render
454    // puts the constant '[' first and all AS-EFF codes are same-length), without allocating two Strings
455    // per comparison.
456    out.sort_by(|a, b| (a.rule.as_str(), a.detail.as_str()).cmp(&(b.rule.as_str(), b.detail.as_str())));
457    // Deterministic for the same reason the violations are: a disclosure a consumer diffs between runs
458    // must not reorder because a HashMap iterated differently.
459    withheld.sort_by(|a, b| (&a.rule, &a.func).cmp(&(&b.rule, &b.func)));
460    withheld.dedup();
461    // ⟨0.27⟩ ZERO-MATCH DISCLOSURE. Counted over the SAME key set the gate iterated, so "bound nothing"
462    // means here exactly what it means to the gate. A `deny`/`pure` with NO scope applies to every
463    // function and so can never be this kind of typo — excluded. A layer rule counts a match on either
464    // endpoint, over the call-graph keys it binds across.
465    let mut zero: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
466    for r in &p.rules {
467        if r.scope.is_some() {
468            zero.entry(r.raw.as_str()).or_insert(0);
469        }
470    }
471    for r in &p.layer_rules {
472        zero.entry(r.raw.as_str()).or_insert(0);
473    }
474    // ⟨0.29⟩ an `only` rule binds nothing when NEITHER endpoint names anything in this tree — the same
475    // typo channel `forbid` has, and the more dangerous one to leave silent: a `forbid` that binds
476    // nothing merely fails to prohibit, while an `only` that binds nothing withholds a promise the
477    // operator believes they made.
478    for r in &p.only_rules {
479        zero.entry(r.raw.as_str()).or_insert(0);
480    }
481    if !zero.is_empty() {
482        let mut names: std::collections::BTreeSet<&str> =
483            gi.all.iter().map(|q| q.as_str()).collect();
484        names.extend(gi.calls.keys().map(String::as_str));
485        for n in names {
486            for r in &p.rules {
487                if let Some(s) = &r.scope {
488                    if scope_matches(n, s) {
489                        *zero.entry(r.raw.as_str()).or_insert(0) += 1;
490                    }
491                }
492            }
493            for r in &p.layer_rules {
494                if scope_matches(n, &r.from) || scope_matches(n, &r.to) {
495                    *zero.entry(r.raw.as_str()).or_insert(0) += 1;
496                }
497            }
498            // ON `from` ONLY, and deliberately NOT on either endpoint the way a `forbid` counts. A
499            // `forbid`'s subject is the pair; an `only`'s subject is `from` — it is a promise ABOUT that
500            // scope — so a rule whose destinations all exist while its `from` names nothing has bound
501            // nothing at all, and is exactly the typo that leaves an operator believing a leaf is
502            // protected. Counting the destinations would hide it behind a scope that happens to resolve.
503            for r in &p.only_rules {
504                if scope_matches(n, &r.from) {
505                    *zero.entry(r.raw.as_str()).or_insert(0) += 1;
506                }
507            }
508        }
509    }
510    let zero_match: Vec<String> = zero
511        .into_iter()
512        .filter(|(_, c)| *c == 0)
513        .map(|(raw, _)| raw.to_string())
514        .collect();
515    GateOutcome { violations: out, withheld, zero_match }
516}