Skip to main content

candor_classify/
policy.rs

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