boundgraph-check 0.1.0

Layer 5 of BoundGraph: the checker engine and the ed25519 signing that makes a verdict evidence.
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
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//! Did the patch touch anything it had no business touching?
//!
//! The sandbox answers "was the agent *able* to write that file". This answers
//! a different and more useful question: "was that file in scope for this
//! task". An agent asked to fix a parser, holding `fs:write:/src/**`, that also
//! edits `/src/auth.rs` has done nothing the sandbox forbids and something
//! nobody asked for.
//!
//! # It reads the raw patch, never the condensate payload
//!
//! A [`Condensate`] is *lossy on purpose* — the diff slicer (US-0704) drops
//! whole hunks to fit a token cap, and a file whose every hunk was dropped
//! keeps only a summary line. Scope-checking that would under-report the change
//! set, and under-reporting is the one error this checker must not make: it
//! would produce a `Pass` that says "nothing out of scope" about a patch it
//! only partly saw.
//!
//! So this fetches [`Condensate::raw`] from the content store and parses the
//! complete original. That is exactly what `raw` exists for, and it is the
//! criterion "the check runs on the actual diff, not on the model's description
//! of it" made structural rather than aspirational.
//!
//! # The parser is strict, unlike the slicer's
//!
//! `DiffSlicer::parse` is deliberately tolerant: a patch with one header line
//! it does not recognise is still mostly a patch, and refusing to summarise a
//! build's diff over it would be worse than ignoring the line. The trade goes
//! the other way here. A line this parser does not understand might be the one
//! introducing the file that should not have been touched, so an unrecognised
//! construct is [`Verdict::Inconclusive`](boundgraph_core::Verdict::Inconclusive) and
//! nothing commits.
//!
//! Hunks are consumed by the line counts in their own `@@` headers rather than
//! by scanning for the next header, so patch *content* that looks like a header
//! cannot end a hunk early and hide the files that follow.
//!
//! # What counts as touching a file
//!
//! Content edits, additions, deletions, both halves of a rename, and **mode
//! changes**. The last is easy to leave out and worth having: `chmod +x` on a
//! script in a deployment directory changes what runs, without changing a byte
//! of content.
//!
//! # Which grant it checks against
//!
//! The one the step was *granted*, handed to the checker when it is built —
//! never [`WorkOrder::requests`], which is what the model asked for. A checker
//! that scoped a patch against the proposer's own request would let the
//! proposer define the scope it is being held to, which is not a check.

use async_trait::async_trait;
use boundgraph_core::{CheckerId, Condensate, Digest, GrantAtom, GrantSet, WorkOrder};
use boundgraph_grant::{Tri, set_leq};
use boundgraph_slice::Store;

use crate::checker::{Checker, Judgement};

/// How many offending paths are named before the rest are counted.
pub const MAX_NAMED: usize = 20;

/// What happened to a file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ChangeKind {
    /// The file is new.
    Added,
    /// The file is gone.
    Deleted,
    /// The file changed in place.
    Modified,
    /// The file moved, possibly with changes.
    Renamed,
}

impl ChangeKind {
    /// How it reads in a diagnostic.
    pub fn describe(self) -> &'static str {
        match self {
            Self::Added => "added",
            Self::Deleted => "deleted",
            Self::Modified => "modified",
            Self::Renamed => "renamed",
        }
    }

    /// The `fs` action that most specifically authorises this change.
    ///
    /// Checked *in addition to* `fs:write`, never instead of it — see
    /// [`in_scope`].
    fn action(self) -> &'static str {
        match self {
            Self::Added => "create",
            Self::Deleted => "delete",
            Self::Modified | Self::Renamed => "write",
        }
    }
}

/// One file a patch touched.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Change {
    /// The path after the change. For a deletion, the path that is gone.
    pub path: String,
    /// The path before it, on a rename.
    pub from: Option<String>,
    /// What happened.
    pub kind: ChangeKind,
    /// The file mode before, where the patch stated one.
    pub old_mode: Option<String>,
    /// The mode after.
    pub new_mode: Option<String>,
    /// Whether the change was binary, and so shown only as a summary.
    pub binary: bool,
}

impl Change {
    /// Every path this change touches.
    ///
    /// Two for a rename: both the source and the destination have to be in
    /// scope, because a rename is a deletion and a creation wearing one header.
    pub fn paths(&self) -> Vec<&str> {
        match &self.from {
            Some(from) if from != &self.path => vec![from.as_str(), self.path.as_str()],
            _ => vec![self.path.as_str()],
        }
    }

    /// Whether the file's mode or permissions changed.
    pub fn mode_changed(&self) -> bool {
        match (&self.old_mode, &self.new_mode) {
            (Some(old), Some(new)) => old != new,
            _ => false,
        }
    }

    /// A one-line description, as it appears in a verdict.
    pub fn describe(&self) -> String {
        let mode = match (&self.old_mode, &self.new_mode) {
            (Some(old), Some(new)) if old != new => format!(", mode {old} -> {new}"),
            _ => String::new(),
        };
        match &self.from {
            Some(from) if from != &self.path => {
                format!("{from} -> {} ({}{mode})", self.path, self.kind.describe())
            }
            _ => format!("{} ({}{mode})", self.path, self.kind.describe()),
        }
    }
}

/// The patch could not be understood, so no scope claim can be made about it.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PatchError {
    /// A line this parser does not recognise.
    ///
    /// A refusal, not something to skip. That line might be the one introducing
    /// the file that should not have been touched.
    #[error("line {line_number}: unrecognised in a patch: {line:?}")]
    Unrecognised {
        /// Which line, counting from one.
        line_number: usize,
        /// The line itself.
        line: String,
    },

    /// A hunk header that does not state usable line counts.
    #[error("line {line_number}: malformed hunk header: {header:?}")]
    MalformedHunk {
        /// Which line, counting from one.
        line_number: usize,
        /// The header.
        header: String,
    },

    /// The patch ends part way through a hunk.
    #[error("the patch ends inside a hunk that began at line {line_number}")]
    Truncated {
        /// Where the unfinished hunk started.
        line_number: usize,
    },

    /// A header whose paths cannot be read unambiguously.
    #[error("line {line_number}: cannot tell which paths this names: {line:?}")]
    Ambiguous {
        /// Which line, counting from one.
        line_number: usize,
        /// The line itself.
        line: String,
    },
}

/// File-header lines that carry no path and change no scope.
const IGNORED_HEADERS: &[&str] = &[
    "index ",
    "similarity index ",
    "dissimilarity index ",
    "old file mode ",
    "GIT binary patch",
    "Binary files ",
    // "\ No newline at end of file" belongs to the hunk line before it and
    // counts against neither side, so a hunk whose counts are already satisfied
    // leaves it sitting at file level.
    "\\ ",
];

/// Parse a unified diff into the set of files it touches.
///
/// Strict: anything it does not recognise is an error rather than a skipped
/// line. See the module documentation for why the trade goes the opposite way
/// from the diff slicer's.
///
/// # Errors
///
/// [`PatchError`] if the patch contains a construct this parser cannot account
/// for, a malformed hunk header, or an unfinished hunk.
pub fn parse_patch(text: &str) -> Result<Vec<Change>, PatchError> {
    let lines: Vec<&str> = text.lines().collect();
    let mut changes: Vec<Change> = Vec::new();
    // Kept alongside `changes` rather than inside `Change`: the line a file
    // header opened on is needed to report an unreadable one, and whether a
    // `---` has been seen is needed to tell one file from the next in a patch
    // with no `diff --git` headers. Neither belongs in the public type.
    let mut starts: Vec<usize> = Vec::new();
    let mut seen_minus: Vec<bool> = Vec::new();
    let mut index = 0usize;

    while index < lines.len() {
        let line = lines[index];
        let number = index + 1;

        // A `diff --git` header opens a file. The paths on it are advisory:
        // `---`/`+++` and the rename lines below are authoritative, because
        // this line cannot be split unambiguously when a name contains a space.
        if let Some(rest) = line.strip_prefix("diff --git ") {
            changes.push(Change {
                path: advisory_path(rest).unwrap_or_default(),
                from: None,
                kind: ChangeKind::Modified,
                old_mode: None,
                new_mode: None,
                binary: false,
            });
            starts.push(number);
            seen_minus.push(false);
            index += 1;
            continue;
        }

        // A bare unified diff, with no `diff --git` preamble. `diff -ru` emits
        // several files this way, one after another, so a new `---` when the
        // current file already had one opens the next file rather than
        // overwriting the previous — which would drop everything before it.
        if line.starts_with("--- ") && seen_minus.last().is_none_or(|seen| *seen) {
            changes.push(Change {
                path: String::new(),
                from: None,
                kind: ChangeKind::Modified,
                old_mode: None,
                new_mode: None,
                binary: false,
            });
            starts.push(number);
            seen_minus.push(false);
        }

        let Some(current) = changes.last_mut() else {
            // Anything before the first file header. A leading commit message
            // is normal in `git format-patch` output, but this parser is not in
            // the business of guessing where prose ends, so it refuses.
            return Err(PatchError::Unrecognised {
                line_number: number,
                line: line.to_string(),
            });
        };

        if let Some(rest) = line.strip_prefix("@@") {
            let (old, new) = hunk_counts(rest).ok_or_else(|| PatchError::MalformedHunk {
                line_number: number,
                header: line.to_string(),
            })?;
            index = consume_hunk(&lines, index + 1, old, new, number)?;
            continue;
        }

        if let Some(rest) = line.strip_prefix("--- ") {
            if rest == "/dev/null" {
                current.kind = ChangeKind::Added;
            } else {
                let path = strip_prefix_marker(rest, 'a').ok_or_else(|| PatchError::Ambiguous {
                    line_number: number,
                    line: line.to_string(),
                })?;
                if current.path.is_empty() {
                    current.path = path.clone();
                }
                current.from.get_or_insert(path);
            }
            if let Some(seen) = seen_minus.last_mut() {
                *seen = true;
            }
            index += 1;
            continue;
        }

        if let Some(rest) = line.strip_prefix("+++ ") {
            if rest == "/dev/null" {
                current.kind = ChangeKind::Deleted;
            } else {
                let path = strip_prefix_marker(rest, 'b').ok_or_else(|| PatchError::Ambiguous {
                    line_number: number,
                    line: line.to_string(),
                })?;
                current.path = path;
            }
            index += 1;
            continue;
        }

        if let Some(mode) = line.strip_prefix("new file mode ") {
            current.kind = ChangeKind::Added;
            current.new_mode = Some(mode.trim().to_string());
            index += 1;
            continue;
        }
        if let Some(mode) = line.strip_prefix("deleted file mode ") {
            current.kind = ChangeKind::Deleted;
            current.old_mode = Some(mode.trim().to_string());
            index += 1;
            continue;
        }
        if let Some(mode) = line.strip_prefix("old mode ") {
            current.old_mode = Some(mode.trim().to_string());
            index += 1;
            continue;
        }
        if let Some(mode) = line.strip_prefix("new mode ") {
            current.new_mode = Some(mode.trim().to_string());
            index += 1;
            continue;
        }
        if let Some(from) = line.strip_prefix("rename from ") {
            current.kind = ChangeKind::Renamed;
            current.from = Some(from.trim().to_string());
            index += 1;
            continue;
        }
        if let Some(to) = line.strip_prefix("rename to ") {
            current.kind = ChangeKind::Renamed;
            current.path = to.trim().to_string();
            index += 1;
            continue;
        }
        if let Some(from) = line.strip_prefix("copy from ") {
            // A copy creates the destination and leaves the source alone, but
            // both are named so both are checked. Being generous with what is
            // in the change set is the safe direction here.
            current.from = Some(from.trim().to_string());
            index += 1;
            continue;
        }
        if let Some(to) = line.strip_prefix("copy to ") {
            current.kind = ChangeKind::Added;
            current.path = to.trim().to_string();
            index += 1;
            continue;
        }

        if line.starts_with("Binary files ") || line.starts_with("GIT binary patch") {
            current.binary = true;
        }

        if IGNORED_HEADERS.iter().any(|h| line.starts_with(h)) || line.is_empty() {
            index += 1;
            continue;
        }

        // A binary patch body is base85 with a length byte in front. It is not
        // parsed, and it is not skipped by guesswork either: once `binary` is
        // set the body runs to the next file header or the end.
        if current.binary {
            index += 1;
            continue;
        }

        return Err(PatchError::Unrecognised {
            line_number: number,
            line: line.to_string(),
        });
    }

    for (position, change) in changes.iter_mut().enumerate() {
        if change.path.is_empty()
            && let Some(from) = &change.from
        {
            change.path = from.clone();
        }

        // A file header whose path could never be read. Refused rather than
        // dropped: dropping it would leave the change set short by exactly the
        // file nobody could name, and a short change set is a `Pass` about a
        // patch this checker did not fully see. It happens for a mode-only
        // change to a path containing a space, where the `diff --git` line
        // cannot be split and there are no `---`/`+++` lines to settle it.
        if change.path.is_empty() {
            let line_number = starts.get(position).copied().unwrap_or(1);
            return Err(PatchError::Ambiguous {
                line_number,
                line: lines
                    .get(line_number.saturating_sub(1))
                    .unwrap_or(&"")
                    .to_string(),
            });
        }
    }
    Ok(changes)
}

/// The `b/` path from a `diff --git` line, when it can be read unambiguously.
fn advisory_path(rest: &str) -> Option<String> {
    let parts: Vec<&str> = rest.split_whitespace().collect();
    if parts.len() != 2 {
        // A name with a space in it. `---`/`+++` will settle it.
        return None;
    }
    strip_prefix_marker(parts[1], 'b')
}

/// Strip git's `a/` or `b/` prefix, and its quoting.
fn strip_prefix_marker(text: &str, marker: char) -> Option<String> {
    // `--- a/src/main.rs\t2026-01-01` — some tools append a timestamp.
    let text = text.split('\t').next().unwrap_or(text).trim_end();
    let text = text.trim_matches('"');

    let prefix = format!("{marker}/");
    match text.strip_prefix(&prefix) {
        Some(path) => Some(path.to_string()),
        // A plain unified diff has no `a/`, `b/` prefixes at all.
        None if !text.is_empty() && text != "/dev/null" => Some(text.to_string()),
        None => None,
    }
}

/// The old and new line counts from a `@@ -l,s +l,s @@` header.
fn hunk_counts(rest: &str) -> Option<(usize, usize)> {
    let inner = rest.split("@@").next()?.trim();
    let mut ranges = inner.split_whitespace();

    let old = ranges.next()?.strip_prefix('-')?;
    let new = ranges.next()?.strip_prefix('+')?;

    Some((span(old)?, span(new)?))
}

/// The length half of a `start,length` range. An absent length means one.
fn span(range: &str) -> Option<usize> {
    match range.split_once(',') {
        Some((start, length)) => {
            start.parse::<usize>().ok()?;
            length.parse().ok()
        }
        None => {
            range.parse::<usize>().ok()?;
            Some(1)
        }
    }
}

/// Consume exactly the lines a hunk header promised, returning the index after.
///
/// Counting rather than scanning for the next header is what stops patch
/// *content* that happens to look like a header from ending a hunk early and
/// hiding the files that follow it.
fn consume_hunk(
    lines: &[&str],
    mut index: usize,
    mut old: usize,
    mut new: usize,
    started_at: usize,
) -> Result<usize, PatchError> {
    while old > 0 || new > 0 {
        let Some(line) = lines.get(index) else {
            return Err(PatchError::Truncated {
                line_number: started_at,
            });
        };
        index += 1;

        match line.chars().next() {
            Some('+') => new = new.saturating_sub(1),
            Some('-') => old = old.saturating_sub(1),
            // "\ No newline at end of file" belongs to the line before it and
            // counts against neither side.
            Some('\\') => {}
            // A context line. Some tools strip the trailing space from an
            // otherwise empty one, which is why an empty line counts as
            // context rather than being an error.
            Some(' ') | None => {
                old = old.saturating_sub(1);
                new = new.saturating_sub(1);
            }
            Some(_) => {
                return Err(PatchError::Unrecognised {
                    line_number: index,
                    line: (*line).to_string(),
                });
            }
        }
    }
    Ok(index)
}

/// Whether `path` may be changed under `scope`.
///
/// Asks for `fs:write` first, and then for the action most specific to the kind
/// of change. Both, rather than only the specific one: a flow that grants
/// `fs:write:/src/**` plainly means to permit deleting a file under `/src`, and
/// a check that refused it because the atom said `write` and the change said
/// `delete` would be pedantry rather than security. And both rather than only
/// `fs:write`, so a narrow `fs:delete:/tmp/**` still authorises what it names.
fn in_scope(scope: &GrantSet, path: &str, kind: ChangeKind) -> Tri {
    let ask = |action: &str| set_leq(&GrantSet::new([GrantAtom::new("fs", action, path)]), scope);
    ask("write").or(ask(kind.action()))
}

/// Confirms that a patch only touched files the step was granted.
///
/// # Which grant
///
/// The one the step was **granted**, passed in here. Never the work order's
/// `requests`: that is what the model asked for, and a checker that scoped a
/// patch against the proposer's own request would be asking the proposer to
/// mark its own homework.
#[derive(Debug)]
pub struct DiffScope<S: Store> {
    store: S,
    scope: GrantSet,
    root: Option<String>,
    id: CheckerId,
}

impl<S: Store> DiffScope<S> {
    /// A scope checker over `scope`, reading raw patches from `store`.
    pub fn new(store: S, scope: GrantSet) -> Self {
        Self {
            store,
            scope,
            root: None,
            id: CheckerId::new("diff-scope", 1),
        }
    }

    /// Treat patch paths as relative to `root` before comparing them.
    ///
    /// A patch says `src/auth.rs`; a grant says `fs:write:/work/repo/src/**`.
    /// The two only meet if the checker knows which directory the patch is
    /// relative to, so set this to the workspace the grant is written against.
    ///
    /// With no root the patch path is compared as an absolute path from the
    /// repository root — `src/auth.rs` becomes `/src/auth.rs` — which is how
    /// every grant in this codebase is spelled.
    #[must_use]
    pub fn rooted_at(mut self, root: impl Into<String>) -> Self {
        let root = root.into().replace('\\', "/");
        self.root = Some(root.trim_end_matches('/').to_string());
        self
    }

    /// Name it something more specific, so a ledger says which scope this was.
    #[must_use]
    pub fn named(mut self, name: impl Into<String>, version: u32) -> Self {
        self.id = CheckerId::new(name, version);
        self
    }

    /// The path as the grant would spell it.
    ///
    /// Always absolute. A grant resource is matched segment by segment, so
    /// `src/auth.rs` and `/src/**` would never meet — and the mismatch would
    /// look like an overreach report rather than a configuration mistake, which
    /// is the worst way for this checker to be wrong.
    fn resolve(&self, path: &str) -> String {
        let path = path.replace('\\', "/");
        let path = path.trim_start_matches('/');
        match &self.root {
            Some(root) => format!("{root}/{path}"),
            None => format!("/{path}"),
        }
    }
}

/// Name at most [`MAX_NAMED`] entries, counting the rest.
fn listing(items: &[String]) -> String {
    let shown: Vec<&str> = items.iter().take(MAX_NAMED).map(String::as_str).collect();
    let rest = items.len().saturating_sub(shown.len());
    if rest == 0 {
        shown.join(", ")
    } else {
        format!("{}, and {rest} more", shown.join(", "))
    }
}

#[async_trait]
impl<S: Store> Checker for DiffScope<S> {
    fn id(&self) -> CheckerId {
        self.id.clone()
    }

    // No grants. The store is handed to this checker rather than reached for,
    // so it reads no file and runs no process. Note that `scope` is not this
    // checker's own authority — it is the authority being checked *against*.

    async fn judge(&self, _order: &WorkOrder, condensate: &Condensate) -> Judgement {
        // The raw patch, not the condensate payload. See the module docs: the
        // payload is lossy by design and would under-report the change set.
        let raw = match self.store.get(&condensate.raw).await {
            Ok(bytes) => bytes,
            Err(e) => {
                return Judgement::inconclusive(format!(
                    "the original patch could not be read from the content store: {e}"
                ));
            }
        };

        let text = match String::from_utf8(raw) {
            Ok(text) => text,
            Err(_) => {
                return Judgement::inconclusive(
                    "the original patch is not valid UTF-8, so its paths cannot be read"
                        .to_string(),
                );
            }
        };

        let changes = match parse_patch(&text) {
            Ok(changes) => changes,
            Err(e) => {
                return Judgement::inconclusive(format!(
                    "the patch could not be parsed, so nothing can be claimed about its scope: {e}"
                ));
            }
        };

        let mut touched: Vec<String> = Vec::new();
        let mut outside: Vec<String> = Vec::new();
        let mut undecided: Vec<String> = Vec::new();

        for change in &changes {
            for path in change.paths() {
                let resolved = self.resolve(path);
                if !touched.contains(&resolved) {
                    touched.push(resolved.clone());
                }
                match in_scope(&self.scope, &resolved, change.kind) {
                    Tri::Yes => {}
                    Tri::No => outside.push(format!("{resolved} ({})", change.describe())),
                    Tri::Unknown => undecided.push(resolved),
                }
            }
        }

        touched.sort();

        // The exact set, recorded so an auditor can ask "did this patch touch
        // `src/auth.rs`" and get an answer bound by the signature rather than a
        // sentence someone wrote. One digest per path, plus one for the set.
        let mut judgement = Judgement::pass();
        for path in &touched {
            judgement = judgement.covering(Digest::of(path.as_bytes()));
        }
        judgement = judgement.covering(Digest::of(touched.join("\n").as_bytes()));

        if !outside.is_empty() {
            return Judgement {
                verdict: boundgraph_core::Verdict::Fail(format!(
                    "{} path{} outside the step's grant: {}",
                    outside.len(),
                    if outside.len() == 1 { "" } else { "s" },
                    listing(&outside)
                )),
                also: judgement.also,
            };
        }

        if !undecided.is_empty() {
            return Judgement {
                verdict: boundgraph_core::Verdict::Inconclusive(format!(
                    "cannot prove {} path{} within the step's grant: {}",
                    undecided.len(),
                    if undecided.len() == 1 { "" } else { "s" },
                    listing(&undecided)
                )),
                also: judgement.also,
            };
        }

        judgement
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sign::LocalKey;
    use boundgraph_core::{CondensatePayload, Intent, ProposalOrigin, SchemaId, SlicerId, Verdict};
    use boundgraph_slice::MemoryStore;

    fn order() -> WorkOrder {
        WorkOrder::new(
            Intent::new("patch.apply", &"fix the header parser").unwrap(),
            vec![],
            // Deliberately wide: the checker must ignore it and use the granted
            // scope instead.
            GrantSet::parse(["fs:write:/**"]).unwrap(),
            ProposalOrigin::new("claude-opus-5", [], Digest::of(b"prompt")),
        )
    }

    fn condensate_for(raw: &[u8]) -> Condensate {
        Condensate::new(
            SchemaId::new("boundgraph.diff.v1", 1),
            // Deliberately a summary that says something different from the
            // patch: the checker must not read it.
            CondensatePayload::inline(&"1 file changed in src/").unwrap(),
            Digest::of(raw),
            400,
            true,
            SlicerId::new("diff", 1),
        )
    }

    fn key() -> LocalKey {
        LocalKey::from_seed("host-key-1", [7u8; 32])
    }

    fn scope(atoms: &[&str]) -> GrantSet {
        GrantSet::parse(atoms.iter().copied()).expect("test scope should parse")
    }

    async fn verdict_for(patch: &str, granted: &[&str]) -> Verdict {
        let store = MemoryStore::new();
        store.put(patch.as_bytes()).await.unwrap();

        DiffScope::new(store, scope(granted))
            .check(&order(), &condensate_for(patch.as_bytes()), &key())
            .await
            .unwrap()
            .verdict
    }

    const IN_SCOPE: &str = "\
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -1,3 +1,3 @@
 fn parse() {
-    old();
+    new();
 }
";

    const REACHES_OUT: &str = "\
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -1,1 +1,1 @@
-old();
+new();
diff --git a/deploy/production.yaml b/deploy/production.yaml
--- a/deploy/production.yaml
+++ b/deploy/production.yaml
@@ -1,1 +1,1 @@
-replicas: 1
+replicas: 99
";

    // ── the check ───────────────────────────────────────────────────────────

    #[tokio::test]
    async fn a_patch_inside_the_grant_passes() {
        assert_eq!(
            verdict_for(IN_SCOPE, &["fs:write:/src/**"]).await,
            Verdict::Pass
        );
    }

    /// The criterion: a path outside the grant is a `Fail` naming the file.
    #[tokio::test]
    async fn a_path_outside_the_grant_fails_and_names_it() {
        let v = verdict_for(REACHES_OUT, &["fs:write:/src/**"]).await;

        let Verdict::Fail(reason) = v else {
            panic!("expected Fail, got {v:?}");
        };
        assert!(reason.contains("deploy/production.yaml"), "{reason}");
        assert!(
            !reason.contains("src/parse.rs"),
            "only the offender: {reason}"
        );
        assert!(reason.contains("1 path outside"), "{reason}");
    }

    /// The criterion: deletions are checked too.
    #[tokio::test]
    async fn a_deletion_outside_the_grant_is_caught() {
        let patch = "\
diff --git a/deploy/secrets.env b/deploy/secrets.env
deleted file mode 100644
--- a/deploy/secrets.env
+++ /dev/null
@@ -1,1 +0,0 @@
-TOKEN=abc
";
        let v = verdict_for(patch, &["fs:write:/src/**"]).await;

        let Verdict::Fail(reason) = v else {
            panic!("expected Fail, got {v:?}");
        };
        assert!(reason.contains("deploy/secrets.env"), "{reason}");
        assert!(reason.contains("deleted"), "{reason}");
    }

    /// The criterion: renames are checked too — and both halves of one, because
    /// a rename is a deletion and a creation wearing a single header.
    #[tokio::test]
    async fn both_halves_of_a_rename_must_be_in_scope() {
        let patch = "\
diff --git a/src/parse.rs b/deploy/parse.rs
similarity index 100%
rename from src/parse.rs
rename to deploy/parse.rs
";
        let v = verdict_for(patch, &["fs:write:/src/**"]).await;

        let Verdict::Fail(reason) = v else {
            panic!("moving a file out of scope must fail, got {v:?}");
        };
        assert!(reason.contains("deploy/parse.rs"), "{reason}");

        // And the other direction: moving something in from outside.
        let inbound = "\
diff --git a/deploy/parse.rs b/src/parse.rs
similarity index 100%
rename from deploy/parse.rs
rename to src/parse.rs
";
        let v = verdict_for(inbound, &["fs:write:/src/**"]).await;
        assert!(matches!(v, Verdict::Fail(_)), "{v:?}");
    }

    /// The criterion: mode and permission changes count, not just content.
    #[tokio::test]
    async fn a_mode_change_alone_is_a_change() {
        let patch = "\
diff --git a/deploy/run.sh b/deploy/run.sh
old mode 100644
new mode 100755
";
        let v = verdict_for(patch, &["fs:write:/src/**"]).await;

        let Verdict::Fail(reason) = v else {
            panic!("chmod +x on an out-of-scope file must fail, got {v:?}");
        };
        assert!(reason.contains("deploy/run.sh"), "{reason}");
        assert!(reason.contains("100644 -> 100755"), "{reason}");
    }

    #[tokio::test]
    async fn a_mode_change_inside_the_grant_still_passes() {
        let patch = "\
diff --git a/src/run.sh b/src/run.sh
old mode 100644
new mode 100755
";
        assert_eq!(
            verdict_for(patch, &["fs:write:/src/**"]).await,
            Verdict::Pass
        );
    }

    #[tokio::test]
    async fn an_addition_is_authorised_by_write_or_by_create() {
        let patch = "\
diff --git a/src/new.rs b/src/new.rs
new file mode 100644
--- /dev/null
+++ b/src/new.rs
@@ -0,0 +1,1 @@
+fn main() {}
";
        assert_eq!(
            verdict_for(patch, &["fs:write:/src/**"]).await,
            Verdict::Pass
        );
        assert_eq!(
            verdict_for(patch, &["fs:create:/src/**"]).await,
            Verdict::Pass
        );
    }

    #[tokio::test]
    async fn a_narrow_delete_grant_authorises_a_deletion() {
        let patch = "\
diff --git a/tmp/scratch b/tmp/scratch
deleted file mode 100644
--- a/tmp/scratch
+++ /dev/null
@@ -1,1 +0,0 @@
-junk
";
        assert_eq!(
            verdict_for(patch, &["fs:delete:/tmp/**"]).await,
            Verdict::Pass
        );
    }

    #[tokio::test]
    async fn an_empty_patch_touches_nothing_and_passes() {
        assert_eq!(verdict_for("", &["fs:write:/src/**"]).await, Verdict::Pass);
    }

    /// Goal G5: what cannot be decided is not assumed.
    #[tokio::test]
    async fn an_undecidable_comparison_is_inconclusive_rather_than_a_pass() {
        // A partial-segment glob is outside the decidable fragment.
        let v = verdict_for(IN_SCOPE, &["fs:write:/src/*.rs"]).await;

        assert!(matches!(v, Verdict::Inconclusive(_)), "{v:?}");
        assert!(!v.is_pass());
        assert!(v.reason().unwrap().contains("src/parse.rs"));
    }

    /// The criterion: the passing verdict records the exact set of paths.
    #[tokio::test]
    async fn a_pass_records_exactly_which_paths_changed() {
        let patch = "\
diff --git a/src/a.rs b/src/a.rs
--- a/src/a.rs
+++ b/src/a.rs
@@ -1,1 +1,1 @@
-a
+A
diff --git a/src/b.rs b/src/b.rs
--- a/src/b.rs
+++ b/src/b.rs
@@ -1,1 +1,1 @@
-b
+B
";
        let store = MemoryStore::new();
        store.put(patch.as_bytes()).await.unwrap();

        let evidence = DiffScope::new(store, scope(&["fs:write:/src/**"]))
            .check(&order(), &condensate_for(patch.as_bytes()), &key())
            .await
            .unwrap();

        assert!(evidence.permits_commit());
        assert!(evidence.covers(&Digest::of(b"/src/a.rs")));
        assert!(evidence.covers(&Digest::of(b"/src/b.rs")));
        assert!(
            !evidence.covers(&Digest::of(b"/src/c.rs")),
            "a file it never touched must not be vouched for"
        );
        assert!(
            evidence.covers(&Digest::of(b"/src/a.rs\n/src/b.rs")),
            "and the set as a whole, so nothing can be added or removed"
        );
    }

    // ── reading the real patch ──────────────────────────────────────────────

    /// The criterion: the check runs on the actual diff. The condensate here
    /// says one thing and the raw patch says another.
    #[tokio::test]
    async fn the_check_reads_the_raw_patch_and_not_the_condensate_payload() {
        let store = MemoryStore::new();
        store.put(REACHES_OUT.as_bytes()).await.unwrap();

        // The payload claims a single in-scope file; the raw patch escapes.
        let condensate = condensate_for(REACHES_OUT.as_bytes());
        assert!(condensate.lossy, "the summary is the model's-eye view");

        let evidence = DiffScope::new(store, scope(&["fs:write:/src/**"]))
            .check(&order(), &condensate, &key())
            .await
            .unwrap();

        assert!(
            !evidence.permits_commit(),
            "the summary said in scope; the patch was not"
        );
    }

    #[tokio::test]
    async fn a_raw_patch_that_is_not_in_the_store_is_inconclusive() {
        let evidence = DiffScope::new(MemoryStore::new(), scope(&["fs:write:/src/**"]))
            .check(&order(), &condensate_for(b"never stored"), &key())
            .await
            .unwrap();

        assert!(matches!(evidence.verdict, Verdict::Inconclusive(_)));
    }

    /// The proposer must not get to define the scope it is held to.
    #[tokio::test]
    async fn the_work_orders_own_request_is_ignored() {
        // `order()` requests `fs:write:/**`, which would permit everything.
        let v = verdict_for(REACHES_OUT, &["fs:write:/src/**"]).await;
        assert!(matches!(v, Verdict::Fail(_)), "{v:?}");
    }

    #[tokio::test]
    async fn the_checker_needs_no_authority_of_its_own() {
        let checker = DiffScope::new(MemoryStore::new(), scope(&["fs:write:/src/**"]));
        assert_eq!(checker.grants(), GrantSet::EMPTY);
    }

    #[tokio::test]
    async fn paths_can_be_resolved_against_a_workspace_root() {
        let store = MemoryStore::new();
        store.put(IN_SCOPE.as_bytes()).await.unwrap();

        let evidence = DiffScope::new(store, scope(&["fs:write:/work/repo/src/**"]))
            .rooted_at("/work/repo/")
            .check(&order(), &condensate_for(IN_SCOPE.as_bytes()), &key())
            .await
            .unwrap();

        assert!(evidence.permits_commit());
        assert!(evidence.covers(&Digest::of(b"/work/repo/src/parse.rs")));
    }

    #[tokio::test]
    async fn the_same_patch_always_gives_the_same_evidence() {
        let store = MemoryStore::new();
        store.put(IN_SCOPE.as_bytes()).await.unwrap();
        let checker = DiffScope::new(store, scope(&["fs:write:/src/**"]));
        let (order, k, key) = (order(), condensate_for(IN_SCOPE.as_bytes()), key());

        let first = checker.check(&order, &k, &key).await.unwrap();
        for _ in 0..4 {
            assert_eq!(checker.check(&order, &k, &key).await.unwrap(), first);
        }
    }

    // ── the strict parser ───────────────────────────────────────────────────

    #[test]
    fn a_plain_unified_diff_with_no_git_preamble_parses() {
        let patch = "\
--- src/old.txt
+++ src/new.txt
@@ -1,1 +1,1 @@
-a
+b
";
        let changes = parse_patch(patch).unwrap();
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].path, "src/new.txt");
    }

    #[test]
    fn a_hunk_is_consumed_by_its_own_line_counts() {
        // The hunk body contains lines that look like file headers. Scanning
        // for the next header would end the hunk here and lose `evil.sh`.
        let patch = "\
diff --git a/src/a.rs b/src/a.rs
--- a/src/a.rs
+++ b/src/a.rs
@@ -1,3 +1,3 @@
 context
-diff --git a/x b/x
+diff --git a/x b/x
 @@ -9,9 +9,9 @@
diff --git a/evil.sh b/evil.sh
--- a/evil.sh
+++ b/evil.sh
@@ -1,1 +1,1 @@
-x
+y
";
        let changes = parse_patch(patch).unwrap();
        let paths: Vec<&str> = changes.iter().map(|c| c.path.as_str()).collect();

        assert_eq!(
            paths,
            vec!["src/a.rs", "evil.sh"],
            "the second file must survive"
        );
    }

    /// The trade that goes the opposite way from the diff slicer's: a line this
    /// parser does not understand might be the one hiding a file.
    #[test]
    fn an_unrecognised_line_is_refused_rather_than_skipped() {
        let patch = "\
diff --git a/src/a.rs b/src/a.rs
what on earth is this line
--- a/src/a.rs
+++ b/src/a.rs
";
        let err = parse_patch(patch).unwrap_err();
        let PatchError::Unrecognised { line, .. } = err else {
            panic!("expected Unrecognised, got {err:?}");
        };
        assert!(line.contains("what on earth"));
    }

    /// `diff -ru` emits several files with no `diff --git` headers at all.
    /// Treating the second `---` as belonging to the first file would drop
    /// every file but the last — a short change set, which is the one error
    /// this checker must not make.
    #[test]
    fn every_file_of_a_multi_file_plain_unified_diff_is_found() {
        let patch = "\
--- src/a.rs
+++ src/a.rs
@@ -1,1 +1,1 @@
-a
+A
--- deploy/production.yaml
+++ deploy/production.yaml
@@ -1,1 +1,1 @@
-replicas: 1
+replicas: 99
";
        let paths: Vec<String> = parse_patch(patch)
            .unwrap()
            .into_iter()
            .map(|c| c.path)
            .collect();

        assert_eq!(paths, vec!["src/a.rs", "deploy/production.yaml"]);
    }

    #[tokio::test]
    async fn a_second_file_of_a_plain_unified_diff_is_still_scope_checked() {
        let patch = "\
--- src/a.rs
+++ src/a.rs
@@ -1,1 +1,1 @@
-a
+A
--- deploy/production.yaml
+++ deploy/production.yaml
@@ -1,1 +1,1 @@
-replicas: 1
+replicas: 99
";
        let v = verdict_for(patch, &["fs:write:/src/**"]).await;

        let Verdict::Fail(reason) = v else {
            panic!("expected Fail, got {v:?}");
        };
        assert!(reason.contains("deploy/production.yaml"), "{reason}");
    }

    /// A header whose path cannot be read is refused, never skipped. Skipping
    /// leaves the change set short by exactly the file nobody could name.
    #[test]
    fn a_file_whose_path_cannot_be_read_is_refused_rather_than_dropped() {
        // A mode-only change to a path with a space: the `diff --git` line
        // cannot be split, and there are no `---`/`+++` lines to settle it.
        let patch = "\
diff --git a/deploy/my script.sh b/deploy/my script.sh
old mode 100644
new mode 100755
";
        assert!(
            matches!(parse_patch(patch), Err(PatchError::Ambiguous { .. })),
            "got {:?}",
            parse_patch(patch)
        );
    }

    #[tokio::test]
    async fn an_unreadable_header_leaves_the_verdict_undecided_not_passing() {
        let patch = "\
diff --git a/deploy/my script.sh b/deploy/my script.sh
old mode 100644
new mode 100755
";
        let v = verdict_for(patch, &["fs:write:/src/**"]).await;

        assert!(matches!(v, Verdict::Inconclusive(_)), "{v:?}");
        assert!(!v.is_pass(), "an unreadable patch must never pass");
    }

    #[test]
    fn a_malformed_hunk_header_is_refused() {
        let patch = "\
diff --git a/src/a.rs b/src/a.rs
@@ not a range @@
";
        assert!(matches!(
            parse_patch(patch),
            Err(PatchError::MalformedHunk { .. })
        ));
    }

    #[test]
    fn a_patch_that_ends_mid_hunk_is_refused() {
        let patch = "\
diff --git a/src/a.rs b/src/a.rs
@@ -1,9 +1,9 @@
 one line only
";
        assert!(matches!(
            parse_patch(patch),
            Err(PatchError::Truncated { .. })
        ));
    }

    #[test]
    fn content_before_the_first_file_header_is_refused() {
        assert!(matches!(
            parse_patch("Subject: a commit message\n\nbody\n"),
            Err(PatchError::Unrecognised { .. })
        ));
    }

    #[test]
    fn a_no_newline_marker_counts_against_neither_side() {
        let patch = "\
diff --git a/a b/a
--- a/a
+++ b/a
@@ -1,1 +1,1 @@
-old
\\ No newline at end of file
+new
\\ No newline at end of file
";
        assert_eq!(parse_patch(patch).unwrap().len(), 1);
    }

    #[test]
    fn a_hunk_header_without_a_length_means_one_line() {
        let patch = "\
diff --git a/a b/a
--- a/a
+++ b/a
@@ -1 +1 @@
-old
+new
";
        assert_eq!(parse_patch(patch).unwrap().len(), 1);
    }

    #[test]
    fn a_binary_change_is_recorded_without_parsing_its_body() {
        let patch = "\
diff --git a/logo.png b/logo.png
index 1111111..2222222 100644
GIT binary patch
literal 120
zcmeAS@N?(olHy`uVBq!ia0vp^
";
        let changes = parse_patch(patch).unwrap();
        assert_eq!(changes.len(), 1);
        assert!(changes[0].binary);
        assert_eq!(changes[0].path, "logo.png");
    }

    #[test]
    fn a_timestamp_after_the_path_is_not_part_of_it() {
        let patch = "\
--- src/a.rs\t2026-01-01 10:00:00
+++ src/a.rs\t2026-01-02 10:00:00
@@ -1,1 +1,1 @@
-a
+b
";
        assert_eq!(parse_patch(patch).unwrap()[0].path, "src/a.rs");
    }

    #[test]
    fn a_quoted_path_with_a_space_is_read_from_the_marker_lines() {
        let patch = "\
diff --git \"a/src/my file.rs\" \"b/src/my file.rs\"
--- \"a/src/my file.rs\"
+++ \"b/src/my file.rs\"
@@ -1,1 +1,1 @@
-a
+b
";
        assert_eq!(parse_patch(patch).unwrap()[0].path, "src/my file.rs");
    }

    // ── change bookkeeping ──────────────────────────────────────────────────

    #[test]
    fn a_rename_names_both_paths_and_a_plain_edit_names_one() {
        let renamed = Change {
            path: "b.rs".into(),
            from: Some("a.rs".into()),
            kind: ChangeKind::Renamed,
            old_mode: None,
            new_mode: None,
            binary: false,
        };
        assert_eq!(renamed.paths(), vec!["a.rs", "b.rs"]);

        let edited = Change {
            from: Some("a.rs".into()),
            path: "a.rs".into(),
            ..renamed.clone()
        };
        assert_eq!(edited.paths(), vec!["a.rs"]);
    }

    #[test]
    fn a_mode_change_is_only_a_change_when_the_modes_differ() {
        let same = Change {
            path: "a.sh".into(),
            from: None,
            kind: ChangeKind::Modified,
            old_mode: Some("100644".into()),
            new_mode: Some("100644".into()),
            binary: false,
        };
        assert!(!same.mode_changed());

        let changed = Change {
            new_mode: Some("100755".into()),
            ..same
        };
        assert!(changed.mode_changed());
        assert!(changed.describe().contains("100644 -> 100755"));
    }

    #[test]
    fn a_long_list_of_offenders_is_counted_rather_than_listed() {
        let paths: Vec<String> = (0..40).map(|n| format!("f{n}")).collect();
        let rendered = listing(&paths);

        assert!(rendered.contains("f0"));
        assert!(rendered.contains("and 20 more"), "{rendered}");
    }
}