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/// SPEC §4 ⟨0.7⟩'s CLOSED FIVE-KIND `unknownWhy` VOCABULARY, as a TABLE — and the single place this
18/// engine SPELLS a reason, not merely the single place it reads one.
19///
20/// SOUNDNESS R490. `ReasonClass::classify` below has carried the note "THIS IS THE ONLY PLACE THIS
21/// ENGINE HOLDS SPEC §4's KIND VOCABULARY" since ⟨0.24⟩, and it was true of the READER and false of the
22/// WRITERS: the nightly dylint lint at the repo root is a SECOND PRODUCER publishing into
23/// `.candor/baseline.candor.Cdylib.json`, and it had drifted in three kinds (`generic-iter:`,
24/// `iter-combinator:`, `deref:`) and two details. That is the hazard `classify`'s own comment describes,
25/// one repo over and in the direction it was not looking.
26///
27/// SO THIS TABLE IS WHAT BOTH HALVES READ. `classify` matches on `Kind::token()` rather than on its own
28/// copy of the five strings, so adding, renaming or removing a kind moves the classifier and the
29/// producers in the same edit — the JVM engine's failure (a correct `classify` beside a typed `Kind`
30/// enum missing `ambiguous`, one token with two answers inside one engine) is not reachable from here.
31///
32/// It is NOT a closed set for PARSING. §2 forward-compatibility lets a producer emit a kind this
33/// version has never heard of, and `classify`'s catch-all is what keeps such a kind inside
34/// `Unknown[*]` / `Unknown[dynamic]`. This type constrains what THIS ENGINE WRITES.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
36pub enum Kind {
37    /// invocation chosen at runtime by name/metadata — reflection, `Method.invoke`, `eval`
38    Reflect,
39    /// a boundary to code the engine cannot analyse — native methods, FFI/`extern`, intrinsics
40    Native,
41    /// an unresolved virtual / interface / protocol dispatch with a resolvable owner type + member
42    Dispatch,
43    /// an unresolved higher-order / owner-less invocation over a function/closure VALUE — §4 names the
44    /// shapes: param, field, bound, computed, opaque-iterable
45    Callback,
46    /// ⟨0.24⟩ the analyser's OWN name resolution was ambiguous — two or more separately-written
47    /// definitions competing for one name, so no owner could be formed at all
48    Ambiguous,
49}
50
51impl Kind {
52    /// The §4 `kind` token — the part before the first `:`, and the part every gate reads.
53    pub fn token(self) -> &'static str {
54        match self {
55            Kind::Reflect => "reflect",
56            Kind::Native => "native",
57            Kind::Dispatch => "dispatch",
58            Kind::Callback => "callback",
59            Kind::Ambiguous => "ambiguous",
60        }
61    }
62
63    /// The five, in a form a census can iterate. `classify` and the source-hygiene census both read
64    /// THIS, so neither can hold its own list.
65    pub const ALL: [Kind; 5] = [Kind::Reflect, Kind::Native, Kind::Dispatch, Kind::Callback, Kind::Ambiguous];
66
67    /// SPEC §6.2's projection of this kind onto a policy CLASS. `ambiguous` projects to `dispatch`:
68    /// §6.2's table has named `ambiguous*` since ⟨0.19⟩, and reclassifying it to `indirect` was measured
69    /// to take `deny E Unknown[dispatch]` from 58 of 200 crates to 0 of 200.
70    pub fn class(self) -> ReasonClass {
71        match self {
72            Kind::Reflect => ReasonClass::Reflect,
73            Kind::Native => ReasonClass::Native,
74            Kind::Dispatch | Kind::Ambiguous => ReasonClass::Dispatch,
75            Kind::Callback => ReasonClass::Indirect,
76        }
77    }
78
79    /// Spell a §4 reason: `kind:detail`. The detail is best-effort for every kind EXCEPT `dispatch:`
80    /// with an owner — use [`Kind::dispatch_on`] there, which is the normative shape.
81    ///
82    /// ⟨0.24⟩ A DOT-FREE `dispatch:` detail is not a defect: it is the RESERVED form for "no owner could
83    /// be formed at all", free text, explicitly not conformance-compared. That is why this constructor
84    /// accepts one rather than forcing every caller through `dispatch_on`.
85    pub fn reason(self, detail: &str) -> String {
86        format!("{}:{}", self.token(), detail)
87    }
88
89    /// `dispatch:<owner-type>.<member>` — §4's ONE normative detail, and the shape §3.1's dispatch
90    /// frontier parses (`possibleViaUnknownDispatch` keys on the dot). The owner is passed as the type's
91    /// own name, never as a language path: `Store.put`, not `p::Store::put`.
92    pub fn dispatch_on(owner: &str, member: &str) -> String {
93        format!("{}:{owner}.{member}", Kind::Dispatch.token())
94    }
95}
96
97/// The NORMATIVE projection of a raw `unknown_why` reason onto a fixed, cross-engine reason CLASS
98/// (candor-spec REASON-SCOPED-UNKNOWN-DESIGN.md §1). Reason-scoped policies (`deny E Unknown[class]`)
99/// quantify over these classes, so the mapping MUST be identical in every engine — this mirrors the
100/// java reference `ReasonClass` (its `classify(String)` path, since rust emits raw string reasons). The
101/// class set is CLOSED (six members); a raw reason matching no pinned prefix maps to `Unresolved` —
102/// conservative: it stays in scope of any `Unknown[*]` / `Unknown[dynamic]` policy, never silently
103/// tolerated.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
105pub enum ReasonClass {
106    /// reflection / metaprogramming
107    Reflect,
108    /// unresolved virtual/dynamic dispatch, same-name ambiguity, invokedynamic
109    Dispatch,
110    /// callback / closure / function-value / async-continuation indirection
111    Indirect,
112    /// FFI / native boundary
113    Native,
114    /// generic unresolvable call/import, AND the catch-all for any unrecognized raw reason
115    Unresolved,
116    /// analysis not wired up (fixable, not a real dynamic hole): missing-config / no-tsconfig
117    Setup,
118}
119
120impl ReasonClass {
121    /// The lowercase policy-facing token (`deny E Unknown[<token>]`).
122    pub fn token(self) -> &'static str {
123        match self {
124            ReasonClass::Reflect => "reflect",
125            ReasonClass::Dispatch => "dispatch",
126            ReasonClass::Indirect => "indirect",
127            ReasonClass::Native => "native",
128            ReasonClass::Unresolved => "unresolved",
129            ReasonClass::Setup => "setup",
130        }
131    }
132
133    /// Parse a policy-facing token back to a class; `None` if it names no class.
134    pub fn from_token(t: &str) -> Option<ReasonClass> {
135        Some(match t {
136            "reflect" => ReasonClass::Reflect,
137            "dispatch" => ReasonClass::Dispatch,
138            "indirect" => ReasonClass::Indirect,
139            "native" => ReasonClass::Native,
140            "unresolved" => ReasonClass::Unresolved,
141            "setup" => ReasonClass::Setup,
142            _ => return None,
143        })
144    }
145
146    /// Map a raw `unknown_why` reason to its normative class — prefix-based (raw reasons carry a
147    /// `kind:detail` shape, e.g. `dispatch:foo::Bar`), unrecognized → `Unresolved`. Byte-identical
148    /// intent to the java `ReasonClass.classify(String)`.
149    ///
150    /// ⟨0.24⟩ THIS IS THE ONLY PLACE THIS ENGINE HOLDS SPEC §4's KIND VOCABULARY. Every other reference
151    /// to a kind is either a raw string being emitted or the `dispatch:` prefix test in candor-query's
152    /// dispatch frontier; there is no typed kind enum here. §4's "AN ENGINE HOLDS THIS VOCABULARY TWICE,
153    /// AND THE HALVES DRIFT" paragraph records the JVM engine classifying `ambiguous` correctly HERE
154    /// while its typed `Kind` enum lacked the kind entirely — one token, two answers, inside one engine,
155    /// concealed precisely because this half was right. Holding it once is why that is not reachable in
156    /// this engine; a future typed representation must be added at the same commit as its control
157    /// (`off_vocabulary_kinds_round_trip_and_classify_through_the_catch_all`).
158    ///
159    /// The five §4 kinds are `reflect`/`native`/`dispatch`/`callback`/`ambiguous`. `ambiguous` maps to
160    /// `dispatch` and rust is its only PRODUCER; `indy`/`task-handoff` are candor-java's migration kinds
161    /// and `dep:`/`dep-stale:` are swift's registered per-dependency-ENTRY kinds, reaching `Unresolved`
162    /// through the catch-all, which is the class §6.2 prescribes for them.
163    ///
164    /// ⟨0.35⟩ **AND THIS ENGINE PRODUCES A SIXTH SPELLING OF ITS OWN, `macro:`, WHICH THE PARAGRAPH
165    /// ABOVE DID NOT NAME UNTIL SOUNDNESS R270.** It is off-vocabulary as a §4 kind — legal under §2
166    /// forward-compatibility, round-tripped verbatim, and reaching `Unresolved` through the catch-all
167    /// below, deliberately: it marks the ZERO-READABLE-DEFS case (a macro this engine declined to
168    /// expand), which is "a limit of its own resolution rather than an ambiguity in the program" in
169    /// §4 ⟨0.25⟩'s words, and `dispatch` is the wrong class for that. Four sites emit it, and they are
170    /// listed here rather than left to a grep because the whole hazard this doc comment exists for is a
171    /// vocabulary held in one place going stale while the code moves:
172    ///
173    ///   * `collector.rs` `macro:unexpanded multi-arm macro_rules! <name>`   (R257)
174    ///   * `collector.rs` `macro:unreadable macro_rules! template <name>`    (R257)
175    ///   * `collector.rs` `macro:re-export key a macro-hidden module could also own`  (R270)
176    ///   * `scan.rs`      `macro:module items hidden by an unexpanded macro`  (R270, R128's site)
177    ///
178    /// R257 minted the spelling at exactly the two lines it was reported for and this comment kept
179    /// asserting the file held the vocabulary once; R270 is the sweep, and the census that justified it
180    /// enumerates every `ambiguous:`-emitting site rather than the ones in hand. The six that REMAIN
181    /// `ambiguous:` are each genuinely two-separately-written-definitions — including
182    /// `ambiguous:same-name macro_rules! definitions`, which a sweep keyed on the WORD "macro" would
183    /// have re-kinded wrongly and cost 15 crates their `deny Unknown[dispatch]` gate. The kind is
184    /// decided by the CONDITION (two readable defs vs none), never by the name.
185    ///
186    /// A dedicated §4 kind for this state is a SPEC clause plus a conformance PART before any engine
187    /// emits it, and candor-rust does not own that file — filed, not invented here (SOUNDNESS R489).
188    /// And the choice is not free: NONE of the five canonical kinds projects to `unresolved`, so mapping
189    /// `macro:` onto any of them MOVES its class. R270 priced that in both directions and it is the
190    /// measurement that keeps the kind where it is.
191    ///
192    /// ⟨R490⟩ **AND THE PARAGRAPH ABOVE WAS STILL COUNTING ONLY THE SPELLINGS IN THIS CRATE.** The
193    /// nightly dylint lint at the repo root is a SECOND PRODUCER, and it held three more kinds outside
194    /// §4's five (`generic-iter:`, `iter-combinator:`, `deref:`) plus two `dispatch:` details spelled as
195    /// rust PATHS. It now builds every reason through `Kind` above, and
196    /// `candor-scan/tests/source_hygiene.rs` asserts it spells none of its own.
197    pub fn classify(why: &str) -> ReasonClass {
198        let w = why.trim().to_ascii_lowercase();
199        // THE FIVE §4 KINDS COME FROM `Kind::ALL`, NOT FROM A SECOND COPY OF THE FIVE STRINGS
200        // (SOUNDNESS R490). Every other arm below is an ALIAS this engine accepts from a sibling
201        // producer — swift's `closure`/`dynamicmemberlookup`, java's `indy`/`task-handoff` migration
202        // kinds, ts's `missing-config`/`no-tsconfig`/`no-node_modules` setup kinds — and each is
203        // deliberately spelled here and nowhere else, because they are things this engine READS and
204        // never WRITES. The canonical five are checked FIRST so an alias can never shadow one.
205        if let Some(k) = Kind::ALL.into_iter().find(|k| w.starts_with(k.token())) {
206            return k.class();
207        }
208        if w == "dynamicmemberlookup" {
209            ReasonClass::Reflect
210        } else if w.starts_with("closure") || w.starts_with("task-handoff") {
211            ReasonClass::Indirect
212        } else if w.starts_with("indy") {
213            ReasonClass::Dispatch
214        } else if w.starts_with("missing-config") || w.starts_with("no-tsconfig") || w.starts_with("no-node_modules") {
215            ReasonClass::Setup
216        } else {
217            ReasonClass::Unresolved
218        }
219    }
220
221    /// The `dynamic` alias — every GENUINE blind-spot class (excludes `setup`), incl. `unresolved` (the
222    /// catch-all) so `Unknown[dynamic]` never under-gates. The design's recommended usable strict gate.
223    pub fn dynamic_set() -> BTreeSet<ReasonClass> {
224        [
225            ReasonClass::Reflect,
226            ReasonClass::Dispatch,
227            ReasonClass::Indirect,
228            ReasonClass::Native,
229            ReasonClass::Unresolved,
230        ]
231        .into_iter()
232        .collect()
233    }
234}
235
236/// SPEC §6.2 ⟨0.24⟩ — does a function's TRANSITIVE reason-class set intersect `want` (class tokens)?
237///
238/// THE `None`/EMPTY ARM IS THE FAIL-CLOSED NET, and it is why this lives here rather than being
239/// open-coded twice. §6.2: "a function whose `Unknown` carries no recorded reason CONTRIBUTES
240/// `unresolved` to its class set — so a narrowed filter never *silently* tolerates a hole it failed to
241/// classify." Read the other way round, `!contains ⇒ exclude` over an empty set drops the entry from
242/// EVERY filter including one naming its own class: a silent under-report wearing a filter.
243///
244/// `classes` is the ACCUMULATED (post-`propagate_str`) set, never the direct `unknownWhy`: a reason
245/// names a site in the function's OWN body (§4), so a function whose `Unknown` is purely inherited
246/// carries none, and matching against the direct field answers a different question. SHARED by the
247/// `deny E Unknown[class]` gate (candor-scan) and `unverified --class` (candor-query) so a gate and the
248/// disclosure explaining it cannot disagree about which holes a class names.
249///
250/// The empty arm is a NET, not a route: it keys on the ABSENCE of a class set, so any other reason on
251/// the same function hides whatever it was covering. The reasonless case that CAN co-occur with a
252/// reason — a direct `Unknown` the unit did not name — must therefore contribute `unresolved` into the
253/// DIRECT map before propagation (candor-scan's `unknown_via_dep`, candor-query's report-side signature),
254/// not arrive here by absence.
255pub fn reason_class_matches(classes: Option<&BTreeSet<String>>, want: &BTreeSet<&str>) -> bool {
256    match classes {
257        None => want.contains(ReasonClass::Unresolved.token()),
258        Some(cs) if cs.is_empty() => want.contains(ReasonClass::Unresolved.token()),
259        Some(cs) => cs.iter().any(|t| want.contains(t.as_str())),
260    }
261}
262
263/// Parse `unknown-alias <name> = <class,…>` lines from `.candor/config` text (⟨0.19⟩, SPEC §6.2) into a
264/// name→classes map. A name that shadows a built-in (`*`/`dynamic`/a class token) is warned-and-skipped (a
265/// config alias may not redefine a built-in), as is a definition naming no valid class. Byte-shape with the
266/// java reference `Config.addAlias`.
267pub fn parse_unknown_aliases(config_text: &str) -> std::collections::BTreeMap<String, BTreeSet<ReasonClass>> {
268    let mut out = std::collections::BTreeMap::new();
269    for raw in config_text.lines() {
270        let line = raw.split('#').next().unwrap_or("").trim();
271        if line.is_empty() {
272            continue;
273        }
274        let mut it = line.splitn(2, char::is_whitespace);
275        // Case-INSENSITIVE key match, like the config loaders in java/ts/swift (which lowercase the key) —
276        // a case-sensitive match here made `Unknown-Alias …` define an alias everywhere BUT rust (a four-way
277        // parse divergence; caught in review). The rest of the line (name + classes) stays case-sensitive.
278        if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("unknown-alias")) {
279            continue;
280        }
281        let val = it.next().unwrap_or("").trim();
282        let Some((name, classes)) = val.split_once('=') else {
283            eprintln!("candor: ignoring `unknown-alias` (want `unknown-alias <name> = <class,…>`): {val}");
284            continue;
285        };
286        let name = name.trim();
287        if name.is_empty() || name == "*" || name == "dynamic" || ReasonClass::from_token(name).is_some() {
288            eprintln!("candor: ignoring `unknown-alias` with reserved/empty name `{name}` (may not shadow `*`/`dynamic`/a class token)");
289            continue;
290        }
291        let mut set = BTreeSet::new();
292        let mut bad: Vec<&str> = Vec::new();
293        for cn in classes.split(',') {
294            let cn = cn.trim();
295            if cn.is_empty() {
296                continue;
297            }
298            if cn == "dynamic" {
299                set.extend(ReasonClass::dynamic_set());
300            } else if let Some(rc) = ReasonClass::from_token(cn) {
301                set.insert(rc);
302            } else {
303                bad.push(cn);
304            }
305        }
306        // ⟨0.24⟩ **AN UNRECOGNISED TOKEN REFUSES THE WHOLE DEFINITION** — SPEC §6.2 `be0b9a9`: the rule
307        // binds every policy value list, and *"the second is the sharper one: the typo is in the
308        // vocabulary the policy is written against rather than in the policy itself, and it fails open
309        // identically."*
310        //
311        // MEASURED: `unknown-alias corp = dispatch,nativ` → the DEFINITION silently became `{dispatch}`,
312        // so `deny Unknown[corp]` exited 0 over a native-caused hole that `= dispatch,native` catches.
313        // The alias resolved, `used_aliases` recorded it, the verdict named the config — every disclosure
314        // fired correctly ABOUT A DEFINITION THAT WAS NOT THE ONE ON DISK.
315        //
316        // REFUSING THE DEFINITION rather than minting a new error channel is what makes this fit: an
317        // alias that does not exist is one the policy's own `Unknown[<name>]` cannot resolve, so it lands
318        // on the `errors` path already there and the gate routes refuse with exit 2 — naming the token
319        // AND the accepted set, as §6.2 requires. It also keeps the blast radius honest: a config
320        // defining ten aliases, one of them typo'd and NONE of them mentioned by this policy, changed
321        // nothing, and turning that into a red gate would be the mirror over-reach. The refusal is
322        // triggered by USE, exactly like `used_aliases` (recorded at the point of use, for the same
323        // reason).
324        if !bad.is_empty() {
325            eprintln!(
326                "candor: REFUSING `unknown-alias {name}` — it names unrecognised reason-class(es) `{}` \
327                 (accepted: reflect, dispatch, indirect, native, unresolved, setup, plus `dynamic`). The \
328                 definition is refused WHOLE rather than narrowed to the tokens that parsed: keeping the \
329                 rest would silently redefine `{name}` as something narrower than the config says, and a \
330                 policy using it would gate less than it reads. `{name}` is now undefined, so a policy \
331                 naming it is a policy error (exit 2).",
332                bad.join("`, `")
333            );
334        } else if set.is_empty() {
335            eprintln!("candor: ignoring `unknown-alias {name}` — no valid reason-class");
336        } else {
337            out.insert(name.to_string(), set);
338        }
339    }
340    out
341}
342
343/// ⟨0.20⟩ Parse `net-partner <host>` lines from `.candor/config` (NET-DESTINATION-CLASS-DESIGN.md): the
344/// per-project set of business-partner hosts the `Net` destination-class classifier treats as
345/// `known-partner`. Multi-value (repeatable key); the value is host-normalized (`:port` stripped,
346/// lowercased) like `MODEL_HOSTS`. Case-insensitive key match, mirroring `parse_unknown_aliases` + the
347/// java/ts/swift config loaders. A partner is per-project — never a universal list.
348pub fn parse_net_partners(config_text: &str) -> BTreeSet<String> {
349    let mut out = BTreeSet::new();
350    for raw in config_text.lines() {
351        let line = raw.split('#').next().unwrap_or("").trim();
352        if line.is_empty() {
353            continue;
354        }
355        let mut it = line.splitn(2, char::is_whitespace);
356        if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("net-partner")) {
357            continue;
358        }
359        let val = it.next().unwrap_or("").trim();
360        if val.is_empty() {
361            continue;
362        }
363        // ⟨0.29⟩ A MALFORMED VALUE IS DISCLOSED, NOT SILENTLY KEPT AS JUNK. The grammar is
364        // `net-partner <host>`; the `=` spelling an operator reaches for by habit
365        // (`net-partner = partner.example`) parsed as the HOST `"= partner.example"`, which entered the
366        // set and matched nothing for the rest of the run. The direction is SAFE — the gate stays armed,
367        // so nothing is certified that should not be — which is precisely why it sat unnoticed: the
368        // operator believes a partner is declared, the verdict disagrees, and no line connects the two.
369        // ⟨0.28⟩ gave POLICY files an `ignored` block for exactly this; config files had none.
370        if val.contains(char::is_whitespace) || val.starts_with('=') {
371            eprintln!(
372                "candor: net-partner takes a bare host — `net-partner <host>`, one per line; \
373                 '{val}' is not one and was IGNORED (an '=' or extra words is the usual cause) — {}",
374                raw.trim()
375            );
376            continue;
377        }
378        out.insert(host_part(val).to_ascii_lowercase());
379    }
380    out
381}
382
383/// Discover `.candor/config` text for a policy/scan anchored at `start`: `$CANDOR_CONFIG` if set + readable,
384/// else the nearest `.candor/config` walking UP from `start`, else `None`. Read-only + lenient (no
385/// process-exit — the caller decides fail-closed); used to resolve `unknown-alias` for the §6.2 gate +
386/// `parsepolicy` so both reflect the same checked-in config.
387pub fn discover_config_text(start: &std::path::Path) -> Option<String> {
388    discover_config(start).map(|(_, t)| t)
389}
390
391/// THE RUNNING BINARY'S REFUSAL WRITER, registered by whichever entry armed a sink.
392///
393/// (These paragraphs once sat ABOVE this static while documenting `discover_config`, which is below it —
394/// so rustdoc rendered that function's path/canonicalization rationale as a description of this hook.
395/// They now live on the item they describe: a doc block belongs to the next item, and separating it with
396/// a blank line is not a fix — clippy's `empty_line_after_doc_comments` rejects that, and CI said so.)
397///
398/// [`discover_config`] is SHARED and sits BELOW every gate sink, so its `exit(2)` for an unreadable
399/// config could not write the refusal document `--gate-json` was promised. Measured: on the `gate`
400/// verb route an unreadable `CANDOR_CONFIG` exited 2 with an EMPTY stream in candor-scan and
401/// candor-ts while candor-java and candor-swift wrote the refusal. The FILE sink was covered — the
402/// armed placeholder survives an exit that writes nothing — so only the stream, which cannot be
403/// pre-armed, was exposed.
404///
405/// NOT registered at startup: `set_refusal_sink` is called by the gate entries that arm a sink, so a
406/// process that never arms one still exits 2 plainly. The comment inside `discover_config` already
407/// records this cause being fixed once, for the EXIT
408/// CODE: the scan route refused and the query route did not. That fix stopped at the exit code and
409/// left the machine channel, which is exactly the split conformance PART 35 and PART 36 exist to
410/// keep apart. A hook rather than a Result because every caller of this function wants the same
411/// answer — refuse through whatever sink this process armed — and threading a new error type through
412/// all of them would create the second copy of a rule that this project keeps getting bitten by.
413static REFUSAL_SINK: std::sync::OnceLock<fn(&str) -> !> = std::sync::OnceLock::new();
414
415/// Register the process's refusal writer. Idempotent; the first registration wins.
416pub fn set_refusal_sink(f: fn(&str) -> !) {
417    let _ = REFUSAL_SINK.set(f);
418}
419
420/// Exit 2 through the registered sink when there is one, and plainly when there is not — a library
421/// consumer that never armed a sink must still get the documented exit code.
422fn refuse_unevaluable(reason: &str) -> ! {
423    if let Some(f) = REFUSAL_SINK.get() {
424        f(reason)
425    }
426    std::process::exit(2)
427}
428
429/// ⟨0.24⟩ As [`discover_config_text`], but ALSO the PATH the text came from, canonicalized.
430///
431/// **WHY THE PATH IS NOW LOAD-BEARING** (SPEC §3.1): a `.candor/config` supplying `unknown-alias`
432/// vocabulary can move a verdict 0→1, and discovery walks PARENT DIRECTORIES, so a file anywhere above
433/// the policy participates — ambient, and until now invisible in the output. *"A verdict changed by a
434/// file the operator cannot see named in the output is the ambient-input failure this whole format
435/// exists to refuse; the remedy is the same one used everywhere else here — not to forbid the input, but
436/// to make it impossible for it to act unnamed."* So the gate document NAMES it, and the path has to
437/// travel out of discovery for that to be possible.
438///
439/// CANONICALIZED because the two routes reach the same file from different working directories, and
440/// §3.1's byte-equality MUST is about the DOCUMENT: a relative path would differ between them for no
441/// reason other than where each was invoked.
442pub fn discover_config(start: &std::path::Path) -> Option<(std::path::PathBuf, String)> {
443    let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
444    // CONFIGURED-BUT-UNUSABLE FAILS LOUD, ON THIS ROUTE TOO. `.ok()` turned an unreadable config into
445    // "no config", so the run continued WITHOUT whatever it declared — a policy, a baseline, an engine
446    // pin, an `unknown-alias` vocabulary. The SCAN route already refuses; this QUERY route did not, so
447    // `gate --report R --policy P` with a broken CANDOR_CONFIG exited 1 here and 2 in java and ts on the
448    // same input. §3.4's posture does not vary by verb.
449    if let Ok(p) = std::env::var("CANDOR_CONFIG") {
450        let p = std::path::PathBuf::from(p);
451        match std::fs::read_to_string(&p) {
452            Ok(t) => return Some((canon(&p), t)),
453            Err(e) => {
454                eprintln!("candor: CANDOR_CONFIG set but {} could not be read ({e}) — failing (exit 2,", p.display());
455                eprintln!("        unevaluable). A config that cannot be read is a guard the operator believes is on.");
456                refuse_unevaluable(&format!("CANDOR_CONFIG set but {} could not be read ({e})", p.display()));
457            }
458        }
459    }
460    let start = canon(start);
461    let mut cur = if start.is_dir() { Some(start.as_path()) } else { start.parent() };
462    while let Some(d) = cur {
463        let cand = d.join(".candor/config");
464        if cand.is_file() {
465            match std::fs::read_to_string(&cand) {
466                Ok(t) => return Some((canon(&cand), t)),
467                Err(e) => {
468                    eprintln!("candor: {} exists but could not be read ({e}) — failing (exit 2,", cand.display());
469                    eprintln!("        unevaluable). Treating it as absent would run without what it declares.");
470                    refuse_unevaluable(&format!("{} exists but could not be read ({e})", cand.display()));
471                }
472            }
473        }
474        cur = d.parent();
475    }
476    None
477}
478
479/// One `deny <Effect…> [scope]` / `pure <scope>` rule (AS-EFF-006). `effects` empty ⇒ a `pure` rule
480/// (ANY effect forbidden). `scope` is a path segment-scope the rule applies to (None = whole unit).
481#[derive(Debug, Clone)]
482pub struct PolicyRule {
483    pub effects: BTreeSet<&'static str>,
484    pub scope: Option<String>,
485    /// Reason-class filter on an `Unknown` membership (REASON-SCOPED-UNKNOWN-DESIGN.md): empty ⇒
486    /// `Unknown[*]` (any reason — the bare form); non-empty ⇒ the Unknown hit fires ONLY for a fn whose
487    /// (transitive) reason classes include one of these. Ignored when `effects` doesn't contain `Unknown`.
488    pub unknown_classes: BTreeSet<ReasonClass>,
489    /// Destination-class filter on a `Net` membership (NET-DESTINATION-CLASS-DESIGN.md): empty ⇒ `Net[*]`
490    /// (any destination — the bare form); non-empty ⇒ the Net hit fires ONLY for a fn whose (transitive)
491    /// destination classes include one of these. Ignored when `effects` doesn't contain `Net`.
492    pub net_classes: BTreeSet<String>,
493    pub raw: String,
494}
495
496/// ⟨0.33⟩ ONE `deny`/`pure` RULE IN ITS CANONICAL EXPANDED FORM — the §6.2 spelling of the rule as THE
497/// MATCHER USED it, after alias resolution (`unknown_classes` is already the resolved token set, not the
498/// raw `Unknown[<alias>]` text).
499///
500/// This is what SPEC §2 ⟨0.33⟩'s `scannedUnder.deny` records: the deny set a policy-scanned peek was
501/// BOUNDED BY, so a consumer gating with a different deny set can tell whether the producer was even
502/// asked its question (candor-java's `Policy.canonicalDenyRule` is the reference sibling — this is the
503/// same rendering, ported).
504///
505/// **NOT effect NAMES.** `pure` is a rule with an EMPTY effect set ("every effect except `Unknown`"), so
506/// flattening the rule to a set of names loses it entirely and a flattened STRICTEST policy compares
507/// equal to the EMPTY set — the four-way false all-clear ⟨0.30⟩ closed on the peek itself, one layer in.
508///
509/// **NOT the raw line.** §3.1 already records that alias expansion breaks byte-equality: two configs
510/// defining `unknown-alias corp` DIFFERENTLY give the raw line `deny Unknown[corp]` two meanings, so
511/// comparing raw text would read a producer that asked the WEAKER question as having answered the
512/// stronger one. Recording the EXPANDED, resolved form is the only rendering that is one meaning per
513/// string.
514pub fn canonical_deny_rule(r: &PolicyRule) -> String {
515    let suffix = r.scope.as_deref().map(|s| format!(" {s}")).unwrap_or_default();
516    if r.effects.is_empty() {
517        return format!("pure{suffix}");
518    }
519    // `effects` is a `BTreeSet<&'static str>`, so this iterates in one fixed (alphabetical) order for
520    // any given set — deterministic across calls and across which order the policy TEXT listed them in,
521    // which is what lets `canonical_deny_set` below produce ONE string per rule regardless of how the
522    // operator wrote it.
523    let parts: Vec<String> = r
524        .effects
525        .iter()
526        .map(|&e| {
527            if e == "Unknown" && !r.unknown_classes.is_empty() {
528                let mut toks: Vec<&str> = r.unknown_classes.iter().map(|c| c.token()).collect();
529                toks.sort_unstable();
530                format!("Unknown[{}]", toks.join(","))
531            } else if e == "Net" && !r.net_classes.is_empty() {
532                // `net_classes` is a `BTreeSet<String>`, already code-point sorted.
533                format!("Net[{}]", r.net_classes.iter().cloned().collect::<Vec<_>>().join(","))
534            } else {
535                e.to_string()
536            }
537        })
538        .collect();
539    format!("deny {}{suffix}", parts.join(" "))
540}
541
542/// ⟨0.33⟩ A rule LIST as a canonical SET — [`canonical_deny_rule`] over every entry, deduplicated and
543/// code-point sorted (`BTreeSet<String>`'s own order, the same collation the verdict's `zeroMatch` list
544/// uses), so one policy produces ONE document however its lines were ordered and a consumer's SUBSET
545/// test (SPEC §2 ⟨0.33⟩) is a plain membership test rather than an order-sensitive comparison.
546pub fn canonical_deny_set(rules: &[PolicyRule]) -> Vec<String> {
547    rules.iter().map(canonical_deny_rule).collect::<BTreeSet<String>>().into_iter().collect()
548}
549
550/// One `allow <Effect> [in <scope>] <literal>…` rule (AS-EFF-008). The effect is one of the four
551/// that carry a literal surface (`Net` hosts / `Exec` commands / `Fs` paths / `Db` tables); a
552/// function in `scope` performing it may reach ONLY the listed literals. Matching is
553/// effect-specific (`literal_allowed`).
554#[derive(Debug, Clone)]
555pub struct AllowRule {
556    pub effect: &'static str,
557    pub scope: Option<String>,
558    pub literals: BTreeSet<String>,
559    pub raw: String,
560}
561
562/// One `forbid <A> -> <B>` module-layering rule (AS-EFF-009): a function in scope `A` must not
563/// transitively call into scope `B`.
564#[derive(Debug, Clone)]
565pub struct LayerRule {
566    pub from: String,
567    pub to: String,
568    pub raw: String,
569}
570
571/// ⟨0.29⟩ One `only <A> -> <B> [<C> …]` PERMISSION rule (AS-EFF-011): a function in scope `A` may reach
572/// `A` itself and the listed scopes, and NOTHING else.
573///
574/// **`forbid` FAILS OPEN; `only` FAILS SAFE, and that is the whole reason the form exists.** A dependency
575/// you forgot to prohibit is silently permitted, so "this package is a leaf" can only be spelled by
576/// enumerating what it must not reach — a list that does not cover a package added later, and nothing says
577/// so. That is the allowlist hazard this project refuses everywhere in the analysis, living in the POLICY
578/// LANGUAGE instead. Under `only`, a dependency you forgot to permit is a loud violation.
579///
580/// Found by pointing candor's own architecture gate at candor: the natural
581/// `forbid io.poly.candor.model -> io.poly.candor` SELF-FIRES at 58 violations, because a scope matches a
582/// contiguous run of segments and `model` sits under the very prefix it is trying to protect itself from.
583///
584/// THE WALK STOPS AT A PERMITTED SCOPE, and that is a semantic decision rather than an optimisation: a
585/// permitted callee's own dependencies are governed by the rules about IT, not by this one. Descending
586/// past it would make `only` require the transitive closure of everything you permit — which is the
587/// enumeration-that-rots this form exists to replace, one level down.
588#[derive(Debug, Clone)]
589pub struct OnlyRule {
590    /// The scope being constrained. It may always reach ITSELF: an explicit `A -> A` would be noise, and
591    /// without the implicit permission the form is unusable for exactly the case it exists for.
592    pub from: String,
593    /// The scopes `from` may reach. At least one — `only A ->` with nothing after the arrow is DROPPED as
594    /// malformed rather than read as "A may reach nothing at all", which is a different rule (and one a
595    /// reader is far more likely to have typed by accident than to have meant).
596    pub to: Vec<String>,
597    pub raw: String,
598}
599
600/// ⟨0.24⟩ ONE POLICY LINE THE PARSER DID NOT HONOUR AS WRITTEN (SPEC §3.1 `901f14d` / `195d45a`).
601///
602/// **THE DEFECT.** `parsepolicy` emitted **no `errors` key at all** (measured 2026-07-28 on the
603/// conformance battery: java 10, ts 4, rust 0, swift 0). Every one of these facts existed — they were
604/// printed to stderr as "ignoring policy rule …" — so the verb whose entire purpose is to let a consumer
605/// diff what an engine made of a policy answered the question with the not-honoured half deleted. Worse,
606/// it was INCONSISTENT with this engine's own gate: the gate refuses an unrecognised class token while
607/// the parse narrowed it silently, which is two answers to one question.
608///
609/// **`kind` IS A CLOSED SET, AND IT IS THE SPEC'S, NOT THE REFERENCE ENGINE'S.** `901f14d` pins four
610/// values: `reason-class/alias`, `Net destination-class`, `effect-name`, `rule-kind`. Measured, candor-java
611/// emits `forbid form`, `allow values` and `rule kind` (space, not hyphen) — three values outside the set
612/// and one spelling divergence — and candor-ts renames `kind`→`vocabulary` and `rule`→`where` and emits
613/// `accepted` as a PROSE STRING. This engine follows the clause: a line that names a rule keyword but does
614/// not form that keyword's rule formed no rule kind, so it is `rule-kind`.
615///
616/// `accepted` is an ARRAY OF TOKENS — the tokens that WOULD have been honoured in the position the bad one
617/// occupies. Empty where the position is open-ended (a host, a path), which is a fact about the grammar
618/// rather than a gap in the report.
619#[derive(Debug, Clone)]
620pub struct PolicyError {
621    /// One of [`PolicyError::KIND_REASON_CLASS`], [`PolicyError::KIND_NET_CLASS`],
622    /// [`PolicyError::KIND_EFFECT_NAME`], [`PolicyError::KIND_RULE_KIND`].
623    pub kind: &'static str,
624    /// The offending token, verbatim. Empty when the position was EMPTY (a missing arrow, an `allow` with
625    /// no values) — which is itself the finding.
626    pub token: String,
627    /// The tokens accepted in that position. Empty ⇒ the position takes an open-ended literal.
628    pub accepted: Vec<String>,
629    /// The raw policy line, verbatim.
630    pub rule: String,
631    /// The human sentence — the same text the stderr channel carries, so the two cannot disagree.
632    pub message: String,
633    /// ⟨0.28⟩ The 1-based SOURCE LINE the error sits on — SPEC §6.2 pins the verdict's `ignored`
634    /// disclosure as `[{ line, text, reason }]`, and a consumer's next action is to go to that line.
635    /// Counted over the normalized text (bare `\r` line breaks count like `\n`, matching the split).
636    pub line: usize,
637    /// ⟨0.28⟩ The source line VERBATIM — before comment-stripping and trimming, unlike `rule`, because
638    /// §6.2's `text` is "the source line, verbatim" and the operator matches it against their file.
639    pub text: String,
640    /// ⟨0.24⟩ Does this error make the policy UNHONOURABLE, so every gate route must refuse (exit 2)?
641    ///
642    /// FATAL and REPORTED are different questions and this field is the only place they are told apart.
643    /// A dropped `nonsense line` is reported and survivable — the rest of the policy means what it says.
644    /// A rewritten `deny Unknown[dispatch,nativ]` is not: the rule that RAN is not the rule that was
645    /// written, and the direction that matters NARROWS it.
646    pub fatal: bool,
647}
648
649impl PolicyError {
650    pub const KIND_REASON_CLASS: &'static str = "reason-class/alias";
651    pub const KIND_NET_CLASS: &'static str = "Net destination-class";
652    pub const KIND_EFFECT_NAME: &'static str = "effect-name";
653    pub const KIND_RULE_KIND: &'static str = "rule-kind";
654}
655
656/// The rule kinds parsed from a CANDOR_POLICY file.
657#[derive(Default, Debug)]
658pub struct ParsedPolicy {
659    pub rules: Vec<PolicyRule>,
660    pub allow_rules: Vec<AllowRule>,
661    pub layer_rules: Vec<LayerRule>,
662    /// ⟨0.29⟩ the `only <A> -> <B> …` permission rules — see [`OnlyRule`]. Kept in their own list rather
663    /// than folded into `layer_rules` because the two read OPPOSITE ways: a `forbid` names what must not
664    /// happen, an `only` names the complete set of what may, so a route that handled one as the other
665    /// would inverse the verdict rather than approximate it.
666    pub only_rules: Vec<OnlyRule>,
667    /// ⟨0.24⟩ POLICY ERRORS — a policy that cannot be honoured AS WRITTEN (SPEC §6.2). Non-empty ⇒ every
668    /// gate route MUST refuse: exit 2, the unreadable-policy posture. Not a warning list: the rules in
669    /// `rules` are what the text would mean if the error were tolerated, and tolerating it is the defect.
670    ///
671    /// Today the only member is an unrecognised reason-class/alias token in an `Unknown[…]` filter. The
672    /// asymmetry that used to justify a warning — "a dropped policy token leaves a WIDER rule standing,
673    /// so the failure is loud" — is false in the case that matters, and the false half is FAIL-OPEN:
674    ///
675    ///   - `deny Unknown[corp]` (sole unrecognised token) — the filter empties and the rule WIDENS to a
676    ///     bare `deny Unknown`, while the engine prints "ignoring policy rule" and then KEEPS and
677    ///     re-scopes it. Merely surprising, but a FALSE DISCLOSURE.
678    ///   - `deny Unknown[dispatch,nativ]` (a typo BESIDE valid tokens) — the token is dropped, the rule
679    ///     NARROWS to `[dispatch]`, and it stops gating native-caused holes entirely while the operator
680    ///     reads a gate that looks armed. **That is the fail-open, and it is the common case: a typo
681    ///     lands beside correct tokens far more often than alone.**
682    ///
683    /// A policy that cannot be honoured as written is not silently rewritten into a different policy.
684    ///
685    /// ⟨0.24⟩ THIS LIST NOW HOLDS EVERY LINE THE PARSER DID NOT HONOUR, fatal or not (SPEC §3.1
686    /// `195d45a`) — `parsepolicy` reports them all, and the gate routes refuse on
687    /// [`ParsedPolicy::fatal_messages`] alone. Widening the LIST without widening what REFUSES is the
688    /// whole of the change: a dropped `nonsense line` was always survivable and stays so.
689    pub errors: Vec<PolicyError>,
690    /// ⟨0.24⟩ The `.candor/config` `unknown-alias` definitions this policy actually resolved a token
691    /// through (SPEC §3.1) — **name → the reason-class TOKENS it expanded to**, not a bare name list.
692    /// Non-empty ⇒ a config file supplied vocabulary that PARTICIPATED in the verdict, and the
693    /// `--gate-json` document MUST name that file. Recorded at the point of USE, not from the alias map:
694    /// a config defining ten aliases none of which the policy mentions changed nothing, and naming it
695    /// would train the reader to ignore the field.
696    ///
697    /// ⟨0.24⟩ **THE VALUE TRAVELS WITH THE NAME, AND THAT IS A SPEC MUST** (§3.1, candor-spec `7f5b5ba`).
698    /// This engine shipped the bare name — as did java and swift — and candor-ts kept the map and won the
699    /// argument from the clause's OWN sentence: `configSources: [path]` is rejected there because *a
700    /// disclosure that names the source but not the content leaves the reader knowing they were affected
701    /// and not how*, and `["corp"]` fails that same test one level down. **`corp = reflect` and
702    /// `corp = reflect,native` gate DIFFERENTLY under one unchanged policy line**, so a reader given only
703    /// the name cannot tell which gate ran. The map is a strict superset — the keys recover the old array.
704    ///
705    /// Class TOKENS rather than `ReasonClass`, so the wire order is the token's alphabetical one (which
706    /// is what candor-ts's `[...set].sort()` produces) and not `ReasonClass`'s declaration order.
707    pub used_aliases: BTreeMap<String, BTreeSet<String>>,
708}
709
710impl ParsedPolicy {
711    /// ⟨0.24⟩ The messages of the errors that make the policy UNHONOURABLE — what every gate route
712    /// refuses on. Non-empty ⇒ exit 2, the unreadable-policy posture.
713    ///
714    /// Separate from `errors` because REPORTED and FATAL are different questions, and conflating them in
715    /// either direction is a defect: refusing on every dropped line would make `nonsense line` fail a
716    /// build, and reporting only the fatal ones is the silent narrowing this rung exists to close.
717    pub fn fatal_messages(&self) -> Vec<&str> {
718        self.errors.iter().filter(|e| e.fatal).map(|e| e.message.as_str()).collect()
719    }
720}
721
722/// The hostname part of a `host[:port]` literal, port stripped — so `api.stripe.com` in a rule accepts
723/// a reached `api.stripe.com:443`. IPv6-aware: a bracketed `[host]:port` yields the bracketed host, and
724/// a BARE IPv6 literal (>1 colon, no brackets) has no port to strip and is returned whole — a naive
725/// first-colon split collapsed every `2001:db8::*` to `2001`, so one allowed IPv6 accepted any address
726/// in that block (/code-review). A hostname/IPv4 `host` or `host:port` (≤1 colon) splits at the colon.
727pub fn host_part(h: &str) -> &str {
728    if let Some(rest) = h.strip_prefix('[') {
729        // `[ipv6]` or `[ipv6]:port` — the host is between the brackets.
730        return rest.split(']').next().unwrap_or(rest);
731    }
732    if h.matches(':').count() > 1 {
733        return h; // bare IPv6 literal — no port suffix to strip
734    }
735    h.split(':').next().unwrap_or(h)
736}
737
738/// The basename of a command (`/usr/bin/git` → `git`), so `allow Exec … git` accepts an absolute path.
739pub fn cmd_base(c: &str) -> &str {
740    c.rsplit(['/', '\\']).next().unwrap_or(c)
741}
742
743/// Whether an allowed path `a` covers a reached path `r` (SPEC §6.2: path-boundary-respecting prefix).
744/// A directory covers itself and everything beneath it, but NOT a sibling sharing a textual prefix
745/// (`/etc/app` ⊉ `/etc/apppwned`); a `..` that climbs out is never covered; absolute/relative are
746/// never conflated.
747pub fn fs_path_covered(a: &str, r: &str) -> bool {
748    if r.split(['/', '\\']).any(|c| c == "..") {
749        return false;
750    }
751    let absolute = |s: &str| s.starts_with('/') || s.starts_with('\\');
752    if absolute(a) != absolute(r) {
753        return false;
754    }
755    let norm = |s: &str| -> Vec<String> {
756        s.split(['/', '\\'])
757            .filter(|c| !c.is_empty() && *c != ".")
758            .map(|c| c.to_string())
759            .collect()
760    };
761    let (ac, rc) = (norm(a), norm(r));
762    ac.len() <= rc.len() && ac.iter().zip(&rc).all(|(x, y)| x == y)
763}
764
765/// Whether an allowed table entry `a` covers a reached table `r` (SPEC §6.2): case-insensitive
766/// exact match on the (possibly schema-qualified) name, or a `schema.*` entry covering every table
767/// in that schema. Strict on qualification — an allowed `entries` does NOT cover a reached
768/// `ledger.entries` (write both forms if your queries mix them); silent widening is the failure
769/// mode an allowlist exists to prevent.
770pub fn db_table_covered(a: &str, r: &str) -> bool {
771    let (a, r) = (a.to_lowercase(), r.to_lowercase());
772    if let Some(schema) = a.strip_suffix(".*") {
773        return r.strip_prefix(schema).is_some_and(|rest| rest.starts_with('.'));
774    }
775    a == r
776}
777
778/// Whether a reached literal is allowed under an effect-specific match (SPEC §6.2): `Net` host by
779/// name (port ignored), `Exec` command by basename, `Fs` path by boundary-respecting prefix,
780/// `Db` table by qualified name or `schema.*`.
781pub fn literal_allowed(effect: &str, reached: &str, allow: &BTreeSet<String>) -> bool {
782    match effect {
783        // `Llm` ⟨0.13⟩ rides the Net host literal (SPEC §1) — matched by hostname like `Net`.
784        "Net" | "Llm" => allow.iter().any(|a| host_part(a) == host_part(reached)),
785        "Exec" => allow.iter().any(|a| cmd_base(a) == cmd_base(reached)),
786        "Fs" => allow.iter().any(|a| fs_path_covered(a, reached)),
787        "Db" => allow.iter().any(|a| db_table_covered(a, reached)),
788        _ => allow.contains(reached),
789    }
790}
791
792/// Split a function name (or scope) into PATH SEGMENTS on either separator. Reports reach the Rust gate
793/// AND `candor-query` from BOTH the Rust engines (`::`-separated names) and the JVM/Swift/TS engines
794/// (`.`-separated names — `candor-query` is explicitly built to read them). Segmenting on `::` ALONE
795/// left a scoped `deny`/`pure` rule silently INERT on a dotted name: the scope matched nothing, so
796/// `whatif` returned a false green on the security boundary (gate-evasion). The JVM engine's own
797/// `scopeMatches` already splits on `.`; this aligns the Rust side. A `:`/`.` never appears WITHIN a
798/// real segment, so splitting on both never over-segments a Rust name (no spurious match).
799fn name_segments(s: &str) -> Vec<&str> {
800    s.split(['.', ':']).filter(|p| !p.is_empty()).collect()
801}
802
803/// A policy scope matches a function name by **path segment** (SPEC §6.2), not substring: split both
804/// into segments (on `::` or `.`); the scope matches a contiguous run of name-segments where every
805/// segment except the last matches exactly and the last is a prefix. So `domain` matches
806/// `app::domain::h`, `com.acme.domain.h`, and `domain_logic` but not `subdomain`.
807/// ⟨0.29⟩ SCOPE MATCHING FOR A **PERMISSION**, where the prefix rule is FAIL-OPEN.
808///
809/// [`scope_matches`]'s last segment is a PREFIX of its name-segment, so `util` matches `utilities`. For
810/// `deny`/`pure`/`forbid` that widening is FAIL-CLOSED — a scope that matches more forbids more — and it
811/// is why the rule exists. For the `to` list of an `only` rule it is the exact inverse: a permitted scope
812/// that matches more PERMITS more, so the matcher that keeps every other rule kind safe silently widens
813/// the one form whose entire purpose is to fail safe.
814///
815/// MEASURED on the shipped ⟨0.29⟩ implementation, before this function existed:
816///
817/// ```text
818/// only model -> util          `model::go` reaching `utilities_untrusted::exfil`  →  policy ✓
819/// forbid model -> util        the identical reach                                 →  AS-EFF-009
820/// ```
821///
822/// The operator wrote a complete permission list and the matcher quietly extended it to anything sharing
823/// a prefix with an entry. So a `to` scope matches by EXACT segment run, with no prefix on the last —
824/// `only a -> util` permits `util::x` and `crate::util::x`, and does NOT permit `utilities_untrusted::x`.
825///
826/// THE `from` SIDE KEEPS THE PREFIX RULE, deliberately: `from` selects which functions the rule BINDS, so
827/// matching more constrains more, which is the safe direction. The asymmetry is the point — each side
828/// takes the matcher whose over-approximation errs toward the gate firing.
829pub fn scope_matches_permitted(name: &str, scope: &str) -> bool {
830    let segs = name_segments(name);
831    let parts = name_segments(scope);
832    if parts.is_empty() || parts.len() > segs.len() {
833        return false;
834    }
835    segs.windows(parts.len()).any(|w| w == parts.as_slice())
836}
837
838/// A TRAILING SEPARATOR MEANS EXACT SEGMENT — `app::` matches the segment `app` and nothing else,
839/// where bare `app` keeps the documented prefix behaviour and still matches `application_name`.
840///
841/// REPORTED FROM THE FIELD (ebman CI adoption, 2026-08-23) and reproduced: `forbid aws -> app` fired
842/// 14 times on honest AWS SDK calls because `app` prefix-matched `application_name`, and writing
843/// `app::` did not help — `name_segments` drops empty parts, so `app::` segmented to exactly `["app"]`
844/// and the separator never survived to mean anything. The reporter deleted the rule, which is the real
845/// cost: **the genuine `aws -> app` violation it existed to catch will now never fire, and nothing in
846/// the policy file records that a boundary stopped being checked.** The two available responses to the
847/// false positives — delete the rule, or widen the scope until it stops firing — end in the same place.
848///
849/// ADDITIVE ON PURPOSE. Bare `app` is unchanged, so no existing verdict moves; only `app::`, which
850/// today silently behaves as `app`, starts meaning what everyone who writes it intends. Silence was
851/// the worst of the three options available (match exactly / error as unsupported / quietly do
852/// nothing), because ⟨0.24⟩ §3.1 already rules that an unanswerable condition must be DISCLOSED rather
853/// than scored as satisfied — and a scope token that segments away is exactly that.
854fn scope_is_exact(scope: &str) -> bool {
855    let t = scope.trim_end();
856    t.ends_with("::") || t.ends_with('.')
857}
858
859pub fn scope_matches(name: &str, scope: &str) -> bool {
860    let segs = name_segments(name);
861    let parts = name_segments(scope);
862    if parts.is_empty() || parts.len() > segs.len() {
863        return false;
864    }
865    let exact = scope_is_exact(scope);
866    let (last, init) = parts.split_last().unwrap();
867    segs.windows(parts.len()).any(|w| {
868        let (w_last, w_init) = w.split_last().unwrap();
869        w_init == init && if exact { w_last == last } else { w_last.starts_with(last) }
870    })
871}
872
873/// Reconstruct a rule's source form and the `Unknown`-forbidding upgrade for it: `pure <scope>` →
874/// (`"pure <scope>"`, `"deny Unknown <scope>"`); `deny <E…> <scope>` → (`"deny <E…> <scope>"`,
875/// `"deny <E…> Unknown <scope>"`). Shared so the gate note and `candor unverified` name the identical
876/// rule and upgrade — one source of truth for the disclosure's advice.
877///
878/// ⟨0.24⟩ **THE NARROWING FILTERS ARE RENDERED, and they had to start being rendered in the same commit
879/// that made them REACHABLE here.** Making `unverified_hole_rule` filter-aware is what first lets a
880/// `deny Unknown[reflect]` / `deny Net[unknown-host]` rule be the rule a hole is disclosed under — and
881/// this reconstruction dropped the bracket, so the fix would have printed the operator's narrowed rule
882/// back to them as the WIDE one (`deny Unknown`) and advised the nonsense upgrade `deny Unknown
883/// Unknown`. That is the same mis-attribution `whatif` carries, arriving through the fix for a different
884/// defect: the hazard on this rung is that each correction manufactures its own mirror, so the rendering
885/// moves with the predicate rather than after it.
886///
887/// A rule carrying NO filter renders byte-identically to before, which is what keeps conformance PARTs
888/// 12c/12d (`deny Db Net Unknown domain`, four-way) unmoved.
889///
890/// THE UPGRADE SPLITS on whether the rule already denies `Unknown`. If it does, it can only be here
891/// NARROWED — a bare `deny … Unknown` fires on every `Unknown`, so the function would be a violation and
892/// not a hole — and the upgrade is that term WIDENED to bare `Unknown`, not a second `Unknown` appended.
893pub fn rule_and_upgrade(r: &PolicyRule) -> (String, String) {
894    let scope = r.scope.clone().unwrap_or_default();
895    let suffix = if scope.is_empty() { String::new() } else { format!(" {scope}") };
896    if r.effects.is_empty() {
897        // `pure` forbids real effects but not Unknown; to REQUIRE provable purity, add a deny-Unknown.
898        return (format!("pure{suffix}"), format!("deny Unknown{suffix}"));
899    }
900    // One effect term, with its narrowing filter if it has one. Class tokens sorted by TOKEN string, as
901    // `parsepolicy` sorts them and as the java reference's `.sorted()` does — the dump and the
902    // disclosure must spell one rule one way.
903    let term = |e: &str| -> String {
904        if e == UNKNOWN && !r.unknown_classes.is_empty() {
905            let mut t: Vec<&str> = r.unknown_classes.iter().map(|c| c.token()).collect();
906            t.sort_unstable();
907            format!("{UNKNOWN}[{}]", t.join(","))
908        } else if e == "Net" && !r.net_classes.is_empty() {
909            format!("Net[{}]", r.net_classes.iter().map(String::as_str).collect::<Vec<_>>().join(","))
910        } else {
911            e.to_string()
912        }
913    };
914    let effs = r.effects.iter().map(|e| term(e)).collect::<Vec<_>>().join(" ");
915    if r.effects.contains(UNKNOWN) {
916        let widened =
917            r.effects.iter().map(|e| if *e == UNKNOWN { UNKNOWN.to_string() } else { term(e) }).collect::<Vec<_>>();
918        (format!("deny {effs}{suffix}"), format!("deny {}{suffix}", widened.join(" ")))
919    } else {
920        (format!("deny {effs}{suffix}"), format!("deny {effs} {UNKNOWN}{suffix}"))
921    }
922}
923
924/// The single predicate for a provable-purity hole (eval/fixloop/DISPATCH-NOTE.md): a function that is
925/// `Unknown`, sits in a `pure`/`deny <E>` scope, and PASSES that rule (carries none of its forbidden real
926/// effects) — so its compliance is asserted but not verified (the Unknown could hide the very effect the
927/// rule forbids; the classic case is a fn/closure-injected port). A *real* violation is the gate's job, not
928/// this. Returns the first governing rule under which the function is such a hole, or `None` if it is not
929/// one. Shared by candor-scan's gate note and candor-query's `unverified` so "what a hole is" has ONE
930/// definition — the two paths can never drift (conformance PART 12d pins their agreement).
931///
932/// ⟨0.24⟩ **"PASSES" IS NOW ASKED OF THE GATE, NOT OF A SECOND COPY OF IT.** This predicate computed the
933/// passing test from `r.effects` alone — "does the rule NAME an effect this function has?" — which is
934/// the pre-⟨0.19⟩ question, still being asked after two rungs gave rules a NARROWING FILTER. So on
935/// `deny Unknown[reflect]` over an `indirect` hole the gate TOLERATED (exit 0, the class does not match)
936/// while this read the same rule as violated; and a hole is *by definition* a function that PASSES its
937/// rule while `Unknown`, so the real hole was reclassified as a violation-that-isn't and **deleted from
938/// the disclosure** — `unverified` answering "every function in a pure/deny layer is PROVABLY clean ✓"
939/// over a function the gate had just declined to clear. MEASURED 2026-07-28, and reachable with no alias
940/// in play at all: one layer below the widening `ea0df4f` closed, in the same four verbs.
941///
942/// It now calls [`crate::gate::rule_hits`] — the gate's own firing decision — so the two cannot disagree
943/// again. That needs the function's TRANSITIVE reason classes and its ⟨0.20⟩ destination classes, the
944/// same two accumulators the gate reads, which is why they are parameters now rather than derivable.
945///
946/// **THE DIRECTION IS THE MIRROR ARGUMENT.** A filter can only ever SHRINK what a rule charges, so a
947/// filter-aware pass test can only ever find MORE holes — this cannot silently suppress a disclosure
948/// that used to appear. Pinned in both directions by
949/// `a_narrowed_rule_the_gate_tolerates_is_a_hole_and_the_one_it_fires_on_is_not`, in one run, because
950/// the fixture proving the fabrication is closed cannot show the reach closed with it. A WITHHELD filter
951/// — nothing to read — likewise counts as PASSING here: the gate did not clear the function, and an
952/// advisory note's fail-safe direction is to disclose.
953pub fn unverified_hole_rule<'a, S: AsRef<str>>(
954    name: &str,
955    effects: &[S],
956    reason_classes: Option<&BTreeSet<String>>,
957    net_classes: &[String],
958    rules: &'a [PolicyRule],
959) -> Option<&'a PolicyRule> {
960    if !effects.iter().any(|e| e.as_ref() == UNKNOWN) {
961        return None;
962    }
963    let effs: Vec<&str> = effects.iter().map(AsRef::as_ref).collect();
964    rules.iter().find(|r| {
965        // in the rule's scope (a scopeless rule governs the whole unit) …
966        if let Some(s) = &r.scope {
967            if !scope_matches(name, s) {
968                return false;
969            }
970        }
971        // … and PASSES it — the gate's own answer, narrowing filters and all. Empty `hits` IS passing.
972        crate::gate::rule_hits(r, &effs, reason_classes, net_classes).hits.is_empty()
973    })
974}
975
976/// R443 — THE PROVABLE-PURITY ADVISORY'S LINES, ONE RENDERER FOR BOTH GATE ROUTES.
977///
978/// `candor-scan --policy` printed this note and `candor-query gate --report` printed NOTHING over the
979/// identical tree, the identical rule and the identical verdict (MEASURED 2026-09-15 on
980/// `pub fn via_callback(f: impl Fn()) { f(); }` under `pure via_callback`: route B three lines naming
981/// `deny Unknown via_callback`, route A `policy ✓` and silence). **The silent route is the DEPLOYED
982/// one** — gating a precomputed report is what the query layer is for, so it is what CI runs.
983///
984/// The SET is already single-sourced ([`unverified_hole_rule`], which both routes have always called);
985/// this is the other half — the rendering, which would otherwise be the same three sentences written
986/// twice in two crates, i.e. the R288/R347 shape arriving through the fix for it. Only the `prefix`
987/// differs, because the two routes must name themselves (an operator has to know which command to
988/// re-run). `holes` is `(fn, upgrade)` in the caller's own order — already the shape candor-scan's
989/// `unverified_holes` returns.
990///
991/// ADVISORY: the caller prints these and does NOT touch its verdict or exit code. Whether `pure`/`deny`
992/// should FAIL CLOSED on `Unknown` is a SPEC question (R443's expensive half) and is deliberately not
993/// decided here.
994pub fn unverified_note_lines(prefix: &str, holes: &[(String, String)]) -> Vec<String> {
995    if holes.is_empty() {
996        return Vec::new();
997    }
998    let mut out = vec![format!(
999        "{prefix}: note — {} function(s) PASS the policy but are Unknown (purity NOT verified — the Unknown could hide a forbidden effect):",
1000        holes.len()
1001    )];
1002    for (fq, up) in holes {
1003        out.push(format!("    `{fq}`  → add  `{up}`"));
1004    }
1005    out.push(
1006        "  (advisory; add the upgrade(s) to REQUIRE provable purity, or run `candor-query unverified` for detail — the gate verdict is unchanged)"
1007            .to_string(),
1008    );
1009    out
1010}
1011
1012/// Parse a CANDOR_POLICY file (SPEC §6.2). One rule per line; `#` comments and blanks ignored:
1013///
1014/// ```text
1015/// deny Net Db  domain     # functions whose path contains segment "domain" must not perform Net or Db
1016/// deny Exec               # no function anywhere may perform Exec
1017/// deny Unknown  api        # functions in "api" must be fully resolvable (forbid the unverifiable)
1018/// pure         parse      # functions whose path contains segment "parse" must be effect-free
1019/// allow Net in billing  api.stripe.com
1020/// forbid domain -> infra
1021/// ```
1022///
1023/// In a `deny` rule, leading tokens that name a known effect (or `Unknown`) are forbidden; the FIRST
1024/// non-effect token is the scope and ends the rule. A `deny` naming no known effect is dropped (it is
1025/// NOT a `pure` rule). Malformed/unknown lines are ignored with a warning — never silently widened.
1026/// The §6.2 token separator: ASCII whitespace ONLY (space/tab/CR/LF/VT/FF). `split_whitespace`/`trim`
1027/// use Unicode `White_Space`, which would split a NBSP/ideographic space that Java drops — a gateless-
1028/// green cross-engine divergence (adversarial DSL review). A non-ASCII space stays part of its token, so
1029/// the rule is malformed and ignored, uniformly.
1030fn is_ascii_ws(c: char) -> bool {
1031    matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
1032}
1033
1034pub fn parse_policy(text: &str) -> ParsedPolicy {
1035    parse_policy_impl(text, true, &std::collections::BTreeMap::new())
1036}
1037/// As [`parse_policy`] but with `.candor/config` `unknown-alias` definitions (⟨0.19⟩, SPEC §6.2): an
1038/// `Unknown[<name>]` filter resolves a user-defined `<name>` to its reason classes. The gate + `parsepolicy`
1039/// pass the discovered aliases (via [`parse_unknown_aliases`]); a config alias never changes what bare
1040/// `deny E Unknown` means (always `Unknown[*]`), so the rule stays legible from the policy alone.
1041pub fn parse_policy_with_aliases(text: &str, aliases: &std::collections::BTreeMap<String, std::collections::BTreeSet<ReasonClass>>) -> ParsedPolicy {
1042    parse_policy_impl(text, true, aliases)
1043}
1044/// ⟨0.24⟩ [`parse_policy_with_aliases`] but SILENT — for a caller that must inspect
1045/// [`ParsedPolicy::errors`] / [`ParsedPolicy::used_aliases`] BEFORE it parses for real (candor-scan
1046/// refuses before touching the classifier's accumulators). Silent so the ordinary parse warnings are not
1047/// printed twice on the same text.
1048pub fn parse_policy_silent(
1049    text: &str,
1050    aliases: &std::collections::BTreeMap<String, BTreeSet<ReasonClass>>,
1051) -> ParsedPolicy {
1052    parse_policy_impl(text, false, aliases)
1053}
1054/// Same as [`parse_policy`] but SILENT about malformed rules — for a SECOND, advisory re-parse within the
1055/// same run (candor-scan parses once for the gate check and again for the `unverified` disclosure), so the
1056/// CI log doesn't print every "ignoring policy rule …" warning twice (#21). The first parse already warned.
1057pub fn parse_policy_quiet(text: &str) -> ParsedPolicy {
1058    parse_policy_impl(text, false, &std::collections::BTreeMap::new())
1059}
1060fn parse_policy_impl(text: &str, warn: bool, aliases: &std::collections::BTreeMap<String, std::collections::BTreeSet<ReasonClass>>) -> ParsedPolicy {
1061    macro_rules! warn_ignore { ($($a:tt)*) => { if warn { eprintln!($($a)*); } } }
1062    let mut out = ParsedPolicy::default();
1063    // ⟨0.28⟩ The source position of the line under the cursor, for `PolicyError::{line, text}` — bound
1064    // BEFORE the macro below so its body (whose free identifiers resolve at definition scope) can read
1065    // them; the loop updates both per iteration. §6.2's `ignored` disclosure is `[{line, text, reason}]`.
1066    let mut cur_line: usize;
1067    let mut cur_text: &str;
1068    // ⟨0.24⟩ Record a line the parser did not honour (SPEC §3.1 `195d45a`), on the ONE list `parsepolicy`
1069    // reports and the gate routes filter for `fatal`. The stderr sentence and `message` are the SAME
1070    // string by construction — a disclosure that can drift from the one beside it is how this family
1071    // produced a FALSE disclosure once already (conformance PART 13b).
1072    macro_rules! not_honoured {
1073        ($fatal:expr, $kind:expr, $token:expr, $accepted:expr, $rule:expr, $msg:expr) => {{
1074            let message: String = $msg;
1075            out.errors.push(PolicyError {
1076                kind: $kind,
1077                token: ($token).to_string(),
1078                accepted: ($accepted).iter().map(|s: &&str| s.to_string()).collect(),
1079                rule: ($rule).to_string(),
1080                message,
1081                line: cur_line,
1082                text: cur_text.to_string(),
1083                fatal: $fatal,
1084            });
1085        }};
1086    }
1087    // `str::lines()` splits on \n and \r\n but NOT bare \r — a classic-Mac file then collapses to ONE
1088    // line, and since \r is also an in-line ASCII-ws token separator (is_ascii_ws), every rule after the
1089    // first was glued into the first rule's tokens and dropped (sweep [16], a gateless-green divergence).
1090    // Java's Files.readAllLines (the reference) breaks on bare \r too — normalize to match it. Allocation
1091    // only when a bare \r is actually present (the overwhelmingly-common \n / \r\n files are untouched).
1092    let normalized;
1093    let text = if text.contains('\r') {
1094        normalized = text.replace("\r\n", "\n").replace('\r', "\n");
1095        normalized.as_str()
1096    } else {
1097        text
1098    };
1099    for (line_idx, raw_line) in text.lines().enumerate() {
1100        cur_line = line_idx + 1;
1101        cur_text = raw_line;
1102        let line = raw_line.split('#').next().unwrap_or("").trim_matches(is_ascii_ws);
1103        if line.is_empty() {
1104            continue;
1105        }
1106        let mut toks = line.split(is_ascii_ws).filter(|s| !s.is_empty());
1107        match toks.next().unwrap_or("") {
1108            "allow" => {
1109                let effect = match toks.next().unwrap_or("") {
1110                    "Net" => "Net",
1111                    // `Llm` ⟨0.13⟩ rides the Net host literal (SPEC §1) — `allow Llm <host…>` restricts which
1112                    // MODEL hosts a scope may reach, matched by hostname like Net (its reached surface IS the
1113                    // Net host surface). Match candor-java's Policy.parsePolicy.
1114                    "Llm" => "Llm",
1115                    "Exec" => "Exec",
1116                    "Fs" => "Fs",
1117                    "Db" => "Db",
1118                    other => {
1119                        let msg = format!(
1120                            "unknown effect-name `{other}` in `allow` (accepted: Db, Exec, Fs, Llm, Net \
1121                             \u{2014} `allow` covers only the effects carrying a literal surface: Net/Llm \
1122                             hosts, Exec commands, Fs paths, Db tables): {line}"
1123                        );
1124                        warn_ignore!("candor: policy error — {msg}");
1125                        // ⟨0.24⟩ FATAL (SPEC §6.2 `1e1748a`). MEASURED four-way before this:
1126                        // `allow Nett host.example` -> exit 0 on rust, ts, java AND swift. The rule is
1127                        // DELETED and the certification silently vanishes, so the operator reads an
1128                        // armed allowlist that does not exist.
1129                        //
1130                        // The grammar defence that kept the token rule inside the bracket does NOT
1131                        // reach here: `allow`'s effect position is a fixed, closed set with **no scope
1132                        // reading available**, so an unrecognised token there is unambiguously a typo
1133                        // and there is no legitimate policy it could be. This document already calls a
1134                        // dropped rule "the limit case of silently rewritten into a different policy…
1135                        // a bigger rewrite than a narrowed filter" — and the bigger rewrite was
1136                        // warning-only while the smaller one was already exit 2.
1137                        not_honoured!(
1138                            true,
1139                            PolicyError::KIND_EFFECT_NAME,
1140                            other,
1141                            ["Db", "Exec", "Fs", "Llm", "Net"],
1142                            line,
1143                            msg
1144                        );
1145                        continue;
1146                    }
1147                };
1148                let mut rest: Vec<&str> = toks.collect();
1149                let scope = if rest.first() == Some(&"in") {
1150                    let s = rest.get(1).map(|s| s.to_string());
1151                    rest.drain(..2.min(rest.len()));
1152                    s
1153                } else {
1154                    None
1155                };
1156                let literals: BTreeSet<String> = rest.iter().map(|h| h.to_string()).collect();
1157                if literals.is_empty() {
1158                    let msg = format!("`allow {effect}` names no values: {line}");
1159                    warn_ignore!("candor: ignoring policy rule ({msg})");
1160                    // `accepted` is EMPTY on purpose: the position takes an open-ended literal (a host, a
1161                    // path, a command, a table), so there is no token list to offer. A fact about the
1162                    // grammar, not a gap in the report.
1163                    not_honoured!(false, PolicyError::KIND_RULE_KIND, "", [], line, msg);
1164                    continue;
1165                }
1166                out.allow_rules.push(AllowRule { effect, scope, literals, raw: line.to_string() });
1167            }
1168            "deny" => {
1169                let mut effects = BTreeSet::new();
1170                let mut scope = None;
1171                // Reason-class filter on `Unknown` (REASON-SCOPED-UNKNOWN-DESIGN.md): empty ⇒ `Unknown[*]`
1172                // (any reason — the bare form); non-empty ⇒ only those classes. `*` = all.
1173                let mut unknown_classes: BTreeSet<ReasonClass> = BTreeSet::new();
1174                let mut unknown_star = false;
1175                // Destination-class filter on `Net` (NET-DESTINATION-CLASS-DESIGN.md): empty ⇒ `Net[*]`
1176                // (any destination — the bare form); non-empty ⇒ only those classes. `*` = all.
1177                let mut net_classes: BTreeSet<String> = BTreeSet::new();
1178                let mut net_star = false;
1179                for t in toks {
1180                    // `Net[unknown-host]` / `Net[*]` / `Net[known-telemetry,unknown-host]`: the destination-scoped form.
1181                    if let Some(inner) = t.strip_prefix("Net[").and_then(|s| s.strip_suffix(']')) {
1182                        effects.insert("Net");
1183                        for cn in inner.split(',') {
1184                            let cn = cn.trim();
1185                            if cn.is_empty() {
1186                                continue;
1187                            }
1188                            if cn == "*" {
1189                                net_star = true;
1190                            } else if crate::NET_DEST_CLASSES.contains(&cn) {
1191                                net_classes.insert(cn.to_string());
1192                            } else {
1193                                // ⟨0.24⟩ A POLICY ERROR, not a warning — SPEC §6.2 `be0b9a9`. Byte-identical
1194                                // in shape to the reason-class arm below, and byte-identical in harm:
1195                                // MEASURED `deny Net[known-telemetry,unknown-hosst]` → exit 0 where the
1196                                // correctly-spelled rule exits 1. The typo is dropped, the filter NARROWS
1197                                // to `[known-telemetry]`, and the gate stops covering unidentifiable
1198                                // destinations while the operator reads a gate that looks armed.
1199                                not_honoured!(
1200                                    true,
1201                                    PolicyError::KIND_NET_CLASS,
1202                                    cn,
1203                                    ["known-telemetry", "known-partner", "unknown-host", "*"],
1204                                    line,
1205                                    format!(
1206                                        "unrecognised Net destination-class `{cn}` in `{line}` — \
1207                                         accepted: known-telemetry, known-partner, unknown-host, plus `*`"
1208                                    )
1209                                );
1210                            }
1211                        }
1212                        continue;
1213                    }
1214                    // `Unknown[dispatch,reflect]` / `Unknown[*]` / `Unknown[dynamic]`: the reason-scoped form.
1215                    if let Some(inner) = t.strip_prefix("Unknown[").and_then(|s| s.strip_suffix(']')) {
1216                        effects.insert(UNKNOWN);
1217                        for cn in inner.split(',') {
1218                            let cn = cn.trim();
1219                            if cn.is_empty() {
1220                                continue;
1221                            }
1222                            if cn == "*" {
1223                                unknown_star = true;
1224                            } else if cn == "dynamic" {
1225                                unknown_classes.extend(ReasonClass::dynamic_set());
1226                            } else if let Some(rc) = ReasonClass::from_token(cn) {
1227                                unknown_classes.insert(rc);
1228                            } else if let Some(a) = aliases.get(cn) {
1229                                unknown_classes.extend(a.iter().copied()); // ⟨0.19⟩ config `unknown-alias`
1230                                // ⟨0.24⟩ → the verdict names it AND what it expanded to (SPEC §3.1
1231                                // `7f5b5ba`): the NAME alone cannot tell a reader which gate ran.
1232                                out.used_aliases
1233                                    .insert(cn.to_string(), a.iter().map(|c| c.token().to_string()).collect());
1234                            } else {
1235                                // ⟨0.24⟩ A POLICY ERROR, not a warning — see `ParsedPolicy::errors`. The
1236                                // token is still dropped below so `rules` stays well-formed for the
1237                                // advisory readers (`unverified`, `parsepolicy`); the gate routes refuse
1238                                // on `errors` before any of it is used as a verdict.
1239                                not_honoured!(
1240                                    true,
1241                                    PolicyError::KIND_REASON_CLASS,
1242                                    cn,
1243                                    [
1244                                        "reflect",
1245                                        "dispatch",
1246                                        "indirect",
1247                                        "native",
1248                                        "unresolved",
1249                                        "setup",
1250                                        "dynamic",
1251                                        "*"
1252                                    ],
1253                                    line,
1254                                    format!(
1255                                        "unrecognised reason-class/alias `{cn}` in `{line}` — accepted: \
1256                                         reflect, dispatch, indirect, native, unresolved, setup, plus the \
1257                                         aliases `dynamic` and `*`, plus any `unknown-alias` defined in \
1258                                         the `.candor/config` beside the policy. (⟨0.24⟩ an \
1259                                         `unknown-alias` whose OWN definition names an unrecognised class \
1260                                         is refused WHOLE, so a typo in the config surfaces as an \
1261                                         undefined alias here — check the `unknown-alias` lines too, and \
1262                                         the line above this one.)"
1263                                    )
1264                                );
1265                            }
1266                        }
1267                        continue;
1268                    }
1269                    let e = if t == UNKNOWN { Some(UNKNOWN) } else { cap_from_name(t) };
1270                    match e {
1271                        Some(e) => {
1272                            effects.insert(e);
1273                            if e == UNKNOWN {
1274                                unknown_star = true; // bare Unknown ⇒ all classes
1275                            }
1276                            if e == "Net" {
1277                                net_star = true; // bare Net ⇒ all destinations
1278                            }
1279                        }
1280                        None => {
1281                            scope = Some(t.to_string());
1282                            break;
1283                        }
1284                    }
1285                }
1286                if effects.is_empty() {
1287                    // The accepted set is the §1 effect vocabulary plus `Unknown` — SORTED, so the
1288                    // document is deterministic and diffable across engines.
1289                    let mut acc: Vec<&str> = candor_report::EFFECTS.to_vec();
1290                    acc.push(UNKNOWN);
1291                    acc.sort_unstable();
1292                    let msg = format!(
1293                        "`deny` names no known effect (accepted: {}): {line}",
1294                        acc.join(", ")
1295                    );
1296                    warn_ignore!("candor: policy error — {msg}");
1297                    // ⟨0.24⟩ FATAL (SPEC §6.2 `1e1748a`). MEASURED four-way: `deny Nett app` -> exit 0
1298                    // on all four; the rule is DELETED and the gate is green. `Nett` is read as the
1299                    // SCOPE (the first unrecognised token ends the effect list), so the line parses to
1300                    // a deny of NOTHING.
1301                    //
1302                    // **A `deny` whose effect list ends up EMPTY is malformed under EITHER reading** —
1303                    // typo-in-the-effect or scope-with-no-effect are both nonsense — so there is no
1304                    // legitimate policy it could be and refusing it loses nothing. What stays open is
1305                    // only the genuinely ambiguous middle (`deny Net Exex app`: at least one valid
1306                    // effect plus an unrecognised trailing token that MIGHT be a scope), which the
1307                    // parser cannot tell from a legitimate scope and which `parsepolicy` shows either
1308                    // way by dumping the `scope` it read.
1309                    not_honoured!(
1310                        true,
1311                        PolicyError::KIND_EFFECT_NAME,
1312                        scope.as_deref().unwrap_or(""),
1313                        acc,
1314                        line,
1315                        msg
1316                    );
1317                    continue;
1318                }
1319                // `*` (or bare `Unknown`) means all classes ⇒ empty filter (matches any Unknown).
1320                if unknown_star {
1321                    unknown_classes.clear();
1322                } else if !unknown_classes.is_empty() && !unknown_classes.contains(&ReasonClass::Unresolved) {
1323                    // A2 under-gating lint: a narrowed scope that omits `unresolved` (the catch-all for holes
1324                    // an engine couldn't classify) may silently tolerate exactly those — flag it (advisory).
1325                    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}");
1326                }
1327                // `*` (or bare `Net`) means all destinations ⇒ empty filter (matches any Net).
1328                if net_star {
1329                    net_classes.clear();
1330                }
1331                out.rules.push(PolicyRule { effects, scope, unknown_classes, net_classes, raw: line.to_string() });
1332            }
1333            "pure" => out.rules.push(PolicyRule {
1334                effects: BTreeSet::new(),
1335                scope: toks.next().map(str::to_string),
1336                unknown_classes: BTreeSet::new(),
1337                net_classes: BTreeSet::new(),
1338                raw: line.to_string(),
1339            }),
1340            "forbid" => {
1341                let a = toks.next().unwrap_or("");
1342                let arrow = toks.next().unwrap_or("");
1343                let b = toks.next().unwrap_or("");
1344                if a.is_empty() || arrow != "->" || b.is_empty() {
1345                    let msg = format!("`forbid` is malformed (want `forbid <scope> -> <scope>`): {line}");
1346                    warn_ignore!("candor: ignoring layering rule ({msg})");
1347                    // The token reported is whatever sat in the ARROW position — `->` must be its own
1348                    // token, so `forbid glued->arrow` finds nothing there and that absence is the finding.
1349                    not_honoured!(false, PolicyError::KIND_RULE_KIND, arrow, ["->"], line, msg);
1350                    continue;
1351                }
1352                out.layer_rules.push(LayerRule {
1353                    from: a.to_string(),
1354                    to: b.to_string(),
1355                    raw: line.to_string(),
1356                });
1357            }
1358            // ⟨0.29⟩ `only <A> -> <B> [<C> …]` — the PERMISSION form. Everything after the arrow is a
1359            // scope, so the rule takes a LIST where `forbid` takes one destination; that is the whole
1360            // ergonomic difference, and it is why the tail is not read left-to-right for anything else.
1361            "only" => {
1362                let a = toks.next().unwrap_or("");
1363                let arrow = toks.next().unwrap_or("");
1364                let to: Vec<String> = toks.map(str::to_string).collect();
1365                if a.is_empty() || arrow != "->" || to.is_empty() {
1366                    let msg = format!(
1367                        "`only` is malformed (want `only <scope> -> <scope> [<scope> …]`): {line}"
1368                    );
1369                    warn_ignore!("candor: ignoring permission rule ({msg})");
1370                    // Same witness as `forbid`: whatever sat in the ARROW position, since `->` must be
1371                    // its own token and `only glued->arrow` finds nothing there.
1372                    not_honoured!(false, PolicyError::KIND_RULE_KIND, arrow, ["->"], line, msg);
1373                    continue;
1374                }
1375                out.only_rules.push(OnlyRule {
1376                    from: a.to_string(),
1377                    to,
1378                    raw: line.to_string(),
1379                });
1380            }
1381            other => {
1382                let msg = format!(
1383                    "unknown rule kind `{other}` (accepted: allow, deny, forbid, only, pure): {line}"
1384                );
1385                warn_ignore!("candor: ignoring policy rule ({msg})");
1386                not_honoured!(
1387                    false,
1388                    PolicyError::KIND_RULE_KIND,
1389                    other,
1390                    ["allow", "deny", "forbid", "only", "pure"],
1391                    line,
1392                    msg
1393                );
1394            }
1395        }
1396    }
1397    out
1398}
1399
1400#[cfg(test)]
1401mod tests {
1402    /// R443 — the note's bytes, pinned. Both gate routes render through this one function now, so the
1403    /// only thing a route may vary is the PREFIX; anything else drifting is this assertion failing.
1404    /// The strings are the ones candor-scan has printed since ⟨0.19⟩, character for character, because
1405    /// the point of the change was to give the SILENT route the EXISTING disclosure — not a new one.
1406    #[test]
1407    fn unverified_note_lines_render_one_note_for_both_routes() {
1408        let holes = vec![
1409            ("via_callback".to_string(), "deny Unknown via_callback".to_string()),
1410            ("domain::price".to_string(), "deny Net Unknown domain".to_string()),
1411        ];
1412        let scan = super::unverified_note_lines("candor-scan", &holes);
1413        let query = super::unverified_note_lines("candor-query gate", &holes);
1414        assert_eq!(scan.len(), 4, "header + one line per hole + the advisory footer");
1415        assert_eq!(
1416            scan[0],
1417            "candor-scan: note — 2 function(s) PASS the policy but are Unknown (purity NOT verified — the Unknown could hide a forbidden effect):"
1418        );
1419        assert_eq!(scan[1], "    `via_callback`  → add  `deny Unknown via_callback`");
1420        assert_eq!(scan[2], "    `domain::price`  → add  `deny Net Unknown domain`");
1421        assert_eq!(
1422            scan[3],
1423            "  (advisory; add the upgrade(s) to REQUIRE provable purity, or run `candor-query unverified` for detail — the gate verdict is unchanged)"
1424        );
1425        // The prefix, and NOTHING else, is what the two routes differ in.
1426        assert_eq!(scan[1..], query[1..]);
1427        assert_eq!(query[0], scan[0].replacen("candor-scan", "candor-query gate", 1));
1428        // A clean pass renders NO lines at all — the over-charge control, at the renderer.
1429        assert!(super::unverified_note_lines("candor-scan", &[]).is_empty());
1430    }
1431
1432    #[test]
1433    fn db_table_covering_is_strict() {
1434        use super::db_table_covered as c;
1435        assert!(c("ledger.entries", "Ledger.Entries")); // case-insensitive exact
1436        assert!(c("ledger.*", "ledger.entries"));       // schema wildcard
1437        assert!(!c("ledger.*", "ledgerx.entries"));     // boundary-respecting
1438        assert!(!c("entries", "ledger.entries"));       // no silent qualification widening
1439        assert!(c("entries", "entries"));
1440    }
1441
1442    #[test]
1443    fn allow_db_parses_and_gates() {
1444        let p = super::parse_policy("allow Db in billing  ledger.* customers\n");
1445        assert_eq!(p.allow_rules.len(), 1);
1446        assert_eq!(p.allow_rules[0].effect, "Db");
1447        assert!(super::literal_allowed("Db", "ledger.entries", &p.allow_rules[0].literals));
1448        assert!(super::literal_allowed("Db", "customers", &p.allow_rules[0].literals));
1449        assert!(!super::literal_allowed("Db", "audit.log", &p.allow_rules[0].literals));
1450    }
1451
1452    use super::*;
1453
1454    #[test]
1455    fn policy_parses() {
1456        let p = parse_policy(
1457            "# the domain layer must stay pure of I/O\n\
1458             deny Net Db  domain\n\
1459             deny Exec\n\
1460             pure  parse\n\
1461             nonsense line\n\
1462             deny notaneffect\n",
1463        );
1464        let rules = &p.rules;
1465        assert_eq!(rules.len(), 3);
1466        assert_eq!(rules[0].effects, ["Db", "Net"].into_iter().collect::<BTreeSet<_>>());
1467        assert_eq!(rules[0].scope.as_deref(), Some("domain"));
1468        assert!(rules[1].effects.contains("Exec") && rules[1].scope.is_none());
1469        assert!(rules[2].effects.is_empty() && rules[2].scope.as_deref() == Some("parse"));
1470        // sweep [16]: a classic-Mac (bare \r) multi-rule policy must NOT collapse to the first rule.
1471        let cr = parse_policy("deny Net a\rdeny Exec b\rdeny Db c\r");
1472        assert_eq!(cr.rules.len(), 3, "bare-CR lines must each parse");
1473        assert!(cr.rules.iter().any(|r| r.effects.contains("Exec") && r.scope.as_deref() == Some("b")));
1474        // mixed \r\n and bare \r normalize identically.
1475        assert_eq!(parse_policy("deny Net a\r\ndeny Exec b\r").rules.len(), 2);
1476        // `Unknown` is a denyable token; a bare `deny` with no effect is ignored.
1477        assert_eq!(parse_policy("deny Unknown core").rules[0].effects, ["Unknown"].into_iter().collect());
1478        assert!(parse_policy("deny\ndeny   \n").rules.is_empty());
1479        // a `deny` whose first token is a non-effect names no effect -> dropped, NOT a pure rule.
1480        assert!(parse_policy("deny notaneffect scope").rules.is_empty());
1481        // the first non-effect token ENDS the rule: a later effect token is not collected.
1482        let p2 = parse_policy("deny Net foo Db");
1483        assert_eq!(p2.rules[0].effects, ["Net"].into_iter().collect::<BTreeSet<_>>());
1484        assert_eq!(p2.rules[0].scope.as_deref(), Some("foo"));
1485        // NBSP is NOT a token separator (only ASCII White_Space is) — pinned to MATCH Java, which
1486        // drops it: a `deny\u{a0}Net` is one token `deny\u{a0}Net`, NOT `deny` + `Net`, so it names no
1487        // known effect and is dropped. Splitting on Unicode whitespace here would let candor see a deny
1488        // the JVM engine doesn't — a gateless-divergence between impls. (See is_ascii_ws.)
1489        assert!(parse_policy("deny\u{a0}Net core").rules.is_empty(),
1490                "an NBSP between deny and the effect must NOT split into separate tokens");
1491        // The NBSP rides INTO the scope token rather than separating it: `deny Net\u{a0}domain` is
1492        // `deny` + `Net` + `\u{a0}domain` — Net is the effect, the scope keeps the NBSP verbatim.
1493        let nb = parse_policy("deny Net \u{a0}domain");
1494        assert_eq!(nb.rules.len(), 1);
1495        assert_eq!(nb.rules[0].effects, ["Net"].into_iter().collect::<BTreeSet<_>>());
1496        assert_eq!(nb.rules[0].scope.as_deref(), Some("\u{a0}domain"));
1497    }
1498
1499    #[test]
1500    fn reason_scoped_unknown_parses() {
1501        use super::ReasonClass::*;
1502        // `Unknown[dispatch,indirect]` narrows the Unknown membership to those classes.
1503        let p = parse_policy("deny Net Unknown[dispatch,indirect] dom\n");
1504        let r = &p.rules[0];
1505        assert!(r.effects.contains("Unknown") && r.effects.contains("Net"));
1506        assert_eq!(r.scope.as_deref(), Some("dom"));
1507        assert_eq!(r.unknown_classes, [Dispatch, Indirect].into_iter().collect());
1508        // bare `Unknown` and `Unknown[*]` ⇒ empty filter (all classes).
1509        assert!(parse_policy("deny Net Unknown dom\n").rules[0].unknown_classes.is_empty(), "bare Unknown ⇒ all");
1510        assert!(parse_policy("deny Net Unknown[*] dom\n").rules[0].unknown_classes.is_empty(), "Unknown[*] ⇒ all");
1511        // `dynamic` alias = every genuine class incl. unresolved, excl. setup.
1512        assert_eq!(
1513            parse_policy("deny Net Unknown[dynamic] dom\n").rules[0].unknown_classes,
1514            [Reflect, Dispatch, Indirect, Native, Unresolved].into_iter().collect()
1515        );
1516        // config `unknown-alias` (⟨0.19⟩): a user-defined name resolves; a reserved name is rejected.
1517        let aliases = super::parse_unknown_aliases(
1518            "unknown-alias risky = reflect,native\nunknown-alias telemetry = indirect\nunknown-alias reflect = native\n");
1519        assert_eq!(aliases.get("risky"), Some(&[Reflect, Native].into_iter().collect()));
1520        assert_eq!(aliases.get("telemetry"), Some(&[Indirect].into_iter().collect()));
1521        assert!(!aliases.contains_key("reflect"), "a config alias may not shadow a class token");
1522        // the `unknown-alias` KEY matches case-insensitively (parity with java/ts/swift, which lowercase it)
1523        assert_eq!(super::parse_unknown_aliases("Unknown-Alias hot = native\n").get("hot"),
1524                   Some(&[Native].into_iter().collect()), "the unknown-alias key must match case-insensitively");
1525        let pr = super::parse_policy_with_aliases("deny Net Unknown[risky] api\n", &aliases);
1526        assert_eq!(pr.rules[0].unknown_classes, [Reflect, Native].into_iter().collect());
1527        // an UNDEFINED alias name is dropped-with-warning → empty filter (behaves like bare Unknown[*])
1528        assert!(super::parse_policy_with_aliases("deny Net Unknown[nope] api\n", &aliases).rules[0].unknown_classes.is_empty());
1529        // classify: raw reason tokens → normative classes (mirrors java ReasonClass.classify).
1530        assert_eq!(ReasonClass::classify("reflect:Class.forName"), Reflect);
1531        assert_eq!(ReasonClass::classify("native:extern fn"), Native);
1532        assert_eq!(ReasonClass::classify("callback:unresolved call"), Indirect);
1533        assert_eq!(ReasonClass::classify("ambiguous:same-name local defs"), Dispatch);
1534        assert_eq!(ReasonClass::classify("unresolved"), Unresolved);
1535        assert_eq!(ReasonClass::classify("whatever-new"), Unresolved); // conservative catch-all
1536    }
1537
1538    /// THE CONTROL SPEC §4 ⟨0.24⟩ MAKES A SHOULD: a FABRICATED, off-vocabulary kind must still behave as
1539    /// §2 forward-compatibility requires. Without it, "added a fifth kind" and "stopped checking the kind
1540    /// set" are the same diff — the classifier is one `_ =>` arm away from either.
1541    ///
1542    /// SOUNDNESS R490 — THE TYPED HALF NOW EXISTS (`Kind`), AND THIS IS THE CONTROL ITS OWN DOC COMMENT
1543    /// SAID TO ADD AT THE SAME COMMIT. The JVM engine's failure was a string classifier correct on
1544    /// `ambiguous` since July beside a typed `Kind` enum that lacked the kind entirely — one token
1545    /// classified two ways inside one engine, concealed precisely because the string half was right. That
1546    /// is unreachable here only while the two halves are the SAME table, so the round-trip below asserts
1547    /// it for every kind rather than for the ones someone remembered: `Kind::ALL` is what `classify`
1548    /// matches on, and what this loop iterates.
1549    #[test]
1550    fn off_vocabulary_kinds_round_trip_and_classify_through_the_catch_all() {
1551        use ReasonClass::*;
1552        // A kind no engine emits and no section names. §2: tolerated, and classified CONSERVATIVELY —
1553        // `unresolved`, the catch-all, so a narrowed `Unknown[unresolved]`/`[dynamic]`/`[*]` still bites it.
1554        assert_eq!(ReasonClass::classify("banana:whatever"), Unresolved);
1555        assert_eq!(ReasonClass::classify("banana:dispatch of a banana"), Unresolved,
1556                   "a canonical kind appearing in the DETAIL must not leak into the classification");
1557        // …and it must not be swallowed into a narrower class. These are the four wrong answers.
1558        for wrong in [Reflect, Dispatch, Indirect, Native] {
1559            assert_ne!(ReasonClass::classify("banana:whatever"), wrong);
1560        }
1561        // The five §4 ⟨0.24⟩ kinds all classify, and `ambiguous` is the fifth — pinned beside the
1562        // fabricated one deliberately: one arm chain answers both, so a change that stops distinguishing
1563        // them fails here rather than in the field.
1564        assert_eq!(ReasonClass::classify("reflect:x"), Reflect);
1565        assert_eq!(ReasonClass::classify("native:x"), Native);
1566        assert_eq!(ReasonClass::classify("dispatch:Owner.member"), Dispatch);
1567        assert_eq!(ReasonClass::classify("callback:x"), Indirect);
1568        assert_eq!(ReasonClass::classify("ambiguous:x"), Dispatch);
1569        // ⟨0.24⟩ `dep:<hash>` / `dep-stale:<pkg>` are REGISTERED §4 kinds, not migration ones — swift
1570        // emits them per dependency ENTRY, and this engine CONSUMES swift/ts reports through
1571        // candor-query. §6.2 pins their class as `unresolved`, which is where the catch-all lands them;
1572        // pinned so a future prefix arm cannot move them without saying so.
1573        assert_eq!(ReasonClass::classify("dep:9f2c1a"), Unresolved);
1574        assert_eq!(ReasonClass::classify("dep-stale:somepkg"), Unresolved);
1575
1576        // ── SOUNDNESS R490: THE TYPED HALF AND THE STRING HALF ARE ONE TABLE ────────────────────────
1577        // Every kind this engine can WRITE must classify to the class it declares, through the same
1578        // `classify` a consumer runs — asserted over `Kind::ALL`, so a kind added without a class, or a
1579        // class arm changed without the producer, fails here. A hand-listed version of this loop is the
1580        // bug it is guarding against.
1581        assert_eq!(Kind::ALL.len(), 5, "SPEC §4 ⟨0.7⟩'s kind set is CLOSED at five");
1582        for k in Kind::ALL {
1583            assert_eq!(ReasonClass::classify(&k.reason("some detail")), k.class(),
1584                       "kind {:?} spells a reason its own classifier does not agree with", k);
1585            assert!(!k.token().contains(':'), "a kind token cannot contain the `kind:detail` separator");
1586        }
1587        // The one NORMATIVE detail shape (§4): `dispatch:<owner-type>.<member>`, dotted, which is what
1588        // §3.1's dispatch frontier parses. Pinned as a STRING because that is what reaches the report.
1589        assert_eq!(Kind::dispatch_on("Store", "put"), "dispatch:Store.put");
1590        assert_eq!(ReasonClass::classify(&Kind::dispatch_on("Store", "put")), Dispatch);
1591        // …and the reserved DOT-FREE form stays a `dispatch:` (⟨0.24⟩): it is the "no owner could be
1592        // formed at all" spelling, free text, not conformance-compared — but still class `dispatch`, so
1593        // re-kinding it to `callback:` would silently narrow every `deny E Unknown[dispatch]` in the field.
1594        assert_eq!(ReasonClass::classify(&Kind::Dispatch.reason("untyped cross-package receiver")), Dispatch);
1595    }
1596
1597    #[test]
1598    fn net_destination_class_parses_and_classifies() {
1599        // `Net[unknown-host,known-telemetry]` narrows the Net membership to those destination classes.
1600        let p = parse_policy("deny Net[unknown-host,known-telemetry] dom\n");
1601        let r = &p.rules[0];
1602        assert!(r.effects.contains("Net"));
1603        assert_eq!(r.scope.as_deref(), Some("dom"));
1604        assert_eq!(
1605            r.net_classes,
1606            ["unknown-host", "known-telemetry"].iter().map(|s| s.to_string()).collect()
1607        );
1608        // bare `Net` and `Net[*]` ⇒ empty filter (all destinations).
1609        assert!(parse_policy("deny Net dom\n").rules[0].net_classes.is_empty(), "bare Net ⇒ all");
1610        assert!(parse_policy("deny Net[*] dom\n").rules[0].net_classes.is_empty(), "Net[*] ⇒ all");
1611        // an unknown destination-class is dropped-with-warning → empty filter (behaves like bare Net[*]).
1612        assert!(parse_policy("deny Net[nope] dom\n").rules[0].net_classes.is_empty());
1613        // the classifier: telemetry (subdomain-aware), model host, unresolved, and the config-partner path.
1614        let no_partners = BTreeSet::new();
1615        assert_eq!(crate::net_dest_class("sentry.io", &no_partners), "known-telemetry");
1616        assert_eq!(crate::net_dest_class("us.i.posthog.com", &no_partners), "known-telemetry"); // 0.20.1 corpus-grown
1617        assert_eq!(crate::net_dest_class("o1.ingest.sentry.io", &no_partners), "known-telemetry");
1618        assert_eq!(crate::net_dest_class("api.openai.com", &no_partners), "known-partner", "a model host is known-partner");
1619        assert_eq!(crate::net_dest_class("evil.example.com", &no_partners), "unknown-host");
1620        let partners: BTreeSet<String> = ["api.stripe.com".to_string()].into_iter().collect();
1621        assert_eq!(crate::net_dest_class("api.stripe.com", &partners), "known-partner", "config-declared partner");
1622        assert_eq!(crate::net_dest_class("api.stripe.com", &no_partners), "unknown-host", "partner is config-only");
1623        // `net-partner` config parsing: host-normalized, case-insensitive key, multi-value.
1624        let pset = super::parse_net_partners("net-partner Api.Stripe.com:443\nNET-PARTNER hooks.stripe.com\n");
1625        assert!(pset.contains("api.stripe.com") && pset.contains("hooks.stripe.com"));
1626    }
1627
1628    #[test]
1629    fn allowlist_parses() {
1630        let p = parse_policy(
1631            "allow Net in billing  api.stripe.com  hooks.stripe.com\n\
1632             allow Exec in ci  git\n\
1633             allow Fs in config  /etc/app\n\
1634             allow Net  github.com\n\
1635             allow Clock  whatever\n\
1636             allow Net in nohosts\n\
1637             allow\n",
1638        );
1639        assert_eq!(p.allow_rules.len(), 4); // Clock carries no literal surface — rejected; Db now does
1640        assert_eq!((p.allow_rules[0].effect, p.allow_rules[0].scope.as_deref()), ("Net", Some("billing")));
1641        assert_eq!(
1642            p.allow_rules[0].literals,
1643            ["api.stripe.com", "hooks.stripe.com"].iter().map(|s| s.to_string()).collect()
1644        );
1645        assert_eq!((p.allow_rules[1].effect, p.allow_rules[1].scope.as_deref()), ("Exec", Some("ci")));
1646        assert!(p.allow_rules[1].literals.contains("git"));
1647        assert_eq!((p.allow_rules[2].effect, p.allow_rules[2].scope.as_deref()), ("Fs", Some("config")));
1648        assert_eq!((p.allow_rules[3].effect, p.allow_rules[3].scope.is_none()), ("Net", true));
1649
1650        let set = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<BTreeSet<_>>();
1651        assert!(literal_allowed("Net", "api.stripe.com:443", &set(&["api.stripe.com"])));
1652        // IPv6: a bare literal is matched WHOLE (no first-colon collapse), so a different address in the
1653        // same block is NOT accepted; a bracketed `[host]:port` matches the bare host. (/code-review.)
1654        assert!(literal_allowed("Net", "2001:db8::aa", &set(&["2001:db8::aa"])));
1655        assert!(!literal_allowed("Net", "2001:db8::ff", &set(&["2001:db8::aa"])));
1656        assert!(!literal_allowed("Net", "2001:dead::1", &set(&["2001:db8::aa"])));
1657        assert!(literal_allowed("Net", "[2001:db8::aa]:443", &set(&["2001:db8::aa"])));
1658        assert_eq!(host_part("2001:db8::aa"), "2001:db8::aa");
1659        assert_eq!(host_part("[2001:db8::aa]:443"), "2001:db8::aa");
1660        assert_eq!(host_part("api.stripe.com:443"), "api.stripe.com");
1661        assert!(literal_allowed("Exec", "/usr/bin/git", &set(&["git"])));
1662        assert!(!literal_allowed("Exec", "/usr/bin/curl", &set(&["git"])));
1663        assert!(literal_allowed("Fs", "/etc/app/conf.toml", &set(&["/etc/app"])));
1664        assert!(!literal_allowed("Fs", "/etc/shadow", &set(&["/etc/app"])));
1665        assert_eq!(cmd_base("/usr/bin/git"), "git");
1666    }
1667
1668    #[test]
1669    fn layering_rule_parses() {
1670        let p = parse_policy(
1671            "forbid domain -> infra\n\
1672             forbid  app::web  ->  app::db \n\
1673             forbid domain infra\n\
1674             forbid domain ->\n\
1675             forbid\n",
1676        );
1677        assert_eq!(p.layer_rules.len(), 2);
1678        assert_eq!((p.layer_rules[0].from.as_str(), p.layer_rules[0].to.as_str()), ("domain", "infra"));
1679        assert_eq!((p.layer_rules[1].from.as_str(), p.layer_rules[1].to.as_str()), ("app::web", "app::db"));
1680    }
1681
1682    /// ⟨0.29⟩ `only <A> -> <B> [<C> …]` — the PERMISSION form. The tail is a LIST, which is the whole
1683    /// ergonomic difference from `forbid`; a missing arrow or an EMPTY tail is dropped rather than read
1684    /// as "A may reach nothing", a rule far likelier to be a typo than an intention.
1685    #[test]
1686    fn parses_the_only_permission_form_and_drops_the_malformed() {
1687        let p = parse_policy(
1688            "only model -> util\n\
1689             only  app::web  ->  app::db  app::dto \n\
1690             only model util\n\
1691             only model ->\n\
1692             only\n",
1693        );
1694        assert_eq!(p.only_rules.len(), 2, "the two well-formed lines, and only those");
1695        assert_eq!(p.only_rules[0].from.as_str(), "model");
1696        assert_eq!(p.only_rules[0].to, vec!["util".to_string()]);
1697        assert_eq!(p.only_rules[1].from.as_str(), "app::web");
1698        assert_eq!(p.only_rules[1].to, vec!["app::db".to_string(), "app::dto".to_string()],
1699                   "every token after the arrow is a permitted scope");
1700        // …and an `only` line is a RULE for the zero-rule refusal: a policy holding one is ARMED, so a
1701        // route that counted only deny/allow/forbid would call this file empty and refuse a live gate.
1702        assert!(!p.rules.is_empty() || !p.only_rules.is_empty(),
1703                "an only-only policy must not read as a zero-rule file");
1704    }
1705
1706    #[test]
1707    fn scope_matches_by_segment_not_substring() {
1708        assert!(scope_matches("app::domain::handle", "domain"));
1709        assert!(scope_matches("domain::handle", "domain"));
1710        assert!(scope_matches("app::domain", "domain"));
1711        assert!(scope_matches("crate::domain_logic", "domain"));
1712        assert!(!scope_matches("app::subdomain::handle", "domain"));
1713        assert!(!scope_matches("app::not_my_domain::f", "domain"));
1714        // multi-segment: intermediates exact, last is a prefix, contiguous.
1715        assert!(scope_matches("crate::net::client::send", "net::client"));
1716        assert!(scope_matches("crate::net::client_pool::get", "net::client"));
1717        assert!(!scope_matches("crate::net::server::send", "net::client"));
1718        assert!(!scope_matches("crate::network::client::send", "net::client"));
1719        assert!(!scope_matches("crate::net::x::client", "net::client"));
1720        assert!(!scope_matches("net", "net::client"));
1721        // DOTTED names (JVM/Swift/TS reports `candor-query` consumes): a scope must match across `.` too,
1722        // else a scoped deny/pure rule is silently inert → whatif false-green (gate-evasion). Both a
1723        // `.`-written and a `::`-written scope must match a dotted name.
1724        assert!(scope_matches("com.acme.domain.Pricing.quote", "domain"));
1725        assert!(scope_matches("com.acme.domain.Pricing.quote", "acme.domain"));
1726        assert!(scope_matches("com.acme.domain.Pricing.quote", "acme::domain"));
1727        assert!(scope_matches("com.acme.infra.Net.fetch", "infra.Net"));
1728        assert!(!scope_matches("com.acme.subdomain.h", "domain"));
1729        assert!(!scope_matches("com.acme.domain.h", "infra"));
1730    }
1731
1732    #[test]
1733    fn fs_path_covered_respects_boundaries() {
1734        assert!(fs_path_covered("/etc/app", "/etc/app"));
1735        assert!(fs_path_covered("/etc/app", "/etc/app/cfg.toml"));
1736        assert!(fs_path_covered("/etc/app/", "/etc/app/cfg"));
1737        assert!(!fs_path_covered("/etc/app", "/etc/apppwned"));
1738        assert!(!fs_path_covered("/etc/app", "/etc/application/x"));
1739        assert!(!fs_path_covered("/etc/app/cfg", "/etc/app"));
1740        assert!(!fs_path_covered("/etc/app", "/etc/app/../passwd"));
1741        assert!(fs_path_covered("/", "/etc/app/x"));
1742        assert!(!fs_path_covered("etc/app", "/etc/app/cfg"));
1743        assert!(!fs_path_covered("/etc/app", "etc/app/cfg"));
1744        assert!(fs_path_covered("etc/app", "etc/app/cfg"));
1745    }
1746
1747    /// ⟨0.24⟩ THE PROVABLE-PURITY DISCLOSURE MUST ASK THE GATE WHAT "PASSES" MEANS — SPEC §6.2, and both
1748    /// directions in ONE test, because killing an over-charge is exactly where a silent under-report gets
1749    /// introduced and the fixture proving the fabrication is closed cannot show the reach closed with it.
1750    ///
1751    /// A hole is a function that PASSES its rule while `Unknown`. `unverified_hole_rule` used to compute
1752    /// PASSES from `r.effects` alone — the pre-⟨0.19⟩ question, asked after two rungs gave rules a
1753    /// NARROWING FILTER — so a rule the gate TOLERATES was read here as violated and the hole was DELETED
1754    /// from the disclosure. MEASURED 2026-07-28: `deny Unknown[reflect]` over an `indirect` hole → gate
1755    /// exit 0, `unverified` "every function in a pure/deny layer is PROVABLY clean ✓".
1756    ///
1757    /// ROW 1 (the fix) — the filter does NOT match, so the gate tolerates and this IS a hole.
1758    /// ROW 2 (the mirror) — the SAME rule, SAME function, filter spelled to MATCH: the gate fires, so it
1759    /// is a violation and NOT a hole. Without row 2 the fix is satisfied by a predicate that calls
1760    /// everything a hole, which is the mirror over-report of the thing being fixed.
1761    /// ROW 3 — the ⟨0.20⟩ `Net[dest…]` filter, the same shape on the other narrowing axis.
1762    /// ROW 4 — no filter at all: byte-identical to pre-⟨0.24⟩, which is what keeps conformance PARTs
1763    /// 12c/12d (four-way) from moving.
1764    #[test]
1765    fn a_narrowed_rule_the_gate_tolerates_is_a_hole_and_the_one_it_fires_on_is_not() {
1766        let effs = ["Unknown"];
1767        let indirect: BTreeSet<String> = ["indirect".to_string()].into_iter().collect();
1768        let hole = |src: &str, classes: Option<&BTreeSet<String>>, nets: &[String]| -> Option<String> {
1769            let p = parse_policy(src);
1770            unverified_hole_rule("app::go", &effs, classes, nets, &p.rules).map(|r| rule_and_upgrade(r).1)
1771        };
1772
1773        // ROW 1 — tolerated by the gate (indirect ∉ {reflect}) ⇒ a hole, and the upgrade WIDENS the
1774        // filter rather than appending a second `Unknown`.
1775        assert_eq!(
1776            hole("deny Unknown[reflect]\n", Some(&indirect), &[]).as_deref(),
1777            Some("deny Unknown"),
1778            "a rule the gate TOLERATES leaves the function unproven — that is the disclosure's whole subject"
1779        );
1780
1781        // ROW 2 — THE MIRROR. Same rule, same signature, filter spelled to match: the gate FIRES, so this
1782        // is a violation and the disclosure must stay silent about it.
1783        assert_eq!(
1784            hole("deny Unknown[indirect]\n", Some(&indirect), &[]),
1785            None,
1786            "a rule the gate FIRES on is a violation, not a hole — filter-awareness must not start \
1787             disclosing the gate's own findings back as unproven passes"
1788        );
1789        assert_eq!(hole("deny Unknown[dynamic]\n", Some(&indirect), &[]), None, "`dynamic` covers indirect");
1790
1791        // ROW 3 — the ⟨0.20⟩ destination filter, both ways, on a fn carrying Net BESIDE its Unknown.
1792        let netfn = ["Net".to_string(), "Unknown".to_string()];
1793        let telemetry = vec!["known-telemetry".to_string()];
1794        let p = parse_policy("deny Net[unknown-host]\n");
1795        assert_eq!(
1796            unverified_hole_rule("app::go", &netfn, Some(&indirect), &telemetry, &p.rules)
1797                .map(|r| rule_and_upgrade(r).1)
1798                .as_deref(),
1799            Some("deny Net[unknown-host] Unknown"),
1800            "a `Net[dest…]` the fn's destinations do not match is tolerated, so the Unknown beside it is a hole"
1801        );
1802        let p = parse_policy("deny Net[known-telemetry]\n");
1803        assert_eq!(
1804            unverified_hole_rule("app::go", &netfn, Some(&indirect), &telemetry, &p.rules).map(|r| r.raw.clone()),
1805            None,
1806            "MIRROR: the matching destination filter FIRES, so it is a violation and not a hole"
1807        );
1808
1809        // ROW 4 — UNFILTERED, unchanged. `deny Unknown` fires on every Unknown (never a hole); `pure` and
1810        // `deny Fs` pass a fn with no real effect (always a hole) — the forms PARTs 12c/12d pin four-way.
1811        assert_eq!(hole("deny Unknown\n", Some(&indirect), &[]), None);
1812        assert_eq!(hole("pure\n", Some(&indirect), &[]).as_deref(), Some("deny Unknown"));
1813        assert_eq!(hole("deny Net Db  domain\ndeny Fs\n", Some(&indirect), &[]).as_deref(), Some("deny Fs Unknown"));
1814        assert_eq!(
1815            hole("deny Net Db  go\n", Some(&indirect), &[]).as_deref(),
1816            Some("deny Db Net Unknown go"),
1817            "the sorted multi-effect upgrade PART 12c-deny pins in all four engines"
1818        );
1819
1820        // A WITHHELD filter — no class set to read — counts as PASSING, so the hole is disclosed rather
1821        // than dropped. The gate withholds there too; between an advisory note that speaks and one that
1822        // goes quiet over a rule that never ran, only the first stays true.
1823        assert_eq!(hole("deny Unknown[reflect]\n", None, &[]).as_deref(), Some("deny Unknown"));
1824    }
1825}
1826
1827// ── ⟨0.27⟩ SPEC §3.4 `engine` — the engine↔baseline coupling ─────────────────────────────────────
1828/// What an `engine` pin says about the build that is running. Data, not a print-and-exit, so every
1829/// branch is testable — including the two that MUST NOT change the exit code.
1830#[derive(Debug, PartialEq, Eq)]
1831pub enum PinVerdict {
1832    /// No pin, or a pin qualified for another implementation. Today's behaviour, exactly.
1833    Absent,
1834    Match,
1835    /// A different version — the engine↔baseline coupling is broken. Exit 2 (UNEVALUABLE, never 1).
1836    Mismatch,
1837    /// Present but unreadable (`engine latest`, a bare `engine`, trailing junk). Exit 2: a pin that
1838    /// cannot be read is a guard the operator believes is on. This is the one place §6.2's
1839    /// warn-and-skip posture INVERTS — skipping a key that ADDS something costs that key; skipping a
1840    /// PIN costs the guard.
1841    Malformed,
1842    /// Well-formed, and this build cannot state its own release. UNANSWERABLE — §3.1's rule applies:
1843    /// disclosed, never scored, INCLUDING as satisfied.
1844    Undetermined,
1845}
1846
1847/// The pin that applies to `impl_name` — the qualified form wins over the unqualified one, and the
1848/// LAST occurrence wins (matching candor-java's map semantics). Two lines that DISAGREE about the same
1849/// key return a value that cannot parse, so they surface as [`PinVerdict::Malformed`] rather than one
1850/// silently discarding the other: two lines disagreeing about which engine to run is not a preference
1851/// to resolve, it is a question the config leaves unanswered.
1852pub fn engine_pin_for(text: &str, impl_name: &str) -> Option<String> {
1853    const IMPLS: [&str; 5] = ["java", "rust", "ts", "swift", "agents"];
1854    let (mut wild, mut qual): (Option<String>, Option<String>) = (None, None);
1855    let mut bad = false;
1856    for raw in text.lines() {
1857        let line = raw.split('#').next().unwrap_or("").trim();
1858        if line.is_empty() {
1859            continue;
1860        }
1861        let mut it = line.split_whitespace();
1862        if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("engine")) {
1863            continue;
1864        }
1865        let rest: Vec<&str> = it.collect();
1866        let slot = |cur: &mut Option<String>, v: String| {
1867            if cur.as_ref().is_some_and(|p| *p != v) {
1868                *cur = Some(format!("{} / {v}", cur.as_ref().unwrap()));
1869            } else {
1870                *cur = Some(v);
1871            }
1872        };
1873        // 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.
1874        if let Some(head) = rest.first() {
1875            if IMPLS.contains(&head.to_ascii_lowercase().as_str()) {
1876                if head.eq_ignore_ascii_case(impl_name) {
1877                    if rest.len() == 2 { slot(&mut qual, rest[1].to_string()); } else { bad = true; }
1878                }
1879                continue;                                     // another impl's line, whatever follows it
1880            }
1881        }
1882        match rest.len() {
1883            0 => bad = true,                                  // a bare `engine` line
1884            1 => slot(&mut wild, rest[0].to_string()),        // engine <version>
1885            _ => bad = true,                                  // trailing junk / unknown qualifier
1886        }
1887    }
1888    if bad {
1889        return Some("<unreadable>".to_string());
1890    }
1891    // AN UNREADABLE UNQUALIFIED LINE IS NOT HIDDEN BY A QUALIFIED PIN. `qual ?? wild` returned the qua
1892    // lified value, so `engine garbage` beside a good qualified line passed SILENTLY here while candor-java ex
1893    // 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.
1894    if let Some(w) = &wild {
1895        if normalize_version(w).is_none() { return Some(w.clone()); }
1896    }
1897    qual.or(wild)
1898}
1899
1900/// [`PinVerdict`] for `pin` against `running`. Pure: no printing, no exit.
1901pub fn pin_verdict(pin: Option<&str>, running: &str) -> PinVerdict {
1902    let Some(pin) = pin else { return PinVerdict::Absent };
1903    let Some(want) = normalize_version(pin) else { return PinVerdict::Malformed };
1904    if running.trim().is_empty() || running == "unknown" {
1905        return PinVerdict::Undetermined;
1906    }
1907    if want == normalize_version(running).unwrap_or_else(|| running.trim().to_string()) {
1908        PinVerdict::Match
1909    } else {
1910        PinVerdict::Mismatch
1911    }
1912}
1913
1914/// A pin token → its comparable form, or None when it is not a version at all. A leading `v` is
1915/// optional (the GitHub-tag `v0.27.0` and the crate `0.27.0` are the same pin) and a two-part `0.27`
1916/// means `0.27.0`. Anything else — `latest`, a branch name — is MALFORMED rather than a version that
1917/// can never match: the difference decides whether the operator reads "wrong version" or "that is not
1918/// a version".
1919fn normalize_version(raw: &str) -> Option<String> {
1920    let s = raw.trim().strip_prefix(['v', 'V']).unwrap_or_else(|| raw.trim());
1921    let parts: Vec<&str> = s.split('.').collect();
1922    if !(parts.len() == 2 || parts.len() == 3) || !parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) {
1923        return None;
1924    }
1925    Some(if parts.len() == 2 { format!("{s}.0") } else { s.to_string() })
1926}