openlatch-client 0.6.9

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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
//! 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 std::borrow::Cow;

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
    }

    /// The same context with every root in its `windows_form`.
    fn windows_form(&self) -> PathEnv<'a> {
        let fix = |value: &String| windows_form(value, true).into_owned();
        PathEnv {
            home: fix(&self.home),
            cwd: fix(&self.cwd),
            path_dirs: self.path_dirs.iter().map(fix).collect(),
            additional_dirs: self.additional_dirs.iter().map(fix).collect(),
            catalogue: self.catalogue,
        }
    }
}

/// Whether `value` is rooted the Windows way: `C:\`, `C:/`, or a `\\` or `//`
/// share — the spellings `normalize_target` reads as Windows.
fn windows_rooted(value: &str) -> bool {
    let bytes = value.as_bytes();
    value.starts_with("\\\\")
        || value.starts_with("//")
        || (bytes.first().is_some_and(u8::is_ascii_alphabetic)
            && bytes.get(1) == Some(&b':')
            && matches!(bytes.get(2), Some(b'/' | b'\\')))
}

/// `value` with `/` separators and ASCII-folded case when it belongs to a
/// `windows` match — the path or what it is matched against — because Windows
/// reads `C:\Users\dev\.ENV` as `c:/users/dev/.env` (#592). Anywhere else a
/// backslash is a literal and case is significant.
fn windows_form(value: &str, windows: bool) -> Cow<'_, str> {
    if windows {
        Cow::Owned(value.replace('\\', "/").to_ascii_lowercase())
    } else {
        Cow::Borrowed(value)
    }
}

// ── 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.
///
/// Both directions — this one, and an absolute path re-written `~`-relative so a
/// `~/.ssh/**` seed can match it — are the same substitution; doing only one
/// leaves a path the caller fully described unplaceable, as the oracle did on
/// `cp /etc/hosts ~/proj/notes.md` until its `_expand_home` (#590).
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('/')))
}

/// Whether a shell token can be located without executing an expansion.
/// Single quotes make every byte literal; double quotes still permit `$` and
/// command substitution. Backslash escapes protect the next unquoted byte.
pub fn shell_word_is_static(raw: &str) -> bool {
    let mut single = false;
    let mut double = false;
    let mut chars = raw.chars();
    while let Some(ch) = chars.next() {
        match ch {
            '\'' if !double => single = !single,
            '"' if !single => double = !double,
            '\\' if !single => {
                chars.next();
            }
            '$' | '`' if !single => return false,
            '*' | '?' if !single && !double => return false,
            _ => {}
        }
    }
    true
}

/// A leading tilde expands only when the shell saw it unquoted and unescaped.
fn shell_expands_home(raw: &str, cooked: &str) -> bool {
    cooked.starts_with('~') && raw.starts_with('~')
}

/**
 * Normalize a shell word while preserving the quote-dependent tilde rule.
 * The tokeniser supplies both forms; direct tool inputs continue to use
 * `normalize_target` and do not acquire shell quote semantics.
 */
pub fn normalize_shell_target(cooked: &str, raw: &str, env: &PathEnv) -> Option<String> {
    if !shell_word_is_static(raw) {
        return None;
    }
    if shell_expands_home(raw, cooked) {
        let expanded = expand_home(cooked, &env.home)?;
        normalize_target_inner(&expanded, env, false)
    } else {
        normalize_target_inner(cooked, env, false)
    }
}

/// Which declared shell context a target depends on: `(cwd, home)`.
pub fn shell_target_dependencies(cooked: &str, raw: &str) -> (bool, bool) {
    if !shell_word_is_static(raw) {
        return (false, false);
    }
    if shell_expands_home(raw, cooked) {
        return (false, true);
    }
    let drive_absolute = cooked.as_bytes().get(1) == Some(&b':')
        && cooked
            .as_bytes()
            .first()
            .is_some_and(u8::is_ascii_alphabetic)
        && matches!(cooked.as_bytes().get(2), Some(b'/' | b'\\'));
    let independent = cooked.starts_with('/') || cooked.starts_with("\\\\") || drive_absolute;
    (!independent, false)
}

/**
 * Normalize one declared target lexically, using only the event's declared
 * home and cwd. This deliberately does not touch the filesystem or resolve
 * symlinks. Windows drive and UNC strings are data and normalize identically
 * when replayed on a non-Windows host.
 */
pub fn normalize_target(path: &str, env: &PathEnv) -> Option<String> {
    normalize_target_inner(path, env, true)
}

fn normalize_target_inner(path: &str, env: &PathEnv, expand_tilde: bool) -> Option<String> {
    if path.is_empty() || path.contains("://") {
        return None;
    }
    let mut value = if expand_tilde {
        expand_home(path, &env.home).unwrap_or_else(|| path.to_string())
    } else {
        path.to_string()
    };
    let drive = |text: &str| {
        (text.as_bytes().get(1) == Some(&b':')
            && text.as_bytes().first().is_some_and(u8::is_ascii_alphabetic))
        .then(|| text[..2].to_string())
    };
    let drive_absolute =
        |text: &str| drive(text).filter(|_| matches!(text.as_bytes().get(2), Some(b'/' | b'\\')));
    let unc = value.starts_with("//") || value.starts_with("\\\\");
    let cwd_drive = drive_absolute(&env.cwd);
    let cwd_unc = env.cwd.starts_with("//") || env.cwd.starts_with("\\\\");
    let drive_relative = drive(&value).filter(|_| drive_absolute(&value).is_none());
    let windows = unc
        || drive_absolute(&value).is_some()
        || (drive_relative.is_some() && cwd_drive == drive_relative)
        || (!value.starts_with('/')
            && drive_relative.is_none()
            && (cwd_drive.is_some() || cwd_unc));

    if let Some(relative_drive) = drive_relative {
        if cwd_drive.as_ref() != Some(&relative_drive) {
            return None;
        }
        value = format!("{}/{}", env.cwd.trim_end_matches(['/', '\\']), &value[2..]);
    } else if !unc
        && drive_absolute(&value).is_none()
        && !value.starts_with('/')
        && !env.cwd.is_empty()
    {
        value = format!("{}/{}", env.cwd.trim_end_matches(['/', '\\']), value);
    }
    if windows {
        value = value.replace('\\', "/");
    }

    let is_unc = windows && value.starts_with("//");
    let drive_absolute = drive_absolute(&value);
    let is_posix = value.starts_with('/') && !is_unc;
    let (prefix, rest, floor) = if is_unc {
        ("//".to_string(), value.trim_start_matches('/'), 2usize)
    } else if let Some(drive) = drive_absolute {
        (
            format!("{drive}/"),
            value[2..].trim_start_matches('/'),
            0usize,
        )
    } else if is_posix {
        ("/".to_string(), value.trim_start_matches('/'), 0usize)
    } else {
        (String::new(), value.as_str(), 0usize)
    };

    let mut parts: Vec<&str> = Vec::new();
    for part in rest.split('/') {
        match part {
            "" | "." => {}
            ".." if parts.len() > floor => {
                parts.pop();
            }
            ".." if prefix.is_empty() => parts.push(part),
            ".." => {}
            _ => parts.push(part),
        }
    }
    let joined = parts.join("/");
    if prefix.is_empty() {
        Some(joined)
    } else if joined.is_empty() {
        Some(prefix)
    } else {
        Some(format!("{prefix}{joined}"))
    }
}

/// Normalize an authored lexical prefix without erasing its directory boundary.
pub fn normalize_prefix(prefix: &str) -> Option<String> {
    let delimited = prefix.ends_with('/') || prefix.ends_with('\\');
    let mut normalized = normalize_target(prefix, &PathEnv::default())?;
    if delimited && !normalized.ends_with('/') {
        normalized.push('/');
    }
    Some(normalized)
}

/// 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, windows: bool) -> bool {
    let pattern = &*windows_form(pattern, windows);
    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, windows: bool) -> bool {
    let forms = candidates(path, env);
    patterns
        .iter()
        .any(|pattern| pattern_matches(pattern, &forms, env, windows))
}

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

/// 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();
    }
    // A native Windows path — rooted, or relative under a Windows cwd — is
    // matched in its `windows_form`, against roots and patterns in theirs:
    // `C:\Users\dev\.env` is `**/.env` (#590). A POSIX path is left as is.
    let windows = windows_rooted(path) || (windows_rooted(&env.cwd) && !path.starts_with('/'));
    let path = &*windows_form(path, windows);
    let windows_env;
    let env = if windows {
        windows_env = env.windows_form();
        &windows_env
    } else {
        env
    };
    // `~/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, windows) {
                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, windows)
        || 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,
        windows,
    ) {
        add_class(&mut out, "classified_source", None);
    }
    if fact_members(facts, "data_store_roots")
        .iter()
        .any(|root| under(&absolute, &windows_form(root, windows)))
    {
        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('~')
            && !windows_rooted(path)
            && !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 occurrence_targets_normalize_lexically_without_losing_boundaries() {
        let env = env();
        assert_eq!(
            normalize_target("/tmp/a/../b", &env).as_deref(),
            Some("/tmp/b")
        );
        assert_eq!(
            normalize_target("/tmp/../etc/passwd", &env).as_deref(),
            Some("/etc/passwd")
        );
        assert_eq!(
            normalize_target("src/../out", &env).as_deref(),
            Some("/home/dev/proj/out")
        );
        assert_eq!(
            normalize_target("~/tmp/x", &env).as_deref(),
            Some("/home/dev/tmp/x")
        );
        assert_eq!(
            normalize_target("\\tmp\\out", &env).as_deref(),
            Some("/home/dev/proj/\\tmp\\out")
        );
        assert_eq!(normalize_prefix("/tmp/").as_deref(), Some("/tmp/"));
        assert!(!normalize_target("/tmp2/x", &env)
            .expect("normalizes")
            .starts_with(&normalize_prefix("/tmp/").expect("prefix")));
    }

    #[test]
    fn windows_and_unc_paths_are_data_on_every_host() {
        let windows = PathEnv {
            home: "C:\\Users\\dev".to_string(),
            cwd: "C:\\work\\repo".to_string(),
            ..PathEnv::default()
        };
        assert_eq!(
            normalize_target(".\\src\\..\\out.txt", &windows).as_deref(),
            Some("C:/work/repo/out.txt")
        );
        assert_eq!(
            normalize_target("C:\\tmp\\..\\Windows\\x", &windows).as_deref(),
            Some("C:/Windows/x")
        );
        assert_eq!(
            normalize_target("C:tmp\\out", &windows).as_deref(),
            Some("C:/work/repo/tmp/out")
        );
        let other_drive = PathEnv {
            cwd: "D:\\work".to_string(),
            ..PathEnv::default()
        };
        assert_eq!(normalize_target("C:tmp\\out", &other_drive), None);
        assert_eq!(
            normalize_target("\\\\server\\share\\a\\..\\b", &windows).as_deref(),
            Some("//server/share/b")
        );
    }

    #[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"
        );
    }

    #[test]
    fn a_windows_root_matches_in_its_windows_form() {
        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": ["D:\\Lake"],
            }))
            .expect("the fixture fact parses")],
            1_756_742_400_000,
        );
        let windows = PathEnv {
            home: "C:\\Users\\dev".to_string(),
            cwd: "C:\\Users\\dev\\project".to_string(),
            ..PathEnv::default()
        };
        assert_eq!(
            resolve_with("d:\\LAKE\\raw\\x.parquet", &windows, &facts).map(|c| c.0),
            Some("data_store".to_string())
        );
        assert_eq!(
            class_of("~\\project\\notes.md", &windows).as_deref(),
            Some("workspace_file")
        );
    }

    /// 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"]);
    }
}