repon 0.30.5

A terminal UI for the outer loop: seeing many git repos at once and acting on many in one gesture
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
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
//! The config document: its schema, its defaults, the deep merge and the four failure grades.
//!
//! `docs/spec/config.md` is the specification. This module implements the top-level bare
//! keys, `[refresh]`, `[fetch]`, `[auto_update]`, the `[[set]]`, `[[launcher]]` and
//! `[[action]]` fields in full. Turning a parsed `[[action]]` and its `[[action.steps]]`
//! into something `repon_core::Core::run_action` can run is
//! [`crate::action_palette::to_action_spec`]'s crossing; `shell = true` and merging a
//! step's `env` with the environment contract stay unresolved across it, since resolving
//! both is `executor::run_step`'s own job in `repon-core`.

use std::{
    collections::{BTreeMap, HashMap},
    env, fs, io,
    ops::Range,
    path::{Path, PathBuf},
    time::Duration,
};

use color_eyre::eyre::{Result, WrapErr, eyre};
use serde::Deserialize;

/// The vetted glyph set a terminal is asked to draw.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Glyphs {
    #[default]
    Full,
    Ascii,
}

/// `[refresh]`: metadata sweep cadence, staleness and the focus trigger.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct RefreshConfig {
    #[serde(with = "humantime_serde")]
    pub poll_interval: Duration,
    #[serde(with = "humantime_serde")]
    pub status_stale_after: Duration,
    pub on_focus: bool,
}

impl Default for RefreshConfig {
    fn default() -> Self {
        Self {
            poll_interval: Duration::from_secs(2),
            status_stale_after: Duration::from_secs(5 * 60),
            on_focus: true,
        }
    }
}

/// `[fetch]`: the periodic fetch.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct FetchConfig {
    pub enabled: bool,
    #[serde(with = "humantime_serde")]
    pub interval: Duration,
    pub concurrency: u32,
}

impl Default for FetchConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            interval: Duration::from_secs(5 * 60),
            concurrency: 4,
        }
    }
}

/// `[auto_update]`: fast-forward only, rides the fetch cycle rather than carrying its own
/// timer.
#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(default)]
pub struct AutoUpdateConfig {
    pub enabled: bool,
}

/// One `[[set]]`. `roots` has no top-level fallback: every Set names its own.
#[derive(Debug, Clone, Deserialize)]
pub struct SetConfig {
    pub name: toml::Spanned<String>,
    pub roots: Vec<String>,
    #[serde(default)]
    pub include: Option<Vec<String>>,
    #[serde(default)]
    pub exclude: Option<Vec<String>>,
    /// Names one declared `[[action]]` to run after a Refresh the user asked for while this
    /// Set is active, read ahead of the top-level `on_refresh` key
    /// ([actions.md](../../../../docs/spec/actions.md)'s "The refresh hook", amended by
    /// [0029](../../../../docs/adr/0029-an-on-refresh-action-runs-on-the-refresh-key-alone.md)).
    /// A name no `[[action]]` declares is [`Warning::SetOnRefreshNamesNoAction`] at load
    /// rather than an exit, naming this Set so a typo shared by two Sets still produces two
    /// distinguishable warnings.
    #[serde(default)]
    pub on_refresh: Option<String>,
    /// Names one declared `[[action]]` to run before `sync` acts on a row while this Set is
    /// active, read ahead of the top-level `before_sync` key, the identical resolution
    /// `on_refresh` above already uses
    /// ([repo-management.md](../../../../docs/spec/repo-management.md)'s "Hooks around
    /// sync",
    /// [0032](../../../../docs/adr/0032-hooks-around-a-built-in-fire-on-its-own-confirm-gate-never-its-completion.md)).
    /// A row whose hook fails never reaches `sync` at all. A name no `[[action]]` declares is
    /// [`Warning::SetBeforeSyncNamesNoAction`] at load rather than an exit, naming this Set so
    /// a typo shared by two Sets still produces two distinguishable warnings.
    #[serde(default)]
    pub before_sync: Option<String>,
    /// Names one declared `[[action]]` to run after `sync` fast-forwards a row while this Set
    /// is active, read ahead of the top-level `after_sync` key. A row's hook failing here
    /// never undoes the fast-forward it already performed. A name no `[[action]]` declares is
    /// [`Warning::SetAfterSyncNamesNoAction`] at load rather than an exit, for the same reason
    /// `before_sync`'s does.
    #[serde(default)]
    pub after_sync: Option<String>,
}

/// A `[[repo]]` entry: rung 1 of [default-branch.md](../../../../docs/spec/default-branch.md)'s
/// resolution chain and the exclude flag, matched by git common dir rather than this entry's
/// own `path` (a Worktree named directly by its own path still beats an entry it would
/// otherwise inherit; [`repo_overrides`] is where `path` crosses to the core to be resolved).
#[derive(Debug, Clone, Deserialize)]
pub struct RepoConfig {
    pub path: toml::Spanned<String>,
    #[serde(default)]
    pub default_branch: Option<String>,
    #[serde(default)]
    pub exclude: bool,
}

/// Turns the parsed `[[repo]]` entries into the crossing type `Core::start` reads
/// ([core-api.md](../../../../docs/spec/core-api.md)'s "What crosses from config"), `~`-expanding
/// `path` the same way every other path in this file is expanded. The core resolves each
/// `path` to its own git common dir itself, since opening a repository is its own work, not
/// this crate's.
pub fn repo_overrides(document: &Document) -> Vec<repon_core::RepoOverride> {
    document
        .repos
        .iter()
        .map(|repo| repon_core::RepoOverride {
            path: expand_home(repo.path.get_ref()),
            default_branch: repo.default_branch.clone(),
            excluded: repo.exclude,
        })
        .collect()
}

/// A `[[launcher]]` entry, per [config.md](../../../../docs/spec/config.md#launchers)'s
/// full field table. `args` and `from_env` are mutually exclusive argv sources;
/// `interactive` runs `shell = true`'s own `$SHELL -c` as `$SHELL -ic` instead, sourcing
/// the user's own rc file first; declaring it without `shell = true` is rejected at load
/// by [`reject_interactive_without_shell`], the same failure grade
/// [`reject_launchers_declaring_both_argv_forms`] already gives `args` and `from_env`
/// together. [`crate::launcher::resolve`] is where a declared entry turns into something
/// runnable.
#[derive(Debug, Clone, Deserialize)]
pub struct LauncherConfig {
    pub name: toml::Spanned<String>,
    #[serde(default)]
    pub args: Option<Vec<String>>,
    #[serde(default)]
    pub from_env: Option<String>,
    #[serde(default)]
    pub shell: bool,
    #[serde(default)]
    pub interactive: bool,
    #[serde(default = "default_launcher_takes_terminal")]
    pub takes_terminal: bool,
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    #[serde(default)]
    pub disabled: bool,
}

/// `true`, [config.md](../../../../docs/spec/config.md#launchers)'s stated default for
/// `takes_terminal`: every shipped default takes the terminal, so an entry that says nothing
/// gets the suspend-and-exec handoff. Read by `LauncherConfig::takes_terminal`'s
/// `#[serde(default = ...)]` rather than derived from `bool::default()`, since that would
/// silently keep the screen for a command that is about to draw over it.
fn default_launcher_takes_terminal() -> bool {
    true
}

/// One `[[action.steps]]` table, per [config.md](../../../../docs/spec/config.md#actions):
/// `args` is the argv vector (with `shell = true`, one element holding the command
/// string, the same convention [`LauncherConfig`] already uses), `env` is merged over
/// the guaranteed environment contract rather than replacing it. `interactive` runs the
/// shell through `$SHELL -ic` rather than `$SHELL -c`, sourcing the user's own rc file
/// first; declaring it without `shell = true` is rejected at load by
/// [`reject_interactive_without_shell`], the same failure grade
/// [`reject_launchers_declaring_both_argv_forms`] already gives a Launcher's own
/// mutually exclusive fields.
/// [`crate::action_palette::to_action_spec`] turns this into a [`repon_core::Step`];
/// `shell`, `interactive` and `env` cross over unresolved, the same way a Launcher's own
/// `shell`, `interactive` and `env` do in [`crate::launcher`].
#[derive(Debug, Clone, Deserialize)]
pub struct StepConfig {
    pub args: Vec<String>,
    #[serde(default)]
    pub shell: bool,
    #[serde(default)]
    pub interactive: bool,
    #[serde(default)]
    pub env: BTreeMap<String, String>,
}

/// `true`, [config.md](../../../../docs/spec/config.md#actions)'s stated default for
/// `confirm`: an Action asks before fanning out unless a config author opts out
/// explicitly. Read by [`ActionConfig::confirm`]'s `#[serde(default = ...)]` rather than
/// derived from `bool::default()`, since that would silently default to `false` and run
/// a destructive Action unprompted.
fn default_action_confirm() -> bool {
    true
}

/// `4`, [config.md](../../../../docs/spec/config.md#actions)'s stated default for
/// `concurrency`, the same number `fetch.concurrency` carries.
fn default_action_concurrency() -> u32 {
    4
}

/// An `[[action]]` entry, per [config.md](../../../../docs/spec/config.md#actions)'s full
/// field table: a unique `name`, an optional `description`, the required ordered `steps`,
/// `confirm` defaulting on, `concurrency` defaulting to four with no schema maximum
/// (`concurrency` is a bare `u32`, so the only ceiling is the type's own, never a
/// deliberate one this schema imposes), and the optional `when`.
/// [`crate::action_palette::to_action_spec`] turns this, plus its `steps`, into
/// `repon_core::ActionSpec` and `repon_core::Step`; `when` crosses too, parsed once there
/// into a `repon_core::Filter`, since `Core::run_action` now decides the fan-out by it
/// rather than only reporting a count over it
/// ([actions.md](../../../../docs/spec/actions.md)'s "The Selection and the gate").
#[derive(Debug, Clone, Deserialize)]
pub struct ActionConfig {
    pub name: toml::Spanned<String>,
    #[serde(default)]
    pub description: Option<String>,
    pub steps: Vec<StepConfig>,
    #[serde(default = "default_action_confirm")]
    pub confirm: bool,
    #[serde(default = "default_action_concurrency")]
    pub concurrency: u32,
    /// A predicate in the Filter grammar, held as the raw text the file carried: parsing it
    /// is `repon_core::Filter::parse`'s job and cannot fail, so there is no load-time check
    /// here and no failure grade to add ([config.md](../../../../docs/spec/config.md#actions)).
    #[serde(default)]
    pub when: Option<String>,
}

/// The document as the file declares it, deep-merged over the compiled defaults.
///
/// `#[serde(default)]` on every struct in this tree is the merge: a field absent from the
/// file falls back to that struct's `Default`, nested struct by nested struct.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct Document {
    pub theme: String,
    pub glyphs: Glyphs,
    pub show_worktrees: bool,
    pub show_submodules: bool,
    /// Whether `space` (`Action::ToggleSelection`) moves the cursor to the next row after
    /// toggling this one, through the same [`crate::app::App::move_cursor`] path `j` already
    /// drives ([keybindings.md](../../../../docs/spec/keybindings.md)'s `space` paragraph).
    /// It governs `space` alone: `v`'s range anchor, `a` and `A` are untouched. On the last
    /// row there is nothing to advance to, so the cursor stays put; nothing else in the list
    /// wraps.
    pub advance_on_toggle: bool,
    /// How long a Notice ([theming.md](../../../../docs/spec/theming.md)'s "Warnings and
    /// Notices") stays on the status row before its own timeout clears it. `"0s"` turns the
    /// timer off rather than turning Notices off, leaving the next keypress or a replacement
    /// as the only ways to clear one.
    #[serde(with = "humantime_serde")]
    pub notice_timeout: Duration,
    /// The name of the one declared `[[action]]` a Refresh the user asked for runs after
    /// it ([actions.md](../../../../docs/spec/actions.md)'s "The refresh hook"). A name no
    /// `[[action]]` declares is [`Warning::OnRefreshNamesNoAction`] at load rather than an
    /// exit, so a typo costs the hook and nothing else.
    pub on_refresh: Option<String>,
    /// The `[[action]]` a Set declaring no `before_sync` of its own falls through to, run
    /// before `sync` acts on a row
    /// ([repo-management.md](../../../../docs/spec/repo-management.md)'s "Hooks around
    /// sync"). A name no `[[action]]` declares is [`Warning::BeforeSyncNamesNoAction`] at
    /// load rather than an exit.
    pub before_sync: Option<String>,
    /// The `[[action]]` a Set declaring no `after_sync` of its own falls through to, run
    /// after `sync` fast-forwards a row. A name no `[[action]]` declares is
    /// [`Warning::AfterSyncNamesNoAction`] at load rather than an exit.
    pub after_sync: Option<String>,
    pub refresh: RefreshConfig,
    pub fetch: FetchConfig,
    pub auto_update: AutoUpdateConfig,
    #[serde(rename = "set")]
    pub sets: Vec<SetConfig>,
    #[serde(rename = "repo")]
    pub repos: Vec<RepoConfig>,
    #[serde(rename = "launcher")]
    pub launchers: Vec<LauncherConfig>,
    #[serde(rename = "action")]
    pub actions: Vec<ActionConfig>,
    /// `[keys]`'s own schema is [keybindings.md](../../../../docs/spec/keybindings.md)'s, and
    /// this crate's `keys` module ([`crate::keys::merge`]) is what parses it: captured whole
    /// here so it, and every key inside it, never trips this module's own unknown-key
    /// warning. [`crate::keys::merge`]'s own doc comment, not this one, is where this spec's
    /// one nesting exception for `[keys]` is recorded.
    pub keys: toml::Table,
}

impl Default for Document {
    fn default() -> Self {
        Self {
            theme: "default".to_string(),
            glyphs: Glyphs::default(),
            show_worktrees: true,
            show_submodules: false,
            advance_on_toggle: false,
            notice_timeout: Duration::from_secs(3),
            on_refresh: None,
            before_sync: None,
            after_sync: None,
            refresh: RefreshConfig::default(),
            fetch: FetchConfig::default(),
            auto_update: AutoUpdateConfig::default(),
            sets: Vec::new(),
            repos: Vec::new(),
            launchers: Vec::new(),
            actions: Vec::new(),
            keys: toml::Table::new(),
        }
    }
}

/// A load-time condition that does not stop the program.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Warning {
    /// A key in the file that no known field consumed, named by its dotted path.
    UnknownKey(String),
    /// A `[[set]]` named `all`, shadowing the implicit Set.
    SetNamedAll,
    /// A `[[set]]` glob that matched nothing under its roots.
    SetGlobMatchesNothing { set: String, glob: String },
    /// A `[[repo]]` path that does not exist on disk.
    RepoPathMatchesNothing { path: String },
    /// `auto_update.enabled` with `fetch.enabled = false`, which can never fire.
    AutoUpdateWithoutFetch,
    /// `on_refresh` naming an Action no `[[action]]` declares, so the hook can never fire.
    OnRefreshNamesNoAction { name: String },
    /// A `[[set]].on_refresh` naming an Action no `[[action]]` declares, so the hook can
    /// never fire while that Set is active. Carries the Set's own name so two Sets sharing
    /// the same bad value produce two distinguishable warnings rather than one that could
    /// belong to either.
    SetOnRefreshNamesNoAction { set: String, name: String },
    /// `before_sync` naming an Action no `[[action]]` declares, so `sync` never runs a
    /// pre-hook and proceeds unhooked rather than never running at all.
    BeforeSyncNamesNoAction { name: String },
    /// A `[[set]].before_sync` naming an Action no `[[action]]` declares, so `sync` runs
    /// unhooked while that Set is active. Carries the Set's own name for the same reason
    /// [`Warning::SetOnRefreshNamesNoAction`] does.
    SetBeforeSyncNamesNoAction { set: String, name: String },
    /// `after_sync` naming an Action no `[[action]]` declares, so a fast-forward runs with
    /// no post-hook rather than never running at all.
    AfterSyncNamesNoAction { name: String },
    /// A `[[set]].after_sync` naming an Action no `[[action]]` declares, so a fast-forward
    /// runs unhooked while that Set is active. Carries the Set's own name for the same
    /// reason [`Warning::SetOnRefreshNamesNoAction`] does.
    SetAfterSyncNamesNoAction { set: String, name: String },
}

impl std::fmt::Display for Warning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Warning::UnknownKey(path) => write!(f, "unknown config key `{path}`"),
            Warning::SetNamedAll => write!(
                f,
                "a [[set]] is named `all`, shadowing the implicit Set; the declaration wins"
            ),
            Warning::SetGlobMatchesNothing { set, glob } => {
                write!(
                    f,
                    "set `{set}`'s glob `{glob}` matches nothing under its roots"
                )
            }
            Warning::RepoPathMatchesNothing { path } => {
                write!(f, "[[repo]] path `{path}` matches no discovered entity")
            }
            Warning::AutoUpdateWithoutFetch => write!(
                f,
                "auto_update.enabled is true but fetch.enabled is false, so auto-update can never fire"
            ),
            Warning::OnRefreshNamesNoAction { name } => write!(
                f,
                "on_refresh names `{name}`, which no [[action]] declares, so nothing runs after a refresh"
            ),
            Warning::SetOnRefreshNamesNoAction { set, name } => write!(
                f,
                "set `{set}`'s on_refresh names `{name}`, which no [[action]] declares, so \
                 nothing runs after a refresh while `{set}` is active"
            ),
            Warning::BeforeSyncNamesNoAction { name } => write!(
                f,
                "before_sync names `{name}`, which no [[action]] declares, so sync runs with \
                 no pre-hook"
            ),
            Warning::SetBeforeSyncNamesNoAction { set, name } => write!(
                f,
                "set `{set}`'s before_sync names `{name}`, which no [[action]] declares, so \
                 sync runs with no pre-hook while `{set}` is active"
            ),
            Warning::AfterSyncNamesNoAction { name } => write!(
                f,
                "after_sync names `{name}`, which no [[action]] declares, so sync runs with \
                 no post-hook"
            ),
            Warning::SetAfterSyncNamesNoAction { set, name } => write!(
                f,
                "set `{set}`'s after_sync names `{name}`, which no [[action]] declares, so \
                 sync runs with no post-hook while `{set}` is active"
            ),
        }
    }
}

/// A parsed document plus the warnings its load raised.
#[derive(Debug)]
pub struct Loaded {
    pub document: Document,
    pub warnings: Vec<Warning>,
    /// `true` only when no file was read at all: the default path absent, or a
    /// `REPON_CONFIG` directory holding no `config.toml`
    /// ([config.md](../../../../docs/spec/config.md#reading-and-failing)'s "Zero config").
    /// `state.toml` keys its scope by this: the active Set's name is `all` either way once a
    /// zero-config document declares no Set of its own, so two different working
    /// directories both running zero-config would otherwise restore each other's session
    /// state ([0006](../../../../docs/adr/0006-no-git-state-cache-session-state-by-name.md)).
    /// `false` for a file that exists but happens to declare no `[[set]]`, since that Set's
    /// name still comes from a document a user can go and edit.
    pub zero_config: bool,
}

/// The pasteable, annotated example config from `config.md`'s "An annotated example"
/// section, shipped as its own file beside this module rather than pulled from
/// [config.md](../../../../docs/spec/config.md) with `include_str!`: `docs/` sits outside
/// this crate's directory, so it is not among the files `cargo package` ships, and
/// `repon config --example` must work for an installed binary with no `docs/` directory
/// alongside it. A test below reads the specification at test time and asserts this file
/// stays byte-identical to its fenced block, so the two cannot drift apart.
const EXAMPLE_CONFIG: &str = include_str!("example.toml");

/// The pasteable, annotated example config `repon config --example` prints.
pub fn annotated_example() -> &'static str {
    EXAMPLE_CONFIG
}

/// Reads and parses `path`. A missing file is not an error: it resolves to the compiled
/// defaults, `glyphs` included, with one implicit Set, `all`, rooted at the working directory.
///
/// `glyphs`'s own default is conditional ([`conditional_glyphs_default`]); the real `TERM`
/// is read here, once, and handed down as plain data, so nothing below this point touches
/// the environment.
pub fn load(path: &Path) -> Result<Loaded> {
    load_with_term(path, term_signal().as_deref())
}

/// The one environment read this decision ever makes, isolated so [`load`] stays a thin
/// wrapper and every other function in this module stays a pure function of its input.
fn term_signal() -> Option<String> {
    env::var("TERM").ok()
}

/// [`load`] with `TERM` passed in rather than read live, which is what lets a test drive
/// both the Linux-console branch and the everything-else branch without calling
/// `std::env::set_var` (unsafe on this edition, and racy across threads).
fn load_with_term(path: &Path, term: Option<&str>) -> Result<Loaded> {
    let text = match fs::read_to_string(path) {
        Ok(text) => text,
        Err(err) if err.kind() == io::ErrorKind::NotFound => {
            let mut document = Document {
                glyphs: conditional_glyphs_default(term),
                ..Document::default()
            };
            document.sets.push(implicit_all_set(working_directory()));
            return Ok(Loaded {
                document,
                warnings: Vec::new(),
                zero_config: true,
            });
        }
        Err(err) => {
            return Err(err).wrap_err_with(|| format!("could not read {}", path.display()));
        }
    };
    parse_with_term(&text, path, term)
}

/// [`parse_with_term`] with no `TERM` signal, which is `full` either way: every existing test
/// below that does not care about the conditional default calls this, unchanged. Test-only:
/// nothing in the running program parses a document without an explicit `TERM` signal to
/// resolve `glyphs` against.
#[cfg(test)]
fn parse(text: &str, path: &Path) -> Result<Loaded> {
    parse_with_term(text, path, None)
}

/// `ascii` when the process is talking to the Linux virtual console (`TERM=linux`), `full`
/// otherwise ([ADR 0020](../../../../docs/adr/0020-the-ascii-glyph-set-is-vetted-over-the-row-interior.md),
/// and `docs/spec/config.md`'s `glyphs` entry). That console's kernel fallback table is fixed
/// and knowable, which is what makes this one check defensible; a table of terminal emulator
/// names is refused, because an emulator's own substitution table is neither fixed nor
/// knowable the way the console's is. This is the only signal ever consulted for this
/// decision: no second `TERM` value and no second environment variable, a claim
/// `glyphs_default_reads_exactly_one_term_value_and_no_other_variable` below checks against
/// this function's own source.
fn conditional_glyphs_default(term: Option<&str>) -> Glyphs {
    if term == Some("linux") {
        Glyphs::Ascii
    } else {
        Glyphs::Full
    }
}

/// Whether the file's own top-level table names `glyphs` at all, independent of what value the
/// struct-level `#[serde(default)]` deep merge already gave it: an absent key and one written
/// explicitly as the compiled default both deserialize to the same `Glyphs::Full`, so telling
/// them apart (needed to pin an explicit `full` against the conditional default flipping it)
/// means asking the source text directly rather than the already-merged `Document`.
fn glyphs_key_declared(text: &str) -> bool {
    text.parse::<toml::Table>()
        .map(|table| table.contains_key("glyphs"))
        .unwrap_or(false)
}

fn parse_with_term(text: &str, path: &Path, term: Option<&str>) -> Result<Loaded> {
    let deserializer =
        toml::de::Deserializer::parse(text).map_err(|err| render_error(path, text, &err))?;

    let mut unknown_paths = Vec::new();
    let mut document: Document = serde_ignored::deserialize(deserializer, |ignored| {
        unknown_paths.push(ignored.to_string())
    })
    .map_err(|err| render_error(path, text, &err))?;

    reject_duplicate_names(&document, text, path)?;
    reject_reserved_action_names(&document, text, path)?;
    reject_launchers_declaring_both_argv_forms(&document, text, path)?;
    reject_interactive_without_shell(&document, text, path)?;

    // An explicit `glyphs` pins the value in both directions (docs/spec/config.md's `glyphs`
    // entry): only an absent key defers to the conditional default.
    if !glyphs_key_declared(text) {
        document.glyphs = conditional_glyphs_default(term);
    }

    let mut warnings: Vec<Warning> = unknown_paths.into_iter().map(Warning::UnknownKey).collect();
    warnings.extend(cross_key_warnings(&document));

    if document.sets.is_empty() {
        document.sets.push(implicit_all_set(working_directory()));
    }

    Ok(Loaded {
        document,
        warnings,
        zero_config: false,
    })
}

/// The resolved current working directory, or `.` when it cannot be read: the implicit
/// `all` Set's own root, and the same value [`crate::app`] keys `state.toml`'s scope by when
/// running with no config at all.
pub(crate) fn working_directory() -> PathBuf {
    env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}

fn implicit_all_set(root: PathBuf) -> SetConfig {
    SetConfig {
        name: toml::Spanned::new(0..0, "all".to_string()),
        roots: vec![root.to_string_lossy().into_owned()],
        include: None,
        exclude: None,
        on_refresh: None,
        before_sync: None,
        after_sync: None,
    }
}

/// Renders a `toml::de::Error` from its own `.message()` and `.span()`, per
/// [config.md](../../../../docs/spec/config.md#reading-and-failing), rather than from its
/// `Display` text.
fn render_error(path: &Path, input: &str, err: &toml::de::Error) -> color_eyre::eyre::Error {
    parse_error(path, input, err.message(), err.span())
}

fn parse_error(
    path: &Path,
    input: &str,
    message: &str,
    span: Option<Range<usize>>,
) -> color_eyre::eyre::Error {
    match span.map(|span| line_col(input, span.start)) {
        Some((line, column)) => eyre!(
            "could not parse {}: {message} at line {line}, column {column}",
            path.display()
        ),
        None => eyre!("could not parse {}: {message}", path.display()),
    }
}

/// 1-based line and column of `offset` into `input`, matching `toml`'s own convention.
fn line_col(input: &str, offset: usize) -> (usize, usize) {
    let mut offset = offset.min(input.len());
    while offset > 0 && !input.is_char_boundary(offset) {
        offset -= 1;
    }
    let mut line = 1;
    let mut column = 1;
    for ch in input[..offset].chars() {
        if ch == '\n' {
            line += 1;
            column = 1;
        } else {
            column += 1;
        }
    }
    (line, column)
}

/// TOML's array-of-tables cannot itself catch a duplicate identity value, so a document
/// with two `[[set]]`s of the same name (or two `[[repo]]`s of the same path, and so on)
/// parses cleanly; this rejects it at load, naming the second occurrence's line.
fn reject_duplicate_names(document: &Document, input: &str, path: &Path) -> Result<()> {
    if let Some((value, span)) = duplicate(&document.sets, |set| &set.name) {
        return Err(parse_error(
            path,
            input,
            &duplicate_message("set name", &value),
            Some(span),
        ));
    }
    if let Some((value, span)) = duplicate(&document.repos, |repo| &repo.path) {
        return Err(parse_error(
            path,
            input,
            &duplicate_message("repo path", &value),
            Some(span),
        ));
    }
    if let Some((value, span)) = duplicate(&document.launchers, |launcher| &launcher.name) {
        return Err(parse_error(
            path,
            input,
            &duplicate_message("launcher name", &value),
            Some(span),
        ));
    }
    if let Some((value, span)) = duplicate(&document.actions, |action| &action.name) {
        return Err(parse_error(
            path,
            input,
            &duplicate_message("action name", &value),
            Some(span),
        ));
    }
    Ok(())
}

/// The one sentence every duplicate-identity failure in this file is written from, so a
/// second producer of the same grade cannot phrase it differently.
fn duplicate_message(what: &str, value: &str) -> String {
    format!("duplicate {what} `{value}`")
}

/// The built-in management operations' names are reserved
/// ([repo-management.md](../../../../docs/spec/repo-management.md)): a config-defined
/// `[[action]]` taking one fails the load rather than one shadowing the other, and it fails
/// with the message a second `[[action]]` of the same name already produces, since a name
/// already taken is what has gone wrong either way. The reserved set is
/// [`crate::management::OPERATIONS`] itself, never a second list here.
fn reject_reserved_action_names(document: &Document, input: &str, path: &Path) -> Result<()> {
    for action in &document.actions {
        let name = action.name.get_ref();
        if crate::management::Operation::from_name(name).is_some() {
            return Err(parse_error(
                path,
                input,
                &duplicate_message("action name", name),
                Some(action.name.span()),
            ));
        }
    }
    Ok(())
}

/// `args` and `from_env` are declared mutually exclusive
/// ([config.md](../../../../docs/spec/config.md#launchers)): a `[[launcher]]` naming both is
/// rejected at load rather than one silently winning, the same failure grade as a duplicate
/// name above. Neither field carries its own span, so the error points at the entry's `name`,
/// the nearest position this document keeps.
fn reject_launchers_declaring_both_argv_forms(
    document: &Document,
    input: &str,
    path: &Path,
) -> Result<()> {
    for launcher in &document.launchers {
        if launcher.args.is_some() && launcher.from_env.is_some() {
            return Err(parse_error(
                path,
                input,
                &format!(
                    "launcher `{}` declares both `args` and `from_env`, which are mutually exclusive",
                    launcher.name.get_ref()
                ),
                Some(launcher.name.span()),
            ));
        }
    }
    Ok(())
}

/// `interactive` sources the user's own rc file by running through `$SHELL -ic` rather
/// than `$SHELL -c`, so it only means anything alongside `shell = true`
/// ([config.md](../../../../docs/spec/config.md#actions)'s `interactive` sentence): a
/// `[[launcher]]` or `[[action.steps]]` entry declaring `interactive = true` without
/// `shell = true` is rejected at load, naming both keys, rather than silently ignored.
/// `StepConfig` carries no span of its own, so a step's error points at its own action's
/// `name`, the nearest position this document keeps.
fn reject_interactive_without_shell(document: &Document, input: &str, path: &Path) -> Result<()> {
    for launcher in &document.launchers {
        if launcher.interactive && !launcher.shell {
            return Err(parse_error(
                path,
                input,
                &format!(
                    "launcher `{}` declares `interactive = true` without `shell = true`",
                    launcher.name.get_ref()
                ),
                Some(launcher.name.span()),
            ));
        }
    }
    for action in &document.actions {
        for step in &action.steps {
            if step.interactive && !step.shell {
                return Err(parse_error(
                    path,
                    input,
                    &format!(
                        "action `{}`'s step declares `interactive = true` without `shell = true`",
                        action.name.get_ref()
                    ),
                    Some(action.name.span()),
                ));
            }
        }
    }
    Ok(())
}

fn duplicate<'a, T>(
    items: &'a [T],
    key: impl Fn(&'a T) -> &'a toml::Spanned<String>,
) -> Option<(String, Range<usize>)> {
    let mut seen: HashMap<&str, ()> = HashMap::new();
    for item in items {
        let spanned = key(item);
        let value = spanned.get_ref().as_str();
        if seen.insert(value, ()).is_some() {
            return Some((value.to_string(), spanned.span()));
        }
    }
    None
}

/// The one resolution chain every hook field in this file shares: the Set named
/// `active_set_name`'s own field first, then the top-level key, then no hook. A pure
/// function of `document` and the active Set's own name rather than something resolved once
/// and cached, since the active Set changes at runtime under `s` and `1` to `9` and a hook
/// latched at startup would keep firing the Set the process launched with.
/// [`resolve_on_refresh_name`], [`resolve_before_sync_name`] and [`resolve_after_sync_name`]
/// are this same chain over three different fields, so the rule cannot drift between them.
fn resolve_hook_name<'a>(
    document: &'a Document,
    active_set_name: &str,
    set_field: impl Fn(&'a SetConfig) -> Option<&'a str>,
    document_field: Option<&'a str>,
) -> Option<&'a str> {
    document
        .sets
        .iter()
        .find(|set| set.name.get_ref() == active_set_name)
        .and_then(set_field)
        .or(document_field)
}

/// [config.md](../../../../docs/spec/config.md)'s "Sets" resolution chain for `on_refresh`,
/// amending [0029](../../../../docs/adr/0029-an-on-refresh-action-runs-on-the-refresh-key-alone.md).
/// The app crate calls this fresh every time a Refresh fires
/// ([`crate::app::App::on_refresh_action`]).
pub(crate) fn resolve_on_refresh_name<'a>(
    document: &'a Document,
    active_set_name: &str,
) -> Option<&'a str> {
    resolve_hook_name(
        document,
        active_set_name,
        |set| set.on_refresh.as_deref(),
        document.on_refresh.as_deref(),
    )
}

/// [repo-management.md](../../../../docs/spec/repo-management.md)'s "Hooks around sync"
/// resolution chain for `before_sync`, the identical rule `resolve_on_refresh_name` uses over
/// a different field
/// ([0032](../../../../docs/adr/0032-hooks-around-a-built-in-fire-on-its-own-confirm-gate-never-its-completion.md)).
/// The app crate calls this fresh every time `sync`'s confirm gate is accepted
/// ([`crate::app::App::before_sync_action`]).
pub(crate) fn resolve_before_sync_name<'a>(
    document: &'a Document,
    active_set_name: &str,
) -> Option<&'a str> {
    resolve_hook_name(
        document,
        active_set_name,
        |set| set.before_sync.as_deref(),
        document.before_sync.as_deref(),
    )
}

/// [repo-management.md](../../../../docs/spec/repo-management.md)'s "Hooks around sync"
/// resolution chain for `after_sync`, the identical rule `resolve_on_refresh_name` uses over a
/// different field. The app crate calls this fresh every time `sync`'s confirm gate is
/// accepted ([`crate::app::App::after_sync_action`]).
pub(crate) fn resolve_after_sync_name<'a>(
    document: &'a Document,
    active_set_name: &str,
) -> Option<&'a str> {
    resolve_hook_name(
        document,
        active_set_name,
        |set| set.after_sync.as_deref(),
        document.after_sync.as_deref(),
    )
}

/// The checks [config.md](../../../../docs/spec/config.md#cross-key-validity) runs at
/// load, each a warning rather than an exit. Run against the sets as declared, before the
/// implicit `all` Set (if any) is added, since that Set always matches everything under the
/// working directory and warning about it would say nothing useful.
fn cross_key_warnings(document: &Document) -> Vec<Warning> {
    let mut warnings = Vec::new();

    if document.auto_update.enabled && !document.fetch.enabled {
        warnings.push(Warning::AutoUpdateWithoutFetch);
    }

    if let Some(name) = document.on_refresh.as_ref().filter(|name| {
        !document
            .actions
            .iter()
            .any(|action| action.name.get_ref() == *name)
    }) {
        warnings.push(Warning::OnRefreshNamesNoAction { name: name.clone() });
    }

    if let Some(name) = document.before_sync.as_ref().filter(|name| {
        !document
            .actions
            .iter()
            .any(|action| action.name.get_ref() == *name)
    }) {
        warnings.push(Warning::BeforeSyncNamesNoAction { name: name.clone() });
    }

    if let Some(name) = document.after_sync.as_ref().filter(|name| {
        !document
            .actions
            .iter()
            .any(|action| action.name.get_ref() == *name)
    }) {
        warnings.push(Warning::AfterSyncNamesNoAction { name: name.clone() });
    }

    for set in &document.sets {
        let name = set.name.get_ref();
        if name == "all" {
            warnings.push(Warning::SetNamedAll);
        }
        if let Some(on_refresh) = set.on_refresh.as_ref().filter(|on_refresh| {
            !document
                .actions
                .iter()
                .any(|action| action.name.get_ref().as_str() == on_refresh.as_str())
        }) {
            warnings.push(Warning::SetOnRefreshNamesNoAction {
                set: name.clone(),
                name: on_refresh.clone(),
            });
        }
        if let Some(before_sync) = set.before_sync.as_ref().filter(|before_sync| {
            !document
                .actions
                .iter()
                .any(|action| action.name.get_ref().as_str() == before_sync.as_str())
        }) {
            warnings.push(Warning::SetBeforeSyncNamesNoAction {
                set: name.clone(),
                name: before_sync.clone(),
            });
        }
        if let Some(after_sync) = set.after_sync.as_ref().filter(|after_sync| {
            !document
                .actions
                .iter()
                .any(|action| action.name.get_ref().as_str() == after_sync.as_str())
        }) {
            warnings.push(Warning::SetAfterSyncNamesNoAction {
                set: name.clone(),
                name: after_sync.clone(),
            });
        }
        for glob in set.include.iter().chain(&set.exclude).flatten() {
            if !set_glob_matches_something(set, glob) {
                warnings.push(Warning::SetGlobMatchesNothing {
                    set: name.clone(),
                    glob: glob.clone(),
                });
            }
        }
    }

    for repo in &document.repos {
        let path = repo.path.get_ref();
        if !expand_home(path).exists() {
            warnings.push(Warning::RepoPathMatchesNothing { path: path.clone() });
        }
    }

    warnings
}

/// `~` expansion, matching [config.md](../../../../docs/spec/config.md#sets)'s `roots` and
/// `[[repo]]`'s `path`.
pub(crate) fn expand_home(path: &str) -> PathBuf {
    if let Some(rest) = path.strip_prefix("~/") {
        if let Ok(home) = etcetera::home_dir() {
            return home.join(rest);
        }
    } else if path == "~"
        && let Ok(home) = etcetera::home_dir()
    {
        return home;
    }
    PathBuf::from(path)
}

/// A generous cap on directory entries visited per glob, so a pathological root cannot hang
/// a load; this is a load-time plausibility check, not the bounded discovery walk itself
/// (that is [discovery.md](../../../../docs/spec/discovery.md)'s).
const MATCH_PROBE_ENTRY_CAP: usize = 20_000;

fn set_glob_matches_something(set: &SetConfig, pattern: &str) -> bool {
    let Ok(glob) = globset::Glob::new(pattern) else {
        // An unparsable glob is a bad value in a known key; that failure grade belongs to
        // the caller that first deserializes `include`/`exclude` as globs. Here, treat it
        // as matching nothing so the file still gets a warning rather than silence.
        return false;
    };
    let matcher = glob.compile_matcher();
    set.roots
        .iter()
        .any(|root| walk_matches(&expand_home(root), &matcher))
}

/// Case-sensitive against the absolute path, per
/// [config.md](../../../../docs/spec/config.md#sets). Stops descending at a directory
/// holding `.git`, mirroring discovery's own boundary rule.
fn walk_matches(root: &Path, matcher: &globset::GlobMatcher) -> bool {
    let mut stack = vec![root.to_path_buf()];
    let mut visited = 0usize;
    while let Some(dir) = stack.pop() {
        if matcher.is_match(&dir) {
            return true;
        }
        if dir.join(".git").exists() {
            continue;
        }
        let Ok(entries) = fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            visited += 1;
            if visited > MATCH_PROBE_ENTRY_CAP {
                return false;
            }
            let path = entry.path();
            if matcher.is_match(&path) {
                return true;
            }
            if path.is_dir() {
                stack.push(path);
            }
        }
    }
    false
}

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

    fn parse_ok(text: &str) -> Loaded {
        parse(text, Path::new("config.toml")).expect("expected the document to parse")
    }

    fn parse_err(text: &str) -> String {
        parse(text, Path::new("config.toml"))
            .expect_err("expected the document to fail to parse")
            .to_string()
    }

    /// [`parse`] with the `TERM` signal named explicitly, for the tests below that exercise
    /// `glyphs`'s conditional default directly rather than through [`parse_ok`]'s fixed
    /// "not the Linux console" signal.
    fn parse_ok_with_term(text: &str, term: Option<&str>) -> Loaded {
        parse_with_term(text, Path::new("config.toml"), term)
            .expect("expected the document to parse")
    }

    // The five bare top-level keys parse with their exact stated defaults. `glyphs` here
    // reads its non-Linux-console default, since `parse_ok` fixes `TERM` to `None`; the
    // conditional half is its own test below.
    #[test]
    fn an_empty_file_carries_the_stated_top_level_defaults() {
        let loaded = parse_ok("");
        assert_eq!(loaded.document.theme, "default");
        assert_eq!(loaded.document.glyphs, Glyphs::Full);
        assert!(loaded.document.show_worktrees);
        assert!(!loaded.document.show_submodules);
        assert_eq!(loaded.document.notice_timeout, Duration::from_secs(3));
    }

    /// ADR 0020 / this ticket's decision: an absent `glyphs` key defaults to `ascii` on the
    /// Linux console's own `TERM=linux` and to `full` for every other `TERM`, including one
    /// that merely contains "linux" as a substring (a mutation this negative case would let
    /// through if the comparison ever loosened to a `contains` check).
    #[test]
    fn an_absent_glyphs_key_defaults_to_ascii_on_term_linux_and_full_otherwise() {
        assert_eq!(
            parse_ok_with_term("", Some("linux")).document.glyphs,
            Glyphs::Ascii
        );

        for term in [
            None,
            Some(""),
            Some("xterm-256color"),
            Some("screen"),
            Some("tmux-256color"),
            Some("linux-256color"),
            Some("LINUX"),
        ] {
            assert_eq!(
                parse_ok_with_term("", term).document.glyphs,
                Glyphs::Full,
                "expected full for TERM={term:?}"
            );
        }
    }

    /// The whole point of a conditional default is that an explicit value still wins, in
    /// both directions: `full` written under `TERM=linux` is not overridden to `ascii`, and
    /// `ascii` written with no Linux console in sight is not overridden to `full`.
    #[test]
    fn an_explicit_glyphs_key_pins_the_value_against_the_conditional_default_either_way() {
        let pinned_full = parse_ok_with_term("glyphs = \"full\"\n", Some("linux"));
        assert_eq!(pinned_full.document.glyphs, Glyphs::Full);

        let pinned_ascii = parse_ok_with_term("glyphs = \"ascii\"\n", None);
        assert_eq!(pinned_ascii.document.glyphs, Glyphs::Ascii);
    }

    /// The zero-config path (no file at all) applies the same conditional default as a file
    /// that merely omits the key, since [`load_with_term`]'s missing-file branch builds its
    /// `Document` without going through [`parse_with_term`] at all.
    #[test]
    fn a_missing_file_still_applies_the_conditional_glyphs_default() {
        let missing = Path::new("/does/not/exist/repon-glyphs-default-test/config.toml");

        assert_eq!(
            load_with_term(missing, Some("linux"))
                .expect("a missing file is not an error")
                .document
                .glyphs,
            Glyphs::Ascii
        );
        assert_eq!(
            load_with_term(missing, None)
                .expect("a missing file is not an error")
                .document
                .glyphs,
            Glyphs::Full
        );
    }

    /// This ticket's own refusal, pinned against the source rather than left as prose:
    /// `TERM` is read from the real environment in exactly one place across both crates, and
    /// [`conditional_glyphs_default`] itself takes that one value as a plain argument and
    /// reads nothing further, comparing it against exactly one significant value, `"linux"`.
    /// A second `TERM` read anywhere in the workspace, a second environment read inside the
    /// decision itself, or a second value the decision treats as significant, fails this
    /// rather than landing unnoticed.
    ///
    /// Mutation run: changed `conditional_glyphs_default`'s guard to
    /// `term == Some("linux") || term == Some("screen.linux")`, simulating a second console
    /// name creeping into the one check the decision refuses to grow a table of. The
    /// `significant_values` assertion below failed with "expected exactly one TERM value to
    /// matter to the decision, got: ... Some(\"linux\") ... Some(\"screen.linux\") ...".
    #[test]
    fn glyphs_default_reads_exactly_one_term_value_and_no_other_variable() {
        use crate::test_support::{
            all_lines_where, blocks_opened_by, production_source_at, workspace_crate_src_dirs,
        };

        let dirs = workspace_crate_src_dirs();
        let term_reads = all_lines_where(&dirs, |line| {
            line.contains("env::var(\"TERM\")") || line.contains("env::var_os(\"TERM\")")
        });
        assert_eq!(
            term_reads.len(),
            1,
            "expected exactly one live `TERM` read across the workspace, found: {:?}",
            term_reads
                .iter()
                .map(|line| format!("{}:{}", line.path.display(), line.number))
                .collect::<Vec<_>>()
        );
        assert!(
            term_reads[0].path.ends_with("config/document.rs"),
            "expected the one TERM read to live in config/document.rs, found: {}",
            term_reads[0].path.display()
        );

        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let source = production_source_at(&manifest_dir.join("src/config/document.rs"));

        let decision_blocks = blocks_opened_by(&source, "fn conditional_glyphs_default");
        assert_eq!(
            decision_blocks.len(),
            1,
            "expected exactly one conditional_glyphs_default function"
        );
        let decision_body = &decision_blocks[0];
        assert!(
            !decision_body.contains("env::"),
            "conditional_glyphs_default must stay a pure function of its `term` argument, but \
             its body reads the environment directly: {decision_body}"
        );
        let significant_values = decision_body.matches("Some(\"").count();
        assert_eq!(
            significant_values, 1,
            "expected exactly one TERM value to matter to the decision, got: {decision_body}"
        );
        assert!(
            decision_body.contains("Some(\"linux\")"),
            "expected the one significant value to be \"linux\", got: {decision_body}"
        );
    }

    /// `"0s"` turns the Notice timer off, per this field's own doc comment and
    /// [theming.md](../../../../docs/spec/theming.md); it is a humantime string like every
    /// other duration in this schema, never a bare integer.
    #[test]
    fn notice_timeout_parses_as_humantime_and_zero_seconds_is_a_valid_value() {
        let loaded = parse_ok("notice_timeout = \"10s\"\n");
        assert_eq!(loaded.document.notice_timeout, Duration::from_secs(10));

        let loaded = parse_ok("notice_timeout = \"0s\"\n");
        assert_eq!(loaded.document.notice_timeout, Duration::ZERO);
    }

    #[test]
    fn a_bare_integer_notice_timeout_is_a_bad_value() {
        let message = parse_err("notice_timeout = 3\n");
        assert!(
            message.contains("duration"),
            "expected a duration type error, got: {message}"
        );
    }

    // Every duration is a humantime string; the disabled poll is "0s", not a bare integer.
    #[test]
    fn the_six_refresh_fetch_and_auto_update_keys_carry_their_stated_defaults() {
        let loaded = parse_ok("");
        let refresh = &loaded.document.refresh;
        assert_eq!(refresh.poll_interval, Duration::from_secs(2));
        assert_eq!(refresh.status_stale_after, Duration::from_secs(5 * 60));
        assert!(refresh.on_focus);
        let fetch = &loaded.document.fetch;
        assert!(!fetch.enabled);
        assert_eq!(fetch.interval, Duration::from_secs(5 * 60));
        assert_eq!(fetch.concurrency, 4);
        assert!(!loaded.document.auto_update.enabled);
    }

    #[test]
    fn a_bare_integer_duration_is_a_bad_value_in_a_known_key() {
        let message = parse_err("[refresh]\npoll_interval = 2\n");
        assert!(
            message.contains("duration"),
            "expected a duration type error, got: {message}"
        );
        assert!(
            message.contains("line 2, column 17"),
            "expected the offending value's position, got: {message}"
        );
    }

    #[test]
    fn a_zero_second_string_disables_the_poll() {
        let loaded = parse_ok("[refresh]\npoll_interval = \"0s\"\n");
        assert_eq!(loaded.document.refresh.poll_interval, Duration::ZERO);
    }

    // A partial file deep-merges over the compiled defaults field by field.
    #[test]
    fn a_partial_refresh_table_merges_over_the_defaults_for_the_fields_it_omits() {
        let loaded = parse_ok("[refresh]\npoll_interval = \"10s\"\n");
        let refresh = &loaded.document.refresh;
        assert_eq!(refresh.poll_interval, Duration::from_secs(10));
        // Untouched fields keep the compiled default, proving the merge is per field.
        assert_eq!(refresh.status_stale_after, Duration::from_secs(5 * 60));
        assert!(refresh.on_focus);
    }

    // Missing file: not an error, one implicit Set named `all`, rooted at the working
    // directory.
    #[test]
    fn a_missing_file_resolves_to_the_implicit_all_set() {
        let loaded = load(Path::new("/does/not/exist/config.toml")).expect("not an error");
        assert_eq!(loaded.document.sets.len(), 1);
        assert_eq!(loaded.document.sets[0].name.get_ref(), "all");
        assert_eq!(
            loaded.document.sets[0].roots,
            vec![working_directory().to_string_lossy().into_owned()]
        );
        assert!(loaded.warnings.is_empty());
        assert!(
            loaded.zero_config,
            "a missing file must report zero_config, since state.toml's own scope key reads \
             this to decide between the active Set's name and the working directory"
        );
    }

    /// The negative control for `zero_config`: a real file that happens to declare no
    /// `[[set]]` still gets the same implicit `all` Set pushed for it, but it is not zero
    /// config, since there is a document a user can go and edit. Distinguishes "no file was
    /// read" from "a file was read and turned out to declare nothing".
    #[test]
    fn a_real_file_declaring_no_set_is_not_reported_as_zero_config() {
        let loaded = parse_ok("");
        assert_eq!(loaded.document.sets[0].name.get_ref(), "all");
        assert!(
            !loaded.zero_config,
            "a file that was actually read must never report zero_config, even when it \
             declares no [[set]] of its own"
        );
    }

    // Malformed TOML exits non-zero (via Result::Err) reporting toml's own line and column.
    #[test]
    fn malformed_toml_reports_line_and_column_from_the_api() {
        let message = parse_err("this is not = = valid toml [[[\n");
        assert!(message.contains("could not parse"));
        assert!(
            message.contains("line 1, column 6"),
            "expected the parser's own position, got: {message}"
        );
    }

    // Unknown keys are enumerated in one pass rather than failing on the first.
    #[test]
    fn every_unknown_key_is_reported_in_one_pass() {
        let loaded = parse_ok(
            "typo_one = true\n\n[refresh]\ntypo_two = 1\n\n[[set]]\nname = \"dev\"\nroots = [\"~/dev\"]\ntypo_three = 1\n",
        );
        let unknown: Vec<&str> = loaded
            .warnings
            .iter()
            .filter_map(|warning| match warning {
                Warning::UnknownKey(path) => Some(path.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            unknown.len(),
            3,
            "expected all three typos, got: {unknown:?}"
        );
        assert!(unknown.contains(&"typo_one"));
        assert!(unknown.contains(&"refresh.typo_two"));
        assert!(unknown.iter().any(|path| path.ends_with("typo_three")));
    }

    // ADR 0011: Repon probes no terminal background and ships no paired light/dark theme,
    // so there is no `appearance` key for one to select between. `appearance` falls through
    // to the same unknown-key warning as any other typo, rather than being a recognised,
    // parsed field.
    #[test]
    fn an_appearance_key_is_not_part_of_the_schema_and_warns_as_unknown() {
        let loaded = parse_ok("appearance = \"dark\"\n");
        assert!(
            loaded.warnings.iter().any(
                |warning| matches!(warning, Warning::UnknownKey(path) if path == "appearance")
            ),
            "expected `appearance` to warn as an unknown key, got: {:?}",
            loaded.warnings
        );
    }

    // A duplicate `[[set]]` name is rejected at load with the line number.
    #[test]
    fn a_duplicate_set_name_is_rejected_with_a_line_number() {
        let message = parse_err(
            "[[set]]\nname = \"dev\"\nroots = [\"~/dev\"]\n\n[[set]]\nname = \"dev\"\nroots = [\"~/other\"]\n",
        );
        assert!(message.contains("duplicate set name"));
        assert!(
            message.contains("line 6"),
            "expected the second declaration's line, got: {message}"
        );
    }

    // A duplicate `[[repo]]` path is rejected at load with the line number.
    #[test]
    fn a_duplicate_repo_path_is_rejected_with_a_line_number() {
        let message =
            parse_err("[[repo]]\npath = \"~/dev/one\"\n\n[[repo]]\npath = \"~/dev/one\"\n");
        assert!(message.contains("duplicate repo path"));
        assert!(message.contains("line 5"), "got: {message}");
    }

    // A duplicate `[[launcher]]` name is rejected at load with the line number, the same
    // uniqueness `reject_duplicate_names` already enforces for sets and repos.
    #[test]
    fn a_duplicate_launcher_name_is_rejected_with_a_line_number() {
        let message = parse_err(
            "[[launcher]]\nname = \"lazygit\"\nargs = [\"lazygit\"]\n\n[[launcher]]\nname = \"lazygit\"\nargs = [\"lg\"]\n",
        );
        assert!(message.contains("duplicate launcher name"));
        assert!(
            message.contains("line 6"),
            "expected the second declaration's line, got: {message}"
        );
    }

    // File order is preserved as tab and palette order: the array is not reordered.
    #[test]
    fn set_declaration_order_is_preserved() {
        let loaded = parse_ok(
            "[[set]]\nname = \"zeta\"\nroots = [\"~/dev\"]\n\n[[set]]\nname = \"alpha\"\nroots = [\"~/dev\"]\n",
        );
        let names: Vec<&str> = loaded
            .document
            .sets
            .iter()
            .map(|set| set.name.get_ref().as_str())
            .collect();
        assert_eq!(names, vec!["zeta", "alpha"]);
    }

    // [[launcher]]'s full field schema (name, args, from_env, shell, interactive,
    // takes_terminal, env, disabled) parses with no unknown-key warnings, and each field's
    // value lands where declared.
    #[test]
    fn a_launcher_entrys_full_field_schema_parses_with_no_unknown_keys() {
        let text = "[[launcher]]\n\
                     name = \"lazygit\"\n\
                     args = [\"lazygit\"]\n\
                     shell = false\n\
                     takes_terminal = true\n\
                     disabled = false\n\
                     [launcher.env]\n\
                     FOO = \"bar\"\n\
                     \n\
                     [[launcher]]\n\
                     name = \"editor\"\n\
                     from_env = \"EDITOR\"\n\
                     takes_terminal = false\n";
        let loaded = parse_ok(text);
        assert!(
            !loaded
                .warnings
                .iter()
                .any(|warning| matches!(warning, Warning::UnknownKey(_))),
            "expected no unknown-key warnings, got: {:?}",
            loaded.warnings
        );

        let lazygit = &loaded.document.launchers[0];
        assert_eq!(
            lazygit.args.as_deref(),
            Some(["lazygit".to_string()].as_slice())
        );
        assert_eq!(lazygit.from_env, None);
        assert!(!lazygit.shell);
        assert!(lazygit.takes_terminal);
        assert!(!lazygit.disabled);
        assert_eq!(lazygit.env.get("FOO").map(String::as_str), Some("bar"));

        let editor = &loaded.document.launchers[1];
        assert_eq!(editor.from_env.as_deref(), Some("EDITOR"));
        assert_eq!(editor.args, None);
        assert!(
            !editor.takes_terminal,
            "an entry declaring `takes_terminal = false` must keep it, whichever argv form it \
             uses"
        );
    }

    // A genuinely unknown [[launcher]] key still warns now that the real schema is
    // implemented: there is no more catch-all field standing in for it.
    #[test]
    fn a_launcher_entrys_actually_unknown_key_still_warns() {
        let text = "[[launcher]]\nname = \"lazygit\"\ntypo_field = 1\n";
        let loaded = parse_ok(text);
        assert!(
            loaded.warnings.iter().any(|warning| matches!(
                warning,
                Warning::UnknownKey(path) if path.ends_with("typo_field")
            )),
            "expected an unknown-key warning for the stray field, got: {:?}",
            loaded.warnings
        );
    }

    // Criterion 3: "there is no working-directory field" is an absence claim about the
    // schema. `cwd` (or any other name) is not a field `LauncherConfig` knows, so a document
    // naming one falls through to the same unknown-key warning as any other typo, exactly the
    // way `an_appearance_key_is_not_part_of_the_schema_and_warns_as_unknown` proves the same
    // shape of absence for the top-level `theme`/`appearance` case.
    #[test]
    fn a_working_directory_key_on_a_launcher_entry_is_not_part_of_the_schema_and_warns_as_unknown()
    {
        let text = "[[launcher]]\nname = \"lazygit\"\ncwd = \"/tmp\"\n";
        let loaded = parse_ok(text);
        assert!(
            loaded.warnings.iter().any(|warning| matches!(
                warning,
                Warning::UnknownKey(path) if path.ends_with("cwd")
            )),
            "expected `cwd` to warn as an unknown key, got: {:?}",
            loaded.warnings
        );
    }

    /// Every row of config.md's "Launchers" field table, as `(field, type cell)` pairs.
    /// Scoped to that section, so a same-named row in another table cannot stand in for one
    /// here.
    fn spec_launcher_field_rows(spec: &str) -> Vec<(String, String)> {
        const ANCHOR: &str = "## Launchers";
        let after = spec
            .split(ANCHOR)
            .nth(1)
            .expect("the Launchers section is present");
        after
            .lines()
            .skip_while(|line| !line.starts_with('|'))
            .take_while(|line| line.starts_with('|'))
            .filter(|line| !line.starts_with("| ---"))
            .filter_map(|line| {
                let cells: Vec<&str> = line.split('|').map(str::trim).collect();
                let (field, kind) = (cells[1].trim_matches('`'), cells[2]);
                (field != "field").then(|| (field.to_string(), kind.to_string()))
            })
            .collect()
    }

    /// The default a bool row's own type cell states, or `None` for a row that is not a bool
    /// with a stated default.
    fn spec_declared_bool_default(kind: &str) -> Option<bool> {
        let stated = kind.strip_prefix("bool, default ")?;
        match stated.trim_matches('`') {
            "true" => Some(true),
            "false" => Some(false),
            other => panic!("unexpected bool default {other:?} in the Launchers field table"),
        }
    }

    /// Every bool key in config.md's Launchers table, read at test time, defaults to the
    /// value the table itself states when an entry omits it. `takes_terminal` is the one that
    /// cannot come from `bool::default()`, so restating its default in Rust is exactly the
    /// "single source of truth shared by production and its tests" trap: the whole table is
    /// walked here instead, and a bool key added to it without being wired up panics on its
    /// own row rather than passing unnoticed.
    #[test]
    fn every_bool_launcher_key_defaults_to_what_the_spec_states_when_an_entry_omits_it() {
        let spec = read_config_spec();
        let mut loaded = parse_ok("[[launcher]]\nname = \"lazygit\"\nargs = [\"lazygit\"]\n");
        let launcher = loaded
            .document
            .launchers
            .pop()
            .expect("one parsed [[launcher]] entry");

        let mut checked = Vec::new();
        for (field, kind) in spec_launcher_field_rows(&spec) {
            let Some(expected) = spec_declared_bool_default(&kind) else {
                continue;
            };
            let actual = match field.as_str() {
                "shell" => launcher.shell,
                "interactive" => launcher.interactive,
                "takes_terminal" => launcher.takes_terminal,
                "disabled" => launcher.disabled,
                other => panic!("no `LauncherConfig` field is wired to the spec's `{other}`"),
            };
            assert_eq!(
                actual, expected,
                "`{field}` must default to the spec's own stated default"
            );
            checked.push(field);
        }
        assert_eq!(
            checked,
            vec!["shell", "interactive", "takes_terminal", "disabled"],
            "the Launchers table's bool rows, in its own order; a parse that stops finding \
             them would otherwise leave this test asserting nothing"
        );
    }

    /// Criterion 3's schema-shape half, the exhaustive-destructure guard this ticket's brief
    /// warns about: hand-enumerating the fields a caller reads (`config.args`, `config.shell`,
    /// ...) lets a new field, such as a working-directory one, compile silently. This
    /// destructure names every field `LauncherConfig` has; one added under any name fails to
    /// compile this test rather than landing unacknowledged, the same guard
    /// `action_config_carries_no_pty_width_field_the_pty_is_a_fixed_constant_never_a_config_key`
    /// already applies to `ActionConfig`.
    #[test]
    fn launcher_config_carries_no_working_directory_field_every_launcher_uses_its_entitys_own_cwd()
    {
        let loaded = parse_ok("[[launcher]]\nname = \"lazygit\"\nargs = [\"lazygit\"]\n");
        let LauncherConfig {
            name: _,
            args: _,
            from_env: _,
            shell: _,
            interactive: _,
            takes_terminal: _,
            env: _,
            disabled: _,
        } = loaded
            .document
            .launchers
            .into_iter()
            .next()
            .expect("one parsed [[launcher]] entry");
    }

    // Criterion 3: `args` and `from_env` are mutually exclusive, so declaring both is an
    // error rather than one silently winning over the other.
    #[test]
    fn a_launcher_declaring_both_args_and_from_env_is_rejected_at_load() {
        let message =
            parse_err("[[launcher]]\nname = \"editor\"\nargs = [\"vi\"]\nfrom_env = \"EDITOR\"\n");
        assert!(
            message.contains("editor") && message.contains("mutually exclusive"),
            "expected a mutual-exclusion error naming the launcher, got: {message}"
        );
    }

    #[test]
    fn a_launcher_declaring_only_args_or_only_from_env_is_accepted() {
        let with_args = parse_ok("[[launcher]]\nname = \"lazygit\"\nargs = [\"lazygit\"]\n");
        assert_eq!(with_args.document.launchers[0].from_env, None);

        let with_from_env = parse_ok("[[launcher]]\nname = \"editor\"\nfrom_env = \"EDITOR\"\n");
        assert_eq!(with_from_env.document.launchers[0].args, None);
    }

    /// `interactive` only means anything alongside `shell = true`: a `[[launcher]]` declaring
    /// it without `shell = true` is a config error naming both keys, the same failure grade
    /// `args` and `from_env` together already get, rather than silently ignored.
    #[test]
    fn a_launcher_declaring_interactive_without_shell_is_rejected_at_load() {
        let message =
            parse_err("[[launcher]]\nname = \"log\"\nargs = [\"true\"]\ninteractive = true\n");
        assert!(
            message.contains("log") && message.contains("interactive") && message.contains("shell"),
            "expected an error naming both the launcher and both keys, got: {message}"
        );
    }

    /// The identical rule over an `[[action.steps]]` entry, which carries no span of its
    /// own, so the error points at its own action's `name` instead.
    #[test]
    fn an_action_step_declaring_interactive_without_shell_is_rejected_at_load() {
        let message = parse_err(
            "[[action]]\nname = \"deploy\"\n\n\
             [[action.steps]]\nargs = [\"true\"]\ninteractive = true\n",
        );
        assert!(
            message.contains("deploy")
                && message.contains("interactive")
                && message.contains("shell"),
            "expected an error naming both the action and both keys, got: {message}"
        );
    }

    /// `interactive = true` alongside `shell = true` is accepted, on both a Launcher and an
    /// action step.
    #[test]
    fn interactive_alongside_shell_is_accepted_on_a_launcher_and_a_step() {
        let launcher = parse_ok(
            "[[launcher]]\nname = \"log\"\nargs = [\"true\"]\nshell = true\ninteractive = true\n",
        );
        assert!(launcher.document.launchers[0].interactive);

        let step = parse_ok(
            "[[action]]\nname = \"deploy\"\n\n\
             [[action.steps]]\nargs = [\"true\"]\nshell = true\ninteractive = true\n",
        );
        assert!(step.document.actions[0].steps[0].interactive);
    }

    // `[[repo]]`'s real schema: `default_branch` and `exclude` parse as typed fields, with
    // `exclude` defaulting to `false` when absent.
    #[test]
    fn a_repo_entrys_default_branch_and_exclude_parse_with_excludes_stated_default() {
        let dir = tempfile::tempdir().expect("tempdir");
        let text = format!(
            "[[repo]]\npath = \"{}\"\ndefault_branch = \"main\"\nexclude = true\n\n[[repo]]\npath = \"{}\"\n",
            dir.path().display(),
            dir.path().join("other").display()
        );
        let loaded = parse_ok(&text);

        assert_eq!(
            loaded.document.repos[0].default_branch.as_deref(),
            Some("main")
        );
        assert!(loaded.document.repos[0].exclude);
        // The second entry states neither field: `default_branch` is absent and
        // `exclude` falls back to its stated default of `false`.
        assert_eq!(loaded.document.repos[1].default_branch, None);
        assert!(!loaded.document.repos[1].exclude);
        assert!(
            !loaded
                .warnings
                .iter()
                .any(|warning| matches!(warning, Warning::UnknownKey(_))),
            "expected no unknown-key warnings, got: {:?}",
            loaded.warnings
        );
    }

    // A genuinely unknown `[[repo]]` key still warns now that the real schema is
    // implemented: there is no more catch-all field standing in for it.
    #[test]
    fn a_repo_entrys_actually_unknown_key_still_warns() {
        let dir = tempfile::tempdir().expect("tempdir");
        let text = format!(
            "[[repo]]\npath = \"{}\"\ntypo_field = 1\n",
            dir.path().display()
        );
        let loaded = parse_ok(&text);

        assert!(
            loaded
                .warnings
                .iter()
                .any(|warning| matches!(warning, Warning::UnknownKey(path) if path.ends_with("typo_field"))),
            "expected an unknown-key warning for the stray field, got: {:?}",
            loaded.warnings
        );
    }

    // The seam `Core::start` reads: `repo_overrides` turns the parsed `[[repo]]` entries
    // into `repon_core::RepoOverride`, `~`-expanding `path` the same way every other path
    // in this file is expanded.
    #[test]
    fn repo_overrides_tilde_expands_the_path_and_carries_default_branch_and_exclude() {
        let loaded = parse_ok(
            "[[repo]]\npath = \"~/dev/legacy-api\"\ndefault_branch = \"main\"\n\n[[repo]]\npath = \"/absolute/vendor-mirror\"\nexclude = true\n",
        );

        let overrides = repo_overrides(&loaded.document);

        assert_eq!(overrides.len(), 2);
        assert_eq!(
            overrides[0].path,
            expand_home("~/dev/legacy-api"),
            "a `~`-prefixed path must expand the same way every other path in this file does"
        );
        assert_eq!(overrides[0].default_branch.as_deref(), Some("main"));
        assert!(!overrides[0].excluded);
        assert_eq!(overrides[1].path, PathBuf::from("/absolute/vendor-mirror"));
        assert_eq!(overrides[1].default_branch, None);
        assert!(overrides[1].excluded);
    }

    // Cross-key check: auto_update.enabled with fetch.enabled = false can never fire.
    #[test]
    fn auto_update_without_fetch_warns() {
        let loaded = parse_ok("[fetch]\nenabled = false\n\n[auto_update]\nenabled = true\n");
        assert!(loaded.warnings.contains(&Warning::AutoUpdateWithoutFetch));
    }

    #[test]
    fn auto_update_with_fetch_does_not_warn() {
        let loaded = parse_ok("[fetch]\nenabled = true\n\n[auto_update]\nenabled = true\n");
        assert!(!loaded.warnings.contains(&Warning::AutoUpdateWithoutFetch));
    }

    // Cross-key check: `on_refresh` naming an Action no `[[action]]` declares. A typo here
    // costs the whole hook, and a hook that never fires is exactly the silence a warning
    // exists for; it is a warning rather than an exit, because every other value in the file
    // is still usable (docs/spec/config.md's "Cross-key validity").
    #[test]
    fn on_refresh_naming_an_undeclared_action_warns_rather_than_failing_the_load() {
        let loaded = parse_ok("on_refresh = \"sync\"\n");

        assert!(
            loaded.warnings.contains(&Warning::OnRefreshNamesNoAction {
                name: "sync".to_string(),
            }),
            "got: {:?}",
            loaded.warnings
        );
        assert_eq!(loaded.document.on_refresh.as_deref(), Some("sync"));
    }

    #[test]
    fn on_refresh_naming_a_declared_action_does_not_warn() {
        let loaded = parse_ok(
            "on_refresh = \"hook\"\n\n[[action]]\nname = \"hook\"\nsteps = [{ args = [\"true\"] }]\n",
        );

        assert!(
            !loaded
                .warnings
                .iter()
                .any(|warning| matches!(warning, Warning::OnRefreshNamesNoAction { name: _ })),
            "got: {:?}",
            loaded.warnings
        );
    }

    /// The key left out entirely is the zero-config shape, and must not warn about an Action
    /// nobody named: a warning here would stand on every default install.
    #[test]
    fn an_absent_on_refresh_key_warns_about_nothing_and_defaults_to_none() {
        let loaded = parse_ok("theme = \"default\"\n");

        assert_eq!(loaded.document.on_refresh, None);
        assert!(
            !loaded
                .warnings
                .iter()
                .any(|warning| matches!(warning, Warning::OnRefreshNamesNoAction { name: _ })),
            "got: {:?}",
            loaded.warnings
        );
    }

    // Issue #250: `[[set]].on_refresh` parses, and an unknown key inside `[[set]]` still
    // warns rather than exits.
    #[test]
    fn a_set_on_refresh_key_parses() {
        let loaded = parse_ok(
            "[[set]]\nname = \"work\"\nroots = [\"~/dev\"]\non_refresh = \"hook\"\n\n\
             [[action]]\nname = \"hook\"\nsteps = [{ args = [\"true\"] }]\n",
        );
        assert_eq!(loaded.document.sets[0].on_refresh.as_deref(), Some("hook"));
    }

    #[test]
    fn an_unknown_key_inside_a_set_that_also_declares_on_refresh_still_warns() {
        let loaded = parse_ok(
            "[[set]]\nname = \"work\"\nroots = [\"~/dev\"]\non_refresh = \"sync\"\ntypo = 1\n",
        );
        assert!(
            loaded.warnings.iter().any(
                |warning| matches!(warning, Warning::UnknownKey(path) if path.ends_with("typo"))
            ),
            "expected the stray key to still warn beside a real on_refresh, got: {:?}",
            loaded.warnings
        );
    }

    // Issue #250: a `[[set]].on_refresh` naming no declared `[[action]]` warns on the
    // existing warnings path and names the Set, so two Sets with the same bad name produce
    // two distinguishable warnings rather than one ambiguous one.
    #[test]
    fn a_set_on_refresh_naming_no_declared_action_warns_and_names_the_set() {
        let loaded = parse_ok(
            "[[set]]\nname = \"work\"\nroots = [\"~/dev\"]\non_refresh = \"nothing-declares-this\"\n",
        );
        assert!(
            loaded
                .warnings
                .contains(&Warning::SetOnRefreshNamesNoAction {
                    set: "work".to_string(),
                    name: "nothing-declares-this".to_string(),
                }),
            "got: {:?}",
            loaded.warnings
        );
    }

    #[test]
    fn two_sets_with_the_same_bad_on_refresh_name_produce_two_distinguishable_warnings() {
        let loaded = parse_ok(
            "[[set]]\nname = \"work\"\nroots = [\"~/dev\"]\non_refresh = \"nothing-declares-this\"\n\n\
             [[set]]\nname = \"personal\"\nroots = [\"~/dev-misc\"]\non_refresh = \"nothing-declares-this\"\n",
        );
        let set_names: Vec<&str> = loaded
            .warnings
            .iter()
            .filter_map(|warning| match warning {
                Warning::SetOnRefreshNamesNoAction { set, .. } => Some(set.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            set_names,
            vec!["work", "personal"],
            "each Set's own bad on_refresh must warn on its own, naming that Set, got: {:?}",
            loaded.warnings
        );
    }

    #[test]
    fn a_set_on_refresh_naming_a_declared_action_does_not_warn() {
        let loaded = parse_ok(
            "[[set]]\nname = \"work\"\nroots = [\"~/dev\"]\non_refresh = \"hook\"\n\n\
             [[action]]\nname = \"hook\"\nsteps = [{ args = [\"true\"] }]\n",
        );
        assert!(
            !loaded
                .warnings
                .iter()
                .any(|warning| matches!(warning, Warning::SetOnRefreshNamesNoAction { .. })),
            "got: {:?}",
            loaded.warnings
        );
    }

    // `before_sync` and `after_sync`: the identical shape and resolution `on_refresh` already
    // has, over two fields instead of one (docs/spec/repo-management.md's "Hooks around
    // sync").

    #[test]
    fn before_sync_naming_an_undeclared_action_warns_rather_than_failing_the_load() {
        let loaded = parse_ok("before_sync = \"tidy\"\n");

        assert!(
            loaded.warnings.contains(&Warning::BeforeSyncNamesNoAction {
                name: "tidy".to_string(),
            }),
            "got: {:?}",
            loaded.warnings
        );
        assert_eq!(loaded.document.before_sync.as_deref(), Some("tidy"));
    }

    #[test]
    fn after_sync_naming_an_undeclared_action_warns_rather_than_failing_the_load() {
        let loaded = parse_ok("after_sync = \"tidy\"\n");

        assert!(
            loaded.warnings.contains(&Warning::AfterSyncNamesNoAction {
                name: "tidy".to_string(),
            }),
            "got: {:?}",
            loaded.warnings
        );
        assert_eq!(loaded.document.after_sync.as_deref(), Some("tidy"));
    }

    #[test]
    fn before_sync_and_after_sync_naming_a_declared_action_do_not_warn() {
        let loaded = parse_ok(
            "before_sync = \"hook\"\nafter_sync = \"hook\"\n\n\
             [[action]]\nname = \"hook\"\nsteps = [{ args = [\"true\"] }]\n",
        );
        assert!(
            !loaded.warnings.iter().any(|warning| matches!(
                warning,
                Warning::BeforeSyncNamesNoAction { .. } | Warning::AfterSyncNamesNoAction { .. }
            )),
            "got: {:?}",
            loaded.warnings
        );
    }

    /// Left out entirely, the zero-config shape: no warning about an Action nobody named.
    #[test]
    fn absent_before_sync_and_after_sync_keys_warn_about_nothing_and_default_to_none() {
        let loaded = parse_ok("theme = \"default\"\n");

        assert_eq!(loaded.document.before_sync, None);
        assert_eq!(loaded.document.after_sync, None);
        assert!(
            !loaded.warnings.iter().any(|warning| matches!(
                warning,
                Warning::BeforeSyncNamesNoAction { .. } | Warning::AfterSyncNamesNoAction { .. }
            )),
            "got: {:?}",
            loaded.warnings
        );
    }

    #[test]
    fn a_set_before_sync_and_after_sync_key_parse() {
        let loaded = parse_ok(
            "[[set]]\nname = \"work\"\nroots = [\"~/dev\"]\n\
             before_sync = \"pre\"\nafter_sync = \"post\"\n\n\
             [[action]]\nname = \"pre\"\nsteps = [{ args = [\"true\"] }]\n\n\
             [[action]]\nname = \"post\"\nsteps = [{ args = [\"true\"] }]\n",
        );
        assert_eq!(loaded.document.sets[0].before_sync.as_deref(), Some("pre"));
        assert_eq!(loaded.document.sets[0].after_sync.as_deref(), Some("post"));
    }

    #[test]
    fn a_set_before_sync_naming_no_declared_action_warns_and_names_the_set() {
        let loaded = parse_ok(
            "[[set]]\nname = \"work\"\nroots = [\"~/dev\"]\nbefore_sync = \"nothing-declares-this\"\n",
        );
        assert!(
            loaded
                .warnings
                .contains(&Warning::SetBeforeSyncNamesNoAction {
                    set: "work".to_string(),
                    name: "nothing-declares-this".to_string(),
                }),
            "got: {:?}",
            loaded.warnings
        );
    }

    #[test]
    fn a_set_after_sync_naming_no_declared_action_warns_and_names_the_set() {
        let loaded = parse_ok(
            "[[set]]\nname = \"work\"\nroots = [\"~/dev\"]\nafter_sync = \"nothing-declares-this\"\n",
        );
        assert!(
            loaded
                .warnings
                .contains(&Warning::SetAfterSyncNamesNoAction {
                    set: "work".to_string(),
                    name: "nothing-declares-this".to_string(),
                }),
            "got: {:?}",
            loaded.warnings
        );
    }

    // The chain over all three rungs from one document, for both fields, the identical proof
    // `on_refresh_resolves_over_all_three_rungs_from_one_document` below already gives that
    // key.
    #[test]
    fn before_sync_and_after_sync_resolve_over_all_three_rungs_from_one_document() {
        let loaded = parse_ok(
            "before_sync = \"top-level-pre\"\nafter_sync = \"top-level-post\"\n\n\
             [[set]]\nname = \"own-hooks\"\nroots = [\"~/dev\"]\n\
             before_sync = \"set-pre\"\nafter_sync = \"set-post\"\n\n\
             [[set]]\nname = \"falls-through\"\nroots = [\"~/dev\"]\n\n\
             [[action]]\nname = \"set-pre\"\nsteps = [{ args = [\"true\"] }]\n\n\
             [[action]]\nname = \"set-post\"\nsteps = [{ args = [\"true\"] }]\n\n\
             [[action]]\nname = \"top-level-pre\"\nsteps = [{ args = [\"true\"] }]\n\n\
             [[action]]\nname = \"top-level-post\"\nsteps = [{ args = [\"true\"] }]\n",
        );

        assert_eq!(
            resolve_before_sync_name(&loaded.document, "own-hooks"),
            Some("set-pre"),
            "a Set with its own before_sync must resolve to it, ahead of the top-level key"
        );
        assert_eq!(
            resolve_after_sync_name(&loaded.document, "own-hooks"),
            Some("set-post"),
            "a Set with its own after_sync must resolve to it, ahead of the top-level key"
        );
        assert_eq!(
            resolve_before_sync_name(&loaded.document, "falls-through"),
            Some("top-level-pre"),
            "a Set with no before_sync of its own must fall through to the top-level key"
        );
        assert_eq!(
            resolve_after_sync_name(&loaded.document, "falls-through"),
            Some("top-level-post"),
            "a Set with no after_sync of its own must fall through to the top-level key"
        );
    }

    // Issue #250: the chain over all three rungs from one document. A pure function of
    // `Document`, so this needs no `App`/`Core` at all to prove the resolution rather than
    // the firing.
    #[test]
    fn on_refresh_resolves_over_all_three_rungs_from_one_document() {
        let loaded = parse_ok(
            "on_refresh = \"top-level\"\n\n\
             [[set]]\nname = \"own-hook\"\nroots = [\"~/dev\"]\non_refresh = \"set-scoped\"\n\n\
             [[set]]\nname = \"falls-through\"\nroots = [\"~/dev\"]\n\n\
             [[set]]\nname = \"third-set-has-one\"\nroots = [\"~/dev\"]\non_refresh = \"set-scoped\"\n\n\
             [[action]]\nname = \"set-scoped\"\nsteps = [{ args = [\"true\"] }]\n\n\
             [[action]]\nname = \"top-level\"\nsteps = [{ args = [\"true\"] }]\n",
        );

        assert_eq!(
            resolve_on_refresh_name(&loaded.document, "own-hook"),
            Some("set-scoped"),
            "a Set with its own hook must resolve to it, ahead of the top-level key"
        );
        assert_eq!(
            resolve_on_refresh_name(&loaded.document, "falls-through"),
            Some("top-level"),
            "a Set with no on_refresh of its own must fall through to the top-level key"
        );
        assert_eq!(
            resolve_on_refresh_name(&loaded.document, "third-set-has-one"),
            Some("set-scoped"),
            "a third Set's own hook must resolve independently of what another Set declares"
        );
    }

    #[test]
    fn on_refresh_resolves_to_none_when_neither_the_set_nor_the_top_level_declares_one() {
        let loaded = parse_ok("[[set]]\nname = \"quiet\"\nroots = [\"~/dev\"]\n");
        assert_eq!(resolve_on_refresh_name(&loaded.document, "quiet"), None);
    }

    // Cross-key check: a [[set]] named `all` warns, and the declaration still wins (it is
    // not replaced by, or merged with, the implicit Set).
    #[test]
    fn a_set_named_all_warns_and_its_declaration_wins() {
        let loaded = parse_ok("[[set]]\nname = \"all\"\nroots = [\"~/dev\"]\n");
        assert!(loaded.warnings.contains(&Warning::SetNamedAll));
        assert_eq!(loaded.document.sets.len(), 1);
        assert_eq!(loaded.document.sets[0].roots, vec!["~/dev".to_string()]);
    }

    // Cross-key check: a [[repo]] path matching no discovered entity warns.
    #[test]
    fn a_repo_path_that_does_not_exist_warns() {
        let loaded = parse_ok("[[repo]]\npath = \"/does/not/exist/anywhere\"\n");
        assert!(loaded.warnings.iter().any(|warning| matches!(
            warning,
            Warning::RepoPathMatchesNothing { path } if path == "/does/not/exist/anywhere"
        )));
    }

    #[test]
    fn a_repo_path_that_exists_does_not_warn() {
        let dir = tempfile::tempdir().expect("tempdir");
        let text = format!("[[repo]]\npath = \"{}\"\n", dir.path().display());
        let loaded = parse_ok(&text);
        assert!(loaded.warnings.is_empty(), "got: {:?}", loaded.warnings);
    }

    // Cross-key check: a [[set]] glob matching nothing warns.
    #[test]
    fn a_set_glob_matching_nothing_under_its_roots_warns() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir(dir.path().join("kept")).expect("create dir");
        let text = format!(
            "[[set]]\nname = \"dev\"\nroots = [\"{}\"]\ninclude = [\"**/nonexistent-glob-target/**\"]\n",
            dir.path().display()
        );
        let loaded = parse_ok(&text);
        assert!(loaded.warnings.iter().any(|warning| matches!(
            warning,
            Warning::SetGlobMatchesNothing { glob, .. } if glob == "**/nonexistent-glob-target/**"
        )));
    }

    #[test]
    fn a_set_glob_matching_something_under_its_roots_does_not_warn() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir(dir.path().join("kept")).expect("create dir");
        let text = format!(
            "[[set]]\nname = \"dev\"\nroots = [\"{}\"]\ninclude = [\"**/kept\"]\n",
            dir.path().display()
        );
        let loaded = parse_ok(&text);
        assert!(loaded.warnings.is_empty(), "got: {:?}", loaded.warnings);
    }

    /// Which part of the template one of its own lines belongs to, coarse enough for
    /// [`section_declares_key`]: everything above the first header is the bare top-level
    /// keys, and every other line belongs to whichever header last preceded it.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum TemplateSection {
        TopLevel,
        Refresh,
        Fetch,
        AutoUpdate,
        Set,
        Repo,
        Launcher,
        Action,
        ActionSteps,
    }

    /// Tags every line of `template` with the section it falls under, by the last
    /// `[section]` or `[[array]]` header seen. A struct's own scalar fields are declared
    /// only inside its own section header's own array-of-tables, so `[[action.steps]]`
    /// switches away from `Action` (a step's fields are not an action's), and a fresh
    /// `[[action]]` switches back.
    fn sectioned_lines(template: &str) -> Vec<(TemplateSection, &str)> {
        let mut section = TemplateSection::TopLevel;
        template
            .lines()
            .map(|line| {
                let trimmed = line.trim();
                if trimmed.starts_with("[[action.steps]]") {
                    section = TemplateSection::ActionSteps;
                } else if trimmed.starts_with("[[set]]") {
                    section = TemplateSection::Set;
                } else if trimmed.starts_with("[[repo]]") {
                    section = TemplateSection::Repo;
                } else if trimmed.starts_with("[[launcher]]") {
                    section = TemplateSection::Launcher;
                } else if trimmed.starts_with("[[action]]") {
                    section = TemplateSection::Action;
                } else if trimmed.starts_with("[refresh]") {
                    section = TemplateSection::Refresh;
                } else if trimmed.starts_with("[fetch]") {
                    section = TemplateSection::Fetch;
                } else if trimmed.starts_with("[auto_update]") {
                    section = TemplateSection::AutoUpdate;
                }
                (section, line)
            })
            .collect()
    }

    /// Whether `line` declares `key`, live or commented out: a leading `#` is stripped
    /// first, so `# poll_interval = "2s"` and `poll_interval = "2s"` both count, and a
    /// prose comment that never reaches an `=` (`# The pipe is why...`) never falsely
    /// matches a key that happens to prefix one of its words.
    fn line_declares_key(line: &str, key: &str) -> bool {
        let line = line.trim();
        let line = line.strip_prefix('#').map(str::trim).unwrap_or(line);
        line.strip_prefix(key)
            .map(|rest| rest.trim_start().starts_with('='))
            .unwrap_or(false)
    }

    /// Whether `key` is declared anywhere inside `section`, live or commented out.
    fn section_declares_key(
        lines: &[(TemplateSection, &str)],
        section: TemplateSection,
        key: &str,
    ) -> bool {
        lines
            .iter()
            .filter(|(line_section, _)| *line_section == section)
            .any(|(_, line)| line_declares_key(line, key))
    }

    /// Every key name [`Document`] itself declares, split into the bare scalars (checked
    /// as a `key = value` line) and the tables and arrays of tables (checked as a header).
    /// An exhaustive destructure with no `..` tail: a field added to `Document` fails this
    /// to compile until it is named here too, rather than the check below silently never
    /// seeing it (the hand-enumeration failure this ticket was asked to watch for).
    fn document_field_names() -> (&'static [&'static str], &'static [&'static str]) {
        let Document {
            theme: _,
            glyphs: _,
            show_worktrees: _,
            show_submodules: _,
            advance_on_toggle: _,
            notice_timeout: _,
            on_refresh: _,
            before_sync: _,
            after_sync: _,
            refresh: _,
            fetch: _,
            auto_update: _,
            sets: _,
            repos: _,
            launchers: _,
            actions: _,
            keys: _,
        } = Document::default();
        (
            &[
                "theme",
                "glyphs",
                "show_worktrees",
                "show_submodules",
                "advance_on_toggle",
                "notice_timeout",
                "on_refresh",
                "before_sync",
                "after_sync",
            ],
            &[
                "[refresh]",
                "[fetch]",
                "[auto_update]",
                "[keys",
                "[[set]]",
                "[[repo]]",
                "[[launcher]]",
                "[[action]]",
            ],
        )
    }

    /// The same exhaustive-destructure guard as [`document_field_names`], one per nested
    /// or repeated table. A required field (`SetConfig::name`, `RepoConfig::path`,
    /// `LauncherConfig::name`, `ActionConfig::{name,steps}`, `StepConfig::args`) still
    /// needs a value to destructure, so each parses the smallest document that can carry
    /// it rather than restating its shape as a struct literal a second time.
    fn refresh_config_field_names() -> &'static [&'static str] {
        let RefreshConfig {
            poll_interval: _,
            status_stale_after: _,
            on_focus: _,
        } = RefreshConfig::default();
        &["poll_interval", "status_stale_after", "on_focus"]
    }

    fn fetch_config_field_names() -> &'static [&'static str] {
        let FetchConfig {
            enabled: _,
            interval: _,
            concurrency: _,
        } = FetchConfig::default();
        &["enabled", "interval", "concurrency"]
    }

    fn auto_update_config_field_names() -> &'static [&'static str] {
        let AutoUpdateConfig { enabled: _ } = AutoUpdateConfig::default();
        &["enabled"]
    }

    fn set_config_field_names() -> &'static [&'static str] {
        let SetConfig {
            name: _,
            roots: _,
            include: _,
            exclude: _,
            on_refresh: _,
            before_sync: _,
            after_sync: _,
        } = toml::from_str::<SetConfig>("name = \"x\"\nroots = []\n").expect("minimal SetConfig");
        &[
            "name",
            "roots",
            "include",
            "exclude",
            "on_refresh",
            "before_sync",
            "after_sync",
        ]
    }

    fn repo_config_field_names() -> &'static [&'static str] {
        let RepoConfig {
            path: _,
            default_branch: _,
            exclude: _,
        } = toml::from_str::<RepoConfig>("path = \"x\"\n").expect("minimal RepoConfig");
        &["path", "default_branch", "exclude"]
    }

    fn launcher_config_field_names() -> &'static [&'static str] {
        let LauncherConfig {
            name: _,
            args: _,
            from_env: _,
            shell: _,
            interactive: _,
            takes_terminal: _,
            env: _,
            disabled: _,
        } = toml::from_str::<LauncherConfig>("name = \"x\"\n").expect("minimal LauncherConfig");
        &[
            "name",
            "args",
            "from_env",
            "shell",
            "interactive",
            "takes_terminal",
            "env",
            "disabled",
        ]
    }

    /// `steps` is excluded here: it is `[[action.steps]]`, an array-of-tables header
    /// rather than a `key = value` line, so the exhaustiveness test below checks it as a
    /// header the same way it checks `Document`'s own array-of-tables fields.
    fn action_config_field_names() -> &'static [&'static str] {
        let ActionConfig {
            name: _,
            description: _,
            steps: _,
            confirm: _,
            concurrency: _,
            when: _,
        } = toml::from_str::<ActionConfig>("name = \"x\"\nsteps = []\n")
            .expect("minimal ActionConfig");
        &["name", "description", "confirm", "concurrency", "when"]
    }

    fn step_config_field_names() -> &'static [&'static str] {
        let StepConfig {
            args: _,
            shell: _,
            interactive: _,
            env: _,
        } = toml::from_str::<StepConfig>("args = []\n").expect("minimal StepConfig");
        &["args", "shell", "interactive", "env"]
    }

    /// Done when: "Every key in the schema appears in the template, proven by a test that
    /// fails when a field is added to a struct and not to the file." Each `*_field_names`
    /// helper above is pinned to its struct by an exhaustive destructure, so a field added
    /// there and never named here fails this file to compile; this test is what then
    /// checks the file actually shows it, commented out or live, rather than trusting the
    /// list of currently-omitted keys this ticket opened with.
    #[test]
    fn every_schema_field_appears_somewhere_in_the_shipped_template() {
        let template = annotated_example();
        let lines = sectioned_lines(template);

        let (top_level, headers) = document_field_names();
        let mut missing = Vec::new();
        for key in top_level {
            if !section_declares_key(&lines, TemplateSection::TopLevel, key) {
                missing.push(format!("Document.{key}"));
            }
        }
        for header in headers {
            if !template.contains(header) {
                missing.push(format!("Document.{header}"));
            }
        }

        let sections: &[(&str, TemplateSection, &[&str])] = &[
            (
                "RefreshConfig",
                TemplateSection::Refresh,
                refresh_config_field_names(),
            ),
            (
                "FetchConfig",
                TemplateSection::Fetch,
                fetch_config_field_names(),
            ),
            (
                "AutoUpdateConfig",
                TemplateSection::AutoUpdate,
                auto_update_config_field_names(),
            ),
            ("SetConfig", TemplateSection::Set, set_config_field_names()),
            (
                "RepoConfig",
                TemplateSection::Repo,
                repo_config_field_names(),
            ),
            (
                "LauncherConfig",
                TemplateSection::Launcher,
                launcher_config_field_names(),
            ),
            (
                "ActionConfig",
                TemplateSection::Action,
                action_config_field_names(),
            ),
            (
                "StepConfig",
                TemplateSection::ActionSteps,
                step_config_field_names(),
            ),
        ];
        for (struct_name, section, fields) in sections {
            for key in *fields {
                if !section_declares_key(&lines, *section, key) {
                    missing.push(format!("{struct_name}.{key}"));
                }
            }
        }
        // `ActionConfig::steps` is its own array-of-tables header, checked separately from
        // `action_config_field_names`'s scalar keys.
        if !template.contains("[[action.steps]]") {
            missing.push("ActionConfig.steps".to_string());
        }

        assert!(
            missing.is_empty(),
            "example.toml omits these schema fields entirely: {missing:?}"
        );
    }

    /// Every commented-out `key = value` line in `template`, uncommented in place: a
    /// standalone comment whose text never reaches an `=` (prose) is left alone, so only a
    /// line shaped like a default demonstration is affected. This is what "uncommenting
    /// the entire template" (config.md's "An annotated example") means for the checks
    /// below.
    fn uncomment_defaults(template: &str) -> String {
        template
            .lines()
            .map(|line| {
                let trimmed = line.trim_start();
                let Some(rest) = trimmed.strip_prefix('#') else {
                    return line.to_string();
                };
                let candidate = rest.trim_start();
                let key_end = candidate
                    .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.'))
                    .unwrap_or(candidate.len());
                let is_key_value =
                    key_end > 0 && candidate[key_end..].trim_start().starts_with('=');
                if is_key_value {
                    let indent = &line[..line.len() - trimmed.len()];
                    format!("{indent}{candidate}")
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    // `repon config --example` prints this exact text; parsing it here, rather than a
    // hand-typed copy, is what proves the printed example and the real schema cannot drift
    // apart. No unknown key means every line the spec shows is a key this schema knows.
    #[test]
    fn the_annotated_example_parses_against_the_real_schema() {
        let example = annotated_example();
        assert!(
            example.starts_with("# This terminal draws braille"),
            "expected the extracted block to start with the spec's own comment, got: {example:?}"
        );

        let loaded = parse_ok(example);

        let unknown: Vec<&Warning> = loaded
            .warnings
            .iter()
            .filter(|warning| matches!(warning, Warning::UnknownKey(_)))
            .collect();
        assert!(
            unknown.is_empty(),
            "expected no unknown-key warnings, got: {unknown:?}"
        );
    }

    // The example's own `[keys]` block, the "single source of truth shared by production and
    // its tests" trap named in this ticket's brief: a hand-typed example that merely parses
    // as a TOML table proves nothing about whether its context and action names are real.
    // This runs it through the actual merge `crate::keys::merge` performs and asserts it
    // raises neither an unknown-context nor an unknown-action warning, and does rebind and
    // unbind the keys it names.
    #[test]
    fn the_annotated_examples_keys_block_merges_cleanly_and_does_what_its_comments_say() {
        let loaded = parse_ok(annotated_example());
        let (bindings, warnings) =
            crate::keys::merge(&loaded.document.keys).expect("expected the keys block to merge");
        assert!(
            warnings.is_empty(),
            "expected the shipped example's [keys] block to raise no warning, got: {warnings:?}"
        );

        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
        // "a rebind moves the binding": refresh_all moved from `r` to Ctrl+L, and its old
        // key is gone.
        assert_eq!(
            bindings.dispatch(
                crate::keys::Context::Global,
                KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)
            ),
            Some(crate::keys::Action::RefreshAll)
        );
        assert_eq!(
            bindings.dispatch(
                crate::keys::Context::Global,
                KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE)
            ),
            None
        );
        // "unbind it entirely": anchor_range no longer fires on `v`.
        assert_eq!(
            bindings.dispatch(
                crate::keys::Context::List,
                KeyEvent::new(KeyCode::Char('v'), KeyModifiers::NONE)
            ),
            None
        );
    }

    // Every value the example shows that already equals the compiled default is annotation
    // only: deleting it falls back to the same value through the deep merge. Comparing
    // against each type's own `Default::default()`, the single source of truth, rather than a
    // value copied by hand, is what would catch the example drifting from a changed default.
    //
    // Most of those values are now shown commented out rather than live (the template's own
    // "full surface" this ticket asked for), so this parses `uncomment_defaults`'s output
    // rather than the shipped text directly: a comment is invisible to the parser, and a
    // commented default with nothing pinning it to the real one is exactly the drift this
    // test exists to catch. No unknown-key warning is what proves every uncommented key is
    // one the schema actually knows, the same filter `the_annotated_example_parses_against_
    // the_real_schema` already applies above: the shipped `[[repo]]` paths and `[[set]]`
    // globs are demonstration values, real only on the machine `config.md` was written on,
    // so `RepoPathMatchesNothing` and `SetGlobMatchesNothing` are expected here and are not
    // this test's concern.
    #[test]
    fn every_default_valued_field_the_example_shows_could_be_deleted() {
        let uncommented = uncomment_defaults(annotated_example());
        let loaded = parse_ok(&uncommented);
        let unknown: Vec<&Warning> = loaded
            .warnings
            .iter()
            .filter(|warning| matches!(warning, Warning::UnknownKey(_)))
            .collect();
        assert!(
            unknown.is_empty(),
            "uncommenting the whole template must raise no unknown-key warning, got: {unknown:?}"
        );
        let document = &loaded.document;

        assert_eq!(document.theme, Document::default().theme);
        assert_eq!(document.glyphs, Glyphs::default());
        assert_eq!(document.show_worktrees, Document::default().show_worktrees);
        assert_eq!(
            document.show_submodules,
            Document::default().show_submodules
        );
        assert_eq!(document.notice_timeout, Document::default().notice_timeout);
        assert_eq!(
            document.refresh.poll_interval,
            RefreshConfig::default().poll_interval
        );
        assert_eq!(
            document.refresh.status_stale_after,
            RefreshConfig::default().status_stale_after
        );
        assert_eq!(document.refresh.on_focus, RefreshConfig::default().on_focus);
        assert_eq!(document.fetch.interval, FetchConfig::default().interval);
        assert_eq!(
            document.fetch.concurrency,
            FetchConfig::default().concurrency
        );

        let editor = document
            .launchers
            .iter()
            .find(|launcher| launcher.name.get_ref() == "editor")
            .expect("the example's editor launcher");
        assert_eq!(editor.env, BTreeMap::new());
        assert!(!editor.disabled);

        let reinstall = document
            .actions
            .iter()
            .find(|action| action.name.get_ref() == "reinstall")
            .expect("the example's reinstall action");
        assert_eq!(reinstall.confirm, default_action_confirm());
        let rm_step = reinstall.steps.first().expect("reinstall's first step");
        assert!(!rm_step.shell);
        assert_eq!(rm_step.env, BTreeMap::new());

        // The negative control: the example deliberately turns these on, or away from
        // their default, to show what an active fetch, auto-update and scoped Action look
        // like, so they must NOT equal the compiled default, or the assertions above
        // would be vacuously true regardless of what they compared.
        assert_ne!(document.fetch.enabled, FetchConfig::default().enabled);
        assert_ne!(
            document.auto_update.enabled,
            AutoUpdateConfig::default().enabled
        );
        assert!(reinstall.when.is_some());
    }

    /// The same extraction `annotated_example()` used to do at compile time, run here at
    /// test time instead so the specification can live outside the crate.
    fn extract_fenced_example(spec: &str) -> &str {
        const HEADING: &str = "## An annotated example";
        const FENCE_OPEN: &str = "```toml\n";
        const FENCE_CLOSE: &str = "\n```";

        let after_heading = &spec[spec
            .find(HEADING)
            .expect("config.md must contain the annotated example section")..];
        let body = &after_heading[after_heading
            .find(FENCE_OPEN)
            .expect("the annotated example section must open a ```toml fence")
            + FENCE_OPEN.len()..];
        let fence_close = body
            .find(FENCE_CLOSE)
            .expect("the annotated example section must close its ```toml fence");
        &body[..=fence_close]
    }

    /// Reads `docs/spec/config.md` at test time via `CARGO_MANIFEST_DIR` rather than
    /// `include_str!`, following repon-core's precedent for `GLOSSARY.md`: the spec lives
    /// outside this crate's directory, so `include_str!` would compile fine in the
    /// workspace checkout but fail the packaged crate's build with no test to report it.
    fn read_config_spec() -> String {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        std::fs::read_to_string(manifest_dir.join("../../docs/spec/config.md"))
            .expect("read the config specification")
    }

    /// The default value the "Actions" field table's own row for `field` states, e.g.
    /// `"true"` from `| \`confirm\` | bool, default \`true\` | ... |`. Read from the
    /// document's own text rather than hand-copied, so a spec edit and this test's
    /// expectation can never silently drift apart.
    fn spec_action_field_default(spec: &str, field: &str) -> String {
        let anchor = format!("| `{field}` |");
        let row = spec
            .lines()
            .find(|line| line.contains(&anchor))
            .unwrap_or_else(|| panic!("no `{field}` row in the Actions field table"));
        let after = row
            .split("default `")
            .nth(1)
            .unwrap_or_else(|| panic!("`{field}`'s row names no stated default: {row}"));
        after
            .split('`')
            .next()
            .unwrap_or_else(|| {
                panic!("`{field}`'s default value is not backtick-terminated: {row}")
            })
            .to_string()
    }

    /// The comment block directly above `header` in `example`: the text between the
    /// nearest blank line before it and `header` itself.
    fn comment_block_immediately_above<'a>(example: &'a str, header: &str) -> &'a str {
        let marker = format!("\n\n{header}");
        let header_at = example
            .find(&marker)
            .unwrap_or_else(|| panic!("example has no {header} header"));
        let before = &example[..header_at];
        let block_start = before.rfind("\n\n").map_or(0, |i| i + 2);
        &before[block_start..]
    }

    /// The block's own prose, with any line carrying the spec URL removed, so a term
    /// check can't be satisfied by the link's anchor text instead of the explanation.
    fn strip_link_lines(block: &str) -> String {
        block
            .lines()
            .filter(|line| !line.contains("http"))
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// The comment above [refresh] must keep naming all four of refresh, fetch,
    /// auto_update and sync so a future edit cannot drop one silently.
    #[test]
    fn the_refresh_fetch_and_auto_update_block_is_preceded_by_a_comment_naming_all_four_terms() {
        let prose = strip_link_lines(comment_block_immediately_above(
            annotated_example(),
            "[refresh]",
        ));

        for term in ["refresh", "fetch", "auto_update", "sync"] {
            assert!(
                prose.contains(term),
                "the comment above [refresh] does not mention `{term}` outside its link: {prose}"
            );
        }
    }

    /// `sync` names two different things here (GLOSSARY.md's Cell and the built-in
    /// Management action), so naming the bare word once is not enough: the comment must
    /// name both senses, not just the one a stray edit happens to leave behind.
    #[test]
    fn the_comment_distinguishes_the_sync_action_from_the_sync_cell() {
        let prose = strip_link_lines(comment_block_immediately_above(
            annotated_example(),
            "[refresh]",
        ));

        assert!(
            prose.matches("sync").count() >= 2,
            "the comment names `sync` only once, not both its senses: {prose}"
        );
        assert!(
            prose.contains("action"),
            "the comment does not name the sync action: {prose}"
        );
        assert!(
            prose.contains("Cell"),
            "the comment does not name the sync Cell as a separate thing: {prose}"
        );
    }

    /// The comment's link must survive a heading rename: if "## Refresh, fetch and
    /// auto-update" ever moves or is reworded, this fails alongside the dead anchor rather
    /// than shipping a template that links nowhere.
    #[test]
    fn the_refresh_fetch_and_auto_update_comment_links_to_its_own_spec_section() {
        let spec = read_config_spec();
        assert!(
            spec.contains("## Refresh, fetch and auto-update"),
            "config.md must keep its \"Refresh, fetch and auto-update\" heading"
        );

        let block = comment_block_immediately_above(annotated_example(), "[refresh]");
        assert!(
            block.contains(
                "https://github.com/paulchiu/repon/blob/main/docs/spec/config.md#refresh-fetch-and-auto-update"
            ),
            "the comment above [refresh] does not link to its own spec section: {block}"
        );
    }

    /// Comparing its fenced block against the shipped `example.toml` byte for byte is what
    /// keeps `repon config --example`'s output and the specification from drifting apart.
    #[test]
    fn the_shipped_example_matches_the_specs_fenced_block() {
        let spec = read_config_spec();
        let expected = extract_fenced_example(&spec);
        assert_eq!(
            annotated_example(),
            expected,
            "config/example.toml has drifted from docs/spec/config.md's annotated example"
        );
    }

    /// Reads `llms.txt` at the repo root via `CARGO_MANIFEST_DIR`, following
    /// [`read_config_spec`]'s precedent: the file lives outside this crate's directory.
    fn read_llms_txt() -> String {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        std::fs::read_to_string(manifest_dir.join("../../llms.txt")).expect("read llms.txt")
    }

    /// Every markdown link's url in `text`, in order. A plain scan rather than a regex
    /// dependency: `](url)` is unambiguous in a file with no other use of `](`.
    fn markdown_link_urls(text: &str) -> Vec<String> {
        let mut urls = Vec::new();
        let mut rest = text;
        while let Some(start) = rest.find("](") {
            let after = &rest[start + 2..];
            let end = after.find(')').expect("an opened markdown link must close");
            urls.push(after[..end].to_string());
            rest = &after[end + 1..];
        }
        urls
    }

    /// Issue #352: `llms.txt` is Repon's front door for a coding agent, and it only earns
    /// that role by staying accurate. Every link must resolve to a real file once the raw
    /// prefix is stripped, and every `docs/spec/` file must be referenced, so a new spec
    /// cannot be added without `llms.txt` learning about it.
    #[test]
    fn llms_txt_links_all_resolve_and_all_specs_are_listed() {
        const RAW_PREFIX: &str = "https://raw.githubusercontent.com/paulchiu/repon/main/";

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let repo_root = manifest_dir.join("../..");
        let llms_txt = read_llms_txt();

        for url in markdown_link_urls(&llms_txt) {
            let relative = url
                .strip_prefix(RAW_PREFIX)
                .unwrap_or_else(|| panic!("llms.txt link is not rooted at {RAW_PREFIX}: {url}"));
            assert!(
                repo_root.join(relative).exists(),
                "llms.txt references missing file: {relative}"
            );
        }

        let spec_names = fs::read_dir(repo_root.join("docs/spec"))
            .expect("read docs/spec")
            .map(|entry| {
                entry
                    .expect("read a docs/spec entry")
                    .file_name()
                    .to_string_lossy()
                    .into_owned()
            })
            .filter(|name| name.ends_with(".md"));
        for name in spec_names {
            assert!(
                llms_txt.contains(&format!("docs/spec/{name}")),
                "docs/spec/{name} is not referenced in llms.txt"
            );
        }
    }

    /// The name of the key carrying an Action's applicability predicate, read out of
    /// [config.md](../../../../docs/spec/config.md)'s own "Actions" table rather than
    /// restated here: the row is the one whose meaning names the Filter grammar, and its
    /// first backticked cell is the key. A rename in the document that never reached the
    /// schema fails the test below rather than passing beside it.
    fn the_applicability_key_config_md_names() -> String {
        let spec = read_config_spec();
        let actions = spec
            .split("## Actions")
            .nth(1)
            .expect("config.md must carry an Actions section");
        let row = actions
            .lines()
            .take_while(|line| !line.starts_with("## "))
            .find(|line| line.starts_with('|') && line.contains("Filter grammar"))
            .expect("config.md's Actions table must carry a row naming the Filter grammar");
        row.split('`')
            .nth(1)
            .expect("that row must name its key in backticks")
            .to_string()
    }

    /// Criterion 1: the key config.md names is the key the schema parses, and it reaches
    /// `ActionConfig` carrying the text the file wrote verbatim. An unknown-key warning is
    /// asserted absent as well, since a key the schema does not know parses "fine" and warns
    /// instead of failing, which would leave a silent nothing behind this assertion.
    #[test]
    fn an_action_parses_the_applicability_predicate_key_config_md_names() {
        let key = the_applicability_key_config_md_names();
        let loaded = parse_ok(&format!(
            "[[action]]\nname = \"reinstall\"\n{key} = \"kind:repo\"\n\n\
             [[action.steps]]\nargs = [\"true\"]\n"
        ));

        assert!(
            !loaded
                .warnings
                .iter()
                .any(|warning| matches!(warning, Warning::UnknownKey(path) if path.contains(&key))),
            "`{key}` is a key of the schema, not an unknown one: {:?}",
            loaded.warnings
        );
        assert_eq!(
            loaded.document.actions[0].when.as_deref(),
            Some("kind:repo")
        );
    }

    /// Criterion 2: totality carries over, so a `when` naming nothing the grammar knows is
    /// not a load error and adds no failure grade of its own. The three inputs are the
    /// grammar's own documented degenerate cases, each of which matches nothing and none of
    /// which is a failure ([0022](../../../../docs/adr/0022-the-filter-language-is-total-and-three-valued.md)).
    #[test]
    fn a_when_naming_nothing_the_grammar_knows_is_never_a_load_error() {
        let key = the_applicability_key_config_md_names();
        for predicate in ["is:banana", ":", "kimd:repo"] {
            let loaded = parse_ok(&format!(
                "[[action]]\nname = \"reinstall\"\n{key} = \"{predicate}\"\n\n\
                 [[action.steps]]\nargs = [\"true\"]\n"
            ));
            assert_eq!(
                loaded.document.actions[0].when.as_deref(),
                Some(predicate),
                "the text must reach the schema unaltered, since nothing here judges it"
            );
            assert!(
                loaded.warnings.is_empty(),
                "a predicate matching nothing is not a condition to warn about: {:?}",
                loaded.warnings
            );
        }
    }

    /// Issue #58, criterion 4's "no config key" half: the PTY is a fixed 120-column
    /// constant, never a config key. An exhaustive destructure names every field
    /// `ActionConfig` has; a width field added under any name fails to compile this
    /// test rather than landing unacknowledged.
    #[test]
    fn action_config_carries_no_pty_width_field_the_pty_is_a_fixed_constant_never_a_config_key() {
        let loaded =
            parse_ok("[[action]]\nname = \"reinstall\"\n\n[[action.steps]]\nargs = [\"true\"]\n");
        let ActionConfig {
            name: _,
            description: _,
            steps: _,
            confirm: _,
            concurrency: _,
            when: _,
        } = loaded
            .document
            .actions
            .into_iter()
            .next()
            .expect("one parsed [[action]] entry");
    }

    /// Criterion 1: every field [config.md](../../../../docs/spec/config.md#actions)'s
    /// "Actions" table names, parsed from one entry that sets all of them, an ordered
    /// step carrying `args`, `shell` and `env` together, and description preserved
    /// rather than discarded.
    #[test]
    fn an_action_entry_parses_every_field_the_spec_names() {
        let loaded = parse_ok(
            "[[action]]\n\
             name = \"reinstall\"\n\
             description = \"Reinstall dependencies from scratch\"\n\
             confirm = false\n\
             concurrency = 8\n\n\
             [[action.steps]]\n\
             args = [\"rm -rf node_modules && pnpm install\"]\n\
             shell = true\n\
             env = { FOO = \"bar\" }\n",
        );
        let action = &loaded.document.actions[0];
        assert_eq!(action.name.get_ref(), "reinstall");
        assert_eq!(
            action.description.as_deref(),
            Some("Reinstall dependencies from scratch")
        );
        assert!(!action.confirm);
        assert_eq!(action.concurrency, 8);
        assert_eq!(action.steps.len(), 1);
        assert_eq!(
            action.steps[0].args,
            vec!["rm -rf node_modules && pnpm install"]
        );
        assert!(action.steps[0].shell);
        assert_eq!(
            action.steps[0].env.get("FOO").map(String::as_str),
            Some("bar")
        );
    }

    /// Criterion 1: `steps` is required, per
    /// [config.md](../../../../docs/spec/config.md#actions)'s "ordered list of step
    /// tables, required". An `[[action]]` naming no steps at all must fail to parse
    /// rather than silently default to an empty run.
    #[test]
    fn an_action_with_no_steps_field_at_all_fails_to_parse() {
        parse_err("[[action]]\nname = \"reinstall\"\n");
    }

    /// Criterion 1: `confirm`'s default is read from
    /// [config.md](../../../../docs/spec/config.md#actions) at test time rather than
    /// restated as a literal, so a schema that flipped the default to off (silently
    /// running a destructive Action unprompted) would be caught here rather than only
    /// in a hand-maintained expectation that drifted along with the same mistake.
    #[test]
    fn action_confirm_defaults_to_the_specs_own_stated_value() {
        let spec = read_config_spec();
        let expected: bool = spec_action_field_default(&spec, "confirm")
            .parse()
            .expect("confirm's stated default parses as a bool");

        let loaded =
            parse_ok("[[action]]\nname = \"reinstall\"\n\n[[action.steps]]\nargs = [\"true\"]\n");

        assert_eq!(loaded.document.actions[0].confirm, expected);
    }

    /// Criterion 1: `concurrency`'s default, read the same way `confirm`'s is.
    #[test]
    fn action_concurrency_defaults_to_the_specs_own_stated_value() {
        let spec = read_config_spec();
        let expected: u32 = spec_action_field_default(&spec, "concurrency")
            .parse()
            .expect("concurrency's stated default parses as an integer");

        let loaded =
            parse_ok("[[action]]\nname = \"reinstall\"\n\n[[action.steps]]\nargs = [\"true\"]\n");

        assert_eq!(loaded.document.actions[0].concurrency, expected);
    }

    /// Criterion 1: "no schema maximum" is an absence claim, so checking only
    /// the default (four) proves nothing about whether some later clamp was added. A
    /// concurrency far past any plausible clamp must still parse to exactly what was
    /// written.
    #[test]
    fn action_concurrency_has_no_schema_maximum() {
        let loaded = parse_ok(
            "[[action]]\nname = \"reinstall\"\nconcurrency = 999999999\n\n\
             [[action.steps]]\nargs = [\"true\"]\n",
        );

        assert_eq!(loaded.document.actions[0].concurrency, 999_999_999);
    }

    /// Criterion 1: "unique name" needs a test that two Actions sharing a
    /// name is rejected, not just that one Action parses, the same shape
    /// [`a_duplicate_set_name_is_rejected_with_a_line_number`] and
    /// [`a_duplicate_repo_path_is_rejected_with_a_line_number`] already prove for their
    /// own identity fields.
    #[test]
    fn a_duplicate_action_name_is_rejected_with_a_line_number() {
        let message = parse_err(
            "[[action]]\nname = \"reinstall\"\n\n[[action.steps]]\nargs = [\"true\"]\n\n\
             [[action]]\nname = \"reinstall\"\n\n[[action.steps]]\nargs = [\"true\"]\n",
        );
        assert!(message.contains("duplicate action name"));
        assert!(
            message.contains("line 8"),
            "expected the second declaration's line, got: {message}"
        );
    }

    /// Criterion 7: a config-defined `[[action]]` may not take a built-in management
    /// operation's name, and the load fails with the message shape a second `[[action]]` of
    /// an already-taken name produces rather than one shadowing the other
    /// ([repo-management.md](../../../../docs/spec/repo-management.md)'s "The operations").
    ///
    /// The expected message is built from a real duplicate's own, with the name substituted,
    /// so this cannot pass against a differently-worded message that merely happens to carry
    /// the same words: if the two grades ever diverge, the comparison fails.
    #[test]
    fn a_config_action_taking_a_reserved_name_fails_with_the_duplicate_name_message_shape() {
        let steps = "\n[[action.steps]]\nargs = [\"true\"]\n";
        for operation in crate::management::OPERATIONS {
            let name = operation.name();
            let reserved = parse_err(&format!("[[action]]\nname = \"{name}\"{steps}"));
            let genuine_duplicate = parse_err(&format!(
                "[[action]]\nname = \"not-reserved\"{steps}\n\
                 [[action]]\nname = \"not-reserved\"{steps}"
            ));

            let shape = |message: &str| {
                message
                    .split(" at line")
                    .next()
                    .expect("a message")
                    .to_string()
            };
            assert_eq!(
                shape(&reserved),
                shape(&genuine_duplicate).replace("not-reserved", name),
                "a reserved name must fail with the same grade and wording a duplicate does"
            );
            assert!(
                reserved.contains("line 2"),
                "expected the offending declaration's own line, got: {reserved}"
            );
        }
    }

    /// `unignore` is not a built-in any more, so the name is the user's to take: `ignore`
    /// covers both directions and nothing in the palette answers to the old name.
    #[test]
    fn a_config_action_may_take_the_name_unignore() {
        let loaded =
            parse_ok("[[action]]\nname = \"unignore\"\n\n[[action.steps]]\nargs = [\"true\"]\n");

        assert_eq!(loaded.document.actions[0].name.get_ref(), "unignore");
    }

    /// The negative control: a name that merely contains a reserved one is not reserved, so
    /// the check is an equality on the whole name rather than a substring test that would
    /// quietly forbid `ignore-vendored`.
    #[test]
    fn an_action_name_that_merely_contains_a_reserved_one_still_loads() {
        let loaded = parse_ok(
            "[[action]]\nname = \"ignore-vendored\"\n\n[[action.steps]]\nargs = [\"true\"]\n",
        );

        assert_eq!(loaded.document.actions[0].name.get_ref(), "ignore-vendored");
    }

    /// Criterion 2's "no config key" half, for `[refresh]`: `refresh.md`'s "Scope and
    /// order" makes scope never a partial dial, not even as a config toggle, and this is
    /// where such a toggle would have to live if one existed. An exhaustive destructure
    /// names every field `RefreshConfig` has (`docs/spec/config.md`'s three
    /// `refresh.*` keys); a fourth field, under any name, fails to compile this test
    /// rather than landing unacknowledged.
    #[test]
    fn refresh_config_carries_no_scoping_field_scope_is_never_a_config_toggle() {
        let RefreshConfig {
            poll_interval: _,
            status_stale_after: _,
            on_focus: _,
        } = RefreshConfig::default();
    }
}