beady-eye 0.13.0

A tree of work in flight: bead graphs annotated with the live agents working them
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
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
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
//! What a setup tells `bdi`: the shape of the config file, what each setting
//! means, and what `bdi` refuses to read.

use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use std::time::Duration;

use chrono::TimeDelta;

use ratatui::style::Color;
use regex_lite::{Captures, Regex};
use serde::{Deserialize, Serialize};

use crate::view::row::{Cell, Layout};

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct Config {
    #[serde(default)]
    pub projects: Vec<Project>,
    #[serde(default)]
    pub roots: Roots,
    #[serde(default)]
    pub badges: Vec<Badge>,
    #[serde(default)]
    pub anomalies: Anomalies,
    #[serde(default)]
    pub join: Join,
    #[serde(default)]
    pub changes: Changes,
    #[serde(default)]
    pub tui: Tui,
    #[serde(default)]
    pub theme: Theme,
    #[serde(default)]
    pub row: Layout,
    /// Which of `projects` this run reads, and what chose them. The rest stay
    /// here rather than being dropped: a pane is placed by which configured
    /// project holds its directory, whether or not that project is read.
    #[serde(skip)]
    pub scope: Scope,
    /// git could not be run, so the projects here are named after the
    /// directories their trackers sit at the top of rather than after
    /// remotes.
    ///
    /// Discovery sets it and nothing else does, so it is only ever true of
    /// the one project a run with no config file draws: a file names its own
    /// projects, and `BDI_PROJECT` names the discovered one outright. That is
    /// also why a config the reader writes mid-run cannot carry it stale —
    /// where this is true there is no file to re-read.
    ///
    /// Like `scope`, a fact about how this run's config came to be rather
    /// than anything a config file could carry.
    #[serde(skip)]
    pub named_without_git: bool,
}

/// The projects a run reads, out of every one the config names, and what
/// decided it. A function of the config, the directory `bdi` was started in
/// and the command line — never a value the config file can carry.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Scope {
    /// Every configured project: nothing asked for fewer, and no project
    /// holds the directory `bdi` was started in.
    #[default]
    Everything,
    /// The projects `--project` named. The reader typed them, so the screen
    /// says nothing about the ones left out.
    Asked(Vec<String>),
    /// The project holding the directory `bdi` was started in, and any the
    /// roots named on the command line widened the read set to. The reader
    /// did not type this one, so the screen says the directory chose.
    Directory {
        project: String,
        widened: Vec<String>,
    },
}

impl Scope {
    pub fn reads(&self, name: &str) -> bool {
        match self {
            Scope::Everything => true,
            Scope::Asked(named) => named.iter().any(|n| n == name),
            Scope::Directory { project, widened } => {
                project == name || widened.iter().any(|n| n == name)
            }
        }
    }
}

/// An unknown key is refused rather than dropped, which is serde's default.
/// A project entry is the one place a reader hand-writes the name of a
/// mechanism, and a key `bdi` silently ignores is read as the default — so a
/// misspelling, or a config written against a key that has since gone, would
/// have its tracker read in an environment it asked not to be read in.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Project {
    pub name: String,
    pub path: PathBuf,
    /// A command that runs another command in the environment this project's
    /// tracker is read in — `direnv exec .`, `nix develop -c`, `mise exec --`.
    /// `bdi` appends the probe that reads the environment back, so the config
    /// names the wrapper and nothing else.
    ///
    /// A project naming none is read in the environment `bdi` itself runs in,
    /// and nothing is run to find that out.
    #[serde(default)]
    pub environment_command: Option<Command>,
    /// A command whose stdout is this tracker's password, never the password
    /// itself. The rung for a setup whose only exotic need is the credential:
    /// its stdout is captured where an environment command's argv is visible
    /// to `ps`, so it stays rather than folding into one.
    #[serde(default)]
    pub credential_command: Option<String>,
    /// Whether this project asks for itself every interval, or leaves saying
    /// its work has moved to whatever reports for it on the inbound channel.
    ///
    /// Per project because a producer is per tracker: a consumer filtered to
    /// one project's database covers that project and no other, and a setup
    /// that has deployed one for some of its trackers should not have to poll
    /// all of them or none.
    ///
    /// Off is a claim, not a saving. It says something else reports this
    /// project's changes, so a producer that dies takes the project's
    /// freshness with it and nothing here quietly covers for that — an
    /// automatic fallback would hide the very failure the operator needs to
    /// see. `bdi` polls until told otherwise, which is why this defaults on.
    #[serde(default = "polls")]
    pub poll: bool,
    /// Badges this project draws in place of the ones `[[badges]]` names, for
    /// the keys it names and no others.
    ///
    /// A link template on a shared badge cannot name a repository or a host,
    /// so a fleet-wide list cannot give one project's `delivery_pr` its own
    /// destination. This is where that project says so, while every key it
    /// stays silent about keeps drawing what the shared list says.
    #[serde(default)]
    pub badges: Vec<Badge>,
    /// Where this project is worked: the place it names, in each working
    /// tree git lists for its repository. Measured rather than configured, so
    /// nothing written by hand can outrank what git says.
    #[serde(skip)]
    pub worktrees: Vec<PathBuf>,
}

/// A project says nothing about polling until it says it does not.
fn polls() -> bool {
    true
}

/// A program and its arguments, written either way round.
///
/// A line is what almost every wrapper wants — `direnv exec .` is three words
/// and no argument holds a space — so that is what the common case writes.
/// It is split on whitespace and nothing else: no quotes are honoured, and a
/// config relying on them would have `bdi` run an argv the reader did not
/// write, which is the class of silent wrong answer this key exists to close.
///
/// So an argument that holds a space is written as a list, where each entry
/// is one argument whatever is inside it:
///
/// ```toml
/// environment_command = ["nix", "develop", ".#dev shell", "-c"]
/// ```
///
/// The exotic case pays a more precise config and the common one pays
/// nothing, rather than every reader learning a quoting rule for a space
/// almost none of them has.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum Command {
    Line(String),
    Words(Vec<String>),
}

impl Command {
    /// The program and its arguments, in order.
    pub fn words(&self) -> Vec<&str> {
        match self {
            Command::Line(line) => line.split_whitespace().collect(),
            Command::Words(words) => words.iter().map(String::as_str).collect(),
        }
    }

    /// Whether it names no program at all, which the config refuses. `bdi`
    /// appends its own probe, so an empty command would run that probe alone
    /// — reading the project in `bdi`'s environment while its config says it
    /// was read in its own.
    ///
    /// A list is the way to write an empty *word*, not only an empty command:
    /// `[""]` has an entry and still names nothing, where a line cannot,
    /// because splitting on whitespace never yields one. So it is the first
    /// word that has to be there rather than any word.
    pub fn names_no_program(&self) -> bool {
        self.words()
            .first()
            .is_none_or(|program| program.is_empty())
    }
}

impl Project {
    /// How deeply this project holds a directory, or nothing where it holds
    /// it at all: the depth of the deepest working tree the directory sits
    /// under, so a project inside another wins the paths they share.
    pub fn holds(&self, path: &Path) -> Option<usize> {
        std::iter::once(&self.path)
            .chain(&self.worktrees)
            .filter(|tree| path.starts_with(tree))
            .map(|tree| tree.components().count())
            .max()
    }
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Roots {
    /// The roots named outright, under the project whose tracker holds each.
    /// Bead prefixes are per-tracker and uncoordinated, so an id on its own
    /// names nothing bdi can go and read.
    pub explicit: BTreeMap<String, Vec<String>>,
}

/// A badge opens a table, so every key written after `[[projects.badges]]`
/// lands in it. A badge that took a project's `path` would leave the project
/// reporting a key the reader did in fact write as missing.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Badge {
    /// Which value of the bead this badge draws, by the key that names it: a
    /// field of the bead by its own name, and a member of a field's object by
    /// the two joined with a dot.
    pub key: String,
    #[serde(rename = "match")]
    pub match_value: Option<Pattern>,
    pub render: String,
    /// What the badge says on a row too narrow for its `render`, as a template
    /// over the same captures.
    ///
    /// A template rather than a character, because a badge's length is not
    /// `bdi`'s to choose at either end: a setup that wants a bare glyph writes
    /// one, and one that wants a number keeps the number.
    ///
    /// A brace pair naming nothing the value supplied leaves the badge with no
    /// short form, as it leaves it with no `link`: a row that fell back to a
    /// half-substituted template would put the template in front of the reader
    /// at exactly the widths where it had least room to explain itself.
    pub short: Option<String>,
    /// Where the badge points, as a template over the same captures `render`
    /// reads.
    ///
    /// A brace pair naming nothing the value supplied leaves the badge with
    /// no link at all: a destination built out of a part that was never
    /// there points somewhere else.
    pub link: Option<String>,
    /// What the badge is drawn in, for one whose config names a colour. A
    /// badge that names none is drawn in the tone of the row it sits on.
    pub colour: Option<Colour>,
}

/// A colour a badge may be drawn in: a slot of `bdi`'s own palette, or a
/// colour the reader wrote.
///
/// Parsed here and resolved in `view::palette`, so the name a config may write
/// is this module's and the colour behind it is the palette's.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Colour {
    /// What this bead's status is drawn in, which is what its id is drawn in
    /// as well. The one colour here that varies per bead: a badge naming it is
    /// red on a blocked bead and orange on an in-progress one.
    ///
    /// Apart from `Slot` rather than one of them because it is not one slot.
    /// It is five, chosen per bead, which is `view::draw::tone`'s rule and not
    /// a value the palette holds.
    Status,
    /// One slot of the palette, drawn in whatever that slot is drawn in and
    /// moving with the theme as it does.
    Slot(Slot),
    /// A colour the reader named outright, drawn in exactly that.
    ///
    /// `colours-come-from-the-palette` refuses a colour named under `src/`.
    /// This is not one: it is data a config carried in.
    Absolute(Color),
}

/// Every slot of `bdi`'s own palette a badge may name, and the name a config
/// writes for each.
///
/// The whole palette rather than the slots that look useful on a badge, so a
/// slot added to `palette` belongs here too.
///
/// `voice` is the one treatment `palette` names that is missing here, because
/// it is not a slot: it is a function of the reader's declared background,
/// with no one value to draw a badge in.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Slot {
    /// `bd`'s own colour for each status, as a fixed colour rather than this
    /// bead's.
    StatusOpen,
    StatusInProgress,
    StatusBlocked,
    StatusClosed,
    StatusDeferred,
    /// `bd show`'s colour for the id at the head of the page.
    Identity,
    /// A live agent is here.
    Agent,
    /// This wants looking at.
    Attention,
    /// The three rungs of how live a row is, as fixed treatments rather than
    /// this row's.
    TierStaffed,
    TierOpen,
    TierFinished,
    /// How the tree is shaped rather than how a bead is going.
    Structure,
    /// Metadata, chrome, an affordance, a rule.
    Quiet,
    /// Every row of the bead window.
    Page,
    /// `bdi`'s own sentence about a forest where nothing went wrong in it.
    Plain,
    /// A code span or a code block: prose's own namespace.
    Code,
    /// The row under the cursor.
    Selected,
    /// A window's own name, on its border.
    Title,
    /// `bd show`'s section names.
    Section,
    /// A heading in prose.
    Heading,
    /// Prose's own emphasis.
    Emphasis,
    Strong,
    /// Somewhere to go.
    Link,
}

/// A slot first, then a colour, and the name the reader wrote in the refusal.
///
/// A slot first because the two name sets are `bdi`'s and the terminal's and
/// nothing coordinates them: were a slot name ever to become a colour name as
/// well, a config that meant the slot would quietly start drawing the colour.
///
/// The refusal says what was written rather than what was expected, because
/// what was expected is two dozen slots and every form `Color` reads — more
/// than the line at the foot of the screen can hold.
impl<'de> Deserialize<'de> for Colour {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::IntoDeserializer;

        let written = String::deserialize(deserializer)?;
        if written == STATUS {
            return Ok(Colour::Status);
        }
        let slot: Result<Slot, serde::de::value::Error> =
            Slot::deserialize(written.as_str().into_deserializer());
        if let Ok(slot) = slot {
            return Ok(Colour::Slot(slot));
        }
        crate::view::palette::colour_named(&written)
            .map(Colour::Absolute)
            .ok_or_else(|| {
                serde::de::Error::custom(format!(
                    "{written:?} is neither a slot of bdi's palette nor a colour"
                ))
            })
    }
}

/// Written back as the reader wrote it, because `--snapshot-json` is read by
/// someone holding the config beside it.
impl Serialize for Colour {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Colour::Status => serializer.serialize_str(STATUS),
            Colour::Slot(slot) => slot.serialize(serializer),
            // `Color`'s own `Display`, which is what its `FromStr` reads, so
            // what comes out of here goes back in.
            Colour::Absolute(colour) => serializer.collect_str(colour),
        }
    }
}

/// The one colour that is neither a slot nor a value, so the one whose name
/// neither `Slot` nor `Color` carries.
const STATUS: &str = "status";

/// A badge's `match`: the pattern a setup wrote, and that pattern compiled.
///
/// Anchored against the whole value. `match` was an exact-value test before
/// it was a pattern, and anchoring is what keeps every config written then
/// saying what it said: unanchored, `human` would begin drawing on
/// `inhumane`.
///
/// Compiled here, as the config is read, because badges are applied to every
/// bead of every collection.
#[derive(Debug, Clone)]
pub struct Pattern {
    source: String,
    anchored: Regex,
}

impl Pattern {
    pub fn new(source: &str) -> Result<Self, regex_lite::Error> {
        Ok(Self {
            source: source.to_string(),
            anchored: Regex::new(&format!("^(?:{source})$"))?,
        })
    }

    fn captures<'v>(&self, value: &'v str) -> Option<Captures<'v>> {
        self.anchored.captures(value)
    }
}

/// The compiled pattern is a function of the source text, so the source text
/// is the whole of what two patterns can differ by. Written out because no
/// regex implements `PartialEq`, and this equality is load-bearing: it is how
/// a re-read config is judged against the one in force.
impl PartialEq for Pattern {
    fn eq(&self, other: &Self) -> bool {
        self.source == other.source
    }
}

impl Eq for Pattern {}

impl<'de> Deserialize<'de> for Pattern {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let source = String::deserialize(deserializer)?;
        Pattern::new(&source)
            .map_err(|e| serde::de::Error::custom(format!("{source:?} is no pattern: {e}")))
    }
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Anomalies {
    pub stale_claim_days: i64,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Join {
    pub pane_key: String,
}

/// Where `bdi` listens for something saying a project's work has moved on.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Changes {
    /// The socket to listen on, rather than the one under the directory this
    /// login session owns.
    ///
    /// Told rather than derived because the two parties that have to agree on
    /// it can be in different login sessions: `bdi` is a TUI a human runs and
    /// a producer is a daemon, and a runtime directory scopes to exactly the
    /// session. Derived, each is free to be right about a different path;
    /// named here, it is one fact both are given. A machine that owns no
    /// runtime directory at all — macOS — has nothing to derive and gets its
    /// channel from this key or not at all.
    ///
    /// The socket is created `0600` wherever it goes, and both platforms
    /// `bdi` runs on check that mode when something connects, so the channel
    /// is this user's for the same reason on either. Who may replace the
    /// socket is the directories above it to say, so `bdi` reads the way down
    /// to it as well: where a directory on that way is one somebody else may
    /// take a name in, `bdi` names that directory and polls.
    ///
    /// Per user, so it cannot be what two simultaneous `bdi` runs differ by —
    /// both read this file and derive this path. `--socket` is what one of
    /// them overrides it with.
    pub socket: Option<PathBuf>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Tui {
    /// How long a project waits after one read before it asks for the next,
    /// where it polls at all. A collection is several `bd` subprocesses
    /// against each tracker's server, per instance running, so this is
    /// measured in seconds.
    ///
    /// A gap after a read rather than a period a read happens inside, and the
    /// difference is worth reading twice: the next ask is armed by the read
    /// that came back, so the effective period is this plus however long a
    /// read takes — `bdi-rer.4` measured 1.53s for the cascade. What it buys
    /// is that each project's schedule comes from its own history and nothing
    /// else, so projects drift apart rather than all paying the cascade on
    /// one tick, and a slow project delays only itself.
    ///
    /// Measured at `40f4eb5` against Dolt-backed trackers, one of 129 beads
    /// and one larger: 1.1 to 1.5 seconds for the small one alone, 2.3 to
    /// 2.4 for the larger alone, 3.5 to 4.1 for both together.
    ///
    /// Most of that is fixed per project rather than per row — a project
    /// costs seven-plus processes before its rows are read at all — so the
    /// cost follows the number of projects configured as much as the size of
    /// any one tracker, and a config naming twice as many wants a longer
    /// interval than this one.
    ///
    /// Setting it below a collection is allowed and is bounded, because the
    /// gap does not start until the read ends: a project asks again this long
    /// after its last answer, never sooner and never twice over. So a short
    /// interval buys back-to-back collections with no idle gap, and a view as
    /// fresh as the collection allows rather than as the interval promised.
    pub refresh_seconds: u64,

    /// How long a collection may go unanswered before `bdi` reports the
    /// tracker as having stopped answering rather than as being read.
    ///
    /// A collection blocks in `Command::output()`, which has no deadline, and
    /// reports nothing until it is done — so without this a tracker hung for
    /// an hour is drawn exactly as one asked half a second ago.
    ///
    /// Configured rather than fixed for the same reason the interval above is,
    /// and by the same measurement: what a healthy collection costs follows
    /// the number of projects, so a config naming twice as many waits longer
    /// before anything is wrong. The default is around eight times the 3.5 to
    /// 4.1 seconds measured for the two projects that measurement was taken
    /// on.
    ///
    /// Passing it abandons nothing. The collection runs on, and a tracker that
    /// answers at last puts its rows up — a deadline that cut the collection
    /// off would leave a merely slow tracker permanently unreadable, which is
    /// the disappearance `bdi` is built not to do.
    pub unanswered_after_seconds: u64,

    /// How long the tail waits after herdr answers before it asks for the
    /// selected pane again. The one interval here counted in milliseconds,
    /// because it is the one that is under a second: the tail is a live
    /// view of a pane, and seconds cannot say how live.
    ///
    /// A gap after an answer rather than a period, as `refresh_seconds` is:
    /// a slow herdr stretches the gap rather than piling asks up behind
    /// itself. The read is one `herdr` process, measured at 2–5 ms, so at
    /// the default four a second cost about a hundredth of a core — and four
    /// a second is where a reader stops being able to tell the band from the
    /// pane it is reading.
    pub tail_refresh_millis: u64,

    /// How far one notch of the wheel moves the forest, and the bead window
    /// over it.
    ///
    /// Settled here rather than in code because no one number serves every
    /// device: a wheel reports a detent, and a high-precision trackpad
    /// reports once per cell of travel, so the same value is a nudge on one
    /// and a leap on the other.
    ///
    /// The terminal's own knob cannot reach this. A terminal scaling the
    /// wheel for its scrollback neutralises that scaling to its sign while a
    /// program is reading mouse reports, so what arrives here is one report
    /// per detent whatever the reader set.
    pub wheel_notch_lines: usize,
}

/// What the reader's terminal is, in the one respect `bdi` can neither see
/// nor ask.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Theme {
    pub background: Background,
}

/// The background the reader's terminal draws on.
///
/// The reader says it because `bdi` cannot find it out. A terminal query
/// degrades either to a wait or to a confident wrong answer, and a wrong
/// answer of that kind is intermittent — right in one terminal and wrong in
/// another, right outside a multiplexer and wrong inside it — so nobody can
/// see what is producing it. A declaration is wrong the same way on every
/// terminal from the first frame, which is what makes it something the
/// reader notices and one line fixes.
///
/// Their background rather than their theme, and that is the whole axis
/// rather than a stand-in for a richer one. A theme brings its own
/// foreground and its own colour 8, so `bdi` needs neither; what no theme
/// can tell it is which side of the background a treatment of `bdi`'s own
/// will land on.
///
/// Dark is what an undeclared reader gets, because it is what the shipped
/// tones were chosen against: the default changes nothing for anyone
/// already reading `bdi`.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Background {
    #[default]
    Dark,
    Light,
}

impl Default for Anomalies {
    fn default() -> Self {
        Self {
            stale_claim_days: 30,
        }
    }
}

impl Default for Join {
    fn default() -> Self {
        Self {
            pane_key: "agent_pane".to_string(),
        }
    }
}

impl Default for Tui {
    fn default() -> Self {
        Self {
            refresh_seconds: 30,
            unanswered_after_seconds: 30,
            tail_refresh_millis: 250,
            wheel_notch_lines: 3,
        }
    }
}

impl Tui {
    pub fn refresh(&self) -> Duration {
        Duration::from_secs(self.refresh_seconds)
    }

    pub fn tail_refresh(&self) -> Duration {
        Duration::from_millis(self.tail_refresh_millis)
    }

    /// The same, as the clock arithmetic beside a project's name counts in,
    /// or the longest interval there is where the config named a patience
    /// longer than that.
    ///
    /// Saturating rather than refusing, because every value up there says the
    /// same thing — a collection this patience gives up on is one no run
    /// reaches — and because the patience is only ever compared against, so
    /// the longest interval there is is an answer every reader of it holds.
    /// `TimeDelta` runs out twice on the way: at `i64` seconds, and again
    /// three decimal places short of that, so a patience past the second
    /// limit is a thousandth of the way to the first.
    pub fn unanswered_after(&self) -> TimeDelta {
        i64::try_from(self.unanswered_after_seconds)
            .ok()
            .and_then(TimeDelta::try_seconds)
            .unwrap_or(TimeDelta::MAX)
    }
}

impl Config {
    /// A config naming these projects and nothing else, with every other
    /// setting at its default: what discovery builds where no file says more.
    pub fn naming(projects: Vec<Project>) -> Self {
        Config {
            projects,
            roots: Roots::default(),
            badges: Vec::new(),
            anomalies: Anomalies::default(),
            join: Join::default(),
            changes: Changes::default(),
            tui: Tui::default(),
            theme: Theme::default(),
            row: Layout::default(),
            scope: Scope::default(),
            named_without_git: false,
        }
    }

    /// The badges this project draws: the global list, with a project's own
    /// entries for a key ahead of the global entries for that same key.
    ///
    /// A project wins a value by being tried first rather than by replacing
    /// anything, so a value its own entries do not read falls through to the
    /// shared shapes. Its entries stand where the global list's first entry for
    /// that key stood, so naming a key does not reorder the row. Keys only the
    /// project names follow the rest.
    pub fn badges_for_project(&self, project: &str) -> Vec<Badge> {
        let Some(own) = self
            .projects
            .iter()
            .find(|p| p.name == project)
            .map(|p| p.badges.as_slice())
            .filter(|own| !own.is_empty())
        else {
            return self.badges.clone();
        };
        let mut drawn: Vec<Badge> = Vec::new();
        let mut went_ahead_of: BTreeSet<&str> = BTreeSet::new();
        for global in &self.badges {
            if own.iter().any(|b| b.key == global.key) && went_ahead_of.insert(&global.key) {
                drawn.extend(own.iter().filter(|b| b.key == global.key).cloned());
            }
            drawn.push(global.clone());
        }
        drawn.extend(
            own.iter()
                .filter(|b| !went_ahead_of.contains(b.key.as_str()))
                .cloned(),
        );
        drawn
    }

    /// The projects this run reads whose names git did not give.
    ///
    /// One call for both mouths: the snapshot the screen draws and the
    /// snapshot `--json` prints are built from this, so neither can qualify
    /// a name the other does not.
    pub fn projects_named_without_git(&self) -> Vec<String> {
        match self.named_without_git {
            true => self.read().map(|project| project.name.clone()).collect(),
            false => Vec::new(),
        }
    }

    pub fn from_toml(s: &str) -> anyhow::Result<Self> {
        let table: toml::Table = toml::from_str(s)?;
        if table
            .get("roots")
            .and_then(|roots| roots.get("metadata_keys"))
            .is_some()
        {
            anyhow::bail!(
                "[roots] metadata_keys is gone: every unfinished bead is a root, so a key \
                 could name nothing bd's statuses do not; remove it"
            );
        }
        let cfg: Config = table.try_into()?;
        if cfg.projects.is_empty() {
            anyhow::bail!("config names no projects; bdi has nothing to read");
        }
        let repeated = cfg.names_borne_by_more_than_one_project();
        if !repeated.is_empty() {
            anyhow::bail!(
                "a project's name is how bdi tells its beads from another tracker's, so \
                 two projects cannot answer to one; repeated: {}",
                repeated.join(", ")
            );
        }
        if let Some(project) = cfg.projects.iter().find(|p| {
            p.environment_command
                .as_ref()
                .is_some_and(Command::names_no_program)
        }) {
            anyhow::bail!(
                "{} names an environment_command with no program in it; bdi appends its own \
                 probe to what you write, so an empty one would read the project in bdi's \
                 environment while saying it was read in its own",
                project.name
            );
        }
        for (named, ids) in &cfg.roots.explicit {
            if !cfg.is_configured(named) {
                anyhow::bail!(
                    "[roots.explicit] gives {} to {named}, which is no project of this \
                     config; bdi is reading {}",
                    ids.join(", "),
                    names_of(&cfg.projects).join(", ")
                );
            }
        }
        let mut named: HashSet<&Cell> = HashSet::new();
        if let Some(twice) = cfg.row.cells().find(|cell| !named.insert(cell)) {
            anyhow::bail!(
                "[row] names {twice} twice; a cell is drawn in one place, so name it in one list"
            );
        }
        let configured: BTreeSet<String> = cfg
            .projects
            .iter()
            .flat_map(|project| cfg.badges_for_project(&project.name))
            .map(|badge| badge.key)
            .collect();
        if let Some(unconfigured) = cfg
            .row
            .cells()
            .find(|cell| matches!(cell, Cell::Badge(key) if !configured.contains(key)))
        {
            anyhow::bail!(
                "[row] names {unconfigured}, which no [[badges]] or [[projects.badges]] entry \
                 configures, so it would draw nothing on any row"
            );
        }
        Ok(cfg)
    }

    /// The projects this run reads, in the order the config names them.
    ///
    /// Every site that gathers reads through this — the collection loop, the
    /// order the trees are drawn in, the forest drawn before any tracker has
    /// answered, the working trees git is asked for — so a project outside
    /// the scope is one nothing can go and read: the projects left out are
    /// not gathered, rather than gathered and hidden. `projects` itself stays
    /// whole for the sites that place a pane.
    pub fn read(&self) -> impl Iterator<Item = &Project> {
        self.projects.iter().filter(|p| self.reads(&p.name))
    }

    pub fn reads(&self, name: &str) -> bool {
        self.scope.reads(name)
    }

    /// The config scoped to the projects `--project` named, or left whole
    /// where none is. What decides that is whether a scope was asked for,
    /// never how many projects one selected: a scope that selected nothing is
    /// refused below rather than obeyed.
    ///
    /// Applied before the roots the command line names, so a *positional*
    /// under a project the scope left out is refused: one command line asking
    /// for a project's root and asking not to read that project contradicts
    /// itself, and the other order would accept it and then draw nothing.
    /// `roots.explicit` is read only inside a project's own collection, so a
    /// root under a project no collection reaches is never consulted.
    ///
    /// A root the *config file* names under an excluded project is not that
    /// contradiction and is left alone — see the test below.
    pub fn scoped_to(mut self, names: &[String]) -> anyhow::Result<Self> {
        if names.is_empty() {
            return Ok(self);
        }
        let unknown: Vec<&str> = names
            .iter()
            .map(String::as_str)
            .filter(|named| !self.is_configured(named))
            .collect();
        if !unknown.is_empty() {
            anyhow::bail!(
                "--project names {}, which is no project of this config; bdi is \
                 configured for {}",
                unknown.join(", "),
                names_of(&self.projects).join(", ")
            );
        }
        self.scope = Scope::Asked(names.to_vec());
        Ok(self)
    }

    /// The config scoped to the project holding `path` — the directory `bdi`
    /// was started in — or left whole where no project holds it. The
    /// deepest project wins, as it does when the join places a pane.
    pub fn scoped_to_the_project_holding(self, path: &Path) -> Self {
        self.scoped_to_the_project_holding_any_of(&[path.to_path_buf()])
    }

    /// The same, over the places one directory is: its counterpart in each
    /// working tree of the repository it sits in.
    pub fn scoped_to_the_project_holding_any_of(mut self, places: &[PathBuf]) -> Self {
        let holding = places
            .iter()
            .flat_map(|place| {
                self.projects
                    .iter()
                    .filter_map(move |p| Some((p.holds(place)?, p)))
            })
            .max_by_key(|(depth, _)| *depth)
            .map(|(_, project)| project.name.clone());
        if let Some(project) = holding {
            self.scope = Scope::Directory {
                project,
                widened: Vec::new(),
            };
        }
        self
    }

    /// Roots named on the command line join those named in config: discovery
    /// rule 3 has two spellings and one meaning. `<project>:<bead-id>` says
    /// whose tracker holds the bead; a bare id can only mean the one project
    /// being read, so the terse form survives exactly as far as it is
    /// unambiguous.
    pub fn with_roots_named_on_the_command_line(
        mut self,
        beads: &[String],
    ) -> anyhow::Result<Self> {
        for named in beads {
            let (project, id) = self.placed(named)?;
            self.roots.explicit.entry(project).or_default().push(id);
        }
        Ok(self)
    }

    /// The project and bead a command-line root names, or why it names
    /// neither.
    ///
    /// A root under a project the scope left out is a contradiction only
    /// when the reader typed the scope. A scope the directory chose is
    /// widened to take the project in: `bdi meadow:mdw-1` from another
    /// project's desktop reads both.
    fn placed(&mut self, named: &str) -> anyhow::Result<(String, String)> {
        let Some((project, id)) = named.split_once(':') else {
            let reading: Vec<&Project> = self.read().collect();
            return match reading.as_slice() {
                [only] => Ok((only.name.clone(), named.to_string())),
                several => anyhow::bail!(
                    "{named} names no project, and bdi is reading {}; write it as \
                     <project>:{named}",
                    several
                        .iter()
                        .map(|p| p.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            };
        };
        if project.is_empty() || id.is_empty() {
            anyhow::bail!("{named} is not <project>:<bead-id>");
        }
        if !self.is_configured(project) {
            anyhow::bail!(
                "{named} gives {id} to {project}, which is not among the projects \
                 bdi is configured for: {}",
                names_of(&self.projects).join(", ")
            );
        }
        if !self.reads(project) {
            match &mut self.scope {
                Scope::Directory { widened, .. } => widened.push(project.to_string()),
                Scope::Asked(_) | Scope::Everything => anyhow::bail!(
                    "{named} gives {id} to {project}, which is not among the projects \
                     bdi is reading: {}",
                    self.read()
                        .map(|p| p.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            }
        }
        Ok((project.to_string(), id.to_string()))
    }

    fn is_configured(&self, name: &str) -> bool {
        self.projects.iter().any(|p| p.name == name)
    }

    fn names_borne_by_more_than_one_project(&self) -> Vec<&str> {
        let mut seen = BTreeSet::new();
        let mut repeated = BTreeSet::new();
        for name in self.projects.iter().map(|p| p.name.as_str()) {
            if !seen.insert(name) {
                repeated.insert(name);
            }
        }
        repeated.into_iter().collect()
    }
}

fn names_of(projects: &[Project]) -> Vec<&str> {
    projects.iter().map(|p| p.name.as_str()).collect()
}

impl Badge {
    /// Render this badge for a metadata value, or `None` if it does not apply.
    /// `{}` in `render` is replaced by the whole value, and `{name}` by what
    /// the pattern's capture of that name took. A brace pair naming nothing
    /// the pattern captured is left as it was written, and the pair taken is
    /// the innermost, so `{{}}` still draws braces around the value.
    ///
    /// One pass, so what is placed is never read again: a value spelled like
    /// a placeholder is a value.
    pub fn apply(&self, value: &str) -> Option<String> {
        Some(self.fill(&self.render, value)?.text)
    }

    /// What this badge says where the row cannot afford its `render`: its
    /// `short` filled in from the captures `render` reads, or `None` where the
    /// config names no short form, the badge does not apply, or a brace pair
    /// in the template named nothing the value supplied.
    pub fn short_for(&self, value: &str) -> Option<String> {
        let filled = self.fill(self.short.as_ref()?, value)?;
        filled.whole.then_some(filled.text)
    }

    /// Where this badge points for a metadata value: its `link` filled in
    /// from the captures `render` reads, or `None` where the config names no
    /// link, the badge does not apply, or a brace pair in the template named
    /// nothing the value supplied.
    pub fn link_for(&self, value: &str) -> Option<String> {
        let filled = self.fill(self.link.as_ref()?, value)?;
        filled.whole.then_some(filled.text)
    }

    /// `template` filled in for `value`, or `None` where this badge does not
    /// apply to the value at all.
    fn fill(&self, template: &str, value: &str) -> Option<Filled> {
        let taken = match &self.match_value {
            Some(pattern) => Some(pattern.captures(value)?),
            None => None,
        };

        let mut text = String::new();
        let mut whole = true;
        let mut rest = template;
        while let Some(close) = rest.find('}') {
            let Some(open) = rest[..close].rfind('{') else {
                text.push_str(&rest[..=close]);
                rest = &rest[close + 1..];
                continue;
            };
            let name = &rest[open + 1..close];
            let placed = match name {
                "" => Some(value),
                _ => taken
                    .as_ref()
                    .and_then(|taken| taken.name(name))
                    .map(|capture| capture.as_str()),
            };
            whole &= placed.is_some();
            text.push_str(&rest[..open]);
            text.push_str(placed.unwrap_or(&rest[open..=close]));
            rest = &rest[close + 1..];
        }
        text.push_str(rest);
        Some(Filled { text, whole })
    }
}

/// One template filled in for one value.
struct Filled {
    text: String,
    /// Whether every brace pair in the template named something the value
    /// supplied. `render` draws a pair that named nothing as it was written,
    /// and a `link` carrying one is dropped, so the two need telling apart.
    whole: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::view::row::{Cell, Layout};
    use std::path::Path;

    const EVERY_SECTION: &str = r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"
credential_command = "secret-tool lookup tracker arkham"

[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
credential_command = "cat /home/user/dev/kadath/.beads-password"

[[projects.badges]]
key    = "metadata.delivery_pr"
render = "⇢ kadath/{}"

[roots.explicit]
arkham  = ["a-1", "a-9"]
kadath = ["b-1"]

[[badges]]
key    = "metadata.delivery_pr"
render = "⇢ {}"

[[badges]]
key    = "metadata.blocked_on"
match  = "human"
render = "⏸ waiting"

[anomalies]
stale_claim_days = 7

[join]
pane_key = "herdr_pane"

[changes]
socket = "/var/folders/T/beady-eye/changes.sock"

[tui]
refresh_seconds = 5
unanswered_after_seconds = 90
tail_refresh_millis = 100
wheel_notch_lines = 1

[theme]
background = "light"

[row]
identity = ["glyph", "id", "badge.metadata.blocked_on"]
state    = ["agent", "anomalies", "progress"]
"#;

    const ONE_PROJECT: &str = r#"
[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
"#;

    const ONE_CREDENTIALLED_ONE_AMBIENT: &str = r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"
credential_command = "secret-tool lookup tracker arkham"

[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
"#;

    const TWO_AMBIENT: &str = r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"
credential_command = "secret-tool lookup tracker arkham"

[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"

[[projects]]
name = "cinder"
path = "/home/user/dev/cinder"
"#;

    #[test]
    fn parses_every_section() {
        let cfg = Config::from_toml(EVERY_SECTION).expect("parses");

        assert_eq!(
            cfg.projects,
            vec![
                Project {
                    name: "arkham".to_string(),
                    path: PathBuf::from("/home/user/arkham"),
                    environment_command: None,
                    credential_command: Some("secret-tool lookup tracker arkham".to_string()),
                    poll: true,
                    badges: Vec::new(),
                    worktrees: Vec::new(),
                },
                Project {
                    name: "kadath".to_string(),
                    path: PathBuf::from("/home/user/dev/kadath"),
                    environment_command: None,
                    credential_command: Some(
                        "cat /home/user/dev/kadath/.beads-password".to_string()
                    ),
                    poll: true,
                    badges: vec![Badge {
                        key: "metadata.delivery_pr".to_string(),
                        match_value: None,
                        render: "⇢ kadath/{}".to_string(),
                        link: None,
                        short: None,
                        colour: None,
                    }],
                    worktrees: Vec::new(),
                },
            ]
        );
        assert_eq!(
            cfg.roots,
            Roots {
                explicit: BTreeMap::from([
                    (
                        "arkham".to_string(),
                        vec!["a-1".to_string(), "a-9".to_string()]
                    ),
                    ("kadath".to_string(), vec!["b-1".to_string()]),
                ]),
            }
        );
        assert_eq!(
            cfg.badges,
            vec![
                Badge {
                    key: "metadata.delivery_pr".to_string(),
                    match_value: None,
                    render: "⇢ {}".to_string(),
                    link: None,
                    short: None,
                    colour: None,
                },
                Badge {
                    key: "metadata.blocked_on".to_string(),
                    match_value: Some(pattern("human")),
                    render: "⏸ waiting".to_string(),
                    link: None,
                    short: None,
                    colour: None,
                },
            ]
        );
        assert_eq!(cfg.anomalies.stale_claim_days, 7);
        assert_eq!(cfg.join.pane_key, "herdr_pane");
        assert_eq!(
            cfg.changes.socket,
            Some(PathBuf::from("/var/folders/T/beady-eye/changes.sock"))
        );
        assert_eq!(cfg.tui.refresh_seconds, 5);
        assert_eq!(cfg.tui.unanswered_after_seconds, 90);
        assert_eq!(cfg.tui.tail_refresh_millis, 100);
        assert_eq!(cfg.tui.wheel_notch_lines, 1);
        assert_eq!(cfg.theme.background, Background::Light);
        assert_eq!(
            cfg.row,
            Layout {
                identity: vec![
                    Cell::Glyph,
                    Cell::Id,
                    Cell::Badge("metadata.blocked_on".to_string())
                ],
                title: vec![Cell::Title, Cell::Badges],
                state: vec![Cell::Agent, Cell::Anomalies, Cell::Progress],
            },
            "a list left out is the default's, and one written is read as written"
        );
    }

    /// A row written without `title` is read as written: a block a reader
    /// emptied is empty, not put back.
    #[test]
    fn a_row_without_title_is_read_as_written() {
        let cfg =
            Config::from_toml(&format!("{ONE_PROJECT}\n[row]\ntitle = []\n")).expect("parses");

        assert_eq!(cfg.row.title, Vec::<Cell>::new());
        assert_eq!(cfg.row.identity, Layout::default().identity);
    }

    #[test]
    fn a_row_nobody_wrote_is_the_default() {
        assert_eq!(
            Config::from_toml(ONE_PROJECT).expect("parses").row,
            Layout::default()
        );
    }

    /// A cell the drawer has no rendering for is refused rather than dropped,
    /// with the word the reader wrote in the reason so they can find it.
    #[test]
    fn a_cell_bdi_cannot_draw_refuses_the_config() {
        let err = Config::from_toml(&format!(
            "{ONE_PROJECT}\n[row]\nstate = [\"progress\", \"priority\"]\n"
        ))
        .unwrap_err()
        .to_string();

        assert!(err.contains("priority"), "got: {err}");
    }

    /// A badge no entry configures would draw nothing on any row of any
    /// project, so naming it as a cell is a blank column and is refused.
    #[test]
    fn a_badge_no_entry_configures_refuses_the_config() {
        let err = Config::from_toml(&format!(
            r#"{ONE_PROJECT}
[[badges]]
key    = "metadata.delivery_pr"
render = "⇢ {{}}"

[row]
identity = ["glyph", "id", "badge.metadata.jira"]
"#
        ))
        .unwrap_err()
        .to_string();

        assert!(err.contains("badge.metadata.jira"), "got: {err}");
    }

    /// The check sees every project's badges, so a badge only one project's
    /// own entries configure is a badge some row draws.
    #[test]
    fn a_badge_only_one_project_configures_is_a_cell_every_row_may_name() {
        let cfg = Config::from_toml(
            r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"

[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"

[[projects.badges]]
key    = "metadata.jira"
render = "{}"

[row]
title = ["title", "badge.metadata.jira", "badges"]
"#,
        )
        .expect("parses");

        assert_eq!(
            cfg.row.title,
            vec![
                Cell::Title,
                Cell::Badge("metadata.jira".to_string()),
                Cell::Badges
            ]
        );
    }

    /// A cell drawn twice would say one thing in two places, so a name
    /// written in two lists, or twice in one, is refused by name.
    #[test]
    fn a_cell_named_twice_refuses_the_config() {
        let err = Config::from_toml(&format!(
            "{ONE_PROJECT}\n[row]\nidentity = [\"glyph\", \"id\"]\nstate = [\"id\", \"agent\"]\n"
        ))
        .unwrap_err()
        .to_string();

        assert!(err.contains("id"), "got: {err}");
        assert!(err.contains("twice"), "got: {err}");
    }

    /// A key the table does not have is refused rather than dropped, as a
    /// project's unknown key is.
    #[test]
    fn a_row_key_bdi_does_not_read_refuses_the_config() {
        let err = Config::from_toml(&format!("{ONE_PROJECT}\n[row]\nfooter = [\"agent\"]\n"))
            .unwrap_err()
            .to_string();

        assert!(err.contains("footer"), "got: {err}");
    }

    fn pattern(source: &str) -> Pattern {
        Pattern::new(source).expect("the pattern compiles")
    }

    fn badge(key: &str, render: &str) -> Badge {
        Badge {
            key: key.to_string(),
            match_value: None,
            render: render.to_string(),
            link: None,
            short: None,
            colour: None,
        }
    }

    fn matching(key: &str, value: &str, render: &str) -> Badge {
        Badge {
            match_value: Some(pattern(value)),
            ..badge(key, render)
        }
    }

    fn drawing(name: &str, badges: Vec<Badge>) -> Project {
        Project {
            name: name.to_string(),
            path: PathBuf::from("/home/user").join(name),
            environment_command: None,
            credential_command: None,
            poll: true,
            badges,
            worktrees: Vec::new(),
        }
    }

    #[test]
    fn a_projects_badge_stands_where_the_first_global_one_for_its_key_stood() {
        let cfg = Config {
            badges: vec![
                badge("metadata.delivery_pr", "⇢ {}"),
                matching("metadata.blocked_on", "human", "⏸ waiting"),
            ],
            ..Config::naming(vec![drawing(
                "kadath",
                vec![
                    badge("metadata.delivery_pr", "⇢ kadath/{}"),
                    badge("metadata.epic", "▣ {}"),
                ],
            )])
        };

        assert_eq!(
            cfg.badges_for_project("kadath"),
            vec![
                badge("metadata.delivery_pr", "⇢ kadath/{}"),
                badge("metadata.delivery_pr", "⇢ {}"),
                matching("metadata.blocked_on", "human", "⏸ waiting"),
                badge("metadata.epic", "▣ {}"),
            ]
        );
    }

    /// The global list may name one key several times, matched on a different
    /// value each time. A project naming that key is tried ahead of the whole
    /// group and replaces none of it, so the project says what it wants for the
    /// values it names and keeps the shared wording for the rest.
    ///
    /// One entry ahead of two is what makes the precedence visible: the project
    /// draws its own words for `human`, and `dependency` still reaches the
    /// shared entry that reads it.
    #[test]
    fn a_projects_badge_is_tried_ahead_of_every_global_entry_for_its_key() {
        let cfg = Config {
            badges: vec![
                matching("metadata.blocked_on", "human", "⏸ waiting"),
                matching("metadata.blocked_on", "dependency", "⏸ blocked"),
            ],
            ..Config::naming(vec![drawing(
                "kadath",
                vec![matching("metadata.blocked_on", "human", "⏸ ask Ada")],
            )])
        };

        assert_eq!(
            cfg.badges_for_project("kadath"),
            vec![
                matching("metadata.blocked_on", "human", "⏸ ask Ada"),
                matching("metadata.blocked_on", "human", "⏸ waiting"),
                matching("metadata.blocked_on", "dependency", "⏸ blocked"),
            ]
        );
    }

    #[test]
    fn a_project_naming_no_badges_draws_the_global_list() {
        let cfg = Config {
            badges: vec![badge("metadata.delivery_pr", "⇢ {}")],
            ..Config::naming(vec![drawing("arkham", Vec::new())])
        };

        assert_eq!(
            cfg.badges_for_project("arkham"),
            vec![badge("metadata.delivery_pr", "⇢ {}")]
        );
    }

    /// The reader is told about the key they wrote, in the place they wrote
    /// it, rather than about the project that quietly lost it.
    ///
    /// `docs/configuration.md` quotes this sentence, so a badge that gains a
    /// key has to update both.
    #[test]
    fn a_project_key_written_after_its_badges_is_refused_by_the_badge() {
        let misplaced = r#"
[[projects]]
name = "kadath"

[[projects.badges]]
key    = "metadata.delivery_pr"
render = "⇢ kadath/{}"

path = "/home/user/dev/kadath"
"#;

        let refused = Config::from_toml(misplaced).expect_err("a badge has no path");

        let said = refused.to_string();
        assert_eq!(
            said.trim_end(),
            "unknown field `path`, expected one of `key`, `match`, `render`, `short`, `link`, \
             `colour`\n\
             in `projects.badges`"
        );
        assert!(!said.contains("missing field"), "{said}");
    }

    #[test]
    fn a_config_of_one_project_gets_every_default() {
        let cfg = Config::from_toml(ONE_PROJECT).expect("parses");

        assert_eq!(cfg.projects[0].credential_command, None);
        assert_eq!(cfg.roots, Roots::default());
        assert!(cfg.badges.is_empty());
        assert_eq!(cfg.anomalies.stale_claim_days, 30);
        assert_eq!(cfg.join.pane_key, "agent_pane");
        assert_eq!(cfg.changes.socket, None);
        assert_eq!(cfg.tui.refresh_seconds, 30);
        assert_eq!(cfg.tui.unanswered_after_seconds, 30);
        assert_eq!(cfg.tui.tail_refresh_millis, 250);
        assert_eq!(
            cfg.tui.wheel_notch_lines, 3,
            "three lines a notch is the convention a reader who says nothing gets"
        );
        assert_eq!(cfg.theme.background, Background::Dark);
    }

    /// `bdi` cannot see the reader's background, so a reader who says
    /// nothing is answered from the shipped default rather than from
    /// anything about the machine. That is what makes a wrong answer stable
    /// and attributable: it is wrong the same way on every terminal, and
    /// one documented key fixes it for good.
    #[test]
    fn an_undeclared_background_is_the_fallback() {
        assert_eq!(Theme::default().background, Background::Dark);
        assert_eq!(
            Config::from_toml(ONE_PROJECT)
                .expect("parses")
                .theme
                .background,
            Background::Dark
        );
    }

    /// And a background the reader misspelled is refused rather than read
    /// as the fallback. A typo answered silently with the default is the
    /// failure the key exists to remove, arriving through the key: the
    /// reader has said which background they are on, believes they have been
    /// heard, and has nothing on screen to tell them otherwise.
    #[test]
    fn a_background_that_is_not_one_of_the_two_is_refused() {
        let mistyped = format!("{ONE_PROJECT}\n[theme]\nbackground = \"Light\"\n");

        let refused =
            Config::from_toml(&mistyped).expect_err("a background bdi has no palette for");

        assert!(refused.to_string().contains("background"), "{refused}");
    }

    /// The interval is written in seconds and read as a duration; nothing
    /// downstream should be doing that arithmetic.
    #[test]
    fn the_refresh_interval_is_read_as_a_duration() {
        let cfg = Config::from_toml(EVERY_SECTION).expect("parses");

        assert_eq!(cfg.tui.refresh(), Duration::from_secs(5));
        assert_eq!(Tui::default().refresh(), Duration::from_secs(30));
    }

    /// The tail's interval is the one written in milliseconds, and it is
    /// read as a duration all the same.
    #[test]
    fn the_tails_interval_is_read_as_a_duration() {
        let cfg = Config::from_toml(EVERY_SECTION).expect("parses");

        assert_eq!(cfg.tui.tail_refresh(), Duration::from_millis(100));
        assert_eq!(Tui::default().tail_refresh(), Duration::from_millis(250));
    }

    /// The same for how long a collection may go unanswered, which is counted
    /// against a `chrono` clock rather than a `std` one because what it dates
    /// is the instant the collection was asked for.
    #[test]
    fn how_long_a_collection_may_go_unanswered_is_read_as_a_duration() {
        let cfg = Config::from_toml(EVERY_SECTION).expect("parses");

        assert_eq!(cfg.tui.unanswered_after(), TimeDelta::seconds(90));
        assert_eq!(Tui::default().unanswered_after(), TimeDelta::seconds(30));
    }

    /// The bound itself, taken off `chrono` rather than written down: the
    /// longest patience an interval can hold is read back as itself, and one
    /// second more is the longest interval there is.
    #[test]
    fn a_patience_longer_than_an_interval_can_hold_is_the_longest_there_is() {
        let longest: u64 = TimeDelta::MAX
            .num_seconds()
            .try_into()
            .expect("the longest interval there is runs forwards");

        assert_eq!(
            patient_for(longest).unanswered_after(),
            TimeDelta::seconds(TimeDelta::MAX.num_seconds())
        );
        assert_eq!(patient_for(longest + 1).unanswered_after(), TimeDelta::MAX);
    }

    /// The other limit, a thousandfold past the one above: a patience too
    /// large to be a signed count of seconds at all. No config file reaches
    /// it — TOML counts in signed 64-bit and refuses the literal — so what
    /// stands here is the crate's own `Tui`, whose fields anything may set,
    /// and nothing but a value up here tells the two limits apart.
    #[test]
    fn a_patience_too_large_to_count_in_signed_seconds_is_the_longest_there_is() {
        assert_eq!(patient_for(u64::MAX).unanswered_after(), TimeDelta::MAX);
    }

    /// The same rule as far out as a config file can put it: `i64::MAX`
    /// seconds, the largest integer TOML carries, already a thousandfold past
    /// what an interval holds — and the exact value the old fallback
    /// substituted for every value it caught.
    #[test]
    fn a_config_naming_a_patience_no_interval_can_hold_is_read_as_the_longest_there_is() {
        let cfg = Config::from_toml(&format!(
            "{ONE_PROJECT}[tui]\nunanswered_after_seconds = {}\n",
            i64::MAX
        ))
        .expect("parses");

        assert_eq!(cfg.tui.unanswered_after(), TimeDelta::MAX);
    }

    fn patient_for(seconds: u64) -> Tui {
        Tui {
            unanswered_after_seconds: seconds,
            ..Tui::default()
        }
    }

    /// The whole of a project entry: a path. A tracker is read in `bdi`'s own
    /// environment unless its entry says otherwise, so a config restates
    /// neither where a tracker is nor how to authenticate to it, however many
    /// it names.
    #[test]
    fn a_project_needs_only_a_path_however_many_the_config_names() {
        for spelling in [ONE_PROJECT, TWO_AMBIENT, ONE_CREDENTIALLED_ONE_AMBIENT] {
            let cfg = Config::from_toml(spelling).expect("a path is the whole of an entry");

            assert!(cfg.projects.iter().any(|p| p.credential_command.is_none()));
        }
    }

    /// The escape hatch survives, for a tracker outside direnv's reach.
    #[test]
    fn a_project_may_still_name_a_credential_command() {
        let cfg = Config::from_toml(ONE_CREDENTIALLED_ONE_AMBIENT).expect("parses");

        assert_eq!(
            cfg.projects[0].credential_command.as_deref(),
            Some("secret-tool lookup tracker arkham")
        );
    }

    /// A project that names no command is read in the environment `bdi`
    /// itself runs in, and nothing is run to reproduce a shell's.
    #[test]
    fn a_project_saying_nothing_about_its_environment_is_read_in_bdis_own() {
        let cfg = Config::from_toml(ONE_PROJECT).expect("parses");

        assert_eq!(cfg.projects[0].environment_command, None);
    }

    const ONE_ENTERED_WITH_DIRENV: &str = r#"
[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
environment_command = "direnv exec ."
"#;

    /// The wrapper is what the config names. What `bdi` runs inside it is
    /// `bdi`'s own business, so the reader writes no probe.
    #[test]
    fn a_project_may_name_the_command_that_gives_its_environment() {
        let cfg = Config::from_toml(ONE_ENTERED_WITH_DIRENV).expect("parses");

        assert_eq!(
            cfg.projects[0].environment_command,
            Some(Command::Line("direnv exec .".to_string()))
        );
    }

    const ENTERED_WITH_A_SPACE_IN_AN_ARGUMENT: &str = r#"
[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
environment_command = ["nix", "develop", ".#dev shell", "-c"]
"#;

    /// A line is split on whitespace and no quoting is honoured, so an
    /// argument holding a space is written as a list instead. Without this
    /// the config would name one argv and `bdi` would run another.
    #[test]
    fn an_argument_holding_a_space_is_written_as_a_list() {
        let cfg = Config::from_toml(ENTERED_WITH_A_SPACE_IN_AN_ARGUMENT).expect("parses");

        assert_eq!(
            cfg.projects[0]
                .environment_command
                .as_ref()
                .expect("the project named one")
                .words(),
            vec!["nix", "develop", ".#dev shell", "-c"],
        );
    }

    /// The common case is a line, and it is the same command either way
    /// round.
    #[test]
    fn a_line_and_a_list_of_its_words_name_the_same_command() {
        assert_eq!(
            Command::Line("direnv exec .".to_string()).words(),
            Command::Words(vec!["direnv".into(), "exec".into(), ".".into()]).words(),
        );
    }

    const ENTERED_SOME_OTHER_WAY: &str = r#"
[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
environment_command = "nix develop -c"
"#;

    /// Any wrapper that runs a command, not a list `bdi` holds. nix and mise
    /// are reached by a config that names them and by no change here, which
    /// is the whole of why the enum went.
    #[test]
    fn a_mechanism_bdi_has_never_heard_of_is_named_the_same_way() {
        let cfg = Config::from_toml(ENTERED_SOME_OTHER_WAY).expect("parses");

        assert_eq!(
            cfg.projects[0].environment_command,
            Some(Command::Line("nix develop -c".to_string()))
        );
    }

    /// An empty command is refused, both ways it can be written. `bdi`
    /// appends its own probe, so an empty one would run `env -0` alone and
    /// hand back the ambient environment — the project read in `bdi`'s
    /// environment while its config says otherwise, which is the silent
    /// wrong read the whole setting exists to close.
    #[test]
    fn an_environment_command_with_no_program_in_it_is_refused() {
        for empty in [r#""""#, r#"" ""#, "[]", r#"[""]"#, r#"["", "exec"]"#] {
            let err = Config::from_toml(&format!(
                r#"
[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
environment_command = {empty}
"#
            ))
            .unwrap_err()
            .to_string();

            assert!(err.contains("kadath"), "for {empty}, got: {err}");
            assert!(
                err.contains("environment_command"),
                "for {empty}, got: {err}"
            );
        }
    }

    const ENTERED_THE_OLD_WAY: &str = r#"
[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
environment = "direnv"
"#;

    /// A config written against the `environment` key is refused rather than
    /// ignored. serde drops an unknown field by default, so without this the
    /// setup that most needs the new key — one already naming direnv — would
    /// be read in `bdi`'s own environment instead, silently, which is the
    /// failure the key exists to stop.
    #[test]
    fn a_config_still_naming_the_key_this_replaced_is_refused() {
        let err = Config::from_toml(ENTERED_THE_OLD_WAY)
            .unwrap_err()
            .to_string();

        assert!(err.contains("environment"), "got: {err}");
    }

    const TWO_PROJECTS: &str = r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"
credential_command = "secret-tool lookup tracker arkham"

[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
credential_command = "cat /home/user/dev/kadath/.beads-password"
"#;

    const ROOT_IN_NO_CONFIGURED_PROJECT: &str = r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"
credential_command = "secret-tool lookup tracker arkham"

[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
credential_command = "cat /home/user/dev/kadath/.beads-password"

[roots.explicit]
cinder = ["c-1"]
"#;

    #[test]
    fn an_explicit_root_under_a_project_the_config_does_not_name_is_rejected() {
        let err = Config::from_toml(ROOT_IN_NO_CONFIGURED_PROJECT)
            .unwrap_err()
            .to_string();

        assert!(err.contains("cinder"), "got: {err}");
        assert!(err.contains("arkham"), "got: {err}");
        assert!(err.contains("kadath"), "got: {err}");
    }

    const ROOT_IN_A_SECOND_PROJECT: &str = r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"
credential_command = "secret-tool lookup tracker arkham"

[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
credential_command = "cat /home/user/dev/kadath/.beads-password"

[roots.explicit]
kadath = ["b-7"]
"#;

    const ONE_NAME_ON_TWO_PROJECTS: &str = r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"
credential_command = "secret-tool lookup tracker arkham"

[[projects]]
name = "arkham"
path = "/home/user/dev/arkham-fork"
credential_command = "cat /home/user/dev/arkham-fork/.beads-password"
"#;

    #[test]
    fn two_projects_of_one_name_are_rejected() {
        let err = Config::from_toml(ONE_NAME_ON_TWO_PROJECTS)
            .unwrap_err()
            .to_string();

        assert!(err.contains("arkham"), "got: {err}");
    }

    const ONE_NAME_ON_TWO_AMBIENT_PROJECTS: &str = r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"

[[projects]]
name = "arkham"
path = "/home/user/dev/arkham-fork"
"#;

    /// Both guards have something to say about this config, and only one of
    /// them says the thing that is actually wrong with it.
    #[test]
    fn a_repeated_name_is_reported_before_a_missing_credential() {
        let err = Config::from_toml(ONE_NAME_ON_TWO_AMBIENT_PROJECTS)
            .unwrap_err()
            .to_string();

        assert!(err.contains("arkham"), "got: {err}");
        assert!(!err.contains("credential_command"), "got: {err}");
    }

    fn two_projects() -> Config {
        Config::from_toml(TWO_PROJECTS).expect("the config parses")
    }

    #[test]
    fn a_qualified_root_from_the_command_line_goes_to_the_project_it_names() {
        let cfg = two_projects()
            .with_roots_named_on_the_command_line(&["kadath:b-7".to_string()])
            .expect("kadath is configured");

        assert_eq!(
            cfg.roots.explicit,
            BTreeMap::from([("kadath".to_string(), vec!["b-7".to_string()])])
        );
    }

    #[test]
    fn a_root_from_the_command_line_joins_those_the_config_names() {
        let cfg = Config::from_toml(EVERY_SECTION)
            .expect("the config parses")
            .with_roots_named_on_the_command_line(&["arkham:a-3".to_string()])
            .expect("arkham is configured");

        assert_eq!(
            cfg.roots.explicit["arkham"],
            ["a-1", "a-9", "a-3"],
            "the command line appends rather than replacing"
        );
    }

    #[test]
    fn a_bare_root_belongs_to_the_only_project_there_is() {
        let cfg = Config::from_toml(ONE_PROJECT)
            .expect("the config parses")
            .with_roots_named_on_the_command_line(&["b-7".to_string()])
            .expect("there is only one project it can mean");

        assert_eq!(
            cfg.roots.explicit,
            BTreeMap::from([("kadath".to_string(), vec!["b-7".to_string()])])
        );
    }

    #[test]
    fn a_bare_root_with_several_projects_configured_is_rejected() {
        let err = two_projects()
            .with_roots_named_on_the_command_line(&["b-7".to_string()])
            .unwrap_err()
            .to_string();

        assert!(err.contains("b-7"), "got: {err}");
        assert!(err.contains("arkham"), "got: {err}");
        assert!(err.contains("kadath"), "got: {err}");
    }

    #[test]
    fn a_root_from_the_command_line_naming_no_configured_project_is_rejected() {
        let err = two_projects()
            .with_roots_named_on_the_command_line(&["cinder:c-1".to_string()])
            .unwrap_err()
            .to_string();

        assert!(err.contains("cinder"), "got: {err}");
        assert!(err.contains("kadath"), "got: {err}");
    }

    #[test]
    fn a_root_that_is_all_colon_and_no_bead_is_rejected() {
        for named in ["arkham:", ":a-1", ":"] {
            let err = two_projects()
                .with_roots_named_on_the_command_line(&[named.to_string()])
                .unwrap_err()
                .to_string();

            assert!(err.contains(named), "got: {err}");
        }
    }

    /// The projects a config reads, by name and in its order.
    fn read_by(cfg: &Config) -> Vec<&str> {
        cfg.read().map(|p| p.name.as_str()).collect()
    }

    /// Scoping is what stops a reader working in one project paying for the
    /// others: every site that gathers reads the projects through `read`, so
    /// a project outside the scope is one nothing can go and read.
    #[test]
    fn a_scope_reads_only_the_projects_it_names() {
        let cfg = two_projects()
            .scoped_to(&["kadath".to_string()])
            .expect("kadath is configured");

        assert_eq!(read_by(&cfg), ["kadath"]);
    }

    /// The projects a scope leaves out stay known. A pane is placed by which
    /// configured project holds its directory, and a run that had forgotten
    /// the other projects would report every pane on another desktop as in a
    /// directory no project covers.
    #[test]
    fn a_scope_leaves_the_config_naming_every_project() {
        let cfg = two_projects()
            .scoped_to(&["kadath".to_string()])
            .expect("kadath is configured");

        assert_eq!(names_of(&cfg.projects), ["arkham", "kadath"]);
        assert!(cfg.reads("kadath"));
        assert!(!cfg.reads("arkham"));
    }

    /// The forest is drawn in the order the config names, so a scope is a
    /// filter over the config rather than a running order of its own.
    #[test]
    fn a_scope_leaves_the_projects_it_keeps_in_the_order_the_config_names() {
        let cfg = two_projects()
            .scoped_to(&["kadath".to_string(), "arkham".to_string()])
            .expect("both are configured");

        assert_eq!(read_by(&cfg), ["arkham", "kadath"]);
    }

    /// Asking for no particular project is not asking for none. What decides
    /// it is whether a scope was requested, never how many projects one
    /// selected — a `bdi` run with no arguments has to start.
    #[test]
    fn naming_no_project_leaves_every_project() {
        let cfg = two_projects()
            .scoped_to(&[])
            .expect("a scope of nothing scopes nothing");

        assert_eq!(read_by(&cfg), ["arkham", "kadath"]);
        assert_eq!(cfg.scope, Scope::Everything);
    }

    /// The directory `bdi` is started in decides the read set: the project
    /// holding it is the one read, and the scope says the directory chose.
    #[test]
    fn the_project_holding_the_directory_is_the_one_read() {
        let cfg =
            two_projects().scoped_to_the_project_holding(Path::new("/home/user/dev/kadath/src"));

        assert_eq!(read_by(&cfg), ["kadath"]);
        assert_eq!(
            cfg.scope,
            Scope::Directory {
                project: "kadath".to_string(),
                widened: Vec::new(),
            }
        );
        assert_eq!(
            names_of(&cfg.projects),
            ["arkham", "kadath"],
            "the projects the directory left out stay known"
        );
    }

    /// A repository inside another resolves to the inner one, which is the
    /// tie the join already breaks the same way when it places a pane.
    #[test]
    fn the_deepest_project_holding_the_directory_is_the_one_read() {
        let cfg = Config::from_toml(
            r#"
[[projects]]
name = "outer"
path = "/home/user/dev"

[[projects]]
name = "inner"
path = "/home/user/dev/inner"
"#,
        )
        .expect("the config parses")
        .scoped_to_the_project_holding(Path::new("/home/user/dev/inner/src"));

        assert_eq!(read_by(&cfg), ["inner"]);
    }

    /// Started outside every configured project there is nothing to scope to
    /// and nothing was asked for, so `bdi` reads everything, as it does today.
    #[test]
    fn a_directory_no_project_holds_leaves_every_project_read() {
        let cfg = two_projects().scoped_to_the_project_holding(Path::new("/home/user/elsewhere"));

        assert_eq!(read_by(&cfg), ["arkham", "kadath"]);
        assert_eq!(cfg.scope, Scope::Everything);
    }

    /// A positional under a project the directory left out widens the read
    /// set to that project: `bdi meadow:mdw-1` from another project's desktop
    /// reads both. Only an explicit `--project` makes that a contradiction.
    #[test]
    fn a_root_under_a_project_the_directory_left_out_widens_the_read_set() {
        let cfg = two_projects()
            .scoped_to_the_project_holding(Path::new("/home/user/dev/kadath"))
            .with_roots_named_on_the_command_line(&["arkham:a-1".to_string()])
            .expect("a root elsewhere widens a scope the directory chose");

        assert_eq!(read_by(&cfg), ["arkham", "kadath"]);
        assert_eq!(
            cfg.roots.explicit,
            BTreeMap::from([("arkham".to_string(), vec!["a-1".to_string()])])
        );
        assert_eq!(
            cfg.scope,
            Scope::Directory {
                project: "kadath".to_string(),
                widened: vec!["arkham".to_string()],
            }
        );
    }

    /// A bare id belongs to the one project being read, however the scope
    /// that left one was arrived at.
    #[test]
    fn a_bare_root_belongs_to_the_project_the_directory_chose() {
        let cfg = two_projects()
            .scoped_to_the_project_holding(Path::new("/home/user/dev/kadath"))
            .with_roots_named_on_the_command_line(&["b-7".to_string()])
            .expect("the directory leaves only kadath");

        assert_eq!(
            cfg.roots.explicit,
            BTreeMap::from([("kadath".to_string(), vec!["b-7".to_string()])])
        );
    }

    /// A scope that quietly selected less than it named would start `bdi` on
    /// a forest the reader did not ask for and could not tell from the one
    /// they did, so a name matching nothing is refused the way every other
    /// unknown project name here is.
    #[test]
    fn a_scope_naming_no_configured_project_is_rejected() {
        let err = two_projects()
            .scoped_to(&["cinder".to_string()])
            .unwrap_err()
            .to_string();

        assert!(err.contains("cinder"), "got: {err}");
        assert!(err.contains("arkham"), "got: {err}");
        assert!(err.contains("kadath"), "got: {err}");
    }

    /// A root the *config* names under an excluded project is not the
    /// contradiction the command line can state, and is allowed. What is
    /// refused is a scope and a positional asking for opposite things in one
    /// invocation; a config root is a standing preference this run overrides,
    /// and a tree the reader excluded is silent by the same rule that makes
    /// scoping itself silent.
    ///
    /// The entry stays where it is rather than being pruned. It is only ever
    /// read inside a project's own collection, so an entry under a project no
    /// collection reaches is never consulted, and taking it out would be work
    /// to reach the state leaving it alone already gives.
    #[test]
    fn a_configured_root_under_a_project_the_scope_left_out_is_kept_and_unread() {
        let cfg = Config::from_toml(ROOT_IN_A_SECOND_PROJECT)
            .expect("the config parses")
            .scoped_to(&["arkham".to_string()])
            .expect("a config root elsewhere is not a contradiction");

        assert_eq!(read_by(&cfg), ["arkham"]);
        assert_eq!(
            cfg.roots.explicit["kadath"],
            ["b-7"],
            "nothing reads it, so nothing has to take it out"
        );
    }

    /// A root in a project the scope left out asks `bdi` to draw a tree out
    /// of a tracker it was told not to read. Refusing says so; keeping it
    /// would put the root in `roots.explicit` under a project no collection
    /// ever reaches, where nothing reads it and nothing reports it.
    #[test]
    fn a_root_naming_a_project_the_scope_left_out_is_rejected() {
        let err = two_projects()
            .scoped_to(&["arkham".to_string()])
            .expect("arkham is configured")
            .with_roots_named_on_the_command_line(&["kadath:b-7".to_string()])
            .unwrap_err()
            .to_string();

        assert!(err.contains("kadath"), "got: {err}");
        assert!(err.contains("arkham"), "got: {err}");
    }

    /// What a bare id was ever ambiguous about is which of the trackers being
    /// read holds it, so a scope that leaves one project settles it.
    #[test]
    fn a_bare_root_belongs_to_the_only_project_a_scope_leaves() {
        let cfg = two_projects()
            .scoped_to(&["kadath".to_string()])
            .expect("kadath is configured")
            .with_roots_named_on_the_command_line(&["b-7".to_string()])
            .expect("the scope leaves only kadath");

        assert_eq!(
            cfg.roots.explicit,
            BTreeMap::from([("kadath".to_string(), vec!["b-7".to_string()])])
        );
    }

    #[test]
    fn config_without_projects_is_rejected() {
        let err = Config::from_toml("[roots]\n").unwrap_err();
        assert!(err.to_string().contains("no projects"), "got: {err}");
    }

    /// `[roots] metadata_keys` marked live work while discovery took only two
    /// statuses. Every unfinished bead is a root now, so a key could name
    /// nothing the statuses do not, and the field went with the feature. A
    /// config still naming it is told so, rather than having it read and
    /// ignored.
    #[test]
    fn a_config_naming_the_retired_metadata_keys_is_told_the_field_is_gone() {
        let err = Config::from_toml(
            r#"
[[projects]]
name = "arkham"
path = "/home/user/arkham"

[roots]
metadata_keys = ["working_topic"]
"#,
        )
        .unwrap_err();
        assert!(err.to_string().contains("metadata_keys"), "got: {err}");
        assert!(err.to_string().contains("gone"), "got: {err}");
    }

    #[test]
    fn badge_without_match_renders_any_value() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: None,
            render: "⇢ {}".to_string(),
            link: None,
            short: None,
            colour: None,
        };
        assert_eq!(b.apply("owner/repo#7"), Some("⇢ owner/repo#7".to_string()));
    }

    #[test]
    fn badge_with_match_is_selective() {
        let b = Badge {
            key: "metadata.blocked_on".to_string(),
            match_value: Some(pattern("human")),
            render: "⏸ waiting".to_string(),
            link: None,
            short: None,
            colour: None,
        };
        assert_eq!(b.apply("human"), Some("⏸ waiting".to_string()));
        assert_eq!(b.apply("dependency"), None);
    }

    /// What anchoring buys, stated over every pair a corpus makes rather
    /// than over one example. `match` was an exact-value test before it was
    /// a pattern, so a config written then names one value and no other:
    /// unanchored, `human` would begin drawing on `inhumane`.
    #[test]
    fn a_match_written_as_a_literal_draws_on_that_value_and_no_other() {
        let values = ["human", "dependency", "pr", "a", "owner/repo#7", ""];
        let anything_near = |v: &str| {
            [
                v.to_string(),
                format!("in{v}"),
                format!("{v}e"),
                format!("in{v}e"),
                format!("{v} {v}"),
                format!(" {v}"),
                format!("{v}\n"),
                v.to_uppercase(),
                String::new(),
            ]
        };

        for value in values {
            let badge = Badge {
                key: "metadata.blocked_on".to_string(),
                match_value: Some(pattern(value)),
                render: "drawn".to_string(),
                link: None,
                short: None,
                colour: None,
            };
            for candidate in values.iter().flat_map(|v| anything_near(v)) {
                assert_eq!(
                    badge.apply(&candidate).is_some(),
                    candidate == value,
                    "{value:?} against {candidate:?}"
                );
            }
        }
    }

    #[test]
    fn render_substitutes_a_capture_by_name_and_braces_by_the_whole_value() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: Some(pattern(r"[^/]+/(?<repo>[^#]+)#(?<number>[0-9]+)")),
            render: "⇢ {repo} #{number} of {}".to_string(),
            link: None,
            short: None,
            colour: None,
        };
        assert_eq!(
            b.apply("owner/arkham#7"),
            Some("⇢ arkham #7 of owner/arkham#7".to_string())
        );
        assert_eq!(b.apply("owner/arkham"), None);
    }

    #[test]
    fn braces_written_around_the_braces_are_drawn_around_the_value() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: None,
            render: "{{}}".to_string(),
            link: None,
            short: None,
            colour: None,
        };
        assert_eq!(b.apply("owner/repo#7"), Some("{owner/repo#7}".to_string()));
    }

    /// A value is placed, never read: what a capture took is not itself a
    /// template, however it happens to be spelled.
    #[test]
    fn a_value_spelled_like_a_placeholder_is_placed_and_not_read() {
        let b = Badge {
            key: "metadata.working_topic".to_string(),
            match_value: Some(pattern(r"(?<channel>[^/]+)/(?<topic>.+)")),
            render: "{channel} · {topic}".to_string(),
            link: None,
            short: None,
            colour: None,
        };
        assert_eq!(
            b.apply("{topic}/arkham"),
            Some("{topic} · arkham".to_string())
        );
    }

    /// A `link` is a template over the same captures `render` reads, which is
    /// what lets one global list build a URL out of a reference held as
    /// `owner/repo#number`: a `render` alone has no way to name a host.
    #[test]
    fn a_link_is_built_from_the_captures_render_reads() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: Some(pattern(r"(?<owner>[^/]+)/(?<repo>[^#]+)#(?<number>[0-9]+)")),
            render: "⇢ #{number}".to_string(),
            link: Some("https://forge.invalid/{owner}/{repo}/pull/{number}".to_string()),
            short: None,
            colour: None,
        };
        assert_eq!(b.apply("dunwich/arkham#7"), Some("⇢ #7".to_string()));
        assert_eq!(
            b.link_for("dunwich/arkham#7"),
            Some("https://forge.invalid/dunwich/arkham/pull/7".to_string())
        );
    }

    /// A capture the pattern names but this value never supplied leaves the
    /// badge with no link. A `delivery_pr` is held as a bare number as well
    /// as a qualified reference, and a URL built round an owner and a
    /// repository that were never there points somewhere else entirely.
    #[test]
    fn a_link_missing_one_of_its_captures_is_no_link_at_all() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: Some(pattern(
                r"(?:(?<owner>[^/]+)/(?<repo>[^#]+))?#?(?<number>[0-9]+)",
            )),
            render: "⇢ #{number}".to_string(),
            link: Some("https://forge.invalid/{owner}/{repo}/pull/{number}".to_string()),
            short: None,
            colour: None,
        };
        assert_eq!(b.apply("12"), Some("⇢ #12".to_string()));
        assert_eq!(b.link_for("12"), None);
        assert_eq!(
            b.link_for("dunwich/arkham#12"),
            Some("https://forge.invalid/dunwich/arkham/pull/12".to_string())
        );
    }

    /// And a name the pattern has no capture for at all, which is the same
    /// mistake written in the config rather than met in a value.
    #[test]
    fn a_link_naming_a_capture_the_pattern_never_had_is_no_link() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: Some(pattern(r"(?<number>[0-9]+)")),
            render: "⇢ #{number}".to_string(),
            link: Some("https://forge.invalid/{repo}/pull/{number}".to_string()),
            short: None,
            colour: None,
        };
        assert_eq!(b.link_for("12"), None);
    }

    #[test]
    fn a_badge_that_does_not_apply_points_nowhere() {
        let b = Badge {
            key: "metadata.blocked_on".to_string(),
            match_value: Some(pattern("human")),
            render: "⏸ waiting".to_string(),
            link: Some("https://forge.invalid/waiting".to_string()),
            short: None,
            colour: None,
        };
        assert_eq!(
            b.link_for("human"),
            Some("https://forge.invalid/waiting".to_string())
        );
        assert_eq!(b.link_for("dependency"), None);
    }

    #[test]
    fn a_badge_whose_config_names_no_link_points_nowhere() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: None,
            render: "⇢ {}".to_string(),
            link: None,
            short: None,
            colour: None,
        };
        assert_eq!(b.link_for("dunwich/arkham#7"), None);
    }

    /// A `short` is a template over the same captures, so a badge says itself
    /// twice at two lengths out of one reading of the value.
    #[test]
    fn a_short_form_is_built_from_the_captures_render_reads() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: Some(pattern(r"(?<owner>[^/]+)/(?<repo>[^#]+)#(?<number>[0-9]+)")),
            render: "⇢ {repo} #{number}".to_string(),
            short: Some("⇢ #{number}".to_string()),
            link: None,
            colour: None,
        };
        assert_eq!(b.apply("dunwich/arkham#7"), Some("⇢ arkham #7".to_string()));
        assert_eq!(b.short_for("dunwich/arkham#7"), Some("⇢ #7".to_string()));
    }

    /// The same rule a `link` follows, for the same reason. `⇢ #{number}`
    /// with no number is `⇢ #{number}` on the row, and a reader who met that
    /// where a reference belongs has been told nothing and shown a template.
    #[test]
    fn a_short_form_missing_one_of_its_captures_is_no_short_form_at_all() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: Some(pattern(
                r"(?:(?<owner>[^/]+)/)?(?<repo>[^#]+)#(?<number>[0-9]+)",
            )),
            render: "⇢ {repo} #{number}".to_string(),
            short: Some("⇢ {owner} #{number}".to_string()),
            link: None,
            colour: None,
        };
        assert_eq!(b.apply("arkham#12"), Some("⇢ arkham #12".to_string()));
        assert_eq!(b.short_for("arkham#12"), None);
        assert_eq!(
            b.short_for("dunwich/arkham#12"),
            Some("⇢ dunwich #12".to_string())
        );
    }

    #[test]
    fn a_badge_whose_config_names_no_short_form_has_none() {
        let b = Badge {
            key: "metadata.delivery_pr".to_string(),
            match_value: None,
            render: "⇢ {}".to_string(),
            short: None,
            link: None,
            colour: None,
        };
        assert_eq!(b.short_for("dunwich/arkham#7"), None);
    }

    /// A badge that does not apply to the value says nothing at either
    /// length: the short form is a second way to say this badge, not a badge
    /// of its own.
    #[test]
    fn a_badge_that_does_not_apply_has_no_short_form_either() {
        let b = Badge {
            key: "metadata.blocked_on".to_string(),
            match_value: Some(pattern("human")),
            render: "⏸ waiting".to_string(),
            short: Some("".to_string()),
            link: None,
            colour: None,
        };
        assert_eq!(b.short_for("human"), Some("".to_string()));
        assert_eq!(b.short_for("dependency"), None);
    }

    #[test]
    fn a_badges_short_form_is_read_out_of_the_config() {
        let cfg = Config::from_toml(&format!(
            r#"{ONE_PROJECT}
[[badges]]
key    = "metadata.delivery_pr"
match  = "(?<owner>[^/]+)/(?<repo>[^#]+)#(?<number>[0-9]+)"
render = "⇢ {{repo}} #{{number}}"
short  = "⇢ #{{number}}"
"#
        ))
        .expect("the config reads");

        assert_eq!(
            cfg.badges[0].short_for("dunwich/arkham#7"),
            Some("⇢ #7".to_string())
        );
    }

    #[test]
    fn a_badges_link_is_read_out_of_the_config() {
        let cfg = Config::from_toml(&format!(
            r#"{ONE_PROJECT}
[[badges]]
key    = "metadata.delivery_pr"
match  = "(?<owner>[^/]+)/(?<repo>[^#]+)#(?<number>[0-9]+)"
render = "⇢ #{{number}}"
link   = "https://forge.invalid/{{owner}}/{{repo}}/pull/{{number}}"
"#
        ))
        .expect("the config reads");

        assert_eq!(
            cfg.badges[0].link_for("dunwich/arkham#7"),
            Some("https://forge.invalid/dunwich/arkham/pull/7".to_string())
        );
    }

    /// The config is refused whole, which is what leaves the one in force
    /// standing and puts the reason at the foot of the screen.
    #[test]
    fn a_match_that_does_not_parse_refuses_the_config() {
        let err = Config::from_toml(&format!(
            r#"{ONE_PROJECT}
[[badges]]
key    = "metadata.blocked_on"
match  = "(unclosed"
render = "⏸ waiting"
"#
        ))
        .unwrap_err();
        assert!(err.to_string().contains("(unclosed"), "got: {err}");
    }

    #[test]
    fn a_badge_may_name_the_colour_the_row_draws_its_status_in() {
        let cfg = Config::from_toml(&format!(
            r#"{ONE_PROJECT}
[[badges]]
key    = "metadata.jira"
render = "{{}}"
colour = "status"
"#
        ))
        .expect("the config reads");

        assert_eq!(cfg.badges[0].colour, Some(Colour::Status));
    }

    /// Read through the config rather than off the `Slot` variants, because
    /// the name a reader writes is what `serde`'s renaming makes of the
    /// variant and a test over the variants would not see that.
    #[test]
    fn a_badge_may_name_any_slot_of_the_palette() {
        for (written, slot) in [
            ("agent", Slot::Agent),
            ("attention", Slot::Attention),
            ("identity", Slot::Identity),
            ("status_blocked", Slot::StatusBlocked),
            ("tier_finished", Slot::TierFinished),
            ("quiet", Slot::Quiet),
            ("code", Slot::Code),
            ("heading", Slot::Heading),
            ("link", Slot::Link),
        ] {
            let cfg = Config::from_toml(&format!(
                r#"{ONE_PROJECT}
[[badges]]
key    = "metadata.jira"
render = "{{}}"
colour = "{written}"
"#
            ))
            .unwrap_or_else(|err| panic!("{written:?} is a slot of the palette: {err}"));

            assert_eq!(cfg.badges[0].colour, Some(Colour::Slot(slot)));
        }
    }

    /// Every form `Color` reads, so a reader who knows one of them is not
    /// turned away for having picked the wrong one.
    #[test]
    fn a_badge_may_name_an_absolute_colour() {
        for (written, colour) in [
            ("#c71585", Color::Rgb(199, 21, 133)),
            ("red", Color::Red),
            ("light-blue", Color::LightBlue),
            ("12", Color::Indexed(12)),
        ] {
            let cfg = Config::from_toml(&format!(
                r#"{ONE_PROJECT}
[[badges]]
key    = "metadata.jira"
render = "{{}}"
colour = "{written}"
"#
            ))
            .unwrap_or_else(|err| panic!("{written:?} is a colour: {err}"));

            assert_eq!(cfg.badges[0].colour, Some(Colour::Absolute(colour)));
        }
    }

    /// `--snapshot-json` is read beside the config that produced it, so a
    /// colour leaves as the name that would bring it back. Both halves are
    /// written by hand here, which is what makes the round trip worth
    /// asserting.
    #[test]
    fn a_colour_is_written_back_as_a_name_that_reads_again() {
        for colour in [
            Colour::Status,
            Colour::Slot(Slot::TierStaffed),
            Colour::Absolute(Color::Rgb(199, 21, 133)),
            Colour::Absolute(Color::Indexed(12)),
            Colour::Absolute(Color::Red),
        ] {
            let written = serde_json::to_string(&colour).expect("a colour serialises");
            assert_eq!(
                serde_json::from_str::<Colour>(&written).expect("and reads again"),
                colour,
                "went out as {written}"
            );
        }
    }

    /// A colour the palette does not have is refused the way an unparseable
    /// pattern is: the config is turned down whole, and the name the reader
    /// wrote is in the reason so they can find it in their file.
    #[test]
    fn a_colour_the_palette_does_not_have_refuses_the_config() {
        let err = Config::from_toml(&format!(
            r#"{ONE_PROJECT}
[[badges]]
key    = "metadata.jira"
render = "{{}}"
colour = "chartreuse"
"#
        ))
        .unwrap_err();

        assert!(err.to_string().contains("chartreuse"), "got: {err}");
    }

    /// The working trees a project occupies are git's answer about a
    /// repository, so a config file cannot write them. It is now told so:
    /// the line was dropped in silence while unknown fields were, and a
    /// reader whose hand-written directory never arrives has no way to find
    /// out that the key was never theirs to set.
    #[test]
    fn a_config_cannot_write_the_worktrees_a_project_occupies() {
        let err = Config::from_toml(
            r#"
[[projects]]
name = "kadath"
path = "/home/user/dev/kadath"
worktrees = ["/home/user/anywhere-at-all"]
"#,
        )
        .unwrap_err()
        .to_string();

        assert!(err.contains("worktrees"), "got: {err}");
    }
}