leviath-core 0.1.2

Core types and traits for Leviath: context regions, memory layouts, blueprints, and lifecycle policies
Documentation
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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
//! The `[read_paths]` allowlist: how an agent is granted read access outside
//! its workdir, and how each access is checked.
//!
//! A blueprint's `[read_paths] allow` array *declares* what the agent wants to
//! read. Declaring is not granting: the user's config must either name the
//! same paths (`[security] read_paths` / `[agent_read_paths.<name>]`) or set
//! `allow_blueprint_read_paths = true`. That keeps the manifest tighten-only -
//! an `agent.leviath` someone downloaded cannot ship one TOML line that reads
//! `~/.ssh`. [`ReadPathPolicy::decide`] is that double check, applied per path
//! at resolve time.
//!
//! Three entry forms:
//! - an exact path: grants the whole subtree under it, checked with the same
//!   canonicalize-then-prefix containment as the workdir sandbox
//! - `glob:` - a glob pattern, `*` stays inside one path component, `**`
//!   crosses them
//! - `regex:` - a regex, auto-anchored as `^(?:pattern)$` so `regex:runs`
//!   cannot quietly match `/etc/runs-anything`
//!
//! Patterns match the **symlink-resolved real path** of the file, never the
//! path the agent asked for. That is what makes them safe: a symlink planted
//! inside an allowlisted directory resolves to its real target, and the real
//! target must itself match an entry. The matched string uses `/` separators
//! on every OS and, on Windows, has the `\\?\` verbatim prefix stripped and is
//! compared case-insensitively (see [`normalize_match_str`]).
//!
//! Portability: `~/` expands to the home directory (honoring `LEVIATH_HOME`),
//! and a bare relative entry resolves against the run's workdir. A relative
//! `regex:` is refused - there is no way to splice a workdir into a regex
//! safely, and `glob:` covers that case.

use std::path::{Path, PathBuf};

/// One compiled allowlist entry. Only [`ReadPathSet`] constructs these; the
/// enum is public so a set's contents are inspectable, not so callers build
/// entries by hand (compilation is where `~`/relative resolution and
/// anchoring happen).
#[derive(Debug, Clone)]
pub enum ReadPathEntry {
    /// An exact root: grants the subtree under it. Stored as resolved at
    /// compile time (tilde/workdir applied) but *uncanonicalized* - the root
    /// is canonicalized at match time so a root created after spawn still
    /// works, and a root that cannot be verified never matches.
    Exact(PathBuf),
    /// A glob over the normalized real path.
    Glob {
        /// The compiled pattern, already `/`-separated and prefixed with the
        /// escaped home or workdir when the source entry was `~/` or relative.
        pattern: glob::Pattern,
        /// Match options: `require_literal_separator` always, case sensitivity
        /// per platform semantics.
        options: glob::MatchOptions,
    },
    /// A regex over the normalized real path, anchored at compile time.
    Regex(regex::Regex),
}

impl ReadPathEntry {
    /// Whether the already-canonicalized `canonical` path (and its
    /// pre-normalized string form) lands inside this entry.
    fn matches(&self, canonical: &Path, normalized: &str) -> bool {
        match self {
            ReadPathEntry::Exact(root) => match std::fs::canonicalize(root) {
                Ok(real_root) => canonical.starts_with(&real_root),
                // The root itself cannot be verified (it does not exist, or a
                // parent is unreadable). `canonical` exists - it was
                // canonicalized by the caller - so it cannot really live under
                // an unverifiable root. Refuse.
                Err(_) => false,
            },
            ReadPathEntry::Glob { pattern, options } => pattern.matches_with(normalized, *options),
            ReadPathEntry::Regex(re) => re.is_match(normalized),
        }
    }

    /// One concrete path this entry matches, or `None` when none can be
    /// synthesized from the pattern alone.
    ///
    /// This exists for *reporting*, not for enforcement: to say whether a
    /// config grant covers what a blueprint declares, something has to stand in
    /// for "a path the declaration would let through", and the honest stand-in
    /// is a path built from the declaration itself. Every synthesized sample is
    /// checked back against its own entry, so a sample that cannot be trusted
    /// comes back as `None` and the caller reports "cannot tell" rather than
    /// guessing.
    pub fn sample_path(&self) -> Option<PathBuf> {
        match self {
            // The root itself is inside the subtree it grants.
            ReadPathEntry::Exact(root) => Some(root.clone()),
            ReadPathEntry::Glob { pattern, options } => {
                let sample = fill_glob_wildcards(pattern.as_str())?;
                pattern
                    .matches_with(&sample, *options)
                    .then(|| PathBuf::from(sample))
            }
            ReadPathEntry::Regex(re) => {
                let literal = literal_prefix(strip_regex_anchors(re.as_str()));
                // A file inside the literal directory prefix first: it is the
                // shape a real read takes, and it is what a `**` grant covers.
                // The bare literal second, for a regex that is all literal.
                let in_dir = literal
                    .rsplit_once('/')
                    .map(|(dir, _)| format!("{dir}/{SAMPLE_COMPONENT}"));
                [in_dir, (!literal.is_empty()).then_some(literal)]
                    .into_iter()
                    .flatten()
                    .find(|candidate| re.is_match(candidate))
                    .map(PathBuf::from)
            }
        }
    }
}

/// The component substituted for a wildcard when synthesizing a sample path.
/// Deliberately unlikely to appear in a real pattern as a literal.
const SAMPLE_COMPONENT: &str = "_leviath_probe";

/// Replace a glob's wildcards with a literal component so the pattern becomes
/// a concrete path. `None` for a character class, whose expansion would have to
/// be guessed at (`[` also carries glob's escape syntax).
fn fill_glob_wildcards(pattern: &str) -> Option<String> {
    let mut out = String::with_capacity(pattern.len());
    let mut previous_was_star = false;
    for ch in pattern.chars() {
        match ch {
            '[' => return None,
            // A run of `*` or `**` collapses to one substitution.
            '*' => {
                if !previous_was_star {
                    out.push_str(SAMPLE_COMPONENT);
                }
                previous_was_star = true;
                continue;
            }
            '?' => out.push('x'),
            other => out.push(other),
        }
        previous_was_star = false;
    }
    Some(out)
}

/// Undo the `^(?:...)$` anchoring [`compile_regex`] applies, so the pattern
/// text can be read for its literal prefix. Text that is not anchored that way
/// is returned as-is.
fn strip_regex_anchors(pattern: &str) -> &str {
    pattern
        .strip_prefix("^(?:")
        .and_then(|rest| rest.strip_suffix(")$"))
        .unwrap_or(pattern)
}

/// The leading run of characters a regex matches literally, stopping at the
/// first metacharacter (an escape included: what follows it is literal, but the
/// prefix is already long enough to be useful).
fn literal_prefix(pattern: &str) -> String {
    pattern
        .chars()
        .take_while(|c| {
            !matches!(
                c,
                '.' | '[' | ']' | '(' | ')' | '{' | '}' | '*' | '+' | '?' | '|' | '^' | '$' | '\\'
            )
        })
        .collect()
}

/// Normalize a canonicalized path string for glob/regex matching.
///
/// With `windows` set (production: `cfg!(windows)`, injected so both branches
/// are testable everywhere):
/// - `\\?\UNC\server\share\..` becomes `\\server\share\..`
/// - `\\?\C:\..` (a drive-letter verbatim path, which is what
///   `fs::canonicalize` returns on Windows) loses the `\\?\` prefix
/// - any other `\\?\` form (`\\?\Volume{..}`) is left alone; such a path
///   simply never matches a drive-letter pattern, which fails closed
/// - every `\` becomes `/`, so patterns are written with `/` on every OS
///
/// Without it the string is returned unchanged - a Unix filename may legally
/// contain `\`.
pub fn normalize_match_str(s: &str, windows: bool) -> String {
    if !windows {
        return s.to_string();
    }
    let stripped = if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
        format!(r"\\{rest}")
    } else if let Some(rest) = s.strip_prefix(r"\\?\") {
        let bytes = rest.as_bytes();
        if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
            rest.to_string()
        } else {
            s.to_string()
        }
    } else {
        s.to_string()
    };
    stripped.replace('\\', "/")
}

/// A compiled set of allowlist entries, bound to the run they were compiled
/// for (tilde and relative entries were resolved at compile time).
#[derive(Debug, Clone, Default)]
pub struct ReadPathSet {
    entries: Vec<ReadPathEntry>,
    /// Windows path semantics for matching (separator normalization and case
    /// folding). Injected rather than read from `cfg!` inside so every branch
    /// runs under test on every OS.
    windows: bool,
}

impl ReadPathSet {
    /// Compile raw `[read_paths] allow` strings against a run's workdir and
    /// home. `windows` selects Windows path semantics: `/`-normalization of
    /// the matched string and case-insensitive glob/regex matching
    /// (production passes `cfg!(windows)`).
    ///
    /// Any invalid entry is a hard error naming the entry - a skipped entry
    /// would degrade the agent silently mid-run, and refusing loudly at
    /// compile (spawn) time is the same posture the sandbox config takes.
    pub fn compile(
        raw: &[String],
        workdir: &Path,
        home: Option<&Path>,
        windows: bool,
    ) -> Result<Self, String> {
        let entries = raw
            .iter()
            .map(|entry| compile_entry(entry, workdir, home, windows))
            .collect::<Result<Vec<_>, String>>()?;
        Ok(Self { entries, windows })
    }

    /// Whether the set has no entries at all.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// The compiled entries, for callers that report or display them.
    pub fn entries(&self) -> &[ReadPathEntry] {
        &self.entries
    }

    /// Whether the already-canonicalized `canonical` path matches any entry.
    pub fn matches(&self, canonical: &Path) -> bool {
        let normalized = normalize_match_str(&canonical.to_string_lossy(), self.windows);
        self.entries
            .iter()
            .any(|e| e.matches(canonical, &normalized))
    }

    /// Whether `path` matches any entry, comparing text instead of the
    /// filesystem: an `Exact` entry is a component-wise prefix test on the path
    /// as written, with no canonicalization.
    ///
    /// [`matches`](Self::matches) is the enforcement path and must resolve
    /// symlinks; this is the reporting path, which must not. A grant naming a
    /// directory that does not exist yet, or one behind macOS's `/tmp` ->
    /// `/private/tmp` link, is still a grant the user wrote, and telling them it
    /// is missing would be wrong. The trade is the other way too: a report is a
    /// pattern-level answer, so a run can still be refused at a path this says
    /// is covered.
    pub fn matches_lexically(&self, path: &Path) -> bool {
        let normalized = normalize_match_str(&path.to_string_lossy(), self.windows);
        self.entries.iter().any(|entry| match entry {
            ReadPathEntry::Exact(root) => {
                let root = normalize_match_str(&root.to_string_lossy(), self.windows);
                covers_lexically(&normalized, &root, self.windows)
            }
            // Glob and regex entries already match on the normalized string
            // alone; the path argument goes unread.
            other => other.matches(path, &normalized),
        })
    }
}

/// Whether `path` is `root` or sits under it, on component boundaries so
/// `/a/bc` is not read as living under `/a/b`. Case-folded under Windows
/// semantics, matching how glob and regex entries compare there.
fn covers_lexically(path: &str, root: &str, windows: bool) -> bool {
    let fold = |s: &str| {
        if windows {
            s.to_lowercase()
        } else {
            s.to_string()
        }
    };
    let path = fold(path);
    let root = fold(root);
    let trimmed = root.trim_end_matches('/');
    // A root of `/` (or `C:/`) trims to `""`/`C:`, and every path under it
    // starts with the separator the trim removed.
    path == trimmed || path.starts_with(&format!("{trimmed}/"))
}

/// The outcome of checking one path against a [`ReadPathPolicy`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadPathDecision {
    /// Declared by the blueprint and granted by the user (or the user opted
    /// into honoring blueprints wholesale).
    Allowed,
    /// The blueprint never asked for this path; the ordinary workdir refusal
    /// stands.
    NotDeclared,
    /// The blueprint asked, but nothing in the user's config grants it.
    NotGranted,
}

/// Everything read-path enforcement needs, resolved once at spawn.
///
/// `blueprint` is what the manifest declares; `grants` is what the user's
/// config allows (`[security] read_paths` plus `[agent_read_paths.<name>]`);
/// `allow_blueprint` is the `[security] allow_blueprint_read_paths` override
/// that honors declarations without itemized grants.
#[derive(Debug, Clone, Default)]
pub struct ReadPathPolicy {
    /// The agent's name, for error and warning text.
    pub agent: String,
    /// Entries the blueprint declares.
    pub blueprint: ReadPathSet,
    /// Entries the user's config grants.
    pub grants: ReadPathSet,
    /// Whether declarations are honored without itemized grants.
    pub allow_blueprint: bool,
}

impl ReadPathPolicy {
    /// A policy that allows nothing beyond the workdir - the default for
    /// every agent whose blueprint has no `[read_paths]`.
    pub fn inactive() -> Self {
        Self::default()
    }

    /// Whether the blueprint declares any read paths at all. When false, the
    /// resolver never consults this policy and the workdir sandbox behaves
    /// exactly as it always has.
    pub fn is_active(&self) -> bool {
        !self.blueprint.is_empty()
    }

    /// The double check: the blueprint must declare the path AND the user
    /// must grant it (itemized, or via the blanket override).
    pub fn decide(&self, canonical: &Path) -> ReadPathDecision {
        if !self.blueprint.matches(canonical) {
            return ReadPathDecision::NotDeclared;
        }
        if self.allow_blueprint || self.grants.matches(canonical) {
            ReadPathDecision::Allowed
        } else {
            ReadPathDecision::NotGranted
        }
    }
}

/// Validate one entry's syntax without binding it to a run: bad glob/regex,
/// a relative `regex:`, an empty entry. Called from manifest parsing so a
/// broken entry fails `lev validate`/`lev add`/spawn loudly instead of
/// degrading the agent at its first out-of-workdir read.
///
/// Environment problems (`~` with no resolvable home) are not syntax and are
/// only caught when the real compile runs at spawn.
pub fn validate_entry_syntax(raw: &str) -> Result<(), String> {
    // The dummy workdir is deep enough that a reasonable `../` prefix in a
    // relative glob validates; how far up a real run can climb is bound to the
    // real workdir at spawn.
    let workdir = Path::new("/validate/a/b/c/d/e/f/g/h");
    compile_entry(raw, workdir, Some(Path::new("/validate-home")), false).map(|_| ())
}

/// Compile one raw entry. `windows` is the same injected platform-semantics
/// flag as [`ReadPathSet::compile`].
fn compile_entry(
    raw: &str,
    workdir: &Path,
    home: Option<&Path>,
    windows: bool,
) -> Result<ReadPathEntry, String> {
    if raw.trim().is_empty() {
        return Err("read_paths entry is empty".to_string());
    }
    if let Some(rest) = raw.strip_prefix("regex:") {
        compile_regex(raw, rest, home, windows)
    } else if let Some(rest) = raw.strip_prefix("glob:") {
        compile_glob(raw, rest, workdir, home, windows)
    } else {
        compile_exact(raw, workdir, home)
    }
}

/// Whether pattern text starts like an absolute path: `/..`, `//server/..`,
/// or a drive letter `C:/..`. Deliberately literal - a pattern opening with a
/// character class (`[A-Z]:/..`) is refused rather than guessed at.
fn absolute_shaped(text: &str) -> bool {
    let bytes = text.as_bytes();
    text.starts_with('/')
        || (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
}

fn compile_regex(
    raw: &str,
    rest: &str,
    home: Option<&Path>,
    windows: bool,
) -> Result<ReadPathEntry, String> {
    if rest.is_empty() {
        return Err(format!("read_paths entry '{raw}': regex pattern is empty"));
    }
    let body = if let Some(after_tilde) = rest.strip_prefix('~') {
        if !(after_tilde.is_empty() || after_tilde.starts_with('/')) {
            return Err(format!(
                "read_paths entry '{raw}': only '~/' home expansion is supported"
            ));
        }
        let home = home.ok_or_else(|| {
            format!("read_paths entry '{raw}': no home directory resolved for '~' expansion")
        })?;
        let prefix = regex::escape(&normalize_match_str(&home.to_string_lossy(), windows));
        format!("{prefix}{after_tilde}")
    } else if absolute_shaped(rest) {
        rest.to_string()
    } else {
        return Err(format!(
            "read_paths entry '{raw}': regex entries must start with '/', a drive letter, or '~/'; \
             use 'glob:' for workdir-relative patterns"
        ));
    };
    regex::RegexBuilder::new(&format!("^(?:{body})$"))
        .case_insensitive(windows)
        .build()
        .map(ReadPathEntry::Regex)
        .map_err(|e| format!("read_paths entry '{raw}': invalid regex: {e}"))
}

fn compile_glob(
    raw: &str,
    rest: &str,
    workdir: &Path,
    home: Option<&Path>,
    windows: bool,
) -> Result<ReadPathEntry, String> {
    if rest.is_empty() {
        return Err(format!("read_paths entry '{raw}': glob pattern is empty"));
    }
    // Glob has no backslash-escape syntax, so this is lossless and makes
    // Windows-style patterns portable.
    let text = rest.replace('\\', "/");
    let text = if let Some(after_tilde) = text.strip_prefix('~') {
        if !(after_tilde.is_empty() || after_tilde.starts_with('/')) {
            return Err(format!(
                "read_paths entry '{raw}': only '~/' home expansion is supported"
            ));
        }
        let home = home.ok_or_else(|| {
            format!("read_paths entry '{raw}': no home directory resolved for '~' expansion")
        })?;
        // The home directory is data, not pattern: escape any glob
        // metacharacters it happens to contain.
        let prefix = glob::Pattern::escape(&normalize_match_str(&home.to_string_lossy(), windows));
        format!("{prefix}{after_tilde}")
    } else if absolute_shaped(&text) {
        text
    } else {
        resolve_relative_glob(raw, &text, workdir, windows)?
    };
    // A `.` or `..` component anywhere in the final pattern can never match a
    // canonicalized path, so it is always a mistake - refuse it rather than
    // let the entry silently match nothing.
    if text.split('/').any(|c| c == "." || c == "..") {
        return Err(format!(
            "read_paths entry '{raw}': glob patterns cannot contain '.' or '..' components \
             (relative entries fold them against the workdir at the start only)"
        ));
    }
    let pattern = glob::Pattern::new(&text)
        .map_err(|e| format!("read_paths entry '{raw}': invalid glob: {e}"))?;
    let options = glob::MatchOptions {
        case_sensitive: !windows,
        // `*` must not cross a `/`; `**` is the explicit way to.
        require_literal_separator: true,
        require_literal_leading_dot: false,
    };
    Ok(ReadPathEntry::Glob { pattern, options })
}

/// Anchor a relative glob at the workdir, folding any *leading* `./` and
/// `../` components into the workdir prefix so `glob:../shared/**` means the
/// workdir's sibling.
fn resolve_relative_glob(
    raw: &str,
    text: &str,
    workdir: &Path,
    windows: bool,
) -> Result<String, String> {
    let base_str = normalize_match_str(&workdir.to_string_lossy(), windows);
    let mut base: Vec<&str> = base_str.split('/').collect();
    // "/" splits to ["", ""]; keep the leading "" (it restores the root `/`
    // on rejoin) and drop trailing empties.
    while base.len() > 1 && base.last().is_some_and(|s| s.is_empty()) {
        base.pop();
    }
    let mut rest = text;
    loop {
        if let Some(r) = rest.strip_prefix("./") {
            rest = r;
        } else if let Some(r) = rest.strip_prefix("../") {
            if base.len() <= 1 {
                return Err(format!(
                    "read_paths entry '{raw}': relative pattern escapes the filesystem root"
                ));
            }
            base.pop();
            rest = r;
        } else {
            break;
        }
    }
    // The workdir is data, not pattern.
    let prefix = glob::Pattern::escape(&base.join("/"));
    Ok(if rest.is_empty() {
        prefix
    } else {
        format!("{prefix}/{rest}")
    })
}

fn compile_exact(raw: &str, workdir: &Path, home: Option<&Path>) -> Result<ReadPathEntry, String> {
    let path = if let Some(after_tilde) = raw.strip_prefix('~') {
        let sub = after_tilde
            .strip_prefix('/')
            .or_else(|| after_tilde.strip_prefix('\\'));
        let sub = match (sub, after_tilde.is_empty()) {
            (_, true) => "",
            (Some(sub), _) => sub,
            (None, false) => {
                return Err(format!(
                    "read_paths entry '{raw}': only '~/' home expansion is supported"
                ));
            }
        };
        let home = home.ok_or_else(|| {
            format!("read_paths entry '{raw}': no home directory resolved for '~' expansion")
        })?;
        if sub.is_empty() {
            home.to_path_buf()
        } else {
            home.join(sub)
        }
    } else if Path::new(raw).is_absolute() {
        PathBuf::from(raw)
    } else {
        workdir.join(raw)
    };
    Ok(ReadPathEntry::Exact(path))
}

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

    fn set(entries: &[&str], workdir: &str, home: Option<&str>, windows: bool) -> ReadPathSet {
        let raw: Vec<String> = entries.iter().map(|s| s.to_string()).collect();
        ReadPathSet::compile(&raw, Path::new(workdir), home.map(Path::new), windows)
            .expect("entries compile")
    }

    fn compile_err(entry: &str, workdir: &str, home: Option<&str>) -> String {
        ReadPathSet::compile(
            &[entry.to_string()],
            Path::new(workdir),
            home.map(Path::new),
            false,
        )
        .expect_err("entry must be refused")
    }

    // -- compile errors ----------------------------------------------------

    #[test]
    fn empty_and_whitespace_entries_are_refused() {
        assert!(compile_err("", "/w", None).contains("empty"));
        assert!(compile_err("   ", "/w", None).contains("empty"));
        assert!(compile_err("glob:", "/w", None).contains("glob pattern is empty"));
        assert!(compile_err("regex:", "/w", None).contains("regex pattern is empty"));
    }

    #[test]
    fn invalid_patterns_are_refused() {
        assert!(compile_err("glob:/a/[", "/w", None).contains("invalid glob"));
        assert!(compile_err("regex:/a/(", "/w", None).contains("invalid regex"));
    }

    /// There is no safe way to splice a workdir into a regex, so a relative
    /// regex is a hard error pointing at glob.
    #[test]
    fn a_relative_regex_is_refused() {
        let err = compile_err("regex:etc/passwd", "/w", None);
        assert!(err.contains("must start with"), "got: {err}");
        assert!(err.contains("glob:"), "got: {err}");
    }

    /// `~user` expansion is not supported in any entry kind - only `~/`.
    #[test]
    fn tilde_user_forms_are_refused() {
        for entry in ["~other/x", "glob:~other/**", "regex:~other/.*"] {
            let err = compile_err(entry, "/w", Some("/home/me"));
            assert!(err.contains("only '~/'"), "{entry}: {err}");
        }
    }

    /// `~` without a resolvable home is an environment error at compile time,
    /// for every entry kind.
    #[test]
    fn tilde_without_a_home_is_refused() {
        for entry in ["~/docs", "glob:~/docs/**", "regex:~/docs/.*"] {
            let err = compile_err(entry, "/w", None);
            assert!(err.contains("no home directory"), "{entry}: {err}");
        }
    }

    /// A dot component in the middle of a glob can never match a canonical
    /// path, so it is refused instead of silently matching nothing.
    #[test]
    fn interior_dot_components_in_globs_are_refused() {
        for entry in ["glob:/a/../b/**", "glob:/a/./b", "glob:a/../../b"] {
            let err = compile_err(entry, "/w/x", None);
            assert!(err.contains("cannot contain"), "{entry}: {err}");
        }
    }

    #[test]
    fn a_relative_glob_cannot_climb_past_the_root() {
        let err = compile_err("glob:../../../x/**", "/w", None);
        assert!(err.contains("escapes the filesystem root"), "got: {err}");
    }

    // -- exact entries -----------------------------------------------------

    #[test]
    fn an_exact_root_grants_its_subtree_and_nothing_else() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join("sub")).unwrap();
        std::fs::write(root.join("sub/f.txt"), b"x").unwrap();
        let outside = tempfile::tempdir().unwrap();
        let outside_file = outside.path().join("f.txt");
        std::fs::write(&outside_file, b"x").unwrap();

        let s = set(&[root.to_str().unwrap()], "/w", None, false);
        assert!(s.matches(&root.join("sub/f.txt")));
        assert!(!s.matches(&std::fs::canonicalize(&outside_file).unwrap()));
    }

    /// The entry itself may be uncanonicalized (macOS `/tmp` vs
    /// `/private/tmp`); the root is canonicalized at match time.
    #[test]
    fn an_uncanonicalized_exact_root_still_matches() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("f.txt"), b"x").unwrap();
        let s = set(&[dir.path().to_str().unwrap()], "/w", None, false);
        assert!(s.matches(&std::fs::canonicalize(dir.path().join("f.txt")).unwrap()));
    }

    /// A root that cannot be verified never matches - the canonicalized
    /// candidate exists, so it cannot really live under a nonexistent root.
    #[test]
    fn a_nonexistent_exact_root_never_matches() {
        let dir = tempfile::tempdir().unwrap();
        let real = std::fs::canonicalize(dir.path()).unwrap();
        let s = set(&["/definitely/not/a/real/root"], "/w", None, false);
        assert!(!s.matches(&real));
    }

    #[test]
    fn a_relative_exact_entry_resolves_against_the_workdir() {
        let parent = tempfile::tempdir().unwrap();
        let workdir = parent.path().join("work");
        let sibling = parent.path().join("shared");
        std::fs::create_dir_all(&workdir).unwrap();
        std::fs::create_dir_all(&sibling).unwrap();
        std::fs::write(sibling.join("doc.md"), b"x").unwrap();

        let s = set(&["../shared"], workdir.to_str().unwrap(), None, false);
        assert!(s.matches(&std::fs::canonicalize(sibling.join("doc.md")).unwrap()));
    }

    #[test]
    fn tilde_exact_entries_expand_to_the_home_argument() {
        let home = tempfile::tempdir().unwrap();
        std::fs::create_dir(home.path().join("docs")).unwrap();
        std::fs::write(home.path().join("docs/a.md"), b"x").unwrap();
        let home_str = home.path().to_str().unwrap();

        let bare = set(&["~"], "/w", Some(home_str), false);
        let scoped = set(&["~/docs"], "/w", Some(home_str), false);
        let canonical = std::fs::canonicalize(home.path().join("docs/a.md")).unwrap();
        assert!(bare.matches(&canonical));
        assert!(scoped.matches(&canonical));
    }

    // -- glob entries (matching is pure string work, no filesystem) --------

    #[test]
    fn star_stays_within_one_component_and_doublestar_crosses() {
        let s = set(&["glob:/data/runs/*"], "/w", None, false);
        assert!(s.matches(Path::new("/data/runs/r1")));
        assert!(!s.matches(Path::new("/data/runs/r1/log.txt")));

        let deep = set(&["glob:/data/runs/**"], "/w", None, false);
        assert!(deep.matches(Path::new("/data/runs/r1/log.txt")));
        assert!(!deep.matches(Path::new("/data/other/x")));
    }

    #[test]
    fn a_relative_glob_is_anchored_at_the_workdir() {
        let s = set(&["glob:../shared/**"], "/w/agent", None, false);
        assert!(s.matches(Path::new("/w/shared/notes/a.md")));
        assert!(!s.matches(Path::new("/w/agent/own.md")));
        assert!(!s.matches(Path::new("/elsewhere/shared/a.md")));
    }

    /// A relative glob anchored at the filesystem root itself: the root's
    /// trailing-empty split segment must not double the separator.
    #[test]
    fn a_relative_glob_works_from_a_root_workdir() {
        let s = set(&["glob:docs/**"], "/", None, false);
        assert!(s.matches(Path::new("/docs/a.md")));
        assert!(!s.matches(Path::new("/other/a.md")));
    }

    /// A pattern that is nothing but dot components (`glob:../`) reduces to
    /// the folded prefix alone and matches exactly that directory.
    #[test]
    fn a_dots_only_glob_matches_the_folded_directory_itself() {
        let s = set(&["glob:../"], "/a/b", None, false);
        assert!(s.matches(Path::new("/a")));
        assert!(!s.matches(Path::new("/a/b")));
    }

    /// The workdir is data: glob metacharacters in it must match literally.
    #[test]
    fn a_metachar_workdir_is_escaped_in_relative_globs() {
        let s = set(&["glob:./docs/**"], "/we[ird]/w", None, false);
        assert!(s.matches(Path::new("/we[ird]/w/docs/a.md")));
        // If the workdir were spliced in unescaped, `[ird]` would be a class
        // and this single-character variant would match.
        assert!(!s.matches(Path::new("/wei/w/docs/a.md")));
    }

    /// The home directory is data too.
    #[test]
    fn a_metachar_home_is_escaped_in_tilde_globs() {
        let s = set(&["glob:~/docs/**"], "/w", Some("/ho[me]"), false);
        assert!(s.matches(Path::new("/ho[me]/docs/a.md")));
        assert!(!s.matches(Path::new("/hom/docs/a.md")));
    }

    /// Windows-style pattern text is normalized to `/` so blueprints written
    /// with backslashes keep working.
    #[test]
    fn backslash_glob_patterns_are_normalized() {
        let s = set(&[r"glob:C:\data\runs\**"], "/w", None, true);
        assert!(s.matches(Path::new(r"C:\data\runs\r1\log.txt")));
    }

    #[test]
    fn glob_case_sensitivity_follows_the_platform_flag() {
        let insensitive = set(&["glob:/Data/**"], "/w", None, true);
        assert!(insensitive.matches(Path::new("/data/x")));
        let sensitive = set(&["glob:/Data/**"], "/w", None, false);
        assert!(!sensitive.matches(Path::new("/data/x")));
    }

    // -- regex entries -----------------------------------------------------

    /// The anchor is the point: an unanchored `regex:/etc/runs` must not
    /// match `/etc/runs-anything` or `/prefix/etc/runs`.
    #[test]
    fn regexes_are_anchored_to_the_whole_path() {
        let s = set(&["regex:/etc/runs"], "/w", None, false);
        assert!(s.matches(Path::new("/etc/runs")));
        assert!(!s.matches(Path::new("/etc/runs-anything")));
        assert!(!s.matches(Path::new("/prefix/etc/runs")));

        let subtree = set(&["regex:/etc/runs/.*"], "/w", None, false);
        assert!(subtree.matches(Path::new("/etc/runs/deep/file")));
    }

    #[test]
    fn regex_case_sensitivity_follows_the_platform_flag() {
        let insensitive = set(&["regex:/Data/.*"], "/w", None, true);
        assert!(insensitive.matches(Path::new("/data/x")));
        let sensitive = set(&["regex:/Data/.*"], "/w", None, false);
        assert!(!sensitive.matches(Path::new("/data/x")));
    }

    /// The home is spliced in escaped, so a metacharacter in the home path
    /// matches itself and nothing else.
    #[test]
    fn a_metachar_home_is_escaped_in_tilde_regexes() {
        let s = set(&["regex:~/docs/.*"], "/w", Some("/ho.me"), false);
        assert!(s.matches(Path::new("/ho.me/docs/a")));
        assert!(!s.matches(Path::new("/hoXme/docs/a")));
    }

    /// A drive-letter regex is accepted as absolute-shaped.
    #[test]
    fn a_drive_letter_regex_is_accepted() {
        let s = set(&["regex:C:/data/.*"], "/w", None, true);
        assert!(s.matches(Path::new(r"C:\data\x")));
    }

    // -- normalize_match_str ----------------------------------------------

    #[test]
    fn unix_strings_pass_through_untouched() {
        assert_eq!(
            normalize_match_str(r"/a/weird\name", false),
            r"/a/weird\name"
        );
    }

    #[test]
    fn windows_verbatim_prefixes_are_stripped_for_matching() {
        assert_eq!(normalize_match_str(r"\\?\C:\Users\x", true), "C:/Users/x");
        assert_eq!(
            normalize_match_str(r"\\?\UNC\srv\share\x", true),
            "//srv/share/x"
        );
        // Unrecognized verbatim forms are left alone (they fail to match
        // drive-letter patterns, which is the safe direction).
        assert_eq!(
            normalize_match_str(r"\\?\Volume{abc}\x", true),
            "//?/Volume{abc}/x"
        );
        assert_eq!(normalize_match_str(r"C:\plain\x", true), "C:/plain/x");
    }

    // -- policy ------------------------------------------------------------

    fn policy(blueprint: &[&str], grants: &[&str], allow_blueprint: bool) -> ReadPathPolicy {
        ReadPathPolicy {
            agent: "tester".into(),
            blueprint: set(blueprint, "/w", None, false),
            grants: set(grants, "/w", None, false),
            allow_blueprint,
        }
    }

    #[test]
    fn an_inactive_policy_declares_nothing() {
        let p = ReadPathPolicy::inactive();
        assert!(!p.is_active());
        assert_eq!(
            p.decide(Path::new("/anything")),
            ReadPathDecision::NotDeclared
        );
    }

    #[test]
    fn a_path_the_blueprint_never_declared_is_not_declared() {
        let p = policy(&["glob:/data/**"], &["glob:/data/**"], false);
        assert!(p.is_active());
        assert_eq!(
            p.decide(Path::new("/etc/passwd")),
            ReadPathDecision::NotDeclared
        );
    }

    /// Declared but ungranted: the blueprint alone grants nothing. This is
    /// the tighten-only invariant.
    #[test]
    fn a_declared_but_ungranted_path_is_not_granted() {
        let p = policy(&["glob:/data/**"], &[], false);
        assert_eq!(p.decide(Path::new("/data/x")), ReadPathDecision::NotGranted);
    }

    #[test]
    fn a_granted_path_is_allowed() {
        let p = policy(&["glob:/data/**"], &["glob:/data/**"], false);
        assert_eq!(p.decide(Path::new("/data/x")), ReadPathDecision::Allowed);
    }

    /// The grant need not be textually identical - it is a second predicate,
    /// so a broad user grant covers a narrow blueprint declaration.
    #[test]
    fn a_broader_grant_covers_a_narrow_declaration() {
        let p = policy(&["glob:/data/runs/**"], &["glob:/data/**"], false);
        assert_eq!(
            p.decide(Path::new("/data/runs/r1")),
            ReadPathDecision::Allowed
        );
    }

    /// A grant that does not cover the declared path does nothing: both
    /// predicates must hold for the same path.
    #[test]
    fn a_nonoverlapping_grant_does_not_help() {
        let p = policy(&["glob:/data/**"], &["glob:/other/**"], false);
        assert_eq!(p.decide(Path::new("/data/x")), ReadPathDecision::NotGranted);
    }

    #[test]
    fn the_blanket_override_honors_declarations_without_grants() {
        let p = policy(&["glob:/data/**"], &[], true);
        assert_eq!(p.decide(Path::new("/data/x")), ReadPathDecision::Allowed);
        // The override does not widen beyond what is declared.
        assert_eq!(p.decide(Path::new("/etc/x")), ReadPathDecision::NotDeclared);
    }

    #[test]
    fn an_empty_set_matches_nothing() {
        let s = set(&[], "/w", None, false);
        assert!(s.is_empty());
        assert!(s.entries().is_empty());
        assert!(!s.matches(Path::new("/anything")));
    }

    // -- validate_entry_syntax --------------------------------------------

    #[test]
    fn syntax_validation_accepts_well_formed_entries() {
        for entry in [
            "/abs/dir",
            "relative/dir",
            "~/docs",
            "glob:~/runs/**",
            "glob:../shared/**",
            "regex:/data/.*",
            r"C:\Users\me\docs",
        ] {
            assert!(validate_entry_syntax(entry).is_ok(), "{entry}");
        }
    }

    #[test]
    fn syntax_validation_refuses_malformed_entries() {
        for entry in ["", "glob:[", "regex:(", "regex:relative/.*", "~oops"] {
            assert!(validate_entry_syntax(entry).is_err(), "{entry}");
        }
    }

    // -- sample paths ------------------------------------------------------

    /// The one sample an entry stands for, or `None` when none could be built.
    fn sample_path_of(entry: &str, workdir: &str, home: Option<&str>) -> Option<PathBuf> {
        set(&[entry], workdir, home, false).entries()[0].sample_path()
    }

    /// The same, as a string, for the pattern entries whose samples are built
    /// from `/`-separated text on every platform.
    fn sample(entry: &str, workdir: &str, home: Option<&str>) -> Option<String> {
        sample_path_of(entry, workdir, home).map(|p| p.to_string_lossy().into_owned())
    }

    /// An exact entry compiles to a `PathBuf`, so a tilde or relative entry is
    /// joined with the platform separator. Compared as paths rather than as
    /// strings for that reason: `/home/me\docs` on Windows is the same answer.
    #[test]
    fn an_exact_entry_samples_as_its_own_root() {
        assert_eq!(
            sample("/data/runs", "/w", None).as_deref(),
            Some("/data/runs")
        );
        assert_eq!(
            sample_path_of("~/docs", "/w", Some("/home/me")),
            Some(Path::new("/home/me").join("docs"))
        );
        // A relative entry samples as the workdir-resolved path it compiled to.
        assert_eq!(
            sample_path_of("../shared", "/w/run", None),
            Some(Path::new("/w/run").join("../shared"))
        );
    }

    #[test]
    fn glob_wildcards_are_filled_with_a_literal_component() {
        assert_eq!(
            sample("glob:/data/**", "/w", None).as_deref(),
            Some("/data/_leviath_probe")
        );
        assert_eq!(
            sample("glob:/data/*/notes", "/w", None).as_deref(),
            Some("/data/_leviath_probe/notes")
        );
        assert_eq!(
            sample("glob:/data/log?", "/w", None).as_deref(),
            Some("/data/logx")
        );
        // A pattern with no wildcards at all samples as itself.
        assert_eq!(
            sample("glob:/data/notes", "/w", None).as_deref(),
            Some("/data/notes")
        );
    }

    /// A character class carries glob's escape syntax too, so its expansion
    /// would have to be guessed at. Refuse rather than report a wrong answer.
    #[test]
    fn a_glob_character_class_has_no_sample() {
        assert_eq!(sample("glob:/data/[abc]/x", "/w", None), None);
    }

    /// `*` cannot cross a separator, so a sample that put one there would not
    /// match the pattern it came from. The self-check catches it.
    #[test]
    fn a_sample_that_fails_its_own_pattern_is_refused() {
        let entry = ReadPathEntry::Glob {
            pattern: glob::Pattern::new("/data/*").expect("pattern compiles"),
            options: glob::MatchOptions {
                case_sensitive: true,
                require_literal_separator: true,
                require_literal_leading_dot: false,
            },
        };
        // Force the mismatch: a pattern whose only wildcard is escaped as a
        // literal `*` can never match the substituted component.
        let literal_star = ReadPathEntry::Glob {
            pattern: glob::Pattern::new("/data/[*]").expect("pattern compiles"),
            options: glob::MatchOptions {
                case_sensitive: true,
                require_literal_separator: true,
                require_literal_leading_dot: false,
            },
        };
        assert!(entry.sample_path().is_some());
        assert_eq!(literal_star.sample_path(), None);
    }

    #[test]
    fn a_regex_samples_a_file_inside_its_literal_prefix() {
        assert_eq!(
            sample("regex:/data/archives/.*", "/w", None).as_deref(),
            Some("/data/archives/_leviath_probe")
        );
        // All-literal: the pattern itself is the only path it matches.
        assert_eq!(
            sample("regex:/data/archives", "/w", None).as_deref(),
            Some("/data/archives")
        );
        assert_eq!(
            sample("regex:~/runs/.*", "/w", Some("/home/me")).as_deref(),
            Some("/home/me/runs/_leviath_probe")
        );
    }

    /// Nothing literal to build on, and nothing that self-checks: report
    /// "cannot tell" instead of a sample the entry does not match.
    #[test]
    fn a_regex_with_no_usable_literal_prefix_has_no_sample() {
        let entry =
            ReadPathEntry::Regex(regex::Regex::new("^(?:[/a-z]+)$").expect("regex compiles"));
        assert_eq!(entry.sample_path(), None);
    }

    /// Anchoring is added at compile time; a regex that arrives without it is
    /// read as its own body rather than as a leading `^`, which would leave no
    /// literal prefix to build on.
    #[test]
    fn an_unanchored_regex_is_read_as_written() {
        let entry = ReadPathEntry::Regex(regex::Regex::new("/data/x.*").expect("regex compiles"));
        assert_eq!(entry.sample_path(), Some(PathBuf::from("/data/x")));
    }

    // -- lexical matching --------------------------------------------------

    #[test]
    fn lexical_matching_covers_a_root_and_its_subtree() {
        let s = set(&["/data/runs"], "/w", None, false);
        assert!(s.matches_lexically(Path::new("/data/runs")));
        assert!(s.matches_lexically(Path::new("/data/runs/june/1")));
        assert!(!s.matches_lexically(Path::new("/data/runs-old/1")));
        assert!(!s.matches_lexically(Path::new("/data")));
    }

    /// The whole point of the lexical variant: a grant naming a directory that
    /// does not exist yet is still a grant. `matches` refuses it (it cannot
    /// canonicalize the root), `matches_lexically` does not.
    #[test]
    fn lexical_matching_does_not_need_the_root_to_exist() {
        let s = set(&["/definitely/not/here"], "/w", None, false);
        assert!(s.matches_lexically(Path::new("/definitely/not/here/x")));
        assert!(!s.matches(Path::new("/definitely/not/here/x")));
    }

    /// The entry is written `/`-first so it compiles as an absolute root on
    /// every host; only the case folding is under test.
    #[test]
    fn lexical_matching_folds_case_under_windows_semantics() {
        let windows = set(&["/Users/Me/docs"], "/w", None, true);
        assert!(windows.matches_lexically(Path::new("/users/me/docs/notes.md")));
        let unix = set(&["/Users/Me/docs"], "/w", None, false);
        assert!(!unix.matches_lexically(Path::new("/users/me/docs/notes.md")));
    }

    /// A filesystem root trims to nothing; everything under it still matches.
    #[test]
    fn lexical_matching_handles_a_root_entry() {
        let s = set(&["/"], "/w", None, false);
        assert!(s.matches_lexically(Path::new("/etc/passwd")));
        assert!(s.matches_lexically(Path::new("/")));
    }

    #[test]
    fn lexical_matching_uses_the_pattern_entries_unchanged() {
        let s = set(&["glob:/data/**", "regex:/logs/.*"], "/w", None, false);
        assert!(s.matches_lexically(Path::new("/data/x/y")));
        assert!(s.matches_lexically(Path::new("/logs/today")));
        assert!(!s.matches_lexically(Path::new("/elsewhere/x")));
    }
}