Skip to main content

candor_classify/
policy.rs

1//! The canonical CANDOR_POLICY DSL parser (candor-spec SPEC §6.2).
2//!
3//! This is the **single** Rust implementation of the policy grammar — shared by the nightly dylint
4//! gate (`src/lib.rs`, AS-EFF-006/008/009) and the stable `candor-query` (`whatif`, and the
5//! `parsepolicy` dump the cross-impl conformance suite diffs against the JVM engine). Keeping one
6//! parser here is what makes "the gate means the same thing in every language" a fact rather than a
7//! hope: the Rust gate, the Rust pre-edit tool, and the cross-impl differential all read THIS code.
8//!
9//! Pure, stable Rust (string parsing only — no rustc types), so it lives beside the classifier.
10
11use crate::cap_from_name;
12use std::collections::{BTreeMap, BTreeSet};
13
14/// The honesty marker (SPEC §4). Denyable so `deny Unknown <scope>` forbids the *unverifiable* case.
15pub const UNKNOWN: &str = "Unknown";
16
17/// The NORMATIVE projection of a raw `unknown_why` reason onto a fixed, cross-engine reason CLASS
18/// (candor-spec REASON-SCOPED-UNKNOWN-DESIGN.md §1). Reason-scoped policies (`deny E Unknown[class]`)
19/// quantify over these classes, so the mapping MUST be identical in every engine — this mirrors the
20/// java reference `ReasonClass` (its `classify(String)` path, since rust emits raw string reasons). The
21/// class set is CLOSED (six members); a raw reason matching no pinned prefix maps to `Unresolved` —
22/// conservative: it stays in scope of any `Unknown[*]` / `Unknown[dynamic]` policy, never silently
23/// tolerated.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub enum ReasonClass {
26    /// reflection / metaprogramming
27    Reflect,
28    /// unresolved virtual/dynamic dispatch, same-name ambiguity, invokedynamic
29    Dispatch,
30    /// callback / closure / function-value / async-continuation indirection
31    Indirect,
32    /// FFI / native boundary
33    Native,
34    /// generic unresolvable call/import, AND the catch-all for any unrecognized raw reason
35    Unresolved,
36    /// analysis not wired up (fixable, not a real dynamic hole): missing-config / no-tsconfig
37    Setup,
38}
39
40impl ReasonClass {
41    /// The lowercase policy-facing token (`deny E Unknown[<token>]`).
42    pub fn token(self) -> &'static str {
43        match self {
44            ReasonClass::Reflect => "reflect",
45            ReasonClass::Dispatch => "dispatch",
46            ReasonClass::Indirect => "indirect",
47            ReasonClass::Native => "native",
48            ReasonClass::Unresolved => "unresolved",
49            ReasonClass::Setup => "setup",
50        }
51    }
52
53    /// Parse a policy-facing token back to a class; `None` if it names no class.
54    pub fn from_token(t: &str) -> Option<ReasonClass> {
55        Some(match t {
56            "reflect" => ReasonClass::Reflect,
57            "dispatch" => ReasonClass::Dispatch,
58            "indirect" => ReasonClass::Indirect,
59            "native" => ReasonClass::Native,
60            "unresolved" => ReasonClass::Unresolved,
61            "setup" => ReasonClass::Setup,
62            _ => return None,
63        })
64    }
65
66    /// Map a raw `unknown_why` reason to its normative class — prefix-based (raw reasons carry a
67    /// `kind:detail` shape, e.g. `dispatch:foo::Bar`), unrecognized → `Unresolved`. Byte-identical
68    /// intent to the java `ReasonClass.classify(String)`.
69    ///
70    /// ⟨0.24⟩ THIS IS THE ONLY PLACE THIS ENGINE HOLDS SPEC §4's KIND VOCABULARY. Every other reference
71    /// to a kind is either a raw string being emitted or the `dispatch:` prefix test in candor-query's
72    /// dispatch frontier; there is no typed kind enum here. §4's "AN ENGINE HOLDS THIS VOCABULARY TWICE,
73    /// AND THE HALVES DRIFT" paragraph records the JVM engine classifying `ambiguous` correctly HERE
74    /// while its typed `Kind` enum lacked the kind entirely — one token, two answers, inside one engine,
75    /// concealed precisely because this half was right. Holding it once is why that is not reachable in
76    /// this engine; a future typed representation must be added at the same commit as its control
77    /// (`off_vocabulary_kinds_round_trip_and_classify_through_the_catch_all`).
78    ///
79    /// The five §4 kinds are `reflect`/`native`/`dispatch`/`callback`/`ambiguous`. `ambiguous` maps to
80    /// `dispatch` and rust is its only PRODUCER; `indy`/`task-handoff` are candor-java's migration kinds
81    /// and `dep:`/`dep-stale:` are swift's registered per-dependency-ENTRY kinds, reaching `Unresolved`
82    /// through the catch-all, which is the class §6.2 prescribes for them.
83    pub fn classify(why: &str) -> ReasonClass {
84        let w = why.trim().to_ascii_lowercase();
85        if w.starts_with("reflect") || w == "dynamicmemberlookup" {
86            ReasonClass::Reflect
87        } else if w.starts_with("native") {
88            ReasonClass::Native
89        } else if w.starts_with("callback") || w.starts_with("closure") || w.starts_with("task-handoff") {
90            ReasonClass::Indirect
91        } else if w.starts_with("dispatch") || w.starts_with("indy") || w.starts_with("ambiguous") {
92            ReasonClass::Dispatch
93        } else if w.starts_with("missing-config") || w.starts_with("no-tsconfig") || w.starts_with("no-node_modules") {
94            ReasonClass::Setup
95        } else {
96            ReasonClass::Unresolved
97        }
98    }
99
100    /// The `dynamic` alias — every GENUINE blind-spot class (excludes `setup`), incl. `unresolved` (the
101    /// catch-all) so `Unknown[dynamic]` never under-gates. The design's recommended usable strict gate.
102    pub fn dynamic_set() -> BTreeSet<ReasonClass> {
103        [
104            ReasonClass::Reflect,
105            ReasonClass::Dispatch,
106            ReasonClass::Indirect,
107            ReasonClass::Native,
108            ReasonClass::Unresolved,
109        ]
110        .into_iter()
111        .collect()
112    }
113}
114
115/// SPEC §6.2 ⟨0.24⟩ — does a function's TRANSITIVE reason-class set intersect `want` (class tokens)?
116///
117/// THE `None`/EMPTY ARM IS THE FAIL-CLOSED NET, and it is why this lives here rather than being
118/// open-coded twice. §6.2: "a function whose `Unknown` carries no recorded reason CONTRIBUTES
119/// `unresolved` to its class set — so a narrowed filter never *silently* tolerates a hole it failed to
120/// classify." Read the other way round, `!contains ⇒ exclude` over an empty set drops the entry from
121/// EVERY filter including one naming its own class: a silent under-report wearing a filter.
122///
123/// `classes` is the ACCUMULATED (post-`propagate_str`) set, never the direct `unknownWhy`: a reason
124/// names a site in the function's OWN body (§4), so a function whose `Unknown` is purely inherited
125/// carries none, and matching against the direct field answers a different question. SHARED by the
126/// `deny E Unknown[class]` gate (candor-scan) and `unverified --class` (candor-query) so a gate and the
127/// disclosure explaining it cannot disagree about which holes a class names.
128///
129/// The empty arm is a NET, not a route: it keys on the ABSENCE of a class set, so any other reason on
130/// the same function hides whatever it was covering. The reasonless case that CAN co-occur with a
131/// reason — a direct `Unknown` the unit did not name — must therefore contribute `unresolved` into the
132/// DIRECT map before propagation (candor-scan's `unknown_via_dep`, candor-query's report-side signature),
133/// not arrive here by absence.
134pub fn reason_class_matches(classes: Option<&BTreeSet<String>>, want: &BTreeSet<&str>) -> bool {
135    match classes {
136        None => want.contains(ReasonClass::Unresolved.token()),
137        Some(cs) if cs.is_empty() => want.contains(ReasonClass::Unresolved.token()),
138        Some(cs) => cs.iter().any(|t| want.contains(t.as_str())),
139    }
140}
141
142/// Parse `unknown-alias <name> = <class,…>` lines from `.candor/config` text (⟨0.19⟩, SPEC §6.2) into a
143/// name→classes map. A name that shadows a built-in (`*`/`dynamic`/a class token) is warned-and-skipped (a
144/// config alias may not redefine a built-in), as is a definition naming no valid class. Byte-shape with the
145/// java reference `Config.addAlias`.
146pub fn parse_unknown_aliases(config_text: &str) -> std::collections::BTreeMap<String, BTreeSet<ReasonClass>> {
147    let mut out = std::collections::BTreeMap::new();
148    for raw in config_text.lines() {
149        let line = raw.split('#').next().unwrap_or("").trim();
150        if line.is_empty() {
151            continue;
152        }
153        let mut it = line.splitn(2, char::is_whitespace);
154        // Case-INSENSITIVE key match, like the config loaders in java/ts/swift (which lowercase the key) —
155        // a case-sensitive match here made `Unknown-Alias …` define an alias everywhere BUT rust (a four-way
156        // parse divergence; caught in review). The rest of the line (name + classes) stays case-sensitive.
157        if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("unknown-alias")) {
158            continue;
159        }
160        let val = it.next().unwrap_or("").trim();
161        let Some((name, classes)) = val.split_once('=') else {
162            eprintln!("candor: ignoring `unknown-alias` (want `unknown-alias <name> = <class,…>`): {val}");
163            continue;
164        };
165        let name = name.trim();
166        if name.is_empty() || name == "*" || name == "dynamic" || ReasonClass::from_token(name).is_some() {
167            eprintln!("candor: ignoring `unknown-alias` with reserved/empty name `{name}` (may not shadow `*`/`dynamic`/a class token)");
168            continue;
169        }
170        let mut set = BTreeSet::new();
171        let mut bad: Vec<&str> = Vec::new();
172        for cn in classes.split(',') {
173            let cn = cn.trim();
174            if cn.is_empty() {
175                continue;
176            }
177            if cn == "dynamic" {
178                set.extend(ReasonClass::dynamic_set());
179            } else if let Some(rc) = ReasonClass::from_token(cn) {
180                set.insert(rc);
181            } else {
182                bad.push(cn);
183            }
184        }
185        // ⟨0.24⟩ **AN UNRECOGNISED TOKEN REFUSES THE WHOLE DEFINITION** — SPEC §6.2 `be0b9a9`: the rule
186        // binds every policy value list, and *"the second is the sharper one: the typo is in the
187        // vocabulary the policy is written against rather than in the policy itself, and it fails open
188        // identically."*
189        //
190        // MEASURED: `unknown-alias corp = dispatch,nativ` → the DEFINITION silently became `{dispatch}`,
191        // so `deny Unknown[corp]` exited 0 over a native-caused hole that `= dispatch,native` catches.
192        // The alias resolved, `used_aliases` recorded it, the verdict named the config — every disclosure
193        // fired correctly ABOUT A DEFINITION THAT WAS NOT THE ONE ON DISK.
194        //
195        // REFUSING THE DEFINITION rather than minting a new error channel is what makes this fit: an
196        // alias that does not exist is one the policy's own `Unknown[<name>]` cannot resolve, so it lands
197        // on the `errors` path already there and the gate routes refuse with exit 2 — naming the token
198        // AND the accepted set, as §6.2 requires. It also keeps the blast radius honest: a config
199        // defining ten aliases, one of them typo'd and NONE of them mentioned by this policy, changed
200        // nothing, and turning that into a red gate would be the mirror over-reach. The refusal is
201        // triggered by USE, exactly like `used_aliases` (recorded at the point of use, for the same
202        // reason).
203        if !bad.is_empty() {
204            eprintln!(
205                "candor: REFUSING `unknown-alias {name}` — it names unrecognised reason-class(es) `{}` \
206                 (accepted: reflect, dispatch, indirect, native, unresolved, setup, plus `dynamic`). The \
207                 definition is refused WHOLE rather than narrowed to the tokens that parsed: keeping the \
208                 rest would silently redefine `{name}` as something narrower than the config says, and a \
209                 policy using it would gate less than it reads. `{name}` is now undefined, so a policy \
210                 naming it is a policy error (exit 2).",
211                bad.join("`, `")
212            );
213        } else if set.is_empty() {
214            eprintln!("candor: ignoring `unknown-alias {name}` — no valid reason-class");
215        } else {
216            out.insert(name.to_string(), set);
217        }
218    }
219    out
220}
221
222/// ⟨0.20⟩ Parse `net-partner <host>` lines from `.candor/config` (NET-DESTINATION-CLASS-DESIGN.md): the
223/// per-project set of business-partner hosts the `Net` destination-class classifier treats as
224/// `known-partner`. Multi-value (repeatable key); the value is host-normalized (`:port` stripped,
225/// lowercased) like `MODEL_HOSTS`. Case-insensitive key match, mirroring `parse_unknown_aliases` + the
226/// java/ts/swift config loaders. A partner is per-project — never a universal list.
227pub fn parse_net_partners(config_text: &str) -> BTreeSet<String> {
228    let mut out = BTreeSet::new();
229    for raw in config_text.lines() {
230        let line = raw.split('#').next().unwrap_or("").trim();
231        if line.is_empty() {
232            continue;
233        }
234        let mut it = line.splitn(2, char::is_whitespace);
235        if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("net-partner")) {
236            continue;
237        }
238        let val = it.next().unwrap_or("").trim();
239        if !val.is_empty() {
240            out.insert(host_part(val).to_ascii_lowercase());
241        }
242    }
243    out
244}
245
246/// Discover `.candor/config` text for a policy/scan anchored at `start`: `$CANDOR_CONFIG` if set + readable,
247/// else the nearest `.candor/config` walking UP from `start`, else `None`. Read-only + lenient (no
248/// process-exit — the caller decides fail-closed); used to resolve `unknown-alias` for the §6.2 gate +
249/// `parsepolicy` so both reflect the same checked-in config.
250pub fn discover_config_text(start: &std::path::Path) -> Option<String> {
251    discover_config(start).map(|(_, t)| t)
252}
253
254/// ⟨0.24⟩ As [`discover_config_text`], but ALSO the PATH the text came from, canonicalized.
255///
256/// **WHY THE PATH IS NOW LOAD-BEARING** (SPEC §3.1): a `.candor/config` supplying `unknown-alias`
257/// vocabulary can move a verdict 0→1, and discovery walks PARENT DIRECTORIES, so a file anywhere above
258/// the policy participates — ambient, and until now invisible in the output. *"A verdict changed by a
259/// file the operator cannot see named in the output is the ambient-input failure this whole format
260/// exists to refuse; the remedy is the same one used everywhere else here — not to forbid the input, but
261/// to make it impossible for it to act unnamed."* So the gate document NAMES it, and the path has to
262/// travel out of discovery for that to be possible.
263///
264/// CANONICALIZED because the two routes reach the same file from different working directories, and
265/// §3.1's byte-equality MUST is about the DOCUMENT: a relative path would differ between them for no
266/// reason other than where each was invoked.
267pub fn discover_config(start: &std::path::Path) -> Option<(std::path::PathBuf, String)> {
268    let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
269    // CONFIGURED-BUT-UNUSABLE FAILS LOUD, ON THIS ROUTE TOO. `.ok()` turned an unreadable config into
270    // "no config", so the run continued WITHOUT whatever it declared — a policy, a baseline, an engine
271    // pin, an `unknown-alias` vocabulary. The SCAN route already refuses; this QUERY route did not, so
272    // `gate --report R --policy P` with a broken CANDOR_CONFIG exited 1 here and 2 in java and ts on the
273    // same input. §3.4's posture does not vary by verb.
274    if let Ok(p) = std::env::var("CANDOR_CONFIG") {
275        let p = std::path::PathBuf::from(p);
276        match std::fs::read_to_string(&p) {
277            Ok(t) => return Some((canon(&p), t)),
278            Err(e) => {
279                eprintln!("candor: CANDOR_CONFIG set but {} could not be read ({e}) — failing (exit 2,", p.display());
280                eprintln!("        unevaluable). A config that cannot be read is a guard the operator believes is on.");
281                std::process::exit(2);
282            }
283        }
284    }
285    let start = canon(start);
286    let mut cur = if start.is_dir() { Some(start.as_path()) } else { start.parent() };
287    while let Some(d) = cur {
288        let cand = d.join(".candor/config");
289        if cand.is_file() {
290            match std::fs::read_to_string(&cand) {
291                Ok(t) => return Some((canon(&cand), t)),
292                Err(e) => {
293                    eprintln!("candor: {} exists but could not be read ({e}) — failing (exit 2,", cand.display());
294                    eprintln!("        unevaluable). Treating it as absent would run without what it declares.");
295                    std::process::exit(2);
296                }
297            }
298        }
299        cur = d.parent();
300    }
301    None
302}
303
304/// One `deny <Effect…> [scope]` / `pure <scope>` rule (AS-EFF-006). `effects` empty ⇒ a `pure` rule
305/// (ANY effect forbidden). `scope` is a path segment-scope the rule applies to (None = whole unit).
306#[derive(Debug, Clone)]
307pub struct PolicyRule {
308    pub effects: BTreeSet<&'static str>,
309    pub scope: Option<String>,
310    /// Reason-class filter on an `Unknown` membership (REASON-SCOPED-UNKNOWN-DESIGN.md): empty ⇒
311    /// `Unknown[*]` (any reason — the bare form); non-empty ⇒ the Unknown hit fires ONLY for a fn whose
312    /// (transitive) reason classes include one of these. Ignored when `effects` doesn't contain `Unknown`.
313    pub unknown_classes: BTreeSet<ReasonClass>,
314    /// Destination-class filter on a `Net` membership (NET-DESTINATION-CLASS-DESIGN.md): empty ⇒ `Net[*]`
315    /// (any destination — the bare form); non-empty ⇒ the Net hit fires ONLY for a fn whose (transitive)
316    /// destination classes include one of these. Ignored when `effects` doesn't contain `Net`.
317    pub net_classes: BTreeSet<String>,
318    pub raw: String,
319}
320
321/// One `allow <Effect> [in <scope>] <literal>…` rule (AS-EFF-008). The effect is one of the four
322/// that carry a literal surface (`Net` hosts / `Exec` commands / `Fs` paths / `Db` tables); a
323/// function in `scope` performing it may reach ONLY the listed literals. Matching is
324/// effect-specific (`literal_allowed`).
325#[derive(Debug, Clone)]
326pub struct AllowRule {
327    pub effect: &'static str,
328    pub scope: Option<String>,
329    pub literals: BTreeSet<String>,
330    pub raw: String,
331}
332
333/// One `forbid <A> -> <B>` module-layering rule (AS-EFF-009): a function in scope `A` must not
334/// transitively call into scope `B`.
335#[derive(Debug, Clone)]
336pub struct LayerRule {
337    pub from: String,
338    pub to: String,
339    pub raw: String,
340}
341
342/// ⟨0.24⟩ ONE POLICY LINE THE PARSER DID NOT HONOUR AS WRITTEN (SPEC §3.1 `901f14d` / `195d45a`).
343///
344/// **THE DEFECT.** `parsepolicy` emitted **no `errors` key at all** (measured 2026-07-28 on the
345/// conformance battery: java 10, ts 4, rust 0, swift 0). Every one of these facts existed — they were
346/// printed to stderr as "ignoring policy rule …" — so the verb whose entire purpose is to let a consumer
347/// diff what an engine made of a policy answered the question with the not-honoured half deleted. Worse,
348/// it was INCONSISTENT with this engine's own gate: the gate refuses an unrecognised class token while
349/// the parse narrowed it silently, which is two answers to one question.
350///
351/// **`kind` IS A CLOSED SET, AND IT IS THE SPEC'S, NOT THE REFERENCE ENGINE'S.** `901f14d` pins four
352/// values: `reason-class/alias`, `Net destination-class`, `effect-name`, `rule-kind`. Measured, candor-java
353/// emits `forbid form`, `allow values` and `rule kind` (space, not hyphen) — three values outside the set
354/// and one spelling divergence — and candor-ts renames `kind`→`vocabulary` and `rule`→`where` and emits
355/// `accepted` as a PROSE STRING. This engine follows the clause: a line that names a rule keyword but does
356/// not form that keyword's rule formed no rule kind, so it is `rule-kind`.
357///
358/// `accepted` is an ARRAY OF TOKENS — the tokens that WOULD have been honoured in the position the bad one
359/// occupies. Empty where the position is open-ended (a host, a path), which is a fact about the grammar
360/// rather than a gap in the report.
361#[derive(Debug, Clone)]
362pub struct PolicyError {
363    /// One of [`PolicyError::KIND_REASON_CLASS`], [`PolicyError::KIND_NET_CLASS`],
364    /// [`PolicyError::KIND_EFFECT_NAME`], [`PolicyError::KIND_RULE_KIND`].
365    pub kind: &'static str,
366    /// The offending token, verbatim. Empty when the position was EMPTY (a missing arrow, an `allow` with
367    /// no values) — which is itself the finding.
368    pub token: String,
369    /// The tokens accepted in that position. Empty ⇒ the position takes an open-ended literal.
370    pub accepted: Vec<String>,
371    /// The raw policy line, verbatim.
372    pub rule: String,
373    /// The human sentence — the same text the stderr channel carries, so the two cannot disagree.
374    pub message: String,
375    /// ⟨0.24⟩ Does this error make the policy UNHONOURABLE, so every gate route must refuse (exit 2)?
376    ///
377    /// FATAL and REPORTED are different questions and this field is the only place they are told apart.
378    /// A dropped `nonsense line` is reported and survivable — the rest of the policy means what it says.
379    /// A rewritten `deny Unknown[dispatch,nativ]` is not: the rule that RAN is not the rule that was
380    /// written, and the direction that matters NARROWS it.
381    pub fatal: bool,
382}
383
384impl PolicyError {
385    pub const KIND_REASON_CLASS: &'static str = "reason-class/alias";
386    pub const KIND_NET_CLASS: &'static str = "Net destination-class";
387    pub const KIND_EFFECT_NAME: &'static str = "effect-name";
388    pub const KIND_RULE_KIND: &'static str = "rule-kind";
389}
390
391/// The rule kinds parsed from a CANDOR_POLICY file.
392#[derive(Default, Debug)]
393pub struct ParsedPolicy {
394    pub rules: Vec<PolicyRule>,
395    pub allow_rules: Vec<AllowRule>,
396    pub layer_rules: Vec<LayerRule>,
397    /// ⟨0.24⟩ POLICY ERRORS — a policy that cannot be honoured AS WRITTEN (SPEC §6.2). Non-empty ⇒ every
398    /// gate route MUST refuse: exit 2, the unreadable-policy posture. Not a warning list: the rules in
399    /// `rules` are what the text would mean if the error were tolerated, and tolerating it is the defect.
400    ///
401    /// Today the only member is an unrecognised reason-class/alias token in an `Unknown[…]` filter. The
402    /// asymmetry that used to justify a warning — "a dropped policy token leaves a WIDER rule standing,
403    /// so the failure is loud" — is false in the case that matters, and the false half is FAIL-OPEN:
404    ///
405    ///   - `deny Unknown[corp]` (sole unrecognised token) — the filter empties and the rule WIDENS to a
406    ///     bare `deny Unknown`, while the engine prints "ignoring policy rule" and then KEEPS and
407    ///     re-scopes it. Merely surprising, but a FALSE DISCLOSURE.
408    ///   - `deny Unknown[dispatch,nativ]` (a typo BESIDE valid tokens) — the token is dropped, the rule
409    ///     NARROWS to `[dispatch]`, and it stops gating native-caused holes entirely while the operator
410    ///     reads a gate that looks armed. **That is the fail-open, and it is the common case: a typo
411    ///     lands beside correct tokens far more often than alone.**
412    ///
413    /// A policy that cannot be honoured as written is not silently rewritten into a different policy.
414    ///
415    /// ⟨0.24⟩ THIS LIST NOW HOLDS EVERY LINE THE PARSER DID NOT HONOUR, fatal or not (SPEC §3.1
416    /// `195d45a`) — `parsepolicy` reports them all, and the gate routes refuse on
417    /// [`ParsedPolicy::fatal_messages`] alone. Widening the LIST without widening what REFUSES is the
418    /// whole of the change: a dropped `nonsense line` was always survivable and stays so.
419    pub errors: Vec<PolicyError>,
420    /// ⟨0.24⟩ The `.candor/config` `unknown-alias` definitions this policy actually resolved a token
421    /// through (SPEC §3.1) — **name → the reason-class TOKENS it expanded to**, not a bare name list.
422    /// Non-empty ⇒ a config file supplied vocabulary that PARTICIPATED in the verdict, and the
423    /// `--gate-json` document MUST name that file. Recorded at the point of USE, not from the alias map:
424    /// a config defining ten aliases none of which the policy mentions changed nothing, and naming it
425    /// would train the reader to ignore the field.
426    ///
427    /// ⟨0.24⟩ **THE VALUE TRAVELS WITH THE NAME, AND THAT IS A SPEC MUST** (§3.1, candor-spec `7f5b5ba`).
428    /// This engine shipped the bare name — as did java and swift — and candor-ts kept the map and won the
429    /// argument from the clause's OWN sentence: `configSources: [path]` is rejected there because *a
430    /// disclosure that names the source but not the content leaves the reader knowing they were affected
431    /// and not how*, and `["corp"]` fails that same test one level down. **`corp = reflect` and
432    /// `corp = reflect,native` gate DIFFERENTLY under one unchanged policy line**, so a reader given only
433    /// the name cannot tell which gate ran. The map is a strict superset — the keys recover the old array.
434    ///
435    /// Class TOKENS rather than `ReasonClass`, so the wire order is the token's alphabetical one (which
436    /// is what candor-ts's `[...set].sort()` produces) and not `ReasonClass`'s declaration order.
437    pub used_aliases: BTreeMap<String, BTreeSet<String>>,
438}
439
440impl ParsedPolicy {
441    /// ⟨0.24⟩ The messages of the errors that make the policy UNHONOURABLE — what every gate route
442    /// refuses on. Non-empty ⇒ exit 2, the unreadable-policy posture.
443    ///
444    /// Separate from `errors` because REPORTED and FATAL are different questions, and conflating them in
445    /// either direction is a defect: refusing on every dropped line would make `nonsense line` fail a
446    /// build, and reporting only the fatal ones is the silent narrowing this rung exists to close.
447    pub fn fatal_messages(&self) -> Vec<&str> {
448        self.errors.iter().filter(|e| e.fatal).map(|e| e.message.as_str()).collect()
449    }
450}
451
452/// The hostname part of a `host[:port]` literal, port stripped — so `api.stripe.com` in a rule accepts
453/// a reached `api.stripe.com:443`. IPv6-aware: a bracketed `[host]:port` yields the bracketed host, and
454/// a BARE IPv6 literal (>1 colon, no brackets) has no port to strip and is returned whole — a naive
455/// first-colon split collapsed every `2001:db8::*` to `2001`, so one allowed IPv6 accepted any address
456/// in that block (/code-review). A hostname/IPv4 `host` or `host:port` (≤1 colon) splits at the colon.
457pub fn host_part(h: &str) -> &str {
458    if let Some(rest) = h.strip_prefix('[') {
459        // `[ipv6]` or `[ipv6]:port` — the host is between the brackets.
460        return rest.split(']').next().unwrap_or(rest);
461    }
462    if h.matches(':').count() > 1 {
463        return h; // bare IPv6 literal — no port suffix to strip
464    }
465    h.split(':').next().unwrap_or(h)
466}
467
468/// The basename of a command (`/usr/bin/git` → `git`), so `allow Exec … git` accepts an absolute path.
469pub fn cmd_base(c: &str) -> &str {
470    c.rsplit(['/', '\\']).next().unwrap_or(c)
471}
472
473/// Whether an allowed path `a` covers a reached path `r` (SPEC §6.2: path-boundary-respecting prefix).
474/// A directory covers itself and everything beneath it, but NOT a sibling sharing a textual prefix
475/// (`/etc/app` ⊉ `/etc/apppwned`); a `..` that climbs out is never covered; absolute/relative are
476/// never conflated.
477pub fn fs_path_covered(a: &str, r: &str) -> bool {
478    if r.split(['/', '\\']).any(|c| c == "..") {
479        return false;
480    }
481    let absolute = |s: &str| s.starts_with('/') || s.starts_with('\\');
482    if absolute(a) != absolute(r) {
483        return false;
484    }
485    let norm = |s: &str| -> Vec<String> {
486        s.split(['/', '\\'])
487            .filter(|c| !c.is_empty() && *c != ".")
488            .map(|c| c.to_string())
489            .collect()
490    };
491    let (ac, rc) = (norm(a), norm(r));
492    ac.len() <= rc.len() && ac.iter().zip(&rc).all(|(x, y)| x == y)
493}
494
495/// Whether an allowed table entry `a` covers a reached table `r` (SPEC §6.2): case-insensitive
496/// exact match on the (possibly schema-qualified) name, or a `schema.*` entry covering every table
497/// in that schema. Strict on qualification — an allowed `entries` does NOT cover a reached
498/// `ledger.entries` (write both forms if your queries mix them); silent widening is the failure
499/// mode an allowlist exists to prevent.
500pub fn db_table_covered(a: &str, r: &str) -> bool {
501    let (a, r) = (a.to_lowercase(), r.to_lowercase());
502    if let Some(schema) = a.strip_suffix(".*") {
503        return r.strip_prefix(schema).is_some_and(|rest| rest.starts_with('.'));
504    }
505    a == r
506}
507
508/// Whether a reached literal is allowed under an effect-specific match (SPEC §6.2): `Net` host by
509/// name (port ignored), `Exec` command by basename, `Fs` path by boundary-respecting prefix,
510/// `Db` table by qualified name or `schema.*`.
511pub fn literal_allowed(effect: &str, reached: &str, allow: &BTreeSet<String>) -> bool {
512    match effect {
513        // `Llm` ⟨0.13⟩ rides the Net host literal (SPEC §1) — matched by hostname like `Net`.
514        "Net" | "Llm" => allow.iter().any(|a| host_part(a) == host_part(reached)),
515        "Exec" => allow.iter().any(|a| cmd_base(a) == cmd_base(reached)),
516        "Fs" => allow.iter().any(|a| fs_path_covered(a, reached)),
517        "Db" => allow.iter().any(|a| db_table_covered(a, reached)),
518        _ => allow.contains(reached),
519    }
520}
521
522/// Split a function name (or scope) into PATH SEGMENTS on either separator. Reports reach the Rust gate
523/// AND `candor-query` from BOTH the Rust engines (`::`-separated names) and the JVM/Swift/TS engines
524/// (`.`-separated names — `candor-query` is explicitly built to read them). Segmenting on `::` ALONE
525/// left a scoped `deny`/`pure` rule silently INERT on a dotted name: the scope matched nothing, so
526/// `whatif` returned a false green on the security boundary (gate-evasion). The JVM engine's own
527/// `scopeMatches` already splits on `.`; this aligns the Rust side. A `:`/`.` never appears WITHIN a
528/// real segment, so splitting on both never over-segments a Rust name (no spurious match).
529fn name_segments(s: &str) -> Vec<&str> {
530    s.split(['.', ':']).filter(|p| !p.is_empty()).collect()
531}
532
533/// A policy scope matches a function name by **path segment** (SPEC §6.2), not substring: split both
534/// into segments (on `::` or `.`); the scope matches a contiguous run of name-segments where every
535/// segment except the last matches exactly and the last is a prefix. So `domain` matches
536/// `app::domain::h`, `com.acme.domain.h`, and `domain_logic` but not `subdomain`.
537pub fn scope_matches(name: &str, scope: &str) -> bool {
538    let segs = name_segments(name);
539    let parts = name_segments(scope);
540    if parts.is_empty() || parts.len() > segs.len() {
541        return false;
542    }
543    let (last, init) = parts.split_last().unwrap();
544    segs.windows(parts.len()).any(|w| {
545        let (w_last, w_init) = w.split_last().unwrap();
546        w_init == init && w_last.starts_with(last)
547    })
548}
549
550/// Reconstruct a rule's source form and the `Unknown`-forbidding upgrade for it: `pure <scope>` →
551/// (`"pure <scope>"`, `"deny Unknown <scope>"`); `deny <E…> <scope>` → (`"deny <E…> <scope>"`,
552/// `"deny <E…> Unknown <scope>"`). Shared so the gate note and `candor unverified` name the identical
553/// rule and upgrade — one source of truth for the disclosure's advice.
554///
555/// ⟨0.24⟩ **THE NARROWING FILTERS ARE RENDERED, and they had to start being rendered in the same commit
556/// that made them REACHABLE here.** Making `unverified_hole_rule` filter-aware is what first lets a
557/// `deny Unknown[reflect]` / `deny Net[unknown-host]` rule be the rule a hole is disclosed under — and
558/// this reconstruction dropped the bracket, so the fix would have printed the operator's narrowed rule
559/// back to them as the WIDE one (`deny Unknown`) and advised the nonsense upgrade `deny Unknown
560/// Unknown`. That is the same mis-attribution `whatif` carries, arriving through the fix for a different
561/// defect: the hazard on this rung is that each correction manufactures its own mirror, so the rendering
562/// moves with the predicate rather than after it.
563///
564/// A rule carrying NO filter renders byte-identically to before, which is what keeps conformance PARTs
565/// 12c/12d (`deny Db Net Unknown domain`, four-way) unmoved.
566///
567/// THE UPGRADE SPLITS on whether the rule already denies `Unknown`. If it does, it can only be here
568/// NARROWED — a bare `deny … Unknown` fires on every `Unknown`, so the function would be a violation and
569/// not a hole — and the upgrade is that term WIDENED to bare `Unknown`, not a second `Unknown` appended.
570pub fn rule_and_upgrade(r: &PolicyRule) -> (String, String) {
571    let scope = r.scope.clone().unwrap_or_default();
572    let suffix = if scope.is_empty() { String::new() } else { format!(" {scope}") };
573    if r.effects.is_empty() {
574        // `pure` forbids real effects but not Unknown; to REQUIRE provable purity, add a deny-Unknown.
575        return (format!("pure{suffix}"), format!("deny Unknown{suffix}"));
576    }
577    // One effect term, with its narrowing filter if it has one. Class tokens sorted by TOKEN string, as
578    // `parsepolicy` sorts them and as the java reference's `.sorted()` does — the dump and the
579    // disclosure must spell one rule one way.
580    let term = |e: &str| -> String {
581        if e == UNKNOWN && !r.unknown_classes.is_empty() {
582            let mut t: Vec<&str> = r.unknown_classes.iter().map(|c| c.token()).collect();
583            t.sort_unstable();
584            format!("{UNKNOWN}[{}]", t.join(","))
585        } else if e == "Net" && !r.net_classes.is_empty() {
586            format!("Net[{}]", r.net_classes.iter().map(String::as_str).collect::<Vec<_>>().join(","))
587        } else {
588            e.to_string()
589        }
590    };
591    let effs = r.effects.iter().map(|e| term(e)).collect::<Vec<_>>().join(" ");
592    if r.effects.contains(UNKNOWN) {
593        let widened =
594            r.effects.iter().map(|e| if *e == UNKNOWN { UNKNOWN.to_string() } else { term(e) }).collect::<Vec<_>>();
595        (format!("deny {effs}{suffix}"), format!("deny {}{suffix}", widened.join(" ")))
596    } else {
597        (format!("deny {effs}{suffix}"), format!("deny {effs} {UNKNOWN}{suffix}"))
598    }
599}
600
601/// The single predicate for a provable-purity hole (eval/fixloop/DISPATCH-NOTE.md): a function that is
602/// `Unknown`, sits in a `pure`/`deny <E>` scope, and PASSES that rule (carries none of its forbidden real
603/// effects) — so its compliance is asserted but not verified (the Unknown could hide the very effect the
604/// rule forbids; the classic case is a fn/closure-injected port). A *real* violation is the gate's job, not
605/// this. Returns the first governing rule under which the function is such a hole, or `None` if it is not
606/// one. Shared by candor-scan's gate note and candor-query's `unverified` so "what a hole is" has ONE
607/// definition — the two paths can never drift (conformance PART 12d pins their agreement).
608///
609/// ⟨0.24⟩ **"PASSES" IS NOW ASKED OF THE GATE, NOT OF A SECOND COPY OF IT.** This predicate computed the
610/// passing test from `r.effects` alone — "does the rule NAME an effect this function has?" — which is
611/// the pre-⟨0.19⟩ question, still being asked after two rungs gave rules a NARROWING FILTER. So on
612/// `deny Unknown[reflect]` over an `indirect` hole the gate TOLERATED (exit 0, the class does not match)
613/// while this read the same rule as violated; and a hole is *by definition* a function that PASSES its
614/// rule while `Unknown`, so the real hole was reclassified as a violation-that-isn't and **deleted from
615/// the disclosure** — `unverified` answering "every function in a pure/deny layer is PROVABLY clean ✓"
616/// over a function the gate had just declined to clear. MEASURED 2026-07-28, and reachable with no alias
617/// in play at all: one layer below the widening `ea0df4f` closed, in the same four verbs.
618///
619/// It now calls [`crate::gate::rule_hits`] — the gate's own firing decision — so the two cannot disagree
620/// again. That needs the function's TRANSITIVE reason classes and its ⟨0.20⟩ destination classes, the
621/// same two accumulators the gate reads, which is why they are parameters now rather than derivable.
622///
623/// **THE DIRECTION IS THE MIRROR ARGUMENT.** A filter can only ever SHRINK what a rule charges, so a
624/// filter-aware pass test can only ever find MORE holes — this cannot silently suppress a disclosure
625/// that used to appear. Pinned in both directions by
626/// `a_narrowed_rule_the_gate_tolerates_is_a_hole_and_the_one_it_fires_on_is_not`, in one run, because
627/// the fixture proving the fabrication is closed cannot show the reach closed with it. A WITHHELD filter
628/// — nothing to read — likewise counts as PASSING here: the gate did not clear the function, and an
629/// advisory note's fail-safe direction is to disclose.
630pub fn unverified_hole_rule<'a, S: AsRef<str>>(
631    name: &str,
632    effects: &[S],
633    reason_classes: Option<&BTreeSet<String>>,
634    net_classes: &[String],
635    rules: &'a [PolicyRule],
636) -> Option<&'a PolicyRule> {
637    if !effects.iter().any(|e| e.as_ref() == UNKNOWN) {
638        return None;
639    }
640    let effs: Vec<&str> = effects.iter().map(AsRef::as_ref).collect();
641    rules.iter().find(|r| {
642        // in the rule's scope (a scopeless rule governs the whole unit) …
643        if let Some(s) = &r.scope {
644            if !scope_matches(name, s) {
645                return false;
646            }
647        }
648        // … and PASSES it — the gate's own answer, narrowing filters and all. Empty `hits` IS passing.
649        crate::gate::rule_hits(r, &effs, reason_classes, net_classes).hits.is_empty()
650    })
651}
652
653/// Parse a CANDOR_POLICY file (SPEC §6.2). One rule per line; `#` comments and blanks ignored:
654///
655/// ```text
656/// deny Net Db  domain     # functions whose path contains segment "domain" must not perform Net or Db
657/// deny Exec               # no function anywhere may perform Exec
658/// deny Unknown  api        # functions in "api" must be fully resolvable (forbid the unverifiable)
659/// pure         parse      # functions whose path contains segment "parse" must be effect-free
660/// allow Net in billing  api.stripe.com
661/// forbid domain -> infra
662/// ```
663///
664/// In a `deny` rule, leading tokens that name a known effect (or `Unknown`) are forbidden; the FIRST
665/// non-effect token is the scope and ends the rule. A `deny` naming no known effect is dropped (it is
666/// NOT a `pure` rule). Malformed/unknown lines are ignored with a warning — never silently widened.
667/// The §6.2 token separator: ASCII whitespace ONLY (space/tab/CR/LF/VT/FF). `split_whitespace`/`trim`
668/// use Unicode `White_Space`, which would split a NBSP/ideographic space that Java drops — a gateless-
669/// green cross-engine divergence (adversarial DSL review). A non-ASCII space stays part of its token, so
670/// the rule is malformed and ignored, uniformly.
671fn is_ascii_ws(c: char) -> bool {
672    matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
673}
674
675pub fn parse_policy(text: &str) -> ParsedPolicy {
676    parse_policy_impl(text, true, &std::collections::BTreeMap::new())
677}
678/// As [`parse_policy`] but with `.candor/config` `unknown-alias` definitions (⟨0.19⟩, SPEC §6.2): an
679/// `Unknown[<name>]` filter resolves a user-defined `<name>` to its reason classes. The gate + `parsepolicy`
680/// pass the discovered aliases (via [`parse_unknown_aliases`]); a config alias never changes what bare
681/// `deny E Unknown` means (always `Unknown[*]`), so the rule stays legible from the policy alone.
682pub fn parse_policy_with_aliases(text: &str, aliases: &std::collections::BTreeMap<String, std::collections::BTreeSet<ReasonClass>>) -> ParsedPolicy {
683    parse_policy_impl(text, true, aliases)
684}
685/// ⟨0.24⟩ [`parse_policy_with_aliases`] but SILENT — for a caller that must inspect
686/// [`ParsedPolicy::errors`] / [`ParsedPolicy::used_aliases`] BEFORE it parses for real (candor-scan
687/// refuses before touching the classifier's accumulators). Silent so the ordinary parse warnings are not
688/// printed twice on the same text.
689pub fn parse_policy_silent(
690    text: &str,
691    aliases: &std::collections::BTreeMap<String, BTreeSet<ReasonClass>>,
692) -> ParsedPolicy {
693    parse_policy_impl(text, false, aliases)
694}
695/// Same as [`parse_policy`] but SILENT about malformed rules — for a SECOND, advisory re-parse within the
696/// same run (candor-scan parses once for the gate check and again for the `unverified` disclosure), so the
697/// CI log doesn't print every "ignoring policy rule …" warning twice (#21). The first parse already warned.
698pub fn parse_policy_quiet(text: &str) -> ParsedPolicy {
699    parse_policy_impl(text, false, &std::collections::BTreeMap::new())
700}
701fn parse_policy_impl(text: &str, warn: bool, aliases: &std::collections::BTreeMap<String, std::collections::BTreeSet<ReasonClass>>) -> ParsedPolicy {
702    macro_rules! warn_ignore { ($($a:tt)*) => { if warn { eprintln!($($a)*); } } }
703    let mut out = ParsedPolicy::default();
704    // ⟨0.24⟩ Record a line the parser did not honour (SPEC §3.1 `195d45a`), on the ONE list `parsepolicy`
705    // reports and the gate routes filter for `fatal`. The stderr sentence and `message` are the SAME
706    // string by construction — a disclosure that can drift from the one beside it is how this family
707    // produced a FALSE disclosure once already (conformance PART 13b).
708    macro_rules! not_honoured {
709        ($fatal:expr, $kind:expr, $token:expr, $accepted:expr, $rule:expr, $msg:expr) => {{
710            let message: String = $msg;
711            out.errors.push(PolicyError {
712                kind: $kind,
713                token: ($token).to_string(),
714                accepted: ($accepted).iter().map(|s: &&str| s.to_string()).collect(),
715                rule: ($rule).to_string(),
716                message,
717                fatal: $fatal,
718            });
719        }};
720    }
721    // `str::lines()` splits on \n and \r\n but NOT bare \r — a classic-Mac file then collapses to ONE
722    // line, and since \r is also an in-line ASCII-ws token separator (is_ascii_ws), every rule after the
723    // first was glued into the first rule's tokens and dropped (sweep [16], a gateless-green divergence).
724    // Java's Files.readAllLines (the reference) breaks on bare \r too — normalize to match it. Allocation
725    // only when a bare \r is actually present (the overwhelmingly-common \n / \r\n files are untouched).
726    let normalized;
727    let text = if text.contains('\r') {
728        normalized = text.replace("\r\n", "\n").replace('\r', "\n");
729        normalized.as_str()
730    } else {
731        text
732    };
733    for raw_line in text.lines() {
734        let line = raw_line.split('#').next().unwrap_or("").trim_matches(is_ascii_ws);
735        if line.is_empty() {
736            continue;
737        }
738        let mut toks = line.split(is_ascii_ws).filter(|s| !s.is_empty());
739        match toks.next().unwrap_or("") {
740            "allow" => {
741                let effect = match toks.next().unwrap_or("") {
742                    "Net" => "Net",
743                    // `Llm` ⟨0.13⟩ rides the Net host literal (SPEC §1) — `allow Llm <host…>` restricts which
744                    // MODEL hosts a scope may reach, matched by hostname like Net (its reached surface IS the
745                    // Net host surface). Match candor-java's Policy.parsePolicy.
746                    "Llm" => "Llm",
747                    "Exec" => "Exec",
748                    "Fs" => "Fs",
749                    "Db" => "Db",
750                    other => {
751                        let msg = format!(
752                            "unknown effect-name `{other}` in `allow` (accepted: Db, Exec, Fs, Llm, Net \
753                             \u{2014} `allow` covers only the effects carrying a literal surface: Net/Llm \
754                             hosts, Exec commands, Fs paths, Db tables): {line}"
755                        );
756                        warn_ignore!("candor: policy error — {msg}");
757                        // ⟨0.24⟩ FATAL (SPEC §6.2 `1e1748a`). MEASURED four-way before this:
758                        // `allow Nett host.example` -> exit 0 on rust, ts, java AND swift. The rule is
759                        // DELETED and the certification silently vanishes, so the operator reads an
760                        // armed allowlist that does not exist.
761                        //
762                        // The grammar defence that kept the token rule inside the bracket does NOT
763                        // reach here: `allow`'s effect position is a fixed, closed set with **no scope
764                        // reading available**, so an unrecognised token there is unambiguously a typo
765                        // and there is no legitimate policy it could be. This document already calls a
766                        // dropped rule "the limit case of silently rewritten into a different policy…
767                        // a bigger rewrite than a narrowed filter" — and the bigger rewrite was
768                        // warning-only while the smaller one was already exit 2.
769                        not_honoured!(
770                            true,
771                            PolicyError::KIND_EFFECT_NAME,
772                            other,
773                            ["Db", "Exec", "Fs", "Llm", "Net"],
774                            line,
775                            msg
776                        );
777                        continue;
778                    }
779                };
780                let mut rest: Vec<&str> = toks.collect();
781                let scope = if rest.first() == Some(&"in") {
782                    let s = rest.get(1).map(|s| s.to_string());
783                    rest.drain(..2.min(rest.len()));
784                    s
785                } else {
786                    None
787                };
788                let literals: BTreeSet<String> = rest.iter().map(|h| h.to_string()).collect();
789                if literals.is_empty() {
790                    let msg = format!("`allow {effect}` names no values: {line}");
791                    warn_ignore!("candor: ignoring policy rule ({msg})");
792                    // `accepted` is EMPTY on purpose: the position takes an open-ended literal (a host, a
793                    // path, a command, a table), so there is no token list to offer. A fact about the
794                    // grammar, not a gap in the report.
795                    not_honoured!(false, PolicyError::KIND_RULE_KIND, "", [], line, msg);
796                    continue;
797                }
798                out.allow_rules.push(AllowRule { effect, scope, literals, raw: line.to_string() });
799            }
800            "deny" => {
801                let mut effects = BTreeSet::new();
802                let mut scope = None;
803                // Reason-class filter on `Unknown` (REASON-SCOPED-UNKNOWN-DESIGN.md): empty ⇒ `Unknown[*]`
804                // (any reason — the bare form); non-empty ⇒ only those classes. `*` = all.
805                let mut unknown_classes: BTreeSet<ReasonClass> = BTreeSet::new();
806                let mut unknown_star = false;
807                // Destination-class filter on `Net` (NET-DESTINATION-CLASS-DESIGN.md): empty ⇒ `Net[*]`
808                // (any destination — the bare form); non-empty ⇒ only those classes. `*` = all.
809                let mut net_classes: BTreeSet<String> = BTreeSet::new();
810                let mut net_star = false;
811                for t in toks {
812                    // `Net[unknown-host]` / `Net[*]` / `Net[known-telemetry,unknown-host]`: the destination-scoped form.
813                    if let Some(inner) = t.strip_prefix("Net[").and_then(|s| s.strip_suffix(']')) {
814                        effects.insert("Net");
815                        for cn in inner.split(',') {
816                            let cn = cn.trim();
817                            if cn.is_empty() {
818                                continue;
819                            }
820                            if cn == "*" {
821                                net_star = true;
822                            } else if crate::NET_DEST_CLASSES.contains(&cn) {
823                                net_classes.insert(cn.to_string());
824                            } else {
825                                // ⟨0.24⟩ A POLICY ERROR, not a warning — SPEC §6.2 `be0b9a9`. Byte-identical
826                                // in shape to the reason-class arm below, and byte-identical in harm:
827                                // MEASURED `deny Net[known-telemetry,unknown-hosst]` → exit 0 where the
828                                // correctly-spelled rule exits 1. The typo is dropped, the filter NARROWS
829                                // to `[known-telemetry]`, and the gate stops covering unidentifiable
830                                // destinations while the operator reads a gate that looks armed.
831                                not_honoured!(
832                                    true,
833                                    PolicyError::KIND_NET_CLASS,
834                                    cn,
835                                    ["known-telemetry", "known-partner", "unknown-host", "*"],
836                                    line,
837                                    format!(
838                                        "unrecognised Net destination-class `{cn}` in `{line}` — \
839                                         accepted: known-telemetry, known-partner, unknown-host, plus `*`"
840                                    )
841                                );
842                            }
843                        }
844                        continue;
845                    }
846                    // `Unknown[dispatch,reflect]` / `Unknown[*]` / `Unknown[dynamic]`: the reason-scoped form.
847                    if let Some(inner) = t.strip_prefix("Unknown[").and_then(|s| s.strip_suffix(']')) {
848                        effects.insert(UNKNOWN);
849                        for cn in inner.split(',') {
850                            let cn = cn.trim();
851                            if cn.is_empty() {
852                                continue;
853                            }
854                            if cn == "*" {
855                                unknown_star = true;
856                            } else if cn == "dynamic" {
857                                unknown_classes.extend(ReasonClass::dynamic_set());
858                            } else if let Some(rc) = ReasonClass::from_token(cn) {
859                                unknown_classes.insert(rc);
860                            } else if let Some(a) = aliases.get(cn) {
861                                unknown_classes.extend(a.iter().copied()); // ⟨0.19⟩ config `unknown-alias`
862                                // ⟨0.24⟩ → the verdict names it AND what it expanded to (SPEC §3.1
863                                // `7f5b5ba`): the NAME alone cannot tell a reader which gate ran.
864                                out.used_aliases
865                                    .insert(cn.to_string(), a.iter().map(|c| c.token().to_string()).collect());
866                            } else {
867                                // ⟨0.24⟩ A POLICY ERROR, not a warning — see `ParsedPolicy::errors`. The
868                                // token is still dropped below so `rules` stays well-formed for the
869                                // advisory readers (`unverified`, `parsepolicy`); the gate routes refuse
870                                // on `errors` before any of it is used as a verdict.
871                                not_honoured!(
872                                    true,
873                                    PolicyError::KIND_REASON_CLASS,
874                                    cn,
875                                    [
876                                        "reflect",
877                                        "dispatch",
878                                        "indirect",
879                                        "native",
880                                        "unresolved",
881                                        "setup",
882                                        "dynamic",
883                                        "*"
884                                    ],
885                                    line,
886                                    format!(
887                                        "unrecognised reason-class/alias `{cn}` in `{line}` — accepted: \
888                                         reflect, dispatch, indirect, native, unresolved, setup, plus the \
889                                         aliases `dynamic` and `*`, plus any `unknown-alias` defined in \
890                                         the `.candor/config` beside the policy. (⟨0.24⟩ an \
891                                         `unknown-alias` whose OWN definition names an unrecognised class \
892                                         is refused WHOLE, so a typo in the config surfaces as an \
893                                         undefined alias here — check the `unknown-alias` lines too, and \
894                                         the line above this one.)"
895                                    )
896                                );
897                            }
898                        }
899                        continue;
900                    }
901                    let e = if t == UNKNOWN { Some(UNKNOWN) } else { cap_from_name(t) };
902                    match e {
903                        Some(e) => {
904                            effects.insert(e);
905                            if e == UNKNOWN {
906                                unknown_star = true; // bare Unknown ⇒ all classes
907                            }
908                            if e == "Net" {
909                                net_star = true; // bare Net ⇒ all destinations
910                            }
911                        }
912                        None => {
913                            scope = Some(t.to_string());
914                            break;
915                        }
916                    }
917                }
918                if effects.is_empty() {
919                    // The accepted set is the §1 effect vocabulary plus `Unknown` — SORTED, so the
920                    // document is deterministic and diffable across engines.
921                    let mut acc: Vec<&str> = candor_report::EFFECTS.to_vec();
922                    acc.push(UNKNOWN);
923                    acc.sort_unstable();
924                    let msg = format!(
925                        "`deny` names no known effect (accepted: {}): {line}",
926                        acc.join(", ")
927                    );
928                    warn_ignore!("candor: policy error — {msg}");
929                    // ⟨0.24⟩ FATAL (SPEC §6.2 `1e1748a`). MEASURED four-way: `deny Nett app` -> exit 0
930                    // on all four; the rule is DELETED and the gate is green. `Nett` is read as the
931                    // SCOPE (the first unrecognised token ends the effect list), so the line parses to
932                    // a deny of NOTHING.
933                    //
934                    // **A `deny` whose effect list ends up EMPTY is malformed under EITHER reading** —
935                    // typo-in-the-effect or scope-with-no-effect are both nonsense — so there is no
936                    // legitimate policy it could be and refusing it loses nothing. What stays open is
937                    // only the genuinely ambiguous middle (`deny Net Exex app`: at least one valid
938                    // effect plus an unrecognised trailing token that MIGHT be a scope), which the
939                    // parser cannot tell from a legitimate scope and which `parsepolicy` shows either
940                    // way by dumping the `scope` it read.
941                    not_honoured!(
942                        true,
943                        PolicyError::KIND_EFFECT_NAME,
944                        scope.as_deref().unwrap_or(""),
945                        acc,
946                        line,
947                        msg
948                    );
949                    continue;
950                }
951                // `*` (or bare `Unknown`) means all classes ⇒ empty filter (matches any Unknown).
952                if unknown_star {
953                    unknown_classes.clear();
954                } else if !unknown_classes.is_empty() && !unknown_classes.contains(&ReasonClass::Unresolved) {
955                    // A2 under-gating lint: a narrowed scope that omits `unresolved` (the catch-all for holes
956                    // an engine couldn't classify) may silently tolerate exactly those — flag it (advisory).
957                    warn_ignore!("candor: policy rule narrows `Unknown[…]` but omits `unresolved` — may UNDER-gate on holes the engine couldn't classify; add `unresolved` (or use `dynamic`) to stay conservative: {line}");
958                }
959                // `*` (or bare `Net`) means all destinations ⇒ empty filter (matches any Net).
960                if net_star {
961                    net_classes.clear();
962                }
963                out.rules.push(PolicyRule { effects, scope, unknown_classes, net_classes, raw: line.to_string() });
964            }
965            "pure" => out.rules.push(PolicyRule {
966                effects: BTreeSet::new(),
967                scope: toks.next().map(str::to_string),
968                unknown_classes: BTreeSet::new(),
969                net_classes: BTreeSet::new(),
970                raw: line.to_string(),
971            }),
972            "forbid" => {
973                let a = toks.next().unwrap_or("");
974                let arrow = toks.next().unwrap_or("");
975                let b = toks.next().unwrap_or("");
976                if a.is_empty() || arrow != "->" || b.is_empty() {
977                    let msg = format!("`forbid` is malformed (want `forbid <scope> -> <scope>`): {line}");
978                    warn_ignore!("candor: ignoring layering rule ({msg})");
979                    // The token reported is whatever sat in the ARROW position — `->` must be its own
980                    // token, so `forbid glued->arrow` finds nothing there and that absence is the finding.
981                    not_honoured!(false, PolicyError::KIND_RULE_KIND, arrow, ["->"], line, msg);
982                    continue;
983                }
984                out.layer_rules.push(LayerRule {
985                    from: a.to_string(),
986                    to: b.to_string(),
987                    raw: line.to_string(),
988                });
989            }
990            other => {
991                let msg = format!(
992                    "unknown rule kind `{other}` (accepted: allow, deny, forbid, pure): {line}"
993                );
994                warn_ignore!("candor: ignoring policy rule ({msg})");
995                not_honoured!(
996                    false,
997                    PolicyError::KIND_RULE_KIND,
998                    other,
999                    ["allow", "deny", "forbid", "pure"],
1000                    line,
1001                    msg
1002                );
1003            }
1004        }
1005    }
1006    out
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    #[test]
1012    fn db_table_covering_is_strict() {
1013        use super::db_table_covered as c;
1014        assert!(c("ledger.entries", "Ledger.Entries")); // case-insensitive exact
1015        assert!(c("ledger.*", "ledger.entries"));       // schema wildcard
1016        assert!(!c("ledger.*", "ledgerx.entries"));     // boundary-respecting
1017        assert!(!c("entries", "ledger.entries"));       // no silent qualification widening
1018        assert!(c("entries", "entries"));
1019    }
1020
1021    #[test]
1022    fn allow_db_parses_and_gates() {
1023        let p = super::parse_policy("allow Db in billing  ledger.* customers\n");
1024        assert_eq!(p.allow_rules.len(), 1);
1025        assert_eq!(p.allow_rules[0].effect, "Db");
1026        assert!(super::literal_allowed("Db", "ledger.entries", &p.allow_rules[0].literals));
1027        assert!(super::literal_allowed("Db", "customers", &p.allow_rules[0].literals));
1028        assert!(!super::literal_allowed("Db", "audit.log", &p.allow_rules[0].literals));
1029    }
1030
1031    use super::*;
1032
1033    #[test]
1034    fn policy_parses() {
1035        let p = parse_policy(
1036            "# the domain layer must stay pure of I/O\n\
1037             deny Net Db  domain\n\
1038             deny Exec\n\
1039             pure  parse\n\
1040             nonsense line\n\
1041             deny notaneffect\n",
1042        );
1043        let rules = &p.rules;
1044        assert_eq!(rules.len(), 3);
1045        assert_eq!(rules[0].effects, ["Db", "Net"].into_iter().collect::<BTreeSet<_>>());
1046        assert_eq!(rules[0].scope.as_deref(), Some("domain"));
1047        assert!(rules[1].effects.contains("Exec") && rules[1].scope.is_none());
1048        assert!(rules[2].effects.is_empty() && rules[2].scope.as_deref() == Some("parse"));
1049        // sweep [16]: a classic-Mac (bare \r) multi-rule policy must NOT collapse to the first rule.
1050        let cr = parse_policy("deny Net a\rdeny Exec b\rdeny Db c\r");
1051        assert_eq!(cr.rules.len(), 3, "bare-CR lines must each parse");
1052        assert!(cr.rules.iter().any(|r| r.effects.contains("Exec") && r.scope.as_deref() == Some("b")));
1053        // mixed \r\n and bare \r normalize identically.
1054        assert_eq!(parse_policy("deny Net a\r\ndeny Exec b\r").rules.len(), 2);
1055        // `Unknown` is a denyable token; a bare `deny` with no effect is ignored.
1056        assert_eq!(parse_policy("deny Unknown core").rules[0].effects, ["Unknown"].into_iter().collect());
1057        assert!(parse_policy("deny\ndeny   \n").rules.is_empty());
1058        // a `deny` whose first token is a non-effect names no effect -> dropped, NOT a pure rule.
1059        assert!(parse_policy("deny notaneffect scope").rules.is_empty());
1060        // the first non-effect token ENDS the rule: a later effect token is not collected.
1061        let p2 = parse_policy("deny Net foo Db");
1062        assert_eq!(p2.rules[0].effects, ["Net"].into_iter().collect::<BTreeSet<_>>());
1063        assert_eq!(p2.rules[0].scope.as_deref(), Some("foo"));
1064        // NBSP is NOT a token separator (only ASCII White_Space is) — pinned to MATCH Java, which
1065        // drops it: a `deny\u{a0}Net` is one token `deny\u{a0}Net`, NOT `deny` + `Net`, so it names no
1066        // known effect and is dropped. Splitting on Unicode whitespace here would let candor see a deny
1067        // the JVM engine doesn't — a gateless-divergence between impls. (See is_ascii_ws.)
1068        assert!(parse_policy("deny\u{a0}Net core").rules.is_empty(),
1069                "an NBSP between deny and the effect must NOT split into separate tokens");
1070        // The NBSP rides INTO the scope token rather than separating it: `deny Net\u{a0}domain` is
1071        // `deny` + `Net` + `\u{a0}domain` — Net is the effect, the scope keeps the NBSP verbatim.
1072        let nb = parse_policy("deny Net \u{a0}domain");
1073        assert_eq!(nb.rules.len(), 1);
1074        assert_eq!(nb.rules[0].effects, ["Net"].into_iter().collect::<BTreeSet<_>>());
1075        assert_eq!(nb.rules[0].scope.as_deref(), Some("\u{a0}domain"));
1076    }
1077
1078    #[test]
1079    fn reason_scoped_unknown_parses() {
1080        use super::ReasonClass::*;
1081        // `Unknown[dispatch,indirect]` narrows the Unknown membership to those classes.
1082        let p = parse_policy("deny Net Unknown[dispatch,indirect] dom\n");
1083        let r = &p.rules[0];
1084        assert!(r.effects.contains("Unknown") && r.effects.contains("Net"));
1085        assert_eq!(r.scope.as_deref(), Some("dom"));
1086        assert_eq!(r.unknown_classes, [Dispatch, Indirect].into_iter().collect());
1087        // bare `Unknown` and `Unknown[*]` ⇒ empty filter (all classes).
1088        assert!(parse_policy("deny Net Unknown dom\n").rules[0].unknown_classes.is_empty(), "bare Unknown ⇒ all");
1089        assert!(parse_policy("deny Net Unknown[*] dom\n").rules[0].unknown_classes.is_empty(), "Unknown[*] ⇒ all");
1090        // `dynamic` alias = every genuine class incl. unresolved, excl. setup.
1091        assert_eq!(
1092            parse_policy("deny Net Unknown[dynamic] dom\n").rules[0].unknown_classes,
1093            [Reflect, Dispatch, Indirect, Native, Unresolved].into_iter().collect()
1094        );
1095        // config `unknown-alias` (⟨0.19⟩): a user-defined name resolves; a reserved name is rejected.
1096        let aliases = super::parse_unknown_aliases(
1097            "unknown-alias risky = reflect,native\nunknown-alias telemetry = indirect\nunknown-alias reflect = native\n");
1098        assert_eq!(aliases.get("risky"), Some(&[Reflect, Native].into_iter().collect()));
1099        assert_eq!(aliases.get("telemetry"), Some(&[Indirect].into_iter().collect()));
1100        assert!(!aliases.contains_key("reflect"), "a config alias may not shadow a class token");
1101        // the `unknown-alias` KEY matches case-insensitively (parity with java/ts/swift, which lowercase it)
1102        assert_eq!(super::parse_unknown_aliases("Unknown-Alias hot = native\n").get("hot"),
1103                   Some(&[Native].into_iter().collect()), "the unknown-alias key must match case-insensitively");
1104        let pr = super::parse_policy_with_aliases("deny Net Unknown[risky] api\n", &aliases);
1105        assert_eq!(pr.rules[0].unknown_classes, [Reflect, Native].into_iter().collect());
1106        // an UNDEFINED alias name is dropped-with-warning → empty filter (behaves like bare Unknown[*])
1107        assert!(super::parse_policy_with_aliases("deny Net Unknown[nope] api\n", &aliases).rules[0].unknown_classes.is_empty());
1108        // classify: raw reason tokens → normative classes (mirrors java ReasonClass.classify).
1109        assert_eq!(ReasonClass::classify("reflect:Class.forName"), Reflect);
1110        assert_eq!(ReasonClass::classify("native:extern fn"), Native);
1111        assert_eq!(ReasonClass::classify("callback:unresolved call"), Indirect);
1112        assert_eq!(ReasonClass::classify("ambiguous:same-name local defs"), Dispatch);
1113        assert_eq!(ReasonClass::classify("unresolved"), Unresolved);
1114        assert_eq!(ReasonClass::classify("whatever-new"), Unresolved); // conservative catch-all
1115    }
1116
1117    /// THE CONTROL SPEC §4 ⟨0.24⟩ MAKES A SHOULD: a FABRICATED, off-vocabulary kind must still behave as
1118    /// §2 forward-compatibility requires. Without it, "added a fifth kind" and "stopped checking the kind
1119    /// set" are the same diff — the classifier is one `_ =>` arm away from either.
1120    ///
1121    /// This engine holds the §4 vocabulary ONCE (the raw `kind:detail` string, read back only through
1122    /// `classify`), so there is no typed half here to drift from it. That is why the JVM engine's failure
1123    /// — a string classifier correct on `ambiguous` since July while its typed `Kind` enum lacked the kind
1124    /// entirely, one token classified two ways inside one engine — is not reproducible here. If a typed
1125    /// kind representation is ever added, this test is where its half gets its control.
1126    #[test]
1127    fn off_vocabulary_kinds_round_trip_and_classify_through_the_catch_all() {
1128        use ReasonClass::*;
1129        // A kind no engine emits and no section names. §2: tolerated, and classified CONSERVATIVELY —
1130        // `unresolved`, the catch-all, so a narrowed `Unknown[unresolved]`/`[dynamic]`/`[*]` still bites it.
1131        assert_eq!(ReasonClass::classify("banana:whatever"), Unresolved);
1132        assert_eq!(ReasonClass::classify("banana:dispatch of a banana"), Unresolved,
1133                   "a canonical kind appearing in the DETAIL must not leak into the classification");
1134        // …and it must not be swallowed into a narrower class. These are the four wrong answers.
1135        for wrong in [Reflect, Dispatch, Indirect, Native] {
1136            assert_ne!(ReasonClass::classify("banana:whatever"), wrong);
1137        }
1138        // The five §4 ⟨0.24⟩ kinds all classify, and `ambiguous` is the fifth — pinned beside the
1139        // fabricated one deliberately: one arm chain answers both, so a change that stops distinguishing
1140        // them fails here rather than in the field.
1141        assert_eq!(ReasonClass::classify("reflect:x"), Reflect);
1142        assert_eq!(ReasonClass::classify("native:x"), Native);
1143        assert_eq!(ReasonClass::classify("dispatch:Owner.member"), Dispatch);
1144        assert_eq!(ReasonClass::classify("callback:x"), Indirect);
1145        assert_eq!(ReasonClass::classify("ambiguous:x"), Dispatch);
1146        // ⟨0.24⟩ `dep:<hash>` / `dep-stale:<pkg>` are REGISTERED §4 kinds, not migration ones — swift
1147        // emits them per dependency ENTRY, and this engine CONSUMES swift/ts reports through
1148        // candor-query. §6.2 pins their class as `unresolved`, which is where the catch-all lands them;
1149        // pinned so a future prefix arm cannot move them without saying so.
1150        assert_eq!(ReasonClass::classify("dep:9f2c1a"), Unresolved);
1151        assert_eq!(ReasonClass::classify("dep-stale:somepkg"), Unresolved);
1152    }
1153
1154    #[test]
1155    fn net_destination_class_parses_and_classifies() {
1156        // `Net[unknown-host,known-telemetry]` narrows the Net membership to those destination classes.
1157        let p = parse_policy("deny Net[unknown-host,known-telemetry] dom\n");
1158        let r = &p.rules[0];
1159        assert!(r.effects.contains("Net"));
1160        assert_eq!(r.scope.as_deref(), Some("dom"));
1161        assert_eq!(
1162            r.net_classes,
1163            ["unknown-host", "known-telemetry"].iter().map(|s| s.to_string()).collect()
1164        );
1165        // bare `Net` and `Net[*]` ⇒ empty filter (all destinations).
1166        assert!(parse_policy("deny Net dom\n").rules[0].net_classes.is_empty(), "bare Net ⇒ all");
1167        assert!(parse_policy("deny Net[*] dom\n").rules[0].net_classes.is_empty(), "Net[*] ⇒ all");
1168        // an unknown destination-class is dropped-with-warning → empty filter (behaves like bare Net[*]).
1169        assert!(parse_policy("deny Net[nope] dom\n").rules[0].net_classes.is_empty());
1170        // the classifier: telemetry (subdomain-aware), model host, unresolved, and the config-partner path.
1171        let no_partners = BTreeSet::new();
1172        assert_eq!(crate::net_dest_class("sentry.io", &no_partners), "known-telemetry");
1173        assert_eq!(crate::net_dest_class("us.i.posthog.com", &no_partners), "known-telemetry"); // 0.20.1 corpus-grown
1174        assert_eq!(crate::net_dest_class("o1.ingest.sentry.io", &no_partners), "known-telemetry");
1175        assert_eq!(crate::net_dest_class("api.openai.com", &no_partners), "known-partner", "a model host is known-partner");
1176        assert_eq!(crate::net_dest_class("evil.example.com", &no_partners), "unknown-host");
1177        let partners: BTreeSet<String> = ["api.stripe.com".to_string()].into_iter().collect();
1178        assert_eq!(crate::net_dest_class("api.stripe.com", &partners), "known-partner", "config-declared partner");
1179        assert_eq!(crate::net_dest_class("api.stripe.com", &no_partners), "unknown-host", "partner is config-only");
1180        // `net-partner` config parsing: host-normalized, case-insensitive key, multi-value.
1181        let pset = super::parse_net_partners("net-partner Api.Stripe.com:443\nNET-PARTNER hooks.stripe.com\n");
1182        assert!(pset.contains("api.stripe.com") && pset.contains("hooks.stripe.com"));
1183    }
1184
1185    #[test]
1186    fn allowlist_parses() {
1187        let p = parse_policy(
1188            "allow Net in billing  api.stripe.com  hooks.stripe.com\n\
1189             allow Exec in ci  git\n\
1190             allow Fs in config  /etc/app\n\
1191             allow Net  github.com\n\
1192             allow Clock  whatever\n\
1193             allow Net in nohosts\n\
1194             allow\n",
1195        );
1196        assert_eq!(p.allow_rules.len(), 4); // Clock carries no literal surface — rejected; Db now does
1197        assert_eq!((p.allow_rules[0].effect, p.allow_rules[0].scope.as_deref()), ("Net", Some("billing")));
1198        assert_eq!(
1199            p.allow_rules[0].literals,
1200            ["api.stripe.com", "hooks.stripe.com"].iter().map(|s| s.to_string()).collect()
1201        );
1202        assert_eq!((p.allow_rules[1].effect, p.allow_rules[1].scope.as_deref()), ("Exec", Some("ci")));
1203        assert!(p.allow_rules[1].literals.contains("git"));
1204        assert_eq!((p.allow_rules[2].effect, p.allow_rules[2].scope.as_deref()), ("Fs", Some("config")));
1205        assert_eq!((p.allow_rules[3].effect, p.allow_rules[3].scope.is_none()), ("Net", true));
1206
1207        let set = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<BTreeSet<_>>();
1208        assert!(literal_allowed("Net", "api.stripe.com:443", &set(&["api.stripe.com"])));
1209        // IPv6: a bare literal is matched WHOLE (no first-colon collapse), so a different address in the
1210        // same block is NOT accepted; a bracketed `[host]:port` matches the bare host. (/code-review.)
1211        assert!(literal_allowed("Net", "2001:db8::aa", &set(&["2001:db8::aa"])));
1212        assert!(!literal_allowed("Net", "2001:db8::ff", &set(&["2001:db8::aa"])));
1213        assert!(!literal_allowed("Net", "2001:dead::1", &set(&["2001:db8::aa"])));
1214        assert!(literal_allowed("Net", "[2001:db8::aa]:443", &set(&["2001:db8::aa"])));
1215        assert_eq!(host_part("2001:db8::aa"), "2001:db8::aa");
1216        assert_eq!(host_part("[2001:db8::aa]:443"), "2001:db8::aa");
1217        assert_eq!(host_part("api.stripe.com:443"), "api.stripe.com");
1218        assert!(literal_allowed("Exec", "/usr/bin/git", &set(&["git"])));
1219        assert!(!literal_allowed("Exec", "/usr/bin/curl", &set(&["git"])));
1220        assert!(literal_allowed("Fs", "/etc/app/conf.toml", &set(&["/etc/app"])));
1221        assert!(!literal_allowed("Fs", "/etc/shadow", &set(&["/etc/app"])));
1222        assert_eq!(cmd_base("/usr/bin/git"), "git");
1223    }
1224
1225    #[test]
1226    fn layering_rule_parses() {
1227        let p = parse_policy(
1228            "forbid domain -> infra\n\
1229             forbid  app::web  ->  app::db \n\
1230             forbid domain infra\n\
1231             forbid domain ->\n\
1232             forbid\n",
1233        );
1234        assert_eq!(p.layer_rules.len(), 2);
1235        assert_eq!((p.layer_rules[0].from.as_str(), p.layer_rules[0].to.as_str()), ("domain", "infra"));
1236        assert_eq!((p.layer_rules[1].from.as_str(), p.layer_rules[1].to.as_str()), ("app::web", "app::db"));
1237    }
1238
1239    #[test]
1240    fn scope_matches_by_segment_not_substring() {
1241        assert!(scope_matches("app::domain::handle", "domain"));
1242        assert!(scope_matches("domain::handle", "domain"));
1243        assert!(scope_matches("app::domain", "domain"));
1244        assert!(scope_matches("crate::domain_logic", "domain"));
1245        assert!(!scope_matches("app::subdomain::handle", "domain"));
1246        assert!(!scope_matches("app::not_my_domain::f", "domain"));
1247        // multi-segment: intermediates exact, last is a prefix, contiguous.
1248        assert!(scope_matches("crate::net::client::send", "net::client"));
1249        assert!(scope_matches("crate::net::client_pool::get", "net::client"));
1250        assert!(!scope_matches("crate::net::server::send", "net::client"));
1251        assert!(!scope_matches("crate::network::client::send", "net::client"));
1252        assert!(!scope_matches("crate::net::x::client", "net::client"));
1253        assert!(!scope_matches("net", "net::client"));
1254        // DOTTED names (JVM/Swift/TS reports `candor-query` consumes): a scope must match across `.` too,
1255        // else a scoped deny/pure rule is silently inert → whatif false-green (gate-evasion). Both a
1256        // `.`-written and a `::`-written scope must match a dotted name.
1257        assert!(scope_matches("com.acme.domain.Pricing.quote", "domain"));
1258        assert!(scope_matches("com.acme.domain.Pricing.quote", "acme.domain"));
1259        assert!(scope_matches("com.acme.domain.Pricing.quote", "acme::domain"));
1260        assert!(scope_matches("com.acme.infra.Net.fetch", "infra.Net"));
1261        assert!(!scope_matches("com.acme.subdomain.h", "domain"));
1262        assert!(!scope_matches("com.acme.domain.h", "infra"));
1263    }
1264
1265    #[test]
1266    fn fs_path_covered_respects_boundaries() {
1267        assert!(fs_path_covered("/etc/app", "/etc/app"));
1268        assert!(fs_path_covered("/etc/app", "/etc/app/cfg.toml"));
1269        assert!(fs_path_covered("/etc/app/", "/etc/app/cfg"));
1270        assert!(!fs_path_covered("/etc/app", "/etc/apppwned"));
1271        assert!(!fs_path_covered("/etc/app", "/etc/application/x"));
1272        assert!(!fs_path_covered("/etc/app/cfg", "/etc/app"));
1273        assert!(!fs_path_covered("/etc/app", "/etc/app/../passwd"));
1274        assert!(fs_path_covered("/", "/etc/app/x"));
1275        assert!(!fs_path_covered("etc/app", "/etc/app/cfg"));
1276        assert!(!fs_path_covered("/etc/app", "etc/app/cfg"));
1277        assert!(fs_path_covered("etc/app", "etc/app/cfg"));
1278    }
1279
1280    /// ⟨0.24⟩ THE PROVABLE-PURITY DISCLOSURE MUST ASK THE GATE WHAT "PASSES" MEANS — SPEC §6.2, and both
1281    /// directions in ONE test, because killing an over-charge is exactly where a silent under-report gets
1282    /// introduced and the fixture proving the fabrication is closed cannot show the reach closed with it.
1283    ///
1284    /// A hole is a function that PASSES its rule while `Unknown`. `unverified_hole_rule` used to compute
1285    /// PASSES from `r.effects` alone — the pre-⟨0.19⟩ question, asked after two rungs gave rules a
1286    /// NARROWING FILTER — so a rule the gate TOLERATES was read here as violated and the hole was DELETED
1287    /// from the disclosure. MEASURED 2026-07-28: `deny Unknown[reflect]` over an `indirect` hole → gate
1288    /// exit 0, `unverified` "every function in a pure/deny layer is PROVABLY clean ✓".
1289    ///
1290    /// ROW 1 (the fix) — the filter does NOT match, so the gate tolerates and this IS a hole.
1291    /// ROW 2 (the mirror) — the SAME rule, SAME function, filter spelled to MATCH: the gate fires, so it
1292    /// is a violation and NOT a hole. Without row 2 the fix is satisfied by a predicate that calls
1293    /// everything a hole, which is the mirror over-report of the thing being fixed.
1294    /// ROW 3 — the ⟨0.20⟩ `Net[dest…]` filter, the same shape on the other narrowing axis.
1295    /// ROW 4 — no filter at all: byte-identical to pre-⟨0.24⟩, which is what keeps conformance PARTs
1296    /// 12c/12d (four-way) from moving.
1297    #[test]
1298    fn a_narrowed_rule_the_gate_tolerates_is_a_hole_and_the_one_it_fires_on_is_not() {
1299        let effs = ["Unknown"];
1300        let indirect: BTreeSet<String> = ["indirect".to_string()].into_iter().collect();
1301        let hole = |src: &str, classes: Option<&BTreeSet<String>>, nets: &[String]| -> Option<String> {
1302            let p = parse_policy(src);
1303            unverified_hole_rule("app::go", &effs, classes, nets, &p.rules).map(|r| rule_and_upgrade(r).1)
1304        };
1305
1306        // ROW 1 — tolerated by the gate (indirect ∉ {reflect}) ⇒ a hole, and the upgrade WIDENS the
1307        // filter rather than appending a second `Unknown`.
1308        assert_eq!(
1309            hole("deny Unknown[reflect]\n", Some(&indirect), &[]).as_deref(),
1310            Some("deny Unknown"),
1311            "a rule the gate TOLERATES leaves the function unproven — that is the disclosure's whole subject"
1312        );
1313
1314        // ROW 2 — THE MIRROR. Same rule, same signature, filter spelled to match: the gate FIRES, so this
1315        // is a violation and the disclosure must stay silent about it.
1316        assert_eq!(
1317            hole("deny Unknown[indirect]\n", Some(&indirect), &[]),
1318            None,
1319            "a rule the gate FIRES on is a violation, not a hole — filter-awareness must not start \
1320             disclosing the gate's own findings back as unproven passes"
1321        );
1322        assert_eq!(hole("deny Unknown[dynamic]\n", Some(&indirect), &[]), None, "`dynamic` covers indirect");
1323
1324        // ROW 3 — the ⟨0.20⟩ destination filter, both ways, on a fn carrying Net BESIDE its Unknown.
1325        let netfn = ["Net".to_string(), "Unknown".to_string()];
1326        let telemetry = vec!["known-telemetry".to_string()];
1327        let p = parse_policy("deny Net[unknown-host]\n");
1328        assert_eq!(
1329            unverified_hole_rule("app::go", &netfn, Some(&indirect), &telemetry, &p.rules)
1330                .map(|r| rule_and_upgrade(r).1)
1331                .as_deref(),
1332            Some("deny Net[unknown-host] Unknown"),
1333            "a `Net[dest…]` the fn's destinations do not match is tolerated, so the Unknown beside it is a hole"
1334        );
1335        let p = parse_policy("deny Net[known-telemetry]\n");
1336        assert_eq!(
1337            unverified_hole_rule("app::go", &netfn, Some(&indirect), &telemetry, &p.rules).map(|r| r.raw.clone()),
1338            None,
1339            "MIRROR: the matching destination filter FIRES, so it is a violation and not a hole"
1340        );
1341
1342        // ROW 4 — UNFILTERED, unchanged. `deny Unknown` fires on every Unknown (never a hole); `pure` and
1343        // `deny Fs` pass a fn with no real effect (always a hole) — the forms PARTs 12c/12d pin four-way.
1344        assert_eq!(hole("deny Unknown\n", Some(&indirect), &[]), None);
1345        assert_eq!(hole("pure\n", Some(&indirect), &[]).as_deref(), Some("deny Unknown"));
1346        assert_eq!(hole("deny Net Db  domain\ndeny Fs\n", Some(&indirect), &[]).as_deref(), Some("deny Fs Unknown"));
1347        assert_eq!(
1348            hole("deny Net Db  go\n", Some(&indirect), &[]).as_deref(),
1349            Some("deny Db Net Unknown go"),
1350            "the sorted multi-effect upgrade PART 12c-deny pins in all four engines"
1351        );
1352
1353        // A WITHHELD filter — no class set to read — counts as PASSING, so the hole is disclosed rather
1354        // than dropped. The gate withholds there too; between an advisory note that speaks and one that
1355        // goes quiet over a rule that never ran, only the first stays true.
1356        assert_eq!(hole("deny Unknown[reflect]\n", None, &[]).as_deref(), Some("deny Unknown"));
1357    }
1358}
1359
1360// ── ⟨0.27⟩ SPEC §3.4 `engine` — the engine↔baseline coupling ─────────────────────────────────────
1361/// What an `engine` pin says about the build that is running. Data, not a print-and-exit, so every
1362/// branch is testable — including the two that MUST NOT change the exit code.
1363#[derive(Debug, PartialEq, Eq)]
1364pub enum PinVerdict {
1365    /// No pin, or a pin qualified for another implementation. Today's behaviour, exactly.
1366    Absent,
1367    Match,
1368    /// A different version — the engine↔baseline coupling is broken. Exit 2 (UNEVALUABLE, never 1).
1369    Mismatch,
1370    /// Present but unreadable (`engine latest`, a bare `engine`, trailing junk). Exit 2: a pin that
1371    /// cannot be read is a guard the operator believes is on. This is the one place §6.2's
1372    /// warn-and-skip posture INVERTS — skipping a key that ADDS something costs that key; skipping a
1373    /// PIN costs the guard.
1374    Malformed,
1375    /// Well-formed, and this build cannot state its own release. UNANSWERABLE — §3.1's rule applies:
1376    /// disclosed, never scored, INCLUDING as satisfied.
1377    Undetermined,
1378}
1379
1380/// The pin that applies to `impl_name` — the qualified form wins over the unqualified one, and the
1381/// LAST occurrence wins (matching candor-java's map semantics). Two lines that DISAGREE about the same
1382/// key return a value that cannot parse, so they surface as [`PinVerdict::Malformed`] rather than one
1383/// silently discarding the other: two lines disagreeing about which engine to run is not a preference
1384/// to resolve, it is a question the config leaves unanswered.
1385pub fn engine_pin_for(text: &str, impl_name: &str) -> Option<String> {
1386    const IMPLS: [&str; 5] = ["java", "rust", "ts", "swift", "agents"];
1387    let (mut wild, mut qual): (Option<String>, Option<String>) = (None, None);
1388    let mut bad = false;
1389    for raw in text.lines() {
1390        let line = raw.split('#').next().unwrap_or("").trim();
1391        if line.is_empty() {
1392            continue;
1393        }
1394        let mut it = line.split_whitespace();
1395        if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("engine")) {
1396            continue;
1397        }
1398        let rest: Vec<&str> = it.collect();
1399        let slot = |cur: &mut Option<String>, v: String| {
1400            if cur.as_ref().is_some_and(|p| *p != v) {
1401                *cur = Some(format!("{} / {v}", cur.as_ref().unwrap()));
1402            } else {
1403                *cur = Some(v);
1404            }
1405        };
1406        // A KNOWN QUALIFIER DECIDES OWNERSHIP BEFORE ARITY. Checking the one-token case first made `engine swift` a WILDCARD pin whose version is the literal "swift" -> MALFORMED -> exit 2 in every engine, so one operator forgetting a version on a qualified line killed the whole family. SPEC 3.4 says the skip is whole-line 'whatever follows it' -- and nothing following it is a case of that too.
1407        if let Some(head) = rest.first() {
1408            if IMPLS.contains(&head.to_ascii_lowercase().as_str()) {
1409                if head.eq_ignore_ascii_case(impl_name) {
1410                    if rest.len() == 2 { slot(&mut qual, rest[1].to_string()); } else { bad = true; }
1411                }
1412                continue;                                     // another impl's line, whatever follows it
1413            }
1414        }
1415        match rest.len() {
1416            0 => bad = true,                                  // a bare `engine` line
1417            1 => slot(&mut wild, rest[0].to_string()),        // engine <version>
1418            _ => bad = true,                                  // trailing junk / unknown qualifier
1419        }
1420    }
1421    if bad {
1422        return Some("<unreadable>".to_string());
1423    }
1424    // AN UNREADABLE UNQUALIFIED LINE IS NOT HIDDEN BY A QUALIFIED PIN. `qual ?? wild` returned the qua
1425    // lified value, so `engine garbage` beside a good qualified line passed SILENTLY here while candor-java ex
1426    // ited 2 — the exact mirror of the bug just fixed in java, four engines the other way. Unreadability is a property of the LINE; precedence only decides which VERSION applies.
1427    if let Some(w) = &wild {
1428        if normalize_version(w).is_none() { return Some(w.clone()); }
1429    }
1430    qual.or(wild)
1431}
1432
1433/// [`PinVerdict`] for `pin` against `running`. Pure: no printing, no exit.
1434pub fn pin_verdict(pin: Option<&str>, running: &str) -> PinVerdict {
1435    let Some(pin) = pin else { return PinVerdict::Absent };
1436    let Some(want) = normalize_version(pin) else { return PinVerdict::Malformed };
1437    if running.trim().is_empty() || running == "unknown" {
1438        return PinVerdict::Undetermined;
1439    }
1440    if want == normalize_version(running).unwrap_or_else(|| running.trim().to_string()) {
1441        PinVerdict::Match
1442    } else {
1443        PinVerdict::Mismatch
1444    }
1445}
1446
1447/// A pin token → its comparable form, or None when it is not a version at all. A leading `v` is
1448/// optional (the GitHub-tag `v0.27.0` and the crate `0.27.0` are the same pin) and a two-part `0.27`
1449/// means `0.27.0`. Anything else — `latest`, a branch name — is MALFORMED rather than a version that
1450/// can never match: the difference decides whether the operator reads "wrong version" or "that is not
1451/// a version".
1452fn normalize_version(raw: &str) -> Option<String> {
1453    let s = raw.trim().strip_prefix(['v', 'V']).unwrap_or_else(|| raw.trim());
1454    let parts: Vec<&str> = s.split('.').collect();
1455    if !(parts.len() == 2 || parts.len() == 3) || !parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) {
1456        return None;
1457    }
1458    Some(if parts.len() == 2 { format!("{s}.0") } else { s.to_string() })
1459}