silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
1110
use anyhow::{bail, Context, Result};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

/// Set by a run whose own writes are the only ones to its tree and each goes through `forget`:
/// between two writes every walk of one directory lists the same files, so each listing is
/// read once.
static READ_ONLY: AtomicBool = AtomicBool::new(false);

type Listing = Option<HashSet<PathBuf>>;
type Listings = Mutex<HashMap<(PathBuf, Vec<String>), Listing>>;

fn listings() -> &'static Listings {
    static CACHE: OnceLock<Listings> = OnceLock::new();
    CACHE.get_or_init(Default::default)
}

/// One walk, filled by the first thread that asks for it while the others wait on it.
type Slot = Arc<Mutex<Option<Vec<PathBuf>>>>;
type Walks = Mutex<HashMap<(&'static str, PathBuf), Slot>>;

fn walks() -> &'static Walks {
    static CACHE: OnceLock<Walks> = OnceLock::new();
    CACHE.get_or_init(Default::default)
}

/// Marks the run as one whose walks are read once between its writes.
pub fn read_only_run() {
    READ_ONLY.store(true, Ordering::Relaxed);
}

/// Drops every listing and walk read so far, as a write to the tree may create or delete a file.
pub fn forget() {
    listings().lock().expect("listing cache").clear();
    walks().lock().expect("walk cache").clear();
}

/// `walk()` of `root`, once between two writes of a run `read_only_run` marked.
fn walked(
    kind: &'static str,
    root: &Path,
    walk: impl Fn() -> Result<Vec<PathBuf>>,
) -> Result<Vec<PathBuf>> {
    if !READ_ONLY.load(Ordering::Relaxed) {
        return walk();
    }
    let slot = Arc::clone(
        walks()
            .lock()
            .expect("walk cache")
            .entry((kind, root.to_path_buf()))
            .or_default(),
    );
    let mut slot = slot.lock().expect("walk slot");
    if let Some(found) = slot.as_ref() {
        return Ok(found.clone());
    }
    let found = walk()?;
    *slot = Some(found.clone());
    Ok(found)
}

#[cfg_attr(not(test), allow(dead_code))]
pub const CODE_EXTS: &[&str] = &[
    "rs",
    "ts",
    "mts",
    "cts",
    "tsx",
    "js",
    "jsx",
    "mjs",
    "cjs",
    "py",
    "html",
    "htm",
    "css",
    "hcl",
    "tf",
    "tfvars",
    "sh",
    "bash",
    "yaml",
    "yml",
    "cedar",
    "dockerfile",
    "containerfile",
    "prisma",
    "jsonc",
    "md",
];

const SKIP_EXTS: &[&str] = &[
    "png",
    "jpg",
    "jpeg",
    "gif",
    "webp",
    "ico",
    "bmp",
    "tif",
    "tiff",
    "heic",
    "avif",
    "psd",
    "pdf",
    "zip",
    "gz",
    "tgz",
    "bz2",
    "xz",
    "zst",
    "7z",
    "rar",
    "tar",
    "wasm",
    "so",
    "dylib",
    "a",
    "o",
    "rlib",
    "rmeta",
    "bin",
    "exe",
    "dll",
    "class",
    "jar",
    "pyc",
    "pyo",
    "woff",
    "woff2",
    "ttf",
    "otf",
    "eot",
    "mp3",
    "mp4",
    "wav",
    "flac",
    "ogg",
    "m4a",
    "mov",
    "mkv",
    "avi",
    "webm",
    "lock",
    "sock",
    "npy",
    "npz",
    "pkl",
    "parquet",
    "feather",
    "arrow",
    "avro",
    "h5",
    "hdf5",
    "onnx",
    "pt",
    "pth",
    "safetensors",
    "sqlite",
    "sqlite3",
    "db",
    "xlsx",
    "xls",
    "docx",
    "pptx",
];

/// Build and dependency directories, which the walk skips only outside git, where nothing says
/// which files belong to the project.
const SKIP_DIRS: &[&str] = &["target", "node_modules", ".cargo"];

/// Whether a walk leaves out the directory at `path`: `.git`, and a directory named in
/// `SKIP_DIRS` outside git or, in git, holding no file git tracks or does not ignore.
pub fn skips_dir(path: &Path) -> Result<bool> {
    // § r4dndth75.b@33zrj
    let name = path.file_name().unwrap_or_default();
    if name == ".git" {
        return Ok(true);
    }
    if !SKIP_DIRS.iter().any(|skip| name == *skip) {
        return Ok(false);
    }
    match git_listed(path)? {
        Some(listed) => Ok(listed.is_empty()),
        None => Ok(!crate::workspace::root_of(path).join(".git").exists()),
    }
}

/// A directory is a project when its `AGENTS.md` carries a Silcrow block, under any tag the
/// harness accepts.
pub fn is_project(dir: &Path) -> bool {
    // § r4dndth75.a@vgect
    std::fs::read_to_string(dir.join("AGENTS.md")).is_ok_and(|text| crate::scheme::has_block(&text))
}

/// A walk from a project never enters a nested project or a nested repository.
fn is_boundary(dir: &Path) -> bool {
    // § r4dndth75.b@y629p
    dir.join(".git").exists() || is_project(dir)
}

pub struct Project {
    pub root: PathBuf,
    pub notes: Notes,
    /// The public documentation, the `docs` list of the block.
    pub docs: Patterns,
}

impl Project {
    pub fn at(root: &Path) -> Result<Self> {
        let agents = std::fs::read_to_string(root.join("AGENTS.md")).ok();
        Ok(Self {
            root: root.to_path_buf(),
            notes: Notes::from_agents(agents.as_deref())
                .map_err(|e| anyhow::anyhow!("{}: {e}", root.join("AGENTS.md").display()))?,
            docs: crate::policy::ProjectPolicy::from_agents(agents.as_deref())
                .map_err(anyhow::Error::msg)?
                .docs,
        })
    }

    /// Whether the file at `rel`, relative to the project root, is public documentation: the
    /// `docs` list matches it and it is no decision note.
    pub fn is_doc(&self, rel: &Path) -> bool {
        !self.is_note(rel) && self.docs.matches(rel)
    }

    /// Whether the file at `rel`, relative to the project root, is a decision note.
    pub fn is_note(&self, rel: &Path) -> bool {
        self.notes.holds(rel)
    }

    /// Whether a file at `rel`, relative to the project root, is code or a documentation
    /// surface by its own path.
    pub fn holds_code(&self, rel: &Path) -> bool {
        // § r4dndth75.h@5v7v3
        let Some(ext) = rel.extension().and_then(|e| e.to_str()) else {
            // A name alone picks a grammar, as `Dockerfile` does.
            return crate::span_lang::lang_for_path(rel).is_some();
        };
        // § end r4dndth75.h
        !SKIP_EXTS.contains(&ext) && !self.is_note(rel)
    }
}

/// The list a block's `notes` attribute writes when it omits it.
pub const DEFAULT_NOTES: &str = "docs/decisions/**/*.md";

/// A list of patterns of a block attribute, relative to the project root, split on spaces, as in
/// a gitignore. One that opens with `!` excludes, the last pattern that matches a path decides
/// it, and a pattern that matches a directory matches every path below it.
#[derive(Clone, Debug, Default)]
pub struct Patterns {
    patterns: Vec<(bool, String, globset::GlobMatcher)>,
}

/// Each matcher is compiled from its pattern, so the patterns decide equality.
impl PartialEq for Patterns {
    fn eq(&self, other: &Self) -> bool {
        let key = |p: &Self| -> Vec<(bool, String)> {
            p.patterns.iter().map(|(b, s, _)| (*b, s.clone())).collect()
        };
        key(self) == key(other)
    }
}

impl Patterns {
    /// The patterns of `list`, the value of the attribute `attr`. A list that includes no path is
    /// `Ok` only when it is empty, and then matches nothing.
    pub fn parse(attr: &str, list: &str) -> Result<Self> {
        // § r40mp2y8s.a@5wt28
        let mut patterns = Vec::new();
        for raw in list.split_whitespace() {
            let (include, body) = match raw.strip_prefix('!') {
                Some(rest) => (false, rest),
                None => (true, raw),
            };
            // § r40mp2y8s.c@f7f0e
            if body.starts_with(['/', '\\']) || Path::new(body).is_absolute() {
                bail!("the `{attr}` pattern `{raw}` is an absolute path: write it relative to the project");
            }
            let segments: Vec<&str> = body
                .split(['/', '\\'])
                .filter(|s| !s.is_empty() && *s != ".")
                .collect();
            if segments.contains(&"..") {
                bail!("the `{attr}` pattern `{raw}` leaves the project through `..`: write it inside the project");
            }
            // § end r40mp2y8s.c
            if segments.is_empty() {
                bail!("the `{attr}` pattern `{raw}` names no path");
            }
            let glob = segments.join("/");
            let matcher = globset::GlobBuilder::new(&glob)
                .literal_separator(true)
                .backslash_escape(true)
                .build()
                .map_err(|e| anyhow::anyhow!("the `{attr}` pattern `{raw}` is not a glob: {e}"))?
                .compile_matcher();
            patterns.push((include, glob, matcher));
        }
        if !patterns.is_empty() && !patterns.iter().any(|(include, ..)| *include) {
            bail!("the `{attr}` list `{list}` includes no path");
        }
        Ok(Self { patterns })
    }

    /// Whether the list includes no path.
    pub fn is_empty(&self) -> bool {
        self.patterns.is_empty()
    }

    /// Whether the list matches `rel`, relative to the project root.
    pub fn matches(&self, rel: &Path) -> bool {
        let rel = rel.to_string_lossy().replace('\\', "/");
        let rel = Path::new(&rel);
        self.patterns
            .iter()
            .rev()
            .find(|(_, _, glob)| {
                rel.ancestors()
                    .any(|p| !p.as_os_str().is_empty() && glob.is_match(p))
            })
            .is_some_and(|(include, ..)| *include)
    }
}

/// The `notes` list of a block, the patterns of its decision notes.
#[derive(Clone, Debug)]
pub struct Notes {
    patterns: Patterns,
}

impl Notes {
    /// The list of `agents`, an `AGENTS.md` text, or `DEFAULT_NOTES` when its block omits it.
    pub fn from_agents(agents: Option<&str>) -> Result<Self> {
        // § r40mp2y8s.b@jbyqy
        match agents.and_then(|text| crate::scheme::attr_from_agents(text, "notes")) {
            Some(list) => Self::parse(&list),
            None => Self::parse(DEFAULT_NOTES),
        }
    }

    /// The list of `agents`, an `AGENTS.md` text that a commit holds, read as that commit wrote
    /// it.
    pub fn at_commit(agents: Option<&str>) -> Result<Self> {
        Self::from_agents(agents.map(crate::scheme::at_commit).as_deref())
    }

    pub fn parse(list: &str) -> Result<Self> {
        // § r40mp2y8s.b@er2bh
        let patterns = Patterns::parse("notes", list)?;
        if patterns.is_empty() {
            bail!("the `notes` list `{list}` includes no path: name the decision notes, or omit the attribute for `{DEFAULT_NOTES}`");
        }
        Ok(Self { patterns })
    }

    /// Whether `rel`, relative to the project root, is a Markdown file the list matches.
    pub fn holds(&self, rel: &Path) -> bool {
        // § r40mp2y8s.a@eh1qv
        rel.extension().and_then(|e| e.to_str()) == Some("md") && self.patterns.matches(rel)
    }

    /// The paths, relative to the project root, at or below which every path the list includes
    /// lies: the literal segments that open each including pattern.
    pub fn roots(&self) -> Vec<PathBuf> {
        let mut out: Vec<PathBuf> = self
            .patterns
            .patterns
            .iter()
            .filter(|(include, ..)| *include)
            .map(|(_, glob, _)| {
                glob.split('/')
                    .take_while(|s| !s.contains(['*', '?', '[', '{', '\\']))
                    .collect()
            })
            .collect();
        out.sort();
        out.dedup();
        let all = out.clone();
        out.retain(|dir| {
            !all.iter()
                .any(|other| other != dir && dir.starts_with(other))
        });
        out
    }
}

/// Whether `rel`, relative to `root`, is a decision note of the nearest project above it.
pub fn is_note_in(root: &Path, rel: &Path) -> Result<bool> {
    for dir in rel.ancestors().skip(1) {
        let at = root.join(dir);
        if is_project(&at) {
            let project = Project::at(&at)?;
            return Ok(rel.strip_prefix(dir).is_ok_and(|rel| project.is_note(rel)));
        }
    }
    Ok(false)
}

pub fn decision_files(root: &Path) -> Result<Vec<PathBuf>> {
    // § r40mp2y8s@13zrz
    walked("notes", root, || {
        let project = Project::at(root)?;
        let mut out = Vec::new();
        walk(root, &mut out, &|path| {
            project.is_note(path.strip_prefix(&project.root).unwrap_or(path))
        })?;
        Ok(out)
    })
}

pub fn doc_files(root: &Path) -> Result<Vec<PathBuf>> {
    // § xs2e8kj86.f@vjhx9
    let project = Project::at(root)?;
    Ok(code_files(root)?
        .into_iter()
        .filter(|path| project.is_doc(path.strip_prefix(&project.root).unwrap_or(path)))
        .collect())
}

pub fn code_files(root: &Path) -> Result<Vec<PathBuf>> {
    // § xs2e8kj86.f@vaewj
    walked("code", root, || {
        read_each(code_candidates(root)?, ReadAs::Text)
    })
}

/// The files in another text encoding that the code walk of `root` skips, each of which `check`
/// names. A binary file is skipped unnamed, as an image is.
pub fn skipped_files(root: &Path) -> Result<Vec<PathBuf>> {
    read_each(code_candidates(root)?, ReadAs::Foreign)
}

/// The `paths` read as `want`, in order, failing on the first that cannot be read.
fn read_each(paths: Vec<PathBuf>, want: ReadAs) -> Result<Vec<PathBuf>> {
    let read = crate::par::map_many(paths, |path| read_as(&path).map(|read| (path, read)));
    let mut out = Vec::new();
    for found in read {
        let (path, read) = found?;
        if read == want {
            out.push(path);
        }
    }
    Ok(out)
}

fn code_candidates(root: &Path) -> Result<Vec<PathBuf>> {
    walked("candidates", root, || {
        let project = Project::at(root)?;
        let mut out = Vec::new();
        walk(root, &mut out, &|path| {
            project.holds_code(path.strip_prefix(&project.root).unwrap_or(path))
        })?;
        Ok(out)
    })
}

/// How the walk reads a file.
#[derive(Debug, PartialEq, Eq)]
enum ReadAs {
    /// UTF-8 text, which the walk reads.
    Text,
    /// Binary, which the walk skips.
    Binary,
    /// Text in another encoding that can carry no marker, which the walk skips.
    Foreign,
}

/// How the walk reads the file at `path`. A file that is not UTF-8 text is skipped when it can
/// carry no marker: a binary one, or text in another encoding whose extension is no grammar
/// Silcrow parses and that holds no line shaped as a marker. Fails, naming it, on any other
/// file that is not UTF-8 text or cannot be read.
fn read_as(path: &Path) -> Result<ReadAs> {
    // § r4dndth75.f@7dhr2
    let bytes = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
    if std::str::from_utf8(&bytes).is_ok() {
        return Ok(ReadAs::Text);
    }
    if is_binary(&bytes) {
        return Ok(ReadAs::Binary);
    }
    // The hook walks a copy of the index inside the git directory, so the path is named from
    // the root of the tree it is in.
    let shown = path
        .ancestors()
        .skip(1)
        .find(|dir| dir.join(".git").exists())
        .and_then(|root| path.strip_prefix(root).ok())
        .unwrap_or(path)
        .display();
    if crate::span_lang::lang_for_path(path).is_some() {
        bail!("{shown} is not UTF-8 text, and Silcrow parses its extension: save it as UTF-8");
    }
    if holds_marker_shape(&bytes) {
        bail!(
            "{shown} is not UTF-8 text, and a line of it is shaped as a marker Silcrow cannot read: save it as UTF-8, or stop tracking it"
        );
    }
    Ok(ReadAs::Foreign)
}

/// Whether the bytes are binary as git reads them: they hold a NUL, as encrypted, compiled and
/// compressed content does and text in an 8-bit encoding never does.
fn is_binary(bytes: &[u8]) -> bool {
    bytes.contains(&0)
}

/// Whether a line of the bytes, read as Latin-1 with a `§` written as Latin-1 or as UTF-8,
/// opens shaped as a marker.
fn holds_marker_shape(bytes: &[u8]) -> bool {
    let text: String = bytes.iter().map(|&b| char::from(b)).collect();
    text.replace("\u{c2}§", "§")
        .trim_start_matches("\u{ef}\u{bb}\u{bf}")
        .lines()
        .any(crate::marker::shaped_as_marker)
}

/// The files under the workspace `root` that the walk of no project reaches, none when `root`
/// is itself a project. Like a project walk, it stops at every project and nested `.git`, and
/// leaves out the files `read_as` skips.
pub fn files_outside_projects(root: &Path) -> Result<Vec<PathBuf>> {
    let mut found = Vec::new();
    if is_project(root) {
        return Ok(found);
    }
    walk(root, &mut found, &|path| {
        path.extension()
            .and_then(|e| e.to_str())
            .is_none_or(|ext| !SKIP_EXTS.contains(&ext))
    })?;
    let mut out = Vec::new();
    for path in found {
        if read_as(&path)? == ReadAs::Text {
            out.push(path);
        }
    }
    Ok(out)
}

/// Whether a file at `rel` in the project, one git tracks at some revision and present on disk
/// or not, is one `code_files` walks.
pub fn walks_to(project: &Project, rel: &Path) -> bool {
    let mut dir = rel.parent();
    while let Some(d) = dir.filter(|d| !d.as_os_str().is_empty()) {
        if is_boundary(&project.root.join(d)) {
            return false;
        }
        dir = d.parent();
    }
    project.holds_code(rel)
}

/// Whether a file at `rel` in the project now lies in a nested project that a run checks: one
/// no nested repository holds, since a project behind a `.git` is never checked.
pub fn in_checked_nested_project(project: &Project, rel: &Path) -> bool {
    // § j44p1s9z8.a@h0ya4
    !behind_nested_repo(&project.root, rel)
        && dirs_of(rel).any(|d| is_project(&project.root.join(d)))
}

/// Whether a file at `rel` in the project lies behind a repository nested in `root`, which no
/// run reads.
pub fn behind_nested_repo(root: &Path, rel: &Path) -> bool {
    dirs_of(rel).any(|d| root.join(d).join(".git").exists())
}

/// The directories between a project root and the file at `rel`, innermost first.
fn dirs_of(rel: &Path) -> impl Iterator<Item = &Path> {
    rel.ancestors()
        .skip(1)
        .filter(|d| !d.as_os_str().is_empty())
}

fn walk(dir: &Path, out: &mut Vec<PathBuf>, keep: &dyn Fn(&Path) -> bool) -> Result<()> {
    if !dir.is_dir() {
        return Ok(());
    }
    let listed = git_listed(dir)?;
    descend(dir, out, &|path| {
        keep(path) && listed.as_ref().is_none_or(|files| files.contains(path))
    })?;
    out.sort();
    Ok(())
}

/// The files under `dir` that git tracks or that are untracked and not ignored, none outside
/// git, where every file counts.
fn git_listed(dir: &Path) -> Result<Option<HashSet<PathBuf>>> {
    // § r4dndth75.c@5xyrn
    git_ls_files(dir, &["--cached", "--others", "--exclude-standard"])
}

/// The files under `dir` that git does not track and does not ignore, which the walk reads and
/// the index the hooks check does not hold. None outside git and in the hooks' index tree.
pub fn untracked_files(dir: &Path) -> Result<BTreeSet<PathBuf>> {
    let listed = git_ls_files(dir, &["--others", "--exclude-standard"])?;
    Ok(listed.into_iter().flatten().collect())
}

fn git_ls_files(dir: &Path, which: &[&str]) -> Result<Option<HashSet<PathBuf>>> {
    if !READ_ONLY.load(Ordering::Relaxed) {
        return list_files(dir, which);
    }
    let key = (
        dir.to_path_buf(),
        which.iter().map(|w| w.to_string()).collect(),
    );
    if let Some(found) = listings().lock().expect("listing cache").get(&key) {
        return Ok(found.clone());
    }
    let found = list_files(dir, which)?;
    listings()
        .lock()
        .expect("listing cache")
        .insert(key, found.clone());
    Ok(found)
}

fn list_files(dir: &Path, which: &[&str]) -> Result<Option<HashSet<PathBuf>>> {
    let root = crate::workspace::root_of(dir);
    let dot_git = root.join(".git");
    if !dot_git.exists() {
        return Ok(None);
    }
    // The hooks read the index as a tree written inside the git directory itself, with a `.git`
    // file pointing back to it: git cannot list from there, and every file of it is staged.
    let link = std::fs::read_to_string(&dot_git).unwrap_or_default();
    if link
        .trim()
        .strip_prefix("gitdir: ")
        .is_some_and(|git_dir| root.starts_with(git_dir))
    {
        return Ok(None);
    }
    // From the root: a hook gets GIT_INDEX_FILE relative to the root, which a nested project
    // directory would resolve wrongly.
    let out = crate::workspace::git(&root)
        .args(["ls-files", "-z"])
        .args(which)
        .args(["--full-name", "--"])
        .arg(match dir.strip_prefix(&root) {
            Ok(rel) if !rel.as_os_str().is_empty() => rel.to_path_buf(),
            _ => PathBuf::from("."),
        })
        .output()?;
    if !out.status.success() {
        bail!(
            "git ls-files in {}: {}",
            dir.display(),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(Some(
        out.stdout
            .split(|&b| b == 0)
            .filter(|rel| !rel.is_empty())
            .map(|rel| root.join(String::from_utf8_lossy(rel).as_ref()))
            .collect(),
    ))
}

fn descend(dir: &Path, out: &mut Vec<PathBuf>, keep: &dyn Fn(&Path) -> bool) -> Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if entry.file_name() == ".git" {
            continue;
        }
        let kind = entry.file_type()?;
        // § d1bc2zca5.d@2pv7p
        // A link may point out of the tree, at a body that differs per machine or is absent.
        if kind.is_symlink() {
            continue;
        }
        if kind.is_dir() {
            if is_boundary(&path) || skips_dir(&path)? {
                continue;
            }
            descend(&path, out, keep)?;
        } else if kind.is_file() && keep(&path) {
            out.push(path);
        }
    }
    Ok(())
}

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

    #[test]
    fn a_decisions_pattern_outside_the_project_or_not_a_glob_is_refused() {
        for list in [
            "/abs/docs/**",
            "../docs/**",
            "docs/../../x",
            "docs/[",
            "!docs/archive/**",
            "",
            "!",
        ] {
            assert!(Notes::parse(list).is_err(), "{list:?}");
        }
        let block = "<silcrow notes=\"\">\n</silcrow>\n";
        assert!(Notes::from_agents(Some(block)).is_err());
    }

    #[test]
    fn the_default_decisions_list_is_docs_decisions_and_only_when_omitted() {
        let notes = Notes::from_agents(Some("<silcrow>\n</silcrow>\n")).unwrap();
        assert!(notes.holds(Path::new("docs/decisions/x.md")));
        assert!(notes.holds(Path::new("docs/decisions/cli/x.md")));
        assert!(!notes.holds(Path::new("docs/guide.md")));
        assert!(!notes.holds(Path::new("docs/decisions/x.rs")));
        assert!(!notes.holds(Path::new("src/docs/decisions/x.md")));
        assert_eq!(notes.roots(), [PathBuf::from("docs/decisions")]);
        let explicit =
            Notes::from_agents(Some("<silcrow notes=\"notes/*.md\">\n</silcrow>\n")).unwrap();
        assert!(!explicit.holds(Path::new("docs/decisions/x.md")));
    }

    #[test]
    fn a_custom_decisions_list_excludes_with_a_later_negation() {
        let notes =
            Notes::parse("./docs/**/*.md !docs/archive/** docs/archive/keep.md rules").unwrap();
        assert!(notes.holds(Path::new("docs/x.md")));
        assert!(notes.holds(Path::new("docs/a/b/x.md")));
        assert!(!notes.holds(Path::new("docs/archive/old.md")));
        assert!(!notes.holds(Path::new("docs/archive/deep/old.md")));
        assert!(notes.holds(Path::new("docs/archive/keep.md")));
        assert!(
            notes.holds(Path::new("rules/pay.md")),
            "a directory covers its files"
        );
        assert!(!notes.holds(Path::new("readme.md")));
        assert_eq!(
            notes.roots(),
            [PathBuf::from("docs"), PathBuf::from("rules")]
        );
        let star = Notes::parse("*.md").unwrap();
        assert!(star.holds(Path::new("x.md")));
        assert!(!star.holds(Path::new("docs/x.md")), "`*` stops at a `/`");
        assert_eq!(star.roots(), [PathBuf::new()]);
    }

    #[test]
    fn documentation_is_what_the_docs_list_matches_outside_the_notes() {
        let dir = tempfile::tempdir().unwrap();
        for sub in ["docs/decisions", "docs/archive", "docs/ideation", "notes"] {
            std::fs::create_dir_all(dir.path().join(sub)).unwrap();
        }
        for (rel, text) in [
            ("docs/guide.md", "guide"),
            ("docs/decisions/x.md", "law"),
            ("docs/archive/old.md", "old"),
            ("docs/ideation/idea.md", "idea"),
            ("notes/n.md", "note"),
        ] {
            std::fs::write(dir.path().join(rel), text).unwrap();
        }
        let rels = |files: Vec<PathBuf>| -> Vec<String> {
            files
                .iter()
                .map(|p| {
                    p.strip_prefix(dir.path())
                        .unwrap()
                        .to_string_lossy()
                        .replace('\\', "/")
                })
                .collect()
        };
        std::fs::write(dir.path().join("AGENTS.md"), "<silcrow>\n</silcrow>\n").unwrap();
        assert!(doc_files(dir.path()).unwrap().is_empty());
        std::fs::write(
            dir.path().join("AGENTS.md"),
            "<silcrow docs=\"docs/**/*.md notes/**\">\n</silcrow>\n",
        )
        .unwrap();
        assert_eq!(
            rels(decision_files(dir.path()).unwrap()),
            ["docs/decisions/x.md"]
        );
        let docs = rels(doc_files(dir.path()).unwrap());
        for kept in [
            "docs/archive/old.md",
            "docs/ideation/idea.md",
            "docs/guide.md",
            "notes/n.md",
        ] {
            assert!(docs.contains(&kept.to_string()), "{kept}: {docs:?}");
        }
        assert!(
            !docs.contains(&"docs/decisions/x.md".to_string()),
            "{docs:?}"
        );
        let code = rels(code_files(dir.path()).unwrap());
        assert!(
            code.contains(&"docs/archive/old.md".to_string()),
            "{code:?}"
        );
        assert!(
            !code.contains(&"docs/decisions/x.md".to_string()),
            "{code:?}"
        );
        std::fs::write(
            dir.path().join("AGENTS.md"),
            "<silcrow notes=\"notes/**/*.md docs/**/*.md !docs/guide.md\" docs=\"**/*.md\">\n</silcrow>\n",
        )
        .unwrap();
        assert_eq!(
            rels(decision_files(dir.path()).unwrap()),
            [
                "docs/archive/old.md",
                "docs/decisions/x.md",
                "docs/ideation/idea.md",
                "notes/n.md"
            ]
        );
        assert_eq!(
            rels(doc_files(dir.path()).unwrap()),
            ["AGENTS.md", "docs/guide.md"]
        );
    }

    #[cfg(unix)]
    #[test]
    fn the_walk_skips_a_symlinked_file_and_directory() {
        let outside = tempfile::tempdir().unwrap();
        std::fs::write(outside.path().join("lib.py"), "def fee():\n    return 1\n").unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("app.py"), "import lib\n").unwrap();
        std::os::unix::fs::symlink(outside.path().join("lib.py"), dir.path().join("lib.py"))
            .unwrap();
        std::os::unix::fs::symlink(outside.path(), dir.path().join("vendor")).unwrap();
        let files = code_files(dir.path()).unwrap();
        assert_eq!(files, vec![dir.path().join("app.py")]);
    }

    #[test]
    fn walk_stops_at_a_nested_project_and_a_nested_repository() {
        let dir = tempfile::tempdir().unwrap();
        let block = "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n";
        std::fs::write(dir.path().join("AGENTS.md"), block).unwrap();
        std::fs::create_dir_all(dir.path().join("pkg/src")).unwrap();
        std::fs::write(dir.path().join("pkg/AGENTS.md"), block).unwrap();
        std::fs::write(dir.path().join("pkg/src/lib.rs"), "").unwrap();
        std::fs::create_dir_all(dir.path().join("vendor/x/.git")).unwrap();
        std::fs::write(dir.path().join("vendor/x/lib.rs"), "").unwrap();
        std::fs::create_dir_all(dir.path().join("plain")).unwrap();
        std::fs::write(dir.path().join("plain/AGENTS.md"), "# no block\n").unwrap();
        std::fs::write(dir.path().join("plain/lib.rs"), "").unwrap();
        let files = code_files(dir.path()).unwrap();
        let rels: Vec<_> = files
            .iter()
            .map(|p| {
                p.strip_prefix(dir.path())
                    .unwrap()
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        assert!(rels.contains(&"plain/lib.rs".to_string()), "{rels:?}");
        assert!(!rels.iter().any(|r| r.starts_with("pkg/")), "{rels:?}");
        assert!(!rels.iter().any(|r| r.starts_with("vendor/")), "{rels:?}");
    }

    #[test]
    fn in_git_the_walk_reads_tracked_and_unignored_untracked_files_only() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            let status = crate::test_git()
                .args(args)
                .current_dir(root)
                .output()
                .unwrap()
                .status;
            assert!(status.success(), "git {args:?}");
        };
        git(&["init", "-q"]);
        std::fs::write(
            root.join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\" docs=\"*.md\">\n</silcrow>\n",
        )
        .unwrap();
        std::fs::write(root.join(".gitignore"), ".venv/\nlocal.py\nnotes.md\n").unwrap();
        std::fs::create_dir_all(root.join(".venv/lib")).unwrap();
        std::fs::create_dir_all(root.join("docs/decisions")).unwrap();
        for (rel, text) in [
            ("tracked.py", "x = 1\n"),
            ("new.py", "x = 2\n"),
            ("local.py", "x = 3\n"),
            (".venv/lib/util.py", "x = 4\n"),
            ("forced.py", "x = 5\n"),
            ("guide.md", "# Guide\n"),
            ("notes.md", "# Notes\n"),
            ("docs/decisions/x.md", "# X\n"),
        ] {
            std::fs::write(root.join(rel), text).unwrap();
        }
        git(&["add", "tracked.py", "AGENTS.md", ".gitignore"]);
        git(&["add", "-f", "forced.py"]);
        std::fs::write(
            root.join(".gitignore"),
            ".venv/\nlocal.py\nnotes.md\nforced.py\n",
        )
        .unwrap();
        let rels = |files: Vec<PathBuf>| -> Vec<String> {
            files
                .iter()
                .map(|p| p.strip_prefix(root).unwrap().to_string_lossy().into_owned())
                .collect()
        };
        let code = rels(code_files(root).unwrap());
        for kept in ["tracked.py", "new.py", "forced.py"] {
            assert!(code.contains(&kept.to_string()), "{kept}: {code:?}");
        }
        for dropped in ["local.py", ".venv/lib/util.py"] {
            assert!(!code.contains(&dropped.to_string()), "{dropped}: {code:?}");
        }
        let docs = rels(doc_files(root).unwrap());
        assert!(docs.contains(&"guide.md".to_string()), "{docs:?}");
        assert!(!docs.contains(&"notes.md".to_string()), "{docs:?}");
        assert_eq!(rels(decision_files(root).unwrap()), ["docs/decisions/x.md"]);
    }

    #[test]
    fn in_git_a_build_directory_name_skips_only_what_git_does_not_list() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            let status = crate::test_git()
                .args(args)
                .current_dir(root)
                .output()
                .unwrap()
                .status;
            assert!(status.success(), "git {args:?}");
        };
        std::fs::write(
            root.join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
        )
        .unwrap();
        std::fs::write(root.join(".gitignore"), "/target/\n").unwrap();
        for rel in [
            "app/target/rules.py",
            "web/node_modules/lib.js",
            "target/debug/out.rs",
        ] {
            std::fs::create_dir_all(root.join(rel).parent().unwrap()).unwrap();
            std::fs::write(root.join(rel), "x = 1\n").unwrap();
        }
        let rels = || -> Vec<String> {
            code_files(root)
                .unwrap()
                .iter()
                .map(|p| p.strip_prefix(root).unwrap().to_string_lossy().into_owned())
                .collect()
        };
        let outside = rels();
        for dropped in ["app/target/rules.py", "web/node_modules/lib.js"] {
            assert!(!outside.contains(&dropped.to_string()), "{outside:?}");
        }
        git(&["init", "-q"]);
        git(&["add", "app/target/rules.py"]);
        let code = rels();
        for kept in ["app/target/rules.py", "web/node_modules/lib.js"] {
            assert!(code.contains(&kept.to_string()), "{kept}: {code:?}");
        }
        assert!(!code.iter().any(|r| r.starts_with("target/")), "{code:?}");
        let project = Project::at(root).unwrap();
        assert!(walks_to(&project, Path::new("app/target/rules.py")));
    }

    #[test]
    fn the_index_tree_inside_the_git_directory_reads_every_file() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let status = crate::test_git()
            .args(["init", "-q"])
            .current_dir(root)
            .status()
            .unwrap();
        assert!(status.success());
        let git_dir = root.join(".git").canonicalize().unwrap();
        let tree = git_dir.join("silcrow-index");
        std::fs::create_dir_all(&tree).unwrap();
        std::fs::write(
            tree.join(".git"),
            format!("gitdir: {}\n", git_dir.display()),
        )
        .unwrap();
        std::fs::write(
            tree.join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
        )
        .unwrap();
        std::fs::write(tree.join("staged.py"), "x = 1\n").unwrap();
        let code = code_files(&tree).unwrap();
        assert!(code.contains(&tree.join("staged.py")), "{code:?}");
    }

    #[test]
    fn code_files_include_fallback_exts_and_skip_binaries() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("main.go"), "package main\n").unwrap();
        std::fs::write(dir.path().join("pic.png"), []).unwrap();
        let files = code_files(dir.path()).unwrap();
        let names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert!(names.contains(&"main.go".to_string()));
        assert!(names.contains(&"AGENTS.md".to_string()));
        assert!(!names.contains(&"pic.png".to_string()));
    }

    /// A file that is not UTF-8 is skipped only when it can carry no marker: a binary one,
    /// unnamed, or text in another encoding that no grammar reads and where no line is shaped as
    /// a marker, named. Any other fails, named.
    #[test]
    fn a_file_that_is_not_utf8_is_skipped_only_when_it_can_carry_no_marker() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::write(
            root.join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n",
        )
        .unwrap();
        std::fs::write(root.join("data.csv"), b"caf\xe9;1\n").unwrap();
        std::fs::write(
            root.join("law.csv"),
            b"Art. \xa7 3;# \xa7 abc\n-- \xa7 Gesetzbuch\n",
        )
        .unwrap();
        std::fs::write(
            root.join("statement.csv"),
            b"\x00GITCRYPT\x00\x8f# \xa7 abcdefgh1.a\n\xe9",
        )
        .unwrap();
        std::fs::write(root.join("model.npy"), b"\x93NUMPY\xa7\xff").unwrap();
        std::fs::write(root.join("blob"), b"\xff\xfe\x00").unwrap();
        std::fs::write(root.join("ok.py"), "x = 1\n").unwrap();
        let names = |files: Vec<PathBuf>| -> Vec<String> {
            files
                .iter()
                .map(|p| p.strip_prefix(root).unwrap().display().to_string())
                .collect()
        };
        assert_eq!(names(code_files(root).unwrap()), ["AGENTS.md", "ok.py"]);
        assert_eq!(names(skipped_files(root).unwrap()), ["data.csv", "law.csv"]);
        for (name, bytes, why) in [
            (
                "bad.py",
                &b"x = '\xe9'\n"[..],
                "Silcrow parses its extension",
            ),
            (
                "latin1.txt",
                &b"caf\xe9\n# \xa7 abcdefgh1.a\n"[..],
                "shaped as a marker",
            ),
            (
                "utf8.txt",
                &b"x \xff\n// \xc2\xa7 one +draft\n"[..],
                "shaped as a marker",
            ),
        ] {
            std::fs::write(root.join(name), bytes).unwrap();
            let err = format!("{:#}", code_files(root).unwrap_err());
            assert!(
                err.contains(&root.join(name).display().to_string()),
                "{err}"
            );
            assert!(err.contains(why), "{err}");
            assert!(skipped_files(root).is_err());
            std::fs::remove_file(root.join(name)).unwrap();
        }
        let ws = tempfile::tempdir().unwrap();
        std::fs::create_dir(ws.path().join("app")).unwrap();
        std::fs::write(
            ws.path().join("app/AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
        )
        .unwrap();
        std::fs::write(ws.path().join("data.csv"), b"caf\xe9;1\n").unwrap();
        std::fs::create_dir_all(ws.path().join("finance/bank")).unwrap();
        std::fs::write(
            ws.path().join("finance/bank/s.csv"),
            b"\x00GITCRYPT\x00\xa7",
        )
        .unwrap();
        let outside = files_outside_projects(ws.path()).unwrap();
        assert!(outside.is_empty(), "{outside:?}");
        std::fs::write(ws.path().join("stray.py"), b"# \xa7 x\n\xff").unwrap();
        let err = format!("{:#}", files_outside_projects(ws.path()).unwrap_err());
        assert!(err.contains("stray.py"), "{err}");
    }
}