croft-software 0.2.3

VSCode-style TUI written in Rust
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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
"""Tests for scripts/check_doc_ownership.py: the #314 doc-capture gate.

The gate exists because inserting an item directly above another item's `///`
block silently hands that prose to the newcomer, and nothing in the compiler
or the test suite notices. These tests build real git repositories, because
the two things the gate gets wrong are both about git history rather than
about parsing: what a merge base can see, and what it cannot.
"""

from __future__ import annotations

import contextlib
import io
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import check_doc_ownership as gate  # noqa: E402


def run(cwd, *args, check=True):
    subprocess.run(
        args, cwd=cwd, check=check, capture_output=True, text=True
    )


class Repo:
    """A throwaway git repo with a `main` and a branch off it."""

    def __init__(self, tmp: Path):
        self.path = tmp
        run(tmp, "git", "init", "-q", "-b", "main")
        run(tmp, "git", "config", "user.email", "t@example.com")
        run(tmp, "git", "config", "user.name", "t")

    def commit(self, name: str, text: str, message: str = "c"):
        (self.path / name).write_text(text)
        run(self.path, "git", "add", "-A")
        run(self.path, "git", "commit", "-q", "-m", message)

    def branch(self, name: str):
        run(self.path, "git", "checkout", "-q", "-b", name)

    def checkout(self, name: str):
        run(self.path, "git", "checkout", "-q", name)

    def merge(self, name: str):
        """Merge `name` into the current branch, as this repo's convention
        says to do when a branch needs main."""
        run(self.path, "git", "merge", "-q", "--no-edit", name)

    def exit_code(self, base="main", head="HEAD"):
        """The gate's exit status: 1 when it found a capture, 0 when clean."""
        import os

        cwd = os.getcwd()
        argv = sys.argv
        os.chdir(self.path)
        sys.argv = ["check_doc_ownership.py", base, head]
        try:
            return gate.main()
        finally:
            sys.argv = argv
            os.chdir(cwd)

    def run_gate(self, base="main", head="HEAD"):
        """The gate's exit status and everything it printed to stdout."""
        out = io.StringIO()
        cwd, argv = os.getcwd(), sys.argv
        os.chdir(self.path)
        sys.argv = ["check_doc_ownership.py", base, head]
        try:
            with contextlib.redirect_stdout(out):
                return gate.main(), out.getvalue()
        finally:
            sys.argv = argv
            os.chdir(cwd)


DOCUMENTED_CONST = '''/// The scopes each role uses.
const SYNTAX_SCOPES: &[&str] = &["a"];
'''

CAPTURED_CONST = '''/// The scopes each role uses.
const SYNTAX_SEMANTIC: &[&str] = &["b"];

const SYNTAX_SCOPES: &[&str] = &["a"];
'''


class ItemKinds(unittest.TestCase):
    """`fn` was the original scope, and it let two captures through in a day."""

    def test_every_item_kind_is_recognised(self):
        for decl, name in [
            ("fn a() {}", "a"),
            ("pub fn a() {}", "a"),
            ("const A: u8 = 1;", "A"),
            ("pub const A: &str = \"x\";", "A"),
            ("static A: u8 = 1;", "A"),
            ("pub static mut A: u8 = 1;", "A"),
            ("struct A;", "A"),
            ("pub enum A { B }", "A"),
            ("union A { b: u8 }", "A"),
            ("pub trait A {}", "A"),
            ("type A = u8;", "A"),
            ("macro_rules! a {}", "a"),
        ]:
            state = gate.documented(f"/// doc\n{decl}\n")
            self.assertEqual(
                state.get(name),
                True,
                f"{decl!r} should be seen as documented item {name!r}",
            )

    def test_declaration_shapes_the_regex_must_not_miss(self):
        """Shapes that look like edge cases and are ordinary Rust.

        Each was probed rather than assumed: the same-line attribute was
        genuinely missed before this test existed, which made the item
        invisible to the gate rather than merely undocumented.
        """
        for label, text in [
            ("attribute on its own line", "/// doc\n#[cfg(test)]\nconst A: u8 = 1;\n"),
            ("attribute on the same line", "/// doc\n#[cfg(test)] const A: u8 = 1;\n"),
            ("generic type alias", "/// doc\npub type A<T> = Vec<T>;\n"),
            ("const fn", "/// doc\npub const fn a() -> u8 { 1 }\n"),
            ("indented impl method", "impl X {\n    /// doc\n    pub fn a(&self) {}\n}\n"),
            # Rust's qualifier order is default, const, async, unsafe, extern.
            # Consuming `const` after the others made these match NOTHING, so
            # the function was invisible rather than undocumented.
            ("const unsafe fn", "/// doc\npub const unsafe fn a() {}\n"),
            ("const extern fn", '/// doc\nconst unsafe extern "C" fn a() {}\n'),
            ("every qualifier", "/// doc\npub default const async unsafe fn a() {}\n"),
        ]:
            state = gate.documented(text)
            self.assertTrue(
                any(state.values()),
                f"{label}: nothing was recognised, so the item is invisible "
                f"to the gate rather than merely undocumented",
            )

    def test_multi_line_attributes_and_block_docs_are_read_correctly(self):
        """Both shapes made a DOCUMENTED item read as undocumented.

        That is a false accusation, not a miss: the gate would report a loss
        that never happened, on a branch that had merely reformatted an
        attribute or used `/** */`. For a gate that is the worse direction,
        because one that cries wolf stops being read.

        The inner form `/*!` and the ordinary `/*` and `/***` comments must
        NOT count, or the gate invents documentation instead.
        """
        documented_shapes = [
            ("multi-line attribute", "/// doc\n#[cfg(all(\n    feature = \"x\",\n    unix\n))]\nconst A: u8 = 1;\n"),
            ("one-line block doc", "/** doc */\nconst A: u8 = 1;\n"),
            ("multi-line block doc", "/**\n * doc\n */\nconst A: u8 = 1;\n"),
            ("block doc then attribute", "/** doc */\n#[cfg(test)]\nconst A: u8 = 1;\n"),
        ]
        for label, text in documented_shapes:
            self.assertEqual(
                gate.documented(text).get("A"), True, f"{label} documents A"
            )

        undocumented_shapes = [
            ("inner block doc documents the MODULE", "/*! module */\nconst A: u8 = 1;\n"),
            ("ordinary block comment", "/* a note */\nconst A: u8 = 1;\n"),
            ("triple-star rule", "/*** rule ***/\nconst A: u8 = 1;\n"),
            ("four slashes is a rule", "//// rule\nconst A: u8 = 1;\n"),
        ]
        for label, text in undocumented_shapes:
            self.assertEqual(
                gate.documented(text).get("A"),
                False,
                f"{label} must not count as documentation",
            )

    def test_a_declaration_inside_a_string_is_not_an_item(self):
        """The regex is line-anchored, so a declaration quoted mid-line is
        not mistaken for one."""
        state = gate.documented('/// doc\nconst A: &str = "const B: u8 = 1;";\n')
        self.assertEqual(state, {"A": True}, "B is inside a string, not an item")

    def test_methods_are_keyed_by_their_enclosing_impl(self):
        """Two `fn new` in different impl blocks are two items (#405).

        Keyed by bare name, "any documented" merged them and a capture on
        one was invisible while the other kept its prose. The enclosing
        `impl` header is the occurrence-unique key that still lines up
        across revisions: an edit above the block moves it, but does not
        change what it is an impl of.
        """
        both_documented = (
            "impl A {\n    /// a\n    fn new() {}\n}\n\n"
            "impl B {\n    /// b\n    fn new() {}\n}\n"
        )
        one_captured = (
            "impl A {\n    /// a\n    fn other() {}\n    fn new() {}\n}\n\n"
            "impl B {\n    /// b\n    fn new() {}\n}\n"
        )
        self.assertEqual(
            gate.documented(both_documented), {"A::new": True, "B::new": True}
        )
        self.assertEqual(
            gate.documented(one_captured),
            {"A::other": True, "A::new": False, "B::new": True},
            "the capture on A::new is visible even though B::new kept its doc",
        )

    def test_trait_impls_for_the_same_type_are_distinct_blocks(self):
        """`impl Display for X` and `impl Debug for X` both define `fmt`;
        the type alone is not a unique key, so the whole header is."""
        text = (
            "impl fmt::Display for X {\n    /// d\n    fn fmt(&self) {}\n}\n"
            "impl fmt::Debug for X {\n    fn fmt(&self) {}\n}\n"
        )
        self.assertEqual(
            gate.documented(text),
            {"fmt::Display for X::fmt": True, "fmt::Debug for X::fmt": False},
        )

    def test_impl_header_shapes(self):
        """Generics, lifetimes, a `where` clause with the brace on its own
        line, and a trait impl: each still yields the same key, so a branch
        that reformats the header does not move the item to a new key."""
        for label, header in [
            ("plain", "impl Foo {"),
            ("generic", "impl<'a, T: Clone> Foo<'a, T> {"),
            ("where clause, brace on the next line", "impl<T> Foo<T>\nwhere\n    T: Clone,\n{"),
            ("unsafe impl", "unsafe impl Foo {"),
        ]:
            state = gate.documented(f"{header}\n    /// doc\n    fn new() {{}}\n}}\n")
            self.assertEqual(state, {"Foo::new": True}, label)
        state = gate.documented(
            "impl<T> Iterator for Foo<T> {\n    /// doc\n    fn next(&mut self) {}\n}\n"
        )
        self.assertEqual(state, {"Iterator for Foo::next": True})

    def test_braces_in_strings_and_chars_do_not_break_block_tracking(self):
        """Format strings are full of braces. Counting them would leave the
        scanner inside a block that has closed, and key the next top-level
        item to an impl it is not in."""
        text = (
            "impl Foo {\n"
            "    /// doc\n"
            '    fn new() { let _ = format!("{{ {x} }}"); let c = \'{\'; }\n'
            "}\n"
            "/// top\n"
            "fn top() {}\n"
        )
        self.assertEqual(gate.documented(text), {"Foo::new": True, "top": True})

    def test_items_outside_any_impl_keep_the_bare_name(self):
        """Top-level items, and items inside `mod` or `fn` bodies, are keyed
        by name as before: the impl header is the only qualifier, so every
        existing key for a free item survives unchanged."""
        text = (
            "/// a\nfn a() {}\n"
            "mod m {\n    /// b\n    pub fn b() {}\n}\n"
            "impl X {\n    /// c\n    fn c() {}\n}\n"
            "/// d\nfn d() {}\n"
        )
        self.assertEqual(
            gate.documented(text), {"a": True, "b": True, "X::c": True, "d": True}
        )

    def test_a_bodyless_impl_does_not_qualify_the_next_block(self):
        """`impl Eq for X {}` opens and closes on one line. Its header must
        not survive onto the next block, or a `mod` after a marker impl has
        every item keyed to that impl, and a capture inside it is filed under
        a key the base revision never had: a missed report, on the exact
        shape (`src/widgets/file_finder.rs`) the repo contains."""
        text = "impl Eq for X {}\nmod util {\n    /// doc\n    pub fn go() {}\n}\n"
        self.assertEqual(gate.documented(text), {"go": True})
        # And the base-vs-head comparison still reports the capture.
        captured = (
            "impl Eq for X {}\nmod util {\n    /// doc\n    pub fn newcomer() {}\n"
            "    pub fn go() {}\n}\n"
        )
        after = gate.documented(captured)
        self.assertEqual(after.get("go"), False, f"go lost its doc: {after}")

    def test_raw_strings_do_not_break_block_tracking(self):
        """`r#"{"#` is not a `"..."`, and a multi-line raw string of JSON is
        braces all the way down. Both left the counter inside a block that
        had closed, on seven real files under src/."""
        single = (
            'impl Foo {\n    /// doc\n    fn m() {\n'
            '        let j = r#"[{"key": "click"}]"#;\n    }\n}\n'
            "/// top\nfn top() {}\n"
        )
        self.assertEqual(gate.documented(single), {"Foo::m": True, "top": True})
        multi = (
            'impl Foo {\n    /// doc\n    fn m() {\n'
            '        let j = r#"{ "tasks": [\n'
            '            { "label": "x" }\n'
            '        ] }"#;\n    }\n}\n'
            "/// top\nfn top() {}\n"
        )
        self.assertEqual(gate.documented(multi), {"Foo::m": True, "top": True})
        plain_multi = (
            'impl Foo {\n    /// doc\n    fn m() {\n'
            '        let s = "{ opens here\n'
            '            and closes here }";\n    }\n}\n'
            "/// top\nfn top() {}\n"
        )
        self.assertEqual(gate.documented(plain_multi), {"Foo::m": True, "top": True})

    def test_a_header_wrapped_by_rustfmt_keeps_its_key(self):
        """`impl<T>` alone on the first line strips to nothing; the key must
        come from the whole header, or a rewrap moves every method to a
        bare key and a capture in that PR goes unreported."""
        text = "impl<T>\n    Trait for X<T>\n{\n    /// doc\n    fn m() {}\n}\n"
        self.assertEqual(gate.documented(text), {"Trait for X::m": True})

    def test_trait_methods_are_keyed_by_their_trait(self):
        """Two traits declaring `id` are the same shape as two impls
        defining `new`."""
        text = (
            "trait A {\n    /// a\n    fn id(&self);\n}\n"
            "trait B: Clone {\n    /// b\n    fn id(&self);\n}\n"
        )
        self.assertEqual(
            gate.documented(text),
            {"A": False, "trait A::id": True, "B": False, "trait B::id": True},
            "the traits are items in their own scope; their methods are in theirs",
        )

    def test_the_block_tracker_is_balanced_at_eof_on_every_real_file(self):
        """The counter is line-based, so the only proof it kept up with a
        file is that it ends where it started: depth zero, no open block.
        Run over every Rust file in the repo, so a new literal shape that
        desyncs it fails here before it mis-keys anything."""
        src = Path(__file__).resolve().parents[2] / "src"
        files = sorted(src.rglob("*.rs"))
        self.assertGreater(len(files), 50, "the control corpus is missing")
        unbalanced = []
        for f in files:
            lines = f.read_text().splitlines()
            kinds = gate.classify(lines)
            t = gate.BlockTracker()
            for line, kind in zip(lines, kinds):
                if kind == gate.CODE:
                    t.feed(line)
            if t.depth != 0 or t.blocks or t.open_string is not None:
                unbalanced.append((str(f.relative_to(src)), t.depth, t.blocks, t.open_string))
        self.assertEqual(unbalanced, [], "the tracker lost count in these files")

    def test_same_named_items_in_the_same_scope_are_still_merged(self):
        """Two definitions under ONE key (a `cfg`-gated pair, say) keep the
        conservative "any documented" reading: the gate under-reports there
        rather than accusing the wrong twin."""
        text = "/// a\nfn new() {}\n\n/// b\nfn new() {}\n"
        one_captured = "/// a\nfn other() {}\nfn new() {}\n\n/// b\nfn new() {}\n"
        self.assertEqual(gate.documented(text), {"new": True})
        self.assertEqual(gate.documented(one_captured), {"other": True, "new": True})

    def test_a_capture_on_one_impl_of_a_shared_method_name_is_reported(self):
        """End to end: the #405 shape blocks the merge."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit(
                "a.rs",
                "impl A {\n    /// a\n    fn new() {}\n}\n"
                "impl B {\n    /// b\n    fn new() {}\n}\n",
            )
            repo.branch("work")
            repo.commit(
                "a.rs",
                "impl A {\n    /// a\n    fn other() {}\n    fn new() {}\n}\n"
                "impl B {\n    /// b\n    fn new() {}\n}\n",
            )
            self.assertEqual(repo.exit_code(), 1, "A::new lost its doc")
            # The declared-removal escape hatch takes the qualified key.
            repo.commit("a.rs", "// nudge\n" + (repo.path / "a.rs").read_text(), "ok\n\ndoc-removal: a.rs::A::new")
            self.assertEqual(repo.exit_code(), 0, "a declared A::new removal is exempt")

    def test_the_error_names_the_revision_the_doc_was_last_seen_at(self):
        """For a file the branch ADDED, `base` is the wrong revision to cite.

        The file does not exist there, so a reader sent to it finds nothing.
        The loss carries the commit it was last documented at.
        """
        import contextlib
        import io
        import os

        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("seed.rs", "fn seed() {}\n")
            repo.branch("work")
            repo.commit("new.rs", DOCUMENTED_CONST)
            documented_at = subprocess.run(
                ["git", "rev-parse", "HEAD"],
                cwd=repo.path,
                capture_output=True,
                text=True,
                check=True,
            ).stdout.strip()
            repo.commit("new.rs", CAPTURED_CONST)

            code, text = repo.run_gate()

            self.assertEqual(code, 1)
            printed = text
            self.assertIn(
                documented_at[:12],
                printed,
                f"the error must name the commit the doc was last seen at, said: {printed}",
            )

    def test_a_rename_is_not_a_lost_doc(self):
        """A documented item renamed within a branch must not read as a loss.

        The check requires the name to still EXIST at head, so a rename drops
        out rather than reporting the old name as undocumented. Pinned because
        it is the obvious false positive for a name-keyed comparison.
        """
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "/// doc\nfn a() {}\n")
            repo.branch("work")
            repo.commit("a.rs", "/// doc\nfn b() {}\n")
            self.assertEqual(
                repo.exit_code(), 0, "a rename is not a captured doc comment"
            )

    def test_a_const_that_loses_its_doc_is_reported(self):
        """The #395 shape: a const inserted above another const's doc."""
        before = gate.documented(DOCUMENTED_CONST)
        after = gate.documented(CAPTURED_CONST)
        self.assertTrue(before["SYNTAX_SCOPES"])
        self.assertFalse(after["SYNTAX_SCOPES"], "its doc now sits on the newcomer")
        self.assertTrue(after["SYNTAX_SEMANTIC"], "which is how the capture hides")


class GitShapes(unittest.TestCase):
    def test_a_capture_in_an_existing_file_is_reported(self):
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", DOCUMENTED_CONST)
            repo.branch("work")
            repo.commit("a.rs", CAPTURED_CONST)
            self.assertEqual(
                repo.exit_code(), 1, "the gate must fail on a captured doc"
            )

    def test_a_file_present_at_the_base_is_not_treated_as_added(self):
        """`git cat-file -e` prints nothing on success, so a probe that read
        its stdout took every changed file for a branch-added one: each
        went through the pairwise commit walk (the slow path, minutes on a
        real branch) and a capture in an existing file was reported twice,
        once per loop. The probe must read the exit status."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", DOCUMENTED_CONST)
            repo.branch("work")
            repo.commit("a.rs", CAPTURED_CONST)
            repo.commit("new.rs", "/// n\nfn n() {}\n")
            cwd = os.getcwd()
            os.chdir(repo.path)
            try:
                self.assertTrue(gate.exists_at("main", "a.rs"))
                self.assertFalse(gate.exists_at("main", "new.rs"))
                self.assertEqual(gate.added_files("main", ["a.rs", "new.rs"]), ["new.rs"])
            finally:
                os.chdir(cwd)

    def test_a_capture_in_an_existing_file_is_reported_exactly_once(self):
        """Two commits on the branch, so the pairwise walk has a pair to
        compare: with every file mistaken for branch-added, the capture
        was reported by that walk AND by the base comparison."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", DOCUMENTED_CONST)
            repo.branch("work")
            repo.commit("a.rs", DOCUMENTED_CONST + "\n/// Extra.\nconst EXTRA: u8 = 1;\n")
            repo.commit("a.rs", CAPTURED_CONST + "\n/// Extra.\nconst EXTRA: u8 = 1;\n")
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertEqual(
                text.count("::error"),
                1,
                f"one loss, one annotation: {text}",
            )

    def test_a_capture_inside_a_file_the_branch_added_is_reported(self):
        """The #391 shape, which the merge-base comparison cannot see.

        The file does not exist at the base, so `documented(before)` is empty
        and no loss is representable. The branch's own commits are the only
        place that history exists.
        """
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("seed.rs", "fn seed() {}\n")
            repo.branch("work")
            repo.commit("new.rs", DOCUMENTED_CONST)
            repo.commit("new.rs", CAPTURED_CONST)
            self.assertEqual(
                repo.exit_code(), 1, "the gate must fail on a captured doc"
            )

    def test_a_doc_captured_and_then_restored_within_a_branch_passes(self):
        """A branch whose HEAD is correct must not be blocked by a state it
        passed through.

        The pairwise pass over branch-added files walks every adjacent pair,
        so a doc captured in one commit and restored in a later one shows up
        as a loss between two intermediate revisions. Reporting that blocks a
        PR that is fine, which is the false accusation that makes a gate
        untrustworthy: the first thing a maintainer does with a gate that
        cries wolf is stop reading it.

        Found within an hour of shipping the pairwise pass, on a real PR
        whose head was correct.
        """
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("seed.rs", "fn seed() {}\n")
            repo.branch("work")
            repo.commit("new.rs", DOCUMENTED_CONST)
            repo.commit("new.rs", CAPTURED_CONST)
            # ... and put it back.
            repo.commit(
                "new.rs",
                "/// Its own doc.\nconst SYNTAX_SEMANTIC: &[&str] = &[\"b\"];\n\n"
                + DOCUMENTED_CONST,
            )
            self.assertEqual(
                repo.exit_code(),
                0,
                "a doc restored before the branch tip is not a loss",
            )

    def test_a_branch_that_captures_nothing_passes(self):
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", DOCUMENTED_CONST)
            repo.branch("work")
            repo.commit("a.rs", DOCUMENTED_CONST + "\n/// Another.\nconst B: u8 = 2;\n")
            self.assertEqual(repo.exit_code(), 0, "an honest addition must pass")

    def test_a_declared_removal_is_exempt(self):
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", DOCUMENTED_CONST)
            repo.branch("work")
            repo.commit(
                "a.rs",
                "const SYNTAX_SCOPES: &[&str] = &[\"a\"];\n",
                "drop it\n\ndoc-removal: a.rs::SYNTAX_SCOPES",
            )
            self.assertEqual(
                repo.exit_code(),
                0,
                "a declared removal is the documented escape hatch",
            )


if __name__ == "__main__":
    unittest.main()


class HeadOnlyOrphanTests(unittest.TestCase):
    """The head-only pass: captures the DIFF cannot see (#427, #436).

    The diff check reports an item that HAD a doc and HAS none. Two real
    captures are invisible to it: one whose victim is new on the branch (so
    it had no doc at the merge base to lose, #427), and one whose capturing
    item is of a kind `ITEM` does not model, such as a `use` (#436). Both
    leave the same fingerprint at HEAD — a doc block with no item under it —
    which needs no base revision to see.
    """

    def test_a_use_between_a_doc_and_its_fn_is_caught(self):
        """#436, reduced. This exact shape shipped and the gate passed."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "fn existing() {}\n")
            repo.branch("feat")
            # The victim is added by the BRANCH, so the diff check has
            # nothing at the base to compare it against.
            repo.commit(
                "a.rs",
                "fn existing() {}\n\n/// Documents beta.\nuse std::fmt;\n\nfn beta() {}\n",
            )
            self.assertEqual(repo.exit_code(), 1)

    def test_a_capture_whose_victim_is_new_on_the_branch_is_caught(self):
        """#427: both items added by the branch, so the merge-base
        comparison sees no loss however many commits it spans."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "fn existing() {}\n")
            repo.branch("feat")
            repo.commit("a.rs", "fn existing() {}\n\n/// Documents beta.\nfn beta() {}\n")
            # A later commit inserts a documented item above it, taking the
            # first doc and stranding its own.
            # Two `///` lines in a row are ONE block, which is legal; a
            # real insertion leaves a blank line between the stranded doc
            # and the newcomer's own, which is what rustfmt produces.
            repo.commit(
                "a.rs",
                "fn existing() {}\n\n/// Documents beta.\n\n"
                "/// Documents gamma.\nfn gamma() {}\n\nfn beta() {}\n",
            )
            self.assertEqual(repo.exit_code(), 1)

    def test_a_capture_both_older_passes_see_is_reported_once(self):
        """#463: when the victim is an item `ITEM` models and was documented
        at the base, the loss pass names it AND the head-only pass names the
        block it left stranded. Both are true and both point at one
        insertion; a reader counting annotations counts two defects. The
        loss message is the older and more precise of the two, so it keeps
        the report and the stranded-block one stands down."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "/// Documents beta.\nfn beta() {}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "/// Documents beta.\n\n/// Documents gamma.\nfn gamma() {}\n\nfn beta() {}\n",
            )
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertIn(
                "`beta` had a doc comment",
                text,
                f"the loss pass keeps the report: {text}",
            )
            self.assertEqual(
                text.count("::error"),
                1,
                f"one insertion, one annotation: {text}",
            )

    def test_a_stranded_block_unrelated_to_a_loss_is_still_reported(self):
        """The stand-down is keyed on the BLOCK, not on the file: a loss in a
        file must not silence every stranded block in it. Here the branch
        makes the #463 capture and, elsewhere in the same file, strands a
        block that never documented the lost item. That one is a second
        defect and keeps its annotation."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "/// Documents beta.\nfn beta() {}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "/// Documents beta.\n\n/// Documents gamma.\nfn gamma() {}\n\nfn beta() {}\n"
                "\n/// Lonely.\n\n/// Documents delta.\nfn delta() {}\n",
            )
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertIn("`beta` had a doc comment", text)
            self.assertIn("'/// Lonely.'", text, f"the unrelated block is still stranded: {text}")
            self.assertNotIn("'/// Documents beta.'", text, f"the block the loss explains stands down: {text}")
            self.assertEqual(text.count("::error"), 2, f"two defects, two annotations: {text}")

    def test_duplicated_prose_does_not_silence_a_second_stranded_block(self):
        """The stand-down pairs a loss with the stranded block ABOVE its
        victim, not with every block that reads the same. `/// Creates a new
        instance.` above two `new`s is ordinary Rust; here one copy is the
        #463 capture of `A::new`, and the other is a #427-shaped capture in
        a new impl, whose victim has no base doc to lose and so is seen by
        the head-only pass alone. Matching on text would silence it."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "impl A {\n    /// Creates a new instance.\n    pub fn new() {}\n}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "impl A {\n    /// Creates a new instance.\n\n    /// Helper.\n"
                "    pub fn helper() {}\n\n    pub fn new() {}\n}\n"
                "impl C {\n    /// Creates a new instance.\n\n    /// Other.\n"
                "    pub fn other() {}\n\n    pub fn new() {}\n}\n",
            )
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertIn("`A::new` had a doc comment", text)
            self.assertIn("line=10::", text, f"the copy in impl C is its own defect: {text}")
            self.assertNotIn("line=2::", text, f"the copy above A::new is the loss's: {text}")
            self.assertEqual(text.count("::error"), 2, f"two captures, two annotations: {text}")

    def test_a_rewritten_victim_block_does_not_lend_its_loss_to_a_farther_block(self):
        """The pairing takes the nearest stranded block ABOVE the victim and
        stands it down only when its text is one a loss explains. When the
        branch both rewrote `A::new`'s prose and captured it, the block
        directly above `A::new` no longer matches the base, and the loss
        must not reach past it to silence an identically-worded stranded
        block in another impl. Three defects, three annotations."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "impl A {\n    /// Creates a new instance.\n    pub fn new() {}\n}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "impl C {\n    /// Creates a new instance.\n\n    /// Other.\n"
                "    pub fn other() {}\n\n    pub fn new() {}\n}\n"
                "impl A {\n    /// Creates a new instance, better.\n\n    /// Helper.\n"
                "    pub fn helper() {}\n\n    pub fn new() {}\n}\n",
            )
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertIn("`A::new` had a doc comment", text)
            self.assertIn("line=2::", text, f"impl C's stranded copy is its own defect: {text}")
            self.assertIn("line=10::", text, f"the rewritten block is stranded too: {text}")
            self.assertEqual(text.count("::error"), 3, f"three defects, three annotations: {text}")

    def test_a_victim_moved_above_its_old_block_leaves_the_block_reported(self):
        """The stand-down needs a victim BELOW the block. Moving `beta` above
        its own doc strands the block at end of file with no victim under
        it, so the loss explains nothing here and both annotations print;
        matching on text alone used to fold them into one."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "/// Documents beta.\nfn beta() {}\n")
            repo.branch("feat")
            repo.commit("a.rs", "fn beta() {}\n/// Documents beta.\n")
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertIn("`beta` had a doc comment", text)
            self.assertIn("line=2::", text, f"the block at end of file is reported: {text}")
            self.assertEqual(text.count("::error"), 2, f"loss and stranded block both print: {text}")

    def test_two_identical_blocks_above_one_victim_are_both_reported(self):
        """When two stranded blocks with the victim's prose both sit above it,
        nothing says which one it lost: the nearer may be an independent
        capture that happens to read the same. Standing the nearer one down
        hides that defect and leaves the report pointing at the other block,
        so an ambiguous pairing stands nothing down and all three print."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "impl A {\n    /// Creates a new instance.\n    pub fn new() {}\n}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "impl A {\n    /// Creates a new instance.\n\n    /// Helper.\n"
                "    pub fn helper() {}\n\n    /// Creates a new instance.\n\n    /// Other.\n"
                "    pub fn other() {}\n\n    pub fn new() {}\n}\n",
            )
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertIn("`A::new` had a doc comment", text)
            self.assertIn("line=2::", text, f"the farther copy is reported: {text}")
            self.assertIn("line=7::", text, f"and so is the nearer one: {text}")
            self.assertEqual(text.count("::error"), 3, f"an ambiguous pairing stands nothing down: {text}")

    def test_cfg_twins_each_captured_stand_both_blocks_down(self):
        """Two `#[cfg]` definitions under one key, each with its own copy of
        the doc, each captured by an insertion. The first victim pairs with
        the first block; the second must still pair with the second, which
        needs the ambiguity count to skip blocks already stood down. One
        loss, no stranded-block annotations."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit(
                "a.rs",
                "/// Creates a new instance.\n#[cfg(unix)]\nfn new() {}\n\n"
                "/// Creates a new instance.\n#[cfg(windows)]\nfn new() {}\n",
            )
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "/// Creates a new instance.\n\n/// Helper.\nfn helper_a() {}\n\n"
                "#[cfg(unix)]\nfn new() {}\n\n"
                "/// Creates a new instance.\n\n/// Helper.\nfn helper_b() {}\n\n"
                "#[cfg(windows)]\nfn new() {}\n",
            )
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertIn("`new` had a doc comment", text)
            self.assertNotIn("line=", text, f"both stranded copies are explained: {text}")
            self.assertEqual(text.count("::error"), 1, f"one loss, one annotation: {text}")

    def test_ordinary_docs_are_not_reported(self):
        """The control. A gate that cries wolf stops being read, so the
        shapes a real file is full of must stay silent: attributes and
        blank lines between a doc and its item, a `//` note under a doc,
        and a doc above an item kind the regex does not model."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "fn existing() {}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "fn existing() {}\n\n"
                # An attribute between doc and item.
                "/// Documented, with an attribute under the doc.\n"
                "#[derive(Clone, Debug)]\n"
                "struct A;\n\n"
                # A plain comment under a doc: does NOT break attachment.
                "/// Documented, with an implementation note.\n"
                "// not a doc comment\n"
                "fn b() {}\n\n"
                # A doc above an item kind `ITEM` does not model.
                "/// Documented, above an impl.\n"
                "impl A {}\n\n"
                # A doc above a module.
                "/// Documented, above a mod.\n"
                "mod inner {}\n",
            )
            self.assertEqual(repo.exit_code(), 0)

    def test_a_doc_block_at_end_of_file_is_reported(self):
        """The third shape the pass reports, and the one with no test until
        now: a doc block with no item after it at all."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "fn existing() {}\n")
            repo.branch("feat")
            repo.commit("a.rs", "fn existing() {}\n\n/// Documents nothing at all.\n")
            self.assertEqual(repo.exit_code(), 1)

    def test_a_capture_by_a_documented_newcomer_is_caught(self):
        """Was the residue #427 kept, and is now caught by the diff pass
        (#455). When the inserted item carries its OWN doc nothing is
        stranded, so the head-only pass still cannot see it; what gives it
        away is that `/// Documents alpha.` sat above `fn alpha()` earlier on
        the branch and sits above a newly inserted item now, leaving `alpha`
        bare. Inverted rather than deleted, as the earlier version asked."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "fn existing() {}\n")
            repo.branch("feat")
            repo.commit("a.rs", "fn existing() {}\n\n/// Documents alpha.\nfn alpha() {}\n")
            repo.commit(
                "a.rs",
                "fn existing() {}\n\n/// Documents alpha.\n"
                "/// ...but now sits above the newcomer.\n"
                "struct Inserted;\n\nfn alpha() {}\n",
            )
            self.assertEqual(repo.exit_code(), 1)

    def test_a_documented_re_export_is_not_reported(self):
        """`pub use` CAN legitimately carry a doc — rustdoc renders it — so
        flagging one would fail a correct PR. A private `use` cannot appear
        in the docs at all, which is why it is the only form treated as
        unable to hold prose."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "fn existing() {}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "fn existing() {}\n\n"
                "/// Re-exported for convenience.\n"
                "pub use crate::x::Y;\n\n"
                "/// Also re-exported.\n"
                "pub(crate) use crate::x::Z;\n",
            )
            self.assertEqual(repo.exit_code(), 0)

    def test_a_use_that_documents_nothing_untouched_is_not_reported(self):
        """Only CHANGED files are swept, so a pre-existing orphan elsewhere
        does not fail an unrelated PR."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "/// Stranded.\nuse std::fmt;\n\nfn a() {}\n")
            repo.commit("b.rs", "fn b() {}\n")
            repo.branch("feat")
            repo.commit("b.rs", "fn b() {}\n\nfn c() {}\n")
            self.assertEqual(repo.exit_code(), 0)



class ReassignedDocTests(unittest.TestCase):
    """The third pass (#455): a doc line that changed the item it sits above.

    The head-only pass sees a capture only through the prose it STRANDS, and
    a capture whose newcomer brings its own doc strands nothing: rustfmt
    leaves the two `///` lines contiguous, they read as one ordinary block,
    and the item below them is the thief. What separates that from a genuine
    two-line doc block is not in the snapshot at all - it is in the diff,
    where the same line used to sit above a different item.
    """

    def test_a_contiguous_capture_of_a_variants_doc_is_caught(self):
        """#455, reduced from the instance that shipped in #454: the victim
        is an enum variant, which `ITEM` does not model, and the stolen doc
        is contiguous with the thief's, which the head-only pass reads as
        one block. Both existing passes are blind to it."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit(
                "a.rs",
                "enum E {\n"
                "    /// Doc for A, an existing item.\n"
                "    A,\n"
                "}\n",
            )
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "enum E {\n"
                "    /// Doc for A, an existing item.\n"
                "    /// Doc for B, inserted above it.\n"
                "    B,\n"
                "    A,\n"
                "}\n",
            )
            self.assertEqual(repo.exit_code(), 1)

    def test_the_error_names_the_line_and_both_items(self):
        """A gate that says only "something moved" sends the reader hunting.
        The message has to carry the prose, what it used to describe, and
        what it describes now."""
        before = "enum E {\n    /// Doc for A.\n    A,\n}\n"
        after = "enum E {\n    /// Doc for A.\n    /// Doc for B.\n    B,\n    A,\n}\n"
        found = gate.reassigned_docs(before, after)
        self.assertEqual(len(found), 1, found)
        _line, doc, old, new = found[0]
        self.assertEqual(doc, "/// Doc for A.")
        self.assertEqual(old, "A,")
        self.assertEqual(new, "B,")

    def test_moving_a_doc_back_onto_its_own_item_is_not_a_capture(self):
        """The corrective PR. Repairing a misattribution moves the prose the
        other way, and the item it lands on is one that already existed -
        which is exactly what an INSERTED thief is not."""
        before = "enum E {\n    /// Doc for A.\n    B,\n    A,\n}\n"
        after = "enum E {\n    B,\n    /// Doc for A.\n    A,\n}\n"
        self.assertEqual(gate.reassigned_docs(before, after), [])

    def test_reordering_documented_items_is_not_a_capture(self):
        """Each doc travels with its own item, so no line changes owner."""
        before = "enum E {\n    /// Doc A.\n    A,\n    /// Doc B.\n    B,\n}\n"
        after = "enum E {\n    /// Doc B.\n    B,\n    /// Doc A.\n    A,\n}\n"
        self.assertEqual(gate.reassigned_docs(before, after), [])

    def test_a_renamed_item_is_not_a_capture(self):
        """The old subject line is gone at head, so nothing was stranded."""
        before = "/// Doc for alpha.\nfn alpha() {}\n"
        after = "/// Doc for alpha.\nfn renamed() {}\n"
        self.assertEqual(gate.reassigned_docs(before, after), [])

    def test_a_victim_that_keeps_a_doc_of_its_own_is_not_reported(self):
        """The swap that fixes a capture leaves both items documented. Only
        prose that leaves an item BARE is a loss worth failing a PR over."""
        # `Inserted` is new, and A keeps a doc line, so nothing is bare.
        before = "enum E {\n    /// Doc A.\n    A,\n    /// Doc B.\n    B,\n}\n"
        after = (
            "enum E {\n    /// Doc A.\n    Inserted,\n"
            "    /// Doc A, still here.\n    A,\n    /// Doc B.\n    B,\n}\n"
        )
        self.assertEqual(gate.reassigned_docs(before, after), [])

    def test_a_doc_line_that_repeats_in_the_file_is_not_a_capture(self):
        """Uniqueness is what keeps a coincidence from reading as a move. The
        same `/// The width, in cells.` above three fields has no single owner
        to have changed, so a rename in one struct plus a deletion in another
        must not add up to a capture."""
        before = (
            "struct A {\n    /// The width, in cells.\n    w: u16,\n}\n"
            "struct B {\n    /// The width, in cells.\n    x: u16,\n}\n"
        )
        after = (
            "struct A {\n    /// The width, in cells.\n    width: u16,\n}\n"
            "struct B {\n    x: u16,\n}\n"
        )
        self.assertEqual(gate.reassigned_docs(before, after), [])

    def test_a_bare_separator_line_is_not_a_doc_that_moved(self):
        """A `///` with no prose says nothing about which item it describes,
        and a long block is full of them. Reporting one names a line the
        reader cannot act on."""
        before = "/// Alpha.\n///\nfn a() {}\n"
        after = "/// Alpha.\n///\nfn zz() {}\n\nfn a() {}\n"
        moved = [f for f in gate.reassigned_docs(before, after) if f[1] == "///"]
        self.assertEqual(moved, [], "a separator is not evidence of anything")

    def test_a_two_hop_capture_names_the_item_that_lost_its_doc(self):
        """The message is the product here. When a doc is captured twice on
        one branch, the victim is the item it described BEFORE the branch, not
        the intermediate thief - repairing the one the gate names would leave
        the real victim bare."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    A,\n}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for A.\n    /// Doc for B.\n    B,\n    A,\n}\n",
            )
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for A.\n    /// Doc for B.\n"
                "    /// Doc for C.\n    C,\n    B,\n    A,\n}\n",
            )
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertIn(
                "described 'A,'",
                text,
                f"the victim is the item that had the doc at the base: {text}",
            )

    def test_a_capture_made_between_two_branch_commits_is_caught(self):
        """Both items are absent at the merge base, so only the walk over the
        branch's own commits can see this one."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "fn existing() {}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "fn existing() {}\n\nenum E {\n    /// Doc for A.\n    A,\n}\n",
            )
            repo.commit(
                "a.rs",
                "fn existing() {}\n\nenum E {\n    /// Doc for A.\n"
                "    /// Doc for B.\n    B,\n    A,\n}\n",
            )
            self.assertEqual(repo.exit_code(), 1)

    def test_a_capture_a_later_commit_repaired_passes(self):
        """What matters is the state at HEAD. Reporting every state a branch
        passed through blocks a PR whose head is correct, which is the false
        accusation that stops a gate being read."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    A,\n}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for A.\n    /// Doc for B.\n    B,\n    A,\n}\n",
            )
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for B.\n    B,\n    /// Doc for A.\n    A,\n}\n",
            )
            self.assertEqual(repo.exit_code(), 0)

    def test_a_declared_removal_exempts_a_variant_too(self):
        """The declaration is keyed on the name the gate's own error prints.
        For a victim `ITEM` does not model - an enum variant is the kind #455
        was filed for - that key comes from the subject line, and without it
        the branch has a merge-blocking check and no way to declare."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    A,\n}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for A.\n    /// Doc for B.\n    B,\n    A,\n}\n",
                message="feat: b\n\ndoc-removal: a.rs::A",
            )
            self.assertEqual(repo.exit_code(), 0)

    def test_the_diff_pass_stays_out_of_a_capture_the_others_report(self):
        """A doc block separated from the newcomer's by a blank line is
        stranded, and both older passes see it: the loss pass names the item
        that lost its prose, the head-only pass names the stranded block. The
        diff pass must not add a THIRD annotation, and in particular must not
        report that the prose now describes another `///` line, which is not
        an item and not something a reader can act on.

        The victim is an enum variant, which `ITEM` does not model, so the
        loss pass cannot fire here: what keeps the diff pass quiet has to be
        the diff pass itself rather than the dedupe against a loss."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    A,\n}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for A.\n\n    /// Doc for B.\n    B,\n    A,\n}\n",
            )
            code, text = repo.run_gate()
            self.assertEqual(code, 1)
            self.assertNotIn(
                "#455",
                text,
                f"the diff pass has nothing to say about a stranded block: {text}",
            )
            self.assertEqual(
                text.count("::error"),
                1,
                f"the head-only pass alone: {text}",
            )

    def test_a_raw_identifier_is_one_name(self):
        """`r#type` and `r#match` are different items. A key that stopped at
        `r` would make one declared removal excuse the other, which is the
        error the file qualifier exists to prevent one level up."""
        self.assertEqual(gate.subject_key("    r#type,"), "r#type")
        self.assertEqual(gate.subject_key("    r#match,"), "r#match")
        self.assertEqual(gate.subject_key("    pub r#fn: u8,"), "r#fn")

    def test_a_declared_removal_of_a_raw_identifier_is_exempt(self):
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for the type arm.\n    r#type,\n}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for the type arm.\n    /// Doc for the match arm.\n"
                "    r#match,\n    r#type,\n}\n",
                message="feat: match\n\ndoc-removal: a.rs::r#type",
            )
            self.assertEqual(repo.exit_code(), 0)

    def test_a_declaration_naming_a_different_raw_identifier_does_not_excuse_it(self):
        """The control for the one above: `r#match` is not `r#type`."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for the type arm.\n    r#type,\n}\n")
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for the type arm.\n    /// Doc for the match arm.\n"
                "    r#match,\n    r#type,\n}\n",
                message="feat: match\n\ndoc-removal: a.rs::r#match",
            )
            self.assertEqual(repo.exit_code(), 1)

    def test_merging_main_does_not_report_what_main_did(self):
        """A merge's first parent is the branch tip, so the pair `(M^, M)` is
        everything the OTHER side brought in. Replaying that as the branch's
        own work reports a capture main already declared - and the
        declaration is invisible here, since the commit-message scan starts
        above the merge base, so the message names a hatch the reader cannot
        use. This repo merges main into a branch that needs it, so the shape
        is the convention rather than an exotic case."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for Toggle.\n    Toggle,\n}\n")
            repo.branch("feat")
            # The branch touches the same file, far from the doc block.
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for Toggle.\n    Toggle,\n}\n\npub fn helper() {}\n",
            )
            repo.checkout("main")
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for Toggle.\n    /// Doc for Load.\n"
                "    Load,\n    Toggle,\n}\n",
                message="feat: load\n\ndoc-removal: a.rs::Toggle",
            )
            repo.checkout("feat")
            repo.merge("main")
            self.assertEqual(
                repo.exit_code(base="main"),
                0,
                "main's own change, declared on main, is not this branch's capture",
            )

    def test_a_capture_after_a_merge_is_still_caught(self):
        """The control for the one above: skipping merges must not skip the
        branch's own commits that follow one."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    A,\n}\n")
            repo.branch("feat")
            repo.commit("b.rs", "fn b() {}\n")
            repo.checkout("main")
            repo.commit("c.rs", "fn c() {}\n")
            repo.checkout("feat")
            repo.merge("main")
            repo.commit(
                "a.rs",
                "enum E {\n    /// Doc for A.\n    /// Doc for B.\n    B,\n    A,\n}\n",
            )
            self.assertEqual(repo.exit_code(base="main"), 1)

    def test_a_capture_split_across_two_commits_is_caught(self):
        """What the base-to-head pair is FOR, and what nothing pinned. Each
        per-commit pair asks whether the line the prose landed on is new IN
        THAT PAIR, so a thief added above the block in one commit and moved
        under it in the next is invisible to every pair but this one."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    A,\n}\n")
            repo.branch("feat")
            # B arrives ABOVE the block: no capture yet.
            repo.commit("a.rs", "enum E {\n    B,\n    /// Doc for A.\n    A,\n}\n")
            # and then moves UNDER it, which is the capture.
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    B,\n    A,\n}\n")
            self.assertEqual(repo.exit_code(), 1)

    def test_a_keyword_led_subject_keys_on_the_name(self):
        """`mod theme;` is the unmodelled-item case the fallback exists for.
        Keying it as `mod` made one declaration excuse every captured `mod`
        in the file, and one leading keyword is not enough: an item can carry
        four before its name, and an impl header names a type rather than the
        first path segment of a trait."""
        for line, key in [
            ("mod theme;", "theme"),
            ("pub mod pane;", "pane"),
            ("impl Foo {", "Foo"),
            ("    A,", "A"),
            ("    r#type,", "r#type"),
            ("pub(crate) fn foo(", "foo"),
            # Four qualifiers, and an ABI string the name pattern cannot step
            # over on its own.
            ('pub async unsafe extern "C" fn bar(', "bar"),
            # The bang belongs to the keyword.
            ("macro_rules! m {", "m"),
            # Impl headers key like the loss pass keys their methods, so one
            # declaration cannot cover two impls of the same type: taking the
            # first word gave `fmt` to both of these.
            ("impl fmt::Display for Foo {", "fmt::Display for Foo"),
            ("impl fmt::Debug for Foo {", "fmt::Debug for Foo"),
            ("unsafe impl Send for X {}", "Send for X"),
            # Generics are stripped, so a reformat does not move the key.
            ("impl<T> Foo<T> {", "Foo"),
        ]:
            self.assertEqual(gate.subject_key(line), key, line)

    def test_two_raw_methods_in_one_impl_are_two_keys(self):
        """`ITEM` stopping at `r` collapsed them, and the "any documented"
        reading then hid a capture on either behind the other's prose."""
        text = (
            "impl Foo {\n    /// Doc for type.\n    pub fn r#type(&self) {}\n\n"
            "    /// Doc for match.\n    pub fn r#match(&self) {}\n}\n"
        )
        keys = gate.documented(text)
        self.assertIn("Foo::r#type", keys)
        self.assertIn("Foo::r#match", keys)

    def test_two_impls_of_one_type_are_two_declarations(self):
        """The collision the impl key exists to prevent, end to end: with both
        headers keyed on `fmt`, one `doc-removal: a.rs::fmt` silenced both."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            before = (
                "struct Foo;\n\n/// Doc for the Display impl.\n"
                "impl fmt::Display for Foo {}\n\n/// Doc for the Debug impl.\n"
                "impl fmt::Debug for Foo {}\n"
            )
            repo.commit("a.rs", before)
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "struct Foo;\n\n/// Doc for the Display impl.\n"
                "/// Doc for the inserted impl.\n"
                "impl fmt::LowerHex for Foo {}\n"
                "impl fmt::Display for Foo {}\n\n/// Doc for the Debug impl.\n"
                "impl fmt::Debug for Foo {}\n",
                message="feat: hex\n\ndoc-removal: a.rs::fmt::Debug for Foo",
            )
            self.assertEqual(
                repo.exit_code(),
                1,
                "a declaration naming the DEBUG impl must not excuse the Display one",
            )

    def test_a_declaration_naming_the_captured_impl_does_excuse_it(self):
        """The other half, and the one that makes the pair discriminate: with
        both headers keyed on `fmt`, the wrong declaration would work, so a
        test that only checks the refusal passes either way."""
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit(
                "a.rs",
                "struct Foo;\n\n/// Doc for the Display impl.\n"
                "impl fmt::Display for Foo {}\n\n/// Doc for the Debug impl.\n"
                "impl fmt::Debug for Foo {}\n",
            )
            repo.branch("feat")
            repo.commit(
                "a.rs",
                "struct Foo;\n\n/// Doc for the Display impl.\n"
                "/// Doc for the inserted impl.\n"
                "impl fmt::LowerHex for Foo {}\n"
                "impl fmt::Display for Foo {}\n\n/// Doc for the Debug impl.\n"
                "impl fmt::Debug for Foo {}\n",
                message="feat: hex\n\ndoc-removal: a.rs::fmt::Display for Foo",
            )
            self.assertEqual(repo.exit_code(), 0)

    def test_a_capture_inside_a_merge_resolution_is_a_known_gap(self):
        """Pinned as scope rather than left to be discovered.

        The walk skips merges, because a merge's first parent is the branch
        tip and `(M^, M)` otherwise replays the other side's work as this
        branch's. What that costs is a capture the RESOLUTION itself makes,
        when the thief is a line that already existed on the side being
        merged: the base-to-head pair cannot see it either, since "the line
        the prose landed on is new" is false for a line main already had.

        A resolution that invents a NEW thief line is still caught, so the
        gap is exactly this shape. If it is ever closed, this test inverts.
        """
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    A,\n    Z,\n}\n")
            repo.branch("feat")
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    A,\n    Zed,\n}\n")
            repo.checkout("main")
            repo.commit("a.rs", "enum E {\n    /// Doc for A.\n    A,\n    Z,\n    B,\n}\n")
            repo.checkout("feat")
            run(repo.path, "git", "merge", "--no-commit", "main", check=False)
            # The resolution puts a line main already had under the doc block.
            (repo.path / "a.rs").write_text(
                "enum E {\n    /// Doc for A.\n    B,\n    A,\n    Zed,\n}\n"
            )
            run(repo.path, "git", "add", "-A")
            run(repo.path, "git", "commit", "-q", "--no-edit")
            self.assertEqual(
                repo.exit_code(base="main"),
                0,
                "known gap: a resolution that moves an existing line under a doc block",
            )

    def test_a_commit_with_no_parent_does_not_abort_the_gate(self):
        """The `rev^` probe, which nothing pinned.

        A commit in `base..head` can have no parent - an orphan branch is the
        reachable case, a shallow boundary the other - and `git show
        <root>^:<file>` fails as a BAD REVISION rather than as a missing path,
        which `git()` deliberately does not tolerate. Without the probe the
        gate raises `SystemExit` and reports nothing at all: not a pass, not a
        failure, just an abort with a git error in the log.
        """
        with tempfile.TemporaryDirectory() as tmp:
            repo = Repo(Path(tmp))
            repo.commit("seed.rs", "fn seed() {}\n")
            # An orphan branch: its first commit has no parent at all.
            run(repo.path, "git", "checkout", "-q", "--orphan", "detached")
            run(repo.path, "git", "rm", "-rq", "--cached", ".")
            repo.commit("a.rs", "/// Doc for a.\nfn a() {}\n")
            self.assertEqual(
                repo.exit_code(base="main"),
                0,
                "a parentless commit is skipped, not fatal",
            )

    def test_a_block_doc_closer_is_not_prose(self):
        """`*/` closes a `/** */` block and says nothing about any item, but
        it matches the continuation-line shape, so it read as a doc line with
        the prose `/`. Reported, it names a line the reader cannot act on."""
        before = "/**\n */\nfn a() {}\n"
        after = "/**\n */\nfn zz() {}\n\nfn a() {}\n"
        self.assertEqual(
            gate.reassigned_docs(before, after),
            [],
            "the delimiter is not the documentation",
        )

    def test_a_captured_block_doc_is_reported_once(self):
        """One insertion is one defect. Keying the report on each doc LINE
        turned a three-line block into three annotations that name the same
        item, the same thief and the same file."""
        before = "/** Doc for A.\n * More.\n */\nfn a() {}\n"
        after = "/** Doc for A.\n * More.\n */\nfn zz() {}\n\nfn a() {}\n"
        found = gate.reassigned_docs(before, after)
        self.assertEqual(
            len(found), 1, f"one block above one item is one report: {found}"
        )
        self.assertEqual(found[0][1], "/** Doc for A.", "and it names the block's first line")