wsb 0.275.7622

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
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
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{generate, Shell};
use colored::Colorize;
use std::env;
use std::fs;
use std::io::IsTerminal;
use std::process::exit;
use std::time::Instant;
use wsb::app::AppContext;
use wsb::fleet::config::GitModules;
use wsb::fleet::error::SuperGitError;
use wsb::fleet::git::{SubmoduleOps, SubmoduleTree};
use wsb::logging::{
    log_operation_complete, log_operation_error, log_operation_start, log_version_info,
    setup_logging,
};
use wsb::prelude::*;
use wsb::state::discard::owns_templates;
use wsb::annotations::Ref;
use wsb::roots;
use wsb::settings::{ProjectSettings, RepoSettings, VersionSettings};
use wsb::state::{
    detect_project_files, is_git_repository_in, update_version_file_in_repo, RunCache, VersionInfo,
    WstemplateEngine,
};

#[derive(Parser, Debug)]
#[command(name = "wsb")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(about = "Worktree - All-in-one development tool suite")]
#[command(
    after_help = "When no subcommand is provided, `wsb` defaults to `serve`.\nRun `wsb completions` to install shell completions."
)]
struct Args {
    /// Emit every line — this command's own output and that of every process
    /// it runs — as JSONL records instead of text meant for a terminal.
    ///
    /// Removed from the argument vector before parsing (see `main`), so it
    /// reaches `wsb github` too, which reads its own arguments. This
    /// declaration is what puts it in `--help`, and reaching the parser at all
    /// means the scan that removes it did not run.
    #[arg(long, global = true)]
    jsonl: bool,

    /// Do the work in this process, with no daemon.
    ///
    /// Nothing is started or told: the run is not shown in the workbench, and
    /// there is no workbench — it is served by the daemon, and this flag says
    /// not to have one.
    ///
    /// Taken out of the arguments before anything parses them, like
    /// `--jsonl`, and passed on to every wsb the run starts, so one flag covers
    /// the whole tree of processes.
    #[arg(long, global = true)]
    no_daemon: bool,

    /// Write into the worktree even while it is locked.
    ///
    /// Whatever copies the tree holds the workspace lock while the copy is
    /// made, and every command that writes into the tree waits for it (five
    /// minutes at most). This proceeds regardless, and says so. Passed on to
    /// every wsb the command starts.
    #[arg(long, global = true)]
    ignore_worktree_lock: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Refactor files and directories using patterns
    Refactor {
        /// Arguments for refactor tool
        #[command(flatten)]
        args: wsb::refactor::Args,
    },

    /// Show status of the active git scope
    Status {
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Throw away local changes across every worktree, after showing what
    /// would go and asking.
    ///
    /// Finds every repository in the fleet with changes — the one you are
    /// standing in and every submodule under it — lists them file by file,
    /// and discards only once you have typed 'yes'. Tracked changes go back
    /// to HEAD; untracked files are left alone unless --untracked says
    /// otherwise; ignored files (build output, .wsb/ state) are never
    /// touched.
    Discard {
        /// Delete untracked files too
        #[arg(long)]
        untracked: bool,
        /// Do not ask
        #[arg(long)]
        yes: bool,
        /// Show what would go, and stop
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Checkout a branch in the active git scope
    Checkout {
        /// Branch name to checkout
        branch: String,
        /// Create the branch if it doesn't exist
        #[arg(short, long)]
        create: bool,
        /// Skip repositories where the branch does not exist instead of failing
        #[arg(long)]
        ignore_missing: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Pull latest changes in the active git scope
    Pull {
        /// Replay local commits on top of the incoming ones instead of
        /// refusing a branch that has diverged
        #[arg(short, long)]
        rebase: bool,
        /// Set aside local changes to the files the incoming commits rewrite,
        /// pull, then put them back on top
        #[arg(long)]
        autostash: bool,
        /// Throw away local changes to the files the incoming commits rewrite.
        /// Only those files; everything else in the tree is left alone
        #[arg(long, conflicts_with = "autostash")]
        overwrite_local: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Push changes in the active git scope
    Push {
        /// Force push with lease
        #[arg(short, long)]
        force_with_lease: bool,
        /// Apply to every repository regardless of whether there are outgoing commits
        #[arg(long)]
        force_all: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Create a new branch in the active git scope
    Create {
        /// Branch name to create
        branch: String,
        /// Base branch to create from
        #[arg(short, long)]
        from: Option<String>,
        /// Push the new branch immediately
        #[arg(short, long)]
        push: bool,
        /// Apply to every repository regardless of whether its worktree has changes
        #[arg(long)]
        force_all: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Commit changes in the active git scope
    Commit {
        /// Commit message
        #[arg(short, long)]
        message: String,
        /// Push after committing
        #[arg(short, long)]
        push: bool,
        /// Stage all unstaged changes before committing (git add -A)
        #[arg(short = 'a', long)]
        stage_all: bool,
        /// Exclude repos by alias; may be repeated (applied after --include)
        #[arg(short = 'x', long = "exclude", value_name = "ALIAS")]
        exclude: Vec<String>,
        /// Include only these aliases (whitelist); may be repeated
        #[arg(short = 'i', long = "include", value_name = "ALIAS")]
        include: Vec<String>,
        /// Apply to every repository regardless of whether its worktree has changes
        #[arg(long)]
        force_all: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Synchronize the active git scope
    Sync {
        /// Initialize missing submodules
        #[arg(short, long)]
        init: bool,
        /// Recursive sync for nested submodules
        #[arg(short, long)]
        recursive: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Delete a branch from the active git scope
    Delete {
        /// Branch name to delete
        branch: String,
        /// Also delete from remote
        #[arg(short, long)]
        remote: bool,
        /// Force delete
        #[arg(short, long)]
        force: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Fetch updates for the active git scope
    Fetch {
        /// Fetch from all remotes
        #[arg(short, long)]
        all: bool,
        /// Apply to every repository regardless of whether remote refs differ locally
        #[arg(long)]
        force_all: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// List branches in the active git scope
    Branch {
        /// Show all branches including remotes
        #[arg(short, long)]
        all: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Initialize submodules in the active git scope
    SubmoduleInit {
        /// Recursively initialize nested submodules
        #[arg(short, long)]
        recursive: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Generate per-file diffs for the active git scope
    Diff {
        /// Base ref to diff against (commit, branch, tag). Without this, diffs unstaged changes.
        #[arg(long, conflicts_with = "since")]
        base: Option<String>,
        /// Relative time period to diff since, e.g. 2d, 4h, 30m. Uses the newest commit older than the cutoff as base.
        #[arg(long, conflicts_with = "base")]
        since: Option<String>,
        /// Output directory for diff files
        #[arg(short, long, default_value = "diffs")]
        output: String,
        /// Include staged changes (only when no base ref is given)
        #[arg(short, long)]
        staged: bool,
        /// Remove the output directory before generating new diffs
        #[arg(long)]
        clean: bool,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Stage all changes in the active git scope
    Stage {
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Merge current branch back into the default branch for the active git scope
    MergeBack {
        /// Commit message for staging uncommitted changes before merge
        #[arg(short, long, default_value = "Pre-merge commit")]
        message: String,
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
        /// Dry run mode (show what would happen without executing)
        #[arg(short = 'n', long)]
        dry_run: bool,
    },


    /// Install shell completions for this shell
    Completions {
        /// The shell to write completions for. Detected from $SHELL when absent.
        #[arg(long)]
        shell: Option<Shell>,
    },

    /// Point every manifest in the fleet at the working copies here, or take
    /// that back
    ///
    /// A manifest is rendered from a `.wstemplate`, and a dependency on a
    /// library this worktree builds is rendered as a PUBLISHED reference — a
    /// version, a tag — because that is what a manifest means to anybody
    /// outside this worktree. While that library is being changed it is the
    /// wrong reference: a fix in a library would have to be committed, tagged
    /// and published before the app consuming it could be built against it.
    ///
    /// `wsb local on` renders the whole fleet with the worktree's local
    /// variable set — named as "local" in `.wsb/stamp.json` — so every such
    /// dependency comes out as a path to the working directory.
    /// `wsb local off` takes that render back, leaving everything you changed
    /// by hand where it is.
    ///
    /// `off` is not the same as rendering without the variable: it restores
    /// what is COMMITTED, rather than producing a fresh render against
    /// published tags. That is what makes it safe to run before a commit.
    Local {
        #[command(subcommand)]
        action: LocalAction,
    },

    /// Take the local render back, commit the fleet, push, and go local again
    ///
    /// The round trip around a commit: a manifest pointing at a working
    /// directory resolves on this machine and nowhere else, so it must not be
    /// what gets committed. This leaves the tree the way it found it — local —
    /// with the commit in between carrying the published references.
    Checkpoint {
        /// Commit message
        #[arg(short, long)]
        message: String,
        /// Commit, but do not push
        #[arg(long)]
        no_push: bool,
        /// Say what each step would do and change nothing
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Update version and render templates
    Update {
        /// Skip git integration (don't auto-add files)
        #[arg(long)]
        no_git: bool,
        /// Automatically add updated files to git staging area
        #[arg(long)]
        git_add: bool,
        /// Append a suffix to the generated version, separated by a dash
        #[arg(long)]
        version_suffix: Option<String>,
        /// Tag the current commit with the generated version, suffixed by this
        ///
        /// The suffix is the version's, in the worktree's one grammar for one:
        /// `--tag rc` produces version `1.8.2-rc` and tag `v1.8.2-rc`. It is
        /// therefore the same thing `--version-suffix` sets, and giving both
        /// would leave the composed version undefined — so they conflict.
        #[arg(long, conflicts_with = "version_suffix")]
        tag: Option<String>,
        /// Suppress progress output; only print on error
        #[arg(long, short)]
        quiet: bool,
        /// Update every submodule too, deepest first, then this repository
        #[arg(long)]
        recursive: bool,
        /// Render every repository twice — once through the run's shared cache
        /// and once through a cache that has remembered nothing — and stop if
        /// the two disagree
        ///
        /// A recursive update reads the worktree once and reuses the answers
        /// across every repository in it. This proves, on THIS worktree rather
        /// than on a fixture, that reusing them writes the same bytes as not
        /// reusing them. It roughly doubles the render work and is meant to be
        /// run when something about the fleet's shape has changed, not every
        /// time.
        #[arg(long)]
        verify: bool,
        /// Take back what an update wrote, keeping everything you changed
        ///
        /// Looks at every file an update would write and, inside each of them,
        /// undoes only the lines the update itself contributed. An edit of
        /// yours beside one of its edits survives; an edit of yours ON one of
        /// its lines is kept and reported, because no answer there is
        /// certainly right.
        ///
        /// This is not `wsb discard`, which throws away a working tree. It
        /// touches only what an update produces.
        #[arg(long = "discard")]
        discard: bool,
        /// With --discard, say what would change and write none of it
        #[arg(long = "dry-run", requires = "discard")]
        dry_run: bool,
    },

    /// Local trash can using a .scrap folder for files you want to delete
    Scrap {
        /// Paths to files or directories to move to .scrap folder
        paths: Vec<std::path::PathBuf>,
        #[command(subcommand)]
        command: Option<ScrapCommands>,
    },

    /// Restore files from .scrap folder to their original locations
    Unscrap {
        /// Name of file/directory in .scrap to restore
        name: Option<String>,
        /// Force restore even if destination exists
        #[arg(short, long)]
        force: bool,
        /// Restore to a different location
        #[arg(short = 't', long)]
        to: Option<std::path::PathBuf>,
    },

    /// Process input lines, replacing repeated tokens with a substitute character
    Ldiff {
        /// Character to use for substitution (default: ░)
        #[arg(default_value = "░")]
        substitute_char: String,
    },

    /// Compact a session transcript by removing low-signal noise
    Compact {
        /// Input file path. Reads from stdin if omitted.
        input: Option<String>,

        /// Output file path. Writes to stdout if omitted.
        #[arg(short, long)]
        output: Option<String>,

        /// Apply token mode: strip stop words and low-value prose tokens
        #[arg(long)]
        token_mode: bool,
    },

    /// Show which executables are shadowed by duplicates on PATH
    AuditPath,

    /// Add a gitignore line to all .gitignore files in immediate subdirectories
    Ignore {
        /// The line to add to .gitignore files
        line: String,
    },

    /// Show the last commit hash for a file (follows renames)
    LastHash {
        /// File path to look up
        file: String,
    },

    /// Code intelligence across the worktree's repositories, from omnicode's `omni`
    Code {
        #[command(subcommand)]
        action: Option<CodeAction>,
    },


    /// Peer continuity: pairing with another machine and carrying this
    /// worktree's working tree to it (`wsb peer help`)
    #[command(disable_help_flag = true)]
    Peer {
        /// The `wsb peer` command and its arguments, read by the tool itself
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Plugins: programs this machine lets use wsb's services, the peer bridge
    /// among them (`wsb plugin help`)
    #[command(disable_help_flag = true)]
    Plugin {
        /// The `wsb plugin` command and its arguments, read by the tool itself
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// A project's worktrees, every submodule a worktree of main-worktree's
    /// repository for it (`wsb worktree help`)
    #[command(disable_help_flag = true)]
    Worktree {
        /// The `wsb worktree` command and its arguments, read by the tool itself
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Rebuild wsb and its daemon from wsb's repository and replace the
    /// installed pair, both or neither (`wsb upgrade help`)
    #[command(disable_help_flag = true)]
    Upgrade {
        /// The `wsb upgrade` arguments, read by the tool itself
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// GitHub issues, pull requests, gists and Projects boards, from the
    /// machine's mirror (`wsb github help`)
    #[command(disable_help_flag = true)]
    Github {
        /// The `wsb github` command and its arguments, read by the tool itself
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Intelligent test runner based on project type
    Test {
        /// Show what test command would be run without executing
        #[arg(long)]
        dry_run: bool,
        /// Install missing test runners if needed
        #[arg(long)]
        install: bool,
        /// Additional arguments to pass to test command
        #[arg(last = true)]
        args: Vec<String>,
    },


    /// Start the workbench: the daemon, if it is not already running.
    ///
    /// The server lives in the daemon, so this starts one and returns. The
    /// page stays up after this command exits — which is the point — and
    /// `wsb daemon stop` is what ends it.
    Serve {
        /// Port for the workbench. Unset: the first free one from 3000.
        #[arg(short, long)]
        port: Option<u16>,
        /// Address to serve on. Unset: 127.0.0.1, reachable only from this
        /// machine.
        ///
        /// `--listen 0.0.0.0` serves every interface. The workbench has NO
        /// authentication — it reads and edits the worktree, runs git on it,
        /// and writes to GitHub as this machine's login — so anyone who can
        /// reach the address can do all of that. Put it behind a tunnel or a
        /// TLS reverse proxy.
        #[arg(long)]
        listen: Option<std::net::IpAddr>,
        /// Enable debug logging
        #[arg(long)]
        debug: bool,
        /// Worktree root directory (default: discovered from current directory)
        #[arg(short, long)]
        worktree: Option<String>,
        /// Exit when this PID is no longer running (e.g. the parent UI process)
        #[arg(long)]
        parent_pid: Option<u32>,
    },

    /// The machine's daemon: what it is serving, and stopping it.
    Daemon {
        #[command(subcommand)]
        action: DaemonAction,
    },

    /// Make this repository, and every submodule under it, one wsb manages:
    /// writes the committed .wsb/repo.json each needs and installs the hook
    Init {
        /// The repository's name (defaults to the project's, in a worktree of the workshop; else the folder's)
        #[arg(long)]
        name: Option<String>,
    },

    /// Check worktree integrity: verify .wsb settings, gitmodules, local state, and super root
    Check {
        /// Skip remote URL reachability checks (useful when offline)
        #[arg(long)]
        no_network: bool,
        /// Suppress progress output; only print the final report
        #[arg(long, short)]
        quiet: bool,
    },





    /// Version management with database-driven major version and git-calculated components
    Version {
        #[command(subcommand)]
        action: VersionAction,
    },

    /// Manage .wstemplate file rendering for version-stamping project files
    Wstemplate {
        #[command(subcommand)]
        action: WstemplateAction,
    },

    /// Run a shell script once for each submodule of the current repo.
    ///
    /// The script is read from --file, piped stdin, or typed interactively
    /// (finish with Ctrl-D). Each invocation runs in the submodule's root
    /// directory with WSB_SUBMODULE_PATH, WSB_SUBMODULE_NAME, and
    /// WSB_SUPERPROJECT_ROOT set in the environment.
    /// Exits non-zero on the first submodule failure.
    Each {
        /// Path to a shell script file to run in each submodule
        #[arg(short, long)]
        file: Option<std::path::PathBuf>,
        /// Suppress progress bar; only print on error
        #[arg(long, short)]
        quiet: bool,
    },

    /// Generate catalogs of the worktree (tests, and future catalog types)
    Catalog {
        #[command(subcommand)]
        action: CatalogAction,
    },

    /// Notes: written into the .wsb/ of the worktree you are in, linked to
    /// what they are about, and read from every worktree of the workshop
    Note {
        #[command(subcommand)]
        action: NoteAction,
    },

    /// Links between any two things — boards, cards, projects, worktrees,
    /// files, machines, notes, sessions — written into the .wsb/ of the
    /// worktree you are in
    Link {
        #[command(subcommand)]
        action: LinkAction,
    },

    /// Bring this machine's checkouts and state from an older wsb's layout
    /// into this one
    Migrate,

    /// This machine: its name, as wsb, its peers and its notes know it
    Machine {
        #[command(subcommand)]
        action: MachineAction,
    },
}

/// What a note or link is about, from the command line.
#[derive(clap::Args, Debug, Default)]
struct AboutArgs {
    /// A ref: board:<owner>/<n>, card:<owner>/<n>/<item>, issue:<owner>/<repo>#<n>,
    /// repo:, project:<owner>/<repo>, worktree:, path:, machine:, note:,
    /// session:, message:, url:
    #[arg(long = "on", value_name = "REF")]
    refs: Vec<String>,
    /// A file or folder of the worktree you are in
    #[arg(long = "on-file", value_name = "PATH")]
    files: Vec<PathBuf>,
    /// The worktree you are in
    #[arg(long = "on-worktree")]
    worktree: bool,
    /// The project you are in
    #[arg(long = "on-project")]
    project: bool,
}

impl AboutArgs {
    fn targets(self) -> wsb::cli::annotations::Targets {
        wsb::cli::annotations::Targets {
            refs: self.refs,
            files: self.files,
            worktree: self.worktree,
            project: self.project,
        }
    }
}

#[derive(Subcommand, Debug)]
enum NoteAction {
    /// Write a note, linked to what it is about
    Add {
        #[arg(long)]
        title: String,
        #[arg(long, conflicts_with = "body_file")]
        body: Option<String>,
        /// Read the body from a file, or from standard input with -
        #[arg(long)]
        body_file: Option<PathBuf>,
        #[command(flatten)]
        about: AboutArgs,
    },
    /// Every note in the workshop, or those linked to a ref
    List {
        /// Only the notes linked to this ref
        #[arg(long = "on", value_name = "REF")]
        on: Option<String>,
    },
    /// One note, whole, with every version of it the worktrees hold
    Show { id: String },
    /// Rewrite a note this worktree holds
    Edit {
        id: String,
        #[arg(long)]
        title: Option<String>,
        #[arg(long, conflicts_with = "body_file")]
        body: Option<String>,
        #[arg(long)]
        body_file: Option<PathBuf>,
    },
    /// Remove a note from this worktree, with the links that name it
    Rm { id: String },
}

#[derive(Subcommand, Debug)]
enum LinkAction {
    /// Link two refs
    Add {
        from: String,
        to: String,
        /// What the link means, when it means more than "these belong together"
        #[arg(long)]
        label: Option<String>,
    },
    /// Every link in the workshop, or those with a ref at one end
    List { at: Option<String> },
    /// Remove a link from this worktree
    Rm {
        from: String,
        to: String,
        #[arg(long)]
        label: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
enum MachineAction {
    /// Show this machine's name, or give it a new one
    Name { name: Option<String> },
}


/// What can be asked of this worktree's daemon.
///
/// Deliberately small. The daemon is not a thing an operator administers — it
/// starts itself when a command needs it — so this is what is left: seeing
/// what it holds, ending it, and reading why it would not start.
#[derive(Subcommand, Debug)]
enum DaemonAction {
    /// Whether one is running, and what it is serving.
    Status,
    /// Stop it.
    Stop,
    /// Stop it and start a new one — what to run after building a new wsb.
    Restart {
        /// Port for the workbench. Unset: the first free one from 3000.
        #[arg(short, long)]
        port: Option<u16>,
    },
    /// Print where the daemon's output goes, and the tail of it.
    Log {
        /// How many lines to show
        #[arg(short = 'n', long, default_value = "40")]
        lines: usize,
    },
    /// Put the daemon on this machine as a service — systemd on Linux,
    /// launchd on macOS — so a supervisor keeps it rather than a terminal.
    ///
    /// Does not decide whether it starts at login; that is `enable`, said
    /// separately. Run it again after rebuilding wsb: the definition names
    /// the executable it was installed from.
    Install {
        /// Port for the workbench. A service names a number rather than
        /// probing at every start, so this is baked in. Unset: the first free
        /// one from 3000, taken once, now.
        #[arg(short, long)]
        port: Option<u16>,
        /// Port peers dial. Zero turns peer listening off.
        #[arg(long)]
        peer_port: Option<u16>,
    },
    /// Take the service off this machine. A running daemon keeps running.
    Uninstall,
    /// Start the daemon at login — and now.
    Enable,
    /// Stop starting the daemon at login. A running daemon keeps running.
    Disable,
}

#[derive(Subcommand, Debug)]
enum CatalogAction {
    /// Every catalogued test, with where it lives and what it asserts
    ///
    /// One record per test under `--jsonl`; one line per test otherwise.
    List {
        /// Only tests in this repository, as the catalogue names it
        /// (worktree-relative; the superproject is "").
        #[arg(long)]
        repo: Option<String>,
    },
    /// Read every test in the worktree into the catalogue table
    Scan {
        /// Suppress the per-repository report; only print on error
        #[arg(long, short)]
        quiet: bool,
    },
    /// What the catalogue says: counts, duplicates, misnumbering
    Report,
    /// The number × repository matrix for a family of mirrors
    Parity {
        /// The family to compare, as declared in .wsb/test.json
        family: String,
        /// Write the full parity report here as markdown instead of printing
        /// the gaps
        #[arg(long, short)]
        output: Option<PathBuf>,
        /// Stage the written file with git add
        #[arg(long)]
        git_add: bool,
    },
    /// The next numbers no test claims
    Free {
        /// Start looking here
        #[arg(long, default_value_t = 1)]
        from: i64,
        /// How many to offer
        #[arg(long, default_value_t = 5)]
        count: usize,
    },
    /// Write TEST_CATALOG.md from the catalogue table
    Export {
        /// Write here instead of <worktree_root>/TEST_CATALOG.md
        #[arg(short, long)]
        output: Option<std::path::PathBuf>,
        /// Only this repository, relative to the worktree root
        #[arg(long)]
        repo: Option<String>,
        /// Stage the written file with git add
        #[arg(long)]
        git_add: bool,
    },
}



/// The two states a fleet's manifests can be in, and the question of which.
#[derive(Subcommand, Debug)]
enum LocalAction {
    /// Render the fleet with the local variable set: manifests point at the
    /// working copies here
    On {
        /// Suppress progress output; only print on error
        #[arg(long, short)]
        quiet: bool,
        /// Automatically add updated files to git staging area
        #[arg(long)]
        git_add: bool,
        /// Render every repository twice, through the run's shared cache and
        /// through a cache of its own, and stop if the two disagree
        #[arg(long)]
        verify: bool,
    },
    /// Take that render back, keeping everything you changed by hand
    Off {
        /// Say what would change and write none of it
        #[arg(short = 'n', long)]
        dry_run: bool,
    },
    /// Say which state this tree is in
    Status {
        /// Name every generated file and the state it is in, not just the
        /// counts and the unsettled ones
        #[arg(long)]
        files: bool,
    },
}



#[derive(Subcommand, Debug)]
enum CodeAction {
    /// Show visual tree of current codebase structure
    Tree {
        /// Maximum depth to display (default: 3)
        #[arg(short, long, default_value = "3")]
        depth: usize,
        /// Show hidden files and directories
        #[arg(long)]
        hidden: bool,
        /// Show file sizes
        #[arg(long)]
        sizes: bool,
        /// Filter by file extensions (e.g., "rs,py,js")
        #[arg(long)]
        extensions: Option<String>,
        /// Ignore .gitignore rules (show all files, default respects .gitignore)
        #[arg(long)]
        no_ignore: bool,
    },
    /// Analyze every repository of the worktree with omnicode and publish the analyses: each
    /// repository's root, and a Cargo workspace below a root that has none as its own
    Index {
        /// One repository of the worktree instead of all of them
        #[arg(long)]
        repo: Option<PathBuf>,
    },
    /// Search source text (literally, or --regex), symbol names (--symbols) or Rust structure
    /// (--structural, rust-analyzer's SSR syntax)
    Search {
        pattern: String,
        /// The pattern is a regular expression
        #[arg(long, conflicts_with_all = ["symbols", "structural"])]
        regex: bool,
        /// Match symbol names, not source text
        #[arg(long, conflicts_with = "structural")]
        symbols: bool,
        /// Match Rust code by its structure
        #[arg(long)]
        structural: bool,
        /// Path globs to search within (repeatable)
        #[arg(long)]
        include: Vec<String>,
        /// Path globs to leave out (repeatable)
        #[arg(long)]
        exclude: Vec<String>,
        /// One repository of the worktree instead of all of them
        #[arg(long)]
        repo: Option<PathBuf>,
    },
    /// Symbols by name or glob (`*`, `?`)
    Symbols {
        pattern: String,
        /// Only symbols of this kind (`function`, `struct`, `class`, ...)
        #[arg(long)]
        kind: Option<String>,
        /// One repository of the worktree instead of all of them
        #[arg(long)]
        repo: Option<PathBuf>,
    },
    /// Every reference to a symbol, named by its path (`pkg.mod.func`, `crate::f`) or its id
    Refs {
        target: String,
        /// One repository of the worktree instead of all of them
        #[arg(long)]
        repo: Option<PathBuf>,
    },
    /// What calls a symbol, transitively to --depth
    Callers {
        target: String,
        #[arg(long, default_value_t = 1)]
        depth: u32,
        /// One repository of the worktree instead of all of them
        #[arg(long)]
        repo: Option<PathBuf>,
    },
    /// What a symbol calls, transitively to --depth
    Callees {
        target: String,
        #[arg(long, default_value_t = 1)]
        depth: u32,
        /// One repository of the worktree instead of all of them
        #[arg(long)]
        repo: Option<PathBuf>,
    },
    /// The diagnostics the analyses recorded
    Diagnostics {
        /// One file, relative to its analysis root
        #[arg(long)]
        file: Option<String>,
        /// One repository of the worktree instead of all of them
        #[arg(long)]
        repo: Option<PathBuf>,
    },
}


#[derive(Subcommand, Debug)]
enum VersionAction {
    /// Display current version with calculation breakdown
    Show {
        /// Show detailed calculation breakdown
        #[arg(long)]
        verbose: bool,
        /// Output format (human, json)
        #[arg(short, long, default_value = "human")]
        format: String,
    },
    /// Set the major version, in the repository's committed .wsb/repo.json
    Major {
        /// Major version number to set
        version: u32,
    },
    /// Create git tag with current calculated version
    Tag {
        /// Tag prefix (default: 'v')
        #[arg(long, default_value = "v")]
        prefix: String,
        /// Tag message
        #[arg(short, long)]
        message: Option<String>,
    },
    /// Show version calculation information and git compatibility
    Info {
        /// Include git history analysis
        #[arg(long)]
        include_history: bool,
    },
}

#[derive(Subcommand, Debug)]
enum WstemplateAction {
    /// Set the name other repositories' templates know this one by, in its
    /// committed .wsb/repo.json
    Alias {
        /// A template identifier: letters, digits and '_', not starting with a digit
        alias: String,
    },
    /// Set the folder this repository's templates look for the repositories
    /// they name under, in its committed .wsb/repo.json
    Root {
        /// The folder; stored relative to the repository
        path: PathBuf,
    },
    /// Show this repository's alias and templates root
    Show,
    /// List all .wstemplate files relevant to this project (no rendering)
    List,
    /// Render all .wstemplate files relevant to this project
    Render,
    /// Show every template variable, resolved against a project
    Vars {
        /// Project alias to resolve values for (defaults to this project)
        alias: Option<String>,
        /// Also resolve the fields that contact the remote
        #[arg(long)]
        remote: bool,
    },
}

#[derive(Subcommand, Debug)]
enum ScrapCommands {
    /// List contents of .scrap folder
    #[command(alias = "ls")]
    List {
        /// Sort by: name, date, size
        #[arg(short, long, default_value = "date")]
        sort: String,
    },

    /// Clean old items from .scrap folder
    Clean {
        /// Remove items older than N days
        #[arg(short, long, default_value = "30")]
        days: u64,

        /// Show what would be removed without actually removing
        #[arg(short = 'n', long)]
        dry_run: bool,
    },

    /// Remove all items from .scrap folder
    Purge {
        /// Skip confirmation prompt
        #[arg(short, long)]
        force: bool,
    },

    /// Search for files in .scrap
    Find {
        /// A regular expression, matched against each item's name and the path
        /// it was scrapped from
        pattern: String,

        /// Also match it against the contents of each item's text files
        #[arg(short, long)]
        content: bool,
    },

    /// Create archive of .scrap contents
    Archive {
        /// Output archive path
        #[arg(short, long)]
        output: Option<std::path::PathBuf>,

        /// Remove files after archiving
        #[arg(short, long)]
        remove: bool,
    },
}

/// The pre-commit hook wsb installs.
///
/// `$WSB_SELF` when there is one, and `wsb` otherwise. Those are two different
/// situations and each has one right answer, so this is not a fallback hiding
/// anything: a commit wsb is DRIVING sets the variable, and the hook must use
/// that wsb — the same build, the same database schema, the same daemon. A
/// commit a person types has no driving wsb to prefer, and PATH is the answer.
///
/// It used to name `wsb` unconditionally. A checkpoint run from a build tree
/// then failed in all thirty-seven repositories: its own hook ran the installed
/// wsb, which refused to speak to the build tree's daemon. The command doing
/// the committing could not commit.
const PRE_COMMIT_HOOK: &str = "#!/bin/sh\n\"${WSB_SELF:-wsb}\" update --quiet --git-add\n";

/// What makes a file recognisable as that hook.
///
/// One string, because three places used to say it — the installer's
/// "should I overwrite", `wsb check`'s "is this the right hook", and the
/// message telling somebody what to expect — and a change to the hook broke
/// two of them silently.
const PRE_COMMIT_MARK: &str = "update --quiet --git-add";

/// The hook's one command: the line a hook of somebody's own needs, to have
/// its commits rendered as wsb's hook would.
fn pre_commit_command() -> &'static str {
    PRE_COMMIT_HOOK
        .lines()
        .last()
        .expect("the hook has a command")
}

/// Whether a pre-commit hook is one wsb wrote, this version or an older one:
/// nothing in it but comments and one command that is wsb's update.
///
/// Anything else is somebody's own hook — a linter, a formatter, a hook that
/// calls wsb among other things — and it is theirs to change, not wsb's.
fn is_wsb_hook(content: &str) -> bool {
    let mut commands = content
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'));
    commands.next().is_some_and(is_wsb_update) && commands.next().is_none()
}

/// Whether one hook command is wsb's update as some wsb wrote it: `wsb`, a
/// path to one, or the driving wsb (`"${WSB_SELF:-wsb}"`), then `update` with
/// `--git-add`.
///
/// Every form, not only the current one: the block an earlier wsb wrote said
/// `wsb update --git-add`, without `--quiet`, and a hook in that form was
/// taken for somebody's own and never replaced.
fn is_wsb_update(command: &str) -> bool {
    let mut words = command.split_whitespace();
    let Some(program) = words.next() else {
        return false;
    };
    let program = program.trim_matches('"');
    let names_wsb = program == "${WSB_SELF:-wsb}"
        || std::path::Path::new(program).file_name().is_some_and(|name| name == "wsb");
    names_wsb && words.next() == Some("update") && words.any(|word| word == "--git-add")
}

/// What `wsb check` says about a pre-commit hook that is not right, or nothing
/// when it is.
///
/// The remedy depends on whose hook it is. `wsb init` replaces only its own,
/// so to tell somebody to run it about a hook of theirs was to send them to a
/// command that, rightly, leaves the hook alone.
fn pre_commit_hook_problem(content: &str) -> Option<String> {
    let own = is_wsb_hook(content);
    let current = content.contains(PRE_COMMIT_MARK) && content.contains(wsb::git_backend::SELF_ENV);
    if own && !current {
        Some("is an older version of wsb's own hook — run 'wsb init' to reinstall it".to_string())
    } else if !content.contains(PRE_COMMIT_MARK) {
        Some(format!(
            "does not invoke '{PRE_COMMIT_MARK}' — it is a hook of your own; add this line to \
             it: {}",
            pre_commit_command()
        ))
    } else if !content.contains(wsb::git_backend::SELF_ENV) {
        // An older hook, which names `wsb` and finds it on PATH. It works when
        // a person commits and fails when wsb drives the commit from anywhere
        // but the installed pair.
        Some(if own {
            "runs whichever wsb is on PATH rather than the one driving the commit — run \
             'wsb init' to reinstall it"
                .to_string()
        } else {
            format!(
                "runs whichever wsb is on PATH rather than the one driving the commit — change \
                 its wsb line to: {}",
                pre_commit_command()
            )
        })
    } else {
        None
    }
}

/// The stack wsb runs on, on every platform.
///
/// A debug build's `run` — one dispatch over every verb — needs more than a
/// megabyte of stack before it has done anything. The main thread gets 8 MiB
/// on macOS and Linux and 1 MiB on Windows, so the same build that worked
/// everywhere it was written overflowed on Windows at `wsb --version`, and
/// every suite that invoked it failed with `thread 'main' has overflowed its
/// stack`.
///
/// So the program does not run on whatever the platform gave its first
/// thread: it runs on a thread whose stack is wsb's own declaration, the 8 MiB
/// it has always been run with on unix.
const PROGRAM_STACK_BYTES: usize = 8 * 1024 * 1024;

fn main() {
    // Named `main`, so a panic reads exactly as it did when this was the
    // process's first thread.
    let program = std::thread::Builder::new()
        .name("main".to_string())
        .stack_size(PROGRAM_STACK_BYTES)
        .spawn(program);
    match program {
        // A panic has already been reported by the hook, on the thread that
        // panicked; the process ends the way an unwinding main ends.
        Ok(running) => {
            if running.join().is_err() {
                exit(101);
            }
        }
        Err(e) => {
            wsb::output::failed(
                &format!("could not start wsb on its own {PROGRAM_STACK_BYTES}-byte stack: {e}"),
                "startup",
            );
            exit(wsb::output::finish(1));
        }
    }
}

fn program() {
    // This process IS wsb, which nothing inside the library can know: the same
    // code is linked by test binaries, build scripts and the daemon, and the
    // variables that answer "which wsb should a child come back to" name a
    // program that will be EXECUTED. Said once, here, where it is true.
    if let Ok(own) = std::env::current_exe() {
        wsb::git_backend::announce_running_wsb(own);
    }
    // The argument vector is read here rather than by the parser, because
    // `--jsonl` has to reach commands the parser never sees: `wsb github`
    // takes its arguments verbatim, and a flag only the top-level parser knew
    // about would arrive at it as an argument it does not have. Taken out first, then everything downstream parses what is
    // left — including clap, which is handed the same shortened vector.
    let mut argv: Vec<String> = std::env::args().collect();
    let jsonl = wsb::output::take_jsonl_flag(&mut argv);
    // Taken out for the same reason and remembered the same way: `wsb github`
    // reads its own arguments, so a flag only the top-level parser knew about
    // would arrive at it as one it does not have. Remembered in the ENVIRONMENT rather than a variable, because it
    // has to reach every wsb this run starts as well as this one.
    if take_no_daemon_flag(&mut argv) {
        std::env::set_var(wsb::daemon::NO_DAEMON_ENV, "1");
    }
    // The same way and for the same reasons as `--no-daemon`: `wsb github`
    // reads its own arguments, and every wsb this one starts has to honour it.
    if take_flag(&mut argv, "--ignore-workspace-lock") {
        std::env::set_var(wsb::worktree_lock::IGNORE_ENV, "1");
    }
    if jsonl {
        wsb::output::jsonl_mode();
        // A panic writes to stderr through a hook of its own, which knows
        // nothing about the format this run promised. Replaced rather than
        // chained: the default hook's text would arrive beside the records as
        // the one thing in the run that was not one.
        std::panic::set_hook(Box::new(|info| {
            let where_at = info
                .location()
                .map(|l| format!(" at {}:{}:{}", l.file(), l.line(), l.column()))
                .unwrap_or_default();
            wsb::output::failed(&format!("panicked{where_at}: {}", panic_message(info)), "panic");
        }));
    }
    // Recording starts before the run says anything, and the file is the first
    // thing said.
    //
    // Announced rather than left to be discovered: the reason to write a log
    // is that somebody will want it later, and the moment they can be told
    // where it is, for free, is now — not after a twenty-minute build has
    // scrolled off the top of a terminal.
    if let Some(root) = wsb::logging::detect_worktree_root() {
        if let Some(path) = wsb::output::attach_transcript(&root, &argv) {
            // Through the sink, so a packaged run gets it as a record and a
            // terminal gets it as one dim line above everything else.
            wsb::output::log_file(&path.display().to_string());
        }
    }
    wsb::output::started(&argv);

    let debug_mode = argv
        .iter()
        .any(|arg| arg == "--debug" || arg == "-v" || arg == "--verbose");

    let _log_guard = match setup_logging(debug_mode) {
        Ok(guard) => guard,
        Err(e) => {
            wsb::output::failed(&format!("Failed to initialize logging: {e}"), "logging");
            exit(wsb::output::finish(1));
        }
    };

    log_version_info(env!("CARGO_PKG_VERSION"), option_env!("GIT_HASH"));

    if let Err(e) = run(&argv) {
        error!(error = %e, "Application error");
        wsb::output::failed(&format!("{}: {:#}", "Error".red(), e), "command");
        exit(wsb::output::finish(1));
    }

    info!("Worktree tool completed successfully");
    let _ = wsb::output::finish(0);
}

/// Parse the argument vector, routing clap's own output through the sink.
///
/// `Args::parse_from` prints help, version and its own refusals straight to
/// the terminal and exits. Under `--jsonl` that is the one thing
/// this format cannot survive: text arriving beside the records, from the one
/// place in the program that does not know the run was packaged.
fn parse_arguments(argv: &[String]) -> Args {
    match Args::try_parse_from(argv) {
        Ok(args) => args,
        Err(error) => {
            let text = error.render().to_string();
            // Help and version are answers, not failures: they leave on the
            // output stream with a zero status, exactly as clap would.
            if matches!(
                error.kind(),
                clap::error::ErrorKind::DisplayHelp
                    | clap::error::ErrorKind::DisplayVersion
                    | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
            ) {
                wsb::outln!("{text}");
                exit(wsb::output::finish(0));
            }
            wsb::output::failed(&text, "arguments");
            exit(wsb::output::finish(2));
        }
    }
}

/// The name of what `command` does to the worktree, when it writes into the
/// tree: renders, the local render and its taking back, checkpoints and
/// commits, template output and discarding.
fn writes_the_tree(command: &Commands) -> Option<String> {
    let named = match command {
        Commands::Local { .. } => "local",
        Commands::Checkpoint { .. } => "checkpoint",
        Commands::Update { .. } => "update",
        Commands::Commit { .. } => "commit",
        Commands::Wstemplate { .. } => "wstemplate",
        Commands::Discard { .. } => "discard",
        Commands::Scrap { .. } => "scrap",
        _ => return None,
    };
    Some(named.to_string())
}

/// Take `flag` out of the argument vector, wherever it appears; whether it did.
fn take_flag(argv: &mut Vec<String>, flag: &str) -> bool {
    let before = argv.len();
    argv.retain(|arg| arg != flag);
    before != argv.len()
}

/// Take `--no-daemon` out of the argument vector, wherever it appears.
///
/// Every occurrence, not the first: `wsb --no-daemon build --no-daemon` is one
/// operator saying it twice, and leaving the second copy for the verb to
/// choke on would be a worse answer than either.
fn take_no_daemon_flag(argv: &mut Vec<String>) -> bool {
    let before = argv.len();
    argv.retain(|arg| arg != "--no-daemon");
    before != argv.len()
}

/// What a panic was about, out of the payload it carries.
fn panic_message(info: &std::panic::PanicHookInfo<'_>) -> String {
    let payload = info.payload();
    if let Some(text) = payload.downcast_ref::<&str>() {
        return (*text).to_string();
    }
    if let Some(text) = payload.downcast_ref::<String>() {
        return text.clone();
    }
    "a panic with no message".to_string()
}

fn run(argv: &[String]) -> Result<()> {
    let start_time = Instant::now();
    let mut args = parse_arguments(argv);

    if args.jsonl {
        // Unreachable by construction: main removes the flag before parsing.
        // If it is here, the scan did not run, and every line after this would
        // be text a consumer asked not to receive.
        bail!("--jsonl reached the argument parser: the scan in main must run first");
    }
    if args.no_daemon {
        // Same construction, same reason: main removes it, and a run that got
        // here with it still attached would start a daemon the operator said
        // not to have.
        bail!("--no-daemon reached the argument parser: the scan in main must run first");
    }
    if args.ignore_worktree_lock {
        bail!("--ignore-workspace-lock reached the argument parser: the scan in main must run first");
    }
    let no_daemon = wsb::daemon::disabled();

    let command = args.command.take().unwrap_or(Commands::Serve {
        port: None,
        listen: None,
        debug: false,
        worktree: None,
        parent_pid: None,
    });

    let cwd = std::env::current_dir().context("Failed to get current directory")?;

    // A command that writes into the worktree waits while something holds
    // the worktree still ([`wsb::worktree_lock`]). Asked once, here, rather
    // than in each command: a writer that forgot to ask is the race this
    // exists to close. And it is registered as writing for as long as it
    // runs, so whatever takes the lock waits for it to finish rather than
    // reading a tree it is half-way through (`worktree_lock::begin_writing`).
    // Held to the end of this function, which is the command.
    let mut _writing = None;
    if let Some(operation) = writes_the_tree(&command) {
        if let Ok(root) = roots::require_repo_root(&cwd) {
            let root = roots::find_super_root(&root).unwrap_or(root);
            _writing = wsb::worktree_lock::begin_writing(&root, &operation).map_err(|e| anyhow::anyhow!(e))?;
        }
    }

    // Init and Check are handled before the worktree-requiring path below.
    // Init: no .wsb/repo.json exists yet, so bootstrap must not assume one.
    // Check: discovers the worktree itself and reports problems gracefully.
    if let Commands::Init { name } = command {
        setup_new_project(name, &cwd)?;
        return init_nested_repos(&cwd);
    }
    if let Commands::Check { no_network, quiet } = command {
        return run_check_command(&cwd, no_network, quiet);
    }
    if let Commands::Migrate = command {
        return run_migrate_command(&cwd);
    }
    if let Commands::Note { action } = command {
        return run_note_command(action, &cwd);
    }
    if let Commands::Link { action } = command {
        return run_link_command(action, &cwd);
    }
    if let Commands::Machine { action: MachineAction::Name { name } } = command {
        exit(wsb::output::finish(i32::from(wsb::cli::machine::name(name.as_deref()))));
    }
    // Serve: validates its own worktree so a misplaced `wsb serve` explains what
    // is missing and how to fix it, instead of the generic worktree error.
    if let Commands::Serve {
        port,
        listen,
        debug,
        worktree: serve_worktree,
        parent_pid,
    } = command
    {
        let worktree_root = validate_server_worktree(serve_worktree.map(PathBuf::from))?;
        return run_serve_command(&worktree_root, port, listen, debug, parent_pid, no_daemon);
    }

    // The daemon's own commands never start one. `wsb daemon stop` that
    // launched a daemon in order to stop it would be a command that cannot
    // report "there is none".
    if let Commands::Daemon { action } = command {
        return run_daemon_command(action);
    }

    // Completions are about this machine's shell, not about a worktree.
    if let Commands::Completions { shell } = command {
        return install_shell_completions(shell);
    }

    // GitHub belongs to the machine and to `$PRJ`, not to the worktree this
    // command stands in, so it needs no `.wsb/repo.json` here.
    if let Commands::Github { args } = command {
        // Through wsb's own stream: under its `--jsonl` every line of the run
        // is a record, and the verb's prose arrives as stdout and stderr ones.
        let code = wsb_github::cli::run_through(args, |stream, line| match stream {
            wsb_github::output::Stream::Out => wsb::outln!("{line}"),
            wsb_github::output::Stream::Err => wsb::errln!("{line}"),
        });
        exit(wsb::output::finish(i32::from(code)));
    }

    // A project's worktrees are `$PRJ`'s, made from wherever `prj` runs: no
    // worktree to stand in, and no daemon to attach to.
    if let Commands::Worktree { args } = command {
        let argv: Vec<String> = ["wsb".to_string(), "worktree".to_string()].into_iter().chain(args).collect();
        exit(wsb::output::finish(i32::from(wsb::cli::worktree::dispatch(&argv))));
    }

    // The command that replaces the pair needs neither a worktree nor a
    // daemon: it is what is run when the daemon is down, or is another build
    // than this wsb and is refused for it.
    if let Commands::Upgrade { args } = command {
        exit(wsb::output::finish(i32::from(wsb::cli::upgrade::dispatch(&args))));
    }

    // Every other command runs with its daemon decided here, once: beside the
    // machine's daemon, which shows it in the workbench while it happens, or in
    // this process alone. A command that decided at its own call site is how a
    // run comes to be shown in one place and missing from another.
    attach_to_the_daemon(&cwd, no_daemon)?;

    // Continuity is the machine's daemon's, and acts on the worktree the
    // command stands in when it stands in one; it needs no project here.
    if let Commands::Peer { args } = command {
        let argv: Vec<String> = ["wsb".to_string(), "peer".to_string()].into_iter().chain(args).collect();
        exit(wsb::output::finish(i32::from(wsb::cli::peer::dispatch(&argv))));
    }
    // Plugins are the machine's, like its peers.
    if let Commands::Plugin { args } = command {
        let argv: Vec<String> = ["wsb".to_string(), "plugin".to_string()].into_iter().chain(args).collect();
        exit(wsb::output::finish(i32::from(wsb::cli::plugin::dispatch(&argv))));
    }

    let project_root = roots::require_repo_root(&cwd)?;
    let ctx = AppContext::bootstrap(&project_root)?;

    match command {
        Commands::Refactor { args } => {
            log_operation_start("refactor", &format!("root: {:?}", args.root_dir));
            match wsb::run_refactor(args) {
                Ok(()) => log_operation_complete("refactor", start_time.elapsed()),
                Err(error) => {
                    log_operation_error("refactor", &error);
                    wsb::output::failed(&format!("{}: {:#}", "Error".red(), error), "refactor");
                    exit(wsb::output::finish(1));
                }
            }
        }

        Commands::Discard {
            untracked,
            yes,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Discard { untracked, yes },
                false,
                dry_run,
            )?;
        }
        Commands::Status { verbose } => {
            run_fleet_or_repo_command(wsb::fleet::cli::Commands::Status, verbose, false)?;
        }

        Commands::Checkout {
            branch,
            create,
            ignore_missing,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Checkout {
                    branch,
                    create,
                    ignore_missing,
                },
                verbose,
                dry_run,
            )?;
        }

        Commands::Pull {
            rebase,
            autostash,
            overwrite_local,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Pull {
                    rebase,
                    autostash,
                    overwrite_local,
                },
                verbose,
                dry_run,
            )?;
        }

        Commands::Push {
            force_with_lease,
            force_all,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Push {
                    force_with_lease,
                    force_all,
                },
                verbose,
                dry_run,
            )?;
        }

        Commands::Create {
            branch,
            from,
            push,
            force_all,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Create {
                    branch,
                    from,
                    push,
                    force_all,
                },
                verbose,
                dry_run,
            )?;
        }

        Commands::Commit {
            message,
            push,
            stage_all,
            exclude,
            include,
            force_all,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Commit {
                    message,
                    push,
                    stage_all,
                    exclude,
                    include,
                    force_all,
                },
                verbose,
                dry_run,
            )?;
        }

        Commands::Sync {
            init,
            recursive,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Sync { init, recursive },
                verbose,
                dry_run,
            )?;
        }

        Commands::Delete {
            branch,
            remote,
            force,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Delete {
                    branch,
                    remote,
                    force,
                },
                verbose,
                dry_run,
            )?;
        }

        Commands::Fetch {
            all,
            force_all,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Fetch { all, force_all },
                verbose,
                dry_run,
            )?;
        }

        Commands::Branch { all, verbose } => {
            run_fleet_or_repo_command(wsb::fleet::cli::Commands::Branch { all }, verbose, false)?;
        }

        Commands::SubmoduleInit {
            recursive,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Init { recursive },
                verbose,
                dry_run,
            )?;
        }

        Commands::Diff {
            base,
            since,
            output,
            staged,
            clean,
            verbose,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::Diff {
                    base,
                    since,
                    output,
                    staged,
                    clean,
                },
                verbose,
                false,
            )?;
        }

        Commands::Stage { verbose, dry_run } => {
            run_fleet_or_repo_command(wsb::fleet::cli::Commands::Stage, verbose, dry_run)?;
        }

        Commands::MergeBack {
            message,
            verbose,
            dry_run,
        } => {
            run_fleet_or_repo_command(
                wsb::fleet::cli::Commands::MergeBack { message },
                verbose,
                dry_run,
            )?;
        }

        Commands::Completions { .. } => {
            unreachable!("Completions is handled before the worktree guard")
        }


        Commands::Local { action } => {
            run_local_command(action, &ctx.repo_root, start_time)?;
        }

        Commands::Checkpoint {
            message,
            no_push,
            dry_run,
        } => {
            log_operation_start(
                "checkpoint",
                &format!("no_push: {no_push}, dry_run: {dry_run}"),
            );
            run_checkpoint_command(&message, no_push, dry_run, &ctx.repo_root)?;
            log_operation_complete("checkpoint", start_time.elapsed());
        }

        Commands::Update {
            no_git,
            git_add,
            version_suffix,
            tag,
            quiet,
            recursive,
            verify,
            discard,
            dry_run: discard_dry_run,
        } => {
            if discard {
                log_operation_start(
                    "update discard",
                    &format!("dry_run: {discard_dry_run}, recursive: {recursive}"),
                );
                if recursive {
                    discard_recursive(&ctx.repo_root, discard_dry_run)?;
                } else {
                    run_update_discard(&ctx.repo_root, discard_dry_run, &RunCache::new())?;
                }
                log_operation_complete("update discard", start_time.elapsed());
                return Ok(());
            }
            refuse_update_in_local_mode(&ctx.repo_root)?;
            log_operation_start(
                "update",
                &format!(
                    "no_git: {}, git_add: {}, version_suffix: {:?}, tag: {:?}, recursive: {}",
                    no_git, git_add, version_suffix, tag, recursive
                ),
            );
            if recursive {
                update_recursive(
                    no_git,
                    git_add,
                    version_suffix.as_deref(),
                    tag.as_deref(),
                    &ctx.repo_root,
                    quiet,
                    verify,
                )?;
            } else {
                update_state(
                    no_git,
                    git_add,
                    version_suffix.as_deref(),
                    tag.as_deref(),
                    &ctx.repo_root,
                    quiet,
                    &RunCache::new(),
                    verify,
                )?;
            }
            log_operation_complete("update", start_time.elapsed());
        }

        Commands::Scrap { paths, command } => {
            run_scrap_command(paths, command)?;
        }

        Commands::Unscrap { name, force, to } => {
            run_unscrap_command(name, force, to)?;
        }

        Commands::Ldiff { substitute_char } => {
            run_ldiff_command(substitute_char)?;
        }

        Commands::Compact {
            input,
            output,
            token_mode,
        } => {
            run_compact_command(input, output, token_mode)?;
        }

        Commands::AuditPath => {
            run_audit_path_command()?;
        }

        Commands::Ignore { line } => {
            run_ignore_command(&line)?;
        }

        Commands::LastHash { file } => {
            run_last_hash_command(&file)?;
        }

        Commands::Code { action } => {
            let action = action.unwrap_or(CodeAction::Tree {
                depth: 3,
                hidden: false,
                sizes: false,
                extensions: None,
                no_ignore: false,
            });
            handle_code_command(action, &ctx.repo_root)?;
        }

        Commands::Test {
            dry_run,
            install,
            args,
        } => {
            handle_test_command(dry_run, install, args, &ctx.repo_root)?;
        }

        Commands::Github { .. } => unreachable!("Github is handled before this match"),
        Commands::Note { .. } => unreachable!("Note is handled before this match"),
        Commands::Link { .. } => unreachable!("Link is handled before this match"),
        Commands::Migrate => unreachable!("Migrate is handled before this match"),
        Commands::Machine { .. } => unreachable!("Machine is handled before this match"),
        Commands::Peer { .. } => unreachable!("Peer is handled before this match"),
        Commands::Plugin { .. } => unreachable!("Plugin is handled before this match"),
        Commands::Worktree { .. } => unreachable!("Worktree is handled before this match"),
        Commands::Upgrade { .. } => unreachable!("Upgrade is handled before this match"),
        // Serve is dispatched before the worktree guard above.
        Commands::Serve { .. } => unreachable!("Serve is handled before this match"),
        Commands::Daemon { .. } => {
            unreachable!("Daemon is handled before this match, so it never starts one")
        }

        Commands::Version { action } => {
            run_version_command(action, &ctx)?;
        }

        Commands::Wstemplate { action } => {
            handle_wstemplate_command(action, &ctx.repo_root)?;
        }

        Commands::Each { file, quiet } => {
            run_each_command(&ctx.repo_root, file, quiet)?;
        }

        Commands::Catalog { action } => run_catalog_command(action, &ctx)?,

        // Handled via early return before the worktree requirement check above.
        Commands::Init { .. } | Commands::Check { .. } => unreachable!(),
    }

    Ok(())
}

fn run_fleet_or_repo_command(
    command: wsb::fleet::cli::Commands,
    verbose: bool,
    dry_run: bool,
) -> Result<()> {
    use wsb::fleet::output::Formatter;

    let cwd = std::env::current_dir().context("Failed to get current directory")?;

    // A fleet is defined by having submodules to act on, not merely by the
    // presence of a .gitmodules file. When every submodule is ignored the
    // effective fleet is empty, and the command must still run against this
    // repository rather than refusing to do anything.
    let tree = wsb::fleet::git::SubmoduleTree::discover_allow_empty(&cwd)
        .map_err(|error| anyhow::anyhow!("{}", error))?;

    // A pattern that matches nothing is almost always a typo, and an ignore list
    // that silently does nothing is exactly what a user would not notice.
    for pattern in tree.unmatched_ignore_patterns() {
        Formatter::print_warning(&format!(
            "ignored_submodules pattern '{}' matched no submodule",
            pattern
        ));
    }

    if tree.is_empty() {
        if !tree.ignored().is_empty() {
            Formatter::print_info(&format!(
                "All {} submodule(s) are ignored; operating on this repository only",
                tree.ignored().len()
            ));
        }
        execute_repo_git_command(command, verbose, dry_run)?;
    } else {
        wsb::fleet::execute(command, verbose, dry_run)?;
    }
    Ok(())
}

fn execute_repo_git_command(
    command: wsb::fleet::cli::Commands,
    _verbose: bool,
    dry_run: bool,
) -> Result<()> {
    use wsb::fleet::cli::Commands;
    use wsb::fleet::git::{GitOps, SubmoduleStatus};
    use wsb::fleet::output::Formatter;

    let cwd = std::env::current_dir().context("Failed to get current directory")?;
    let repo_root = wsb::git_backend::repo_root(&cwd)?;
    let repo = wsb::git_backend::open_repo(&repo_root)?;

    match command {
        Commands::Status => {
            let is_detached =
                GitOps::is_detached_head(&repo).map_err(|e| anyhow::anyhow!("{}", e))?;
            let current_branch = if is_detached {
                None
            } else {
                Some(GitOps::current_branch(&repo).map_err(|e| anyhow::anyhow!("{}", e))?)
            };
            // The same separation the fleet walk makes, for the same reason: a
            // generated file standing exactly as a render would write it is the
            // renderer's doing, not somebody's work, and reporting the two
            // together is what buries the second. Asked of the WORKTREE, so a
            // repository inside one is measured against the render that
            // actually wrote its manifests.
            let rendered = wsb::state::discard::rendered_as_written(
                &wsb::roots::find_super_root(&repo_root).unwrap_or_else(|| repo_root.clone()),
                &wsb::state::RunCache::new(),
            )?;
            let (changed, moved_pointers) = GitOps::uncommitted_files_and_pointers(&repo)
                .map_err(|e| anyhow::anyhow!("{}", e))?;
            let (uncommitted_files, rendered_files) =
                wsb::fleet::git::split_rendered(&repo_root, changed, &rendered);
            let is_clean = uncommitted_files.is_empty();
            let (ahead, behind) = if is_detached {
                (0, 0)
            } else {
                GitOps::get_ahead_behind(&repo).unwrap_or((0, 0))
            };
            let repo_name = repo_root
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("[REPOSITORY]")
                .to_string();
            Formatter::print_status(&[SubmoduleStatus {
                name: repo_name,
                path: ".".to_string(),
                current_branch,
                is_clean,
                is_detached,
                ahead,
                behind,
                uncommitted_files,
                rendered_files,
                moved_pointers,
                exists: true,
                depth: 0,
            }]);
        }
        // The fleet walk already starts at this repository and includes it, so
        // there is nothing repo-only to do differently — a tree with no
        // submodules is a fleet of one.
        Commands::Discard { untracked, yes } => {
            wsb::fleet::commands::discard::execute(
                &repo_root,
                wsb::fleet::commands::discard::Options {
                    untracked,
                    assume_yes: yes,
                    dry_run,
                },
            )
            .map_err(|e| anyhow::anyhow!("{}", e))?;
        }
        Commands::Checkout {
            branch,
            create,
            ignore_missing,
        } => {
            let local_branch_exists = wsb::git_backend::branch_exists(
                &repo,
                &branch,
                wsb::git_backend::BranchKind::Local,
            )?;
            let remote_branch_exists = if !local_branch_exists && !create {
                wsb::git_backend::branch_exists(
                    &repo,
                    &format!("origin/{branch}"),
                    wsb::git_backend::BranchKind::Remote,
                )?
            } else {
                false
            };
            let remote_branch_advertised =
                if !local_branch_exists && !remote_branch_exists && !create {
                    wsb::git_backend::remote_branch_head(&repo, "origin", &branch)?.is_some()
                } else {
                    false
                };
            let branch_available =
                local_branch_exists || remote_branch_exists || remote_branch_advertised;

            if !branch_available && !create && ignore_missing {
                Formatter::print_info(&format!(
                    "Branch '{}' does not exist; skipping checkout",
                    branch
                ));
                return Ok(());
            }
            if !branch_available && !create {
                anyhow::bail!(
                    "Branch '{}' does not exist. Use --create to create it.",
                    branch
                );
            }
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                if local_branch_exists {
                    Formatter::print_info(&format!("Would checkout '{}'", branch));
                } else if remote_branch_exists {
                    Formatter::print_info(&format!("Would checkout '{}' from remote", branch));
                } else if remote_branch_advertised {
                    Formatter::print_info(&format!(
                        "Would fetch and checkout '{}' from remote",
                        branch
                    ));
                } else if create {
                    Formatter::print_info(&format!("Would create and checkout '{}'", branch));
                } else {
                    Formatter::print_info(&format!("Would checkout '{}'", branch));
                }
                return Ok(());
            }
            if create && !local_branch_exists {
                wsb::git_backend::create_branch(&repo, &branch, None)?;
            } else {
                if remote_branch_advertised {
                    wsb::git_backend::fetch_remote_branch(&repo, "origin", &branch)?;
                }
                wsb::git_backend::checkout_branch(&repo, &branch)?;
            }
            Formatter::print_success(&format!("Checked out '{}'", branch));
        }
        Commands::Pull {
            rebase,
            autostash,
            overwrite_local,
        } => {
            let options = wsb::git_backend::PullOptions {
                rebase,
                autostash,
                overwrite_local,
            };
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                // The state is fetched, not remembered: what a pull would do
                // is a question about the remote as it is now.
                let state = wsb::git_backend::remote_state(&repo, Some("origin"))?;
                Formatter::print_info(&format!("Branch is {}", state.describe()));
                return Ok(());
            }
            // The same words as the fleet run, from the same place: one
            // repository and forty must not describe the same state
            // differently.
            let label = wsb::git_backend::current_branch(&repo)?;
            match wsb::fleet::commands::pull::pull_one(&repo, &label, options) {
                Ok(wsb::fleet::commands::pull::Verdict::Changed(message)) => {
                    Formatter::print_success(&message);
                }
                Ok(wsb::fleet::commands::pull::Verdict::Unchanged(message)) => {
                    Formatter::print_info(&message);
                }
                Ok(wsb::fleet::commands::pull::Verdict::Blocked(message))
                | Err(message) => return Err(anyhow::anyhow!(message)),
            }
        }
        Commands::Push {
            force_with_lease,
            force_all,
        } => {
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                let state = wsb::git_backend::remote_state(&repo, Some("origin"))?;
                if force_all || state.has_outgoing() {
                    Formatter::print_info("Would push current branch");
                } else {
                    Formatter::print_info(&format!("Branch is {}; would skip push", state.describe()));
                }
                return Ok(());
            }
            let state = wsb::git_backend::remote_state(&repo, Some("origin"))?;
            if let wsb::git_backend::RemoteState::Diverged { incoming, outgoing } = state {
                return Err(anyhow::anyhow!(
                    "the branch has diverged: {outgoing} local commit(s) and {incoming} \
                     incoming — pull (or `wsb pull --rebase`) before pushing"
                ));
            }
            if !force_all && !state.has_outgoing() {
                Formatter::print_info(&format!("Branch is {}; skipping push", state.describe()));
                return Ok(());
            }
            match wsb::git_backend::push_current_branch(
                &repo,
                Some("origin"),
                true,
                force_with_lease,
            )? {
                wsb::git_backend::PushOutcome::Updated => {
                    Formatter::print_success("Pushed current branch");
                }
                wsb::git_backend::PushOutcome::UpToDate => {
                    Formatter::print_info("Current branch is already up to date");
                }
            }
        }
        Commands::Create {
            branch,
            from,
            push,
            force_all,
        } => {
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                if force_all || !wsb::git_backend::is_clean(&repo)? {
                    Formatter::print_info(&format!(
                        "Would create branch '{}'{}",
                        branch,
                        from.as_deref()
                            .map(|base| format!(" from '{}'", base))
                            .unwrap_or_default()
                    ));
                } else {
                    Formatter::print_info("No worktree changes; would skip branch creation");
                }
                return Ok(());
            }
            if !force_all && wsb::git_backend::is_clean(&repo)? {
                Formatter::print_info("No worktree changes; skipping branch creation");
                return Ok(());
            }
            wsb::git_backend::create_branch(&repo, &branch, from.as_deref())?;
            Formatter::print_success(&format!("Created branch '{}'", branch));
            if push {
                match wsb::git_backend::push_current_branch(&repo, Some("origin"), true, false)? {
                    wsb::git_backend::PushOutcome::Updated => {
                        Formatter::print_success("Pushed new branch");
                    }
                    wsb::git_backend::PushOutcome::UpToDate => {
                        Formatter::print_info("New branch is already up to date");
                    }
                }
            }
        }
        Commands::Commit {
            message,
            push,
            stage_all,
            force_all,
            ..
        } => {
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                if force_all || !wsb::git_backend::is_clean(&repo)? {
                    if stage_all {
                        Formatter::print_info("Would stage all changes (git add -A)");
                    }
                    Formatter::print_info(&format!(
                        "Would commit changes with message '{}'",
                        message
                    ));
                } else {
                    Formatter::print_info("No worktree changes; would skip commit");
                }
                return Ok(());
            }
            if !force_all && wsb::git_backend::is_clean(&repo)? {
                Formatter::print_info("No worktree changes; skipping commit");
                return Ok(());
            }
            if stage_all {
                wsb::git_backend::stage_all(&repo)?;
            }
            match wsb::git_backend::commit_all(&repo, &message)? {
                Some(sha) => Formatter::print_success(&format!("Committed changes: {}", sha)),
                None => Formatter::print_info("Nothing to commit"),
            }
            if push {
                match wsb::git_backend::push_current_branch(&repo, Some("origin"), true, false)? {
                    wsb::git_backend::PushOutcome::Updated => {
                        Formatter::print_success("Pushed commit")
                    }
                    wsb::git_backend::PushOutcome::UpToDate => {
                        Formatter::print_info("Current branch is already up to date")
                    }
                }
            }
        }
        Commands::Sync { init, recursive } => {
            if init || recursive {
                anyhow::bail!(
                    "'wsb sync --init/--recursive' requires a fleet root with a .gitmodules file"
                );
            }
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                Formatter::print_info("Would fetch and pull current branch");
                return Ok(());
            }
            // `pull` fetches; a fetch before it was a second round trip that
            // could only tell the same story.
            let label = wsb::git_backend::current_branch(&repo)?;
            match wsb::fleet::commands::pull::pull_one(
                &repo,
                &label,
                wsb::git_backend::PullOptions::default(),
            ) {
                Ok(wsb::fleet::commands::pull::Verdict::Changed(message)) => {
                    Formatter::print_success(&message);
                }
                Ok(wsb::fleet::commands::pull::Verdict::Unchanged(message)) => {
                    Formatter::print_info(&message);
                }
                Ok(wsb::fleet::commands::pull::Verdict::Blocked(message))
                | Err(message) => return Err(anyhow::anyhow!(message)),
            }
        }
        Commands::Delete {
            branch,
            remote,
            force,
        } => {
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                Formatter::print_info(&format!("Would delete branch '{}'", branch));
                if remote {
                    Formatter::print_info(&format!("Would delete remote branch '{}'", branch));
                }
                return Ok(());
            }
            wsb::git_backend::delete_local_branch(&repo, &branch, force)?;
            Formatter::print_success(&format!("Deleted branch '{}'", branch));
            if remote {
                wsb::git_backend::delete_remote_branch(&repo, Some("origin"), &branch)?;
                Formatter::print_success(&format!("Deleted remote branch '{}'", branch));
            }
        }
        Commands::Fetch { all, force_all } => {
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                if force_all || wsb::git_backend::has_fetchable_updates(&repo, all)? {
                    Formatter::print_info("Would fetch remote updates");
                } else {
                    Formatter::print_info("No fetchable remote updates; would skip fetch");
                }
                return Ok(());
            }
            if !force_all && !wsb::git_backend::has_fetchable_updates(&repo, all)? {
                Formatter::print_info("No fetchable remote updates; skipping fetch");
                return Ok(());
            }
            if all {
                wsb::git_backend::fetch_all(&repo)?;
            } else {
                wsb::git_backend::fetch(&repo, Some("origin"))?;
            }
            Formatter::print_success("Fetched remote updates");
        }
        Commands::Branch { all } => {
            let current = wsb::git_backend::current_branch(&repo).ok();
            let branches = if all {
                let mut local = wsb::git_backend::local_branches(&repo)?;
                local.extend(wsb::git_backend::remote_branches(&repo)?);
                local
            } else {
                wsb::git_backend::local_branches(&repo)?
            };
            Formatter::print_branches("[REPOSITORY]", &branches, current.as_deref());
        }
        Commands::Init { recursive: _ } => {
            anyhow::bail!("'wsb submodule-init' requires a fleet root with a .gitmodules file");
        }
        Commands::Diff {
            base,
            since,
            output,
            staged,
            clean,
        } => {
            let outdir = std::path::Path::new(&output);
            if clean && outdir.exists() {
                std::fs::remove_dir_all(outdir).map_err(|e| {
                    anyhow::anyhow!("Failed to remove '{}': {}", outdir.display(), e)
                })?;
            }
            let files = wsb::fleet::commands::diff::generate_per_file_diffs(
                &repo_root,
                base.as_deref(),
                since.as_deref(),
                outdir,
                staged,
            )
            .map_err(|e| anyhow::anyhow!("{}", e))?;
            if files.is_empty() {
                Formatter::print_info("No changes to diff");
            } else {
                Formatter::print_success(&format!(
                    "{} diff file(s) written to '{}'",
                    files.len(),
                    output
                ));
                for file in &files {
                    wsb::outln!("  {}.diff", file);
                }
            }
        }
        Commands::Stage => {
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                Formatter::print_info("Would stage all changes");
                return Ok(());
            }
            wsb::git_backend::stage_all(&repo)?;
            Formatter::print_success("Staged all changes");
        }
        Commands::MergeBack { message } => {
            if dry_run {
                Formatter::print_warning("DRY RUN: No changes will be made");
                Formatter::print_info("Would merge current branch back into the default branch");
                return Ok(());
            }
            let current_branch = wsb::git_backend::current_branch(&repo)?;
            let default_branch = wsb::git_backend::get_default_branch(&repo)?;
            if current_branch == default_branch {
                anyhow::bail!("already on '{}'", default_branch);
            }
            if !wsb::git_backend::is_clean(&repo)? {
                wsb::git_backend::stage_all(&repo)?;
            }
            let _ = wsb::git_backend::commit_all(&repo, &message)?;
            let _ = wsb::git_backend::push_current_branch(&repo, Some("origin"), true, false)?;
            wsb::git_backend::checkout_branch(&repo, &default_branch)?;
            wsb::git_backend::merge_ff(&repo, &current_branch)?;
            let _ = wsb::git_backend::push_current_branch(&repo, Some("origin"), false, false)?;
            Formatter::print_success("Merge-back complete");
        }
        Commands::TestCatalog {
            output,
            git_add,
            quiet,
        } => {
            wsb::fleet::commands::catalogue::execute(
                &repo_root,
                output.as_deref(),
                git_add,
                quiet,
            )
            .map_err(|e| anyhow::anyhow!("{}", e))?;
        }
    }

    Ok(())
}

fn make_spinner(quiet: bool, msg: &'static str) -> indicatif::ProgressBar {
    // A spinner is cursor movement and escape codes. A packaged run has no
    // terminal to move a cursor on, and the same facts leave as records.
    if quiet || wsb::output::is_jsonl() {
        indicatif::ProgressBar::hidden()
    } else {
        let pb = indicatif::ProgressBar::new_spinner();
        pb.set_style(
            indicatif::ProgressStyle::with_template("{spinner:.cyan} {msg}")
                .unwrap()
                .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
        );
        pb.set_message(msg);
        pb.enable_steady_tick(std::time::Duration::from_millis(80));
        pb
    }
}

fn make_progress_bar(quiet: bool, total: u64) -> indicatif::ProgressBar {
    if quiet || wsb::output::is_jsonl() {
        indicatif::ProgressBar::hidden()
    } else {
        let pb = indicatif::ProgressBar::new(total);
        pb.set_style(
            indicatif::ProgressStyle::with_template("{spinner:.cyan} [{pos}/{len}] {wide_msg}")
                .unwrap()
                .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
        );
        pb.enable_steady_tick(std::time::Duration::from_millis(80));
        pb
    }
}


/// How this worktree renders against its working copies, as `.wsb/stamp.json`
/// at the worktree root declares it — or why it declares nothing.
///
/// Read from the worktree root, not the directory the command was typed in:
/// "is this fleet local" is a question about the whole nesting tree.
fn local_rendering(project_root: &Path) -> Result<wsb::state::stamp_config::LocalRendering> {
    wsb::state::stamp_config::StampConfig::local(&worktree_root_of(project_root))
}

/// The same, for a command that works whether or not the worktree has a
/// local render: `None` when it declares none.
fn declared_local_rendering(
    project_root: &Path,
) -> Result<Option<wsb::state::stamp_config::LocalRendering>> {
    Ok(wsb::state::stamp_config::StampConfig::load(&worktree_root_of(project_root))?
        .and_then(|config| config.local))
}

fn worktree_root_of(project_root: &Path) -> PathBuf {
    wsb::roots::find_super_root(project_root).unwrap_or_else(|| project_root.to_path_buf())
}

/// Run one of the declared local-render commands in the worktree root.
fn run_declared(argv: &[String], root: &Path, what: &str) -> Result<()> {
    let (program, arguments) = argv
        .split_first()
        .ok_or_else(|| anyhow::anyhow!("the declared {what} command is empty"))?;
    let status = wsb::git_backend::program_without_repo_scope(program)
        .args(arguments)
        .current_dir(root)
        .status()
        .with_context(|| format!("cannot run the declared {what} command `{}`", argv.join(" ")))?;
    if !status.success() {
        bail!("the declared {what} command `{}` failed ({status})", argv.join(" "));
    }
    Ok(())
}

/// `wsb local on|off|status`.
///
/// `on` and `off` are the same render, run for its two opposite reasons, and
/// BOTH need the variable set. That is not obvious for `off`: taking a render
/// back means knowing exactly what it contributed, which means producing it
/// again — and a render produced without the variable is a different render, so
/// it would fail to recognise the one on disk. Doing it here rather than
/// leaving it to a shell alias is most of why this is a command.
fn run_local_command(action: LocalAction, project_root: &Path, start_time: Instant) -> Result<()> {
    let local = local_rendering(project_root)?;
    // Set for this process and everything it starts. Templates read the
    // environment the render ran in; there is no toggle and no allowlist,
    // which is exactly why the command has to be the thing that sets it.
    std::env::set_var(&local.variable, "1");

    match action {
        LocalAction::On {
            quiet,
            git_add,
            verify,
        } => {
            log_operation_start("local on", &format!("git_add: {git_add}, verify: {verify}"));
            render_local(project_root, &local, git_add, quiet, verify)?;
            if !quiet {
                wsb::outln!(
                    "Manifests point at the working copies here. \
                     Run 'wsb local off' before committing."
                );
            }
            log_operation_complete("local on", start_time.elapsed());
        }
        LocalAction::Off { dry_run } => {
            log_operation_start("local off", &format!("dry_run: {dry_run}"));
            discard_recursive(project_root, dry_run)?;
            ensure_not_local(project_root, &local.variable, dry_run)?;
            if !dry_run {
                release_what_the_local_render_named(project_root, &local)?;
            }
            log_operation_complete("local off", start_time.elapsed());
        }
        LocalAction::Status { files } => {
            log_operation_start("local status", &format!("files: {files}"));
            report_local_status(project_root, &local.variable, files)?;
            log_operation_complete("local status", start_time.elapsed());
        }
    }
    Ok(())
}

/// Render the fleet against the working copies, then build what that render
/// names outside them.
///
/// The render first: it writes the libraries' own versions, and what is built
/// for the render is built from them as rendered — built before it, the
/// artifact would carry the committed version while every manifest the render
/// then wrote pinned the working copy's. A tree whose dependencies cannot be
/// built is still not left local: the render is taken back, because its
/// manifests would link to something that is not there.
fn render_local(
    project_root: &Path,
    local: &wsb::state::stamp_config::LocalRendering,
    git_add: bool,
    quiet: bool,
    verify: bool,
) -> Result<()> {
    update_recursive(false, git_add, None, None, project_root, quiet, verify)?;
    if let Err(built) = build_what_the_local_render_names(project_root, local) {
        return match discard_recursive(project_root, false) {
            Ok(()) => Err(anyhow::anyhow!("{built:#}\n  The render was taken back: the tree is not local.")),
            Err(discard) => Err(anyhow::anyhow!(
                "{built:#}\n  and taking the render back failed: {discard:#}\n  Finish it with: wsb local off"
            )),
        };
    }
    Ok(())
}

/// Build what a local render names outside the working copies, and hold it
/// for as long as the tree is local: the worktree's declared `prepare`, run
/// only when some template's local branch names the build root.
fn build_what_the_local_render_names(
    project_root: &Path,
    local: &wsb::state::stamp_config::LocalRendering,
) -> Result<()> {
    let root = worktree_root_of(project_root);
    if !wsb::state::local_render::local_render_reads_build_root(&root, &local.variable)
        .map_err(|e| anyhow::anyhow!("{e}"))?
    {
        return Ok(());
    }
    match &local.prepare {
        Some(argv) => run_declared(argv, &root, "local prepare"),
        None => Ok(()),
    }
}

/// The tree is no longer local: what its render named may be swept again —
/// the worktree's declared `release`.
fn release_what_the_local_render_named(
    project_root: &Path,
    local: &wsb::state::stamp_config::LocalRendering,
) -> Result<()> {
    let root = worktree_root_of(project_root);
    if !wsb::state::local_render::local_render_reads_build_root(&root, &local.variable)
        .map_err(|e| anyhow::anyhow!("{e}"))?
    {
        return Ok(());
    }
    match &local.release {
        Some(argv) => run_declared(argv, &root, "local release"),
        None => Ok(()),
    }
}

/// Which of the two states one generated file is in.
///
/// Four answers rather than two. A file can be in neither state — an update
/// writes into a working tree that a person also edits — and saying "local" or
/// "committed" about a file that is neither would be the more useful-sounding
/// of two wrong answers. And a file can be in BOTH, because most generated
/// files carry no dependency that the environment switches: they render the
/// same bytes either way, so they cannot answer the question and are counted
/// apart from the ones that can.
enum LocalState {
    /// The file is exactly the local render, and the local render is not what
    /// is committed.
    Local,
    /// The file is exactly what is committed, and that is not the local render.
    Committed,
    /// The local render and the committed file are the same bytes. Nothing
    /// here distinguishes the two states.
    Indifferent,
    /// Neither. Something changed it by hand, or an earlier render is stuck
    /// half-way.
    Edited,
    /// The render would create it and it is not there yet.
    Absent,
}

/// `wsb local status` — the state of every file the local render writes.
///
/// Read-only. It produces the render in memory, exactly as `on` would, and
/// compares it against the working tree and against the last commit; nothing
/// is written, including by the version calculation.
///
/// A file is rendered by more than one repository — its owner, and every
/// project a template in it names — so the render that ANSWERS for it is the
/// last one in the walk, which is the one `wsb local on` leaves on disk. The
/// first version of this compared every pass's render separately and reported
/// one file several times, mostly as "neither".
fn report_local_status(project_root: &Path, variable: &str, list_files: bool) -> Result<()> {
    use wsb::fleet::git::tree::SubmoduleTree;

    let cache = RunCache::new();
    let tree = SubmoduleTree::discover_allow_empty(project_root)
        .with_context(|| format!("discovering submodules under {}", project_root.display()))?;

    let mut repositories: Vec<PathBuf> = tree
        .bottom_up()
        .iter()
        .map(|node| node.abs_path.clone())
        .collect();
    repositories.push(project_root.to_path_buf());

    let boundaries: Vec<PathBuf> = tree
        .top_down()
        .iter()
        .map(|node| node.abs_path.clone())
        .collect();

    // Walk order, with the last render of each path winning — the same rule
    // the writes themselves follow.
    let mut order: Vec<PathBuf> = Vec::new();
    let mut landing: HashMap<PathBuf, String> = HashMap::new();

    for repository in &repositories {
        if !owns_templates(repository, &boundaries, &cache)? {
            continue;
        }
        let planned = wsb::state::discard::planned_outputs_with_cache(repository, &cache)
            .with_context(|| format!("reading {}", repository.display()))?;
        for (path, rendered) in planned {
            if landing.insert(path.clone(), rendered).is_none() {
                order.push(path);
            }
        }
    }

    let (mut local, mut committed, mut edited, mut absent, mut indifferent) =
        (0usize, 0usize, 0usize, 0usize, 0usize);
    let mut unsettled: Vec<String> = Vec::new();

    for path in &order {
        let rendered = &landing[path];
        let shown = path
            .strip_prefix(project_root)
            .unwrap_or(path.as_path())
            .display()
            .to_string();

        let worktree = match std::fs::read_to_string(path) {
            Ok(text) => Some(text),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
            Err(error) => {
                wsb::errln!("  unreadable       {shown} — {error}");
                continue;
            }
        };
        let head = wsb::state::discard::head_text(path);
        // Asked before anything else: where the local render and the committed
        // file are the same bytes, no state of the working copy can tell the
        // two apart, and counting such a file either way would make a whole
        // tree look half-committed when it is not.
        let indistinguishable = head.as_deref() == Some(rendered.as_str());

        let state = match worktree {
            None => LocalState::Absent,
            Some(_) if indistinguishable => LocalState::Indifferent,
            Some(worktree) if &worktree == rendered => LocalState::Local,
            Some(worktree) if head.as_deref() == Some(worktree.as_str()) => LocalState::Committed,
            Some(_) => LocalState::Edited,
        };
        let label = match state {
            LocalState::Local => {
                local += 1;
                "local"
            }
            LocalState::Committed => {
                committed += 1;
                "as committed"
            }
            LocalState::Indifferent => {
                indifferent += 1;
                "same either way"
            }
            LocalState::Absent => {
                absent += 1;
                unsettled.push(format!("  not written yet  {shown}"));
                "not written yet"
            }
            LocalState::Edited => {
                edited += 1;
                unsettled.push(format!("  neither          {shown}"));
                "neither"
            }
        };
        if list_files {
            wsb::outln!("  {:<16} {shown}", label);
        }
    }

    let total = local + committed + edited + absent + indifferent;
    if total == 0 {
        wsb::outln!("No repository under here has anything a render writes.");
        return Ok(());
    }

    let deciding = local + committed + edited + absent;
    if deciding == 0 {
        wsb::outln!(
            "Nothing here tells the two states apart: all {total} generated file(s) render the \
             same with and without {variable}."
        );
        return Ok(());
    }

    // The count that answers the question, first, over the files that can
    // answer it. The ones that answer neither are named, because those are the
    // ones with a decision left in them.
    wsb::outln!(
        "{local} of {deciding} file(s) that tell the two states apart carry the local render; \
         {committed} stand as committed."
    );
    if indifferent > 0 {
        wsb::outln!("  ({indifferent} more render the same either way.)");
    }
    for line in &unsettled {
        wsb::outln!("{line}");
    }
    if edited + absent == 0 {
        if local == 0 {
            wsb::outln!(
                "This tree is as committed. 'wsb local on' points it at the working copies."
            );
        } else if committed == 0 {
            wsb::outln!("This tree is local. 'wsb local off' takes that back.");
        }
    }
    Ok(())
}

/// Leave a tree that is genuinely not local, whatever it took.
///
/// # The trap this exists for
///
/// `wsb local off` restores what is COMMITTED, and that is the right rule: it
/// is what preserves a hand edit made since the last render. But it makes the
/// committed local render a FIXED POINT. Once a locally-rendered manifest has
/// been committed, `off` restores the local render, `checkpoint` — which is
/// `off`, commit, push, `on` — commits and pushes it again, and every run
/// afterwards does the same. Nothing in the loop can get out of it.
///
/// That is not hypothetical. Thirty-two generated manifests across the
/// cartridges, the cartridge SDKs, fabricloom, mfab-tests, the fabric and the
/// website reached HEAD that way, one of them a PUBLISHED mirror carrying
/// `capdag = { path = "../../capdag/capdag-rs" }` — the exact shape that once
/// made a published capdag tag unresolvable for every consumer of it.
///
/// So the take-back is CHECKED, and where the committed form is itself local
/// the only thing that can produce a committable tree is a fresh render
/// against published tags. That is done here, and said out loud, because it
/// rewrites files `off` had just decided to leave alone.
///
/// Fresh rendering only ever fires where the committed form is broken, so the
/// ordinary case — a local render that is only in the working tree — still
/// restores hand edits exactly as before.
/// Refuse a plain `wsb update` in a worktree that is in local mode.
///
/// Local mode is a render made with the local variable set, and nothing on disk
/// remembers that it was: a plain update renders without it, so it quietly
/// turned the dependents it reached back to published tags while the rest of
/// the fleet stayed local — half of each mode, which neither `local on` nor
/// `local off` had produced. Each of those states is reached by its own
/// command, so the update says which one was meant.
fn refuse_update_in_local_mode(project_root: &Path) -> Result<()> {
    // A worktree that declares no local render cannot be in local mode.
    let Some(local) = declared_local_rendering(project_root)? else {
        return Ok(());
    };
    if std::env::var_os(&local.variable).is_some_and(|v| !v.is_empty()) {
        return Ok(());
    }
    let found = wsb::state::local_render::scan_worktree(project_root, &local.variable)
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    if found.is_empty() {
        return Ok(());
    }
    Err(anyhow::anyhow!(
        "this worktree is in local mode: {} file(s) are rendered against the working copies \
         (first: {}). A plain update would render what it reaches against published tags and \
         leave the rest local.\n  \
         Refresh the local render: wsb local on\n  \
         Leave local mode:         wsb local off",
        found.len(),
        found[0].message()
    ))
}

fn ensure_not_local(project_root: &Path, variable: &str, dry_run: bool) -> Result<()> {
    // The WORKTREE root, not the directory the command was typed in. "Is this
    // fleet local" is a question about the whole nesting tree, and asked of a
    // submodule it answers for that submodule alone — so a `checkpoint` run
    // from inside a submodule scanned a repository with no local templates in
    // it at all, found nothing, and committed the whole fleet's local render
    // with a clean bill of health. The store resolves its own
    // location the same way and for the same reason.
    let root = wsb::roots::find_super_root(project_root)
        .unwrap_or_else(|| project_root.to_path_buf());
    let found =
        wsb::state::local_render::scan_worktree(project_root, variable).map_err(|e| anyhow::anyhow!("{e}"))?;
    if found.is_empty() {
        return Ok(());
    }

    wsb::outln!(
        "── {} file(s) are still local after the take-back ──",
        found.len()
    );
    // WHY each one survived, read from git. The two reasons call for opposite
    // responses — one means a repository's history needs repairing, the other
    // means nothing does — and this line used to assert the first
    // unconditionally. Run from `wsb/`, where the take-back reaches its own
    // update scope and not the nested submodules, it named a contaminated
    // history for thirty-three manifests whose committed form was clean, and
    // sent whoever read it to repair them.
    use wsb::state::local_render::Persistence;
    let why: Vec<Persistence> = found
        .iter()
        .map(|one| wsb::state::local_render::persistence(&root, one, variable))
        .collect();
    for (one, state) in found.iter().zip(&why).take(5) {
        wsb::outln!("  {}  ({})", one.message(), state.describe());
    }
    if found.len() > 5 {
        wsb::outln!("  … and {} more", found.len() - 5);
    }
    let committed = why.iter().filter(|s| **s == Persistence::Committed).count();
    if committed > 0 {
        wsb::outln!(
            "  {committed} of them are committed that way, so restoring what is committed \
             restores it and every checkpoint re-pushes it. Those repositories need the \
             fresh render COMMITTED, not just written."
        );
    }
    wsb::outln!("  Rendering fresh against published tags instead.");

    if dry_run {
        wsb::outln!("  would re-render the fleet with {variable} unset");
        return Ok(());
    }

    // The one render that can escape: without the variable, so the templates
    // take their published branch. Removed rather than emptied — the map a
    // template reads treats an empty value as false, but a reader of this code
    // should not have to know that to see what is happening.
    //
    // And LEFT removed. Putting it back here looked tidy and silently undid
    // the whole repair: the commit that follows renders again to bump the
    // version, that render read the variable, and every manifest went local
    // again between "the tree is no longer local" and the commit. Two whole
    // checkpoints reported success having committed nothing but version bumps.
    // The caller owns the variable from here — `checkpoint` sets it again for
    // its own last step, which is the only thing that wants it.
    std::env::remove_var(variable);
    update_recursive(false, false, None, None, &root, true, false)?;

    let left = wsb::state::local_render::scan_worktree(project_root, variable)
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    if !left.is_empty() {
        // Fail hard rather than report success over a tree that would ship a
        // path dependency. Nothing downstream can tell the difference, which
        // is why this is the last place that can.
        bail!(
            "{} file(s) still carry the local render after a fresh render:\n{}\n  \
             Something outside the templates is writing them, and committing this tree \
             would publish a dependency that resolves on this machine only.",
            left.len(),
            left.iter()
                .take(10)
                .map(|one| format!("      {}", one.message()))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }
    wsb::outln!("  the tree is no longer local");
    Ok(())
}

/// `wsb checkpoint` — the round trip around a commit.
///
/// A manifest rendered against the working copies resolves on this machine and
/// nowhere else, so what gets committed has to be the published references.
/// Taking the render back, committing, pushing and putting it back is four
/// commands that must not be run out of order, and one of them is easy to
/// forget — which is the whole reason this is one command. A worktree that
/// declares no local render has nothing to take back: it brings main in,
/// commits and pushes.
fn run_checkpoint_command(
    message: &str,
    no_push: bool,
    dry_run: bool,
    project_root: &Path,
) -> Result<()> {
    let local = declared_local_rendering(project_root)?;

    if let Some(local) = &local {
        std::env::set_var(&local.variable, "1");
        wsb::outln!("── taking the local render back ──");
        discard_recursive(project_root, dry_run)?;
        // Checked, not assumed. A checkpoint that commits a local render
        // pushes it to every mirror, and the next checkpoint pushes it again.
        ensure_not_local(project_root, &local.variable, dry_run)?;
        // Cleared whichever way the take-back went. The commit renders again —
        // every repository's pre-commit hook runs `update --git-add`, and
        // hooks inherit this process's environment — so a variable still set
        // here made those renders local and staged them. `ensure_not_local`
        // clears it only when it had to repair something, so the checkpoint
        // after a repair committed the local render again: manifests
        // alternated between published and local from one checkpoint to the
        // next.
        std::env::remove_var(&local.variable);
    }

    wsb::outln!("── bringing main in ──");
    wsb::fleet::commands::pull::bring_main_in(project_root, dry_run).map_err(|e| anyhow::anyhow!(e))?;

    wsb::outln!("── committing ──");
    run_fleet_or_repo_command(
        wsb::fleet::cli::Commands::Commit {
            message: message.to_string(),
            push: false,
            stage_all: true,
            exclude: Vec::new(),
            include: Vec::new(),
            force_all: false,
        },
        false,
        dry_run,
    )?;

    // A push that fails is reported after the tree is local again, not
    // instead of it. The commits are made; a push refused by the remote (a
    // GitHub 500 did it) is retried with a plain push, and returning here left
    // the tree rendered against published tags, which nobody had asked for.
    let pushed = if no_push {
        wsb::outln!("── not pushing (--no-push) ──");
        Ok(())
    } else {
        wsb::outln!("── pushing ──");
        run_fleet_or_repo_command(
            wsb::fleet::cli::Commands::Push {
                force_with_lease: false,
                force_all: false,
            },
            false,
            dry_run,
        )
    };

    // Last, and unconditional: the tree is left the way it was found. A
    // checkpoint that stopped here would leave a developer building against
    // published tags without having asked to.
    if let Some(local) = &local {
        wsb::outln!("── going local again ──");
        // Set HERE, and not before the commit. Everything above this line —
        // the take-back, the escape render, the commit's own version bump —
        // has to read a tree that is not local, and the commit renders too.
        std::env::set_var(&local.variable, "1");
        if dry_run {
            wsb::outln!("  would render the fleet with {} set", local.variable);
        } else {
            render_local(project_root, local, false, true, false)?;
        }
        wsb::outln!("Manifests point at the working copies here.");
    }
    pushed.map_err(|e| {
        anyhow::anyhow!("{e:#}\n  The commits are made; push again with: wsb push")
    })
}

/// `wsb update --recursive` — every repository in the nesting tree, leaves first.
///
/// The order is the whole point. A parent's templates render its OWN version
/// and, through `{{ projects.<alias>.* }}`, the versions of the projects it
/// depends on — so a parent rendered before its submodules bakes the versions
/// they had a moment ago. Children first means every parent reads what is
/// already on disk.
///
/// A repository that owns no `.wstemplate` is not updated, and is SAID rather
/// than passed over: `update` would otherwise write a version file into a
/// checkout that never had one, which is how a vendored dependency acquires
/// wsb state it did not ask for. Ownership follows git's boundary — a template
/// inside a nested submodule belongs to that submodule, never to its parent.
fn update_recursive(
    no_git: bool,
    git_add: bool,
    version_suffix: Option<&str>,
    tag: Option<&str>,
    project_root: &Path,
    quiet: bool,
    verify: bool,
) -> Result<()> {
    use wsb::fleet::git::tree::SubmoduleTree;

    // One cache for the whole walk. Each repository below reads what the ones
    // before it already read — the worktree's `.wsb/repo.json` settings, its
    // `.wstemplate` files and what they refer to, commit counts, tags, remote
    // tags — and NOT the two things an update changes underneath itself: a
    // project's version.txt, and whether a worktree is clean. See
    // [`wsb::state::RunCache`].
    let cache = RunCache::new();

    let tree = SubmoduleTree::discover_allow_empty(project_root)
        .with_context(|| format!("discovering submodules under {}", project_root.display()))?;

    // Children before parents, then this repository last.
    let mut repositories: Vec<PathBuf> =
        tree.bottom_up().iter().map(|node| node.abs_path.clone()).collect();
    repositories.push(project_root.to_path_buf());

    // Every nested repository, so a parent's own scan can exclude them.
    let boundaries: Vec<PathBuf> = tree
        .top_down()
        .iter()
        .map(|node| node.abs_path.clone())
        .collect();

    let mut updated = 0usize;
    let mut skipped: Vec<String> = Vec::new();
    for repository in &repositories {
        let label = match repository.strip_prefix(project_root) {
            Ok(relative) if relative.as_os_str().is_empty() => ".".to_string(),
            Ok(relative) => relative.display().to_string(),
            Err(_) => repository.display().to_string(),
        };
        if !owns_templates(repository, &boundaries, &cache)? {
            skipped.push(label);
            continue;
        }
        if !quiet {
            wsb::outln!("── {label} ──");
        }
        update_state(
            no_git,
            git_add,
            version_suffix,
            tag,
            repository,
            quiet,
            &cache,
            verify,
        )
        .with_context(|| format!("updating {label}"))?;
        updated += 1;
    }

    if !quiet {
        wsb::outln!("update: {updated} repository(ies) updated");
        if !skipped.is_empty() {
            wsb::outln!(
                "  no templates of their own, so untouched: {}",
                skipped.join(" ")
            );
        }
    }
    Ok(())
}

/// Take back what an update wrote, in every repository it would write to.
///
/// The same tree `update --recursive` walks, in the same order and skipping
/// the same repositories — a discard that visited a different set from the
/// update it undoes would leave some of the update behind.
fn discard_recursive(project_root: &Path, dry_run: bool) -> Result<()> {
    use wsb::fleet::git::tree::SubmoduleTree;

    // Same walk, same cache, same reasons as `update_recursive`.
    let cache = RunCache::new();

    let tree = SubmoduleTree::discover_allow_empty(project_root)
        .with_context(|| format!("discovering submodules under {}", project_root.display()))?;

    let mut repositories: Vec<PathBuf> = tree
        .bottom_up()
        .iter()
        .map(|node| node.abs_path.clone())
        .collect();
    repositories.push(project_root.to_path_buf());

    let boundaries: Vec<PathBuf> = tree
        .top_down()
        .iter()
        .map(|node| node.abs_path.clone())
        .collect();

    let mut visited = 0usize;
    for repository in &repositories {
        if !owns_templates(repository, &boundaries, &cache)? {
            continue;
        }
        let label = match repository.strip_prefix(project_root) {
            Ok(relative) if relative.as_os_str().is_empty() => ".".to_string(),
            Ok(relative) => relative.display().to_string(),
            Err(_) => repository.display().to_string(),
        };
        wsb::outln!("── {label} ──");
        run_update_discard(repository, dry_run, &cache)?;
        visited += 1;
    }

    if visited == 0 {
        wsb::outln!("No repository under here has anything an update writes.");
    }
    Ok(())
}

/// Take back what an update wrote, and report what could not be taken back.
fn run_update_discard(project_root: &Path, dry_run: bool, cache: &Arc<RunCache>) -> Result<()> {
    use wsb::state::discard::Outcome;

    let report = wsb::state::discard::run_with_cache(project_root, dry_run, cache)?;
    let verb = if dry_run { "would take back" } else { "took back" };

    for file in &report.files {
        let shown = file
            .path
            .strip_prefix(project_root)
            .unwrap_or(&file.path)
            .display();
        match &file.outcome {
            Outcome::Reverted => wsb::outln!("  {verb}  {shown}"),
            // Named individually: this is the case where the reader still has
            // a decision to make, and a count at the bottom would not tell
            // them which files to look at.
            Outcome::Partial { kept } => wsb::outln!(
                "  {verb}  {shown} — {kept} region(s) left alone, yours and the update's edits \
                 are on the same lines"
            ),
            Outcome::Removed => wsb::outln!("  {verb}  {shown} (created by the update, removed)"),
            Outcome::Unresolvable { reason } => {
                wsb::errln!("  refused  {shown} — {reason}")
            }
            // Every file an update writes is listed above; the ones it
            // contributed nothing to are not worth a line each.
            Outcome::Untouched => {}
        }
    }

    let changed = report.changed();
    let refused = report
        .files
        .iter()
        .filter(|f| matches!(f.outcome, Outcome::Unresolvable { .. }))
        .count();
    let partial = report.partial().count();

    if changed == 0 && refused == 0 {
        wsb::outln!("Nothing to take back: no file carries changes from an update.");
        return Ok(());
    }
    wsb::outln!(
        "{} {changed} file(s) of {} the update writes.",
        if dry_run { "Would change" } else { "Changed" },
        report.files.len()
    );
    if partial > 0 {
        wsb::outln!(
            "{partial} file(s) still hold an update's edit on a line you also changed — those \
             lines are yours and were not touched."
        );
    }
    if refused > 0 {
        wsb::errln!("{refused} file(s) were refused; nothing was written to them.");
    }
    Ok(())
}

fn update_state(
    no_git: bool,
    git_add: bool,
    version_suffix: Option<&str>,
    tag: Option<&str>,
    project_root: &Path,
    quiet: bool,
    cache: &Arc<RunCache>,
    verify: bool,
) -> Result<()> {
    // The repository being updated, not the one the command was typed in. A
    // recursive update never changes directory, so a current-directory check
    // here answered for the superproject on all 34 passes.
    if !no_git && !is_git_repository_in(project_root) {
        anyhow::bail!(
            "{} is not a git repository. Run 'wsb init' there first, or use 'wsb update --no-git' for a non-git directory.",
            project_root.display()
        );
    }

    let pb = make_spinner(quiet, "loading configuration…");

    let settings = RepoSettings::require(project_root)?;

    if let Some(t) = tag {
        wsb::state::validate_git_tag(t)?;
    }

    pb.set_message("calculating version…");
    // `--git-add` is the pre-commit hook's: this render is for a commit being
    // made in this repository.
    if git_add {
        cache.commit_is_being_made_in(project_root);
    }
    let mut version_info = if no_git {
        calculate_version_without_git(project_root, &settings)?
    } else {
        calculate_version(project_root, &settings, cache)?
    };

    // Before anything is written, so both answers describe the same tree: the
    // version this repository gets, taken again through a cache that has
    // remembered nothing. See `--verify`.
    if verify && !no_git {
        let fresh = RunCache::new();
        if git_add {
            fresh.commit_is_being_made_in(project_root);
        }
        let alone = calculate_version(project_root, &settings, &fresh)?;
        anyhow::ensure!(
            alone.full_version == version_info.full_version,
            "--verify: the run's cache calculated version {} for {}, a cache of its own {}",
            version_info.full_version,
            project_root.display(),
            alone.full_version
        );
    }

    // A tag names the version it tags, so it IS the version's suffix — in the
    // one grammar the worktree has for one, `1.8.2-rc`, which
    // `parse_version_string` reads back. Appending it with an underscore
    // instead produced `1.8.2_rc`: a string this worktree writes into
    // `version.txt` and then cannot parse, so every repository updated after
    // it in a recursive run failed on "Invalid patch in version string".
    version_info.full_version = settings.full_version(
        &version_info.major_version,
        version_info.minor_version,
        version_info.patch_version,
        tag.or(version_suffix),
    );

    pb.set_message(format!("writing {} → {}…", "version", &settings.version.file));
    // Write the version file first — other repositories read it when
    // resolving {{ projects.OUR_ALIAS.version }}
    update_version_file_in_repo(&version_info, &settings.version, project_root)?;
    info!("Updated version file: {}", settings.version.file);
    if !quiet {
        pb.println(format!("  {} updated {}", "✓".green(), settings.version.file));
    }

    let full_version = version_info.full_version.clone();

    pb.set_message("rendering .wstemplate files…");
    let mut rendered_wstemplate_files: Vec<String> = Vec::new();
    {
        let engine = WstemplateEngine::for_repo(&settings, version_info.clone(), project_root, Arc::clone(cache));

        let produced = engine.produce_relevant()?;
        if verify {
            let alone = WstemplateEngine::for_repo(&settings, version_info, project_root, RunCache::new());
            compare_renders(&produced, &alone.produce_relevant()?, project_root)?;
        }

        let rendered = engine.write_produced(produced)?;
        for r in &rendered {
            info!(
                "wstemplate: {} -> {}",
                r.source_path.display(),
                r.output_path.display()
            );
            rendered_wstemplate_files.push(r.output_path.display().to_string());
            // The lock the render kept in agreement with this manifest is staged
            // with it, or the commit carries the manifest's version beside a
            // lock naming the previous one. Only a lock the repository tracks:
            // a library that ignores its lock keeps ignoring it.
            if let Some(lock) = &r.lockfile {
                if wsb::git_backend::is_tracked(lock)? {
                    rendered_wstemplate_files.push(lock.display().to_string());
                }
            }
        }
        if !rendered.is_empty() && !quiet {
            pb.println(format!(
                "  {} rendered {} .wstemplate file(s)",
                "✓".green(),
                rendered.len()
            ));
        }
    }

    if !no_git && git_add && is_git_repository_in(project_root) {
        pb.set_message("staging files…");
        let mut files_to_add = vec![settings.version.file.clone()];

        for file in collect_project_files_for_git_add(project_root, &settings.version)? {
            if !files_to_add.contains(&file) {
                files_to_add.push(file);
            }
        }

        for file in &rendered_wstemplate_files {
            if !files_to_add.contains(file) {
                files_to_add.push(file.clone());
            }
        }

        if !files_to_add.is_empty() {
            let added_files = add_files_to_git(&files_to_add, &project_root)?;
            if !added_files.is_empty() {
                info!(
                    "Added {} files to git staging area: {}",
                    added_files.len(),
                    added_files.join(", ")
                );
                if !quiet {
                    pb.println(format!(
                        "  {} staged {} file(s)",
                        "✓".green(),
                        added_files.len()
                    ));
                    for file in &added_files {
                        pb.println(format!("      {}", file));
                    }
                }
            }
        }
    }

    // Create git tag if --tag was provided
    if let Some(t) = tag {
        if is_git_repository_in(project_root) {
            pb.set_message(format!("creating tag {}…", t));
            let tag_name = format!("v{}", full_version);
            let tag_message = format!("Tagged version {}", full_version);
            // The repository being updated. Taking this from the current
            // directory tagged the superproject once per submodule, each time
            // with that submodule's version.
            let repo = wsb::git_backend::discover_repo(project_root)?;
            wsb::git_backend::create_tag(&repo, &tag_name, &tag_message)?;
            // A ref moved. Everything this run remembers about that repository
            // — its tags, what HEAD describes as — was true a moment ago and is
            // not now.
            cache.forget_repo(project_root);
            info!("Created git tag: {} (tag: {})", tag_name, t);
            if !quiet {
                pb.println(format!(
                    "  {} created tag {}",
                    "✓".green(),
                    tag_name.green().bold()
                ));
            }
        } else {
            anyhow::bail!("--tag requires a git repository; {} is not one", project_root.display());
        }
    }

    pb.finish_and_clear();
    if !quiet {
        wsb::outln!("{} {}", "✓".green().bold(), full_version.bold());
    }

    Ok(())
}

fn collect_project_files_for_git_add(
    project_root: &Path,
    config: &VersionSettings,
) -> Result<Vec<String>> {
    let mut files = Vec::new();

    if config.detect_manifests {
        for project_file in detect_project_files(project_root)? {
            let path = project_file.path.to_string_lossy().to_string();
            if !files.contains(&path) {
                files.push(path);
            }
        }
    }

    for configured_path in &config.manifests {
        let full_path = project_root.join(configured_path);
        if full_path.exists() {
            let path = full_path.to_string_lossy().to_string();
            if !files.contains(&path) {
                files.push(path);
            }
        }
    }

    // Each manifest's lock, which the update kept in step with it, when the
    // repository tracks one: a commit of the manifest alone carries the lock
    // naming the previous version.
    let mut locks = Vec::new();
    for manifest in &files {
        if let Some(lock) = wsb::state::wstemplate::lockfile_followed_by(Path::new(manifest)) {
            let lock_path = lock.to_string_lossy().to_string();
            if lock.is_file() && wsb::git_backend::is_tracked(&lock)? && !files.contains(&lock_path) && !locks.contains(&lock_path) {
                locks.push(lock_path);
            }
        }
    }
    files.extend(locks);

    Ok(files)
}

fn handle_wstemplate_command(action: WstemplateAction, project_root: &Path) -> Result<()> {
    let mut settings = RepoSettings::require(project_root)?;
    let scan_root = settings.templates_root_of(project_root);

    match action {
        WstemplateAction::Alias { alias } => {
            wsb::settings::repo::check_alias(&alias)?;
            settings.alias = alias;
            settings.save(project_root)?;
            wsb::outln!(
                "{} is now known to templates as '{}' ({}; commit it)",
                settings.name,
                settings.alias,
                RepoSettings::path(project_root).display()
            );
        }

        WstemplateAction::Root { path } => {
            let root = wsb::platform::canonicalize(&path)
                .with_context(|| format!("Cannot resolve path: {}", path.display()))?;
            let repo = wsb::platform::canonicalize(project_root)
                .with_context(|| format!("Cannot resolve path: {}", project_root.display()))?;
            settings.templates_root = wsb_prj::settings::relative_path(&root, &repo)?;
            settings.save(project_root)?;
            wsb::outln!(
                "{}'s templates look under {} ({}; commit it)",
                settings.name,
                settings.templates_root,
                RepoSettings::path(project_root).display()
            );
        }

        WstemplateAction::Show => {
            wsb::outln!("alias  {}", settings.alias);
            wsb::outln!("root   {} ({})", settings.templates_root, scan_root.display());
        }

        WstemplateAction::List => {
            // Listing renders nothing, but it reports what a render WOULD
            // produce; it must read the same declared version a render does.
            let version_info = wsb::state::read_version_from_path(project_root)?;
            let engine = WstemplateEngine::for_repo(&settings, version_info, project_root, RunCache::new());

            let project_roots = engine.discover_project_roots()?;
            let templates = engine.discover_relevant(&project_roots)?;
            if templates.is_empty() {
                wsb::outln!("No relevant .wstemplate files found.");
            } else {
                wsb::outln!("{} relevant .wstemplate files:", templates.len());
                for path in &templates {
                    wsb::outln!("  {}", path.display());
                }
            }
        }

        WstemplateAction::Vars { alias, remote } => {
            // The declared version, for the same reason `Render` reads it:
            // `vars` must report the values a render would actually stamp.
            let engine = WstemplateEngine::for_repo(
                &settings,
                wsb::state::read_version_from_path(project_root)?,
                project_root,
                RunCache::new(),
            );
            let project_roots = engine.discover_project_roots()?;

            // Values are resolved against a real project so the listing shows
            // what a template would actually stamp, not just field names.
            let alias = alias.unwrap_or_else(|| settings.alias.clone());
            let (root, version) = if alias == settings.alias {
                (
                    project_root.to_path_buf(),
                    wsb::state::read_version_from_path(project_root)?,
                )
            } else {
                let root = project_roots.get(&alias).cloned().ok_or_else(|| {
                    let mut known: Vec<&str> =
                        project_roots.keys().map(|key| key.as_str()).collect();
                    known.sort();
                    anyhow::anyhow!(
                        "Unknown alias '{}'. Known aliases: [{}]",
                        alias,
                        known.join(", ")
                    )
                })?;
                let version = wsb::state::read_version_from_path(&root)?;
                (root, version)
            };

            let facts = wsb::state::project_facts::gather(
                &wsb::state::project_facts::ProjectIdentity {
                    alias: &alias,
                    root: &root,
                    scan_root: &scan_root,
                    version: &version,
                    name: if alias == settings.alias {
                        Some(settings.name.as_str())
                    } else {
                        None
                    },
                },
                remote,
            )?;

            wsb::outln!(
                "Template variables for {} ({}):",
                alias.bold(),
                root.display()
            );
            for field in wsb::state::project_facts::FIELDS {
                let usage = format!("{{{{ projects.{}.{} }}}}", alias, field.name);
                match facts.values().get(field.name) {
                    Some(value) => {
                        let text = match value {
                            serde_json::Value::String(text) => text.clone(),
                            other => other.to_string(),
                        };
                        wsb::outln!("  {:<44} {}", usage, text);
                    }
                    None => {
                        let reason = facts
                            .unavailable()
                            .get(field.name)
                            .map(String::as_str)
                            .unwrap_or("unavailable");
                        wsb::outln!("  {:<44} {}", usage, format!("— {reason}").dimmed());
                    }
                }
            }
            wsb::outln!(
                "\n{}",
                "Also available: {{ datetime.iso | date | time | year | month | day | timestamp }}"
                    .dimmed()
            );
            wsb::outln!(
                "{}",
                "The same fields are available as {{ project.FIELD }} for the project owning a template."
                    .dimmed()
            );
        }

        WstemplateAction::Render => {

            // The DECLARED version, not a freshly calculated one. A manifest is
            // generated from `version.txt`; recomputing here would stamp a
            // number the declaration does not carry, and every rendered
            // manifest would drift one commit ahead of the project it belongs
            // to. Only `wsb update` advances the declaration — and it writes
            // `version.txt` before it renders, so it still stamps the new one.
            let version_info = wsb::state::read_version_from_path(project_root)?;
            let engine = WstemplateEngine::for_repo(&settings, version_info, project_root, RunCache::new());

            let rendered = engine.render_relevant()?;
            if rendered.is_empty() {
                wsb::outln!("No templates to render.");
            } else {
                wsb::outln!("Rendered {} templates:", rendered.len());
                for r in &rendered {
                    wsb::outln!(
                        "  {} \u{2192} {}",
                        r.source_path.display(),
                        r.output_path.display()
                    );
                }
            }
        }
    }

    Ok(())
}

fn run_scrap_command(paths: Vec<std::path::PathBuf>, command: Option<ScrapCommands>) -> Result<()> {
    let mut args = Vec::new();

    // Convert clap ScrapCommands to original scrap binary arguments
    match command {
        Some(ScrapCommands::List { sort }) => {
            args.push("list".to_string());
            args.push("--sort".to_string());
            args.push(sort);
        }
        Some(ScrapCommands::Clean { days, dry_run }) => {
            args.push("clean".to_string());
            args.push("--days".to_string());
            args.push(days.to_string());
            if dry_run {
                args.push("--dry-run".to_string());
            }
        }
        Some(ScrapCommands::Purge { force }) => {
            args.push("purge".to_string());
            if force {
                args.push("--force".to_string());
            }
        }
        Some(ScrapCommands::Find { pattern, content }) => {
            args.push("find".to_string());
            args.push(pattern);
            if content {
                args.push("--content".to_string());
            }
        }
        Some(ScrapCommands::Archive { output, remove }) => {
            args.push("archive".to_string());
            if let Some(output_path) = output {
                args.push("--output".to_string());
                args.push(output_path.to_string_lossy().to_string());
            }
            if remove {
                args.push("--remove".to_string());
            }
        }
        None => {
            // Add all paths as arguments
            for path in paths {
                args.push(path.to_string_lossy().to_string());
            }
        }
    }

    wsb::run_scrap(args)
}

fn run_unscrap_command(
    name: Option<String>,
    force: bool,
    to: Option<std::path::PathBuf>,
) -> Result<()> {
    let mut args = Vec::new();

    if let Some(item_name) = name {
        args.push(item_name);
    }

    if force {
        args.push("--force".to_string());
    }

    if let Some(target_path) = to {
        args.push("--to".to_string());
        args.push(target_path.to_string_lossy().to_string());
    }

    wsb::run_unscrap(args)
}

fn run_ldiff_command(substitute_char: String) -> Result<()> {
    let mut chars = substitute_char.chars();
    let ch = chars
        .next()
        .ok_or_else(|| anyhow::anyhow!("Substitute character cannot be empty"))?;
    if chars.next().is_some() {
        anyhow::bail!(
            "Substitute character must be exactly one Unicode character, got: '{}'",
            substitute_char
        );
    }
    wsb::ldiff::process_stdin(ch)
}

fn run_compact_command(
    input: Option<String>,
    output: Option<String>,
    token_mode: bool,
) -> Result<()> {
    let result = match input {
        Some(path) => wsb::compact::compact_file(std::path::Path::new(&path), token_mode)
            .with_context(|| format!("Failed to compact file: {}", path))?,
        None => {
            if std::io::stdin().is_terminal() {
                wsb::errln!("Reading from stdin. Pipe input or provide a file path.");
                wsb::errln!("Usage: wsb compact [FILE] [-o OUTPUT] [--token-mode]");
                anyhow::bail!("No input provided and stdin is a terminal");
            }
            wsb::compact::compact_stdin(token_mode).with_context(|| "Failed to compact stdin")?
        }
    };

    match output {
        Some(path) => {
            std::fs::write(&path, &result)
                .with_context(|| format!("Failed to write output to: {}", path))?;
        }
        None => {
            wsb::out!("{}", result);
        }
    }
    Ok(())
}

fn run_audit_path_command() -> Result<()> {
    let path_var = std::env::var("PATH").context("PATH environment variable not set")?;
    let dirs: Vec<&str> = path_var.split(':').collect();

    let mut all_bins: std::collections::HashMap<String, Vec<std::path::PathBuf>> =
        std::collections::HashMap::new();

    for dir in &dirs {
        let dir_path = std::path::Path::new(dir);
        if let Ok(entries) = std::fs::read_dir(dir_path) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() {
                    if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                        let is_executable = std::fs::metadata(&path)
                            .map(|m| {
                                #[cfg(unix)]
                                {
                                    use std::os::unix::fs::PermissionsExt;
                                    m.permissions().mode() & 0o111 != 0
                                }
                                #[cfg(not(unix))]
                                {
                                    true
                                }
                            })
                            .unwrap_or(false);
                        if is_executable {
                            all_bins.entry(name.to_string()).or_default().push(path);
                        }
                    }
                }
            }
        }
    }

    let mut shadowed: Vec<(&String, &Vec<std::path::PathBuf>)> = all_bins
        .iter()
        .filter(|(_, paths)| paths.len() > 1)
        .collect();
    shadowed.sort_by_key(|(name, _)| (*name).clone());

    if shadowed.is_empty() {
        wsb::outln!("No shadowed executables found on PATH.");
        return Ok(());
    }

    for (name, paths) in &shadowed {
        wsb::outln!("== {} ==", name);
        for path in paths.iter() {
            wsb::outln!("  {}", path.display());
        }
        wsb::outln!();
    }

    wsb::outln!("{} shadowed executable(s) found.", shadowed.len());
    Ok(())
}

fn run_ignore_command(line: &str) -> Result<()> {
    let current_dir = std::env::current_dir().context("Cannot determine current directory")?;
    let entries = std::fs::read_dir(&current_dir)
        .with_context(|| format!("Cannot read directory: {}", current_dir.display()))?;

    let mut modified_count = 0;
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            let gitignore = path.join(".gitignore");
            if gitignore.exists() {
                let content = std::fs::read_to_string(&gitignore)
                    .with_context(|| format!("Cannot read {}", gitignore.display()))?;
                if !content.lines().any(|l| l == line) {
                    let mut new_content = content;
                    if !new_content.ends_with('\n') {
                        new_content.push('\n');
                    }
                    new_content.push_str(line);
                    new_content.push('\n');
                    std::fs::write(&gitignore, new_content)
                        .with_context(|| format!("Cannot write {}", gitignore.display()))?;
                    wsb::outln!("Added '{}' to {}", line, gitignore.display());
                    modified_count += 1;
                }
            }
        }
    }

    if modified_count == 0 {
        wsb::outln!("No .gitignore files needed updating (line already present or no .gitignore files found).");
    } else {
        wsb::outln!("Updated {} .gitignore file(s).", modified_count);
    }
    Ok(())
}

fn run_last_hash_command(file: &str) -> Result<()> {
    let output = wsb::git_backend::git_command()
        .args([
            "log",
            "-n",
            "1",
            "--follow",
            "--pretty=format:%H",
            "--",
            file,
        ])
        .output()
        .context("Failed to execute git log")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git log failed: {}", stderr.trim());
    }

    let hash = String::from_utf8_lossy(&output.stdout);
    let hash = hash.trim();
    if hash.is_empty() {
        anyhow::bail!("No commit found for file: {}", file);
    }
    wsb::outln!("{}", hash);
    Ok(())
}

fn calculate_version(
    project_root: &std::path::Path,
    settings: &RepoSettings,
    cache: &Arc<RunCache>,
) -> Result<VersionInfo> {
    let version_info = VersionInfo::calculate_with_major_in_repo_cached(settings.version.major, project_root, cache)?;
    info!("Version calculated: {}", version_info.full_version);
    Ok(version_info)
}

/// Two renders of the same repository, one through the run's shared cache and
/// one through a cache that has remembered nothing.
///
/// They must be the same bytes in the same order. Where they are not, the run
/// stops and names the file, because the whole claim of the shared cache is
/// that the fleet ends up byte-for-byte where it would have without one.
fn compare_renders(
    shared: &[wsb::state::wstemplate::Produced],
    alone: &[wsb::state::wstemplate::Produced],
    project_root: &Path,
) -> Result<()> {
    if shared.len() != alone.len() {
        let named = |set: &[wsb::state::wstemplate::Produced]| {
            set.iter()
                .map(|one| one.output_path.display().to_string())
                .collect::<Vec<_>>()
                .join(", ")
        };
        anyhow::bail!(
            "--verify: updating {} renders {} file(s) through the run's cache and {} through a \
             cache of its own.\n  with the run's: {}\n  on its own:     {}",
            project_root.display(),
            shared.len(),
            alone.len(),
            named(shared),
            named(alone)
        );
    }
    for (a, b) in shared.iter().zip(alone) {
        anyhow::ensure!(
            a.output_path == b.output_path,
            "--verify: updating {} renders {} through the run's cache where a cache of its own \
             renders {}",
            project_root.display(),
            a.output_path.display(),
            b.output_path.display()
        );
        anyhow::ensure!(
            a.content == b.content,
            "--verify: {} renders differently through the run's cache than on its own.\n\
             This is the cache serving an answer that stopped being true — report it with the \
             template at {}.",
            a.output_path.display(),
            a.source_path.display()
        );
    }
    Ok(())
}

/// The version of a repository with no git history to count: what its version
/// file declares, or its committed major with nothing counted when it has
/// none yet.
fn calculate_version_without_git(project_root: &std::path::Path, settings: &RepoSettings) -> Result<VersionInfo> {
    let version_path = project_root.join(&settings.version.file);
    let version_info = if version_path.exists() {
        wsb::state::read_version_from_path(project_root)?
    } else {
        let major = settings.version.major;
        VersionInfo {
            major_version: format!("v{major}"),
            minor_version: 0,
            patch_version: 0,
            full_version: format!("{major}.0.0"),
        }
    };
    info!(
        "Version calculated without git state: {}",
        version_info.full_version
    );
    Ok(version_info)
}

fn log_action(message: &str) {
    match log_to_file(message) {
        Ok(_) => {}
        Err(_) => {}
    }
}

fn log_to_file(message: &str) -> Result<()> {
    // Use structured logging instead of custom file logging
    info!("{}", message);
    Ok(())
}

fn ensure_git_repository_at(path: &Path) -> Result<()> {
    if is_git_checkout(path) {
        return Ok(());
    }
    wsb::git_backend::init_repository(path)?;
    wsb::outln!("Initialized Git repository at {}", path.display());
    Ok(())
}

/// `wsb init`: make the repository at `repo_root` one wsb manages, and every
/// submodule under it.
fn setup_new_project(name: Option<String>, repo_root: &Path) -> Result<()> {
    let settings = setup_repo_at(repo_root, name.as_deref())?;
    print_repo_setup_complete(&settings, repo_root);
    Ok(())
}

/// Make the repository at `repo_root` one wsb manages: its committed
/// `.wsb/repo.json`, kept when it is there and written when it is not, and the
/// pre-commit hook that versions every commit.
fn setup_repo_at(repo_root: &Path, name: Option<&str>) -> Result<RepoSettings> {
    wsb::outln!(
        "{}",
        format!("Setting up wsb in {}...", repo_root.display()).bold().green()
    );
    ensure_git_repository_at(repo_root)?;
    refuse_hidden_settings(repo_root)?;

    let settings = match RepoSettings::load(repo_root)? {
        Some(held) => {
            if let Some(name) = name {
                if held.name != name {
                    anyhow::bail!(
                        "{} already names this repository '{}'; edit it there to rename it",
                        RepoSettings::path(repo_root).display(),
                        held.name
                    );
                }
            }
            wsb::outln!(
                "  {} {} is already there; it is kept as it is",
                "✓".green(),
                RepoSettings::path(repo_root).display()
            );
            held
        }
        None => {
            let (alias, templates_root) = default_alias_and_root(repo_root)?;
            let settings = RepoSettings {
                name: match name {
                    Some(name) => name.to_string(),
                    None => wsb_prj::repository_name(repo_root)?,
                },
                alias,
                templates_root,
                version: VersionSettings::at_major(wsb::state::read_major_version_from_file(repo_root).unwrap_or(0)),
            };
            settings.save(repo_root)?;
            wsb::outln!(
                "  {} wrote {}; commit it, so every clone is set up the same",
                "✓".green(),
                RepoSettings::path(repo_root).display()
            );
            settings
        }
    };
    install_pre_commit_hook(repo_root)?;
    Ok(settings)
}

/// Refuse a repository whose ignore rules hide `.wsb/`: everything in it is
/// meant to be committed, and settings git cannot see are settings no clone
/// will have. The rule that hides it is named.
fn refuse_hidden_settings(repo_root: &Path) -> Result<()> {
    let probe = RepoSettings::path(repo_root);
    let output = wsb::git_backend::git_command()
        .arg("-C")
        .arg(repo_root)
        .args(["check-ignore", "--no-index", "-v"])
        .arg(&probe)
        .output()
        .with_context(|| format!("cannot run git in {}", repo_root.display()))?;
    match output.status.code() {
        Some(1) => Ok(()),
        Some(0) => anyhow::bail!(
            "{} hides .wsb/, which is committed whole: {}. Remove that rule and run again",
            repo_root.display(),
            String::from_utf8_lossy(&output.stdout).trim()
        ),
        _ => anyhow::bail!(
            "cannot ask git whether .wsb/ is ignored in {}: {}",
            repo_root.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        ),
    }
}

/// Install the pre-commit hook that runs `wsb update --quiet --git-add` on
/// every commit of the repository at `repo_root`.
fn install_pre_commit_hook(repo_root: &Path) -> Result<()> {
    let git_dir = repo_git_dir(repo_root)?;
    let hooks_dir = git_dir.join("hooks");
    if hooks_dir.is_dir() {
        let hook_path = hooks_dir.join("pre-commit");
        let hook_content = PRE_COMMIT_HOOK;
        // Written when there is no hook, and over an older version of this
        // one. It was skipped whenever the mark was there, so an older version
        // — one that named an absolute wsb, `~/.cargo/bin/wsb` — was never
        // replaced: `wsb check` reported it and said to run `wsb init`, and
        // `wsb init` left it as it was. When that wsb was removed, every commit
        // in the fleet failed on "No such file or directory", a release's own
        // commit of its notes among them (20 Oct 2026).
        //
        // A hook of somebody's own is never written over. Replacing anything
        // that was not exactly this hook threw away a linter or a formatter
        // the repository's owner had installed, without a word; it is left as
        // it is, and what to add to it is said.
        let existing = match std::fs::read_to_string(&hook_path) {
            Ok(existing) => Some(existing),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => {
                return Err(e).with_context(|| format!("reading {}", hook_path.display()))
            }
        };
        let needs_write = match &existing {
            None => true,
            Some(existing) if existing == hook_content => false,
            Some(existing) if is_wsb_hook(existing) => true,
            Some(existing) => {
                if let Some(problem) = pre_commit_hook_problem(existing) {
                    wsb::errln!(
                        "  {} left the pre-commit hook at {} as it is: it {}",
                        "!".yellow(),
                        hook_path.display(),
                        problem
                    );
                }
                false
            }
        };
        if needs_write {
            std::fs::write(&hook_path, hook_content)?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mut perms = std::fs::metadata(&hook_path)?.permissions();
                perms.set_mode(0o755);
                std::fs::set_permissions(&hook_path, perms)?;
            }
            wsb::outln!(
                "  {} installed pre-commit hook: {}",
                "✓".green(),
                hook_path.display()
            );
        }
    }
    Ok(())
}

/// The alias a new repository's templates are known by, and the folder its
/// templates look for other repositories under, relative to it.
fn default_alias_and_root(project_root: &Path) -> Result<(String, String)> {
    if let Some((_immediate, submodule_name)) = find_parent_repo_submodule(project_root)? {
        // The root is the OUTERMOST superproject, not the immediate one. It is
        // where peers are looked for, and templates reference peers across
        // superrepos constantly — a cartridge's manifest names both
        // `capdag_rs` (under `capdag/`) and `capdag_cartridge_sdk_rs` (under
        // `cartridge-sdks/`). With the immediate parent as the root, a nested
        // repository could see only its own siblings, and 33 references in
        // one tree resolved to nothing.
        let outermost = outermost_superproject(project_root)?
            .expect("a project with a parent repository has an outermost one");
        // The alias is the name the parent records, which
        // `find_parent_repo_submodule` has already checked against the
        // directory it sits in. Through `derive_alias`, not verbatim: an alias
        // is a template IDENTIFIER, so `capdag-cartridge-sdk` is
        // `capdag_cartridge_sdk` — a hyphenated alias parses as subtraction,
        // and is a repository no template can name.
        return Ok((
            WstemplateEngine::derive_alias(Path::new(&submodule_name)),
            wsb_prj::settings::relative_path(&outermost, project_root)?,
        ));
    }
    Ok((
        WstemplateEngine::derive_alias(Path::new(&wsb_prj::repository_name(project_root)?)),
        ".".to_string(),
    ))
}

/// The furthest repository up that contains `project_root` as a submodule,
/// transitively.
///
/// Walked step by step, and each step must list the previous one as a
/// submodule of its own. That is what keeps it inside the worktree: a plain
/// "walk up while something looks like a repository" would climb out into
/// whatever unrelated repository happened to be above it — a checkout inside
/// somebody's home directory that is itself under version control, say — and
/// scan that instead.
fn outermost_superproject(project_root: &Path) -> Result<Option<PathBuf>> {
    let mut here = project_root.to_path_buf();
    let mut outermost = None;
    while let Some((parent, _)) = find_parent_repo_submodule(&here)? {
        outermost = Some(parent.clone());
        here = parent;
    }
    Ok(outermost)
}

fn find_parent_repo_submodule(project_root: &Path) -> Result<Option<(PathBuf, String)>> {
    let mut parent = project_root.parent();
    while let Some(candidate) = parent {
        let gitmodules = match GitModules::parse(candidate) {
            Ok(gitmodules) => gitmodules,
            Err(SuperGitError::NoSubmodules) => {
                parent = candidate.parent();
                continue;
            }
            Err(error) => {
                return Err(anyhow::anyhow!(
                    "Failed to parse parent .gitmodules at {}: {}",
                    candidate.display(),
                    error
                ));
            }
        };

        let relative_path = project_root.strip_prefix(candidate).with_context(|| {
            format!(
                "Failed to compute submodule path for {} inside {}",
                project_root.display(),
                candidate.display()
            )
        })?;

        if let Some(submodule) = gitmodules
            .submodules
            .into_iter()
            .find(|submodule| submodule.path == relative_path)
        {
            // The recorded name and the directory it sits in must be the same
            // thing. Git does not require it, and the alias is derived from
            // the name — so where they disagree, a project's alias is one no
            // reader of the tree could guess, and a template naming the
            // obvious one fails with "alias cannot be resolved" pointing at a
            // directory that is plainly there.
            //
            // Refused rather than reconciled: which of the two is wrong is a
            // question about the repository, and picking one here would bury
            // it.
            let directory = relative_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or_default();
            if submodule.name != directory {
                return Err(anyhow::anyhow!(
                    "submodule at {} is recorded in {} as '{}' but its directory is '{}'.\n\
                     The alias a template names is derived from that name, so the two have to \
                     agree — fix the name in .gitmodules or move the directory.",
                    relative_path.display(),
                    candidate.join(".gitmodules").display(),
                    submodule.name,
                    directory
                ));
            }
            return Ok(Some((candidate.to_path_buf(), submodule.name)));
        }

        parent = candidate.parent();
    }

    Ok(None)
}

fn print_repo_setup_complete(settings: &RepoSettings, repo_root: &Path) {
    wsb::outln!(
        "{}",
        format!("wsb manages '{}' at {}", settings.name, repo_root.display()).bold().green()
    );
}

fn is_git_checkout(path: &Path) -> bool {
    let git_path = path.join(".git");
    git_path.is_dir() || git_path.is_file()
}

fn repo_git_dir(project_root: &Path) -> Result<PathBuf> {
    let git_path = project_root.join(".git");
    if git_path.is_dir() {
        return Ok(git_path);
    }
    if git_path.is_file() {
        let content = std::fs::read_to_string(&git_path)
            .with_context(|| format!("Failed to read {}", git_path.display()))?;
        let git_dir = content
            .trim()
            .strip_prefix("gitdir:")
            .map(str::trim)
            .ok_or_else(|| anyhow::anyhow!("Invalid gitdir file at {}", git_path.display()))?;
        let git_dir = PathBuf::from(git_dir);
        return Ok(if git_dir.is_absolute() {
            git_dir
        } else {
            project_root.join(git_dir)
        });
    }

    anyhow::bail!(
        "No .git directory or gitdir file at {}",
        project_root.display()
    )
}

fn init_nested_repos(project_root: &Path) -> Result<()> {
    let outcome = SubmoduleOps::init_tree(project_root, true, |node| {
        wsb::outln!(
            "{}",
            format!("Initializing git submodule '{}'", node.label())
                .bold()
                .green()
        );
    })
    .map_err(|error| {
        anyhow::anyhow!(
            "Failed to walk submodules at {}: {}",
            project_root.display(),
            error
        )
    })?;

    if let Some((name, error)) = outcome.failures.into_iter().next() {
        anyhow::bail!("Failed to initialize submodule '{}': {}", name, error);
    }

    let tree = SubmoduleTree::discover_allow_empty(project_root).map_err(|error| {
        anyhow::anyhow!(
            "Failed to read submodules at {}: {}",
            project_root.display(),
            error
        )
    })?;

    // Parents before children, so a nested repository is set up inside a
    // parent that already is.
    for node in tree.top_down() {
        // init_tree above either checked this out or reported it as a failure,
        // so anything still uninitialized here means the tree changed underneath us.
        if !node.initialized {
            anyhow::bail!(
                "Submodule '{}' is still not checked out after initialization at {}",
                node.label(),
                node.abs_path.display()
            );
        }

        if !node.abs_path.is_dir() {
            anyhow::bail!(
                "Submodule '{}' path is not a directory: {}",
                node.label(),
                node.abs_path.display()
            );
        }

        if !is_git_checkout(&node.abs_path) {
            anyhow::bail!(
                "Submodule '{}' at {} is not a usable git repository",
                node.label(),
                node.abs_path.display()
            );
        }

        let settings = setup_repo_at(&node.abs_path, None)?;
        print_repo_setup_complete(&settings, &node.abs_path);
    }

    Ok(())
}

fn read_script_from_stdin() -> Result<String> {
    use std::io::Read;
    let mut script = String::new();
    std::io::stdin()
        .read_to_string(&mut script)
        .context("Failed to read script from stdin")?;
    Ok(script)
}

fn read_script_interactively() -> Result<String> {
    use std::io::Read;
    wsb::errln!("Enter shell script (Ctrl-D when done):");
    let mut script = String::new();
    std::io::stdin()
        .read_to_string(&mut script)
        .context("Failed to read script interactively")?;
    Ok(script)
}

fn run_each_command(
    project_root: &Path,
    file: Option<std::path::PathBuf>,
    quiet: bool,
) -> Result<()> {
    use colored::Colorize;
    use wsb::fleet::config::gitmodules::GitModules;

    let script: String = match file {
        Some(ref path) => std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read script file: {}", path.display()))?,
        None => {
            use std::io::IsTerminal;
            if std::io::stdin().is_terminal() {
                read_script_interactively()?
            } else {
                read_script_from_stdin()?
            }
        }
    };

    let script = script.trim();
    if script.is_empty() {
        anyhow::bail!("Script is empty — nothing to run");
    }

    let modules = match GitModules::parse(project_root) {
        Ok(m) => m,
        Err(wsb::fleet::error::SuperGitError::NoSubmodules) => {
            anyhow::bail!(
                "No submodules found in {} — 'wsb each' requires a fleet root with .gitmodules",
                project_root.display()
            );
        }
        Err(e) => return Err(anyhow::anyhow!(".gitmodules parse error: {:#}", e)),
    };

    let total = modules.submodules.len() as u64;
    let pb = make_progress_bar(quiet, total);

    for sub in &modules.submodules {
        let sub_path = project_root.join(&sub.path);
        if !sub_path.is_dir() {
            pb.finish_and_clear();
            anyhow::bail!(
                "Submodule '{}': path '{}' does not exist — run 'git submodule update --init'",
                sub.name,
                sub.path.display()
            );
        }

        pb.set_message(sub.name.clone());

        let status = wsb::git_backend::command_without_repo_scope("sh")
            .arg("-c")
            .arg(script)
            .current_dir(&sub_path)
            .env("WSB_SUBMODULE_PATH", &sub_path)
            .env("WSB_SUBMODULE_NAME", &sub.name)
            .env("WSB_SUPERPROJECT_ROOT", project_root)
            .status()
            .with_context(|| format!("Failed to launch sh for submodule '{}'", sub.name))?;

        if !status.success() {
            pb.finish_and_clear();
            let code = status
                .code()
                .map(|c| c.to_string())
                .unwrap_or_else(|| "signal".to_string());
            anyhow::bail!("Script failed in submodule '{}' (exit {})", sub.name, code);
        }

        pb.inc(1);
    }

    pb.finish_and_clear();
    if !quiet {
        wsb::outln!(
            "{} ran in {}/{} submodule(s)",
            "✓".green().bold(),
            total,
            total
        );
    }
    Ok(())
}

fn run_check_command(cwd: &Path, no_network: bool, quiet: bool) -> Result<()> {
    use colored::Colorize;
    use wsb::fleet::config::gitmodules::GitModules;

    // Each issue carries a category tag for grouped output.
    #[derive(Clone)]
    struct CheckItem {
        category: &'static str,
        text: String,
    }

    let mut issues: Vec<CheckItem> = Vec::new();
    let mut warnings: Vec<CheckItem> = Vec::new();
    let mut ok_items: Vec<String> = Vec::new();

    let pb = make_spinner(quiet, "checking worktree…");

    macro_rules! ok {
        ($msg:expr) => {{
            ok_items.push(format!("  {} {}", "✓".green(), $msg))
        }};
    }
    macro_rules! issue {
        ($cat:literal, $msg:expr) => {{
            issues.push(CheckItem {
                category: $cat,
                text: format!("  {} {}", "✗".red().bold(), $msg),
            })
        }};
        ($msg:expr) => {{
            issues.push(CheckItem {
                category: "General",
                text: format!("  {} {}", "✗".red().bold(), $msg),
            })
        }};
    }
    macro_rules! warn_item {
        ($cat:literal, $msg:expr) => {{
            warnings.push(CheckItem {
                category: $cat,
                text: format!("  {} {}", "⚠".yellow(), $msg),
            })
        }};
        ($msg:expr) => {{
            warnings.push(CheckItem {
                category: "General",
                text: format!("  {} {}", "⚠".yellow(), $msg),
            })
        }};
    }

    pb.set_message("resolving the repository and its worktree…");

    // ── 1. The repository wsb manages here, and its worktree ──────────────
    let project_root = match wsb::roots::find_repo_root(cwd) {
        Some(root) => {
            ok!(format!("repository: {}", root.display()));
            root
        }
        None => {
            issue!(
                "Repository",
                format!(
                    "no .wsb/repo.json at or above {} — run 'wsb init' in the repository",
                    cwd.display()
                )
            );
            pb.finish_and_clear();
            wsb::outln!();
            for i in &issues {
                wsb::outln!("{}", i.text);
            }
            std::process::exit(wsb::output::finish(1));
        }
    };
    let super_root = wsb::roots::find_super_root(cwd);
    match &super_root {
        Some(root) if root == &project_root => ok!("worktree root: the repository itself (no submodule nesting)"),
        Some(root) if RepoSettings::exists(root) => ok!(format!("worktree root: {}", root.display())),
        Some(root) => issue!(
            "Repository",
            format!(
                "the outermost repository {} has no .wsb/repo.json, so this is no worktree wsb manages — run 'wsb init' there",
                root.display()
            )
        ),
        None => issue!("Repository", "not inside any git repository"),
    }
    let worktree_root = super_root.clone().unwrap_or_else(|| project_root.clone());

    // ── 2. The committed settings ───────────────────────────────────────────
    let settings = match RepoSettings::load(&project_root) {
        Ok(Some(settings)) => {
            ok!(format!(
                ".wsb/repo.json: '{}', alias '{}', major {}, version file {}",
                settings.name, settings.alias, settings.version.major, settings.version.file
            ));
            let scan_root = settings.templates_root_of(&project_root);
            if scan_root.is_dir() {
                ok!(format!("templates root: {} ({})", settings.templates_root, scan_root.display()));
            } else {
                issue!("Settings", format!("the templates root {} does not exist", scan_root.display()));
            }
            Some(settings)
        }
        Ok(None) => None,
        Err(e) => {
            issue!("Settings", format!("{e:#}"));
            None
        }
    };
    match ProjectSettings::load(&worktree_root) {
        Ok(project) => ok!(format!(
            ".wsb/project.json at the worktree root: {} board(s), {} ignored submodule(s)",
            project.boards.len(),
            project.ignored_submodules.len()
        )),
        Err(e) => issue!("Settings", format!("{e:#}")),
    }
    if let Err(e) = refuse_hidden_settings(&project_root) {
        issue!("Git", format!("{e:#}"));
    } else {
        ok!(".wsb/ is visible to git, so every clone has it");
    }

    // ── 3. What an older wsb left in the checkout ───────────────────────────
    let leftovers = wsb::migrate::leftovers_in(&project_root)?;
    if leftovers.is_empty() {
        ok!("nothing of an older wsb's layout is left in the checkout");
    } else {
        for leftover in &leftovers {
            issue!("Migrate", format!("{leftover} — run 'wsb migrate'"));
        }
    }

    // ── 4. The version file ────────────────────────────────────────────────
    if let Some(settings) = &settings {
        let version_path = project_root.join(&settings.version.file);
        match std::fs::read_to_string(&version_path) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => warn_item!(
                "Version",
                format!("{} is not there yet; the next 'wsb update' writes it", version_path.display())
            ),
            Err(e) => issue!("Version", format!("{} is unreadable: {e}", version_path.display())),
            Ok(content) => match wsb::state::parse_version_string(content.trim()) {
                Ok(declared) if declared.major_version.trim_start_matches('v') == settings.version.major.to_string() => {
                    ok!(format!("{} declares {}", settings.version.file, declared.full_version))
                }
                Ok(declared) => warn_item!(
                    "Version",
                    format!(
                        "{} declares {} while .wsb/repo.json commits major {}; the next 'wsb update' rewrites it",
                        settings.version.file, declared.full_version, settings.version.major
                    )
                ),
                Err(e) => issue!("Version", format!("{} does not hold a version: {e:#}", version_path.display())),
            },
        }
    }

    // ── 5. The worktree's local state ───────────────────────────────────────
    match wsb::local_state::LocalState::of(&worktree_root) {
        Ok(state) => {
            ok!(format!("local state: {}", state.dir().display()));
            // Disposable directories are out of the machine's backups: a sticky
            // exclusion goes with its folder, so one made again since is
            // reported here.
            let build_root = wsb::state::stamp_config::StampConfig::load(&worktree_root)
                .ok()
                .flatten()
                .and_then(|config| config.build_root)
                .map(|relative| worktree_root.join(relative));
            let disposable = [Some(state.logs()), build_root];
            for path in disposable.into_iter().flatten().filter(|path| path.is_dir()) {
                match wsb::platform::excluded_from_backups(&path) {
                    Ok(true) => {}
                    Ok(false) => warn_item!("Backups", format!(
                        "{} is disposable and backed up — `tmutil addexclusion {}`",
                        path.display(),
                        path.display()
                    )),
                    Err(error) => warn_item!("Backups", error),
                }
            }
        }
        Err(e) => issue!("Local state", format!("{e:#}")),
    }

    // ── 7a. declared local paths ───────────────────────────────────────────
    //
    // Every manifest that depends on a sibling BY PATH is making a claim about
    // where it sits in a tree, and the claim is a count of `..`. When a
    // repository moves the count is silently wrong: the manifest still parses,
    // and the failure arrives later, somewhere else, as a build that cannot
    // resolve a dependency or a package manager chasing a link into nothing.
    pb.set_message("checking declared local paths…");
    let broken_paths = wsb::local_paths::check(&project_root);
    if broken_paths.is_empty() {
        ok!("every declared local path resolves (cargo, swift, npm, lockfiles)");
    } else {
        for broken in &broken_paths {
            issue!(
                "Paths",
                format!(
                    "{}: {} '{}' points at {}, which does not exist",
                    broken.manifest, broken.kind, broken.declared, broken.resolves_to
                )
            );
        }
    }

    // ── 7a-i. absolute paths into a home directory ─────────────────────────
    //
    // A relative path can be wrong after a move. An absolute one under
    // somebody's home is wrong for everybody except them, committed.
    pb.set_message("checking for committed home paths…");
    let home_paths = wsb::local_paths::home_rooted(&project_root);
    if home_paths.is_empty() {
        ok!("no committed file names a path inside somebody's home directory");
    } else {
        for found in &home_paths {
            issue!(
                "Paths",
                format!(
                    "{}:{} names {}, which is one machine's layout — make it relative to the project",
                    found.manifest, found.line, found.path
                )
            );
        }
    }

    // ── 7a-ii. source git does not have ────────────────────────────────────
    //
    // The other way a tree fails to contain what the build reads: an ignore
    // pattern for output that also matches a source directory. Nothing about
    // it looks wrong locally — the files are there and they compile — and the
    // failure is somebody else's, on their first pull.
    pb.set_message("checking for source hidden from git…");
    let hidden = wsb::local_paths::hidden_source(&project_root);
    if hidden.is_empty() {
        ok!("no source file is hidden from git by an ignore rule");
    } else {
        for file in &hidden {
            issue!(
                "Paths",
                format!(
                    "{} is a source file git is ignoring ({}) — anchor the pattern with a leading slash",
                    file.path, file.rule
                )
            );
        }
    }

    // ── 7b. pre-commit hook ────────────────────────────────────────────────
    pb.set_message("checking pre-commit hook…");
    let hook_path = project_root.join(".git").join("hooks").join("pre-commit");
    if !hook_path.exists() {
        issue!("Git", format!(
            "pre-commit hook missing at {} — run 'wsb init' to install it (runs 'wsb update --quiet --git-add' on every commit)",
            hook_path.display()
        ));
    } else {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::metadata(&hook_path)?.permissions();
            if perms.mode() & 0o111 == 0 {
                issue!(
                    "Git",
                    format!(
                        "pre-commit hook at {} is not executable — run: chmod +x {}",
                        hook_path.display(),
                        hook_path.display()
                    )
                );
            } else {
                ok!(format!(
                    "pre-commit hook is executable: {}",
                    hook_path.display()
                ));
            }
        }
        match std::fs::read_to_string(&hook_path) {
            Err(e) => issue!("Git", format!("pre-commit hook unreadable: {}", e)),
            Ok(hook_content) => match pre_commit_hook_problem(&hook_content) {
                Some(problem) => issue!(
                    "Git",
                    format!("pre-commit hook at {} {problem}", hook_path.display())
                ),
                None => {
                    ok!("pre-commit hook invokes '{PRE_COMMIT_MARK}' with the driving wsb")
                }
            },
        }
    }

    // ── 8. Fleet: .gitmodules validation and submodule checks ──────────────
    let gitmodules_path = project_root.join(".gitmodules");
    let is_fleet_root = gitmodules_path.is_file();

    if !is_fleet_root {
        ok!("no .gitmodules — single-repo worktree (not a fleet root)");
    } else {
        ok!(format!(
            ".gitmodules found at {}",
            gitmodules_path.display()
        ));

        match GitModules::parse(&project_root) {
            Err(e) => {
                issue!("Fleet", format!(".gitmodules parse error: {:#}", e));
            }
            Ok(modules) => {
                ok!(format!(
                    "{} submodule(s) declared in .gitmodules",
                    modules.submodules.len()
                ));

                // Read `git submodule status` once for commit-pointer checks
                let submodule_status_output = wsb::git_backend::git_command()
                    .args(["submodule", "status"])
                    .current_dir(&project_root)
                    .output()
                    .ok();

                let mut all_aliases: Vec<(String, String)> = Vec::new();

                // The super root's own alias.
                if let Some(settings) = &settings {
                    all_aliases.push((settings.alias.clone(), project_root.display().to_string()));
                }

                for sub in &modules.submodules {
                    let sub_path = project_root.join(&sub.path);
                    let display = sub.path.display().to_string();

                    // ── 8a. URL reachability ───────────────────────────────
                    if no_network {
                        warn_item!(
                            "Fleet",
                            format!(
                            "submodule '{}': skipping remote URL check (--no-network) — url: {}",
                            sub.name, sub.url
                        )
                        );
                    } else {
                        let ls_remote = wsb::git_backend::git_command()
                            .args(["ls-remote", "--exit-code", "--heads", &sub.url])
                            .stdout(std::process::Stdio::null())
                            .stderr(std::process::Stdio::piped())
                            .output();
                        match ls_remote {
                            Ok(out) if out.status.success() => {
                                ok!(format!(
                                    "submodule '{}': remote url reachable — {}",
                                    sub.name, sub.url
                                ));
                            }
                            Ok(out) => {
                                let stderr = String::from_utf8_lossy(&out.stderr);
                                issue!(
                                    "Fleet",
                                    format!(
                                        "submodule '{}': remote url unreachable — {} ({})",
                                        sub.name,
                                        sub.url,
                                        stderr.trim()
                                    )
                                );
                            }
                            Err(e) => {
                                issue!("Fleet", format!(
                                    "submodule '{}': could not run 'git ls-remote' to check url {}: {}",
                                    sub.name, sub.url, e
                                ));
                            }
                        }
                    }

                    // ── 8b. Path exists on disk ────────────────────────────
                    if !sub_path.is_dir() {
                        issue!("Fleet", format!(
                            "submodule '{}': path '{}' does not exist on disk — run 'git submodule update --init'",
                            sub.name, display
                        ));
                        continue;
                    }
                    ok!(format!(
                        "submodule '{}': path exists at {}",
                        sub.name,
                        sub_path.display()
                    ));

                    // ── 8c. .git entry (initialized) ──────────────────────
                    let sub_git = sub_path.join(".git");
                    if !sub_git.exists() {
                        issue!("Fleet", format!(
                            "submodule '{}': no .git entry — submodule not initialized (run 'git submodule update --init')",
                            sub.name
                        ));
                    } else {
                        ok!(format!(
                            "submodule '{}': .git entry present (initialized)",
                            sub.name
                        ));
                    }

                    // ── 8d. Declared branch exists in the remote ───────────
                    if let Some(ref branch) = sub.branch {
                        if branch == "." {
                            ok!(format!(
                                "submodule '{}': branch tracks superproject HEAD (branch = .)",
                                sub.name
                            ));
                        } else if no_network {
                            warn_item!("Fleet", format!(
                                "submodule '{}': skipping branch '{}' existence check (--no-network)",
                                sub.name, branch
                            ));
                        } else {
                            // Check if the branch ref is known locally (after fetch) via git ls-remote
                            let branch_check = wsb::git_backend::git_command()
                                .args(["ls-remote", "--exit-code", "--heads", &sub.url, branch])
                                .stdout(std::process::Stdio::null())
                                .stderr(std::process::Stdio::piped())
                                .output();
                            match branch_check {
                                Ok(out) if out.status.success() => {
                                    ok!(format!(
                                        "submodule '{}': declared branch '{}' exists on remote",
                                        sub.name, branch
                                    ));
                                }
                                Ok(_) => {
                                    issue!("Fleet", format!(
                                        "submodule '{}': declared branch '{}' does not exist on remote {}",
                                        sub.name, branch, sub.url
                                    ));
                                }
                                Err(e) => {
                                    issue!(
                                        "Fleet",
                                        format!(
                                        "submodule '{}': could not check branch '{}' on remote: {}",
                                        sub.name, branch, e
                                    )
                                    );
                                }
                            }
                        }
                    } else {
                        warn_item!("Fleet", format!(
                            "submodule '{}': no branch declared in .gitmodules — submodule will track a detached commit",
                            sub.name
                        ));
                    }

                    // ── 8e. Commit pointer (git submodule status) ──────────
                    // `git submodule status` output prefix: ' ' = ok, '-' = not init, '+' = dirty, 'U' = conflict
                    if let Some(ref status_out) = submodule_status_output {
                        if status_out.status.success() {
                            let status_text = String::from_utf8_lossy(&status_out.stdout);
                            let sub_path_str = sub.path.to_string_lossy();
                            let line = status_text.lines().find(|l| {
                                l.trim_start_matches(['-', '+', 'U', ' '])
                                    .contains(sub_path_str.as_ref())
                            });
                            match line {
                                None => {
                                    issue!("Fleet", format!(
                                        "submodule '{}': not found in 'git submodule status' output — may not be registered in git index",
                                        sub.name
                                    ));
                                }
                                Some(l) => {
                                    let prefix = l.chars().next().unwrap_or(' ');
                                    match prefix {
                                        '-' => issue!("Fleet", format!(
                                            "submodule '{}': not initialized (git submodule status shows '-') — run 'git submodule update --init'",
                                            sub.name
                                        )),
                                        '+' => issue!("Fleet", format!(
                                            "submodule '{}': checked out commit differs from superproject pointer (git submodule status shows '+') — run 'git submodule update'",
                                            sub.name
                                        )),
                                        'U' => issue!("Fleet", format!(
                                            "submodule '{}': merge conflict in submodule (git submodule status shows 'U')",
                                            sub.name
                                        )),
                                        _ => ok!(format!(
                                            "submodule '{}': commit pointer matches superproject (clean)",
                                            sub.name
                                        )),
                                    }
                                }
                            }
                        } else {
                            let stderr = String::from_utf8_lossy(&status_out.stderr);
                            warn_item!(
                                "Fleet",
                                format!("could not run 'git submodule status': {}", stderr.trim())
                            );
                        }
                    }

                    // ── 8f. the submodule's committed settings ───────────
                    match RepoSettings::load(&sub_path) {
                        Ok(None) => issue!(
                            "Settings",
                            format!(
                                "submodule '{}': no .wsb/repo.json — run 'wsb init' inside {}",
                                sub.name,
                                sub_path.display()
                            )
                        ),
                        Err(e) => issue!("Settings", format!("submodule '{}': {e:#}", sub.name)),
                        Ok(Some(sub_settings)) => {
                            ok!(format!(
                                "submodule '{}': .wsb/repo.json — '{}', alias '{}', major {}",
                                sub.name, sub_settings.name, sub_settings.alias, sub_settings.version.major
                            ));
                            // ── 8g. its version file ─────────────────────
                            let version_path = sub_path.join(&sub_settings.version.file);
                            if !version_path.exists() {
                                warn_item!(
                                    "Version",
                                    format!(
                                        "submodule '{}': {} is not there yet; the next 'wsb update' writes it",
                                        sub.name, sub_settings.version.file
                                    )
                                );
                            }
                            all_aliases.push((sub_settings.alias, sub_path.display().to_string()));
                        }
                    }
                    match wsb::migrate::leftovers_in(&sub_path) {
                        Ok(leftovers) => {
                            for leftover in leftovers {
                                issue!("Migrate", format!("submodule '{}': {leftover} — run 'wsb migrate'", sub.name));
                            }
                        }
                        Err(e) => issue!("Migrate", format!("submodule '{}': {e:#}", sub.name)),
                    }
                    if let Err(e) = refuse_hidden_settings(&sub_path) {
                        issue!("Git", format!("submodule '{}': {e:#}", sub.name));
                    }

                    // Where THIS submodule's git lives.
                    //
                    // A submodule's `.git` is a file saying `gitdir: …`, and
                    // everything below is inside the directory it names —
                    // `<super>/.git/modules/<name>`. Joined onto `.git` as
                    // though it were a directory, both checks below looked at
                    // paths that cannot exist in any correct checkout, so
                    // `wsb check` reported every submodule in this fleet as
                    // missing its exclude and its hook while both were there.
                    // A standing false failure is worse than none: it teaches
                    // people to skip reading the report.
                    let sub_git_dir = repo_git_dir(&sub_path)
                        .unwrap_or_else(|_| sub_path.join(".git"));
                    // ── 8i. submodule pre-commit hook ──────────────────────
                    let sub_hook = sub_git_dir.join("hooks").join("pre-commit");
                    if !sub_hook.exists() {
                        issue!("Git", format!(
                            "submodule '{}': pre-commit hook missing — run 'wsb init' inside {} to install it",
                            sub.name, sub_path.display()
                        ));
                    } else {
                        #[cfg(unix)]
                        {
                            use std::os::unix::fs::PermissionsExt;
                            if let Ok(meta) = std::fs::metadata(&sub_hook) {
                                if meta.permissions().mode() & 0o111 == 0 {
                                    issue!(
                                        "Git",
                                        format!(
                                            "submodule '{}': pre-commit hook is not executable",
                                            sub.name
                                        )
                                    );
                                }
                            }
                        }
                        match std::fs::read_to_string(&sub_hook) {
                            Err(e) => issue!(
                                "Git",
                                format!(
                                    "submodule '{}': pre-commit hook unreadable: {}",
                                    sub.name, e
                                )
                            ),
                            Ok(content) => {
                                // Through the one definition of what the hook
                                // IS. This said `wsb update` in its own words,
                                // so the moment the hook learned to prefer the
                                // wsb driving the commit — `"${WSB_SELF:-wsb}"
                                // update` — every submodule in the fleet was
                                // reported as having the wrong hook.
                                if let Some(problem) = pre_commit_hook_problem(&content) {
                                    issue!("Git", format!(
                                        "submodule '{}': pre-commit hook {problem}",
                                        sub.name
                                    ));
                                } else {
                                    ok!(format!(
                                        "submodule '{}': pre-commit hook correct",
                                        sub.name
                                    ));
                                }
                            }
                        }
                    }
                }

                // ── 8j. Alias uniqueness across all repo.json files ────────
                let mut seen_aliases: std::collections::HashMap<String, Vec<String>> =
                    std::collections::HashMap::new();
                for (alias, source) in &all_aliases {
                    seen_aliases
                        .entry(alias.clone())
                        .or_default()
                        .push(source.clone());
                }
                for (alias, sources) in &seen_aliases {
                    if sources.len() > 1 {
                        issue!(
                            "Fleet",
                            format!(
                                "duplicate wstemplate alias '{}' in {} projects: {}",
                                alias,
                                sources.len(),
                                sources.join(", ")
                            )
                        );
                    } else {
                        ok!(format!("wstemplate alias '{}' is unique", alias));
                    }
                }
            }
        }
    }

    // ── Summary ────────────────────────────────────────────────────────────
    pb.finish_and_clear();

    if !quiet {
        wsb::outln!();
        for item in &ok_items {
            wsb::outln!("{}", item);
        }
    }

    // Group warnings by category
    if !warnings.is_empty() {
        let mut by_cat: std::collections::BTreeMap<&str, Vec<&str>> =
            std::collections::BTreeMap::new();
        for w in &warnings {
            by_cat.entry(w.category).or_default().push(&w.text);
        }
        wsb::outln!();
        wsb::outln!("{} {} warning(s):", "⚠".yellow(), warnings.len());
        for (cat, items) in &by_cat {
            wsb::outln!("  [{}]", cat.yellow());
            for item in items {
                wsb::outln!("{}", item);
            }
        }
    }

    if !issues.is_empty() {
        // Group issues by category
        let mut by_cat: std::collections::BTreeMap<&str, Vec<&str>> =
            std::collections::BTreeMap::new();
        for iss in &issues {
            by_cat.entry(iss.category).or_default().push(&iss.text);
        }
        wsb::outln!();
        wsb::outln!("{} {} issue(s) found:", "✗".red().bold(), issues.len());
        for (cat, items) in &by_cat {
            wsb::outln!("  [{}]", cat.red().bold());
            for item in items {
                wsb::outln!("{}", item);
            }
        }
        wsb::outln!();
        std::process::exit(wsb::output::finish(1));
    } else {
        wsb::outln!();
        wsb::outln!("{}", "All checks passed.".green().bold());
    }

    Ok(())
}

fn add_files_to_git(files: &[String], project_root: &Path) -> Result<Vec<String>> {
    let repo = wsb::git_backend::discover_repo(project_root)?;
    let repo_root = repo
        .workdir()
        .context("Bare repositories are not supported for staging")?;
    let mut files_to_stage = Vec::new();

    for file in files {
        let file_path = std::path::Path::new(file);
        // Resolve to absolute so we can always strip the repo root.
        let absolute = if file_path.is_absolute() {
            file_path.to_path_buf()
        } else {
            project_root.join(file_path)
        };
        if !absolute.exists() {
            continue;
        }
        let relative_path = match absolute.strip_prefix(repo_root) {
            Ok(rel) => rel.to_string_lossy().to_string(),
            Err(_) => continue,
        };

        // A file inside a submodule belongs to that submodule's index, never to
        // this one. Rendering reaches into submodules on purpose — a template
        // there that references this project's alias must be re-rendered when
        // this version changes — but staging must not follow it: `git add` on a
        // path inside a submodule is a hard error, and it would abort the whole
        // update over a file this repo could not have committed anyway.
        if let Some(submodule) = wsb::git_backend::submodule_containing(&repo, &relative_path)? {
            debug!(
                "not staging '{}': it lives in submodule '{}', which owns its own index",
                relative_path, submodule
            );
            continue;
        }

        files_to_stage.push(relative_path);
    }

    let added_files = wsb::git_backend::stage_paths(&repo, &files_to_stage)?;
    for file in &added_files {
        log_action(&format!("Added file to git: {}", file));
    }

    Ok(added_files)
}
/// Write the completion script for `shell` and say how to load it.
///
/// Reached only from `wsb completions`. This used to run on every invocation,
/// which meant that merely asking wsb a question wrote three files into the
/// user's home — and wsb's own uninstall suite proves that a dry run leaves the
/// machine untouched, so the tool was failing the rule it enforces.
fn install_shell_completions(shell: Option<Shell>) -> Result<()> {
    let shell = match shell {
        Some(shell) => shell,
        None => detect_shell()?,
    };

    generate_completion_file(shell)?;

    let completion_dir = get_completion_dir(shell)?;
    let completion_file = get_completion_file_path(shell, &completion_dir)?;
    print_activation_hint(shell, &completion_file);

    Ok(())
}

fn detect_shell() -> Result<Shell> {
    // Try to detect from SHELL environment variable first
    if let Ok(shell) = env::var("SHELL") {
        if shell.contains("bash") {
            return Ok(Shell::Bash);
        } else if shell.contains("zsh") {
            return Ok(Shell::Zsh);
        } else if shell.contains("fish") {
            return Ok(Shell::Fish);
        }
    }

    // Check for shell-specific environment variables
    if env::var("ZSH_VERSION").is_ok() {
        return Ok(Shell::Zsh);
    } else if env::var("BASH_VERSION").is_ok() {
        return Ok(Shell::Bash);
    } else if env::var("FISH_VERSION").is_ok() {
        return Ok(Shell::Fish);
    }

    // Default to bash if we can't detect
    Ok(Shell::Bash)
}

/// Generate the shell completion script file (silently, no hints).
fn generate_completion_file(shell: Shell) -> Result<()> {
    let mut completion_script = Vec::new();
    {
        let mut app = Args::command();
        let name = app.get_name().to_string();
        generate(shell, &mut app, name, &mut completion_script);
    }

    let completion_content = String::from_utf8(completion_script)
        .context("Failed to convert completion script to string")?;

    let completion_dir = get_completion_dir(shell)?;
    fs::create_dir_all(&completion_dir).context("Failed to create completion directory")?;

    let completion_file = get_completion_file_path(shell, &completion_dir)?;
    fs::write(&completion_file, &completion_content)
        .context("Failed to write completion script")?;

    Ok(())
}

fn get_completion_dir(shell: Shell) -> Result<PathBuf> {
    // Check XDG_DATA_HOME first, fallback to ~/.local/share
    let data_home = env::var("XDG_DATA_HOME").unwrap_or_else(|_| {
        let home = env::var("HOME").unwrap_or_default();
        format!("{}/.local/share", home)
    });

    let dir = match shell {
        Shell::Zsh => format!("{}/zsh/site-functions", data_home),
        Shell::Bash => format!("{}/bash-completion/completions", data_home),
        Shell::Fish => {
            // Fish uses .local/share for completions like other shells
            format!("{}/fish/completions", data_home)
        }
        Shell::PowerShell => format!("{}/powershell/completions", data_home),
        _ => format!("{}/completions", data_home),
    };

    Ok(PathBuf::from(dir))
}

fn get_completion_file_path(shell: Shell, completion_dir: &std::path::Path) -> Result<PathBuf> {
    let file_name = match shell {
        // zsh loads `_<command>`; this said `_ws`, left over from when the
        // binary was called `ws`, so zsh never completed `wsb` at all.
        Shell::Zsh => "_wsb",
        Shell::Bash => "wsb",
        Shell::Fish => "wsb.fish",
        Shell::PowerShell => "wsb.ps1",
        _ => "wsb",
    };

    Ok(completion_dir.join(file_name))
}

/// Say how to load the completion script that was just written.
fn print_activation_hint(shell: Shell, file_path: &std::path::Path) {
    match shell {
        Shell::Bash => {
            wsb::errln!("# To enable wsb completions, add this to your ~/.bashrc:");
            wsb::errln!("source '{}'", file_path.to_string_lossy());
        }
        Shell::Zsh => {
            let completion_parent = file_path.parent().unwrap_or(std::path::Path::new(""));
            wsb::errln!("# To enable wsb completions, add these lines to your ~/.zshrc:");
            wsb::errln!("fpath=(\"{}\" $fpath)", completion_parent.to_string_lossy());
            wsb::errln!("autoload -U compinit && compinit");
        }
        Shell::Fish => {
            wsb::errln!(
                "# wsb completions installed to: {}",
                file_path.to_string_lossy()
            );
        }
        Shell::PowerShell => {
            wsb::errln!("# To enable wsb completions, add this to your PowerShell profile:");
            wsb::errln!(". '{}'", file_path.to_string_lossy());
        }
        _ => {
            wsb::errln!("# Completion script at: {}", file_path.to_string_lossy());
        }
    }
}

/// `wsb catalog …` — the worktree's tests, as a set that can be queried.
///
/// The scan writes rows; everything else reads them. Two programs used to walk
/// the tree and each print its own markdown — one in Rust here, one in Python
/// under scripts/ — and neither recorded anything, so "how many tests are
/// there" had as many answers as there were passes.
fn run_catalog_command(action: CatalogAction, ctx: &AppContext) -> Result<()> {
    let catalogue = ctx.db.catalogue_repo();
    let root = &ctx.worktree_root;

    match action {
        CatalogAction::List { repo } => {
            let mut tests = catalogue.all()?;
            if let Some(wanted) = &repo {
                tests.retain(|test| &test.repo == wanted);
            }
            for test in &tests {
                wsb::output::emit(wsb::output::Record::CatalogueTest {
                    number: test.number,
                    name: test.function_name.clone(),
                    repo: test.repo.clone(),
                    language: test.language.as_str().to_string(),
                    file: test.file_path.clone(),
                    line: test.line_number,
                    description: test.description.clone(),
                });
            }
            // The same facts for a person at a terminal. A JSONL run
            // emits nothing here: the records above already said all of it, and
            // saying it twice would double every line of the stream.
            if !wsb::output::is_jsonl() {
                for test in &tests {
                    wsb::outln!(
                        "{:<10}  {:<12}  {:<44}  {}",
                        test.number
                            .map(|n| format!("TEST{n}"))
                            .unwrap_or_else(|| "—".to_string()),
                        test.language.as_str(),
                        test.function_name,
                        test.location(),
                    );
                }
                wsb::outln!("\n{} tests", tests.len());
            }
        }

        CatalogAction::Scan { quiet } => {
            let scans = wsb::catalogue::scan::scan_worktree(root, &catalogue)
                .map_err(|e| anyhow::anyhow!("{}", e))?;
            if !quiet {
                let rows: Vec<wsb::report::Row> = scans
                    .iter()
                    .map(|scan| {
                        wsb::report::Row::new(
                            wsb::catalogue::scan::display_repo(&scan.repo),
                            format!("{} TESTS", scan.found),
                            format!("{} numbered", scan.numbered),
                        )
                    })
                    .collect();
                let total: usize = scans.iter().map(|s| s.found).sum();
                let conclusion =
                    format!("{total} tests across {} repositories", scans.len());
                wsb::report::show(
                    "Catalogue scan",
                    &rows,
                    Some((conclusion.as_str(), wsb::report::Verdict::Ok)),
                );
            }
        }

        CatalogAction::Report => {
            let survey = wsb::catalogue::report::Survey::read(&catalogue)?;
            wsb::out!("{}", survey.render());
            if !survey.is_clean() {
                // A catalogue with a number used twice cannot answer "where is
                // TEST8420"; exiting non-zero is what lets a hook or a gate care.
                std::process::exit(wsb::output::finish(1));
            }
        }

        CatalogAction::Parity {
            family,
            output,
            git_add,
        } => {
            let members = wsb::catalogue::families::members(root, &family)?;
            // Two shapes of the same reading. The terminal wants the gaps —
            // what is missing, now — and the document wants all of it, because
            // it is what a person reads when they are deciding what to port.
            match output {
                None => {
                    let parity =
                        wsb::catalogue::report::Parity::read(&catalogue, &members)?;
                    wsb::out!("{}", parity.render());
                }
                Some(path) => {
                    let markdown = wsb::catalogue::report::parity_markdown(
                        &catalogue, &members,
                    )?;
                    // Relative to the worktree root, like every other declared
                    // path: the document lives in the family's own repository
                    // and is written from wherever the command was run.
                    let path = if path.is_absolute() { path } else { root.join(path) };
                    std::fs::write(&path, markdown)
                        .with_context(|| format!("failed to write {}", path.display()))?;
                    wsb::outln!("wrote {}", path.display());
                    if git_add {
                        let repository = wsb::git_backend::discover_repo(&path)?;
                        wsb::git_backend::stage_paths(
                            &repository,
                            &[path.to_string_lossy().to_string()],
                        )?;
                    }
                }
            }
        }

        CatalogAction::Free { from, count } => {
            for number in catalogue.free_numbers(from, count)? {
                wsb::outln!("TEST{number}");
            }
        }

        CatalogAction::Export {
            output,
            repo,
            git_add,
        } => {
            let markdown =
                wsb::catalogue::report::markdown(&catalogue, repo.as_deref())?;
            let path = output.unwrap_or_else(|| root.join("TEST_CATALOG.md"));
            std::fs::write(&path, markdown)
                .with_context(|| format!("failed to write {}", path.display()))?;
            wsb::outln!("wrote {}", path.display());
            if git_add {
                let repository = wsb::git_backend::discover_repo(root)?;
                wsb::git_backend::stage_paths(
                    &repository,
                    &[path.to_string_lossy().to_string()],
                )?;
            }
        }
    }

    Ok(())
}

/// Resolve and check the worktree the workbench should serve.
///
/// Run before the generic worktree guard, so a misplaced `wsb serve` gets a
/// diagnostic naming what is missing and how to fix it.
fn validate_server_worktree(worktree: Option<PathBuf>) -> Result<PathBuf> {
    let start_dir = match worktree {
        Some(p) => wsb::platform::canonicalize(&p)
            .with_context(|| format!("worktree path '{}' does not exist", p.display()))?,
        None => std::env::current_dir().context("failed to get current directory")?,
    };
    // The SUPER root, not the nearest repository. Most of this worktree is
    // submodules, and the workbench serves the worktree — the database, the
    // declared model and the store all live at the top.
    let worktree_root = roots::find_super_root(&start_dir).ok_or_else(|| {
        anyhow::anyhow!(
            "cannot start the workbench from '{}': not inside a git repository.\n\
             The workbench serves an initialized wsb worktree.\n\
             initialize this directory first:\n  wsb init\n\
             or change into an existing worktree and try again.",
            start_dir.display()
        )
    })?;

    if !RepoSettings::exists(&worktree_root) {
        bail!(
            "cannot start the workbench from '{}': '{}' is no repository wsb manages: it has no {}.\n\
             set it up first:\n  wsb init\n\
             or change into a repository wsb manages and try again.",
            start_dir.display(),
            worktree_root.display(),
            RepoSettings::path(&worktree_root).strip_prefix(&worktree_root).unwrap_or(&RepoSettings::path(&worktree_root)).display()
        );
    }

    Ok(worktree_root)
}

/// Start the workbench, which means: make sure this worktree has a daemon.
///
/// Returns as soon as one is answering. The page outlives this command, which
/// is the whole reason the server moved into a daemon — before, it lived for
/// as long as somebody kept a terminal open on it.
fn run_serve_command(
    worktree_root: &Path,
    port: Option<u16>,
    listen: Option<std::net::IpAddr>,
    debug: bool,
    parent_pid: Option<u32>,
    no_daemon: bool,
) -> Result<()> {
    if no_daemon {
        bail!(
            "there is no workbench without a daemon: the server IS the daemon, and \
             this run says not to have one (--no-daemon, or {} in the \
             environment).\n  \
             Run `wsb serve` without it, and put --no-daemon on the commands \
             that should stay in this process.",
            wsb::daemon::NO_DAEMON_ENV
        );
    }
    let state_dir = wsb::daemon::machine_dir().map_err(|e| anyhow::anyhow!(e))?;
    let spawn = wsb::daemon::Spawn {
        listen: listen.unwrap_or(wsb::daemon::LOOPBACK),
        http_port: daemon_port(port),
        parent_pid,
        debug,
        peer_port: wsb::peer::DEFAULT_PEER_PORT,
    };
    let (client, info, started) =
        wsb::daemon::ensure_running(&state_dir, worktree_root, &spawn)
            .map_err(|e| anyhow::anyhow!(e))?;
    // This worktree's page, not the daemon's front door: one daemon serves
    // every worktree on the machine, and its root is the machine's page.
    let worktree = client
        .resolve_worktree(worktree_root)
        .map_err(|e| anyhow::anyhow!(e))?;
    let page = format!(
        "http://{}/w/{}",
        // Through SocketAddr, which knows an IPv6 address needs brackets
        // before it is a URL.
        std::net::SocketAddr::new(info.http_address, info.http_port),
        worktree.id
    );

    if started {
        wsb::outln!("workbench started at {page} (wsb-daemon pid {})", info.pid);
        if listen.is_some_and(|address| !address.is_loopback()) {
            wsb::outln!(
                "  reachable from other machines, and the workbench has no \
                 authentication: anyone who can reach it can read and edit this \
                 worktree, run git on it and write to GitHub as this machine's \
                 login. Put it behind a tunnel or a TLS reverse proxy."
            );
        }
    } else {
        wsb::outln!("workbench already running at {page} (wsb-daemon pid {})", info.pid);
        if listen.is_some_and(|address| address != info.http_address) {
            wsb::outln!(
                "  --listen applies only to a daemon this command starts. \
                 `wsb daemon stop` and then `wsb serve --listen …` moves it."
            );
        }
        if port.is_some_and(|asked| asked != info.http_port) {
            let asked = port.expect("just checked");
            wsb::outln!(
                "  --port applies only to a daemon this command starts. \
                 `wsb daemon restart --port {asked}` moves it."
            );
        }
    }
    Ok(())
}

/// Whether this run stays in its own process rather than running beside the
/// machine's daemon.
///
/// Separated from attaching so the decision can be asked about: it is one
/// answer with several reasons, and the reasons are not obvious from the call
/// site.
fn runs_without_the_daemon(worktree: Option<&Path>, no_daemon: bool) -> bool {
    // `--no-daemon`, or `WSB_NO_DAEMON` from whatever started this run: it,
    // and everything it starts, stays in one process.
    if no_daemon {
        return true;
    }
    // A directory that is not a worktree yet has nothing for a daemon to
    // serve. `wsb init` runs there.
    //
    // `worktree` is the SUPER root, so a command run inside a submodule uses
    // the worktree's one daemon rather than asking for a second one of its
    // own — which is what a git hook running in a submodule would do, on a
    // port the real daemon already holds.
    let Some(worktree_root) = worktree else {
        return true;
    };
    // A worktree with no commits has no identity, and a daemon serves
    // worktrees BY identity: the superproject's root commit, which is what two
    // machines compare when they pair. Before the first commit there is none,
    // so the daemon rightly refuses to register it.
    //
    // Which would make the first commit impossible: `wsb init` installs a
    // pre-commit hook that runs `wsb update --git-add`, that would ask the
    // daemon, the daemon would refuse, and git would refuse the commit. There
    // is genuinely nothing for a daemon to hold yet, and the update the hook
    // wants is entirely local.
    !has_a_commit(worktree_root)
}

/// Whether the superproject has any commit at all.
///
/// Asked of git, not of `.git/refs`: an unborn HEAD is a repository whose HEAD
/// names a branch that does not exist yet, and reading the file system for that
/// is reimplementing what gix already answers.
fn has_a_commit(worktree_root: &Path) -> bool {
    wsb::git_backend::open_repo(worktree_root)
        .map(|repo| repo.head_id().is_ok())
        .unwrap_or(false)
}

/// Make sure the machine's daemon is running and report this run to it, unless
/// the run stays in its own process.
///
/// A daemon that cannot be started is reported rather than worked around:
/// `--no-daemon` is the way to say a run should have none.
fn attach_to_the_daemon(acting: &Path, no_daemon: bool) -> Result<()> {
    let worktree = wsb::roots::find_worktree_root(acting);
    if runs_without_the_daemon(worktree.as_deref(), no_daemon) {
        return Ok(());
    }
    let worktree_root = worktree.expect("a worktree, since the decision above found one");

    // The MACHINE's directory: one daemon serves every worktree on it.
    let state_dir = wsb::daemon::machine_dir().map_err(|e| anyhow::anyhow!(e))?;
    let spawn = wsb::daemon::Spawn {
        // Never anything but loopback: this start is a side effect of running
        // some other command, and a daemon the whole network can reach is not
        // something to acquire without asking for it.
        listen: wsb::daemon::LOOPBACK,
        http_port: daemon_port(None),
        parent_pid: None,
        debug: false,
        peer_port: wsb::peer::DEFAULT_PEER_PORT,
    };
    let (client, _info, _started) = wsb::daemon::ensure_running(&state_dir, &worktree_root, &spawn)
        .map_err(|e| anyhow::anyhow!(e))?;
    // A command typed in a terminal shows up in the workbench's activity panel
    // exactly as one started from a page does, because the daemon puts both in
    // one registry.
    wsb::output::report_to_daemon(&client);
    Ok(())
}

/// The port a daemon this command starts should take.
///
/// A port the operator named is a demand: taken means refused, because
/// quietly serving somewhere else is not an answer to "serve on 3000". An
/// unnamed one is the first free port from the default, so a second worktree
/// on the same machine can have a daemon at all.
fn daemon_port(asked: Option<u16>) -> wsb::daemon::Port {
    match asked {
        Some(port) => wsb::daemon::Port::Exact(port),
        None => wsb::daemon::Port::FirstFreeFrom(wsb::daemon::DEFAULT_HTTP_PORT),
    }
}

/// The daemon's own commands. None of them starts one.
fn run_daemon_command(action: DaemonAction) -> Result<()> {
    let state_dir = wsb::daemon::machine_dir().map_err(|e| anyhow::anyhow!(e))?;

    // Read by every arm, including the ones that report there is none: a
    // rendezvous file naming a dead port is not a running daemon, and saying
    // so is the answer rather than an error.
    let running = match wsb::daemon::MachineRendezvous::read(&state_dir)
        .map_err(|e| anyhow::anyhow!(e))?
    {
        Some(rendezvous) => {
            let client = wsb::daemon::Client::from_rendezvous(&rendezvous)
                .map_err(|e| anyhow::anyhow!(e))?;
            client.info().ok().map(|info| (client, info))
        }
        None => None,
    };

    match action {
        DaemonAction::Status => match running {
            Some((_, info)) => {
                wsb::outln!("wsb-daemon {} (pid {})", info.version, info.pid);
                wsb::outln!(
                    "  workbench   http://{}{}",
                    std::net::SocketAddr::new(info.http_address, info.http_port),
                    // Stated where it matters: a daemon on every interface is
                    // one anybody on the network can drive, and it should not
                    // take a port scan to find that out.
                    if info.http_address.is_loopback() {
                        ""
                    } else {
                        "  (reachable beyond this machine — no authentication)"
                    }
                );
                wsb::outln!("  machine     {} ({})", info.machine_name, info.machine_id);
                if info.peer_port > 0 {
                    wsb::outln!(
                        "  peers       {}{}",
                        std::net::SocketAddr::new(info.peer_address, info.peer_port),
                        // The opposite warning to the workbench's, for the
                        // opposite reason: this listener is meant to be
                        // reachable, and one that is not cannot be paired with.
                        if info.peer_address.is_loopback() {
                            "  (this machine only — no peer can reach it)"
                        } else {
                            ""
                        }
                    );
                } else if let Some(why) = &info.peer_refused {
                    wsb::outln!("  peers       not listening: {why}");
                } else {
                    wsb::outln!("  peers       off (--peer-port 0)");
                }
                if info.worktrees.is_empty() {
                    wsb::outln!("  worktrees   none open yet");
                } else {
                    wsb::outln!("  worktrees   {} open", info.worktrees.len());
                }
                for worktree in &info.worktrees {
                    wsb::outln!("    {:<28} {}", worktree.id, worktree.root);
                }
                report_service(&state_dir, Some(info.pid));
                Ok(())
            }
            None => {
                wsb::outln!("no daemon is running on this machine");
                wsb::outln!("  one starts by itself with the next command, or `wsb serve`");
                report_service(&state_dir, None);
                Ok(())
            }
        },
        DaemonAction::Stop => match running {
            Some((client, info)) => {
                stop_daemon(&client, &info)?;
                wsb::daemon::wait_until_stopped(&state_dir, &info)
                    .map_err(|e| anyhow::anyhow!(e))?;
                wsb::outln!("stopped wsb-daemon (pid {})", info.pid);
                Ok(())
            }
            None => {
                wsb::outln!("no daemon is running on this machine");
                Ok(())
            }
        },
        DaemonAction::Restart { port } => {
            // A supervisor that is watching the daemon decides what happens
            // when it exits. Stopping it here and starting a replacement
            // alongside is how a machine ends up with two — one the supervisor
            // brought back and one this command started, racing for the port.
            if wsb::daemon::service::status(&state_dir)
                .is_ok_and(|service| service.installed && service.active)
            {
                wsb::daemon::service::restart().map_err(|e| anyhow::anyhow!(e))?;
                wsb::outln!("asked the supervisor to restart the daemon");
                if let Some(port) = port {
                    wsb::outln!(
                        "  --port {port} was ignored: a service is started with the port \
                         it was installed with (`wsb daemon install --port {port}`)"
                    );
                }
                return Ok(());
            }
            if let Some((client, info)) = running {
                stop_daemon(&client, &info)?;
                // Waited for, not assumed: the daemon answers the request to
                // stop before it exits, so starting the replacement here
                // would start it against a port the old one still holds and a
                // rendezvous file that still names the old one.
                wsb::daemon::wait_until_stopped(&state_dir, &info)
                    .map_err(|e| anyhow::anyhow!(e))?;
                wsb::outln!("stopped wsb-daemon (pid {})", info.pid);
            }
            // Restarting is a machine act; the worktree is whichever one this
            // command is standing in, and the daemon registers it as it would
            // for any other command.
            let worktree_root = std::env::current_dir()?;
            let spawn = wsb::daemon::Spawn {
                // `restart` restores a daemon on this machine. Serving it
                // wider is `wsb serve --listen`, said deliberately.
                listen: wsb::daemon::LOOPBACK,
                http_port: daemon_port(port),
                parent_pid: None,
                debug: false,
                peer_port: wsb::peer::DEFAULT_PEER_PORT,
            };
            let (_client, info, _started) =
                wsb::daemon::ensure_running(&state_dir, &worktree_root, &spawn)
                    .map_err(|e| anyhow::anyhow!(e))?;
            wsb::outln!(
                "started wsb-daemon {} at http://127.0.0.1:{} (pid {})",
                info.version,
                info.http_port,
                info.pid
            );
            Ok(())
        }
        DaemonAction::Log { lines } => {
            let path = wsb::daemon::log_path(&state_dir);
            wsb::outln!("{}", path.display());
            match std::fs::read_to_string(&path) {
                Ok(text) => {
                    let all: Vec<&str> = text.lines().collect();
                    for line in all.iter().skip(all.len().saturating_sub(lines)) {
                        wsb::outln!("{line}");
                    }
                    Ok(())
                }
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                    wsb::outln!("  (no daemon has written to it yet)");
                    Ok(())
                }
                Err(e) => Err(anyhow::anyhow!("cannot read {}: {e}", path.display())),
            }
        }
        DaemonAction::Install { port, peer_port } => {
            // The worktree the service opens first is the one this command is
            // standing in, exactly as an on-demand start uses it. Others
            // register themselves as commands are run in them.
            let worktree_root = std::env::current_dir()?;
            // A service names a port rather than probing, so one has to be
            // chosen here — and the right one to choose is the one this
            // machine's daemon is already answering on. Probing instead would
            // find that port taken by the daemon the service is going to
            // replace, bake the next one up, and move the workbench to an
            // address every bookmark and every printed URL has wrong.
            let spawn = match (port, &running) {
                (None, Some((_, info))) => wsb::daemon::service::spawn_for_service(
                    Some(info.http_port),
                    peer_port.or(Some(info.peer_port)),
                ),
                _ => wsb::daemon::service::spawn_for_service(port, peer_port),
            };
            let record = wsb::daemon::service::install(&state_dir, &worktree_root, &spawn)
                .map_err(|e| anyhow::anyhow!(e))?;
            let supervisor = wsb::daemon::service::supervisor()
                .map_err(|e| anyhow::anyhow!(e))?;
            let definition = wsb::daemon::service::definition_path(supervisor)
                .map_err(|e| anyhow::anyhow!(e))?;
            wsb::outln!(
                "installed the wsb daemon as a service under {}",
                supervisor.describe()
            );
            wsb::outln!("  definition  {}", definition.display());
            wsb::outln!("  starts      {}", record.executable.display());
            wsb::outln!("  worktree   {}", record.worktree_root.display());
            wsb::outln!("  log         {}", record.log.display());
            // Printed because it is baked in and invisible otherwise, and
            // because it is the thing most likely to be wrong: a service
            // installed from a shell without the toolchains on PATH starts a
            // daemon that cannot build anything.
            wsb::outln!("  PATH        {}", record.path);
            if record.autostart {
                wsb::outln!("  at login    yes (it was already enabled)");
            } else {
                wsb::outln!("  at login    no — `wsb daemon enable` starts it at login, and now");
            }
            Ok(())
        }
        DaemonAction::Enable => {
            // One daemon per machine. Enabling starts the supervisor's, and a
            // daemon this machine already has — started on demand by some
            // earlier command — holds the port and the rendezvous file it
            // needs. So it is handed over rather than left to collide: the
            // supervisor's replacement would otherwise fail to bind, and the
            // one that answered would be whichever won the race.
            let service_pid = wsb::daemon::service::status(&state_dir)
                .ok()
                .filter(|service| service.active)
                .and_then(|service| service.pid);
            if let Some((client, info)) = &running {
                if service_pid != Some(info.pid) {
                    wsb::outln!(
                        "handing over from the daemon started on demand (pid {})",
                        info.pid
                    );
                    stop_daemon(client, info)?;
                    wsb::daemon::wait_until_stopped(&state_dir, info)
                        .map_err(|e| anyhow::anyhow!(e))?;
                }
            }
            let record = wsb::daemon::service::enable(&state_dir)
                .map_err(|e| anyhow::anyhow!(e))?;
            wsb::outln!(
                "the wsb daemon starts at login, and is running now (worktree {})",
                record.worktree_root.display()
            );
            report_linger(&state_dir);
            Ok(())
        }
        DaemonAction::Disable => {
            wsb::daemon::service::disable(&state_dir).map_err(|e| anyhow::anyhow!(e))?;
            wsb::outln!("the wsb daemon no longer starts at login");
            // Said because the command deliberately does not do it: ending a
            // running daemon is a separate decision.
            match running {
                Some((_, info)) => wsb::outln!(
                    "  the one running now (pid {}) keeps running; `wsb daemon stop` ends it",
                    info.pid
                ),
                None => wsb::outln!("  one still starts by itself with the next command"),
            }
            Ok(())
        }
        DaemonAction::Uninstall => {
            match wsb::daemon::service::uninstall(&state_dir).map_err(|e| anyhow::anyhow!(e))? {
                true => {
                    wsb::outln!("removed the wsb daemon service from this machine");
                    wsb::outln!("  one still starts by itself with the next command");
                }
                false => wsb::outln!("no wsb daemon service is installed on this machine"),
            }
            Ok(())
        }
    }
}

/// What the supervisor holds, appended to `wsb daemon status`.
///
/// Reported alongside the running daemon rather than as its own command,
/// because the question is one question: an operator asking what is serving
/// this machine wants to know whether anything will still be serving it after
/// a reboot.
///
/// Silent about the supervisor's absence. A machine with no service manager
/// wsb knows is not a machine with a problem — the daemon starts itself there
/// — and a line saying so on every status would be noise on every machine that
/// never wanted one.
fn report_service(state_dir: &Path, daemon_pid: Option<u32>) {
    let Ok(service) = wsb::daemon::service::status(state_dir) else {
        return;
    };
    if !service.installed {
        return;
    }
    wsb::outln!(
        "  service     {} — {}",
        service.supervisor.describe(),
        if service.autostart {
            "starts at login"
        } else {
            "installed, does not start at login"
        }
    );
    match (service.active, service.pid) {
        // The daemon answering and the job the supervisor is running are two
        // facts, and they can disagree: a daemon started from a terminal while
        // the service was stopped is the ordinary way that happens.
        (true, Some(pid)) if Some(pid) == daemon_pid => {
            wsb::outln!("              the daemon above is the one it is keeping")
        }
        (true, Some(pid)) => wsb::outln!(
            "              it is running pid {pid}, which is not the daemon above"
        ),
        (true, None) => wsb::outln!("              it is running"),
        (false, _) => wsb::outln!("              it is not running one right now"),
    }
    if service.drifted {
        wsb::outln!(
            "              the definition is not what this wsb would write — \
             run `wsb daemon install` again"
        );
    }
    if service.autostart && service.linger == Some(false) {
        wsb::outln!(
            "              \"at login\" means at login: without lingering this user's \
             services stop at logout (`loginctl enable-linger $USER`)"
        );
    }
}

/// Say what "at login" will actually mean on this machine.
///
/// systemd stops a user's services when their last session ends unless
/// lingering is on. On a workstation that is what an operator wants; on a
/// build host reached over ssh it means the daemon they just enabled will be
/// gone the moment they log out — and nothing would have told them.
fn report_linger(state_dir: &Path) {
    let Ok(service) = wsb::daemon::service::status(state_dir) else {
        return;
    };
    if service.linger == Some(false) {
        wsb::outln!(
            "  this user does not linger, so its services stop at logout: \
             `loginctl enable-linger $USER` keeps the daemon across sessions"
        );
    }
}

/// Stop a running daemon, with the control secret its rendezvous file
/// published.
fn stop_daemon(client: &wsb::daemon::Client, info: &wsb::daemon::Info) -> Result<()> {
    client
        .shutdown()
        .map_err(|error| anyhow::anyhow!("cannot stop wsb-daemon (pid {}): {error}", info.pid))
}






// Entity relationship management functions

// ============================================================================
// Session Artifact Management Functions (F0159)
// ============================================================================

fn handle_code_command(action: CodeAction, project_root: &Path) -> Result<()> {
    use wsb::omnicode::query::{Question, SearchMode};
    let (question, repo) = match action {
        CodeAction::Tree { depth, hidden, sizes, extensions, no_ignore } => {
            return show_codebase_tree(depth, hidden, sizes, extensions, no_ignore);
        }
        CodeAction::Index { repo } => (Question::Index, repo),
        CodeAction::Search { pattern, regex, symbols, structural, include, exclude, repo } => {
            let mode = match (regex, symbols, structural) {
                (true, _, _) => SearchMode::Regex,
                (_, true, _) => SearchMode::Symbols,
                (_, _, true) => SearchMode::Structural,
                _ => SearchMode::Literal,
            };
            (Question::Search { pattern, mode, include, exclude }, repo)
        }
        CodeAction::Symbols { pattern, kind, repo } => (Question::Symbols { pattern, kind }, repo),
        CodeAction::Refs { target, repo } => (Question::Refs { target }, repo),
        CodeAction::Callers { target, depth, repo } => (Question::Callers { target, depth }, repo),
        CodeAction::Callees { target, depth, repo } => (Question::Callees { target, depth }, repo),
        CodeAction::Diagnostics { file, repo } => (Question::Diagnostics { file }, repo),
    };
    // The worktree as a whole: every repository of it, wherever the command stands.
    let worktree = roots::find_super_root(project_root).unwrap_or_else(|| project_root.to_path_buf());
    wsb::omnicode::cli::code(&worktree, repo.as_deref(), &question).map_err(|e| anyhow::anyhow!(e))
}

/// Directories from `root` down to `leaf`, inclusive, ordered outermost first.
///
/// `.gitignore` files apply to everything beneath them, so a tree rooted at
/// `leaf` must still honour the ones declared by its ancestors.
fn dirs_from_root_to(root: &Path, leaf: &Path) -> Vec<PathBuf> {
    let Ok(relative) = leaf.strip_prefix(root) else {
        return vec![leaf.to_path_buf()];
    };

    let mut dirs = vec![root.to_path_buf()];
    let mut current = root.to_path_buf();
    for component in relative.components() {
        current = current.join(component);
        dirs.push(current.clone());
    }
    dirs
}

fn show_codebase_tree(
    depth: usize,
    show_hidden: bool,
    show_sizes: bool,
    extensions_filter: Option<String>,
    no_ignore: bool,
) -> Result<()> {
    use colored::Colorize;
    use ignore::gitignore::GitignoreBuilder;

    let current_dir = std::env::current_dir()?;
    let project_root = find_project_root(&current_dir);

    // Show project information
    wsb::outln!("{}", "📁 Codebase Structure".bright_blue().bold());
    wsb::outln!(
        "{} {}",
        "Project Root:".bright_green(),
        project_root.display()
    );
    wsb::outln!(
        "{} {}",
        "Current Location:".bright_yellow(),
        current_dir.display()
    );

    if current_dir != project_root {
        let relative_path = current_dir
            .strip_prefix(&project_root)
            .unwrap_or(&current_dir);
        wsb::outln!(
            "{} {}",
            "Relative Path:".bright_cyan(),
            relative_path.display()
        );
    }

    wsb::outln!();

    // Parse extensions filter
    let extensions: Option<Vec<String>> = extensions_filter.map(|ext_str| {
        ext_str
            .split(',')
            .map(|s| s.trim().to_lowercase())
            .collect()
    });

    // Initialize gitignore if needed
    let gitignore = if no_ignore {
        None
    } else {
        // Ignore patterns are written relative to the repository root, so the
        // matcher must be rooted there. A worktree nested inside a repository
        // would otherwise never match a rule such as `wsb/target/`.
        let ignore_root = match wsb::git_backend::repo_root(&project_root) {
            Ok(root) => root,
            // Not a git repository: only the project's own .gitignore applies.
            Err(_) => project_root.clone(),
        };

        let mut builder = GitignoreBuilder::new(&ignore_root);
        for dir in dirs_from_root_to(&ignore_root, &project_root) {
            let candidate = dir.join(".gitignore");
            if !candidate.is_file() {
                continue;
            }
            if let Some(error) = builder.add(&candidate) {
                anyhow::bail!("failed to read {}: {}", candidate.display(), error);
            }
        }

        Some(
            builder
                .build()
                .context("failed to compile .gitignore rules for the codebase tree")?,
        )
    };

    // Display tree
    display_tree(
        &project_root,
        "",
        depth,
        0,
        show_hidden,
        show_sizes,
        &extensions,
        &gitignore,
    )?;

    Ok(())
}

fn find_project_root(current: &Path) -> std::path::PathBuf {
    let mut path = current.to_path_buf();

    // Look for common project markers
    let project_markers = [
        "Cargo.toml",
        "package.json",
        "pyproject.toml",
        "setup.py",
        "composer.json",
        "pom.xml",
        "build.gradle",
        "CMakeLists.txt",
        ".git",
        ".svn",
        ".hg",
        "Makefile",
        "go.mod",
    ];

    loop {
        for marker in &project_markers {
            if path.join(marker).exists() {
                return path;
            }
        }

        if !path.pop() {
            break;
        }
    }

    // If no markers found, return current directory
    current.to_path_buf()
}

fn display_tree(
    dir: &Path,
    prefix: &str,
    max_depth: usize,
    current_depth: usize,
    show_hidden: bool,
    show_sizes: bool,
    extensions: &Option<Vec<String>>,
    gitignore: &Option<ignore::gitignore::Gitignore>,
) -> Result<()> {
    if current_depth >= max_depth {
        return Ok(());
    }

    let entries = fs::read_dir(dir)?;
    let mut entries: Vec<_> = entries.collect::<Result<Vec<_>, _>>()?;

    // Filter out gitignored files first
    if let Some(ref gi) = gitignore {
        entries.retain(|entry| {
            let path = entry.path();
            let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
            let matched = gi.matched(&path, is_dir);
            !matched.is_ignore()
        });
    }

    entries.sort_by_key(|entry| {
        let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
        (!is_dir, entry.file_name())
    });

    let total_entries = entries.len();

    for (index, entry) in entries.iter().enumerate() {
        let file_name = entry.file_name();
        let file_name_str = file_name.to_string_lossy();
        let path = entry.path();
        let is_last = index == total_entries - 1;

        // Skip hidden files unless requested
        if !show_hidden && file_name_str.starts_with('.') {
            continue;
        }

        let is_dir = entry.file_type()?.is_dir();
        let connector = if is_last { "└── " } else { "├── " };
        let new_prefix = if is_last { "    " } else { "│   " };

        // Apply extension filter for files
        if !is_dir {
            if let Some(ref exts) = extensions {
                if let Some(ext) = path.extension() {
                    let ext_str = ext.to_string_lossy().to_lowercase();
                    if !exts.contains(&ext_str) {
                        continue;
                    }
                } else if !exts.is_empty() {
                    continue;
                }
            }
        }

        // Format output
        wsb::out!("{}{}", prefix, connector);

        if is_dir {
            wsb::out!("{}", file_name_str.bright_blue().bold());
        } else {
            let colored_name = match path.extension().and_then(|s| s.to_str()) {
                Some("rs") => file_name_str.bright_red(),
                Some("py") => file_name_str.bright_yellow(),
                Some("js" | "ts" | "jsx" | "tsx") => file_name_str.bright_green(),
                Some("json" | "yaml" | "yml" | "toml") => file_name_str.bright_cyan(),
                Some("md" | "txt" | "doc") => file_name_str.white(),
                Some("sh" | "bash" | "zsh") => file_name_str.bright_magenta(),
                _ => file_name_str.normal(),
            };
            wsb::out!("{}", colored_name);
        }

        // Show file size if requested
        if show_sizes && !is_dir {
            if let Ok(metadata) = entry.metadata() {
                let size = format_file_size(metadata.len());
                wsb::out!(" {}", size.dimmed());
            }
        }

        wsb::outln!();

        // Recurse into directories
        if is_dir && current_depth + 1 < max_depth {
            let next_prefix = format!("{}{}", prefix, new_prefix);
            display_tree(
                &path,
                &next_prefix,
                max_depth,
                current_depth + 1,
                show_hidden,
                show_sizes,
                extensions,
                gitignore,
            )?;
        }
    }

    Ok(())
}

// Helper structures and functions

fn format_file_size(bytes: u64) -> String {
    const UNITS: &[&str] = &["B", "KB", "MB", "GB"];

    let mut size = bytes as f64;
    let mut unit_index = 0;

    while size >= 1024.0 && unit_index < UNITS.len() - 1 {
        size /= 1024.0;
        unit_index += 1;
    }

    if unit_index == 0 {
        format!("{} {}", bytes, UNITS[unit_index])
    } else {
        format!("{:.1} {}", size, UNITS[unit_index])
    }
}

fn run_version_command(action: VersionAction, ctx: &AppContext) -> Result<()> {
    match action {
        VersionAction::Show { verbose, format } => handle_version_show(verbose, format, ctx),
        VersionAction::Major { version } => handle_version_major(version, ctx),
        VersionAction::Tag { prefix, message } => handle_version_tag(prefix, message, ctx),
        VersionAction::Info { include_history } => handle_version_info(include_history, ctx),
    }
}

/// The version of the repository the command runs in, as an update would
/// write it: calculated at its committed major, with its suffix.
fn current_version(ctx: &AppContext) -> Result<(RepoSettings, VersionInfo)> {
    let settings = RepoSettings::require(&ctx.repo_root)?;
    let mut info = VersionInfo::calculate_with_major_in_repo(settings.version.major, &ctx.repo_root)?;
    info.full_version = settings.full_version(&info.major_version, info.minor_version, info.patch_version, None);
    Ok((settings, info))
}

fn handle_version_show(verbose: bool, format: String, ctx: &AppContext) -> Result<()> {
    let (settings, version_info) = current_version(ctx)?;
    let major = settings.version.major;
    let calc_info = if verbose {
        Some(VersionInfo::get_calculation_info_in_repo(major, &ctx.repo_root)?)
    } else {
        None
    };
    match format.as_str() {
        "json" => {
            let mut json_output = serde_json::json!({
                "version": version_info.full_version,
                "major": major,
                "minor": version_info.minor_version,
                "patch": version_info.patch_version,
                "repository": settings.name,
            });
            if let Some(calc_info) = calc_info {
                json_output["calculation"] = serde_json::json!({
                    "total_commits": calc_info.total_commits,
                    "changes_since_release": calc_info.changes_since_release,
                    "last_release_tag": calc_info.last_release_tag,
                    "method": calc_info.calculation_method
                });
            }
            wsb::outln!("{}", serde_json::to_string_pretty(&json_output)?);
        }
        _ => {
            wsb::outln!("{} {}", "Version:".blue().bold(), version_info.full_version.green().bold());
            wsb::outln!("{} {}", "Repository:".blue(), settings.name);
            if let Some(calc_info) = calc_info {
                wsb::outln!("\n{}", "Calculation Breakdown:".blue().bold());
                wsb::outln!("  {} {}", "Major (.wsb/repo.json):".blue(), major.to_string().yellow());
                wsb::outln!("  {} {}", "Minor (commits):".blue(), version_info.minor_version.to_string().yellow());
                wsb::outln!("  {} {}", "Patch (changes):".blue(), version_info.patch_version.to_string().yellow());
                match calc_info.last_release_tag {
                    Some(tag) => wsb::outln!("  {} {}", "Last release tag:".blue(), tag.green()),
                    None => wsb::outln!("  {} {}", "Last release tag:".blue(), "none".yellow()),
                }
                wsb::outln!("  {} {}", "Method:".blue(), calc_info.calculation_method.cyan());
            }
        }
    }
    Ok(())
}

fn handle_version_major(version: u32, ctx: &AppContext) -> Result<()> {
    let mut settings = RepoSettings::require(&ctx.repo_root)?;
    settings.version.major = version;
    settings.save(&ctx.repo_root)?;
    let (_, version_info) = current_version(ctx)?;
    info!("Major version set to {}, new version: {}", version, version_info.full_version);
    wsb::outln!(
        "{} Major version set to {} in {} — commit it",
        "✅".green(),
        version.to_string().green().bold(),
        RepoSettings::path(&ctx.repo_root).display()
    );
    wsb::outln!("{} New version: {}", "🔢".blue(), version_info.full_version.green().bold());
    wsb::outln!("\n{} {}", "Note:".blue(), "Minor/patch are calculated from git state");
    wsb::outln!("{} Use 'wsb version tag' to create a release tag", "💡".yellow());
    Ok(())
}

fn handle_version_tag(prefix: String, message: Option<String>, ctx: &AppContext) -> Result<()> {
    let (_, version_info) = current_version(ctx)?;
    let tag_name = format!("{}{}", prefix, version_info.full_version);
    let tag_message = message.unwrap_or_else(|| format!("Release version {}", version_info.full_version));

    // The repository this command is FOR, not the directory it was typed in:
    // the version above was calculated for `ctx.repo_root`, and tagging
    // anywhere else would attach that version to a different history.
    let repo = wsb::git_backend::discover_repo(&ctx.repo_root)?;
    wsb::git_backend::create_tag(&repo, &tag_name, &tag_message)?;

    info!("Created git tag: {}", tag_name);
    wsb::outln!("{} Created git tag: {}", "✅".green(), tag_name.green().bold());
    wsb::outln!("{} Message: {}", "📝".blue(), tag_message);
    wsb::outln!("\n{} To push tag to remote: git push origin {}", "💡".yellow(), tag_name);
    Ok(())
}

fn handle_version_info(include_history: bool, ctx: &AppContext) -> Result<()> {
    let (settings, version_info) = current_version(ctx)?;
    let major_version = settings.version.major;
    let calc_info = VersionInfo::get_calculation_info_in_repo(major_version, &ctx.repo_root)?;

    wsb::outln!("{}", "Version Calculation Information".blue().bold());
    wsb::outln!("=====================================");
    wsb::outln!();

    wsb::outln!("{}", "Current Version Breakdown:".green().bold());
    wsb::outln!("  {} {}", "Version:".blue(), version_info.full_version.green());
    wsb::outln!(
        "  {} {} (committed in .wsb/repo.json)",
        "Major:".blue(),
        major_version.to_string().green()
    );
    wsb::outln!(
        "  {} {} (total git commits)",
        "Minor:".blue(),
        version_info.minor_version.to_string().yellow()
    );
    wsb::outln!(
        "  {} {} (changes since last v{}.* tag)",
        "Patch:".blue(),
        version_info.patch_version.to_string().cyan(),
        major_version
    );
    wsb::outln!();

    wsb::outln!("{}", "Git Integration:".green().bold());
    if let Some(ref git_root) = calc_info.git_root {
        wsb::outln!("  {} {}", "Git Root:".blue(), git_root.display().to_string().cyan());
    }
    match calc_info.last_release_tag {
        Some(ref tag) => wsb::outln!("  {} {}", "Last Release Tag:".blue(), tag.green()),
        None => wsb::outln!("  {} {}", "Last Release Tag:".blue(), "none found".yellow()),
    }
    wsb::outln!();

    wsb::outln!("{}", "Commands:".green().bold());
    wsb::outln!("  {} Set major version", "wsb version major <number>".cyan());
    wsb::outln!("  {} Create release tag", "wsb version tag".cyan());
    wsb::outln!("  {} Show current version", "wsb version show".cyan());
    wsb::outln!();

    if include_history {
        wsb::outln!("{}", "Git History Analysis:".green().bold());
        let repo = wsb::git_backend::discover_repo(&ctx.repo_root)?;
        let tags = wsb::git_backend::list_tags(&repo)?;
        if tags.is_empty() {
            wsb::outln!("  {} {}", "Recent Tags:".blue(), "none found".yellow());
        } else {
            wsb::outln!("  {}:", "Recent Tags".blue());
            for (i, tag) in tags.iter().take(5).enumerate() {
                wsb::outln!("    {}. {}", i + 1, tag.green());
            }
        }
        wsb::outln!();
    }
    Ok(())
}

fn run_migrate_command(cwd: &Path) -> Result<()> {
    let report = wsb::cli::annotations::migrate(cwd)?;
    for line in &report.done {
        wsb::outln!("  {} {line}", "✓".green());
    }
    for line in &report.refused {
        wsb::errln!("  {} {line}", "✗".red());
    }
    if report.done.is_empty() && report.refused.is_empty() {
        wsb::outln!("nothing of an older wsb's layout is left on this machine");
    }
    if !report.refused.is_empty() {
        anyhow::bail!(
            "{} item(s) were left as they were; deal with each and run `wsb migrate` again",
            report.refused.len()
        );
    }
    Ok(())
}

/// The body given as text, read from a file, or read from standard input.
fn body_of(body: Option<String>, body_file: Option<PathBuf>) -> Result<Option<String>> {
    match (body, body_file) {
        (Some(text), None) => Ok(Some(text)),
        (None, Some(path)) if path.as_os_str() == "-" => {
            let mut text = String::new();
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut text).context("reading the body from standard input")?;
            Ok(Some(text))
        }
        (None, Some(path)) => Ok(Some(
            std::fs::read_to_string(&path).with_context(|| format!("reading the body from {}", path.display()))?,
        )),
        (None, None) => Ok(None),
        (Some(_), Some(_)) => anyhow::bail!("give --body or --body-file, not both"),
    }
}

fn print_note(held: &wsb::annotations::HeldNote) {
    let places: Vec<String> = held.places.iter().map(|place| format!("{}/{}", place.worktree, place.worktree)).collect();
    wsb::outln!("{}  {}", held.note.id.dimmed(), held.note.title.bold());
    wsb::outln!("  written {} on {}; in {}", held.note.created, held.note.machine, places.join(", "));
}

fn run_note_command(action: NoteAction, cwd: &Path) -> Result<()> {
    match action {
        NoteAction::Add { title, body, body_file, about } => {
            let body = body_of(body, body_file)?.unwrap_or_default();
            let machine = wsb::daemon::machine_name().map_err(anyhow::Error::msg)?;
            let (note, written) = wsb::cli::annotations::note_add(cwd, &title, &body, &about.targets(), &machine)?;
            wsb::outln!("{} wrote note {} ({})", "✓".green(), note.id, note.title);
            for path in &written {
                wsb::outln!("    {}", path.display());
            }
            wsb::outln!("Commit them to share them with every clone.");
        }
        NoteAction::List { on } => {
            let index = wsb::cli::annotations::index()?;
            let on = on.map(|text| text.parse::<wsb::annotations::Ref>()).transpose()?;
            let notes = wsb::cli::annotations::notes_about(&index, on.as_ref());
            for problem in &index.problems {
                wsb::errln!("  {} {problem}", "!".yellow());
            }
            if notes.is_empty() {
                wsb::outln!("no notes");
            }
            for held in notes {
                print_note(held);
            }
        }
        NoteAction::Show { id } => {
            let index = wsb::cli::annotations::index()?;
            let versions = index.note(&id);
            if versions.is_empty() {
                anyhow::bail!("no worktree in the workshop holds a note {id}");
            }
            if versions.len() > 1 {
                wsb::outln!("{} worktrees hold {} versions of this note", versions.iter().map(|v| v.places.len()).sum::<usize>(), versions.len());
            }
            let note = Ref::Note { id: id.clone() };
            for held in versions {
                print_note(held);
                wsb::outln!();
                wsb::outln!("{}", held.note.body);
            }
            for link in index.links_at(&note) {
                if let Some(other) = link.link.other_end(&note) {
                    wsb::outln!("  → {other}");
                }
            }
        }
        NoteAction::Edit { id, title, body, body_file } => {
            let body = body_of(body, body_file)?;
            let (note, path) = wsb::cli::annotations::note_edit(cwd, &id, title.as_deref(), body.as_deref())?;
            wsb::outln!("{} rewrote note {} ({}) in {}", "✓".green(), note.id, note.title, path.display());
        }
        NoteAction::Rm { id } => {
            for path in wsb::cli::annotations::note_rm(cwd, &id)? {
                wsb::outln!("{} removed {}", "✓".green(), path.display());
            }
        }
    }
    Ok(())
}

fn run_link_command(action: LinkAction, cwd: &Path) -> Result<()> {
    match action {
        LinkAction::Add { from, to, label } => {
            let path = wsb::cli::annotations::link_add(cwd, &from.parse()?, &to.parse()?, label.as_deref())?;
            wsb::outln!("{} linked {from} → {to} ({}); commit it to share it", "✓".green(), path.display());
        }
        LinkAction::List { at } => {
            let index = wsb::cli::annotations::index()?;
            let at = at.map(|text| text.parse::<wsb::annotations::Ref>()).transpose()?;
            for problem in &index.problems {
                wsb::errln!("  {} {problem}", "!".yellow());
            }
            let links = wsb::cli::annotations::links_at(&index, at.as_ref());
            if links.is_empty() {
                wsb::outln!("no links");
            }
            for held in links {
                let label = held.link.label.as_deref().map(|label| format!(" [{label}]")).unwrap_or_default();
                wsb::outln!("{} → {}{label}", held.link.from, held.link.to);
            }
        }
        LinkAction::Rm { from, to, label } => {
            let path = wsb::cli::annotations::link_rm(cwd, &from.parse()?, &to.parse()?, label.as_deref())?;
            wsb::outln!("{} removed {}", "✓".green(), path.display());
        }
    }
    Ok(())
}

fn handle_test_command(
    dry_run: bool,
    install: bool,
    args: Vec<String>,
    project_root: &Path,
) -> Result<()> {
    use wsb::state::detect_project_files;

    // Detect project files to determine project type
    let project_files = detect_project_files(&project_root)?;

    if project_files.is_empty() {
        wsb::outln!(
            "{} No project files detected in current directory",
            "⚠️".yellow()
        );
        wsb::outln!("{} Supported project types: Rust (Cargo.toml), Node.js (package.json), Python (pyproject.toml), PHP (composer.json), Dart (pubspec.yaml), Java (pom.xml, build.gradle), C++ (CMakeLists.txt)", "💡".blue());
        return Ok(());
    }

    // Determine primary project type and test command
    let (test_cmd, test_args, description) = determine_test_command(&project_files)?;

    wsb::outln!("{} Detected project: {}", "🔍".blue(), description);
    wsb::outln!(
        "{} Test command: {} {}",
        "🚀".green(),
        test_cmd,
        test_args.join(" ")
    );

    if !args.is_empty() {
        wsb::outln!("{} Additional args: {}", "📋".blue(), args.join(" "));
    }

    if dry_run {
        wsb::outln!("{} Dry run - would execute:", "👀".cyan());
        let mut full_args = test_args.clone();
        full_args.extend(args);
        wsb::outln!("  {} {}", test_cmd, full_args.join(" "));
        return Ok(());
    }

    // Check if test runner is available and install if needed
    if install {
        ensure_test_runner_available(&test_cmd, &project_files)?;
    }

    // Execute the test command
    let mut full_args = test_args.clone();
    full_args.extend(args);

    wsb::outln!("{} Running tests...", "🧪".green());
    let mut command = wsb::git_backend::command_without_repo_scope(&test_cmd);
    command.args(&full_args);

    let status = command.status()?;

    if status.success() {
        wsb::outln!("{} Tests completed successfully!", "✅".green());
    } else {
        wsb::outln!(
            "{} Tests failed with exit code: {}",
            "❌".red(),
            status.code().unwrap_or(-1)
        );
        std::process::exit(status.code().unwrap_or(1));
    }

    Ok(())
}

fn determine_test_command(
    project_files: &[wsb::state::ProjectFile],
) -> Result<(String, Vec<String>, String)> {
    use wsb::state::ProjectFileType;

    // Priority order for when multiple project files exist. The first type in
    // this list that is present wins, regardless of where it sits in
    // `project_files` — otherwise a repository with both a Cargo.toml and a
    // package.json would pick whichever the scan happened to find first.
    const PRIORITY: &[ProjectFileType] = &[
        ProjectFileType::CargoToml,
        ProjectFileType::PackageJson,
        ProjectFileType::PyprojectToml,
        ProjectFileType::SetupPy,
        ProjectFileType::GoMod,
        ProjectFileType::MixExs,
        ProjectFileType::BuildSbt,
        ProjectFileType::ShardYml,
        ProjectFileType::JuliaProject,
        ProjectFileType::ComposerJson,
        ProjectFileType::PubspecYaml,
        ProjectFileType::PomXml,
        ProjectFileType::BuildGradle,
        ProjectFileType::BuildGradleKts,
        ProjectFileType::CMakeLists,
        ProjectFileType::PackageSwift,
        ProjectFileType::Gemspec,
        ProjectFileType::Csproj,
    ];

    for wanted in PRIORITY {
        if project_files
            .iter()
            .any(|project_file| project_file.file_type == *wanted)
        {
            return Ok(test_command_for(wanted));
        }
    }

    anyhow::bail!("No supported test runner found for detected project files")
}

fn test_command_for(file_type: &wsb::state::ProjectFileType) -> (String, Vec<String>, String) {
    use wsb::state::ProjectFileType;

    match file_type {
        ProjectFileType::CargoToml => (
            "cargo".to_string(),
            vec![
                "nextest".to_string(),
                "run".to_string(),
                "--no-fail-fast".to_string(),
            ],
            "Rust (Cargo.toml)".to_string(),
        ),
        ProjectFileType::PackageJson => (
            "npm".to_string(),
            vec!["test".to_string()],
            "Node.js (package.json)".to_string(),
        ),
        ProjectFileType::PyprojectToml => (
            "pytest".to_string(),
            vec![],
            "Python (pyproject.toml)".to_string(),
        ),
        ProjectFileType::SetupPy => (
            "python".to_string(),
            vec!["-m".to_string(), "pytest".to_string()],
            "Python (setup.py)".to_string(),
        ),
        ProjectFileType::ComposerJson => (
            "vendor/bin/phpunit".to_string(),
            vec![],
            "PHP (composer.json)".to_string(),
        ),
        ProjectFileType::PubspecYaml => (
            "flutter".to_string(),
            vec!["test".to_string()],
            "Dart/Flutter (pubspec.yaml)".to_string(),
        ),
        ProjectFileType::PomXml => (
            "mvn".to_string(),
            vec!["test".to_string()],
            "Java Maven (pom.xml)".to_string(),
        ),
        ProjectFileType::BuildGradle => (
            "./gradlew".to_string(),
            vec!["test".to_string()],
            "Java Gradle (build.gradle)".to_string(),
        ),
        ProjectFileType::BuildGradleKts => (
            "./gradlew".to_string(),
            vec!["test".to_string()],
            "Kotlin Gradle (build.gradle.kts)".to_string(),
        ),
        ProjectFileType::CMakeLists => (
            "ctest".to_string(),
            vec!["--output-on-failure".to_string()],
            "C/C++ (CMakeLists.txt)".to_string(),
        ),
        ProjectFileType::PackageSwift => (
            "swift".to_string(),
            vec!["test".to_string()],
            "Swift (Package.swift)".to_string(),
        ),
        ProjectFileType::Gemspec => (
            "bundle".to_string(),
            vec!["exec".to_string(), "rspec".to_string()],
            "Ruby (gemspec)".to_string(),
        ),
        ProjectFileType::Csproj => (
            "dotnet".to_string(),
            vec!["test".to_string()],
            ".NET (csproj)".to_string(),
        ),
        ProjectFileType::GoMod => (
            "go".to_string(),
            vec!["test".to_string(), "./...".to_string()],
            "Go (go.mod)".to_string(),
        ),
        ProjectFileType::MixExs => (
            "mix".to_string(),
            vec!["test".to_string()],
            "Elixir (mix.exs)".to_string(),
        ),
        ProjectFileType::BuildSbt => (
            "sbt".to_string(),
            vec!["test".to_string()],
            "Scala (build.sbt)".to_string(),
        ),
        ProjectFileType::ShardYml => (
            "crystal".to_string(),
            vec!["spec".to_string()],
            "Crystal (shard.yml)".to_string(),
        ),
        ProjectFileType::JuliaProject => (
            "julia".to_string(),
            vec![
                "--project=.".to_string(),
                "-e".to_string(),
                "using Pkg; Pkg.test()".to_string(),
            ],
            "Julia (Project.toml)".to_string(),
        ),
    }
}

fn ensure_test_runner_available(
    test_cmd: &str,
    project_files: &[wsb::state::ProjectFile],
) -> Result<()> {
    use wsb::state::ProjectFileType;

    // Check if command exists
    if wsb::report::which(test_cmd).is_some() {
        wsb::outln!(
            "{} Test runner {} is already available",
            "✅".green(),
            test_cmd
        );
        return Ok(());
    }

    // Try to install missing test runners
    for project_file in project_files {
        match project_file.file_type {
            ProjectFileType::CargoToml if test_cmd.contains("nextest") => {
                wsb::outln!("{} Installing cargo-nextest...", "📦".blue());
                let status = wsb::git_backend::command_without_repo_scope("cargo")
                    .args(["install", "cargo-nextest", "--locked"])
                    .status()?;

                if status.success() {
                    wsb::outln!("{} Successfully installed cargo-nextest", "✅".green());
                } else {
                    wsb::outln!(
                        "{} Failed to install cargo-nextest, falling back to standard cargo test",
                        "⚠️".yellow()
                    );
                    // Could modify the test command here to fallback to regular cargo test
                }
                return Ok(());
            }
            ProjectFileType::PyprojectToml | ProjectFileType::SetupPy
                if test_cmd.contains("pytest") =>
            {
                wsb::outln!("{} Installing pytest...", "📦".blue());
                let status = wsb::git_backend::command_without_repo_scope("pip")
                    .args(["install", "pytest"])
                    .status()?;

                if status.success() {
                    wsb::outln!("{} Successfully installed pytest", "✅".green());
                } else {
                    wsb::outln!("{} Failed to install pytest", "❌".red());
                    anyhow::bail!("Could not install pytest");
                }
                return Ok(());
            }
            _ => {}
        }
    }

    wsb::outln!(
        "{} Test runner {} not found, please install it manually",
        "⚠️".yellow(),
        test_cmd
    );
    Ok(())
}

#[cfg(test)]
mod daemon_decision_tests {
    //! Which runs go beside the machine's daemon, and which stay alone.

    use super::runs_without_the_daemon;

    /// A repository wsb manages, with a commit or with none.
    ///
    /// Made here rather than borrowed from the checkout this is compiled in: a
    /// guest is staged a snapshot with no `.git`, and the test, standing in
    /// that copy, would report the rule as broken when it was the fixture that
    /// was not a worktree.
    fn worktree(committed: bool) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("a directory");
        let git = |args: &[&str]| {
            let out = wsb::git_backend::git_command()
                .args(args)
                .current_dir(dir.path())
                .output()
                .unwrap_or_else(|e| panic!("git {args:?}: {e}"));
            assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
        };
        git(&["init", "--quiet"]);
        wsb::settings::RepoSettings {
            name: "fixture".to_string(),
            alias: "fixture".to_string(),
            templates_root: ".".to_string(),
            version: wsb::settings::VersionSettings::at_major(0),
        }
        .save(dir.path())
        .expect("managed");
        if committed {
            std::fs::write(dir.path().join("README"), "x\n").expect("a file");
            git(&["add", "README"]);
            git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "--quiet", "-m", "first"]);
        }
        dir
    }

    /// TEST20013: an ordinary command in a committed worktree runs beside the
    /// daemon; `--no-daemon`, a directory that is no worktree, and a worktree
    /// with no commit yet all stay in their own process.
    ///
    /// Running beside the daemon is what puts a terminal's run in the
    /// workbench's activity panel. Nothing did that: the decision went with the
    /// code it used to share a function with, and every command line ran
    /// unseen. The first-commit case is the one that must not attach — the
    /// daemon refuses a worktree with no identity, and the commit's own hook
    /// would then refuse the commit.
    #[test]
    fn test20013_which_runs_go_beside_the_daemon() {
        let committed = worktree(true);
        assert!(
            !runs_without_the_daemon(Some(committed.path()), false),
            "an ordinary command in a committed worktree must report to the daemon"
        );
        assert!(runs_without_the_daemon(Some(committed.path()), true), "--no-daemon means what it says");
        assert!(runs_without_the_daemon(None, false), "no worktree, nothing to serve");
        let fresh = worktree(false);
        assert!(
            runs_without_the_daemon(Some(fresh.path()), false),
            "a worktree with no commit has no identity for a daemon to serve"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::owns_templates;
    use wsb::state::RunCache;
    use std::fs;
    use std::path::PathBuf;

    /// TEST8826: a repository owns the templates inside its own boundary, and
    /// only those.
    ///
    /// `--recursive` decides what to update from this. The first version asked
    /// whether a template sat under any OTHER repository in the tree — which is
    /// true of every template in a nested repository, because its path starts
    /// with its parent's. So every nested repository in the fleet reported
    /// owning nothing, and `wsb update --recursive` silently skipped all of
    /// them: fourteen top-level projects updated, every capdag mirror and every
    /// cartridge passed over with "no templates of their own".
    ///
    /// Both directions are asserted, because getting one right is what made the
    /// bug look plausible: the parent must NOT claim its child's template, and
    /// the child MUST claim it.
    #[test]
    fn test8826_ownership_follows_the_nearest_repository_boundary() {
        let temp = tempfile::tempdir().expect("a scratch directory");
        let root = temp.path();
        let nested = root.join("family/member");
        fs::create_dir_all(&nested).expect("the nested repository");

        // A template belonging to the nested repository, and nothing else.
        fs::write(nested.join("Cargo.toml.wstemplate"), "x").expect("the template");

        let boundaries = vec![root.join("family"), nested.clone()];
        let cache = RunCache::new();

        assert!(
            owns_templates(&nested, &boundaries, &cache)
                .expect("the nested repository is scanned"),
            "a repository owns the template sitting directly in it"
        );
        assert!(
            !owns_templates(&root.join("family"), &boundaries, &cache)
                .expect("the parent is scanned"),
            "a parent must not claim a template that belongs to a repository nested in it"
        );

        // And a template the parent DOES own is found, so the exclusion is not
        // simply refusing everything under a parent. A fresh cache, because the
        // scan of `family` a moment ago is remembered and this adds a file to
        // it — the run this models never does that, which is the claim
        // `RunCache::note_written` enforces.
        fs::write(root.join("family/own.wstemplate"), "x").expect("the parent's own template");
        assert!(
            owns_templates(&root.join("family"), &boundaries, &RunCache::new())
                .expect("the parent is scanned again"),
            "a template outside every nested repository belongs to the parent"
        );

        let _ = PathBuf::new();
    }
}

#[cfg(test)]
mod wstemplate_entry_tests {
    //! What `wsb init` writes into a project's `.wsb/repo.json`.
    //!
    //! Two fields, and both were wrong for a nested project. The scan root is
    //! where peers are looked for, so an alias in another superrepo could not
    //! be resolved — 33 references in this worktree, every render. The alias
    //! is derived from a name that git does not require to match the directory
    //! it sits in, so where they disagree a project's alias is one nobody
    //! reading the tree could guess.

    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// Make `repo/path` a submodule of `repo`, recorded under `name`.
    fn declare(repo: &Path, name: &str, path: &str) {
        let modules = repo.join(".gitmodules");
        let mut text = fs::read_to_string(&modules).unwrap_or_default();
        text.push_str(&format!(
            "[submodule \"{name}\"]\n\tpath = {path}\n\turl = git@example.com:{name}.git\n"
        ));
        fs::write(&modules, text).unwrap();
        fs::create_dir_all(repo.join(path)).unwrap();
    }

    /// TEST11364: a nested project scans the OUTERMOST superproject.
    ///
    /// The immediate parent is not enough: a cartridge's manifest names both
    /// `capdag_rs` under `capdag/` and `capdag_cartridge_sdk_rs` under
    /// `cartridge-sdks/`, and with its own superrepo as the root it can see
    /// neither.
    #[test]
    fn test11364_a_nested_project_scans_the_whole_workspace() {
        let place = TempDir::new().unwrap();
        let worktree = place.path();
        declare(worktree, "capdag", "capdag");
        declare(&worktree.join("capdag"), "capdag-objc", "capdag-objc");

        let nested = worktree.join("capdag/capdag-objc");
        let (alias, root) = default_alias_and_root(&nested).expect("an alias and root are derived");

        assert_eq!(root, "../..", "the templates root must be the outermost superproject");
        assert_eq!(alias, "capdag_objc");
    }

    /// TEST11365: a dash in the name becomes an underscore in the alias.
    ///
    /// An alias is a Tera identifier. `projects.capdag-cartridge-sdk` parses as
    /// subtraction, so a hyphenated alias is a project no template can name —
    /// which is how hand-written relative paths get into manifests.
    #[test]
    fn test11365_dashes_become_underscores() {
        let place = TempDir::new().unwrap();
        let worktree = place.path();
        declare(worktree, "cartridge-sdks", "cartridge-sdks");
        declare(
            &worktree.join("cartridge-sdks"),
            "capdag-cartridge-sdk-objc",
            "capdag-cartridge-sdk-objc",
        );

        let nested = worktree.join("cartridge-sdks/capdag-cartridge-sdk-objc");
        let (alias, _) = default_alias_and_root(&nested).expect("an alias is derived");
        assert_eq!(alias, "capdag_cartridge_sdk_objc");
        assert!(!alias.contains('-'), "{alias}");
    }

    /// TEST11366: a recorded name that disagrees with its directory is refused.
    ///
    /// Git allows it and the alias comes from the name, so the two disagreeing
    /// produces an alias that cannot be guessed from the tree. Which of them is
    /// wrong is a question about the repository, so it is asked rather than
    /// answered here.
    #[test]
    fn test11366_a_name_that_disagrees_with_its_directory_is_refused() {
        let place = TempDir::new().unwrap();
        let worktree = place.path();
        declare(worktree, "something-else", "capdag-objc");

        let nested = worktree.join("capdag-objc");
        let error = default_alias_and_root(&nested)
            .expect_err("a name that disagrees with its directory must be refused");
        let said = format!("{error:#}");
        assert!(said.contains("something-else"), "{said}");
        assert!(said.contains("capdag-objc"), "{said}");
        assert!(said.contains(".gitmodules"), "{said}");
    }

    /// TEST11367: a project that is nobody's submodule scans itself.
    #[test]
    fn test11367_a_standalone_project_scans_itself() {
        let place = TempDir::new().unwrap();
        let alone = place.path().join("my-thing");
        fs::create_dir_all(&alone).unwrap();
        let (alias, root) = default_alias_and_root(&alone).expect("an alias is derived");
        assert_eq!(root, ".");
        assert_eq!(alias, "my_thing");
    }
}