brgr-cli 2.15.12

Let Codex or Claude Code hand work to other coding agents, each in its own Herdr pane: the brgr CLI and Herdr plugin.
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
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
//! Removal of brgr-owned task worktrees and the branches they created.
//!
//! [`crate::workspace`] creates task worktrees and never deletes, so removal
//! lives here: behind `brgr prune`, which defaults to reporting, and
//! [`reclaim_task`], which a decision runs for its own revision.
//!
//! git is used for the two removals, but it is deliberately **not** trusted as
//! the only safety authority. `git worktree remove` refuses a worktree with
//! modified or untracked files, and is forced only when brgr has shown every
//! such change is disposable: an untracked tool-state or cache directory
//! (`.gjc/`, `.commandcode/`, `.agent-progress/`, `.build/` and the like), or a
//! worktree whose patch is byte-for-byte the diff the store sealed with the
//! result. A task branch goes when every commit on it
//! survives elsewhere: in `HEAD`, or on another branch or remote-tracking
//! branch — a task started from a feature branch carries that branch's
//! commits, which `git branch -d` would count as unmerged forever — or, for an
//! explicit `brgr prune` only, when the revision is settled, its result sealed a
//! `text/x-diff` (`--capture-diff`), and every change in
//! `git diff --binary MERGE_BASE TIP` (changed lines, and mode changes, renames,
//! created and deleted files) is also in that sealed diff. `MERGE_BASE` is
//! `git merge-base HEAD TIP`. The reclaim a decision runs never uses the sealed
//! rule: the branch is how an owner pushes the work. A rebase may drop lines; it
//! may not add any. A missing merge-base, a diff
//! larger than the sealed-artifact limit, a binary patch the comparison cannot
//! prove, or any error keeps the branch. git's clean check runs
//! `git status --porcelain` without `--ignored`, so a `.env`, a downloaded
//! credential, or a build cache is invisible to it and would be deleted
//! silently. A task worktree is exactly where an agent has been working, which
//! makes it the most likely place in a repository to hold such a file. This
//! module therefore checks the ignored set itself and keeps the worktree unless
//! the caller opts in, or every ignored path is a directory a tool owns
//! (`node_modules`, `target`, `.next`, `.agent-progress`, `.build`,
//! `.commandcode` and the like). The four worker tool-state names are also judged
//! disposable when untracked; the package managers' names are not.
//!
//! Every candidate must also be a real directory (not a symlink), a worktree git
//! itself has registered for its repository and has not locked, a name
//! [`crate::workspace`] could have produced, outside the current working
//! directory, and the checkout of a settled task revision: a candidate the owner
//! decided, or a failed, cancelled, or lost result the owner acknowledged, with
//! no attempt or granted retry left and no worker process still alive.
//!
//! The repositories come from the store, never from the worktrees root. Each
//! candidate is judged against the repository its own task was admitted in; a
//! directory's name is only a name, and a checkout of some other repository can
//! be dropped under the root by hand. An earlier version asked whichever
//! directory sorted first and trusted the answer, so a stray `Backup` checkout
//! made `--apply` delete branches in a repository brgr had never touched.
//!
//! A sweep also reclaims the `brgr/task-*` branches left behind by worktrees that
//! no longer exist — removing one by hand was the only reclamation available
//! before this command. Those branches get the same checks as a worktree: a task
//! revision of that repository, a recorded decision, a reported owner, and
//! commits that live elsewhere or in the sealed result. Stale registrations
//! are removed one path at a time;
//! `git worktree prune` is repository-wide and would also drop the registration
//! of a user's own worktree on an unmounted volume. One unreadable directory is
//! reported as a single kept row rather than ending the sweep, and each
//! repository is read from git once.
//!
//! No sealed result, decision, artifact, or task row is ever removed. Those cost
//! roughly 9 KiB per task; a worktree costs the size of the checkout.
//!
//! Cross-owner isolation is explicitly outside v1 scope, so a prune acts on
//! every settled task in this control home. Each row reports its owner so that
//! is visible rather than silent.

use std::{
    collections::{BTreeMap, HashMap},
    fs,
    io::Read as _,
    path::{Path, PathBuf},
    process::Command,
};

use anyhow::Result;
use brgr_protocol::{TaskId, TaskSpec, TerminalOutcome};
use brgr_store::{OpenReason, Settlement, Store};
use serde_json::json;

use crate::{Paths, print_value};

/// Everything one sweep found: the worktrees it walked, and the branches left
/// behind by worktrees that no longer exist.
pub(crate) struct Prune {
    pub(crate) entries: Vec<Entry>,
    pub(crate) orphans: Vec<Orphan>,
}

/// A `brgr/task-*` branch whose worktree is gone.
pub(crate) struct Orphan {
    pub(crate) branch: String,
    pub(crate) owner: Option<String>,
    pub(crate) outcome: Outcome,
}

/// One brgr-owned worktree directory and what pruning did or would do with it.
pub(crate) struct Entry {
    pub(crate) worktree: PathBuf,
    pub(crate) slug: String,
    pub(crate) owner: Option<String>,
    /// Ignored-but-present paths git's own clean check cannot see.
    pub(crate) ignored: Vec<String>,
    pub(crate) outcome: Outcome,
}

pub(crate) enum Outcome {
    /// Eligible, and this was a report-only run. Every check that `--apply`
    /// performs has already passed, so the two runs agree.
    Removable,
    /// Eligible, and this run removed it. `Some` names the sealed result that
    /// already holds the branch's changes when that is why the branch went.
    Removed(Option<String>),
    /// The checkout is gone but git kept the branch, which is the normal outcome
    /// for a task whose agent committed work. Counted as removed, because the
    /// reclaimed space is gone and the directory will never be seen again.
    RemovedKeepingBranch(String),
    /// Left in place; the string says why, so a report is actionable.
    Kept(String),
}

impl Outcome {
    pub(crate) fn code(&self) -> &'static str {
        match self {
            Self::Removable => "removable",
            Self::Removed(_) => "removed",
            Self::RemovedKeepingBranch(_) => "removed_branch_kept",
            Self::Kept(_) => "kept",
        }
    }

    pub(crate) fn reason(&self) -> Option<&str> {
        match self {
            Self::Kept(reason) | Self::RemovedKeepingBranch(reason) => Some(reason),
            Self::Removed(reason) => reason.as_deref(),
            Self::Removable => None,
        }
    }
}

/// Reports, and with `apply` removes, every prunable task worktree.
///
/// `include_ignored` opts in to removing a worktree that holds ignored files.
pub(crate) fn prune(
    worktrees_root: &Path,
    store: &Store,
    worker_alive: &dyn Fn(TaskId) -> bool,
    apply: bool,
    include_ignored: bool,
) -> Prune {
    let current_dir = std::env::current_dir()
        .ok()
        .and_then(|path| canonical(&path));
    let sweep = Sweep {
        store,
        current_dir: current_dir.as_deref(),
        include_ignored,
        worker_alive,
    };
    let mut entries = Vec::new();
    let mut orphans = Vec::new();

    let mut known = Repositories::load(store);
    let mut unlocated = Vec::new();

    let (directories, unreadable) = repository_directories(worktrees_root);
    entries.extend(unreadable.into_iter().map(unreadable_entry));

    for directory in directories {
        let (candidates, unreadable) = child_directories(&directory);
        entries.extend(unreadable.into_iter().map(unreadable_entry));
        let directory_name = file_name(&directory);
        // Only a directory with nothing left in it can hide a repository: any
        // candidate gets its own row with its own reason.
        let emptied_by_hand = candidates.is_empty();

        let mut removed_any = false;
        for worktree in candidates {
            let slug = file_name(&worktree);
            let assessment = assess(&worktree, &slug, &sweep, &mut known);
            let (outcome, removed) = sweep_outcome(&worktree, &slug, &assessment, store, apply);
            if removed {
                removed_any = true;
            }
            entries.push(Entry {
                worktree,
                slug,
                owner: assessment.owner,
                ignored: assessment.ignored,
                outcome,
            });
        }

        if apply && removed_any {
            remove_if_emptied(&directory, current_dir.as_deref());
        }
        if emptied_by_hand {
            unlocated.push(directory_name);
        }
    }
    // A directory whose repository nobody could name: every checkout in it is
    // gone and brgr did not record where it came from (tasks admitted before
    // checkouts were recorded). Its branches may remain, and saying so beats a
    // report of zero.
    unlocated.retain(|name| {
        !known
            .inventories
            .iter()
            .any(|inventory| file_name(&inventory.primary) == *name)
    });
    for name in unlocated {
        let directory = worktrees_root.join(&name);
        if directory.is_dir() {
            entries.push(Entry {
                worktree: directory,
                slug: name,
                owner: None,
                ignored: Vec::new(),
                outcome: Outcome::Kept(
                    "no checkout of this repository survives and brgr did not record its path, \
                     so its brgr/task-* branches cannot be located; remove them from the \
                     repository with `git branch -d`"
                        .to_owned(),
                ),
            });
        }
    }

    // Once per repository brgr has tasks in, not once per directory: two
    // directories can resolve to one repository, and a repository can have no
    // directory left at all — which is exactly the case this exists for.
    for inventory in &known.inventories {
        orphans.extend(reconcile_orphans(inventory, store, apply));
    }

    entries.sort_by(|left, right| left.worktree.cmp(&right.worktree));
    orphans.sort_by(|left, right| left.branch.cmp(&right.branch));
    Prune { entries, orphans }
}

/// Drops a repository directory this run emptied.
///
/// Never a dot-directory: `<worktrees>/.locks` holds the cross-process admission
/// lock and is empty at rest. Never the directory the process is sitting in or an
/// ancestor of it either, or removing the last child unlinks the caller's own
/// working directory.
fn remove_if_emptied(repository: &Path, current_dir: Option<&Path>) {
    if file_name(repository).starts_with('.') {
        return;
    }
    if current_dir.is_some_and(|cwd| is_self_or_ancestor(repository, cwd)) {
        return;
    }
    if fs::read_dir(repository).is_ok_and(|mut entries| entries.next().is_none()) {
        let _ = fs::remove_dir(repository);
    }
}

/// Reclaims `brgr/task-*` branches whose worktree no longer exists.
///
/// A branch gets the checks a worktree gets: it must name a task revision of
/// this repository with a recorded decision, and its owner is reported. git
/// still holds the last line — `branch -d` refuses unmerged commits — but report
/// mode asks the same merge question first, so `removable` means removable.
fn reconcile_orphans(inventory: &Inventory, store: &Store, apply: bool) -> Vec<Orphan> {
    let Ok(listing) = git(
        &inventory.primary,
        &[
            "branch",
            "--list",
            "brgr/task-*",
            "--format=%(refname:short)",
        ],
    ) else {
        return Vec::new();
    };
    let mut orphans = Vec::new();
    for branch in listing
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
    {
        let Some((prefix, revision)) = branch.strip_prefix("brgr/task-").and_then(parse_slug)
        else {
            continue;
        };
        let mut owner = None;
        let judged = orphan_objection(inventory, store, (prefix, revision), branch, &mut owner);
        let outcome = match judged {
            // Still checked out: the per-worktree pass owns it.
            Err(Live) => continue,
            Ok(Some(reason)) => Outcome::Kept(reason),
            Ok(None) if apply => reclaim(inventory, store, (prefix, revision), branch),
            Ok(None) => Outcome::Removable,
        };
        orphans.push(Orphan {
            branch: branch.to_owned(),
            owner,
            outcome,
        });
    }
    orphans
}

/// The branch's worktree still exists, so it is not an orphan.
struct Live;

/// The task revision of *this* repository a branch belongs to.
///
/// A recorded checkout decides it. A task admitted before checkouts were
/// recorded belongs here when git still registers its worktree path, which it
/// does after a hand deletion until the registration is removed.
fn owning_task(
    inventory: &Inventory,
    store: &Store,
    (prefix, revision): (&str, u32),
) -> Result<Option<TaskSpec>, String> {
    let matches = store
        .task_revisions_with_prefix(prefix, revision)
        .map_err(|error| format!("task lookup failed: {error}"))?;
    let mut ours = Vec::new();
    for task in matches {
        let belongs = match store.task_checkout(task.task_id, revision) {
            Ok(Some(recorded)) => resolve(Path::new(&recorded)) == inventory.primary,
            Ok(None) => inventory.is_registered(&resolve(Path::new(&task.workspace))),
            Err(error) => return Err(format!("checkout lookup failed: {error}")),
        };
        if belongs {
            ours.push(task);
        }
    }
    match ours.len() {
        0 | 1 => Ok(ours.pop()),
        _ => Err("task id prefix is ambiguous; refusing to guess".to_owned()),
    }
}

/// Why a revision's checkout must stay, or `None` once it is settled.
///
/// A revision is settled when the owner decided its candidate, or acknowledged
/// its failed, cancelled, or lost result with nothing left to run. The store
/// guards make that stronger than it looks: `record_decision_in_transaction`
/// accepts only a candidate, `claim_attempt` refuses a new attempt after a
/// candidate or a lost result, and after a failure only with a retry grant,
/// which counts as unsettled. What the store cannot see is a worker still
/// running under a dead supervisor, which a lost result warns about; with a
/// worktree present, `worker_alive` rules that out.
fn unsettled(
    store: &Store,
    task: TaskId,
    revision: u32,
    worker_alive: Option<&dyn Fn(TaskId) -> bool>,
) -> Option<String> {
    let settlement = match store.revision_settlement(task, revision) {
        Ok(settlement) => settlement,
        Err(error) => return Some(format!("settlement lookup failed: {error}")),
    };
    match settlement {
        Settlement::Acknowledged(_) if worker_alive.is_some_and(|alive| alive(task)) => {
            Some("a worker of this task is still running".to_owned())
        }
        Settlement::Decided | Settlement::Acknowledged(_) => None,
        Settlement::Open(OpenReason::NoResult) => {
            Some("no result recorded for this revision yet".to_owned())
        }
        Settlement::Open(OpenReason::Undecided) => {
            Some("no owner decision recorded for this revision".to_owned())
        }
        Settlement::Open(OpenReason::Unacknowledged(outcome)) => Some(format!(
            "its {} result is not acknowledged; run `brgr result {task} --ack`",
            outcome_name(outcome)
        )),
        Settlement::Open(OpenReason::AttemptActive) => {
            Some("an attempt of this revision is still running".to_owned())
        }
        Settlement::Open(OpenReason::RetryGranted) => {
            Some("a retry was granted for this revision and may still start".to_owned())
        }
    }
}

fn outcome_name(outcome: TerminalOutcome) -> &'static str {
    match outcome {
        TerminalOutcome::Candidate => "candidate",
        TerminalOutcome::Failed => "failed",
        TerminalOutcome::Cancelled => "cancelled",
        TerminalOutcome::Lost => "lost",
    }
}

/// Returns why an orphan branch must be kept, `Ok(None)` when it may go, or
/// `Err(Live)` when its worktree still exists.
fn orphan_objection(
    inventory: &Inventory,
    store: &Store,
    (prefix, revision): (&str, u32),
    branch: &str,
    owner: &mut Option<String>,
) -> Result<Option<String>, Live> {
    let task = match owning_task(inventory, store, (prefix, revision)) {
        Ok(Some(task)) => task,
        Ok(None) => {
            return Ok(Some(
                "no task revision of this repository matches this branch".to_owned(),
            ));
        }
        Err(reason) => return Ok(Some(reason)),
    };
    let worktree = resolve(Path::new(&task.workspace));
    if worktree.is_dir() {
        return Err(Live);
    }
    *owner = Some(task.owner_id.as_str().to_owned());
    // Its worktree is gone, so no worker can still be running in it.
    if let Some(reason) = unsettled(store, task.task_id, revision, None) {
        return Ok(Some(reason));
    }
    if inventory.is_locked(&worktree) {
        return Ok(Some(
            "its stale worktree registration is locked; unlock it first with `git worktree unlock`"
                .to_owned(),
        ));
    }
    match preservation(&inventory.primary, branch, store, &task, true) {
        Ok(Some(_)) => Ok(None),
        Ok(None) => Ok(Some(UNPRESERVED.to_owned())),
        Err(reason) => Ok(Some(format!("branch could not be checked: {reason}"))),
    }
}

/// Drops the task's own stale registration, then the branch. Never `git
/// worktree prune`: that is repository-wide and would also drop the
/// registration of a user's worktree on an unmounted volume.
fn reclaim(
    inventory: &Inventory,
    store: &Store,
    (prefix, revision): (&str, u32),
    branch: &str,
) -> Outcome {
    let Ok(Some(task)) = owning_task(inventory, store, (prefix, revision)) else {
        return Outcome::Kept("task could not be re-read before removal".to_owned());
    };
    let worktree = resolve(Path::new(&task.workspace));
    if inventory.is_registered(&worktree)
        && let Err(error) = git(
            &inventory.primary,
            &["worktree", "remove", &lossy(&worktree)],
        )
    {
        return Outcome::Kept(format!(
            "stale registration {} could not be removed: {error}",
            worktree.display()
        ));
    }
    match delete_task_branch(&inventory.primary, branch, store, &task, true) {
        Ok(reason) => Outcome::Removed(reason),
        Err(reason) => Outcome::Kept(reason),
    }
}

/// What the checks found for one candidate. `blocked` is `Some` when the
/// worktree is kept, and the same checks run in report and apply mode so the two
/// runs agree on what is removable.
struct Assessment {
    blocked: Option<String>,
    owner: Option<String>,
    ignored: Vec<String>,
    /// The worktree holds changes that git's own remove refuses, all of which
    /// brgr has shown are disposable: a harness's cache, or exactly the patch
    /// the store sealed. Only then is `git worktree remove --force` used.
    force: bool,
    /// The primary checkout of the repository this worktree's task belongs to.
    primary: Option<PathBuf>,
    /// The settled task revision this worktree was created for.
    task: Option<TaskSpec>,
}

/// What stays the same for every worktree in one sweep.
struct Sweep<'a> {
    store: &'a Store,
    current_dir: Option<&'a Path>,
    include_ignored: bool,
    /// Whether a worker of this task may still be running where the store
    /// cannot see it: a live supervisor, or a harness process whose supervisor
    /// died without reaping it.
    worker_alive: &'a dyn Fn(TaskId) -> bool,
}

fn assess(worktree: &Path, slug: &str, sweep: &Sweep<'_>, known: &mut Repositories) -> Assessment {
    let mut found = Assessment {
        blocked: None,
        owner: None,
        ignored: Vec::new(),
        force: false,
        primary: None,
        task: None,
    };
    found.blocked = objection(worktree, slug, sweep, known, &mut found);
    found
}

/// Returns the first reason this worktree must be kept, or `None` to remove it.
fn objection(
    worktree: &Path,
    slug: &str,
    sweep: &Sweep<'_>,
    known: &mut Repositories,
    found: &mut Assessment,
) -> Option<String> {
    let Sweep {
        store,
        current_dir,
        include_ignored,
        worker_alive,
    } = *sweep;
    // `?` must never be used for these: in a function whose `None` means "no
    // objection", a short-circuit would mark an unrecognized directory removable.
    let Some((prefix, revision)) = parse_slug(slug) else {
        return Some("directory name is not a brgr task slug; refusing to touch it".to_owned());
    };

    // `Path::is_dir` follows symlinks, and `git worktree remove` resolves its
    // argument, so a symlink placed here would make git destroy a checkout
    // entirely outside the worktrees root.
    match fs::symlink_metadata(worktree) {
        Ok(metadata) if metadata.file_type().is_symlink() => {
            return Some("path is a symlink; refusing to follow it".to_owned());
        }
        Ok(metadata) if !metadata.is_dir() => {
            return Some("path is not a directory".to_owned());
        }
        Ok(_) => {}
        Err(error) => return Some(format!("path is unreadable: {error}")),
    }

    let Some(resolved) = canonical(worktree) else {
        return Some("path could not be resolved".to_owned());
    };
    if let Some(cwd) = current_dir
        && is_self_or_ancestor(&resolved, cwd)
    {
        return Some(
            "this is the current working directory; refusing to remove it from under the \
             running process"
                .to_owned(),
        );
    }

    let matches = match store.task_revisions_with_prefix(prefix, revision) {
        Ok(matches) => matches,
        Err(error) => return Some(format!("task lookup failed: {error}")),
    };
    // The store records the exact worktree it created for each revision. A
    // directory under the right name that is not that path — a copy, a clone,
    // one someone made — was not put here by brgr. This also settles a prefix
    // shared by two tasks, which the name alone cannot.
    let Some(task) = matches
        .into_iter()
        .find(|task| resolve(Path::new(&task.workspace)) == resolved)
    else {
        return Some("no task revision was admitted in this directory".to_owned());
    };
    found.owner = Some(task.owner_id.as_str().to_owned());
    found.task = Some(task.clone());

    // Locate the repository before anything can return early: a worktree kept
    // for any reason still tells the sweep which repository its siblings'
    // orphaned branches live in. Ask the repository this task came from, never
    // whatever directory sits beside it.
    let recorded = match store.task_checkout(task.task_id, revision) {
        Ok(recorded) => recorded,
        Err(error) => return Some(format!("checkout lookup failed: {error}")),
    };
    let Some(index) = known.locate(recorded.as_deref(), worktree, &resolved) else {
        return Some("worktree is not a usable git checkout".to_owned());
    };
    let primary = known.inventories[index].primary.clone();
    if let Some(recorded) = recorded
        && resolve(Path::new(&recorded)) != primary
    {
        return Some(format!(
            "brgr recorded this worktree under {recorded}, but git places it in {}",
            primary.display()
        ));
    }

    if let Some(reason) = unsettled(store, task.task_id, revision, Some(worker_alive)) {
        return Some(reason);
    }

    let inventory = &known.inventories[index];
    if !inventory.is_registered(&resolved) {
        return Some("path is not a registered worktree of its repository".to_owned());
    }
    if inventory.is_locked(&resolved) {
        return Some("worktree is locked; unlock it first with `git worktree unlock`".to_owned());
    }

    if let Some(reason) = changes_objection(worktree, store, &task, include_ignored, found) {
        return Some(reason);
    }
    found.primary = Some(inventory.primary.clone());
    None
}

/// The reason a worktree's own contents keep it, or `None`. Sets
/// `found.force` and `found.ignored` for the removal.
fn changes_objection(
    worktree: &Path,
    store: &Store,
    task: &TaskSpec,
    include_ignored: bool,
    found: &mut Assessment,
) -> Option<String> {
    // One status call answers both questions: tracked or untracked changes, and
    // the ignored set that git's own clean check does not look at. `matching`
    // lists each ignored path at the level its pattern matched: the default
    // folds a directory whose files are all ignored into one entry, so a
    // `build/prod.env` caught by `*.env` would read as `build/`.
    // `--untracked-files=all` stops at a nested repository's own directory
    // instead of folding it into the untracked directory above it.
    let status = match git(
        worktree,
        &[
            "status",
            "--porcelain",
            "--ignored=matching",
            "--untracked-files=all",
        ],
    ) {
        Ok(status) => status,
        Err(reason) => return Some(format!("worktree status is unreadable: {reason}")),
    };
    let changed: Vec<&str> = status
        .lines()
        .filter(|line| !line.is_empty() && !line.starts_with("!! "))
        .collect();
    if !changed.is_empty() {
        // A patch records a repository nested in the worktree as one commit
        // id, and leaves brgr's own report directory out: neither survives in
        // the store, so neither may be forced away.
        if let Some(line) = changed.iter().find(|line| unsealable(worktree, line)) {
            return Some(format!(
                "worktree holds {}, which no sealed patch can hold",
                line.get(3..).unwrap_or(line)
            ));
        }
        // Only a harness's own cache, or exactly what the store sealed: either
        // way nothing in the worktree exists only there.
        if changed.iter().all(|line| harness_cache(line)) || patch_is_sealed(store, task) {
            found.force = true;
        } else {
            return Some("worktree holds modified or untracked files".to_owned());
        }
    }
    found.ignored = status
        .lines()
        .filter_map(|line| line.strip_prefix("!! "))
        .map(str::to_owned)
        .collect();
    let kept_ignored: Vec<&String> = found
        .ignored
        .iter()
        .filter(|path| !regenerable(path))
        .collect();
    if !kept_ignored.is_empty() && !include_ignored {
        return Some(format!(
            "worktree holds {} ignored path(s) git's clean check cannot see, such as {}; \
             pass --include-ignored to remove them",
            kept_ignored.len(),
            kept_ignored.first().map_or("", |path| path.as_str())
        ));
    }
    None
}

/// A changed entry a patch cannot carry: a directory holding its own `.git`,
/// recorded only as a commit id, or brgr's `.brgr/` report directory, which
/// is archived out of the worktree once the result is handled and left out of
/// the patch.
fn unsealable(worktree: &Path, status_line: &str) -> bool {
    let Some(path) = status_line.get(3..) else {
        return false;
    };
    let path = path.trim_end_matches('/');
    path == ".brgr" || path.starts_with(".brgr/") || worktree.join(path).join(".git").exists()
}

/// Directory names that never keep a worktree, whether git reports them as
/// ignored (`!!`) or untracked (`??`). Package-manager and compiler caches,
/// plus worker tool-state directories. A file is never disposable, even when
/// it shares a name with one of these. Generic names such as `dist`, `build`
/// or `out` are not here: people keep their own files under those.
const DISPOSABLE: [&str; 13] = [
    "node_modules",
    "target",
    ".next",
    ".turbo",
    "__pycache__",
    ".pytest_cache",
    ".mypy_cache",
    ".venv",
    ".gradle",
    ".gjc",
    ".commandcode",
    ".agent-progress",
    ".build",
];

/// The worker tool-state directories. Unlike the package managers' and
/// compilers' directories above, these are disposable even when git lists them
/// as untracked, because a worker harness writes them and nothing else does.
const TOOL_STATE: [&str; 4] = [".gjc", ".commandcode", ".agent-progress", ".build"];

/// An untracked directory a worker tool owns, or a file git listed inside one.
/// `--untracked-files=all` reports files, not the enclosing untracked
/// directory, so a path under a [`TOOL_STATE`] directory counts as well, at any
/// depth. A file that only shares the name does not. Only an untracked entry
/// counts: a change to a tracked file under one of these names is the
/// repository's own content. The package managers' and compilers' directories
/// are deliberately not here: an untracked file inside a directory that merely shares
/// such a name is the worker's own work, and those names are disposable only when git ignores the
/// directory. `.claude/` and `.cursor/` are not here either: they also hold
/// project configuration a task may be asked to write (`.claude/commands/`,
/// `.cursor/rules/`), and git reports either as the bare directory.
fn harness_cache(status_line: &str) -> bool {
    let Some(path) = status_line.strip_prefix("?? ") else {
        return false;
    };
    // A trailing slash is a directory entry; otherwise the last component is a
    // file and only its parents can make it a cache.
    let directories = path
        .strip_suffix('/')
        .unwrap_or_else(|| path.rsplit_once('/').map_or("", |(parent, _)| parent));
    directories
        .split('/')
        .any(|component| TOOL_STATE.contains(&component))
}

/// An ignored directory a tool owns: an entry git reported as a directory
/// whose own name is in [`DISPOSABLE`]. A file is never regenerable, wherever
/// it sits, including a nested `.env` git reported on its own.
///
/// When the directory itself matches an ignore pattern, git reports only the
/// directory and never what is inside, so a file put there by hand would go
/// with it. Generic names such as `dist`, `build` or `out` are therefore not
/// in [`DISPOSABLE`]: people keep their own files under those.
fn regenerable(path: &str) -> bool {
    path.strip_suffix('/')
        .map(|directory| directory.rsplit('/').next().unwrap_or(directory))
        .is_some_and(|name| DISPOSABLE.contains(&name))
}

/// Whether the worktree's changes are exactly what the store sealed with the
/// revision's result, so removing the checkout loses nothing the store lacks:
/// the patch byte for byte, and each `--evidence-file`, which the patch leaves
/// out, with the digest of an artifact sealed with it.
fn patch_is_sealed(store: &Store, task: &TaskSpec) -> bool {
    if !task.evidence.capture_diff {
        return false;
    }
    let Ok(Some(result)) = store.revision_result(task.task_id, task.revision) else {
        return false;
    };
    let Some(sealed) = result
        .artifacts
        .iter()
        .find(|artifact| artifact.media_type == "text/x-diff")
    else {
        return false;
    };
    let limit = artifact_limit(task);
    let Ok(sealed) = store.read_artifact(sealed, limit) else {
        return false;
    };
    if !brgr_core::task_patch(task, limit, std::time::Duration::from_secs(30))
        .is_ok_and(|now| now == sealed)
    {
        return false;
    }
    let workspace = Path::new(&task.workspace);
    task.evidence.files.iter().all(|relative| {
        let path = workspace.join(relative);
        // A file no longer there holds nothing to lose.
        if fs::symlink_metadata(&path).is_err() {
            return true;
        }
        read_bounded(&path, limit).is_some_and(|bytes| {
            let digest = crate::pane_adapter::native_digest(&bytes);
            result
                .artifacts
                .iter()
                .any(|artifact| artifact.digest == digest)
        })
    })
}

fn artifact_limit(task: &TaskSpec) -> u64 {
    task.artifact_contract.max_bytes.min(8 * 1024 * 1024)
}

/// A file's bytes when it holds at most `limit` of them. Sealing refuses a
/// larger file, so one cannot match a sealed artifact and is never read whole.
fn read_bounded(path: &Path, limit: u64) -> Option<Vec<u8>> {
    let mut bytes = Vec::new();
    fs::File::open(path)
        .ok()?
        .take(limit.saturating_add(1))
        .read_to_end(&mut bytes)
        .ok()?;
    (u64::try_from(bytes.len()).ok()? <= limit).then_some(bytes)
}

/// Lists the repository directories under the worktrees root, and the ones that
/// could not be read.
///
/// An unreadable entry is returned rather than propagated: every other failure in
/// this module becomes one reported row, and enumeration was the last place where
/// a single bad directory made the whole sweep report nothing — including the
/// worktrees it could have reclaimed elsewhere.
fn repository_directories(worktrees_root: &Path) -> (Vec<PathBuf>, Vec<PathBuf>) {
    if !worktrees_root.is_dir() {
        return (Vec::new(), Vec::new());
    }
    let (children, mut unreadable) = child_directories(worktrees_root);
    let mut repositories = Vec::new();
    for child in children {
        if fs::read_dir(&child).is_ok() {
            repositories.push(child);
        } else {
            unreadable.push(child);
        }
    }
    (repositories, unreadable)
}

/// Sorted children of `directory`, skipping dot-entries. The second half is the
/// directory itself when it cannot be read at all.
fn child_directories(directory: &Path) -> (Vec<PathBuf>, Vec<PathBuf>) {
    let Ok(read) = fs::read_dir(directory) else {
        return (Vec::new(), vec![directory.to_path_buf()]);
    };
    let mut found = Vec::new();
    let mut unreadable = Vec::new();
    for entry in read {
        match entry {
            Ok(entry) if !file_name(&entry.path()).starts_with('.') => found.push(entry.path()),
            Ok(_) => {}
            Err(_) => unreadable.push(directory.to_path_buf()),
        }
    }
    found.sort();
    unreadable.dedup();
    (found, unreadable)
}

fn unreadable_entry(path: PathBuf) -> Entry {
    let slug = file_name(&path);
    Entry {
        worktree: path,
        slug,
        owner: None,
        ignored: Vec::new(),
        outcome: Outcome::Kept("directory could not be read".to_owned()),
    }
}

/// Splits `abcd1234` or `abcd1234-r3` into its task-id prefix and revision.
///
/// Only the exact shape [`crate::workspace`] produces is accepted: anything
/// else is a directory somebody put here, not a task slug.
fn parse_slug(slug: &str) -> Option<(&str, u32)> {
    const PREFIX_LENGTH: usize = 8;
    let (prefix, revision) = match slug.split_once("-r") {
        // The suffix has to be the one `task_slug` would have written. Rust's
        // integer parser accepts a leading `+` and leading zeros, so `-r+5`,
        // `-r007`, and `-r01` all resolved to real revisions; `-r1` did too,
        // although `task_slug` drops the suffix entirely at revision one. Each
        // named a directory brgr never created, and each would then have its
        // checkout removed and a branch rebuilt from the raw slug that does not
        // exist. Re-rendering is the check: a suffix that does not round-trip is
        // not ours. Found by `a_parsed_slug_is_always_one_brgr_could_have_written`.
        Some((prefix, revision)) => {
            let parsed = revision.parse::<u32>().ok()?;
            if parsed < 2 || revision != parsed.to_string() {
                return None;
            }
            (prefix, parsed)
        }
        None => (slug, 1),
    };
    // `task_slug` renders a UUID, which is lowercase. Accepting `A-F` would let a
    // directory brgr never created resolve to a real task on a case-sensitive
    // filesystem, and the branch name rebuilt from the raw slug would not exist.
    if prefix.len() != PREFIX_LENGTH
        || !prefix
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    {
        return None;
    }
    Some((prefix, revision))
}

/// Report or apply the assessment of one worktree. The second value is whether
/// the checkout was actually removed, so the repository directory can go too.
fn sweep_outcome(
    worktree: &Path,
    slug: &str,
    assessment: &Assessment,
    store: &Store,
    apply: bool,
) -> (Outcome, bool) {
    match (
        assessment.blocked.as_ref(),
        assessment.primary.as_ref(),
        assessment.task.as_ref(),
    ) {
        (Some(reason), _, _) => (Outcome::Kept(reason.clone()), false),
        (None, Some(primary), Some(task)) if apply => {
            match remove(
                worktree,
                slug,
                primary,
                assessment.force,
                (store, task, true),
            ) {
                Ok(RemovedWhat::Both { reason }) => (Outcome::Removed(reason), true),
                Ok(RemovedWhat::CheckoutOnly { reason }) => {
                    (Outcome::RemovedKeepingBranch(reason), true)
                }
                Err(reason) => (Outcome::Kept(reason), false),
            }
        }
        (None, Some(_), Some(_)) => (Outcome::Removable, false),
        (None, _, _) => (
            Outcome::Kept("no repository was resolved for it".to_owned()),
            false,
        ),
    }
}

/// What `remove` did after git accepted the worktree removal.
enum RemovedWhat {
    Both { reason: Option<String> },
    CheckoutOnly { reason: String },
}

/// Removes one worktree and then its branch.
///
/// `Both` removed both. `CheckoutOnly` removed the checkout while git kept the
/// branch, which preserves committed work.
fn remove(
    worktree: &Path,
    slug: &str,
    primary: &Path,
    force: bool,
    (store, task, allow_sealed): (&Store, &TaskSpec, bool),
) -> Result<RemovedWhat, String> {
    let path = lossy(worktree);
    let mut arguments = vec!["worktree", "remove"];
    if force {
        arguments.push("--force");
    }
    arguments.push(&path);
    git(primary, &arguments)
        .map_err(|error| format!("git declined to remove the worktree: {error}"))?;
    let branch = format!("brgr/task-{slug}");
    match delete_task_branch(primary, &branch, store, task, allow_sealed) {
        Ok(reason) => Ok(RemovedWhat::Both { reason }),
        Err(reason) => Ok(RemovedWhat::CheckoutOnly {
            reason: format!("checkout removed; branch {branch} kept: {reason}"),
        }),
    }
}

/// Every repository brgr has worktrees in, each read from git once.
///
/// Seeded from the checkouts the store recorded at admission, so a directory
/// dropped under the worktrees root by hand is never asked which repository it
/// belongs to. A task admitted before checkouts were recorded is located from
/// its own worktree, once the store has confirmed brgr created that path.
struct Repositories {
    inventories: Vec<Inventory>,
}

impl Repositories {
    fn load(store: &Store) -> Self {
        let mut known = Self {
            inventories: Vec::new(),
        };
        for primary in store.task_checkouts().unwrap_or_default() {
            if let Some(inventory) = Inventory::load(Path::new(&primary)) {
                known.adopt(inventory);
            }
        }
        known
    }

    fn adopt(&mut self, inventory: Inventory) -> usize {
        if let Some(index) = self
            .inventories
            .iter()
            .position(|known| known.primary == inventory.primary)
        {
            return index;
        }
        self.inventories.push(inventory);
        self.inventories.len() - 1
    }

    /// The repository holding a store-verified worktree: its recorded checkout,
    /// else one already read that registers it, else the worktree's own answer.
    fn locate(
        &mut self,
        recorded: Option<&str>,
        worktree: &Path,
        resolved: &Path,
    ) -> Option<usize> {
        if let Some(recorded) = recorded {
            let primary = resolve(Path::new(recorded));
            if let Some(index) = self
                .inventories
                .iter()
                .position(|known| known.primary == primary)
            {
                return Some(index);
            }
        }
        if let Some(index) = self
            .inventories
            .iter()
            .position(|known| known.is_registered(resolved))
        {
            return Some(index);
        }
        Inventory::load(worktree).map(|inventory| self.adopt(inventory))
    }
}

/// One repository's worktree registrations.
struct Inventory {
    primary: PathBuf,
    registered: Vec<PathBuf>,
    locked: Vec<PathBuf>,
}

impl Inventory {
    /// Reads the repository that `checkout` belongs to.
    fn load(checkout: &Path) -> Option<Self> {
        let listing = git(checkout, &["worktree", "list", "--porcelain"]).ok()?;
        let primary = listing
            .lines()
            .find_map(|line| line.strip_prefix("worktree "))
            .map(|path| resolve(Path::new(path)))?;
        Some(Self::parse(primary, &listing))
    }

    fn parse(primary: PathBuf, listing: &str) -> Self {
        let mut registered = Vec::new();
        let mut locked = Vec::new();
        let mut current: Option<PathBuf> = None;
        for line in listing.lines() {
            if let Some(path) = line.strip_prefix("worktree ") {
                let path = resolve(Path::new(path));
                registered.push(path.clone());
                current = Some(path);
            } else if (line == "locked" || line.starts_with("locked "))
                && let Some(path) = current.clone()
            {
                locked.push(path);
            }
        }
        Self {
            primary,
            registered,
            locked,
        }
    }

    fn is_registered(&self, resolved: &Path) -> bool {
        self.registered.iter().any(|path| path == resolved)
    }

    /// `git worktree remove` refuses a locked worktree, so report mode has to see
    /// the lock too or it promises a removal that apply mode then declines.
    fn is_locked(&self, resolved: &Path) -> bool {
        self.locked.iter().any(|path| path == resolved)
    }
}

const UNPRESERVED: &str = "branch has commits not merged into the repository's HEAD and \
     found on no other branch or remote; deleting it would lose them";

/// Where a task branch's commits survive: another ref, or a sealed result.
enum Holder {
    Elsewhere,
    Sealed(String),
}

/// Whether this branch may go, and why. `None` means some commit lives only
/// here. Errors from git's own lookups keep the branch as "could not be
/// checked"; errors in the sealed-diff comparison mean not preserved.
fn preservation(
    primary: &Path,
    branch: &str,
    store: &Store,
    task: &TaskSpec,
    allow_sealed: bool,
) -> Result<Option<(String, Holder)>, String> {
    if let Some((tip, _)) = preserved_elsewhere(primary, branch)? {
        return Ok(Some((tip, Holder::Elsewhere)));
    }
    // The task branch is how an owner pushes the work. Only an explicit
    // `brgr prune` may drop it on the strength of the sealed copy; the
    // reclaim a decision runs must not.
    if !allow_sealed {
        return Ok(None);
    }
    let tip = branch_tip(primary, branch)?;
    Ok(sealed_result_holds_branch(primary, &tip, store, task)
        .map(|result_id| (tip, Holder::Sealed(result_id))))
}

fn branch_tip(primary: &Path, branch: &str) -> Result<String, String> {
    git(
        primary,
        &[
            "rev-parse",
            "--verify",
            &format!("refs/heads/{branch}^{{commit}}"),
        ],
    )
    .map(|tip| tip.trim().to_owned())
}

/// Where every commit on a task branch also lives, or `None` when some commit
/// is on this branch alone. Returns the branch tip it checked, and the holder:
/// `HEAD`, or the first other branch or remote-tracking branch containing it.
/// Other task branches do not count, since a sweep may delete them too.
fn preserved_elsewhere(primary: &Path, branch: &str) -> Result<Option<(String, String)>, String> {
    let tip = branch_tip(primary, branch)?;
    if git(primary, &["merge-base", "--is-ancestor", &tip, "HEAD"]).is_ok() {
        return Ok(Some((tip, "HEAD".to_owned())));
    }
    let holders = git(
        primary,
        &[
            "for-each-ref",
            "--contains",
            &tip,
            "--format=%(refname)",
            "refs/heads",
            "refs/remotes",
        ],
    )?;
    let holder = holders
        .lines()
        .map(str::trim)
        .find(|name| {
            !name.is_empty()
                && !name.starts_with("refs/heads/brgr/task-")
                && !name.ends_with("/HEAD")
        })
        .map(str::to_owned);
    Ok(holder.map(|holder| (tip, holder)))
}

/// The sealed `text/x-diff` already holds every changed line of
/// `git diff --binary MERGE_BASE TIP`. Any error, a missing merge-base, a
/// binary patch, or a line the sealed diff does not hold yields `None`.
fn sealed_result_holds_branch(
    primary: &Path,
    tip: &str,
    store: &Store,
    task: &TaskSpec,
) -> Option<String> {
    if !task.evidence.capture_diff {
        return None;
    }
    let result = store.revision_result(task.task_id, task.revision).ok()??;
    let sealed = result
        .artifacts
        .iter()
        .find(|artifact| artifact.media_type == "text/x-diff")?;
    let limit = artifact_limit(task);
    let sealed = store.read_artifact(sealed, limit).ok()?;
    let merge_base = git(primary, &["merge-base", "HEAD", tip]).ok()?;
    let merge_base = merge_base.trim();
    if merge_base.is_empty() {
        return None;
    }
    let branch_diff = git_bounded(primary, &["diff", "--binary", merge_base, tip], limit).ok()?;
    let branch_counts = changed_line_counts(&branch_diff)?;
    let sealed_counts = changed_line_counts(&sealed)?;
    counts_are_subset(&branch_counts, &sealed_counts).then(|| result.result_id.to_string())
}

fn counts_are_subset(
    branch: &HashMap<(String, String), usize>,
    sealed: &HashMap<(String, String), usize>,
) -> bool {
    branch
        .iter()
        .all(|(key, count)| sealed.get(key).copied().unwrap_or(0) >= *count)
}

/// Multiset of `(path, changed line including its + or - sign)`, plus the
/// header lines that carry a change on their own (a mode change, a rename, a
/// created or deleted file), keyed by the file's new path: a commit that only
/// chmods a file has no changed line and must still count. Hunk headers, index
/// lines and context are ignored. Lines inside a hunk are content however they
/// begin, so a removed SQL comment (`--- old comment`) is a change, not a file
/// header. A binary patch cannot be proved, so this returns `None`.
fn changed_line_counts(diff: &[u8]) -> Option<HashMap<(String, String), usize>> {
    let text = std::str::from_utf8(diff).ok()?;
    let mut counts = HashMap::new();
    let mut paths: Option<(String, String)> = None;
    let mut in_hunk = false;
    for line in text.split('\n') {
        if binary_patch_line(line) {
            return None;
        }
        if let Some(rest) = line.strip_prefix("diff --git ") {
            in_hunk = false;
            paths = git_diff_paths(rest);
            paths.as_ref()?;
            continue;
        }
        if line.starts_with("@@ ") {
            in_hunk = true;
            continue;
        }
        let Some(sign) = line.chars().next() else {
            continue;
        };
        if in_hunk {
            if sign != '+' && sign != '-' {
                continue;
            }
            let (old, new) = paths.as_ref()?;
            let path = match sign {
                '+' if new != "/dev/null" => new,
                '-' if old != "/dev/null" => old,
                '+' => old,
                _ => new,
            };
            *counts.entry((path.clone(), line.to_owned())).or_default() += 1;
        } else if carries_a_change(line) {
            let (_, new) = paths.as_ref()?;
            *counts.entry((new.clone(), line.to_owned())).or_default() += 1;
        }
    }
    Some(counts)
}

/// A header line that is itself a change to the file.
fn carries_a_change(line: &str) -> bool {
    [
        "new file mode ",
        "deleted file mode ",
        "old mode ",
        "new mode ",
        "rename from ",
        "rename to ",
        "copy from ",
        "copy to ",
    ]
    .iter()
    .any(|prefix| line.starts_with(prefix))
}

fn binary_patch_line(line: &str) -> bool {
    if line == "GIT binary patch" || line.starts_with("Binary files ") {
        return true;
    }
    line.strip_prefix("literal ")
        .or_else(|| line.strip_prefix("delta "))
        .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|byte| byte.is_ascii_digit()))
}

fn git_diff_paths(rest: &str) -> Option<(String, String)> {
    let rest = rest.strip_prefix("a/")?;
    let (old, new) = rest.split_once(" b/")?;
    Some((old.to_owned(), new.to_owned()))
}

/// Deletes a task branch whose commits all survive elsewhere or in the sealed
/// result. `Ok(Some(reason))` is the sealed-result note for the prune report.
///
/// `git branch -D` is used for its refusal to delete a branch some worktree has
/// checked out; the force only skips its merge test, which
/// [`preservation`] replaces. Should the branch have moved between the
/// check and the deletion, it is recreated at the commit git reports it had.
fn delete_task_branch(
    primary: &Path,
    branch: &str,
    store: &Store,
    task: &TaskSpec,
    allow_sealed: bool,
) -> Result<Option<String>, String> {
    let Some((tip, holder)) = preservation(primary, branch, store, task, allow_sealed)? else {
        return Err(UNPRESERVED.to_owned());
    };
    restore_if_moved(primary, branch, &tip)?;
    Ok(match holder {
        Holder::Sealed(result_id) => Some(format!("changes are held by sealed result {result_id}")),
        Holder::Elsewhere => None,
    })
}

/// Deletes `branch` and recreates it when git reports it moved.
fn restore_if_moved(primary: &Path, branch: &str, tip: &str) -> Result<(), String> {
    let deleted = git(primary, &["branch", "-D", branch])
        .map_err(|error| format!("git refused to delete it: {error}"))?;
    // "Deleted branch NAME (was ABBREV)."
    let was = deleted
        .rsplit("(was ")
        .next()
        .and_then(|rest| rest.split(')').next())
        .unwrap_or_default()
        .trim();
    if was.is_empty() || !tip.starts_with(was) {
        let restored = if was.is_empty() { tip } else { was };
        git(primary, &["branch", branch, restored]).map_err(|error| {
            format!("branch moved during removal and could not be restored: {error}")
        })?;
        return Err("branch moved while it was being removed; restored and kept".to_owned());
    }
    Ok(())
}

fn git(directory: &Path, args: &[&str]) -> Result<String, String> {
    let bytes = git_bounded(directory, args, u64::MAX)?;
    Ok(String::from_utf8_lossy(&bytes).into_owned())
}

fn git_bounded(directory: &Path, args: &[&str], limit: u64) -> Result<Vec<u8>, String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(directory)
        .args(args)
        .output()
        .map_err(|error| error.to_string())?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(stderr.trim().replace('\n', "; "));
    }
    if u64::try_from(output.stdout.len()).unwrap_or(u64::MAX) > limit {
        return Err(format!("output exceeds {limit} bytes"));
    }
    Ok(output.stdout)
}

/// Reports whether `candidate` is `inside` itself or one of its ancestors, which
/// is what makes removing it pull the ground out from under `inside`.
fn is_self_or_ancestor(candidate: &Path, inside: &Path) -> bool {
    inside == candidate || inside.starts_with(candidate)
}

fn canonical(path: &Path) -> Option<PathBuf> {
    path.canonicalize().ok()
}

/// Canonical form of a path that may no longer exist. A stale registration's
/// directory is gone, but its parent usually is not, and comparing the raw text
/// against a canonical root misses it wherever a symlink sits in between —
/// `/tmp` on macOS, for one.
fn resolve(path: &Path) -> PathBuf {
    if let Some(found) = canonical(path) {
        return found;
    }
    match (path.parent().and_then(canonical), path.file_name()) {
        (Some(parent), Some(name)) => parent.join(name),
        _ => path.to_path_buf(),
    }
}

fn file_name(path: &Path) -> String {
    path.file_name()
        .and_then(|name| name.to_str())
        .unwrap_or_default()
        .to_owned()
}

fn lossy(path: &Path) -> String {
    path.to_string_lossy().into_owned()
}

/// Removes one decided revision's worktree when nothing in it would be lost,
/// with the same checks as `brgr prune --apply`, and `--include-ignored` only
/// when the owner gave it to the decision.
/// Returns what happened, for a note on stderr; `None` when there was nothing
/// to do. Never fails the decision that triggered it.
pub(crate) fn reclaim_task(paths: &Paths, task: TaskId, revision: u32) -> Option<String> {
    let store = Store::open(&paths.store).ok()?;
    let launch: crate::LaunchEnvelope =
        serde_json::from_slice(&fs::read(paths.launch(task, revision)).ok()?).ok()?;
    // A kept pane still runs its worker in the worktree; a headless run has
    // no pane, so `--keep-pane` says nothing about its worktree.
    if launch.keep_worktree || (launch.keep_pane && launch.pane_mode) {
        return None;
    }
    let worktree = resolve(Path::new(&launch.spec.workspace));
    // Only a checkout brgr made under its own root; a non-Git task ran in
    // place, in the user's own directory.
    let root = canonical(&paths.worktrees)?;
    let parent = worktree.parent()?;
    if parent.parent() != Some(root.as_path()) || !worktree.is_dir() {
        return None;
    }
    // A pane-mode worker still runs in the worktree until its pane closes;
    // the pane cleanup calls this again once it has.
    if paths.pane_receipt(task, revision).exists() && !pane_closed(paths, task, revision) {
        return None;
    }
    // Only a settled revision is assessed, so the once-only marker below can
    // never record an assessment made before the decision.
    if unsettled(&store, task, revision, None).is_some() {
        return None;
    }
    // A decision can land while a headless supervisor is still exiting after
    // sealing the result; nothing would retry once it has gone, so wait a moment.
    let exited_by = std::time::Instant::now() + WORKER_EXIT_WAIT;
    while crate::supervision::worker_may_be_running(paths, task) {
        if std::time::Instant::now() >= exited_by {
            return None;
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
    // The decision and the pane's session loop both reclaim once the pane
    // closes. One attempt at a time: the other process is already on it.
    let lock = fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(paths.runs.join(format!("{task}-r{revision}.reclaim.lock")))
        .ok()?;
    if lock.try_lock().is_err() {
        return None;
    }
    if !worktree.is_dir() {
        return None;
    }
    // Decided once: a worktree kept for its contents is `brgr prune`'s from
    // here on. Without this, every hook's pending-work pass reassessed it and
    // printed the same note again.
    let assessed = paths.runs.join(format!("{task}-r{revision}.reclaimed"));
    if assessed.exists() {
        return None;
    }
    // The process deciding, or closing the pane, may itself be sitting in the
    // worktree; the check that refuses to remove a working directory would
    // then keep it for good. Step out first: this process is finishing.
    if let Some(cwd) = std::env::current_dir()
        .ok()
        .and_then(|path| canonical(&path))
        && is_self_or_ancestor(&worktree, &cwd)
    {
        std::env::set_current_dir(&paths.home).ok()?;
    }
    let current_dir = std::env::current_dir()
        .ok()
        .and_then(|path| canonical(&path));
    let sweep = Sweep {
        store: &store,
        current_dir: current_dir.as_deref(),
        include_ignored: ignored_files_allowed(&store, paths, task, revision),
        worker_alive: &|task| crate::supervision::worker_may_be_running(paths, task),
    };
    let slug = file_name(&worktree);
    // Only this worktree's repository is needed, and `locate` reads it from
    // the worktree itself; loading every repository brgr has ever recorded
    // cost one `git worktree list` each on every decision.
    let mut known = Repositories {
        inventories: Vec::new(),
    };
    let assessment = assess(&worktree, &slug, &sweep, &mut known);
    let shown = worktree.display();
    // A worktree that is gone was removed by someone else: nothing was kept.
    // The reason is written for `brgr prune`; a decision takes none of its
    // flags, so its advice names the command that does.
    let kept = |reason: String| {
        worktree.exists().then(|| {
            let reason = reason.replace(
                "pass --include-ignored to remove them",
                "`brgr prune --apply --include-ignored` removes them",
            );
            format!("kept worktree {shown}: {reason}; `brgr prune` lists it")
        })
    };
    let _ = fs::write(&assessed, b"");
    match (assessment.blocked, assessment.primary, assessment.task) {
        (Some(reason), _, _) => kept(reason),
        (None, Some(primary), Some(task)) => {
            match remove(
                &worktree,
                &slug,
                &primary,
                assessment.force,
                (&store, &task, false),
            ) {
                Ok(RemovedWhat::Both { reason }) => {
                    remove_if_emptied(parent, current_dir.as_deref());
                    Some(match reason {
                        None => format!("removed worktree {shown}"),
                        Some(reason) => format!("removed worktree {shown}; {reason}"),
                    })
                }
                Ok(RemovedWhat::CheckoutOnly { reason }) => {
                    remove_if_emptied(parent, current_dir.as_deref());
                    Some(format!("removed worktree {shown}; {reason}"))
                }
                Err(reason) => kept(reason),
            }
        }
        (None, _, _) => None,
    }
}

/// How long a decision waits for a worker that is exiting after sealing its
/// result.
const WORKER_EXIT_WAIT: std::time::Duration = std::time::Duration::from_secs(5);

/// The marker that records the owner's `--include-ignored` on a decision. A
/// pane-mode worktree is reclaimed later, when its pane closes, by a process
/// that never saw the flag, so the choice is written down, with the id of the
/// decision it belongs to. It is written before the decision is recorded, so a
/// process that dies in between leaves a marker for a decision that never
/// existed; honouring it only for the decision actually recorded keeps that
/// from reaching a later one.
fn include_ignored_marker(paths: &Paths, task: TaskId, revision: u32) -> std::path::PathBuf {
    paths
        .runs
        .join(format!("{task}-r{revision}.include-ignored"))
}

/// Records that the decision `decision` also removes the worktree's ignored files.
pub(crate) fn allow_ignored(paths: &Paths, task: TaskId, revision: u32, decision: &str) {
    let _ = fs::write(
        include_ignored_marker(paths, task, revision),
        decision.as_bytes(),
    );
}

/// Whether the owner asked, in the decision that was actually recorded for this
/// revision, to remove ignored files too.
fn ignored_files_allowed(store: &Store, paths: &Paths, task: TaskId, revision: u32) -> bool {
    let Ok(marked) = fs::read_to_string(include_ignored_marker(paths, task, revision)) else {
        return false;
    };
    let Ok(result) = store.latest_result(task) else {
        return false;
    };
    if result.revision != revision {
        return false;
    }
    store
        .decision_for_result(result.result_id)
        .ok()
        .flatten()
        .is_some_and(|decision| decision.decision_id.to_string() == marked.trim())
}

/// Withdraws [`allow_ignored`] when the decision it was written for failed.
pub(crate) fn forget_ignored(paths: &Paths, task: TaskId, revision: u32) {
    let _ = fs::remove_file(include_ignored_marker(paths, task, revision));
}

/// Runs [`reclaim_task`] and notes the outcome on stderr.
pub(crate) fn reclaim_and_report(paths: &Paths, task: TaskId, revision: u32) {
    if let Some(note) = reclaim_task(paths, task, revision) {
        eprintln!("brgr · {note}");
    }
}

/// Whether the revision's pane receipt says its pane has been closed.
fn pane_closed(paths: &Paths, task: TaskId, revision: u32) -> bool {
    fs::read(paths.pane_receipt(task, revision))
        .ok()
        .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
        .is_some_and(|receipt| receipt["cleanup"] == "closed")
}

/// Runs `brgr prune` and prints its report.
/// Reports, and with `apply` removes, task worktrees whose revision is decided.
///
/// Nothing in the store is removed: a worktree is a rebuildable checkout, while
/// a sealed result and its decision are the durable record brgr exists to keep.
pub(crate) fn command(
    paths: &Paths,
    apply: bool,
    include_ignored: bool,
    json_output: bool,
) -> Result<()> {
    let store = Store::open(&paths.store)?;
    let swept = prune(
        &paths.worktrees,
        &store,
        &|task| crate::supervision::worker_may_be_running(paths, task),
        apply,
        include_ignored,
    );
    let worktrees: Vec<serde_json::Value> = swept
        .entries
        .iter()
        .map(|entry| {
            let mut row = json!({
                "worktree": entry.worktree,
                "task_slug": entry.slug,
                "status": entry.outcome.code(),
            });
            if let Some(reason) = entry.outcome.reason() {
                row["reason"] = json!(reason);
            }
            if let Some(owner) = &entry.owner {
                // Pruning is not owner-scoped, so the owner is reported rather
                // than silently acted on.
                row["owner_id"] = json!(owner);
            }
            if !entry.ignored.is_empty() {
                row["ignored_paths"] = json!(entry.ignored);
            }
            row
        })
        .collect();
    let orphans: Vec<serde_json::Value> = swept
        .orphans
        .iter()
        .map(|orphan| {
            let mut row = json!({"branch": orphan.branch, "status": orphan.outcome.code()});
            if let Some(reason) = orphan.outcome.reason() {
                row["reason"] = json!(reason);
            }
            if let Some(owner) = &orphan.owner {
                row["owner_id"] = json!(owner);
            }
            row
        })
        .collect();
    // One pass each rather than one per reported figure.
    let mut tally = BTreeMap::<&str, usize>::new();
    for entry in &swept.entries {
        *tally.entry(entry.outcome.code()).or_default() += 1;
    }
    let mut orphan_tally = BTreeMap::<&str, usize>::new();
    for orphan in &swept.orphans {
        *orphan_tally.entry(orphan.outcome.code()).or_default() += 1;
    }
    let count = |code: &str| tally.get(code).copied().unwrap_or_default();
    let orphan_count = |code: &str| orphan_tally.get(code).copied().unwrap_or_default();
    // A checkout whose branch git kept is still reclaimed: its directory is gone
    // and will never be enumerated again, so counting it as kept would report
    // that nothing happened.
    let removed = count("removed") + count("removed_branch_kept");
    print_value(
        &json!({
            "applied": apply,
            "removed": removed,
            "removed_keeping_branch": count("removed_branch_kept"),
            "removable": count("removable"),
            "kept": count("kept"),
            "worktrees": worktrees,
            "orphan_branches_removed": orphan_count("removed"),
            "orphan_branches_removable": orphan_count("removable"),
            "orphan_branches_kept": orphan_count("kept"),
            "orphan_branches": orphans,
            "note": "sealed results, decisions, artifacts, and task rows are never removed",
        }),
        json_output,
    );
    Ok(())
}

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

    #[test]
    fn a_file_over_the_limit_is_never_read_whole() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("evidence.bin");
        fs::write(&path, b"0123456789").unwrap();
        assert_eq!(read_bounded(&path, 10).unwrap(), b"0123456789");
        assert!(read_bounded(&path, 9).is_none());
        assert!(read_bounded(&temp.path().join("absent"), 10).is_none());
    }

    #[test]
    fn only_an_untracked_harness_directory_is_a_cache() {
        assert!(harness_cache("?? .gjc/"));
        assert!(harness_cache("?? .commandcode/"));
        assert!(harness_cache("?? .agent-progress/"));
        assert!(harness_cache("?? .build/"));
        assert!(harness_cache("?? .gjc/session.json"));
        assert!(!harness_cache("?? .claude/"));
        assert!(!harness_cache("?? .cursor/"));
        assert!(!harness_cache(" M .gjc/config.json"));
        assert!(!harness_cache("?? src/main.rs"));
        assert!(!harness_cache("?? .gjcx/"));
        assert!(!harness_cache("?? .build"));
        assert!(!harness_cache("?? .build-notes.txt"));
        assert!(!harness_cache("?? .buildx/"));
        assert!(!harness_cache("?? dist/"));
    }

    #[test]
    fn only_dependency_and_build_directories_are_regenerable() {
        assert!(regenerable("node_modules/"));
        assert!(regenerable("packages/web/.next/"));
        assert!(regenerable("target/"));
        assert!(regenerable(".gjc/"));
        assert!(regenerable(".commandcode/"));
        assert!(regenerable(".agent-progress/"));
        assert!(regenerable(".build/"));
        assert!(regenerable("ios/.build/"));
        // Generic output names may hold files someone put there.
        assert!(!regenerable("dist/"));
        assert!(!regenerable("build/"));
        assert!(!regenerable("coverage/"));
        assert!(!regenerable(".env"));
        assert!(!regenerable("secrets/credentials.json"));
        assert!(!regenerable("node_modules_backup.tar"));
        // A secret inside one of those directories is still a file.
        assert!(!regenerable("build/prod.env"));
        assert!(!regenerable("dist/.env"));
        assert!(!regenerable("node_modules/x/.env"));
        // Prefix lookalikes and a file that only shares the name are not directories we own.
        assert!(!regenerable(".build-notes.txt"));
        assert!(!regenerable(".buildx/"));
        assert!(!regenerable(".build"));
    }

    #[test]
    fn untracked_and_ignored_tool_state_directories_get_the_same_verdict() {
        for path in [
            ".agent-progress/",
            ".build/",
            ".commandcode/",
            ".gjc/",
            "ios/.build/",
        ] {
            assert!(regenerable(path), "{path}");
            assert!(harness_cache(&format!("?? {path}")), "{path}");
        }
        for path in [".build", ".build-notes.txt", ".buildx/", "dist/", "build/"] {
            assert!(!regenerable(path), "{path}");
            assert!(!harness_cache(&format!("?? {path}")), "{path}");
        }
    }

    /// A package manager's or compiler's directory is only disposable when git
    /// ignores it. An untracked file under a directory that merely shares the
    /// name (a plan file in a `target` folder) is the worker's own content.
    #[test]
    fn an_untracked_file_under_a_generic_looking_directory_is_not_a_cache() {
        for status in [
            "?? work/target/plan.txt",
            "?? node_modules/x.js",
            "?? target/",
            "?? packages/web/.next/page.js",
            "?? .venv/notes.txt",
        ] {
            assert!(!harness_cache(status), "{status}");
        }
        for status in [
            "?? vendor/.build/x",
            "?? .agent-progress/state.json",
            "?? a/b/.gjc/c",
        ] {
            assert!(harness_cache(status), "{status}");
        }
        assert!(
            !harness_cache("?? vendor/.build"),
            "a file named like the directory"
        );
    }

    #[test]
    fn every_tool_state_name_is_also_disposable_when_ignored() {
        for name in TOOL_STATE {
            assert!(DISPOSABLE.contains(&name), "{name}");
        }
    }
    #[test]
    fn a_changed_line_that_looks_like_a_diff_header_is_still_counted() {
        let diff = "diff --git a/q.sql b/q.sql\nindex 111..222 100644\n--- a/q.sql\n+++ b/q.sql\n@@ -1,2 +1,2 @@\n--- old comment\n+++ new\n select 1;\n";
        let counts = changed_line_counts(diff.as_bytes()).unwrap();
        let key = |line: &str| ("q.sql".to_owned(), line.to_owned());
        assert_eq!(counts.get(&key("--- old comment")), Some(&1));
        assert_eq!(counts.get(&key("+++ new")), Some(&1));
        assert_eq!(counts.get(&key("--- a/q.sql")), None);
        assert_eq!(counts.get(&key("+++ b/q.sql")), None);
    }

    #[test]
    fn a_change_without_changed_lines_is_still_a_change() {
        let none = HashMap::new();
        for diff in [
            "diff --git a/run.sh b/run.sh\nold mode 100644\nnew mode 100755\n",
            "diff --git a/a.txt b/b.txt\nsimilarity index 100%\nrename from a.txt\nrename to b.txt\n",
            "diff --git a/e b/e\nnew file mode 100644\nindex 0000000..e69de29\n",
            "diff --git a/gone b/gone\ndeleted file mode 100644\nindex e69de29..0000000\n",
        ] {
            let counts = changed_line_counts(diff.as_bytes()).unwrap();
            assert!(!counts_are_subset(&counts, &none), "{diff}");
            assert!(counts_are_subset(&counts, &counts), "{diff}");
        }
    }
    use crate::adversary::Adversary;

    /// Every slug the parser accepts must be one `task_slug` would have written.
    ///
    /// The parser's job is not "does this look plausible" but "did brgr create
    /// this", because what follows an accepted slug is `git worktree remove`.
    /// Re-rendering the parse is the whole property: if the round trip does not
    /// land back on the input, the directory was named by someone else.
    ///
    /// This found four families the example tests missed — `-r+5`, `-r007`,
    /// `-r01`, and a plain `-r1` — all of which resolved to a live revision.
    #[test]
    fn a_parsed_slug_is_always_one_brgr_could_have_written() {
        // Structured, not free-form. Sixteen random characters over a mixed
        // alphabet essentially never lands on "eight hex digits, `-r`, a
        // revision", so a free-form generator explores only the rejection path
        // and the property never fires — confirmed by reverting the parser and
        // watching 4,096 free-form cases all pass. Building a slug from the
        // parts a real one has puts the cases where the decision is.
        // Weighted, not uniform. A uniform draw over lengths and an alphabet
        // half of which is uppercase left 11 of 4,096 cases parsing at all, so
        // the property almost never ran — the counter below is what caught it.
        // The point is to crowd the boundary, not to sample garbage evenly.
        const PREFIX_ALPHABET: &str = "0123456789abcdefabcdefabcdefABCDEF";
        // Each of these is a plausible revision suffix, and the ones that are
        // not canonical decimal are exactly the interesting half.
        const SUFFIXES: &[&str] = &[
            "1",
            "2",
            "10",
            "01",
            "007",
            "+5",
            "-3",
            "0",
            "",
            "x",
            " 2",
            "2 ",
            "4294967295",
            "4294967296",
            "99999999999999999999",
            "1_0",
            "2.0",
            "Ù£",
        ];
        let mut adversary = Adversary::new(0x5eed_0f0f_c0de_0002);

        // See the bridge property's counter: a generator that stops reaching the
        // accepting path leaves the assertion below unreached and the test green.
        let mut accepted = 0_u32;
        for case in 0..4_096 {
            // Eight characters most of the time; the other lengths are there to
            // keep the length check honest.
            let length = if adversary.below(4) == 0 {
                adversary.below(11)
            } else {
                8
            };
            let mut slug: String = (0..length)
                .map(|_| {
                    let letters: Vec<char> = PREFIX_ALPHABET.chars().collect();
                    letters[adversary.below(letters.len())]
                })
                .collect();
            match adversary.below(4) {
                // A bare slug, which is what revision one looks like.
                0 => {}
                // A suffix drawn from the plausible set.
                1 | 2 => {
                    let suffix = SUFFIXES[adversary.below(SUFFIXES.len())];
                    slug.push_str("-r");
                    slug.push_str(suffix);
                }
                // Free-form, so the rejection path keeps getting exercised too.
                _ => slug = adversary.text("0123456789abcdefABCDEFr-+ ._", 16),
            }
            let Some((prefix, revision)) = parse_slug(&slug) else {
                continue;
            };
            accepted += 1;
            // `task_slug`, spelled out rather than called: the two live in
            // different modules, and a test that reuses the renderer would pass
            // even if both agreed on the wrong thing.
            let rendered = if revision == 1 {
                prefix.to_owned()
            } else {
                format!("{prefix}-r{revision}")
            };
            assert_eq!(
                rendered, slug,
                "case {case}: {slug:?} parsed as ({prefix:?}, {revision}), which renders as \
                 {rendered:?} — brgr never created a directory by that name"
            );
        }
        assert!(
            accepted > 100,
            "only {accepted} of 4096 generated slugs parsed; the generator is no \
             longer reaching the path this asserts about"
        );
    }

    #[test]
    fn a_slug_suffix_has_to_be_the_one_task_slug_would_write() {
        // The four the property found, pinned so a future edit that reopens any
        // one of them fails by name rather than by seed.
        assert_eq!(parse_slug("3d3c9081-r+5"), None);
        assert_eq!(parse_slug("3d3c9081-r007"), None);
        assert_eq!(parse_slug("3d3c9081-r01"), None);
        assert_eq!(parse_slug("3d3c9081-r1"), None);
        // Still accepted: what `task_slug` actually writes.
        assert_eq!(parse_slug("3d3c9081"), Some(("3d3c9081", 1)));
        assert_eq!(parse_slug("3d3c9081-r2"), Some(("3d3c9081", 2)));
        assert_eq!(
            parse_slug("3d3c9081-r4294967295"),
            Some(("3d3c9081", u32::MAX))
        );
    }

    #[test]
    fn slugs_parse_their_revision_and_reject_every_other_directory_name() {
        assert_eq!(parse_slug("3d3c9081"), Some(("3d3c9081", 1)));
        assert_eq!(parse_slug("3d3c9081-r4"), Some(("3d3c9081", 4)));
        assert_eq!(parse_slug("3d3c9081-r0"), None);
        assert_eq!(parse_slug("3d3c9081-rx"), None);
        assert_eq!(parse_slug("not-a-slug"), None);
        assert_eq!(parse_slug(""), None);
        assert_eq!(parse_slug(".DS_Store"), None);
        // `workspace::task_slug` emits exactly eight hex characters. A shorter or
        // longer hex name is somebody else's directory, and accepting it would
        // prefix-match a large share of all task ids.
        assert_eq!(parse_slug("f"), None);
        assert_eq!(parse_slug("cafe"), None);
        assert_eq!(parse_slug("dec0de"), None);
        assert_eq!(parse_slug("deadbeefcafe"), None);
        assert_eq!(parse_slug("deadbeefcafe-r2"), None);
    }

    #[test]
    fn slugs_reject_uppercase_hex_that_task_slug_could_not_emit() {
        assert_eq!(parse_slug("abcd1234"), Some(("abcd1234", 1)));
        // A UUID renders lowercase, so these name a directory brgr never created.
        assert_eq!(parse_slug("ABCD1234"), None);
        assert_eq!(parse_slug("abcD1234"), None);
        assert_eq!(parse_slug("ABCD1234-r2"), None);
    }

    #[test]
    fn the_cwd_guard_covers_the_directory_holding_the_worktrees() {
        let repository = Path::new("/home/brgr/worktrees/repo");
        let worktree = repository.join("abcd1234");
        // Sitting in the worktree blocks the worktree.
        assert!(is_self_or_ancestor(&worktree, &worktree));
        assert!(is_self_or_ancestor(&worktree, &worktree.join("src")));
        // Sitting in the repository directory blocks that directory too, which the
        // per-worktree check alone cannot see.
        assert!(is_self_or_ancestor(repository, repository));
        assert!(is_self_or_ancestor(repository, &worktree));
        // An unrelated directory blocks nothing.
        assert!(!is_self_or_ancestor(&worktree, repository));
        assert!(!is_self_or_ancestor(
            &worktree,
            Path::new("/home/brgr/worktrees/other/abcd1234")
        ));
    }

    #[test]
    fn outcomes_report_their_reason_and_removed_states_do_not() {
        assert_eq!(Outcome::Removable.code(), "removable");
        assert_eq!(Outcome::Removed(None).code(), "removed");
        assert_eq!(Outcome::Kept("why".to_owned()).code(), "kept");
        assert_eq!(Outcome::Kept("why".to_owned()).reason(), Some("why"));
        let kept_branch = Outcome::RemovedKeepingBranch("branch kept".to_owned());
        assert_eq!(kept_branch.code(), "removed_branch_kept");
        assert_eq!(kept_branch.reason(), Some("branch kept"));
        assert_eq!(Outcome::Removed(None).reason(), None);
        assert_eq!(
            Outcome::Removed(Some("sealed".to_owned())).reason(),
            Some("sealed")
        );
        assert_eq!(Outcome::Removable.reason(), None);
    }

    #[test]
    fn changed_line_counts_ignore_headers_and_count_multiplicity() {
        let diff = b"\
diff --git a/foo.txt b/foo.txt
index 1111111..2222222 100644
--- a/foo.txt
+++ b/foo.txt
@@ -1,3 +1,4 @@
 context
-old
+new
+new
";
        let counts = changed_line_counts(diff).unwrap();
        assert_eq!(counts.get(&("foo.txt".into(), "-old".into())), Some(&1));
        assert_eq!(counts.get(&("foo.txt".into(), "+new".into())), Some(&2));
        assert!(!counts.keys().any(|(_, line)| line.starts_with("@@")));
        assert!(!counts.keys().any(|(_, line)| line.starts_with("diff ")));
    }

    #[test]
    fn a_binary_patch_cannot_prove_containment() {
        let diff = b"\
diff --git a/image.bin b/image.bin
new file mode 100644
index 0000000..abc1234
GIT binary patch
literal 4
zcmV+0NbbH9
";
        assert_eq!(changed_line_counts(diff), None);
    }

    #[test]
    fn a_branch_multiset_must_not_exceed_the_sealed_multiset() {
        let mut sealed = HashMap::new();
        sealed.insert(("f".into(), "+foo".into()), 2);
        let mut fewer = HashMap::new();
        fewer.insert(("f".into(), "+foo".into()), 1);
        assert!(counts_are_subset(&fewer, &sealed));
        let mut extra = HashMap::new();
        extra.insert(("f".into(), "+foo".into()), 3);
        assert!(!counts_are_subset(&extra, &sealed));
    }
}