openlatch-client 0.6.5

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! The path → `TargetClass` resolver — plan 02 §2f, PRD §Client evaluator.
//!
//! Roots are bundle facts the customer can extend (`env_selectors`,
//! `data_store_roots`, `classified_sources`), and **every matching row adds its
//! class** (AZ-4 D-I16-29: a path matching several patterns carries every class,
//! so an added pattern never masks a seed class — `.npmrc` is `agent_config` and
//! `secret_material` at once). The classes come out in the order of the rows below
//! — the order the resolver used to stop at — so the first one is what a
//! first-match resolver would have answered.
//!
//! | Order | Class | Where it comes from |
//! | ----- | ----- | ------------------- |
//! | 1 | `secret_material` | catalogue target entries |
//! | 2 | `agent_config` | catalogue target entries |
//! | 3 | `system_path` | code: `/`, top-level dirs, home root, drive roots, cwd and its parents, `$PATH` dirs, `/etc` |
//! | 4 | `classified_source` | code: anything in the `classified_sources` fact |
//! | 5 | `data_store` | catalogue target entries, plus the `data_store_roots` fact |
//! | 6 | `workspace_file` | code, **only when no other class matched**: under the agent's working directory or additional directories |
//!
//! A catalogue target of any other class sorts after these.
//!
//! # Rows 3 and 6 read `Event.env`, and nothing else
//!
//! They need the home root, the cwd and its parents, the `$PATH` dirs, and the
//! agent's working directory — host state the Event carries as **declared
//! strings**. This resolver never stats a path and never walks a tree
//! (guarantee G4): the hook path walks up from the payload's working directory
//! and this one must not. A path that does not exist classifies exactly like one
//! that does, because neither is ever looked at.
//!
//! **With no `env` on the Event, neither row fires, and an absolute path no other
//! row places resolves to unknown — never a guessed `workspace_file`.**
//!
//! # portability-ok: these are classification data, not paths this process resolves
//!
//! `ci/check-portability.py` reads `/var/lib/mongodb/**`, `/etc/**` and `~/` as
//! POSIX assumptions, and everywhere else in this crate it would be right. Here
//! the whole file IS the resolver table: these literals are a description of
//! what a path MEANS, matched as text against a string the caller declared. The
//! engine never touches a filesystem at all — `ci/check-engine-purity.py` rule
//! `filesystem` enforces that, and it is a stronger claim than the waiver needs,
//! because the path classifier reads DECLARED STRINGS ONLY: a path that does not
//! exist classifies exactly like one that does. So a second gate proves what
//! this one is being asked to take on trust.
//!
//! The Windows rows sit in the same table for the same reason (`C:\\`,
//! `C:\\Windows\\**`) — a Windows agent's paths are classified by a Linux daemon
//! whenever a replay crosses hosts, so both vocabularies have to be present on
//! every platform. Waiving per file rather than per line is deliberate: 24
//! identical trailing comments would bury the one line where a future reader
//! should have thought harder.

use crate::generated::types::TargetClass;

use super::super::facts::FactSet;
use super::super::types::EventEnv;
use super::catalogue::{Catalogue, Origin, PatternKind};

// ── What stays in code ───────────────────────────────────────────────
//
// Rows 1, 2 and 5 of the table above are **catalogue targets** now (AZ-4
// D-I16-28): `secret_material`, `agent_config` and `data_store` patterns arrive
// in the bundle, and the evaluator holds none of them. What is left is the part
// that is not a lookup — row 3, whose roots come from `Event.env`, row 4, which
// reads a fact, row 5's `data_store_roots` fact, and row 6's fallthrough. `const`,
// not a `OnceLock`: derived from nothing and retained across nothing, which is
// what `ci/check-engine-purity.py` rule `global-state` is asking for.

/// Row 3, the part that is a pattern rather than a piece of `env`.
///
/// **`/var` is here and `/var/**` is not**, deliberately: `/var/lib/postgresql/**`
/// is a `data_store` pattern, and a `/var/**` seed would shadow it from row 3 and
/// turn every database directory into a `system_path`.
pub const SYSTEM_PATH_GLOBS: &[&str] = &[
    "/",
    "/etc",
    "/etc/**",
    "/usr",
    "/usr/**",
    "/bin",
    "/bin/**",
    "/sbin",
    "/sbin/**",
    "/lib",
    "/lib/**",
    "/opt",
    "/opt/**",
    "/boot",
    "/boot/**",
    "/proc",
    "/proc/**",
    "/sys",
    "/sys/**",
    "/var",
    "/dev",
    "/dev/**",
    "C:\\",
    "C:\\Windows\\**",
];

// ── Glob matching ────────────────────────────────────────────────────

/// `globset` semantics narrowed to what the seed lists use: `**` crosses `/`,
/// `*` and `?` do not, every other character is a literal.
///
/// A pattern that starts with `**/` also matches without that prefix, so
/// `**/.npmrc` matches a relative `.npmrc` (AZ-4 D-6). Matching stays
/// case-sensitive with `/` separators.
///
/// `{a,b}` alternation and `[…]` classes are deliberately **not** supported, and
/// a brace or a bracket matches itself. They would serve one seed pattern; a
/// seed list that writes its three roots out in full costs a reader nothing,
/// while two extra pattern syntaxes cost every reader a translation.
///
/// Hand-rolled rather than `globset::Glob`: the whole matcher is thirty lines,
/// it needs no compile step to cache, and it cannot disagree with the oracle's
/// `glob_to_regex` about a corner it never implemented.
pub fn glob_match(pattern: &str, value: &str) -> bool {
    let value: Vec<char> = value.chars().collect();
    let full: Vec<char> = pattern.chars().collect();
    if match_from(&full, 0, &value, 0) {
        return true;
    }
    match pattern.strip_prefix("**/") {
        Some(rest) => {
            let rest: Vec<char> = rest.chars().collect();
            match_from(&rest, 0, &value, 0)
        }
        None => false,
    }
}

fn match_from(pattern: &[char], mut pi: usize, value: &[char], mut vi: usize) -> bool {
    while pi < pattern.len() {
        if pattern[pi] == '*' {
            if pattern.get(pi + 1) == Some(&'*') {
                // `**` — any sequence, `/` included.
                let rest = pi + 2;
                if rest == pattern.len() {
                    return true;
                }
                return (vi..=value.len()).any(|k| match_from(pattern, rest, value, k));
            }
            // `*` — any sequence that does not cross a `/`.
            let rest = pi + 1;
            let mut k = vi;
            loop {
                if match_from(pattern, rest, value, k) {
                    return true;
                }
                if k >= value.len() || value[k] == '/' {
                    return false;
                }
                k += 1;
            }
        }
        let Some(&ch) = value.get(vi) else {
            return false;
        };
        if pattern[pi] == '?' {
            if ch == '/' {
                return false;
            }
        } else if pattern[pi] != ch {
            return false;
        }
        pi += 1;
        vi += 1;
    }
    vi == value.len()
}

// ── The host context rows 3 and 6 need ───────────────────────────────

/// [`EventEnv`] flattened into the four strings the resolver reads, so a caller
/// with no `env` and a caller with an empty one take the same path through here.
///
/// It also carries the catalogue the target patterns come from: with none, no
/// pattern row fires and only the rows that read `env` and facts can.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PathEnv<'a> {
    pub home: String,
    pub cwd: String,
    pub path_dirs: Vec<String>,
    pub additional_dirs: Vec<String>,
    pub catalogue: Option<&'a Catalogue>,
}

impl<'a> PathEnv<'a> {
    /// Read the declared strings off the Event. `None` yields the empty context,
    /// under which rows 3 and 6 simply do not fire.
    pub fn from_event(env: Option<&EventEnv>) -> PathEnv<'a> {
        let Some(env) = env else {
            return PathEnv::default();
        };
        PathEnv {
            home: env.home.clone().unwrap_or_default(),
            cwd: env.cwd.clone().unwrap_or_default(),
            path_dirs: env.path_dirs.clone(),
            additional_dirs: env.additional_dirs.clone(),
            catalogue: None,
        }
    }

    /// The same context, resolving target patterns against `catalogue`.
    pub fn with_catalogue(mut self, catalogue: Option<&'a Catalogue>) -> PathEnv<'a> {
        self.catalogue = catalogue;
        self
    }
}

// ── Fact-supplied roots ──────────────────────────────────────────────

/// The roots a set-shaped fact supplies, or `[]` when it does not resolve.
///
/// A fact that cannot be resolved contributes **no** roots. It never contributes
/// a default: an unresolvable `data_store_roots` means the customer's extra roots
/// are unknown, not that they are empty-and-therefore-fine — and the resulting
/// coverage gap on the path is what the atom's `on_inconclusive` then decides.
///
/// Staleness and the validity window are [`facts::resolve_set`]'s, read against
/// the frame's own `now_ms` off the [`FactSet`]. The classifier has no `now_ms`
/// parameter of its own and must not grow one: a second timestamp is a second
/// answer to "is this fact fresh?".
pub fn fact_members(facts: &FactSet, fact_id: &str) -> Vec<String> {
    super::super::facts::resolve_set(facts, fact_id, facts.now_ms).unwrap_or_default()
}

// ── The resolver ─────────────────────────────────────────────────────

/// Whether `path` is `root` or sits under it. Pure string comparison.
fn under(path: &str, root: &str) -> bool {
    if root.is_empty() {
        return false;
    }
    path == root || path.starts_with(&format!("{}/", root.trim_end_matches('/')))
}

fn same_dir(left: &str, right: &str) -> bool {
    !left.is_empty() && left.trim_end_matches('/') == right.trim_end_matches('/')
}

/// `~` and `~/…` against the declared home. The home is a **declared string**,
/// so expanding against it stays inside guarantee G4.
///
/// The oracle only builds the other direction — an absolute path re-written
/// `~`-relative so a `~/.ssh/**` seed can match it — and so answers `unknown` on
/// `cp /etc/hosts ~/proj/notes.md` even with an `env` in hand. Both directions
/// are the same substitution; doing only one leaves a path the caller fully
/// described unplaceable.
fn expand_home(path: &str, home: &str) -> Option<String> {
    if home.is_empty() {
        return None;
    }
    if path == "~" {
        return Some(home.to_string());
    }
    path.strip_prefix("~/")
        .map(|rest| format!("{}/{rest}", home.trim_end_matches('/')))
}

/// The forms a path is matched in: itself and, with a declared home, its
/// `~`-relative and `~`-expanded forms.
fn candidates(path: &str, env: &PathEnv) -> Vec<String> {
    let mut out = vec![path.to_string()];
    if !env.home.is_empty() {
        if let Some(rest) = path.strip_prefix(env.home.as_str()) {
            out.push(format!("~{rest}"));
        }
        if let Some(expanded) = expand_home(path, &env.home) {
            out.push(expanded);
        }
    }
    out
}

/// One pattern against every form of the path.
///
/// Up to four combinations per pattern — the path and its `~`-relative form,
/// against the pattern and its `~`-expanded form — because a seed written
/// `~/.ssh/**` has to match `/home/dev/.ssh/id_rsa` and a seed written
/// `**/.ssh/**` has to match both. With no `home` only the literal patterns can
/// fire.
fn pattern_matches(pattern: &str, candidates: &[String], env: &PathEnv) -> bool {
    let expanded = match pattern.strip_prefix('~') {
        Some(rest) if !env.home.is_empty() => format!("{}{rest}", env.home),
        _ => pattern.to_string(),
    };
    candidates
        .iter()
        .any(|candidate| glob_match(pattern, candidate) || glob_match(&expanded, candidate))
}

fn match_any(path: &str, patterns: &[&str], env: &PathEnv) -> bool {
    let forms = candidates(path, env);
    patterns
        .iter()
        .any(|pattern| pattern_matches(pattern, &forms, env))
}

fn match_any_owned<I: IntoIterator<Item = String>>(path: &str, patterns: I, env: &PathEnv) -> bool {
    let forms = candidates(path, env);
    patterns
        .into_iter()
        .any(|pattern| pattern_matches(&pattern, &forms, env))
}

/// One class a path resolved to, and the catalogue targets that put it there
/// (alternatives; empty for a class a code row gave).
#[derive(Debug, Clone, PartialEq)]
pub struct PathClass {
    pub class: TargetClass,
    pub origins: Vec<Origin>,
}

/// The order the resolver's rows had, so the first class of a multi-class answer
/// is what a first-match resolver would have said.
fn rank(class: &str) -> u8 {
    match class {
        "secret_material" => 1,
        "agent_config" => 2,
        "system_path" => 3,
        "classified_source" => 4,
        "data_store" => 5,
        "workspace_file" => 6,
        _ => 7,
    }
}

fn add_class(out: &mut Vec<PathClass>, class: &str, origin: Option<&Origin>) {
    let existing = out.iter_mut().find(|c| c.class.0 == class);
    let entry = match existing {
        Some(entry) => entry,
        None => {
            out.push(PathClass {
                class: TargetClass(class.to_string()),
                origins: Vec::new(),
            });
            out.last_mut().expect("just pushed")
        }
    };
    if let Some(origin) = origin {
        if !entry.origins.contains(origin) {
            entry.origins.push(origin.clone());
        }
    }
}

/// Resolve one path to every target class it carries, or `[]` when no row places
/// it.
///
/// Returning nothing rather than guessing `workspace_file` is the whole point: an
/// absolute path the resolver cannot place is a coverage gap the caller turns
/// into an `unknown`, not a quietly-downgraded workspace write.
pub fn resolve_all(path: &str, env: &PathEnv, facts: &FactSet) -> Vec<PathClass> {
    if path.is_empty() {
        return Vec::new();
    }
    // `~/proj/x` and `/home/dev/proj/x` are the same path when the Event says
    // what home is; the row-3 and row-6 comparisons read the expanded form.
    let absolute = expand_home(path, &env.home).unwrap_or_else(|| path.to_string());
    let forms = candidates(path, env);
    let mut out: Vec<PathClass> = Vec::new();

    // Catalogue targets: every matching pattern adds its class (multi-class).
    if let Some(catalogue) = env.catalogue {
        let mut removed: Vec<&str> = Vec::new();
        for target in catalogue
            .targets
            .iter()
            .filter(|t| t.kind == PatternKind::Path)
        {
            if !pattern_matches(&target.pattern, &forms, env) {
                continue;
            }
            if target.narrow {
                removed.push(&target.target_class);
            } else {
                add_class(&mut out, &target.target_class, Some(&target.origin));
            }
        }
        out.retain(|c| !removed.contains(&c.class.0.as_str()));
    }

    // Row 3: the patterns, then `env`'s half — the home root, the cwd's PARENTS,
    // and the `$PATH` dirs.
    if match_any(path, SYSTEM_PATH_GLOBS, env)
        || same_dir(&absolute, &env.home)
        || (!env.cwd.is_empty() && !same_dir(&absolute, &env.cwd) && under(&env.cwd, &absolute))
        || env.path_dirs.iter().any(|dir| same_dir(&absolute, dir))
    {
        add_class(&mut out, "system_path", None);
    }
    if match_any_owned(path, fact_members(facts, "classified_sources"), env) {
        add_class(&mut out, "classified_source", None);
    }
    if fact_members(facts, "data_store_roots")
        .iter()
        .any(|root| under(&absolute, root))
    {
        add_class(&mut out, "data_store", None);
    }
    // Row 6 is the fallthrough: given only when nothing else matched.
    if out.is_empty()
        && ((!path.starts_with('/') && !path.starts_with('~') && !path.contains("://"))
            || under(&absolute, &env.cwd)
            || env.additional_dirs.iter().any(|dir| under(&absolute, dir)))
    {
        add_class(&mut out, "workspace_file", None);
    }
    out.sort_by_key(|c| rank(&c.class.0));
    out
}

/// The classes a URL's host carries through the catalogue's host patterns.
pub fn resolve_host(host: &str, env: &PathEnv) -> Vec<PathClass> {
    let mut out: Vec<PathClass> = Vec::new();
    let Some(catalogue) = env.catalogue else {
        return out;
    };
    let mut removed: Vec<&str> = Vec::new();
    for target in catalogue
        .targets
        .iter()
        .filter(|t| t.kind == PatternKind::Host)
    {
        if !super::catalogue::host_matches(&target.pattern, host) {
            continue;
        }
        if target.narrow {
            removed.push(&target.target_class);
        } else {
            add_class(&mut out, &target.target_class, Some(&target.origin));
        }
    }
    out.retain(|c| !removed.contains(&c.class.0.as_str()));
    out
}

/// Resolve one path to its first target class, or `None` when no row places it.
pub fn resolve(path: &str, env: Option<&EventEnv>, facts: &FactSet) -> Option<TargetClass> {
    resolve_with(path, &PathEnv::from_event(env), facts)
}

/// [`resolve`], against an already-flattened context.
pub fn resolve_with(path: &str, env: &PathEnv, facts: &FactSet) -> Option<TargetClass> {
    resolve_all(path, env, facts)
        .into_iter()
        .next()
        .map(|c| c.class)
}

#[cfg(test)]
mod tests {
    use super::*;

    use super::super::catalogue::fixtures::{seed_r1, seed_r1_plus};

    /// The seed-r1 catalogue on an empty host context.
    fn seeded() -> PathEnv<'static> {
        PathEnv::default().with_catalogue(Some(seed_r1()))
    }

    fn env() -> PathEnv<'static> {
        PathEnv {
            home: "/home/dev".to_string(),
            cwd: "/home/dev/proj".to_string(),
            path_dirs: vec!["/usr/local/bin".to_string()],
            additional_dirs: vec!["/srv/extra".to_string()],
            catalogue: Some(seed_r1()),
        }
    }

    fn class_of(path: &str, env: &PathEnv) -> Option<String> {
        resolve_with(path, env, &FactSet::default()).map(|c| c.0)
    }

    fn classes_of(path: &str, env: &PathEnv) -> Vec<String> {
        resolve_all(path, env, &FactSet::default())
            .into_iter()
            .map(|c| c.class.0)
            .collect()
    }

    #[test]
    fn double_star_crosses_a_slash_and_single_star_does_not() {
        assert!(glob_match("**/*.pem", "certs/nested/server.pem"));
        assert!(!glob_match("*.pem", "certs/server.pem"));
        assert!(glob_match("*.pem", "server.pem"));
        assert!(glob_match("**/migrations/**", "db/migrations/0001.py"));
        assert!(!glob_match("/etc/**", "/etcetera/x"));
    }

    #[test]
    fn a_backslash_in_a_windows_seed_is_a_literal() {
        assert!(glob_match(
            "C:\\Windows\\**",
            "C:\\Windows\\System32\\hosts"
        ));
        assert!(!glob_match("C:\\Windows\\**", "C:/Windows/System32"));
    }

    #[test]
    fn the_order_is_the_semantics() {
        let env = seeded();
        assert_eq!(
            class_of("config/.env", &env).as_deref(),
            Some("secret_material")
        );
        assert_eq!(
            class_of(".claude/x.md", &env).as_deref(),
            Some("agent_config")
        );
        // `/var` is row 3 and `/var/lib/postgresql/**` is row 5: the narrower
        // seed must win, which it only does because `/var/**` is not row 3.
        assert_eq!(
            class_of("/var/lib/postgresql/16/base", &env).as_deref(),
            Some("data_store")
        );
    }

    #[test]
    fn rows_three_and_six_need_env_and_stay_silent_without_it() {
        let none = seeded();
        assert_eq!(class_of("/home/dev", &none), None, "no env, no home root");
        assert_eq!(class_of("/srv/extra/notes.md", &none), None);
        let env = env();
        assert_eq!(class_of("/home/dev", &env).as_deref(), Some("system_path"));
        assert_eq!(
            class_of("/usr/local/bin", &env).as_deref(),
            Some("system_path")
        );
        assert_eq!(
            class_of("/srv/extra/notes.md", &env).as_deref(),
            Some("workspace_file")
        );
    }

    #[test]
    fn an_unplaceable_absolute_path_is_never_a_guessed_workspace_file() {
        assert_eq!(class_of("/srv/blob/opaque.bin", &env()), None);
    }

    #[test]
    fn a_tilde_resolves_against_the_declared_home_and_not_the_host() {
        assert_eq!(
            class_of("~/proj/notes.md", &env()).as_deref(),
            Some("workspace_file")
        );
        assert_eq!(
            class_of("~/tmp/stale", &seeded()),
            None,
            "with no declared home there is nothing to expand against"
        );
    }

    #[test]
    fn a_customer_root_arrives_as_a_fact_and_not_as_a_constant() {
        let facts = FactSet::new(
            vec![serde_json::from_value(serde_json::json!({
                "fact_id": "data_store_roots",
                "kind": "set",
                "observed_at": "2025-09-01T15:59:00+00:00",
                "max_age_s": 86400,
                "value": ["/lake"],
            }))
            .expect("the fixture fact parses")],
            1_756_742_400_000,
        );
        assert_eq!(
            resolve_with("/lake/raw/x.parquet", &PathEnv::default(), &facts).map(|c| c.0),
            Some("data_store".to_string())
        );
        assert_eq!(
            resolve_with(
                "/lake/raw/x.parquet",
                &PathEnv::default(),
                &FactSet::default()
            ),
            None,
            "without the fact the root is unknown, not empty-and-therefore-fine"
        );
    }

    /// AZ-4 D-I16-29: an added pattern never masks a seed class.
    #[test]
    fn a_path_matching_several_patterns_carries_every_class() {
        let catalogue = seed_r1_plus(serde_json::json!({"targets": [
            {"id": "n1", "origin": "org", "pattern_kind": "path", "key": "**/.npmrc",
             "target_class": "secret_material"}
        ]}));
        let env = PathEnv::default().with_catalogue(Some(catalogue));
        assert_eq!(
            classes_of(".npmrc", &env),
            vec!["secret_material", "agent_config"]
        );
        assert_eq!(
            classes_of("/home/dev/p/.npmrc", &env),
            vec!["secret_material", "agent_config"]
        );
        let all = resolve_all(".npmrc", &env, &FactSet::default());
        assert_eq!(all[0].origins, vec![Origin::Entry("n1".to_string())]);
    }

    /// `/opt/**` is a code row, a learned pattern is a catalogue one: both count.
    #[test]
    fn a_code_row_and_a_catalogue_row_both_add_their_class() {
        let catalogue = seed_r1_plus(serde_json::json!({"targets": [
            {"id": "acme", "origin": "org", "pattern_kind": "path", "key": "/opt/acme/**",
             "target_class": "secret_material"}
        ]}));
        let env = PathEnv::default().with_catalogue(Some(catalogue));
        assert_eq!(
            classes_of("/opt/acme/secrets.yaml", &env),
            vec!["secret_material", "system_path"]
        );
    }

    #[test]
    fn a_leading_double_star_slash_is_optional() {
        assert!(glob_match("**/.npmrc", ".npmrc"));
        assert!(glob_match("**/.npmrc", "/home/dev/p/.npmrc"));
        assert!(glob_match("**/.ssh/**", ".ssh/id_rsa"));
        assert!(!glob_match("**/.npmrc", "x.npmrc"));
        assert!(
            !glob_match(".npmrc", "p/.npmrc"),
            "only a leading `**/` is optional"
        );
    }

    #[test]
    fn a_narrow_target_removes_its_class_in_every_scope() {
        let catalogue = seed_r1_plus(serde_json::json!({"targets": [
            {"id": "fix", "origin": "org", "narrow": true, "pattern_kind": "path",
             "key": "**/*token*", "target_class": "secret_material"}
        ]}));
        let env = PathEnv::default().with_catalogue(Some(catalogue));
        assert_eq!(
            classes_of("docs/token-bucket.md", &env),
            vec!["workspace_file"]
        );
    }

    #[test]
    fn with_no_catalogue_no_pattern_row_fires() {
        let env = PathEnv::default();
        assert_eq!(classes_of("config/.env", &env), vec!["workspace_file"]);
    }
}