htl-cli 0.17.0

htl command line (also `cargo htl`): check / run / test / fmt / build / pkg / new for Teal projects
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
//! htl CLI. Also built as `cargo-htl` so `cargo htl <verb>` works.
//!
//! - `htl check <paths...>`   type-check files or directories
//! - `htl gen <file.tl>`      emit readable Lua (escape hatch)
//! - `htl run <file.tl|.hb>`  type-check then execute (strict: type errors abort)
//! - `htl build <dir>`        compile a tree of `.tl` into one stripped-bytecode bundle
//! - `htl bundle info <.hb>`  print what a bundle records, without running it
//! - `htl lsp`                a language server on stdio; its diagnostics are `htl check`'s

use htl::cache;
mod junit;
mod lsp;
mod pin;
pub mod report;
mod scaffold;

/// Output format of every command that has `--format`. One enum, so its help must be
/// true of all of them: `check` / `test` / `fix` / `unused` / `adopt` print their JSON
/// document on stdout and nothing on stderr, and their text form on stderr only, so the
/// two never mix; `cache status` / `bundle info` / `resolve` are reports rather than runs,
/// so both of their forms go to stdout. The exit code is the same in either form.
#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
enum Format {
    /// Human-readable lines
    Text,
    /// One JSON document on stdout (README, "Machine-readable output":
    /// https://github.com/ynishi/htl#machine-readable-output)
    Json,
}

/// How `htl check` grains its cache. Separate from whether it caches at all, which is
/// `--no-cache`.
#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
enum CacheModeArg {
    /// One entry per module: an edit costs that module and what depends on it
    PerModule,
    /// One entry per run: any edit re-checks everything, a run with no edits reads one file
    WholeRun,
}

#[derive(Subcommand)]
enum TypesCmd {
    /// Copy a library's declarations from teal-types into `types/`, and record which
    /// commit they came from
    Add {
        /// The library as teal-types names it (`luasocket`, `lpeg`, …)
        library: String,
        /// Take them from a checkout of teal-types already on disk instead of fetching
        #[arg(long)]
        from: Option<PathBuf>,
        /// Replace declarations that are already in `types/`
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum PkgCmd {
    /// Fetch every dependency `mlua-pkg.toml` declares and write `mlua-pkg.lock`
    Install,
    /// Write a dependency into `mlua-pkg.toml`; `install` is what fetches it
    Add {
        /// The name `require()` will use for it
        name: String,
        /// Remote git URL
        git: String,
        /// Pin to a tag: exact (`v1.0.0`), or a prefix that follows its patches (`v1.0`)
        #[arg(long)]
        tag: Option<String>,
        /// Pin to a commit
        #[arg(long)]
        rev: Option<String>,
        /// Track a branch (a build from it is not reproducible)
        #[arg(long)]
        branch: Option<String>,
        /// The subdirectory `require()` resolves through, when it is not the one the
        /// package declares
        #[arg(long)]
        entry: Option<PathBuf>,
        /// Copy the package into this directory instead of linking it (manifest-relative,
        /// rewritten by every install)
        #[arg(long)]
        target_dir: Option<PathBuf>,
    },
    /// Refresh dependencies, bump the pins that follow releases, then install
    Update {
        /// One dependency; every one when omitted
        name: Option<String>,
        /// Print the plan and write nothing
        #[arg(long)]
        dry_run: bool,
        /// Bump exact tag pins too, to the highest release the remote has
        #[arg(long)]
        force: bool,
    },
    /// Remove cached packages the lockfile no longer refers to
    Clean {
        /// Remove the whole cache rather than the unreferenced entries
        #[arg(long)]
        all: bool,
    },
    /// Take a dependency's source into `patches/<dep>/`: a copy the project owns, edits
    /// and commits, which install resolves the dependency from
    Patch {
        /// The dependency as `mlua-pkg.toml` names it
        dep: String,
        /// Refresh the copy even when it has uncommitted changes (they are discarded)
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum CacheCmd {
    /// Delete this project's stored check results
    Clear {
        /// A path inside the project; the store is .htl/cache at the project root, the
        /// nearest htl.toml or mlua-pkg.toml above
        path: Option<PathBuf>,
    },
    /// Report what the store holds
    Status {
        /// A path inside the project; the store is .htl/cache at the project root, the
        /// nearest htl.toml or mlua-pkg.toml above
        path: Option<PathBuf>,
        /// Output format
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
        /// List every entry rather than counting them by kind
        #[arg(long)]
        entries: bool,
    },
}

#[derive(Subcommand)]
enum BundleCmd {
    /// Print what a bundle records: format, the htl that built it, payload kind, the Lua
    /// its bytecode was compiled for, entry, modules, host-provided names
    Info {
        /// The `.hb` file
        file: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
    },
}

impl From<CacheModeArg> for cache::Mode {
    fn from(m: CacheModeArg) -> Self {
        match m {
            CacheModeArg::PerModule => cache::Mode::PerModule,
            CacheModeArg::WholeRun => cache::Mode::WholeRun,
        }
    }
}

use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use htl::BuildTarget;
use htl::Htl;
use htl::bundle::Bundle;
// The project layer: which files a check walks, what it replays from the run cache and
// what it keeps there, and which of a run's findings are said. Shared with `include_tl!`,
// which asks the same of the same store.
use htl::project;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

#[derive(Parser)]
#[command(
    name = "htl",
    version,
    about = "Teal, hidden: run / check / build .tl on mlua",
    long_about = "\
Teal, hidden: run / check / build .tl on mlua.

htl is a toolchain for Teal, and a way to embed one. It type-checks `.tl` sources with \
Teal's own checker, runs and tests them on an embedded mlua state, formats them, and \
links them into a single stripped-bytecode bundle. A Rust host embeds the same engine, \
so the scripts it ships are checked when the host is built rather than when its user \
first runs one.

The guide, with every command and what a project looks like:
  https://github.com/ynishi/htl

The API a Rust host holds — `include_tl!`, `#[host_module]`, the run cache:
  https://docs.rs/htl"
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Type-check .tl files or directories (htl lints are reported as `lint:`)
    ///
    /// A module reached through `require` is checked with the file that required it, and
    /// what has not changed is replayed from `.htl/`. README, "Lints":
    /// https://github.com/ynishi/htl#lints-htl-check-include_tl
    #[command(after_long_help = "\
Examples:
  htl check src                  every .tl under src/
  htl check src --strict         every warn counts as deny: warnings and lints fail
  htl check src --lint nil-index=deny,no-any=warn
                                 one rule fails the run, another is advice
  htl check src --lint -tl:hint  a warning kind of the Teal compiler silenced
  htl check --list-lints         every rule with its default level, then exit
  htl check --explain union-exhaustive
                                 why the rule exists and how to decide its cases
  htl check src --statistics     how many findings each rule produced, not the findings

The store is .htl/cache at the project root, the nearest htl.toml or mlua-pkg.toml above
the paths; --no-cache skips it, --explain-cache says why a lookup missed.
Caching: https://github.com/ynishi/htl#caching
")]
    Check {
        paths: Vec<PathBuf>,
        /// Treat every `warn` as `deny`: warnings and lints fail the run
        #[arg(long)]
        strict: bool,
        /// Rule levels over the defaults, e.g. `nil-index=deny,no-any=warn` (`-rule` =
        /// allow, `+rule` = warn)
        // A spec that silences a rule starts with `-`, and without this clap reads
        // `--lint -contract` as a cluster of short flags and answers `unexpected argument
        // '-c'`: the documented way to turn one rule off never reached the spec parser.
        #[arg(long, allow_hyphen_values = true)]
        lint: Option<String>,
        /// List every lint rule with its default level and exit
        #[arg(long)]
        list_lints: bool,
        /// Print a rule's explanation — what it catches, why, the fix, the judgment call —
        /// and exit; the name is the one a finding prints in `[htl <rule>]`
        #[arg(long, value_name = "RULE")]
        explain: Option<String>,
        /// Output format
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
        /// Check even if an identical run is cached, and do not store this one
        #[arg(long)]
        no_cache: bool,
        /// How the cache is grained; overrides `[cache] mode` in htl.toml
        #[arg(long, value_enum)]
        cache_mode: Option<CacheModeArg>,
        /// Say why the cache was not used, and what this run did with it
        #[arg(long)]
        explain_cache: bool,
        /// Print how many findings each rule produced, instead of the findings
        /// themselves: one row per rule with at least one, count first, `[*]` when every
        /// finding of it has a fix `htl fix` applies, `[-]` when only some do or only
        /// with `--unsafe`, `[ ]` when none has one; rules with no finding are not
        /// listed. The summary line and the exit code are unchanged. With `--format
        /// json`, `statistics` carries the same rows and `diagnostics` is empty
        #[arg(long)]
        statistics: bool,
    },
    /// Run tests: every `.tl` that requires the test library, one isolated state per file
    ///
    /// README, "Tests": https://github.com/ynishi/htl#tests
    #[command(after_long_help = "\
Examples:
  htl test                       every .tl that requires htl.test
  htl test tests --filter parser only tests whose \"suite > name\" contains it
  htl test --coverage --coverage-lines
                                 which lines of each module the suite never reached
  htl test --junit report.xml    also write the run as a JUnit report, for a CI
")]
    Test {
        paths: Vec<PathBuf>,
        /// Only run tests whose "suite > name" contains this substring
        #[arg(long)]
        filter: Option<String>,
        /// Assertion library module consulted for the verdict (must expose `run(filter)`)
        #[arg(long, default_value = htl::testing::DEFAULT_LIB)]
        lib: String,
        /// Lint rules on top of the defaults, e.g. `+no-any`
        #[arg(long, allow_hyphen_values = true)]
        lint: Option<String>,
        /// Stop at the first failure (within a file, and across files)
        #[arg(long)]
        fail_fast: bool,
        /// Pass when no test file is found (the summary still says 0 files)
        ///
        /// Without it, finding nothing exits 1: a test file is found by what it loads, not
        /// by its name, so a wrong `--lib` or a wrong directory finds nothing and would
        /// otherwise pass silently. For a project whose gate runs `htl test` before its
        /// first test exists; remove the flag when that test arrives. With test files
        /// present it changes nothing.
        #[arg(long)]
        allow_empty: bool,
        /// Print every test with its time (default: only failures and files)
        #[arg(short, long)]
        verbose: bool,
        /// Only failures (with details), errors, and the summary line; no per-file `ok` lines
        #[arg(short, long, conflicts_with = "verbose")]
        quiet: bool,
        /// Also print tests slower than this many milliseconds
        #[arg(long, value_name = "MS")]
        slow: Option<f64>,
        /// Rewrite snapshots (`to_match_snapshot`) that differ instead of failing
        #[arg(long)]
        update: bool,
        /// Report executed statements per `.tl` module the tests reached (slower: a line hook)
        #[arg(long)]
        coverage: bool,
        /// With --coverage, also list the unexecuted line ranges of each module
        #[arg(long, requires = "coverage")]
        coverage_lines: bool,
        /// Also write the coverage as an lcov tracefile here (implies --coverage)
        #[arg(long, value_name = "FILE")]
        lcov: Option<PathBuf>,
        /// Also write the run as a JUnit XML report here, for a CI that reads test results
        #[arg(long, value_name = "FILE")]
        junit: Option<PathBuf>,
        /// Seed the random stream tests draw from; printed every run, so a failure repeats
        #[arg(long)]
        seed: Option<u64>,
        /// Output format
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
        /// Check and generate every file even if a cached form is available, and store none
        #[arg(long)]
        no_cache: bool,
        /// Say why the cache was not used, and what this run did with it
        #[arg(long)]
        explain_cache: bool,
    },
    /// Apply the fixes diagnostics carry (safe ones by default)
    ///
    /// The working tree is the undo: a file git reports as modified or staged is refused
    /// (`--allow-dirty`), and so is a file outside a repository (`--allow-no-vcs`), since a
    /// rewrite git could not give back is one nobody can review. `--dry-run` reports
    /// without writing; `--diff` prints a unified diff per file instead, and a `suggest`
    /// fix — never applied — is listed as skipped and printed there as a second diff
    /// headed `<file> (suggested)`. The `.d.tl` declarations the project publishes are
    /// regenerated first, as `htl check` regenerates them; a dry run works them out and
    /// writes none.
    ///
    /// README, "Fixing": https://github.com/ynishi/htl#fixing-htl-fix
    #[command(after_long_help = "\
Examples:
  htl fix src                    apply the safe fixes to every .tl under src/
  htl fix src --diff --dry-run   what would change, as a unified diff per file
  htl fix src --rule forward-ref only that rule's fixes
  htl fix src --unsafe           also the fixes that may change what the program does
")]
    Fix {
        paths: Vec<PathBuf>,
        /// Only fixes of these rules: any rule `htl check --list-lints` names, or
        /// `forward-ref` / `tl:error`, the classes an error's fix is filed under
        #[arg(long, value_delimiter = ',')]
        rule: Vec<String>,
        /// Also apply `unsafe` fixes (may change what the program does)
        #[arg(long = "unsafe")]
        unsafe_fixes: bool,
        /// Compute and report, write nothing
        #[arg(long)]
        dry_run: bool,
        /// Like --dry-run, and print a unified diff per file that would change
        #[arg(long)]
        diff: bool,
        /// Fix files that git reports as modified or staged
        #[arg(long)]
        allow_dirty: bool,
        /// Fix files that are not inside a git repository
        #[arg(long)]
        allow_no_vcs: bool,
        /// Exit 1 when any file was changed (for CI)
        #[arg(long)]
        exit_non_zero_on_fix: bool,
        /// Output format
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
    },
    /// Write the `.d.tl` files this project declares: those `#[host_module(dts = ..)]` /
    /// `#[teal(dts = ..)]` ask for in a Rust crate, without building it, and the module
    /// each `---@contract` type is declared in (check / run / test / build do both)
    ///
    /// Each declaration is reported as `wrote`, `unchanged`, or `not written`, one line
    /// each. The commands that generate before they work (`check` / `run` / `test` /
    /// `build` / `fix` / `unused` / `adopt` / `resolve` / `gen`) do the same job first and print only
    /// what moved, prefixed `dts:` — `dts: wrote …`, `dts: not written: …`, `dts: left in
    /// place: …` — and never an `unchanged` line; a dependency's declarations land under
    /// `types/<crate>/` from every one of them. The exit code is about `not written` and
    /// nothing else: non-zero when a declaration this command was asked to write could
    /// not be written. A file already under `types/` that no dependency ships any more is
    /// reported as `left in place` — nothing was asked for, nothing is deleted, and the
    /// exit code does not move.
    Dts {
        /// Crate root or any path inside it (default: current directory)
        dir: Option<PathBuf>,
    },
    /// Write a run-time shape (an lshape schema) for each record and enum this project
    /// declares, and the `.d.tl` that types it
    ///
    /// Reads the project's own `.tl` files under its source directory (a `.d.tl`, the test
    /// root and `types/` are not read) and writes, per module that declares a record or an
    /// enum, `<source>/shapes/<module>.lua` — a Lua module returning one shape per
    /// declaration, written against `require("lshape")` — and `<types>/shapes/<module>.d.tl`,
    /// which declares each as `lshape.Schema<module.Record>`; and once
    /// `<types>/lshape.d.tl`, the declaration of lshape those are written against. A value
    /// that arrives from outside is then narrowed once, at the boundary, with
    /// `lshape.check.assert(v, S.Record)`, and read without a cast after it. The record is
    /// the source: nothing generated is to be edited. What is lowered, how, and what is
    /// not (the record a file returns, which is the module; `record R is I`; a union of
    /// records) is the module doc of `htl::shapes`.
    ///
    /// Reports `shapes: wrote <path>` or `shapes: current <path>` for each file, on stderr;
    /// a file whose text would not change is not touched. A target that exists and does
    /// not begin with the line `htl shapes` writes is not one of its own and is never
    /// overwritten or removed. A module that declares nothing to lower any more has the
    /// files an earlier run wrote for it removed (`shapes: removed <path>`); one that is
    /// refused keeps them, and each is reported as `left as it was and is stale`. The exit code is non-zero when a file fails its check (it is lowered
    /// and written all the same, so a file that requires a shapes module before the first
    /// run wrote it is clean on the second), when a declaration has no shape (named at its field, and nothing is written for that
    /// module), when two modules need each other's shapes, when a module is named `shapes`
    /// (the namespace the generated modules sit in), when a target is not its own to
    /// overwrite, and when `require("lshape")` resolves to no Lua or Teal module — lshape is
    /// not vendored or installed — in which case nothing is written.
    Shapes {
        /// Project root or any path inside it (default: current directory)
        dir: Option<PathBuf>,
    },
    /// Create a new Teal project directory
    ///
    /// README, "Layout of a project": https://github.com/ynishi/htl#layout-of-a-project-htl-new
    #[command(after_long_help = "\
Examples:
  htl new hello                    src/main.tl, a module, tests/, mlua-pkg.toml
  htl new hello --lib              a library: no entry script
  htl new hello --embed            the same, plus a Rust host (--target bin)
  htl new hello --target cdylib --lib
                                   a library behind a C ABI, for a caller that is not Rust
  htl new hello --embed --htl main
                                   built against the unreleased htl (a git pin on main)
  htl new hello --embed --htl path:../htl
                                   built against a local checkout of this repository
  htl new hello --no-x             without the htlx dependency the manifest gets by default

Build targets: https://docs.rs/htl/latest/htl/build_target/enum.BuildTarget.html
Layout of a project: https://github.com/ynishi/htl#layout-of-a-project-htl-new
")]
    New {
        name: String,
        /// Library only (no src/main.tl)
        #[arg(long)]
        lib: bool,
        /// Also emit a Rust host: shorthand for --target bin
        #[arg(long)]
        embed: bool,
        /// What will run this project's output: a target writes Cargo.toml + src/lib.rs
        /// (the #[host_module], the embedded module, preload) and, when there is an entry
        /// script, a thin src/main.rs
        #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
        target: Option<String>,
        /// The htl the project depends on: `release`, `main`, or `path:<checkout>`.
        /// Without it, the htl this binary was built with — its version on crates.io, or
        /// the checkout it was built in
        #[arg(long, value_name = "REQ")]
        htl: Option<String>,
        /// Leave the htlx (htl-x collections) dependency out of mlua-pkg.toml
        #[arg(long)]
        no_x: bool,
    },
    /// Fill in the scaffold files that are missing in an existing directory
    Init {
        dir: Option<PathBuf>,
        #[arg(long)]
        lib: bool,
        /// Shorthand for --target bin
        #[arg(long)]
        embed: bool,
        /// Fill in this target's files, and report the ones that were already there
        #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
        target: Option<String>,
        /// The htl the project depends on: `release`, `main`, or `path:<checkout>`.
        /// Without it, the htl this binary was built with — its version on crates.io, or
        /// the checkout it was built in
        #[arg(long, value_name = "REQ")]
        htl: Option<String>,
        /// Leave the htlx (htl-x collections) dependency out of mlua-pkg.toml
        #[arg(long)]
        no_x: bool,
    },
    /// Move the htl a project `htl new` already wrote depends on
    ///
    /// Rewrites `Cargo.toml`'s `htl` line (and `htl-mq`'s, under `--target window`),
    /// `mise.toml`, and `[toolchain] htl` in `htl.toml` when the project has one, then runs
    /// `cargo update` so `Cargo.lock` agrees — the same four things `--htl` decides for a
    /// project that does not exist yet (see `htl new`). `release` is this CLI's own
    /// version, `main` its repository's branch, `path:<checkout>` a local clone — a
    /// relative one resolved against the current directory, the way the shell reads it,
    /// not against `dir`, and refused when there is no `crates/htl/Cargo.toml` under it;
    /// a number is refused, the way `htl new --htl <number>` is, naming the release's own
    /// CLI instead. `--no-update` writes the three files and prints the `cargo update` to
    /// run by hand rather than running it.
    ///
    /// A `Cargo.toml` whose `htl` (or `htl-mq`) line this command does not recognise —
    /// anything but a bare version, or a table naming exactly one of `version` / `git` +
    /// `branch` / `path` plus an optional `features` list — is left untouched: the fallback
    /// is the `[patch.crates-io]` block this refusal prints. README, "Running against an
    /// unpublished htl": https://github.com/ynishi/htl#running-against-an-unpublished-htl
    ///
    /// Exit 0 once everything above is moved; 2 when `--htl` is not one of the three (or
    /// names no checkout), there is no `Cargo.toml` to move, the line is not recognised,
    /// or `cargo update` fails (the files are rewritten either way — only the lock is left
    /// unresolved).
    #[command(after_long_help = "\
Examples:
  htl pin path:../htl            from this project's own directory, move it onto a sibling
                                  checkout, for a change that has to be built against it
  htl pin release                move it back once that checkout's change is released
")]
    Pin {
        /// `release`, `main`, or `path:<checkout>` — the same names `htl new --htl` takes
        htl: String,
        /// Project root or any path inside it (default: current directory)
        dir: Option<PathBuf>,
        /// Write the three files and print the `cargo update` to run, rather than running it
        #[arg(long)]
        no_update: bool,
    },
    /// Package management at the nearest `mlua-pkg.toml` project root: install / add /
    /// update / clean / patch, through mlua-pkg's library rather than its binary
    Pkg {
        #[command(subcommand)]
        cmd: PkgCmd,
    },
    /// Bring declarations for a library into `types/`
    Types {
        #[command(subcommand)]
        cmd: TypesCmd,
    },
    /// Manage the check cache
    ///
    /// README, "Caching": https://github.com/ynishi/htl#caching
    Cache {
        #[command(subcommand)]
        cmd: CacheCmd,
    },
    /// Format .tl files in place (indentation / blank lines / trailing whitespace)
    Fmt {
        paths: Vec<PathBuf>,
        /// Do not write; exit 1 if any file would change
        #[arg(long)]
        check: bool,
        /// Indent width in spaces (default: `[fmt] indent` in htl.toml, else 3)
        #[arg(long)]
        indent: Option<usize>,
    },
    /// Emit readable Lua for one .tl file (escape hatch)
    ///
    /// Line n of the output is line n of the .tl, so a run-time error names the .tl line.
    /// A comment-only line (`--` or `---` after indentation, not a `--[[` opener) survives
    /// verbatim at its line, `---` doc included, and so do the comment lines after the last
    /// line of code (the `---` after a module's `return`): the output ends with the last of
    /// them. A trailing comment (after code) and a block comment (`--[[ ... ]]`) do not
    /// survive: the trailing one is dropped from its line, and every line of the block comes
    /// out empty, a `--` line inside it included.
    Gen {
        file: PathBuf,
        #[arg(short, long)]
        out: Option<PathBuf>,
    },
    /// Run a .tl script or a .hb bundle
    Run {
        file: PathBuf,
        #[arg(trailing_var_arg = true)]
        args: Vec<String>,
    },
    /// Compile a directory of .tl into a stripped-bytecode bundle
    ///
    /// A bundle is the `hb` target, so this refuses a project whose `[build] target` is
    /// another one — a `bin` or a `cdylib` is built with `cargo build`.
    ///
    /// README, "Bundles": https://github.com/ynishi/htl#bundles-htl-build
    #[command(after_long_help = "\
Examples:
  htl build src/main.tl -o app.hb
                                 the entry's require closure, as one bundle
  htl build src/main.tl -o app.hb --debug
                                 keep line numbers and local names in the bytecode
  htl build src/main.tl -o app.hb --host mymod
                                 leave a module the host provides out of the bundle
  htl run app.hb                 run what was built

Caching: https://github.com/ynishi/htl#caching
")]
    /// The closure is judged by the project's `[lint.rules]` as `htl check` judges it — a
    /// rule the project turned off is not reported here either — and no bundle is written
    /// when it fails. A project whose `[build] target` is not `hb` is refused, naming the
    /// command that does build it: the key records a decision the project made rather
    /// than a note about itself, and dropping it from `htl.toml` is how a project with
    /// Rust in it asks for a bundle anyway.
    Build {
        /// Entry `.tl` file: it and everything it requires are bundled, replaying from
        /// the run cache what still holds (a directory bundles every `.tl` under it, the
        /// older snapshot form, which is not cached)
        entry: PathBuf,
        #[arg(short, long, default_value = "app.hb")]
        out: PathBuf,
        /// Entry module name when `entry` is a directory
        #[arg(short, long, default_value = "main")]
        main: String,
        /// Keep debug info (line numbers, local names) in the bytecode
        #[arg(long)]
        debug: bool,
        /// Store generated Lua source instead of bytecode: for a big-endian target, a Lua
        /// with non-default number types, or a bundle that must outlive a Lua upgrade
        #[arg(long)]
        source: bool,
        /// Modules to bundle that only a dynamic require reaches (also `[build] extra`)
        #[arg(long, value_delimiter = ',')]
        extra: Vec<String>,
        /// Modules the host provides, besides the project's own list (`#[host_module]`, `[build] host`, `std.*`; `.d.tl`-only modules are implied)
        #[arg(long, value_delimiter = ',')]
        host: Vec<String>,
        /// Generate every module even if its cached form still holds, and do not store
        /// (the directory form is never cached)
        #[arg(long)]
        no_cache: bool,
        /// Say why the cache was not used, and what this run did with it
        #[arg(long)]
        explain_cache: bool,
    },
    /// Report what no entry's `require` closure reaches: modules, and `mlua-pkg.toml`
    /// dependencies
    ///
    /// README, "Unused": https://github.com/ynishi/htl#unused-htl-unused
    #[command(after_long_help = "\
Examples:
  htl unused                     modules and dependencies no entry reaches
  htl unused --exit-non-zero-on-unused
                                 the same report, and a non-zero exit for a CI
  htl unused --format json       the same report as one JSON document
")]
    Unused {
        /// What to report on (default: the working directory). The walk is the project's
        /// either way: a module reached only from `tests/` is reached
        paths: Vec<PathBuf>,
        /// Output format
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
        /// Exit 1 when anything is reported (for CI)
        #[arg(long)]
        exit_non_zero_on_unused: bool,
        /// Build the graph from a fresh check even if a cached one is available, and
        /// store none
        #[arg(long)]
        no_cache: bool,
        /// Say why the cache was not used, and what this run did with it
        #[arg(long)]
        explain_cache: bool,
    },
    /// Report how many declarations carry each of htl's nine markers, and where
    ///
    /// `applicable` is how many declarations a lint has found the evidence to call
    /// candidates for a marker. Two rows have one so far: `---@struct`'s is what
    /// `unmarked-struct` would report, a record built whole at every one of its
    /// construction sites and left unmarked; `---@sealed`'s is what `unmarked-sealed`
    /// would report, a record built and cast only in the file that declares it and left
    /// unmarked. Every other row is empty (`-`), not `0`: a feature with no evidence
    /// counted is a different claim from a feature nothing is applicable to, and this
    /// command does not guess between them. `--detail` lists each candidate after the
    /// row's marked declarations, with `(applicable: <reason>, N site(s))`. It is a
    /// report, not a gate: the exit code is always 0.
    /// README, "Adoption": https://github.com/ynishi/htl#adoption-htl-adopt
    #[command(after_long_help = "\
Examples:
  htl adopt                      which of htl's nine markers this project writes, and how much
  htl adopt --detail             the same, plus every marked declaration's file, line and name
  htl adopt --format json        the same report as one JSON document
")]
    Adopt {
        /// What to report on (default: the working directory). The walk behind the
        /// census is always the whole project, so the check resolves and replays as
        /// usual; the counts are of the files under the paths given here.
        paths: Vec<PathBuf>,
        /// Output format
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
        /// List every marked declaration under the table, file:line and name, grouped by
        /// feature, and each `applicable` candidate after them; the plain form prints
        /// the table alone
        #[arg(long)]
        detail: bool,
        /// Build the census from a fresh check even if a cached one is available, and
        /// store none
        #[arg(long)]
        no_cache: bool,
        /// Say why the cache was not used, and what this run did with it
        #[arg(long)]
        explain_cache: bool,
    },
    /// Which file `require("<module>")` resolves to, and what that hides
    ///
    /// The whole chain in search order: what is read, what is reachable and not read, and
    /// which crate or dependency each one came from. An override on the search path is the
    /// mechanism working, and this is how to see it. README, "Which file a name resolves
    /// to": https://github.com/ynishi/htl#which-file-a-name-resolves-to-htl-resolve
    #[command(after_long_help = "\
Examples:
  htl resolve mq                 the chain for require(\"mq\")
  htl resolve socket.http        a name with dots, as a require spells it
  htl resolve mq --format json   the same rows as one JSON document

Exits 1 when the name resolves to nothing, when two files implement it, or when a file of
the project implements a name the host provides, so a script can ask.

`htl.test` is answered like a host-provided name: no file of the project implements it
(`htl test` preloads it into the state it runs), and its one row is the declaration the
binary carries, `provided by the environment`.
")]
    Resolve {
        /// The module name a `require` would spell (`mq`, `socket.http`)
        module: String,
        /// A path inside the project (default: the working directory)
        path: Option<PathBuf>,
        /// Output format
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
    },
    /// Read a `.hb` bundle without running it
    ///
    /// README, "Bundles": https://github.com/ynishi/htl#bundles-htl-build
    Bundle {
        #[command(subcommand)]
        cmd: BundleCmd,
    },
    /// A language server on stdio whose diagnostics are `htl check`'s
    ///
    /// Speaks the Language Server Protocol on stdin and stdout; an editor starts it as a
    /// child process. A file is checked when it is opened and when it is saved, from disk,
    /// under the project it belongs to: the same resolution rules, lint levels,
    /// `-- htl: allow(..)` comments and `.d.tl` declarations `htl check` applies, and the
    /// same messages and lines. Saving a file also re-checks the other open files that
    /// require it. A change to `htl.toml`, `mlua-pkg.toml`, `mlua-pkg.lock`, a `.d.tl` under
    /// `types/` or the Rust `htl dts` reads re-checks the open files of that project when the
    /// client watches files (`didChangeWatchedFiles`); for any client, the three
    /// manifests are noticed at the next open or save in the project. Diagnostics are not computed
    /// while typing. Anything the server has to say about itself goes to stderr.
    Lsp,
}

/// The command line as clap holds it, before any argument is parsed.
///
/// The help is documentation, and the tests that keep it from rotting read it from here
/// rather than from a copy kept beside them: they walk this tree and ask each command,
/// argument and value for the strings it would print.
pub fn command() -> clap::Command {
    <Cli as clap::CommandFactory>::command()
}

/// `htl::registry::register_installer("htl-std", htl_std::install, htl_std::PROVIDES)`,
/// once.
///
/// This binary links both `htl-core` and `htl-std` at once, which is exactly the seam
/// `htl_core::registry`'s own doc describes ("Why this exists"): `htl-core` cannot depend
/// on `htl-std` back (`htl-std -> htl -> htl-core -> htl-std` would be a cycle), so only a
/// binary that sits above both can hand `htl-core` the function pointer. Doing it here —
/// in `run()`, before anything parses a command — rather than in `htl-core` itself is the
/// whole reason the registry module exists; see that module's doc for the rest. The call
/// goes through `htl::registry` rather than naming `htl-core` directly: `htl` already
/// re-exports it (`pub use htl_core::*`), and this crate has no other reason to depend on
/// `htl-core` itself.
///
/// Registering the same name twice is refused (`register_installer`'s own doc, "Order and
/// duplicates"), so this is behind a `std::sync::Once`: `run()` is the entry both `htl` and
/// `cargo-htl` call, once each per process, which is enough on its own, but an in-process
/// caller could call it more than once without the guard.
fn register_libraries() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        htl::registry::register_installer("htl-std", htl_std::install, htl_std::PROVIDES)
            .expect("\"htl-std\" registered twice");
    });
}

/// Parse the command line and run the command; the exit code.
///
/// An exit of 1 is a verdict — an error in a file, a finding at `deny`, a failing test, a
/// name that resolves to nothing ([`htl::verdict`]). A command that could not get as far
/// as a verdict — a directory in no project, an `htl.toml` that does not parse, a file it
/// cannot read, a flag it does not take — says why and exits 2, whichever command it was
/// (clap exits 2 on a bad flag, and an `Err` from any command lands on the same arm).
pub fn run() -> ExitCode {
    register_libraries();
    // Invoked as `cargo htl ...` -> argv = ["cargo-htl", "htl", ...]; drop the "htl".
    let mut argv: Vec<String> = std::env::args().collect();
    let is_cargo = Path::new(&argv[0])
        .file_stem()
        .and_then(|s| s.to_str())
        .map(|s| s == "cargo-htl")
        .unwrap_or(false);
    if is_cargo && argv.get(1).map(String::as_str) == Some("htl") {
        argv.remove(1);
    }
    match real_main(Cli::parse_from(argv)) {
        Ok(code) => code,
        Err(e) => {
            eprintln!("htl: {e:#}");
            ExitCode::from(2)
        }
    }
}

fn real_main(cli: Cli) -> Result<ExitCode> {
    match cli.cmd {
        Cmd::Check {
            paths,
            strict,
            lint,
            list_lints,
            explain,
            format,
            no_cache,
            cache_mode,
            explain_cache,
            statistics,
        } => cmd_check(
            &paths,
            lint.as_deref(),
            CheckFlags {
                strict,
                list_lints,
                explain_rule: explain,
                json: format == Format::Json,
                use_cache: !no_cache,
                cache_mode: cache_mode.map(Into::into),
                explain: explain_cache,
                statistics,
            },
        ),
        Cmd::Fmt {
            paths,
            check,
            indent,
        } => cmd_fmt(&paths, check, indent),
        Cmd::Test {
            paths,
            filter,
            lib,
            lint,
            fail_fast,
            allow_empty,
            verbose,
            quiet,
            slow,
            update,
            coverage,
            coverage_lines,
            lcov,
            junit,
            seed,
            format,
            no_cache,
            explain_cache,
        } => cmd_test(
            &paths,
            filter.as_deref(),
            &lib,
            lint.as_deref(),
            TestFlags {
                fail_fast,
                allow_empty,
                verbose,
                quiet,
                slow,
                update,
                coverage: coverage || lcov.is_some(),
                coverage_lines,
                lcov,
                junit,
                json: format == Format::Json,
                no_cache,
                explain: explain_cache,
                seed,
            },
        ),
        Cmd::Pkg { cmd } => match cmd {
            PkgCmd::Install => cmd_pkg_install(),
            PkgCmd::Add {
                name,
                git,
                tag,
                rev,
                branch,
                entry,
                target_dir,
            } => cmd_pkg_add(htl::pkg::mlua_pkg::ops::AddSpec {
                name,
                git,
                tag,
                rev,
                branch,
                entry,
                target_dir,
            }),
            PkgCmd::Update {
                name,
                dry_run,
                force,
            } => cmd_pkg_update(htl::pkg::mlua_pkg::ops::UpdateOpts {
                name,
                dry_run,
                force,
            }),
            PkgCmd::Clean { all } => cmd_pkg_clean(all),
            PkgCmd::Patch { dep, force } => cmd_pkg_patch(&dep, force),
        },
        Cmd::Types { cmd } => match cmd {
            TypesCmd::Add {
                library,
                from,
                force,
            } => cmd_types_add(&library, from.as_deref(), force),
        },
        Cmd::Cache { cmd } => match cmd {
            CacheCmd::Clear { path } => cmd_cache_clear(path.as_deref()),
            CacheCmd::Status {
                path,
                format,
                entries,
            } => cmd_cache_status(path.as_deref(), format == Format::Json, entries),
        },
        Cmd::Dts { dir } => cmd_dts(dir.as_deref()),
        Cmd::Shapes { dir } => cmd_shapes(dir.as_deref()),
        Cmd::New {
            name,
            lib,
            embed,
            target,
            htl,
            no_x,
        } => cmd_new(&name, lib, embed, target.as_deref(), htl.as_deref(), no_x),
        Cmd::Init {
            dir,
            lib,
            embed,
            target,
            htl,
            no_x,
        } => cmd_init(
            dir.as_deref(),
            lib,
            embed,
            target.as_deref(),
            htl.as_deref(),
            no_x,
        ),
        Cmd::Pin {
            htl,
            dir,
            no_update,
        } => pin::cmd_pin(&htl, dir, no_update),
        Cmd::Gen { file, out } => cmd_gen(&file, out.as_deref()),
        Cmd::Run { file, args } => cmd_run(&file, &args),
        Cmd::Fix {
            paths,
            rule,
            unsafe_fixes,
            dry_run,
            diff,
            allow_dirty,
            allow_no_vcs,
            exit_non_zero_on_fix,
            format,
        } => cmd_fix(
            &paths,
            FixFlags {
                rule,
                unsafe_fixes,
                dry_run: dry_run || diff,
                diff,
                allow_dirty,
                allow_no_vcs,
                exit_non_zero_on_fix,
                json: format == Format::Json,
            },
        ),
        Cmd::Build {
            entry,
            out,
            main,
            debug,
            source,
            extra,
            host,
            no_cache,
            explain_cache,
        } => cmd_build(
            &entry,
            &out,
            &main,
            htl::link::LinkOptions {
                debug,
                source,
                extra,
                host,
                entry_name: None,
            },
            BuildCache {
                use_cache: !no_cache,
                explain: explain_cache,
            },
        ),
        Cmd::Unused {
            paths,
            format,
            exit_non_zero_on_unused,
            no_cache,
            explain_cache,
        } => cmd_unused(
            &paths,
            UnusedFlags {
                json: format == Format::Json,
                fail_on_unused: exit_non_zero_on_unused,
                use_cache: !no_cache,
                explain: explain_cache,
            },
        ),
        Cmd::Adopt {
            paths,
            format,
            detail,
            no_cache,
            explain_cache,
        } => cmd_adopt(
            &paths,
            AdoptFlags {
                json: format == Format::Json,
                detail,
                use_cache: !no_cache,
                explain: explain_cache,
            },
        ),
        Cmd::Resolve {
            module,
            path,
            format,
        } => cmd_resolve(&module, path.as_deref(), format == Format::Json),
        Cmd::Bundle { cmd } => match cmd {
            BundleCmd::Info { file, format } => cmd_bundle_info(&file, format == Format::Json),
        },
        Cmd::Lsp => lsp::serve(),
    }
}

/// The reporting layer, for the commands that report without a `--format` of their own.
///
/// `htl check` and `htl test` hand their findings to a [`project::Sink`] over a
/// [`report::Out`]; `gen` / `run` / `build` used to loop `eprintln!` over the three
/// vectors themselves, so the same finding read differently depending on which verb was
/// typed. They come through here instead, and there is one renderer again.
///
/// One sink per command run, not per file: what the layer decides once per run — a
/// dependency's error said once, and never on behalf of a file the run checks itself —
/// is then once per *command*, which is what `htl build` over a closure of modules wants.
fn text_sink() -> project::Sink<report::Out> {
    project::Sink::new(report::Out::new(false, false))
}

/// What else a verdict counted besides errors, for a summary line: a finding at `deny`,
/// and under `strict` every warning and lint. Empty when neither. Without it a run that
/// failed on a lint would end in `0 error(s)`.
fn judged(found: &htl::verdict::Findings, policy: &htl::verdict::Policy) -> String {
    let mut out = String::new();
    if policy.capped {
        return out;
    }
    if found.denied > 0 {
        out.push_str(&format!(", {} at deny", found.denied));
    }
    if policy.strict && found.warnings + found.lints > 0 {
        out.push_str(&format!(
            ", {} warning(s) and {} lint(s) under strict",
            found.warnings, found.lints
        ));
    }
    out
}

/// Hand the checker the project's `[lang]`: whether `async` / `await` are keywords in the
/// files it is about to read. For a command that parses without a checker of the project's
/// ([`checker_for`] sets this itself).
fn config_lang(h: &Htl, cfg: &project::Config) -> Result<()> {
    h.set_lang(&project::lang_of(cfg))
}

/// (Re)generate the `.d.tl` files this project declares: the ones a Rust crate's
/// `#[host_module]` / `#[derive(TealRecord)]` ask for, so the checker sees Rust-side
/// modules before any `cargo build`, and the module each `---@contract` type is declared
/// in, which is what an outside author writes their modules against. Quiet unless
/// something was written.
///
/// A contract that could not be published is said here, on every command that generates:
/// `htl check` reports it again as a lint (which `strict` makes fatal) and `htl dts`
/// exits non-zero on it, but `run` / `test` / `build` have neither, and a declaration
/// that is quietly not written is one an outside author finds missing later.
fn auto_dts(start: &Path) -> Result<()> {
    auto_dts_to(start, true)
}

/// [`auto_dts`], writing only when `write` is set. A dry run (`htl fix --dry-run` /
/// `--diff`) works out every declaration the same way and says which it would write, and
/// what it then checks is the declarations as they are on disk — which is why it says so.
fn auto_dts_to(start: &Path, write: bool) -> Result<()> {
    let mut project = None;
    if let Some((root, _, cfg)) = load_config(start)? {
        // The contracts the project's model holds, published from there.
        let model = htl::model::Project::load(&root, cfg)?;
        let contracts: Vec<_> = model.contracts.iter().map(|c| c.terms.clone()).collect();
        let (results, problems) = htl::contract::publish_to(&root, &contracts, write);
        announce_dts_to(&results, &root, write);
        for p in &problems {
            eprintln!("dts: {p}");
        }
        project = Some(root);
    }
    let Some(root) = htl::dts::find_cargo_package_root(start) else {
        return Ok(());
    };
    let results =
        htl::dts::generate_crate_to(&root, write).map_err(|e| anyhow::anyhow!("htl dts: {e}"))?;
    announce_dts_to(&results, &root, write);
    let types_root = project.unwrap_or_else(|| root.clone());
    let report = dep_dts_to(&root, &types_root, write);
    announce_dts_to(&report.written, &types_root, write);
    announce_dep_report(&report, "dts: ");
    Ok(())
}

/// What `htl dts` has to say about the declarations its dependencies ship. Three kinds,
/// kept apart because they mean three different things to the reader and to the exit code
/// — which is the distinction the single `[htl <rule>]` suffix they all used to carry was
/// hiding. None of them is a lint: no rule name, nothing to configure or silence, and
/// nothing that reaches the `Sink`, so `htl check` neither counts one nor carries one in
/// `--format json` — it prints them, prefixed `dts:`, exactly as this command does.
#[derive(Default)]
struct DepReport {
    /// `(target, written)` pairs, in the shape the rest of the report prints.
    written: Vec<(PathBuf, bool)>,
    /// Asked for and not written. This, and only this, is what `htl dts` exits non-zero on.
    not_written: Vec<String>,
    /// Under `types/` and no longer shipped by anything. Reported, never deleted, and it
    /// fails nothing: what the file is for is the project's to say.
    left_in_place: Vec<String>,
    /// The crate graph would not resolve, so nothing was asked for — cargo could not be
    /// run, or the project's lockfile does not cover its manifest and the graph is read
    /// with `--locked`. Either way the committed declarations stand and the check that
    /// follows names the module if one is missing, which is why this fails nothing.
    unresolved: Option<String>,
}

/// Materialise the declarations this project's dependencies ship, under
/// `<declaration root>/<crate>/` — the declaration root of the project at `types_root`,
/// `types/` unless its `htl.toml` says otherwise — and report on what happened to each.
///
/// The graph comes from `cargo metadata`, so this costs a subprocess on every command that
/// generates. Nothing is built, and nothing is downloaded for dependencies already fetched.
fn dep_dts(cargo_root: &Path, types_root: &Path) -> DepReport {
    dep_dts_to(cargo_root, types_root, true)
}

/// [`dep_dts`], writing only when `write` is set.
fn dep_dts_to(cargo_root: &Path, types_root: &Path, write: bool) -> DepReport {
    let decls = match htl::dep_dts::resolve(cargo_root) {
        Ok(d) => d,
        Err(e) => {
            return DepReport {
                unresolved: Some(e),
                ..DepReport::default()
            };
        }
    };
    // Orphans before materialising: the note beside a crate's declarations is what says
    // which crate they came from, and the write below rewrites it.
    let types = match decl_root(types_root) {
        Ok(t) => t,
        Err(e) => {
            return DepReport {
                unresolved: Some(format!("{e:#}")),
                ..DepReport::default()
            };
        }
    };
    let left_in_place = htl::dep_dts::orphans(&types, &decls);
    let (written, not_written) = htl::dep_dts::materialise_to(&types, &decls, write);
    DepReport {
        written,
        not_written,
        left_in_place,
        unresolved: None,
    }
}

/// The three report lists, each said as what it is. `wrote` / `unchanged` name what
/// happened to a declaration, and so do these: a reader who has never heard the words
/// `shipped-declaration` or `orphaned-declaration` can still tell which line failed the
/// command and which one is a file sitting there to decide about.
fn announce_dep_report(report: &DepReport, prefix: &str) {
    for p in &report.not_written {
        eprintln!("{prefix}not written: {p}");
    }
    for p in &report.left_in_place {
        eprintln!("{prefix}left in place: {p}");
    }
    if let Some(e) = &report.unresolved {
        eprintln!("{prefix}{e}");
    }
}

/// What generation wrote, or for a run that did not write (`wrote` unset) what it would
/// have.
fn announce_dts_to(results: &[(PathBuf, bool)], root: &Path, wrote: bool) {
    for (target, changed) in results {
        if *changed {
            let target = target.strip_prefix(root).unwrap_or(target).display();
            if wrote {
                eprintln!("dts: wrote {target}");
            } else {
                eprintln!(
                    "dts: would write {target} (dry run: not written; checked against the \
                     file on disk)"
                );
            }
        }
    }
}

fn cmd_dts(dir: Option<&Path>) -> Result<ExitCode> {
    let start = match dir {
        Some(d) => d.to_path_buf(),
        None => std::env::current_dir()?,
    };
    // The contract types first: a project may publish one without having a Rust host at
    // all, and the `bail!` below would then be wrong about there being nothing to do.
    let mut results = Vec::new();
    let mut failed = false;
    let mut project = None;
    if let Some((croot, _, cfg)) = load_config(&start)? {
        let model = htl::model::Project::load(&croot, cfg)?;
        let contracts: Vec<_> = model.contracts.iter().map(|c| c.terms.clone()).collect();
        let (published, problems) = htl::contract::publish(&croot, &contracts);
        for p in &problems {
            eprintln!("  {p}");
        }
        // Asked to generate and did not: the command says so in its exit code, or a CI
        // step that regenerates declarations would pass having written nothing.
        failed = !problems.is_empty();
        results.extend(published);
        project = Some(croot);
    }
    let code = |failed: bool| {
        if failed {
            ExitCode::FAILURE
        } else {
            ExitCode::SUCCESS
        }
    };
    let Some(root) = htl::dts::find_cargo_package_root(&start) else {
        if results.is_empty() && !failed {
            bail!(
                "no Cargo.toml with a [package] section, and no ---@contract type to publish, \
                 at or above {}",
                start.display()
            );
        }
        report_dts(&results, &start);
        return Ok(code(failed));
    };
    results.extend(htl::dts::generate_crate(&root).map_err(|e| anyhow::anyhow!("{e}"))?);
    let types_root = project.unwrap_or_else(|| root.clone());
    let report = dep_dts(&root, &types_root);
    announce_dep_report(&report, "  ");
    // An orphan, and a graph that would not resolve, are reports. A declaration asked for
    // and not written is a failure, the same as a contract that could not be published.
    failed = failed || !report.not_written.is_empty();
    results.extend(report.written);
    report_dts(&results, &root);
    Ok(code(failed))
}

fn report_dts(results: &[(PathBuf, bool)], root: &Path) {
    let mut written = 0usize;
    for (target, w) in results {
        let rel = target.strip_prefix(root).unwrap_or(target).display();
        eprintln!("  {} {}", if *w { "wrote    " } else { "unchanged" }, rel);
        written += usize::from(*w);
    }
    eprintln!(
        "htl dts: {} declaration(s) from {}, {} written",
        results.len(),
        root.display(),
        written
    );
}

/// One source file `htl shapes` read, with the check that was kept for it.
struct ShapeFile {
    /// The project-relative path, for the header and the diagnostics.
    rel: PathBuf,
    /// The module name the file answers to.
    module: String,
    info: htl::CheckInfo,
}

/// What became of one file `htl shapes` writes.
enum Generated {
    Wrote,
    Current,
    /// It was its own and the module it was generated for lowers to nothing now.
    Removed,
    /// It exists and does not start with the header `htl shapes` writes: not its own.
    Foreign,
}

/// Whether the file at `path` exists and starts with the header `htl shapes` writes.
fn written_by_shapes(path: &Path) -> bool {
    fs::read_to_string(path)
        .map(|cur| cur.starts_with(htl::shapes::HEADER))
        .unwrap_or(false)
}

/// The two files a module lowers to: `<source>/shapes/<module>.lua` and
/// `<types>/shapes/<module>.d.tl`.
fn shape_targets(source: &Path, types: &Path, module: &str) -> [PathBuf; 2] {
    let name = module.replace('.', "/");
    [
        source.join("shapes").join(format!("{name}.lua")),
        types.join("shapes").join(format!("{name}.d.tl")),
    ]
}

/// Remove a file `htl shapes` wrote for a module that lowers to nothing now. `None` when
/// there is no such file; a file that is not its own is left (`Foreign`).
fn remove_generated(path: &Path) -> Result<Option<Generated>> {
    if !path.exists() {
        return Ok(None);
    }
    if !written_by_shapes(path) {
        return Ok(Some(Generated::Foreign));
    }
    fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
    Ok(Some(Generated::Removed))
}

/// `path` as the table of shapes spells it: symlinks and `..` resolved.
fn canonical_path(p: &Path) -> PathBuf {
    fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
}

/// Write `text` to `path` when it would change, unless the file is somebody's: a target
/// that exists and whose first line is not the one `htl shapes` writes is left as it is.
fn write_generated(path: &Path, text: &str) -> Result<Generated> {
    if path.exists() && !written_by_shapes(path) {
        return Ok(Generated::Foreign);
    }
    let changed = htl::write_if_changed_when(path, text, true)
        .with_context(|| format!("writing {}", path.display()))?;
    Ok(if changed {
        Generated::Wrote
    } else {
        Generated::Current
    })
}

/// `htl shapes`: the module doc of `htl::shapes` says what is lowered and how; this is the
/// part that reads and writes files.
///
/// Two passes over the project's sources, because a shape names the shapes of other files:
/// the first checks every file and collects where each declaration is ([`htl::shapes::RefTable`]),
/// the second lowers each file against that table and writes what came out. A file with a
/// problem is not written, the others are, and the exit code says so.
fn cmd_shapes(dir: Option<&Path>) -> Result<ExitCode> {
    let start = match dir {
        Some(d) => d.to_path_buf(),
        None => std::env::current_dir()?,
    };
    let ProjectChecker { h, cfg, model, .. } = checker_for(&start, true)?;
    let Some((root, _, _)) = cfg else {
        bail!(
            "no htl.toml at or above {}: `htl shapes` writes into a project",
            start.display()
        );
    };
    let Some(model) = model else {
        bail!("no project at or above {}", start.display());
    };
    // The generated shapes are written against lshape, which this project supplies. An
    // implementation, not a declaration: after a first run `types/lshape.d.tl` is a row of
    // its own, and says nothing about whether a Lua module is there to load.
    let lshape = htl::resolve::resolve(&h, "lshape", Some(&root), Some(&model))?;
    if !lshape
        .candidates
        .iter()
        .any(|c| c.kind != htl::ModuleKind::Declaration)
    {
        eprintln!(
            "shapes: lshape is not on the path (no Lua or Teal module answers require(\"lshape\")); vendor or install it, then rerun"
        );
        return Ok(ExitCode::FAILURE);
    }
    let own = model.own();
    let Some(source) = own.roots.source.clone() else {
        bail!("the project at {} has no source directory", root.display());
    };
    let types = own.roots.decl.clone().unwrap_or_else(|| root.join("types"));
    let shown = |p: &Path| p.strip_prefix(&root).unwrap_or(p).to_path_buf();

    // The files, and the modules they answer to. A module called `shapes` is in the
    // namespace the generated modules are written under.
    let paths = [source.clone()];
    let skip = project::not_walked(Some(&model), &paths, htl::model::Purpose::Own);
    let mut modules = Vec::new();
    let mut collides = false;
    for file in htl::collect_tl_skipping(&paths, &skip)? {
        let Some(place) = model.locate(&file) else {
            continue;
        };
        if place.module.owner != htl::model::Owner::Own {
            continue;
        }
        if place.name == "shapes" || place.name.starts_with("shapes.") {
            eprintln!(
                "shapes: module `{}` ({}) is in the namespace the generated modules are written under (shapes.*); rename it, then rerun",
                place.name,
                shown(&file).display()
            );
            collides = true;
        }
        modules.push((file, place.name));
    }
    if collides {
        return Ok(ExitCode::FAILURE);
    }

    // Pass 1: check every file, keeping the index.
    let mut sink = text_sink();
    let mut failed = false;
    let mut checked = Vec::new();
    for (file, module) in modules {
        let info = h.check_indexed(&file)?;
        // A file whose check fails is reported, fails the run, and is lowered all the same:
        // the index is kept for any file that parsed, and a field whose type did not
        // resolve is refused at that field by the lowering itself. What this buys is the
        // first run. A file that requires `shapes.<m>` before that module exists fails its
        // check on that line and nothing else; written anyway, the second run is clean.
        // Skipped, a file that asserts its own records could never be written at all.
        if runs_fail(&info) {
            sink.checkinfo(&info);
            failed = true;
        }
        checked.push(ShapeFile {
            rel: shown(&file),
            module,
            info,
        });
    }
    let mut refs = htl::shapes::RefTable::new(canonical_path);
    for f in &checked {
        if let Some(decls) = f.info.types.declarations() {
            refs.extend(htl::shapes::declared_shapes(&f.module, decls));
        }
    }

    // Pass 2: lower each file against the table.
    let lowered: Vec<htl::shapes::Lowered> = checked
        .iter()
        .map(|f| {
            htl::shapes::lower(
                &htl::shapes::Source {
                    module: &f.module,
                    rel_path: &f.rel,
                    info: &f.info,
                },
                &refs,
            )
        })
        .collect();
    // Shapes that need each other's cannot be loaded: Lua's `require` would loop.
    let edges: Vec<(String, Vec<String>)> = checked
        .iter()
        .zip(&lowered)
        .filter_map(|(f, l)| match l {
            htl::shapes::Lowered::Written { requires, .. } => {
                Some((f.module.clone(), requires.clone()))
            }
            _ => None,
        })
        .collect();
    let cycles = htl::shapes::module_cycles(&edges);
    let in_cycle = |module: &str| cycles.iter().find(|g| g.iter().any(|m| m == module));

    // A module that is refused keeps the files an earlier run wrote for it, which still
    // validate against the old shape: said, not left standing in silence.
    let say_stale = |module: &str| {
        for target in shape_targets(&source, &types, module) {
            if written_by_shapes(&target) {
                eprintln!(
                    "shapes: {} left as it was and is stale: the module is refused above",
                    shown(&target).display()
                );
            }
        }
    };

    for (f, l) in checked.iter().zip(&lowered) {
        match l {
            htl::shapes::Lowered::Nothing => {
                // Its records are gone: so are the files that were written for them. Only
                // when the check kept an index; a file that did not parse says nothing about
                // its records, and its files stay.
                if f.info.types.declarations().is_some() {
                    for target in shape_targets(&source, &types, &f.module) {
                        if let Some(g) = remove_generated(&target)? {
                            failed |= announce_shape(&shown(&target), g);
                        }
                    }
                }
            }
            htl::shapes::Lowered::Refused { problems, notes } => {
                notes
                    .iter()
                    .chain(problems)
                    .for_each(|d| sink.diagnostic(d));
                say_stale(&f.module);
                failed = true;
            }
            htl::shapes::Lowered::Written { output, notes, .. } => {
                notes.iter().for_each(|d| sink.diagnostic(d));
                if let Some(group) = in_cycle(&f.module) {
                    let named: Vec<String> =
                        group.iter().map(|m| format!("`shapes.{m}`")).collect();
                    let (last, init) = named.split_last().expect("a cycle has members");
                    let all = if init.is_empty() {
                        last.clone()
                    } else {
                        format!("{} and {last}", init.join(", "))
                    };
                    sink.diagnostic(&htl::Diagnostic::new(
                        htl::Severity::Error,
                        f.rel.display().to_string(),
                        1,
                        1,
                        format!(
                            "{all} require each other, a `require` loop Lua cannot load; move the records they share into one module"
                        ),
                        None,
                    ));
                    say_stale(&f.module);
                    failed = true;
                    continue;
                }
                let [lua, dtl] = shape_targets(&source, &types, &f.module);
                failed |= announce_shape(&shown(&lua), write_generated(&lua, &output.lua)?);
                failed |= announce_shape(&shown(&dtl), write_generated(&dtl, &output.dtl)?);
            }
        }
    }
    let lshape_dtl = types.join("lshape.d.tl");
    failed |= announce_shape(
        &shown(&lshape_dtl),
        write_generated(&lshape_dtl, htl::shapes::LSHAPE_DTL)?,
    );
    Ok(if failed {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    })
}

/// Say what became of one generated file, one line on stderr. `true` when the file was not
/// its to write, which fails the run.
fn announce_shape(rel: &Path, g: Generated) -> bool {
    match g {
        Generated::Wrote => eprintln!("shapes: wrote {}", rel.display()),
        Generated::Current => eprintln!("shapes: current {}", rel.display()),
        Generated::Removed => eprintln!("shapes: removed {}", rel.display()),
        Generated::Foreign => {
            eprintln!(
                "shapes: {} exists and was not written by htl shapes; move it aside",
                rel.display()
            );
            return true;
        }
    }
    false
}

/// What the run wrote, and — when a target was asked for by name — what it left alone. The
/// kept list is what makes `htl init --target bin` on an older project say which of that
/// target's files were already there instead of skipping them in silence.
fn report_scaffold(dir: &Path, written: &[PathBuf], kept: &[PathBuf]) {
    let rel = |p: &PathBuf| p.strip_prefix(dir).unwrap_or(p).display().to_string();
    for p in written {
        eprintln!("  created {}", rel(p));
    }
    for p in kept {
        eprintln!("  kept    {} (already there)", rel(p));
    }
    if kept.is_empty() {
        eprintln!(
            "htl: {} file(s) written under {}",
            written.len(),
            dir.display()
        );
    } else {
        eprintln!(
            "htl: {} file(s) written, {} kept under {}",
            written.len(),
            kept.len(),
            dir.display()
        );
    }
}

fn cmd_new(
    name: &str,
    lib: bool,
    embed: bool,
    target: Option<&str>,
    htl: Option<&str>,
    no_x: bool,
) -> Result<ExitCode> {
    let dir = PathBuf::from(name);
    let pkg_name = dir
        .file_name()
        .and_then(|s| s.to_str())
        .ok_or_else(|| anyhow::anyhow!("invalid project name: {name}"))?
        .to_string();
    // Before the directory is touched: an unknown target, or one that disagrees with
    // --lib, fails here and leaves nothing behind. So does an htl this scaffold does not
    // write for — a release by number — so it is settled first too.
    let target = scaffold::resolve_target(target, embed, lib)?;
    let htl = scaffold::HtlPin::parse(htl)?;
    let opts = scaffold::Options {
        lib,
        target,
        htl,
        no_x,
    };
    let done = scaffold::scaffold(&dir, &pkg_name, &opts, true)?;
    report_scaffold(&dir, &done.written, &[]);
    // The manifest names a dependency: the fetch comes before the first test, or the
    // first test is a `module not found`.
    let fetch = if opts.writes_htlx() {
        "htl pkg install && "
    } else {
        ""
    };
    // The window target's first build needs two files nothing has written yet: `htl check`
    // materialises the dependency's declaration as `types/htl-mq/mq.d.tl` (from its
    // `[package.metadata.htl] dts`) and writes `src/fx.d.tl` from the host module, and
    // `cargo build` reads the first of them when `include_bundle!` links `mq`. So the
    // check comes before the run rather than after it.
    let then = match opts.target.map(|t| t.target) {
        Some(BuildTarget::Window) => "htl check . && cargo run",
        _ => "htl test",
    };
    eprintln!("next: cd {} && {fetch}{then}", dir.display());
    Ok(ExitCode::SUCCESS)
}

fn cmd_init(
    dir: Option<&Path>,
    lib: bool,
    embed: bool,
    target: Option<&str>,
    htl: Option<&str>,
    no_x: bool,
) -> Result<ExitCode> {
    let dir = match dir {
        Some(d) => d.to_path_buf(),
        None => std::env::current_dir()?,
    };
    let abs = std::fs::canonicalize(&dir).unwrap_or(dir.clone());
    let name = abs
        .file_name()
        .and_then(|s| s.to_str())
        .ok_or_else(|| anyhow::anyhow!("cannot derive a project name from {}", abs.display()))?
        .to_string();
    let asked_for_a_target = target.is_some() || embed;
    let target = scaffold::resolve_target(target, embed, lib)?;
    let htl = scaffold::HtlPin::parse(htl)?;
    let opts = scaffold::Options {
        lib,
        target,
        htl,
        no_x,
    };
    let done = scaffold::scaffold(&dir, &name, &opts, false)?;
    // A target was named: say what it would have written and found already there. Without
    // one the old one-liner stands, so a plain re-run does not list the whole tree.
    let kept: &[PathBuf] = if asked_for_a_target { &done.kept } else { &[] };
    if done.written.is_empty() && kept.is_empty() {
        eprintln!("htl init: nothing to do, all scaffold files already exist");
    } else {
        report_scaffold(&dir, &done.written, kept);
    }
    Ok(ExitCode::SUCCESS)
}

/// The project `htl pkg` acts on: the one above the working directory, found the way
/// every command finds it ([`htl::model::Project::find_root`]), with its `mlua-pkg.toml`.
///
/// mlua-pkg reports a missing manifest as an I/O error that does not name the file, and the
/// path htl looked for is the whole of the answer, so it is checked here.
fn pkg_project() -> Result<htl::pkg::MluaProject> {
    let cwd = std::env::current_dir()?;
    let root = htl::model::Project::find_root(&cwd)?.map(|r| r.root);
    root.filter(|r| r.join(htl::pkg::MANIFEST_NAME).is_file())
        .map(|r| htl::pkg::MluaProject::at(&r))
        .with_context(|| {
            format!(
                "no {} above {}: `htl pkg` runs in a project",
                htl::pkg::MANIFEST_NAME,
                cwd.display()
            )
        })
}

/// The declaration root of the project at `root`, from its model: `[layout] types`, which
/// is `types/` unless `htl.toml` says otherwise — where the declarations htl brings into a
/// project are written.
fn decl_root(root: &Path) -> Result<PathBuf> {
    let cfg = load_config(root)?;
    Ok(project::model_of(&cfg, root)?
        .and_then(|m| m.own().roots.decl.clone())
        .unwrap_or_else(|| root.join("types")))
}

/// `htl pkg install`: fetch what the manifest declares, then bring in what the deps publish.
fn cmd_pkg_install() -> Result<ExitCode> {
    let project = pkg_project()?;
    let report = project.install()?;
    report_install(&report, &project);
    // Re-read the project: install wrote the lockfile the two reports below are read from.
    // A dep publishes its declarations at `types/` in its package root, which is not where
    // `require` looks, so they are copied in for the checker to see.
    let project = htl::pkg::MluaProject::at(&project.root);
    report_types_sync(
        &project.sync_types(&decl_root(&project.root)?)?,
        &project.root,
    );
    report_patch_drift(&project);
    Ok(ExitCode::SUCCESS)
}

/// What install did, in the shape the other reports use. The library prints nothing.
fn report_install(
    report: &htl::pkg::mlua_pkg::ops::InstallReport,
    project: &htl::pkg::MluaProject,
) {
    use htl::pkg::mlua_pkg::ops::Placement;
    for w in &report.warnings {
        // A patch that was not used is reported below in htl's own verbs, where both ways
        // out are named. The library's line points at `mlua-pkg patch --force`, which
        // rebuilds the copy without asking git whether what is in it was committed.
        if w.contains("patch_dir") && w.contains("not used") {
            continue;
        }
        eprintln!("warning: {w}");
    }
    let rel = |p: &Path| {
        p.strip_prefix(&project.root)
            .unwrap_or(p)
            .display()
            .to_string()
    };
    for p in &report.packages {
        let sha: String = p.sha.chars().take(7).collect();
        let where_it_is = match (&p.placement, p.patched) {
            (_, true) => format!("from {}", rel(p.root())),
            (Placement::Copied(dest), _) => format!("copied to {}", rel(dest)),
            (Placement::Symlink(_), _) => p.entry.display().to_string(),
        };
        eprintln!("  install {} {sha} ({where_it_is})", p.name);
    }
    let n = report.packages.len();
    if report.transitive > 0 {
        eprintln!(
            "htl pkg install: {n} package(s), {} of them transitive",
            report.transitive
        );
    } else {
        eprintln!("htl pkg install: {n} package(s)");
    }
}

/// `htl pkg add <name> <git>`: the manifest entry, without fetching anything.
///
/// This is the one verb that may run outside a project: mlua-pkg writes a manifest when
/// there is none. It writes it at the project's root — beside `htl.toml`, when the working
/// directory is in a project that has one — and in the working directory only outside any
/// project. Written in a subdirectory, it would give the project a second root, which
/// every command then refuses.
fn cmd_pkg_add(spec: htl::pkg::mlua_pkg::ops::AddSpec) -> Result<ExitCode> {
    use htl::pkg::mlua_pkg::ops::AddOutcome;
    let cwd = std::env::current_dir()?;
    let root = htl::model::Project::find_root(&cwd)?
        .map(|r| r.root)
        .unwrap_or(cwd);
    let project = htl::pkg::MluaProject::at(&root);
    let name = spec.name.clone();
    let done = project.add(spec)?;
    let manifest = project
        .manifest
        .strip_prefix(&project.root)
        .unwrap_or(&project.manifest)
        .display();
    if done.report.manifest_created {
        eprintln!("  created {manifest}");
    }
    let verb = match done.report.outcome {
        AddOutcome::Added => "added",
        AddOutcome::Replaced => "updated",
    };
    eprintln!("  {verb}   {name} in {manifest}");
    if let Some(dir) = &done.kept_patch_dir {
        // `add` rewrites the entry, and its spec has no room for a patch. Putting the key
        // back is the difference between the project resolving that dependency from its own
        // copy and resolving it from upstream with the copy left unread in the tree.
        eprintln!(
            "  kept    patch_dir = {} ({name} is patched)",
            dir.display()
        );
    }
    eprintln!("htl pkg add: run `htl pkg install` to fetch it");
    Ok(ExitCode::SUCCESS)
}

/// `htl pkg update [name]`: what each pin does next, then the install that follows.
fn cmd_pkg_update(opts: htl::pkg::mlua_pkg::ops::UpdateOpts) -> Result<ExitCode> {
    use htl::pkg::mlua_pkg::ops::UpdateOutcome;
    let project = pkg_project()?;
    let dry_run = opts.dry_run;
    let report = project.update(opts)?;
    if report.entries.is_empty() {
        eprintln!("htl pkg update: no dependency selected");
        return Ok(ExitCode::SUCCESS);
    }
    for (name, outcome) in &report.entries {
        match outcome {
            UpdateOutcome::TagBumped { old, new } => {
                eprintln!("  update  {name}: tag {old} -> {new}")
            }
            UpdateOutcome::PrefixResolved { pin, resolved } => eprintln!(
                "  update  {name}: prefix '{pin}' is {resolved} (the manifest keeps the prefix)"
            ),
            UpdateOutcome::Refresh => eprintln!("  update  {name}: refresh (branch or unpinned)"),
            UpdateOutcome::Skipped(why) => eprintln!("  skip    {name}: {why}"),
        }
    }
    if dry_run {
        eprintln!("htl pkg update: dry run; nothing was written");
        return Ok(ExitCode::SUCCESS);
    }
    if let Some(install) = &report.install {
        report_install(install, &project);
        let project = htl::pkg::MluaProject::at(&project.root);
        report_types_sync(
            &project.sync_types(&decl_root(&project.root)?)?,
            &project.root,
        );
        report_patch_drift(&project);
    }
    Ok(ExitCode::SUCCESS)
}

/// `htl pkg clean`: the cache, which is machine-local and rebuilt by the next install.
fn cmd_pkg_clean(all: bool) -> Result<ExitCode> {
    use htl::pkg::mlua_pkg::ops::CleanReport;
    let project = pkg_project()?;
    match project.clean(all)? {
        CleanReport::CacheRemoved => eprintln!("htl pkg clean: removed every cached package"),
        CleanReport::NoLockfile => {
            eprintln!("htl pkg clean: no lockfile, so nothing was ever cached")
        }
        CleanReport::StaleRemoved { removed: 0 } => eprintln!("htl pkg clean: nothing to remove"),
        CleanReport::StaleRemoved { removed } => eprintln!(
            "htl pkg clean: removed {removed} cache entr{} the lockfile no longer refers to",
            if removed == 1 { "y" } else { "ies" }
        ),
    }
    Ok(ExitCode::SUCCESS)
}

/// A patched copy the dependency is no longer resolved from, said after every install
/// until it is refreshed or removed.
///
/// A patch is bound to the revision it was taken from, and an upgrade moves the pin off it.
/// Install does not fail over that — the project builds against the new upstream — so the
/// only thing that keeps the copy from being forgotten in the tree is being told about it
/// each time. Both ways out are named, in htl's verbs: mlua-pkg's own warning points at
/// `mlua-pkg patch --force`, which skips the question htl asks git before overwriting.
fn report_patch_drift(project: &htl::pkg::MluaProject) {
    let short = |s: &str| s.chars().take(7).collect::<String>();
    for s in project.patch_status() {
        if s.in_use {
            continue;
        }
        let rel = s
            .dir
            .strip_prefix(&project.root)
            .unwrap_or(&s.dir)
            .display();
        let why = match (&s.base, &s.locked) {
            _ if !s.dir.is_dir() => "the copy is not there".to_string(),
            (None, _) => "the lockfile records no revision it was taken from".to_string(),
            (Some(b), Some(l)) => {
                format!("taken from {}, {} is now at {}", short(b), s.name, short(l))
            }
            (Some(b), None) => format!("taken from {}, and nothing is locked", short(b)),
        };
        eprintln!("  patch   {rel} is not in use ({why})");
        eprintln!(
            "          carry the change forward: commit it, then `htl pkg patch {}`",
            s.name
        );
        eprintln!("          drop it: remove patch_dir from mlua-pkg.toml and delete {rel}");
    }
}

/// `htl pkg patch <dep>`: the dependency's source, taken into `patches/<dep>/` where the
/// project owns it. Not a passthrough — htl decides the directory, writes `patch_dir` into
/// the manifest and answers the "may this be overwritten" question against git; the copy
/// and the `patch_base` bookkeeping are mlua-pkg's. See `Project::patch`.
fn cmd_pkg_patch(dep: &str, force: bool) -> Result<ExitCode> {
    let project = pkg_project().context("a patch belongs to a project, so this runs in one")?;
    let done = project.patch(dep, force)?;
    let report = &done.report;
    let rel = report
        .patch_dir
        .strip_prefix(&project.root)
        .unwrap_or(&report.patch_dir);
    let verb = if report.created { "patched" } else { "rebuilt" };
    let base: String = report.base.chars().take(7).collect();
    eprintln!("  {verb} {} ({dep} at {base})", rel.display());
    // Only when there was something to drop: on a dependency whose repository holds
    // nothing but the package this line would be noise, and the reader would learn the
    // rule from a line that says nothing happened.
    if !done.dropped.is_empty() {
        eprintln!(
            "  dropped {} (the repository's, not the package's)",
            done.dropped.join(", ")
        );
    }
    eprintln!("htl: it is the project's code now — edit it, commit it, then `htl pkg install`.");
    Ok(ExitCode::SUCCESS)
}

/// What the deps published, in the shape `htl init` reports its scaffold. A name that was
/// already taken is said out loud: nothing was overwritten, and the project is the one
/// that decides which declaration it wants.
fn report_types_sync(sync: &htl::pkg::TypesSync, root: &Path) {
    let rel = |p: &Path| p.strip_prefix(root).unwrap_or(p).display().to_string();
    for (path, dep) in &sync.written {
        eprintln!("  types   {} (from {dep})", rel(path));
    }
    for (path, dep) in &sync.taken {
        eprintln!("  kept    {} ({dep} publishes one too)", rel(path));
    }
}

/// `htl types add <library>`: the declarations a library did not ship, from the collection
/// that has them. The revision is recorded because nothing else in that ecosystem does —
/// see `Project::add_types`.
fn cmd_types_add(library: &str, from: Option<&Path>, force: bool) -> Result<ExitCode> {
    let project = pkg_project().context("`types/` is a project's, so this runs in one")?;
    let types = decl_root(&project.root)?;
    let sync = match from {
        Some(dir) => project.add_types_from(dir, library, "local", force, &types)?,
        None => project.add_types(library, force, &types)?,
    };
    report_types_sync(&sync, &project.root);
    if sync.written.is_empty() && !sync.taken.is_empty() {
        eprintln!("htl: nothing written; --force replaces what is already there");
    }
    Ok(ExitCode::SUCCESS)
}

/// What `htl unused` was asked for, beyond the paths.
struct UnusedFlags {
    json: bool,
    /// Exit 1 when anything was reported. Off by default: "unused" is a question about
    /// intent, so CI opts in rather than out.
    fail_on_unused: bool,
    use_cache: bool,
    explain: bool,
}

/// What `htl adopt` was asked for, beyond the paths.
struct AdoptFlags {
    json: bool,
    /// List every marked declaration under the table, and each `applicable` candidate
    /// after them; the plain form prints the table alone.
    detail: bool,
    use_cache: bool,
    explain: bool,
}

/// What `htl check` was asked for, beyond the paths and the lint selection.
struct CheckFlags {
    strict: bool,
    list_lints: bool,
    /// `--explain <rule>`: print the rule's explanation and exit.
    explain_rule: Option<String>,
    json: bool,
    use_cache: bool,
    cache_mode: Option<cache::Mode>,
    explain: bool,
    /// `--statistics`: the per-rule table in place of the findings.
    statistics: bool,
}

struct TestFlags {
    fail_fast: bool,
    /// Finding no test file is a pass rather than a failure.
    allow_empty: bool,
    verbose: bool,
    quiet: bool,
    slow: Option<f64>,
    update: bool,
    coverage: bool,
    coverage_lines: bool,
    /// Where to write the lcov tracefile, if asked for.
    lcov: Option<PathBuf>,
    /// Where to write the JUnit XML report, if asked for.
    junit: Option<PathBuf>,
    json: bool,
    no_cache: bool,
    explain: bool,
    seed: Option<u64>,
}

fn print_coverage(cov: &report::CoverageReport, with_lines: bool) {
    let width = cov
        .modules
        .iter()
        .map(|m| m.path.len())
        .max()
        .unwrap_or(4)
        .max(5);
    for m in &cov.modules {
        eprintln!(
            "coverage: {:<width$}  {:>5}/{:<5} {:5.1}%",
            m.path,
            m.executed,
            m.total,
            100.0 * m.executed as f64 / m.total as f64
        );
        if !m.never_ran.is_empty() {
            let names: Vec<String> = m
                .never_ran
                .iter()
                .map(|f| format!("{} ({})", f.name, f.line))
                .collect();
            eprintln!("          never ran: {}", names.join(", "));
        }
        if with_lines && !m.unexecuted.is_empty() {
            let spans: Vec<String> = m
                .unexecuted
                .iter()
                .map(|(a, b)| {
                    if a == b {
                        a.to_string()
                    } else {
                        format!("{a}-{b}")
                    }
                })
                .collect();
            eprintln!("          unexecuted: {}", spans.join(", "));
        }
    }
    if cov.total > 0 {
        eprintln!(
            "coverage: {:<width$}  {:>5}/{:<5} {:5.1}%  (statements)",
            "total",
            cov.executed,
            cov.total,
            100.0 * cov.executed as f64 / cov.total as f64
        );
    } else {
        eprintln!("coverage: no .tl module reached");
    }
}

/// One file's report as a JUnit suite.
///
/// The assertion library reports a failure as `"<suite > test>: <message>"` and its tests
/// by the same composed name, so a failing case takes back the message printed under the
/// file by matching that prefix — including the traceback a runtime error carries, which
/// belongs in the report for the same reason it belongs on the terminal: it is the part
/// that says where.
fn junit_suite(rep: &htl::testing::FileReport) -> junit::Suite {
    let mut left: Vec<&str> = rep.failures.iter().map(String::as_str).collect();
    let cases = rep
        .tests
        .iter()
        .map(|t| {
            let failure = (!t.ok)
                .then(|| {
                    let head = format!("{}: ", t.name);
                    let at = left.iter().position(|m| m.starts_with(&head))?;
                    Some(left.remove(at)[head.len()..].to_string())
                })
                .flatten();
            junit::Case {
                name: t.name.clone(),
                ms: t.ms,
                // A failing test whose message could not be matched still failed: say so
                // rather than reporting it as passed.
                failure: failure.or_else(|| (!t.ok).then(|| "failed".to_string())),
            }
        })
        .collect();
    let error = if !rep.check.ok() {
        Some(junit::Error {
            message: "type check failed".to_string(),
            kind: "check",
            body: rep
                .check
                .error_items
                .iter()
                .map(|d| d.clone().spelled().to_string())
                .collect::<Vec<_>>()
                .join("\n"),
        })
    } else {
        rep.error.as_ref().map(|e| junit::Error {
            message: e.clone(),
            kind: "error",
            body: e.clone(),
        })
    };
    junit::Suite {
        file: htl::diagnostic::display_path(&rep.path),
        duration_ms: rep.duration_ms,
        error,
        cases,
    }
}

fn cmd_test(
    paths: &[PathBuf],
    filter: Option<&str>,
    lib: &str,
    lint: Option<&str>,
    flags: TestFlags,
) -> Result<ExitCode> {
    let paths = if paths.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        paths.to_vec()
    };
    if let Some(first) = paths.first() {
        auto_dts(first)?;
    }
    // A patched dependency's tests are its suite, not this project's: `htl pkg patch`
    // takes the whole package root, tests included, and running them here would report a
    // library's own failures as the project's.
    let cfg = load_config(&paths[0])?;
    let model = project::model_of(&cfg, &paths[0])?;
    let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Test);
    let files = htl::testing::discover_tests_for(&paths, &skip, lib)?;
    // A test at the root of a project laid out flat without saying so would only fail on
    // its first `require`; say what is wrong instead, as `check` does.
    project::refuse_flat_root(model.as_ref(), &paths, &files)?;
    // Finding nothing goes through the same report as any run: under `--allow-empty` its
    // summary line, and under `--format json` its document whether allowed or not, so a
    // reader of stdout always gets one.
    let empty = files.is_empty();
    if empty {
        eprintln!("htl test: no test files found (looked for .tl files that require(\"{lib}\"))");
    }
    let opts = project::TestOptions {
        config: &cfg,
        model: model.as_ref(),
        lint,
        lib,
        filter,
        run: htl::testing::RunOptions {
            fail_fast: flags.fail_fast,
            update_snapshots: flags.update,
            coverage: flags.coverage,
            // Given, or drawn for the run and printed below, so that it can be given back.
            seed: flags.seed,
            // `project::test` fills it from the config it is handed.
            async_: Default::default(),
            lang: Default::default(),
        },
        cache: project::cache_options(
            !flags.no_cache,
            Some(cache::Mode::PerModule),
            &cfg,
            flags.explain,
        ),
    };

    let mut sink = project::Sink::new(report::Out::new(flags.json, false));
    let mut json_files: Vec<report::TestFile> = Vec::new();
    let mut junit_suites: Vec<junit::Suite> = Vec::new();
    // What is left of the run here: how a file reads on a terminal, and what the document
    // says about it. Which files run, in what isolation, from what store — and what they
    // draw — is `project::test`'s.
    let rep = if empty {
        // Nothing to run, so no session to open and no store to touch: the run's report
        // with every count at zero, and no file having drawn from the seed.
        project::TestReport {
            files: Vec::new(),
            ran: 0,
            passed: 0,
            failed: 0,
            files_with_errors: 0,
            replayed: 0,
            seed: flags.seed.unwrap_or(0),
            duration_ms: 0.0,
            coverage: None,
        }
    } else {
        project::test(&mut sink, &files, &opts, &mut |rep, sink| {
            if flags.json {
                json_files.push(report::TestFile::from_report(rep, sink.out().take()));
            }
            if flags.junit.is_some() {
                junit_suites.push(junit_suite(rep));
            }
            // Spelled as `htl check` spells the same file, whatever path the walk was handed.
            let f = htl::diagnostic::display_path(&rep.path);
            let tag = if rep.ok() { "ok  " } else { "FAIL" };
            let detail = if !rep.check.ok() {
                "type check failed".to_string()
            } else if let Some(e) = &rep.error {
                // The cause on the file's own line, its frames under it: a traceback inside
                // the parenthesised summary would push `12 ms` past a screen of stack.
                format!("error: {}", e.lines().next().unwrap_or_default())
            } else if rep.file_level {
                "ran to completion (no test library used)".to_string()
            } else {
                format!("{} passed, {} failed", rep.passed, rep.failed)
            };
            // Quiet: a passing file is silence; failures, errors and slow tests still show.
            // JSON: nothing on stderr, the document carries it all.
            let show_file = !flags.json && (!flags.quiet || !rep.ok());
            if show_file {
                eprintln!("{tag} {f}  ({detail}, {:.0} ms)", rep.duration_ms);
                if let Some(e) = &rep.error {
                    for line in e.lines().skip(1) {
                        eprintln!("      {line}");
                    }
                }
            }
            for tr in &rep.tests {
                let slow = flags.slow.is_some_and(|ms| tr.ms >= ms);
                if !flags.json && (flags.verbose || slow) {
                    if flags.quiet && !show_file {
                        // The file line was skipped: name the file with the slow test.
                        eprintln!("slow {f}  {}  ({:.1} ms)", tr.name, tr.ms);
                        continue;
                    }
                    let mark = if tr.ok { "ok  " } else { "FAIL" };
                    let note = if slow && !flags.verbose {
                        "  [slow]"
                    } else {
                        ""
                    };
                    eprintln!("      {mark} {}  ({:.1} ms){note}", tr.name, tr.ms);
                }
            }
            if !flags.json {
                for m in &rep.failures {
                    eprintln!("      - {m}");
                }
                // A snapshot written or rewritten is a change on disk: always say so, even in -q.
                for p in &rep.snapshots_written {
                    eprintln!(
                        "snapshot written: {}",
                        htl::diagnostic::display_path(Path::new(p))
                    );
                }
                for p in &rep.snapshots_updated {
                    eprintln!(
                        "snapshot updated: {}",
                        htl::diagnostic::display_path(Path::new(p))
                    );
                }
            }
        })?
    };

    if let Some(out) = &flags.junit {
        // The run's own total, not the sum of the files: it is the number the summary
        // line prints, and the report is there to agree with the summary line.
        std::fs::write(out, junit::document(&junit_suites, rep.duration_ms))
            .with_context(|| format!("writing {}", out.display()))?;
    }
    if let (Some(out), Some(cov)) = (&flags.lcov, &rep.coverage) {
        // Against the project root rather than the working directory: a tracefile is
        // uploaded from wherever CI ran the command and resolved against the repository.
        let root = match &cfg {
            Some((dir, _, _)) => dir.clone(),
            None => std::env::current_dir()?,
        };
        let root = std::fs::canonicalize(&root).unwrap_or(root);
        std::fs::write(out, cov.lcov(&root))
            .with_context(|| format!("writing {}", out.display()))?;
    }
    // An empty run is a pass only when asked for; the document's `ok` says what the exit
    // code says, so a reader of either sees the same refusal.
    let ok = rep.ok() && (!empty || flags.allow_empty);
    if flags.json {
        let summary = report::TestSummary {
            files: rep.files.len(),
            files_run: rep.ran,
            passed: rep.passed,
            failed: rep.failed,
            files_with_errors: rep.files_with_errors,
            replayed: rep.replayed,
            duration_ms: rep.duration_ms,
            ok,
            seed: rep.seed,
        };
        report::emit(&report::TestReport {
            files: json_files,
            summary,
            coverage: rep.coverage,
        })?;
    } else if !empty || flags.allow_empty {
        // A refused empty run says so with the notice alone, as it always has.
        if let Some(cov) = &rep.coverage {
            print_coverage(cov, flags.coverage_lines);
            if let Some(out) = &flags.lcov {
                eprintln!("coverage: lcov written to {}", out.display());
            }
        }
        eprintln!(
            "htl test: {} file(s), {} passed, {} failed, {} file(s) with errors{}{} ({:.0} ms)",
            rep.ran,
            rep.passed,
            rep.failed,
            rep.files_with_errors,
            if rep.skipped() > 0 {
                format!(", {} file(s) not run (--fail-fast)", rep.skipped())
            } else {
                String::new()
            },
            // Says the checking was reused, not the run: every one of these files ran.
            if rep.replayed > 0 {
                format!(", {} checked from cache", rep.replayed)
            } else {
                String::new()
            },
            rep.duration_ms
        );
        // Always, not only on failure: the seed of a run that passed is what reproduces
        // the run that passes, and a failure two commits later is compared against it.
        // A run of no files drew nothing, so there is nothing to repeat.
        if !empty {
            eprintln!(
                "htl test: seed {} (repeat with --seed {})",
                rep.seed, rep.seed
            );
        }
    }
    Ok(if ok {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    })
}

/// Name the patched dependencies this walk enters, in the shape the other reports use.
///
/// Only the ones actually below a given root: `htl check src` walks the project's own
/// sources and nothing under `patches/`, and saying otherwise would be a claim about files
/// that were not read.
fn report_patched(paths: &[PathBuf]) {
    let roots: Vec<PathBuf> = paths
        .iter()
        .filter_map(|p| std::fs::canonicalize(p).ok())
        .collect();
    let cwd = std::env::current_dir().unwrap_or_default();
    // The project found the way every command finds it; a failure to find one was said by
    // the command itself, which ran first.
    let Some(project) = paths
        .first()
        .and_then(|p| htl::model::Project::find_root(p).ok().flatten())
        .map(|r| r.root)
        .filter(|r| r.join(htl::pkg::MANIFEST_NAME).is_file())
        .map(|r| htl::pkg::MluaProject::at(&r))
    else {
        return;
    };
    for p in &project.patches {
        let canon = std::fs::canonicalize(&p.dir).unwrap_or_else(|_| p.dir.clone());
        if !roots.iter().any(|r| canon.starts_with(r)) {
            continue;
        }
        let shown = p.dir.strip_prefix(&cwd).unwrap_or(&p.dir);
        eprintln!("  patched {} ({})", shown.display(), p.name);
    }
}

/// Nearest `htl.toml` above the first path: `(dir holding it, path, config)`.
///
/// Where `[toolchain] htl` is answered, and the only place: every command that reads the
/// config comes through here, and the pin has to be settled before the command reads a
/// source file — which is a property of this function, not something each command could
/// be trusted to repeat. `htl new` / `htl init` do not call it, so a mismatch never stops
/// anyone from creating a project.
///
/// The version compared is this binary's, which is the one the pin is about. The `htl`
/// crate a Rust host builds against is Cargo's, pinned in `Cargo.toml` — a separate
/// question, and the one [`warn_cargo_htl_mismatch`] answers.
fn load_config(first: &Path) -> Result<project::Config> {
    let cfg = project::config_of(first)?;
    if let Some((_, path, c)) = &cfg {
        htl::config::check_toolchain(c, path, env!("CARGO_PKG_VERSION"))?;
    }
    Ok(cfg)
}

/// Say so, once, when the `Cargo.toml` around this project asks for an `htl` crate this
/// command is not.
///
/// The two halves of htl are released together and a project uses both: the crate the host
/// links, and the command that checks the Teal beside it. A project left at `htl = "0.5.1"`
/// while the installed CLI had moved to 0.6.0 was checked by one and built against the
/// other, and nothing in either output mentioned the other one — which is the whole of the
/// failure, since either version alone was fine.
///
/// **A warning, not an error, and not one of the summary's `warning(s)`** — that count is
/// the checker's, and this is not about the sources. A project goes to a hard error over a
/// version skew for one of two reasons, and htl has neither: the format between the halves
/// is unstable, so a mismatched pair miscompiles rather than failing (wasm-bindgen refuses
/// a JS glue built by another version); or the diagnostic downstream is opaque, so the
/// person would otherwise read a type error from deep inside a dependency (cargo's
/// `rust-version`). Here both halves worked — the run that produced this report is the
/// evidence — and the line is worth printing only because the person has no other way to
/// notice. npm's `engines` is the same shape and warns by default; Prisma says nothing at
/// all, and its silence is filed as a bug.
///
/// Read from the `Cargo.toml` of the crate the project sits in, `[dependencies] htl` only:
/// a string, or a table with `version`. A table without one — `path`, `git`, or a
/// `workspace = true` inheritance — states no requirement here and is passed over without
/// a word, which is exactly what a scaffold written by a checkout-built CLI produces. No
/// `Cargo.toml`, no `[dependencies]`, no `htl` key, or a requirement cargo itself would
/// reject: nothing is printed, because there is nothing this can be surer about than cargo.
fn warn_cargo_htl_mismatch(first: &Path) {
    let Some(root) = htl::dts::find_cargo_package_root(first) else {
        return;
    };
    let Ok(text) = fs::read_to_string(root.join("Cargo.toml")) else {
        return;
    };
    let Ok(manifest) = text.parse::<toml::Table>() else {
        return;
    };
    let Some(dep) = manifest.get("dependencies").and_then(|d| d.get("htl")) else {
        return;
    };
    let req_text = match dep {
        toml::Value::String(s) => s.as_str(),
        toml::Value::Table(t) => match t.get("version").and_then(toml::Value::as_str) {
            Some(s) => s,
            None => return,
        },
        _ => return,
    };
    let running = env!("CARGO_PKG_VERSION");
    let (Ok(req), Ok(version)) = (
        semver::VersionReq::parse(req_text),
        semver::Version::parse(running),
    ) else {
        return;
    };
    if req.matches(&version) {
        return;
    }
    // Both ways out are named because either is the right one: the project may be the
    // thing that is current, in which case the command is what moves.
    eprintln!(
        "htl {running}; Cargo.toml asks for htl {req_text} — the crate and the CLI are \
         meant to move together (cargo install htl-cli --version {req_text}, or bump the \
         dependency)"
    );
}

fn cmd_fmt(paths: &[PathBuf], check: bool, indent: Option<usize>) -> Result<ExitCode> {
    let paths = if paths.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        paths.to_vec()
    };
    let cfg = load_config(&paths[0])?;
    let indent = indent
        .or_else(|| cfg.as_ref().and_then(|(_, _, c)| c.fmt.indent))
        .unwrap_or(3);
    let h = Htl::new()?;
    config_lang(&h, &cfg)?;
    // Not a dependency's files, a patched one included: formatting the copy would turn
    // every one of its files into a diff against the revision it was taken from, and bury
    // the project's own change somewhere inside that.
    let model = project::model_of(&cfg, &paths[0])?;
    let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Own);
    let files = htl::collect_tl_skipping(&paths, &skip)?;
    let (mut changed, mut failed) = (0usize, 0usize);
    for f in &files {
        let before = fs::read_to_string(f).with_context(|| format!("reading {}", f.display()))?;
        let after = match h.format_file(f, indent) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("error: {e}");
                failed += 1;
                continue;
            }
        };
        if after != before {
            changed += 1;
            if check {
                eprintln!("would reformat: {}", f.display());
            } else {
                fs::write(f, after).with_context(|| format!("writing {}", f.display()))?;
                eprintln!("reformatted: {}", f.display());
            }
        }
    }
    eprintln!(
        "htl fmt: {} file(s), {} {}, {} failed",
        files.len(),
        changed,
        if check { "would change" } else { "reformatted" },
        failed
    );
    let fail = failed > 0 || (check && changed > 0);
    Ok(if fail {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    })
}

struct FixFlags {
    rule: Vec<String>,
    unsafe_fixes: bool,
    dry_run: bool,
    diff: bool,
    allow_dirty: bool,
    allow_no_vcs: bool,
    exit_non_zero_on_fix: bool,
    json: bool,
}

fn cmd_fix(paths: &[PathBuf], flags: FixFlags) -> Result<ExitCode> {
    use htl::fix::{FixOptions, fix_file, git_dirty, unified_diff};
    let paths = if paths.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        paths.to_vec()
    };
    // What `htl check` holds a file to, resolved the same way and read by the same checker,
    // so a file this run leaves reports what a check of it would. A dry run writes nothing,
    // the declarations generated before the check included.
    let ProjectChecker {
        h,
        cfg,
        model,
        scope,
    } = checker_for(&paths[0], !flags.dry_run)?;
    let opts = FixOptions {
        unsafe_fixes: flags.unsafe_fixes,
        promoted: cfg
            .as_ref()
            .map(|(_, _, c)| c.fix.unsafe_.clone())
            .unwrap_or_default(),
        disabled: cfg
            .as_ref()
            .map(|(_, _, c)| c.fix.disable.clone())
            .unwrap_or_default(),
        only: flags.rule.clone(),
        dry_run: flags.dry_run,
    };
    // Here as well as inside `fix_file`, so a misspelt rule is answered even when the
    // paths hold no `.tl` at all — the request is wrong either way.
    opts.validate()?;
    // Written as `htl fmt` walks, not as `htl check` does: this command rewrites files, so a
    // patched dependency is left alone whatever the fixes would be. An edit there belongs
    // in the diff the project makes against the revision it took, written by a person.
    let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Own);
    // Only what a module of the project holds, as `htl check` walks it.
    let (files, outside) = project::held_by_modules(
        model.as_ref(),
        &paths,
        htl::collect_tl_skipping(&paths, &skip)?,
    )?;
    if let Some(note) = project::outside_modules_note(model.as_ref(), &outside, "fixed") {
        eprintln!("htl fix: {note}");
    }
    // But checked as `htl check` walks: the copy is still the project's code, and what is
    // wrong in it is what the two commands both judge the tree by. Only checked, never
    // handed to `fix_file`.
    let check_skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Check);
    let checked_only: Vec<PathBuf> = project::held_by_modules(
        model.as_ref(),
        &paths,
        htl::collect_tl_skipping(&paths, &check_skip)?,
    )?
    .0
    .into_iter()
    .filter(|f| !files.contains(f))
    .collect();

    // The working tree is the undo: refuse to rewrite what git could not give back.
    if !flags.dry_run {
        let mut dirty = Vec::new();
        let mut no_vcs = Vec::new();
        for f in &files {
            match git_dirty(f)? {
                Some(true) => dirty.push(f.clone()),
                Some(false) => {}
                None => no_vcs.push(f.clone()),
            }
        }
        if !dirty.is_empty() && !flags.allow_dirty {
            bail!(
                "htl fix rewrites files in place and relies on git to undo it; these have uncommitted changes:\n  {}\ncommit or stash them, or pass --allow-dirty",
                dirty
                    .iter()
                    .map(|p| p.display().to_string())
                    .collect::<Vec<_>>()
                    .join("\n  ")
            );
        }
        if !no_vcs.is_empty() && !flags.allow_no_vcs {
            bail!(
                "htl fix rewrites files in place and relies on git to undo it; these are not in a git repository:\n  {}\npass --allow-no-vcs to proceed without that safety net",
                no_vcs
                    .iter()
                    .map(|p| p.display().to_string())
                    .collect::<Vec<_>>()
                    .join("\n  ")
            );
        }
    }

    let mut sink = project::Sink::new(report::Out::new(flags.json, false));
    // Judged by the levels `htl check` judges by: a finding under a rule at `deny` fails.
    sink.judge_by(scope.lints.selection());
    // Dependencies are reported as `htl check` reports them and never rewritten: a fix
    // under `.htl/` goes at the next install, one under `[check] paths` is not this
    // project's. `fix_file` only ever writes the file it was given.
    let origins = project::Origins::new(model.as_ref());
    let walk = scope.walk(&cfg, model.as_ref(), &origins);
    let walked: Vec<PathBuf> = files.iter().chain(&checked_only).cloned().collect();
    sink.walking(&walked);
    let (mut applied, mut skipped, mut json_files) = (Vec::new(), Vec::new(), Vec::new());
    let (mut changed, mut deferred, mut reverted) = (0usize, 0usize, 0usize);
    let mut found = htl::verdict::Findings::default();
    let mut infos: Vec<(PathBuf, htl::CheckInfo)> = Vec::with_capacity(walked.len());
    for f in &files {
        // Put back after each file, as `htl check` does, so a file is fixed against what
        // it may read and not also against the directories of the files before it.
        let saved = h.search_path()?;
        project::file_view(&h, model.as_ref(), f)?;
        let before = if flags.diff {
            std::fs::read_to_string(f).ok()
        } else {
            None
        };
        let out = fix_file(&h, f, &opts)?;
        if out.contents.is_some() {
            changed += 1;
        }
        deferred += out.deferred;
        if out.reverted.is_some() {
            reverted += 1;
        }
        if !flags.json {
            for a in &out.applied {
                eprintln!(
                    "fixed: {}:{}: {} ({}{})",
                    project::display_path(f),
                    a.line,
                    a.rule,
                    a.applicability.as_str(),
                    if flags.dry_run { ", not written" } else { "" }
                );
            }
            for s in &out.skipped {
                eprintln!(
                    "skipped: {}:{}: {} — {}",
                    project::display_path(f),
                    s.line,
                    s.rule,
                    s.reason
                );
            }
            if let Some(r) = &out.reverted {
                eprintln!("reverted: {}: {r}", project::display_path(f));
            }
            if let Some(o) = &out.oscillation {
                eprintln!(
                    "stopped: {}: fixes of {o} undo each other",
                    project::display_path(f)
                );
            }
            if out.deferred > 0 {
                eprintln!(
                    "deferred: {}: {} edit(s) overlapped applied ones; run htl fix again",
                    project::display_path(f),
                    out.deferred
                );
            }
            if flags.diff
                && let (Some(b), Some(a)) = (&before, &out.contents)
            {
                print!("{}", unified_diff(&project::display_path(f), b, a));
            }
            // A suggestion is never written, so the diff is the only place it is shown.
            // Against what was applied, when something was: the two are one edit session.
            if flags.diff
                && let (Some(b), Some(s)) = (
                    out.contents.as_ref().or(before.as_ref()),
                    out.suggested.as_ref(),
                )
            {
                print!(
                    "{}",
                    unified_diff(&format!("{} (suggested)", project::display_path(f)), b, s)
                );
            }
        }
        // What the file says as it is left, the way `htl check` would say it: the checker's
        // result and this layer's lints, while the path it was checked under is in place.
        found.lints += project::file_findings(&h, &mut sink, f, &out.check, &walk)?;
        h.set_search_path(&saved)?;
        found.errors += out.check.errors.len();
        found.warnings += out.check.warnings.len();
        infos.push((f.clone(), out.check.clone()));
        if flags.json {
            applied.extend(out.applied.iter().map(|a| report::FixApplied {
                file: project::display_path(f),
                line: a.line,
                rule: a.rule.clone(),
                applicability: a.applicability.as_str(),
                pass: a.pass,
            }));
            skipped.extend(out.skipped.iter().map(|s| report::FixSkipped {
                file: project::display_path(f),
                line: s.line,
                rule: s.rule.clone(),
                reason: s.reason.clone(),
            }));
            json_files.push(report::FixFile {
                path: project::display_path(f),
                changed: out.contents.is_some(),
                deferred: out.deferred,
                reverted: out.reverted.clone(),
                oscillation: out.oscillation.clone(),
                diagnostics: sink.out().take(),
            });
        }
    }
    // A patched copy: checked as `htl check` checks it, and not fixed.
    for f in &checked_only {
        let m = project::check_one(&h, &mut sink, f, &walk)?;
        found.errors += m.errors;
        found.warnings += m.warnings;
        found.lints += m.lints;
        infos.push((f.clone(), m.requires_only()));
        if flags.json {
            json_files.push(report::FixFile {
                path: project::display_path(f),
                changed: false,
                deferred: 0,
                reverted: None,
                oscillation: None,
                diagnostics: sink.out().take(),
            });
        }
    }
    // What the project says about itself as a whole.
    // A dry run publishes nothing either.
    let mut whole = scope.whole(&cfg, model.as_ref());
    whole.publish = !flags.dry_run;
    let w = project::project_findings(&mut sink, &whole, &infos);
    found.errors += w.errors;
    found.lints += w.lints;
    let project_diagnostics = if flags.json {
        sink.out().take()
    } else {
        Vec::new()
    };
    // A broken dependency is an error `htl fix` cannot remove; it remains, as `htl check`
    // would count it.
    found.errors += sink.dependency_error_count();
    found.denied = sink.denied();
    // Judged as `htl check` judges the same tree: the same findings, the same policy.
    let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
    let errors_remaining = found.errors;
    let n_applied = if flags.json { applied.len() } else { 0 };
    let fail =
        htl::verdict::verdict(&found, &policy) || (flags.exit_non_zero_on_fix && changed > 0);
    if flags.json {
        let n_skipped = skipped.len();
        report::emit(&report::FixReport {
            dry_run: flags.dry_run,
            applied,
            skipped,
            files: json_files,
            summary: report::FixSummary {
                files: files.len(),
                files_changed: changed,
                applied: n_applied,
                skipped: n_skipped,
                deferred,
                reverted,
                errors_remaining,
                warnings: found.warnings,
                lints: found.lints,
                denied: found.denied,
                strict: policy.strict,
                ok: !fail,
            },
            diagnostics: project_diagnostics,
        })?;
    } else {
        // What else the verdict counted, said only when it did: a finding at `deny`, and
        // under `strict` every warning and lint. Without it a run that failed on a lint
        // would end in `0 error(s) remaining`.
        let judged = judged(&found, &policy);
        eprintln!(
            "htl fix: {} file(s){}, {} changed{}, {} error(s) remaining{}{}",
            files.len(),
            if checked_only.is_empty() {
                String::new()
            } else {
                format!(" + {} checked in patched dependencies", checked_only.len())
            },
            changed,
            if flags.dry_run {
                " (dry run, nothing written)"
            } else {
                ""
            },
            errors_remaining,
            judged,
            if deferred > 0 {
                format!(", {deferred} deferred")
            } else {
                String::new()
            }
        );
    }
    Ok(if fail {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    })
}

/// Type-check a tree, replaying the modules whose inputs have not moved.
///
/// The order here is load-bearing. Generating `.d.tl` and collecting the file list come
/// first, because both produce inputs the keys are built from. Every module is looked up
/// before any is checked, so that a run where nothing moved never builds a checker at all —
/// that costs about 13.5 ms (`crates/htl-core/benches/check.rs`), which is most of what a
/// fully replayed run has to save on a small project.
///
/// A module that misses re-checks its dependencies as part of its own check, since the
/// checker's store starts empty. So an edit costs the edited module, whatever depends on
/// it, and whatever those pull in — less than the project, more than the minimum.
fn cmd_check(paths: &[PathBuf], lint: Option<&str>, flags: CheckFlags) -> Result<ExitCode> {
    let CheckFlags {
        list_lints,
        json,
        use_cache,
        cache_mode,
        explain,
        statistics,
        ..
    } = flags;
    let mut sink = project::Sink::new(report::Out::new(json, statistics));
    let paths = if paths.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        paths.to_vec()
    };
    // Listing the rules reports nothing about the project and shares nothing with a run —
    // and now not even a Lua state: the registry is Rust (`htl_core::lint::RULES`), which
    // is what lets the rules the project layer reports under be listed beside the ones
    // `lint.lua` implements.
    // `--explain <rule>`: the rule's explanation, and nothing else. The name is the one a
    // finding prints in its `[htl <rule>]` suffix, so a reader hands the flag what they
    // were shown; a name no check reports under — a typo, or a fix class — is refused the
    // way `--lint` refuses it, on stderr, with the exit code an unusable argument gets.
    if let Some(rule) = flags.explain_rule.as_deref() {
        let Some(r) = htl::lint::explained(rule) else {
            eprintln!("unknown lint rule: {rule}");
            return Ok(ExitCode::from(2));
        };
        println!("{}  (default: {})\n\n{}", r.name, r.default, r.explain);
        return Ok(ExitCode::SUCCESS);
    }
    if list_lints {
        // The name and the level a project that says nothing gets. Two columns rather than
        // one because the default is a level now, and the five rules at `allow` are
        // otherwise invisible: a reader would have to turn one on to find out it was off.
        // Still one rule per line, name first, so it reads and greps as it always did.
        let width = htl::lint::rule_names()
            .iter()
            .map(|r| r.len())
            .max()
            .unwrap_or(0);
        for (name, level) in htl::lint::rule_defaults() {
            println!("{name:width$}  {level}");
        }
        // No pointer to `--explain` here: every rule listed has an explanation (the
        // registry's test holds it to that), and the listing is name-level pairs that
        // tests and greps read line by line. `--help` and a finding's own hint carry it.
        return Ok(ExitCode::SUCCESS);
    }
    // htl.toml first, then --lint, so the flag wins; `strict` from the file unless flagged.
    let cfg = load_config(&paths[0])?;
    warn_cargo_htl_mismatch(&paths[0]);
    let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), flags.strict);
    // `.d.tl` written from Rust source is an input to the check, so it is regenerated
    // before anything hashes the tree: a hit computed over stale declarations would be a
    // hit on a different question from the one being asked.
    if let Some(first) = paths.first() {
        auto_dts(first)?;
    }
    // A patched dependency is walked with the project's own sources — it is the project's
    // code, and its errors are the project's to fix. Which dependency each directory
    // stands in for is said here, so that an error under it is read as that dependency's
    // without the reader having to know the manifest.
    let walk_model = project::model_of(&cfg, &paths[0])?;
    // A directory is checked as a project: which of its files is which module, and what
    // they may read, is the project's to say. With none there is no answer to give, and
    // checking each file as a thing on its own would answer a different question without
    // saying so. A file named on its own is that question, asked outright, and is checked.
    if walk_model.is_none()
        && let Some(dir) = paths.iter().find(|p| p.is_dir())
    {
        bail!(
            "no {} or {} in {} or any directory above it: a directory is checked as a \
             project. Run `htl init` there to make it one, or name the .tl files to check \
             each on its own",
            htl::config::CONFIG_NAME,
            htl::pkg::MANIFEST_NAME,
            // Absolute: where the search started is the whole of the answer, and `.`
            // relative to itself would say nothing.
            fs::canonicalize(dir)
                .unwrap_or_else(|_| dir.clone())
                .display()
        );
    }
    let skip = project::not_walked(walk_model.as_ref(), &paths, htl::model::Purpose::Check);
    let (files, outside) = project::held_by_modules(
        walk_model.as_ref(),
        &paths,
        htl::collect_tl_skipping(&paths, &skip)?,
    )?;
    if let Some(note) = project::outside_modules_note(walk_model.as_ref(), &outside, "checked") {
        eprintln!("htl check: {note}");
    }
    if !json {
        report_patched(&paths);
    }

    // The walk, the store and every decision about them are the library's: `include_tl!`
    // asks the same questions of the same store, and the two answering them separately is
    // what let them disagree. What is left here is the flags, the summary and the exit code.
    let rep = project::check(
        &mut sink,
        &files,
        &project::Options {
            paths: &paths,
            config: &cfg,
            model: walk_model.as_ref(),
            lint,
            cache: project::cache_options(use_cache, cache_mode, &cfg, explain),
        },
    )?;
    let fail = report_check(
        sink.out(),
        json,
        statistics,
        &rep,
        &policy,
        patched_files(walk_model.as_ref(), &rep.files),
    )?;
    Ok(if fail {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    })
}

/// Report what no entry's `require` closure reaches.
///
/// The graph is the check's — `htl check` resolves every `require` already, and the
/// `require-cycle` lint reads the same edges — so this is that walk plus the entries the
/// project declares (`htl::unused`). What is left here is the flags, the printing and the
/// exit code.
fn cmd_unused(paths: &[PathBuf], flags: UnusedFlags) -> Result<ExitCode> {
    let UnusedFlags {
        json,
        fail_on_unused,
        use_cache,
        explain,
    } = flags;
    let paths = if paths.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        paths.to_vec()
    };
    let cfg = load_config(&paths[0])?;
    // A `.d.tl` written from Rust source is an input to the check the graph comes from,
    // exactly as it is for `htl check`.
    auto_dts(&paths[0])?;
    let model = project::model_of(&cfg, &paths[0])?;
    let rep = htl::unused::unused(&htl::unused::Options {
        paths: &paths,
        config: &cfg,
        model: model.as_ref(),
        cache: project::cache_options(use_cache, None, &cfg, explain),
    })?;
    let s = &rep.summary;
    if json {
        report::emit(&rep)?;
    } else if s.no_entry {
        eprintln!(
            "htl unused: nothing to start from, so nothing is reported. An entry is \
             main.tl in the source root ([layout] source) or beside the manifest, a test file, a module under a [[contract]] directory, or a name \
             in [build] extra / host"
        );
    } else {
        if s.check_errors > 0 {
            eprintln!(
                "htl unused: {} error(s) in the check this graph comes from — what those \
                 files require is missing from it (htl check)",
                s.check_errors
            );
        }
        for m in &rep.modules {
            match &m.module {
                Some(n) => eprintln!("module: {} ({n})", m.path),
                None => eprintln!("module: {}", m.path),
            }
        }
        for d in &rep.dependencies {
            eprintln!("dependency: {}", d.name);
        }
        eprintln!(
            "htl unused: {}, {} [{} considered, {} reached, {}]",
            count(s.modules, "module", "modules"),
            count(s.dependencies, "dependency", "dependencies"),
            s.considered,
            s.reached,
            count(s.entries, "entry", "entries"),
        );
    }
    Ok(if fail_on_unused && !s.ok {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    })
}

/// Report how many declarations carry each of htl's nine markers, and where.
///
/// The census is the check's — `htl check` already read every marker by position while
/// checking a file, exactly as the lints it drives do — so this is that census folded into
/// the nine features (`htl::adopt`). What is left here is the flags, the table, and the
/// exit code, which never moves: a report, not a gate.
fn cmd_adopt(paths: &[PathBuf], flags: AdoptFlags) -> Result<ExitCode> {
    let AdoptFlags {
        json,
        detail,
        use_cache,
        explain,
    } = flags;
    let paths = if paths.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        paths.to_vec()
    };
    let cfg = load_config(&paths[0])?;
    // A `.d.tl` written from Rust source is an input to the check the census comes from,
    // exactly as it is for `htl check` and `htl unused`.
    auto_dts(&paths[0])?;
    let model = project::model_of(&cfg, &paths[0])?;
    let rep = htl::adopt::adopt(&htl::adopt::Options {
        paths: &paths,
        config: &cfg,
        model: model.as_ref(),
        cache: project::cache_options(use_cache, None, &cfg, explain),
    })?;
    if json {
        report::emit(&rep)?;
    } else {
        print_adopt(&rep, detail);
    }
    // Always 0: `htl adopt` reports what the project has adopted, and does not judge it
    // (the module doc says why — a threshold invites marking records to move the number).
    Ok(ExitCode::SUCCESS)
}

/// The marker column's width, in both the table and `--detail`'s lines: the longest of
/// htl's nine, `---@extensible`, plus two spaces.
fn adopt_marker_width() -> usize {
    htl::adopt::FEATURES
        .iter()
        .map(|m| format!("---@{m}").len())
        .max()
        .unwrap_or(0)
        + 2
}

/// The table, `--detail`'s lines when asked for, and the summary line — the text form of
/// an [`htl::adopt::Report`].
fn print_adopt(rep: &htl::adopt::Report, detail: bool) {
    let width = adopt_marker_width();
    eprintln!(
        "{:<width$} {:>4}  {:>10}",
        "feature",
        "used",
        "applicable",
        width = width
    );
    for f in &rep.features {
        let applicable = match f.applicable {
            Some(n) => n.to_string(),
            None => "-".to_string(),
        };
        eprintln!(
            "{:<width$} {:>4}  {:>10}",
            format!("---@{}", f.marker),
            f.used,
            applicable,
            width = width
        );
    }
    if detail {
        // Padded to the longest `file:line` of every site and every candidate about to
        // be printed, not per feature: one column, so the names line up down the whole
        // list, a candidate's line included.
        let line_width = rep
            .features
            .iter()
            .flat_map(|f| {
                f.sites
                    .iter()
                    .map(|s| format!("{}:{}", s.file.display(), s.line))
                    .chain(
                        f.candidates
                            .iter()
                            .map(|c| format!("{}:{}", c.file.display(), c.line)),
                    )
            })
            .map(|s| s.len())
            .max()
            .unwrap_or(0);
        for f in &rep.features {
            for s in &f.sites {
                eprintln!(
                    "  {:<width$}{:<line_width$}  {}",
                    format!("---@{}", f.marker),
                    format!("{}:{}", s.file.display(), s.line),
                    s.name,
                    width = width,
                    line_width = line_width
                );
            }
            // A candidate's line ends with how many construction sites made it one, so
            // a reader can tell it from a marked declaration above it.
            for c in &f.candidates {
                let sites = if c.sites == 1 {
                    "1 site".to_string()
                } else {
                    format!("{} sites", c.sites)
                };
                eprintln!(
                    "  {:<width$}{:<line_width$}  {}  (applicable: {}, {sites})",
                    format!("---@{}", f.marker),
                    format!("{}:{}", c.file.display(), c.line),
                    c.name,
                    c.reason,
                    width = width,
                    line_width = line_width
                );
            }
        }
    }
    let s = &rep.summary;
    if s.check_errors > 0 {
        eprintln!(
            "htl adopt: {} error(s) in the project's check (htl check says which); a file \
             with a syntax error contributes no markers",
            s.check_errors
        );
    }
    if s.markers == 0 {
        eprintln!(
            "htl adopt: {} of {} features used, no markers",
            s.used, s.features
        );
    } else {
        eprintln!(
            "htl adopt: {} of {} features used, {} in {}",
            s.used,
            s.features,
            count(s.markers, "marker", "markers"),
            count(s.files, "file", "files"),
        );
    }
}

/// Say which file a module name resolves to, and what that hides.
///
/// The chain comes from the library ([`htl::resolve`]), over a checker set up exactly as a
/// check of this project sets one up — the installed deps, then the config's search paths,
/// in that order, because `add_path` prepends and the order is the whole answer. Asking
/// any other way would report a path nothing else uses.
///
/// A report, so both forms go to stdout (README, "Machine-readable output").
fn cmd_resolve(module: &str, path: Option<&Path>, json: bool) -> Result<ExitCode> {
    let start = path.unwrap_or(Path::new("."));
    // The declarations a check generates before it reads anything are inputs to the
    // answer — `types/<crate>/` is written by `htl dts` — and a report without them would
    // describe a project nobody checks; `checker_for` writes them. The search order the
    // report prints is `project::checker`'s, the one `htl check` reads under.
    let ProjectChecker { h, cfg, model, .. } = checker_for(start, true)?;
    let rep = htl::resolve::resolve(
        &h,
        module,
        cfg.as_ref().map(|(r, _, _)| r.as_path()),
        model.as_ref(),
    )?;
    if json {
        report::emit(&rep)?;
    } else {
        print_resolution(&rep);
    }
    Ok(if rep.summary.ok {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    })
}

/// The text form of a resolution: a table in search order, then who answered — the project
/// model, or the search path and the directories it consulted. The order column is the reason one row is read and the others are not, which
/// is why it is printed rather than left to be looked up.
fn print_resolution(r: &htl::resolve::Resolution) {
    let ambiguous = r
        .candidates
        .iter()
        .any(|c| c.status == htl::resolve::Status::Ambiguous);
    // A name the host provides: what answers it at run time is the host, and a row read
    // for it is only the declaration it is typed from. Refused when a file implements it
    // too, and then the header is the error, as a check reports it.
    let typed_by = r
        .read
        .as_ref()
        .map(|d| format!(", typed by {d}"))
        .unwrap_or_default();
    match (&r.read, &r.error, &r.provided_by) {
        (_, Some(e), _) => println!("htl resolve {}: error: {e}", r.module),
        // Declared and nothing else: the environment provides it — a library installed on
        // the machine, a module registered where the model cannot read it. The declaration
        // is the file read, and comes first, as any file the name resolves to does.
        (Some(read), None, Some(by)) if r.provider == Some(htl::model::Provider::Declared) => {
            println!(
                "htl resolve {}: {read}, provided by the environment ({by})",
                r.module
            )
        }
        (_, None, Some(by)) => {
            println!(
                "htl resolve {}: provided by the host ({by}){typed_by}",
                r.module
            )
        }
        (Some(read), None, None) => println!("htl resolve {}: {read}", r.module),
        (None, None, None) if ambiguous => println!(
            "htl resolve {}: more than one module implements it, and no order picks one",
            r.module
        ),
        (None, None, None) => println!(
            "htl resolve {}: nothing in the project or on the search path answers require(\"{}\")",
            r.module, r.module
        ),
    }
    if !r.candidates.is_empty() {
        let w = |f: fn(&htl::resolve::Candidate) -> usize, head: usize| {
            r.candidates.iter().map(f).max().unwrap_or(0).max(head)
        };
        let file = w(|c| c.path.len(), 4);
        let kind = w(|c| c.kind.as_str().len(), 4);
        let read_at = r
            .candidates
            .iter()
            .find(|c| c.status == htl::resolve::Status::Read)
            .map(|c| c.order);
        println!();
        println!("  order  {:file$}  {:kind$}  status", "file", "kind");
        for c in &r.candidates {
            let status = match (c.status, c.shadowed_by, read_at) {
                (htl::resolve::Status::Shadowed, Some(by), _) => format!("shadowed by {by}"),
                // Not hidden by the row that is read: typed by it, and loaded by the run.
                (htl::resolve::Status::Runtime, _, Some(by)) => format!("runtime, typed by {by}"),
                (s, _, _) => s.as_str().to_string(),
            };
            let origin = match &c.origin {
                Some(o) => format!("  ({})", o.describe()),
                None => String::new(),
            };
            println!(
                "  {:<5}  {:file$}  {:kind$}  {status}{origin}",
                c.order,
                c.path,
                c.kind.as_str()
            );
        }
    }
    println!();
    match r.answered_by {
        htl::resolve::AnsweredBy::Model => println!("  answered by the project model"),
        // The name is not the project's: where the search looked is half the answer, and
        // all of it when nothing was found.
        htl::resolve::AnsweredBy::Path => {
            println!("  searched, in order: {}", r.searched.join(", "))
        }
    }
}

/// `1 module` / `2 modules`: a count whose noun agrees with it, for a line short enough
/// that `module(s)` would be the loudest thing on it.
fn count(n: usize, one: &str, many: &str) -> String {
    format!("{n} {}", if n == 1 { one } else { many })
}

/// Delete this project's cache store.
///
/// The store sits beside `htl.toml`, which is not necessarily where anyone is standing:
/// `htl check src` run from anywhere in a repo writes to the project root. That is the
/// reason this exists rather than leaving people to work out which directory to remove.
///
/// Only `.htl/cache` goes. `.htl/` itself is left in place for whatever else may come to
/// live there, and the path is built here rather than taken from an argument, so there is
/// no spelling of the command that removes anything else.
fn cmd_cache_clear(path: Option<&Path>) -> Result<ExitCode> {
    let root = cache_root(path)?;
    let dir = root.join(".htl").join("cache");
    if !dir.is_dir() {
        eprintln!("htl cache: nothing stored at {}", dir.display());
        return Ok(ExitCode::SUCCESS);
    }
    let n = fs::read_dir(&dir)
        .map(|rd| {
            rd.flatten()
                .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
                .count()
        })
        .unwrap_or(0);
    fs::remove_dir_all(&dir).with_context(|| format!("removing {}", dir.display()))?;
    eprintln!(
        "htl cache: removed {n} {} from {}",
        if n == 1 { "entry" } else { "entries" },
        dir.display()
    );
    Ok(ExitCode::SUCCESS)
}

/// The directory a cache command works on: the project's root, as every command keeps its
/// store there ([`project::store_root`]), or the working directory outside a project.
fn cache_root(path: Option<&Path>) -> Result<PathBuf> {
    let start = path.unwrap_or(Path::new("."));
    let model = htl::model::Project::find_root(start)?.map(|r| r.root);
    Ok(model.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))))
}

/// Say what the store holds.
///
/// Answers "what is stored", not "what would be reused": an entry listed here can still miss
/// on the next run because a file it recorded has changed. The two are different questions
/// and conflating them would make this command lie in the more dangerous direction.
fn cmd_cache_status(path: Option<&Path>, json: bool, list_entries: bool) -> Result<ExitCode> {
    let c = cache::describe(&cache_root(path)?);
    if json {
        report::emit(&c)?;
        return Ok(ExitCode::SUCCESS);
    }

    if c.entries.is_empty() {
        println!("htl cache: empty ({})", c.dir);
        return Ok(ExitCode::SUCCESS);
    }
    let mut by_kind: std::collections::BTreeMap<&str, (usize, u64)> = Default::default();
    for e in &c.entries {
        let slot = by_kind.entry(e.kind.as_str()).or_default();
        slot.0 += 1;
        slot.1 += e.bytes;
    }
    println!(
        "htl cache: {} entries, {} at {}",
        c.entries.len(),
        human_bytes(c.bytes),
        c.dir
    );
    for (kind, (n, bytes)) in &by_kind {
        let what = match *kind {
            cache::CHECK => "checked modules",
            cache::GEN => "checked and generated test files (htl test)",
            cache::MODULE => "generated modules (htl test / build, include_bundle!)",
            cache::RUN => "whole runs",
            _ => "entries this build cannot read",
        };
        println!("  {n:>5} {what} ({})", human_bytes(*bytes));
    }
    if let (Some(min), Some(max)) = (
        c.entries.iter().map(|e| e.age_secs).min(),
        c.entries.iter().map(|e| e.age_secs).max(),
    ) {
        println!(
            "  last used between {} and {} ago",
            human_age(min),
            human_age(max)
        );
    }
    if list_entries {
        println!();
        for e in &c.entries {
            println!(
                "  {:<6} {:>8}  {}",
                e.kind,
                human_bytes(e.bytes),
                e.subjects.join(", ")
            );
        }
    }
    Ok(ExitCode::SUCCESS)
}

fn human_bytes(n: u64) -> String {
    if n >= 1 << 20 {
        format!("{:.1} MB", n as f64 / (1u64 << 20) as f64)
    } else if n >= 1 << 10 {
        format!("{:.0} KB", n as f64 / (1u64 << 10) as f64)
    } else {
        format!("{n} B")
    }
}

fn human_age(secs: u64) -> String {
    match secs {
        s if s < 90 => format!("{s}s"),
        s if s < 5400 => format!("{}m", s / 60),
        s if s < 172_800 => format!("{}h", s / 3600),
        s => format!("{}d", s / 86_400),
    }
}

/// How many of the files a walk visited came out of a patched dependency: the files in the
/// home of a module the project owns as a patch ([`htl::model::Project::home_of`]) — its
/// tests included, which no name reaches. Zero outside a project and for a
/// project with no patch, which is what keeps the summary line below unchanged for
/// everyone who has never run `htl pkg patch`.
fn patched_files(model: Option<&htl::model::Project>, files: &[PathBuf]) -> usize {
    let Some(model) = model else {
        return 0;
    };
    if !model
        .modules
        .iter()
        .any(|m| m.owner == htl::model::Owner::Patched)
    {
        return 0;
    }
    files
        .iter()
        .filter(|f| {
            model
                .home_of(f)
                .is_some_and(|m| m.owner == htl::model::Owner::Patched)
        })
        .count()
}

/// `htl check --statistics`'s table: one row per rule, count first, the rule names left
/// aligned on the longest of them. Nothing is printed for an empty slice — a run with no
/// finding leaves the summary line to say `0 error(s), 0 warning(s), 0 lint(s)` on its own.
fn print_statistics(rows: &[report::RuleStatistic]) {
    let width = rows.iter().map(|r| r.rule.len()).max().unwrap_or(0);
    for r in rows {
        eprintln!(
            "{:>5}  {:<width$}  {}",
            r.count,
            r.rule,
            statistics_marker(r)
        );
    }
}

/// `[*]`: every finding of the rule carries a fix `htl fix` applies without being asked
/// (`safe`) or shows (`suggest`). `[ ]`: none does. `[-]`: the rest — some findings fixable
/// and some not, or every one fixable but only some `safe`/`suggest`, the remainder
/// needing `--unsafe`.
fn statistics_marker(r: &report::RuleStatistic) -> &'static str {
    if r.fixable == r.count {
        "[*]"
    } else if r.fixable + r.unsafe_fixable == 0 {
        "[ ]"
    } else {
        "[-]"
    }
}

#[cfg(test)]
mod statistics_marker_tests {
    use super::statistics_marker;
    use crate::report::RuleStatistic;

    fn stat(count: usize, fixable: usize, unsafe_fixable: usize) -> RuleStatistic {
        RuleStatistic {
            rule: "r".to_string(),
            count,
            fixable,
            unsafe_fixable,
        }
    }

    /// Every finding fixable, and none of it `--unsafe`-only.
    #[test]
    fn full_safe_coverage_is_a_star() {
        assert_eq!(statistics_marker(&stat(2, 2, 0)), "[*]");
    }

    /// No finding carries a fix at all.
    #[test]
    fn no_fix_at_all_is_blank() {
        assert_eq!(statistics_marker(&stat(2, 0, 0)), "[ ]");
    }

    /// Some fixable, some not: a genuine mix.
    #[test]
    fn a_mix_of_fixable_and_not_is_a_dash() {
        assert_eq!(statistics_marker(&stat(3, 1, 0)), "[-]");
    }

    /// Full coverage, but not every one of it `safe`/`suggest`: the `--unsafe` ones keep
    /// it from being a plain `[*]`.
    #[test]
    fn full_coverage_split_between_safe_and_unsafe_is_a_dash() {
        assert_eq!(statistics_marker(&stat(2, 1, 1)), "[-]");
    }

    /// Full coverage, every one of it `--unsafe`-only.
    #[test]
    fn full_unsafe_only_coverage_is_a_dash() {
        assert_eq!(statistics_marker(&stat(2, 0, 2)), "[-]");
    }
}

/// The one place a check reports its totals, so a replayed module and a checked one cannot
/// drift apart in how they are summarized. Returns whether the run counts as a failure.
///
/// `patched` is how many of those files are a patched dependency's ([`patched_files`]),
/// split out of the count rather than added to it. One `htl pkg patch` turned a project's
/// `15 file(s)` into `25 file(s)` with nothing said, and a file count that moves for a
/// reason the line does not give is a file count a reader cannot use: the dependency's
/// `tests/` are now in the walk, they are not the project's, and the line has to say so.
fn report_check(
    out: &mut report::Out,
    json: bool,
    statistics: bool,
    rep: &project::Report,
    policy: &htl::verdict::Policy,
    patched: usize,
) -> Result<bool> {
    let (files, replayed) = (rep.files.len(), rep.replayed);
    let (errors, warnings, lints) = (rep.errors, rep.warnings, rep.lints);
    let strict = policy.strict;
    let fail = htl::verdict::verdict(&rep.findings(), policy);
    let all_cached = rep.all_cached();
    if json {
        report::emit(&report::CheckReport {
            files,
            patched,
            diagnostics: out.take(),
            summary: report::CheckSummary {
                errors,
                warnings,
                lints,
                denied: rep.denied,
                strict,
                ok: !fail,
                cached: all_cached,
                replayed,
            },
            statistics: statistics.then(|| out.statistics()),
        })?;
    } else {
        if statistics {
            print_statistics(&out.statistics());
        }
        // Say nothing when nothing was replayed; say how much when it was only some.
        let cached = if all_cached {
            " [cached]".to_string()
        } else if replayed > 0 {
            format!(" [{replayed}/{files} cached]")
        } else {
            String::new()
        };
        // The three counts say what kinds of thing the run said; `at deny` says how much
        // of that it failed on, and is left out when it is none of it — its being there at
        // all is the news. A run with two warnings and one denied lint reads as
        // `0 error(s), 2 warning(s), 1 lint(s), 1 at deny`.
        let denied = match rep.denied {
            0 => String::new(),
            n => format!(", {n} at deny"),
        };
        // A project with no patch reads exactly as it read before the split existed: the
        // second number appears only when there is something on the other side of it, and
        // the two always add up to the one number that was there.
        let counted = match patched {
            0 => format!("{files} file(s)"),
            n => format!("{} file(s) + {n} in patched dependencies", files - n),
        };
        // Where the why is, once per rule this run said something under, after the
        // findings and before the summary — the way cargo names `cargo fix` once rather
        // than on every line. A finding's message names the site; the explanation names
        // the rule. Only rules that have one (every lint does; an error has no rule).
        for rule in out.rules_said() {
            if htl::lint::explained(rule).is_some() {
                eprintln!("htl check --explain {rule}");
            }
        }
        eprintln!(
            "htl check: {counted}, {errors} error(s), {warnings} warning(s), {lints} lint(s){denied}{}{cached}",
            if strict { " [strict]" } else { "" }
        );
    }
    Ok(fail)
}

/// What [`checker_for`] set up, and what it set it up from.
struct ProjectChecker {
    /// The checker: the lint selection and `[lang]` of the project, its test library,
    /// `std.*`, the libraries this binary registers and `htl.task`, then the model's
    /// directories on the search path with its dependencies reachable.
    h: Htl,
    /// The config around the starting path; `None` outside a project.
    cfg: project::Config,
    /// The project model; `None` when there is neither an `htl.toml` nor an
    /// `mlua-pkg.toml`.
    model: Option<htl::model::Project>,
    /// What `htl check` holds a file to: the lint selection `h` was configured from
    /// (`scope.lints`), and the contracts and host modules a walk reads. A command
    /// that judges what it generates asks the same `Lints` for its levels, so the
    /// rules `h` runs and the rules the command reports under are one answer.
    scope: project::Scope,
}

/// A checker set up for the project `start` is in, through the two library functions
/// `htl check` goes through: [`project::Scope::new`] for the lint input, and
/// [`project::checker`] for the checker built from it: declarations written, model
/// loaded, scope, checker. A command that parses `.tl` and resolves requires calls this
/// and does not assemble a checker itself, so a `require` the checker resolves for
/// `htl check` is one `htl gen`, `htl run`, `htl build`, `htl resolve`, `htl shapes` and
/// `htl fix` resolve too, at the same lint levels. They each used to spell the install
/// calls out, in an order of their own, and `htl check` agreed with none of them: `htl
/// gen` did not install `htl.task`, and found its declaration only when a check or a run
/// had left it in the temporary directory first.
///
/// `write_dts` is the one difference between callers: whether the declarations the
/// project publishes (`auto_dts`) are written before anything is read. `htl fix
/// --dry-run` is the only caller that passes `false`; what it then checks is the
/// declarations as they are on disk.
///
/// What one file may read beyond what the model gives — the test root, for a file under
/// it; its own directory, for a file in no project — is [`project::file_view`], asked per
/// file by the command that has one.
///
/// The sites that do not come through here, and why:
/// - `cmd_fmt` only parses, and resolves no `require`, so it has no search path to set up.
/// - `htl check` and the language server hold a [`project::Scope`] of their own across
///   many files and call [`project::checker`] directly.
/// - the proc macros in `htl-macros` (`include_tl!`, `include_bundle!`) check inside
///   `rustc`, which has no `main` that called `register_installer`: see the module doc of
///   `htl_core::registry`.
fn checker_for(start: &Path, write_dts: bool) -> Result<ProjectChecker> {
    let cfg = load_config(start)?;
    auto_dts_to(start, write_dts)?;
    let model = project::model_of(&cfg, start)?;
    let scope = project::Scope::new(&cfg, model.as_ref(), start, None)?;
    let h = project::checker(
        model.as_ref(),
        scope.lints.selection(),
        &project::lang_of(&cfg),
    )?;
    Ok(ProjectChecker {
        h,
        cfg,
        model,
        scope,
    })
}

fn cmd_gen(file: &Path, out: Option<&Path>) -> Result<ExitCode> {
    // The search path `htl check` gives this file, so `htl gen` resolves what `htl check`
    // resolved and a file the checker accepts is one this command can emit.
    let ProjectChecker { h, model, .. } = checker_for(file, true)?;
    project::file_view(&h, model.as_ref(), file)?;
    let (code, c) = h.gen_lua(file)?;
    text_sink().checkinfo(&c);
    // Judged on its errors alone (`Policy::ERRORS_ONLY`): the warnings and lints above are
    // reported, and `htl check` is where they are judged.
    let (Some(code), false) = (code, runs_fail(&c)) else {
        return Ok(ExitCode::FAILURE);
    };
    // Written as it came back. This command used to append the final newline itself, which
    // made it the one consumer of `gen_lua` whose output was a whole file; the generator
    // does it for all of them now (`H.gen` in `prelude.lua` says why).
    match out {
        Some(p) => fs::write(p, code).with_context(|| format!("writing {}", p.display()))?,
        None => print!("{code}"),
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_run(file: &Path, args: &[String]) -> Result<ExitCode> {
    let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
    // The search path `htl check` gives this file, so `htl run` resolves what `htl check`
    // resolved rather than failing on a `require` the checker was happy with. Before the
    // bundle branch because a bundle carries its own modules and gains nothing from it
    // either way.
    let ProjectChecker { h, cfg, model, .. } = checker_for(file, true)?;
    // The executor's `[async]` is not part of what a check reads; nothing starts a task
    // before `load_bundle` / `run_root`, so setting it once the checker is up is early enough.
    h.configure_async(async_config(&cfg))?;
    if Bundle::is_bundle(&bytes) {
        let b = Bundle::decode(&bytes)?;
        // A bundle's frames are as good as its payload: stripped bytecode has no lines to
        // show, and `htl build --debug` is what keeps them.
        let main = h.load_bundle(&b, args)?;
        return run_root(&h, Entry::Main(main), args);
    }
    // Check first so lints/warnings are visible before the script runs.
    project::file_view(&h, model.as_ref(), file)?;
    h.install_searcher()?;
    h.set_arg(&file.to_string_lossy(), args)?;
    let (code, c) = h.gen_lua(file)?;
    text_sink().checkinfo(&c);
    // As `htl gen`: errors stop it, the rest is reported (`Policy::ERRORS_ONLY`).
    let (Some(code), false) = (code, runs_fail(&c)) else {
        return Ok(ExitCode::FAILURE);
    };
    run_root(
        &h,
        Entry::Chunk {
            code,
            name: format!("@{}", file.display()),
        },
        args,
    )
}

/// What `htl run` runs as the program's root: a generated chunk, or a bundle's entry.
enum Entry {
    Chunk { code: String, name: String },
    Main(htl::mlua::Function),
}

/// The `[async]` of a loaded `htl.toml`, or the default when there is no file.
fn async_config(cfg: &project::Config) -> &htl::config::AsyncConfig {
    static DEFAULT: htl::config::AsyncConfig = htl::config::AsyncConfig {
        grace_ms: None,
        preempt: None,
    };
    match cfg {
        Some((_, _, c)) => &c.async_,
        None => &DEFAULT,
    }
}

/// Run the program as a root coroutine on the executor, with Ctrl-C cancelling it.
///
/// The runtime is a current-thread tokio runtime with its time driver (the grace is a
/// tokio timeout) and a `LocalSet`, built for this run; `Htl::run_async` is awaited to
/// the end, so when it resolves nothing the program started is alive.
///
/// Ctrl-C is watched from a thread of its own rather than a task on this runtime: a
/// program in a CPU loop never yields to the runtime, so a task here would never get to
/// run, while the cancel hook reads the token from any thread at its next check. The
/// first Ctrl-C cancels the root — the program gets its grace to clean up — and a second
/// one ends the process, for a program that does not.
///
/// A cancelled run prints `htl run: interrupted` and exits 130, the shell's own code for
/// it; a program that raised prints the innermost cause and the frames that reached it
/// (`htl run` is a development command, so the frames are the default; `htl::user_message`
/// is what an embedding host shows people who did not write the Teal).
fn run_root(h: &Htl, entry: Entry, args: &[String]) -> Result<ExitCode> {
    let token = htl::mlua_isle::runtime::CancelToken::new();
    {
        let token = token.clone();
        std::thread::Builder::new()
            .name("htl-ctrl-c".into())
            .spawn(move || {
                let Ok(rt) = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                else {
                    return;
                };
                rt.block_on(async {
                    if tokio::signal::ctrl_c().await.is_ok() {
                        token.cancel();
                    }
                    if tokio::signal::ctrl_c().await.is_ok() {
                        std::process::exit(130);
                    }
                });
            })
            .context("starting the Ctrl-C watcher")?;
    }
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("building the executor's runtime")?;
    let local = tokio::task::LocalSet::new();
    let out = local.block_on(&rt, async {
        match entry {
            Entry::Chunk { code, name } => h.run_async(&code, &name, args, &token).await,
            Entry::Main(main) => {
                let va: htl::mlua::Variadic<String> = args.iter().cloned().collect();
                h.call_async(main, va, &token).await.map(|_| ())
            }
        }
    });
    Ok(match out {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) if htl::is_cancelled(&e) => {
            eprintln!("htl run: interrupted");
            ExitCode::from(130)
        }
        Err(e) => {
            eprintln!("{}", htl::developer_message(&e));
            ExitCode::FAILURE
        }
    })
}

/// Whether `htl run` / `htl gen` stop at the check `c`: [`htl::verdict::verdict`] under
/// [`Policy::ERRORS_ONLY`](htl::verdict::Policy::ERRORS_ONLY), so an error does and
/// nothing else.
fn runs_fail(c: &htl::CheckInfo) -> bool {
    htl::verdict::verdict(
        &htl::verdict::Findings {
            errors: c.errors.len(),
            warnings: c.warnings.len(),
            lints: c.lints.len(),
            denied: 0,
        },
        &htl::verdict::Policy::ERRORS_ONLY,
    )
}

/// The run cache as `htl build` was asked to use it: `--no-cache` and `--explain-cache`,
/// the two switches that mean something for one closure. There is no `--cache-mode`: a
/// build's entries are per module, as `htl test`'s are, since a build is many modules and
/// an edit to one should cost that one and its dependents rather than the closure.
struct BuildCache {
    use_cache: bool,
    explain: bool,
}

fn cmd_build(
    entry: &Path,
    out: &Path,
    main: &str,
    mut opts: htl::link::LinkOptions,
    cache_flags: BuildCache,
) -> Result<ExitCode> {
    // `std.*` resolves to its declaration and nothing else, so the linker files it under
    // the host's modules — which is what it is: the binary that runs the bundle preloads
    // it, as `htl run` does before `run_bundle`.
    let ProjectChecker {
        h,
        cfg,
        model,
        scope,
    } = checker_for(entry, true)?;
    // The rules and levels `htl check` uses: a bundle is judged as a check of its closure
    // would be, and a rule the project turned off is not reported here either.
    let lints = scope.lints;
    let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
    // The names the host provides are the model's — `#[host_module]`s in the crate around
    // the project, `[build] host`, `std.*` — so the bundle leaves out what the host
    // registers without anyone restating it; `--host` adds to them.
    if let Some(m) = &model {
        opts.host.extend(m.provided().map(|(n, _)| n.to_string()));
    }
    if let Some((_, _, cfg)) = &cfg {
        opts.extra.extend(cfg.build.extra.iter().cloned());
        opts.host.extend(cfg.build.host.iter().cloned());
        // The one thing `[build] target` changes: this command produces the `hb` target and
        // nothing else, so a project that records another is told which command does build
        // it rather than handed a bundle nothing in it was going to load. Here rather than
        // further down because both forms of `htl build` pass through — the directory form
        // returns a few lines below — and because nothing has been written yet.
        if let Some(t) = cfg.build.target.filter(|t| *t != BuildTarget::Hb) {
            eprintln!(
                "htl build: this project's target is `{}` — what runs its output is {} — and `htl build` writes a `.hb` bundle, which is the `hb` target. Build it with `cargo build`; to bundle its scripts anyway, drop `[build] target` from htl.toml.",
                t.name(),
                t.runs_it()
            );
            return Ok(ExitCode::FAILURE);
        }
    }
    if entry.is_dir() {
        if cache_flags.explain {
            eprintln!("htl cache: the directory form of `htl build` is not cached");
        }
        // Not into an installed or vendored copy — a dependency's files, which the model
        // knows — and into a patch, which is the project's code.
        let skip = project::not_walked(
            model.as_ref(),
            &[entry.to_path_buf()],
            htl::model::Purpose::Check,
        );
        return cmd_build_dir(&h, entry, out, main, &opts, &skip, &lints, &policy);
    }
    project::file_view(&h, model.as_ref(), entry)?;
    // The name the entry is served under: the one the project's model gives the file,
    // which is what a `require` of it elsewhere in the project writes.
    opts.entry_name = model.as_ref().and_then(|m| m.locate(entry).map(|p| p.name));
    // The store: `module` entries keyed the way `htl test` and the macros key them — the
    // file the module is and the lint selection `htl.toml` puts in force — so a module any
    // of them generated is one the build replays, and the reverse. Nothing is swept here:
    // a build sees one closure, and only `htl check`, which sees the project, bounds the
    // store (`cache.rs`).
    let root = project::store_root(model.as_ref());
    // `htl.toml`'s spec as the scope joined it, the one `lints` was parsed from.
    let lint = (!scope.spec.is_empty()).then_some(scope.spec.as_str());
    let cache_opts = project::cache_options(
        cache_flags.use_cache,
        Some(cache::Mode::PerModule),
        &cfg,
        cache_flags.explain,
    );
    let store = project::with_model(
        project::store(&root, cache_opts, None, "htl build"),
        model.as_ref(),
    );
    let link_store = store.as_ref().map(|c| htl::link::LinkStore {
        cache: c,
        lint,
        root: &root,
        config: cfg.as_ref().map(|(_, p, c)| (p.as_path(), c)),
    });
    let linked = htl::link::link_with(&h, entry, &opts, link_store)?;
    project::explain_cache(store.as_ref(), cache_opts);
    // One sink for the whole closure: a build is many modules, and what the layer says
    // once per run is said once for the build rather than once per module.
    let mut sink = text_sink();
    sink.judge_by(lints.selection());
    for (p, c) in &linked.checks {
        sink.checkinfo(&linked.reported(p, c));
    }
    let n_err = linked.errors.len();
    let found = htl::verdict::Findings {
        errors: n_err,
        warnings: linked.checks.iter().map(|(_, c)| c.warnings.len()).sum(),
        lints: linked.lints.len(),
        denied: sink.denied(),
    };
    // The checks' own errors went through the sink above; the linker's are its own list,
    // said through the same sink so they read as the checks' do.
    for d in &linked.link_errors {
        sink.diagnostic(d);
    }
    if htl::verdict::verdict(&found, &policy) {
        eprintln!(
            "htl build: {n_err} error(s){}, bundle not written",
            judged(&found, &policy)
        );
        return Ok(ExitCode::FAILURE);
    }
    let buf = linked.bundle()?.encode();
    fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
    let typed = linked.modules.iter().filter(|m| m.typed).count();
    // The same suffix `htl check` prints: everything from the store, some of it, or
    // nothing said when none was.
    let cached = if typed > 0 && linked.cached == typed {
        " [cached]".to_string()
    } else if linked.cached > 0 {
        format!(" [{}/{typed} cached]", linked.cached)
    } else {
        String::new()
    };
    eprintln!(
        "htl build: {} module(s) ({typed} typed, {} lua) -> {} ({} bytes{}{}){cached}",
        linked.modules.len(),
        linked.modules.len() - typed,
        out.display(),
        buf.len(),
        if opts.source {
            ", source"
        } else {
            ", bytecode"
        },
        if opts.debug { " with debug info" } else { "" }
    );
    if !linked.host_modules.is_empty() {
        eprintln!(
            "htl build: host must provide: {}",
            linked.host_modules.join(", ")
        );
    }
    Ok(ExitCode::SUCCESS)
}

/// The older form: every `.tl` under a directory, module names from their paths.
// Eight because the two judgments `cmd_build` already holds are handed in rather than
// asked for again from the config.
#[allow(clippy::too_many_arguments)]
fn cmd_build_dir(
    h: &Htl,
    dir: &Path,
    out: &Path,
    entry: &str,
    opts: &htl::link::LinkOptions,
    skip: &[PathBuf],
    lints: &htl::lint::Lints,
    policy: &htl::verdict::Policy,
) -> Result<ExitCode> {
    // `lints` and `policy` are the file form's, passed in by `cmd_build`: `htl.toml`'s rules
    // and levels, its `strict`.
    h.add_path(dir)?;
    let files = htl::collect_tl_skipping(&[dir.to_path_buf()], skip)?;
    let mut b = Bundle {
        entry: entry.to_string(),
        htl_version: env!("CARGO_PKG_VERSION").into(),
        ..Default::default()
    };
    let mut found = htl::verdict::Findings::default();
    let mut sink = text_sink();
    sink.judge_by(lints.selection());
    for f in &files {
        // Named against the directory the bundle is built from, by the naming rule.
        let rel = f.strip_prefix(dir).unwrap_or(f);
        let name = htl::naming::name_of("", rel)
            .with_context(|| format!("cannot derive a module name for {}", f.display()))?;
        let (code, c) = h.gen_lua(f)?;
        sink.checkinfo(&c);
        found.errors += c.errors.len();
        found.warnings += c.warnings.len();
        found.lints += c.lints.len();
        let Some(code) = code else { continue };
        let (kind, payload) = if opts.source {
            (htl::bundle::Kind::Source, code.into_bytes())
        } else {
            (
                htl::bundle::Kind::Bytecode,
                h.compile_with(&name, &code, !opts.debug)?,
            )
        };
        b.modules.push(htl::bundle::Module {
            name,
            kind,
            payload,
        });
    }
    found.denied = sink.denied();
    if htl::verdict::verdict(&found, policy) {
        eprintln!(
            "htl build: {} error(s){}, bundle not written",
            found.errors,
            judged(&found, policy)
        );
        return Ok(ExitCode::FAILURE);
    }
    if b.module(entry).is_none() {
        bail!(
            "entry module '{entry}' not found among {} module(s)",
            b.modules.len()
        );
    }
    if !opts.source {
        b.fingerprint = h.fingerprint()?;
    }
    let buf = b.encode();
    fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
    eprintln!(
        "htl build: {} module(s) -> {} ({} bytes)",
        b.modules.len(),
        out.display(),
        buf.len()
    );
    Ok(ExitCode::SUCCESS)
}

/// What `htl bundle info` reports: everything the file records and nothing it does not
/// (no Lua state is created, nothing is loaded), which is what a build step checks in and
/// a bug report pastes; `--format json` is the same fields. `lua` is the header the
/// bytecode was compiled for, in the fields the mismatch message names; `None` when the
/// bundle carries no fingerprint, which `payload` explains (`source`: the text says `any`)
/// or `format` does (`1`, before the fingerprint: `not recorded`).
#[derive(serde::Serialize)]
struct BundleInfo {
    file: String,
    format: u8,
    htl_version: Option<String>,
    /// `bytecode`, `source`, or `mixed` when modules disagree.
    payload: &'static str,
    lua: Option<htl::bundle::LuaHeader>,
    entry: String,
    modules: Vec<BundleModuleInfo>,
    host_modules: Vec<String>,
}

#[derive(serde::Serialize)]
struct BundleModuleInfo {
    name: String,
    kind: &'static str,
    bytes: usize,
}

fn cmd_bundle_info(file: &Path, json: bool) -> Result<ExitCode> {
    let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
    let Some(format) = htl::bundle::format_version(&bytes) else {
        bail!("{} is not an htl bundle (bad magic)", file.display());
    };
    let b = Bundle::decode(&bytes)?;
    let kind_name = |k: htl::bundle::Kind| match k {
        htl::bundle::Kind::Bytecode => "bytecode",
        htl::bundle::Kind::Source => "source",
    };
    let payload = match (
        b.modules
            .iter()
            .any(|m| m.kind == htl::bundle::Kind::Bytecode),
        b.modules
            .iter()
            .any(|m| m.kind == htl::bundle::Kind::Source),
    ) {
        (true, true) => "mixed",
        (false, true) => "source",
        // Bytecode, or no modules at all: what the loader would treat it as.
        _ => "bytecode",
    };
    let info = BundleInfo {
        file: file.display().to_string(),
        format,
        htl_version: (!b.htl_version.is_empty()).then(|| b.htl_version.clone()),
        payload,
        lua: htl::bundle::LuaHeader::parse(&b.fingerprint),
        entry: b.entry.clone(),
        modules: b
            .modules
            .iter()
            .map(|m| BundleModuleInfo {
                name: m.name.clone(),
                kind: kind_name(m.kind),
                bytes: m.payload.len(),
            })
            .collect(),
        host_modules: b.host_modules.clone(),
    };
    if json {
        report::emit(&info)?;
        return Ok(ExitCode::SUCCESS);
    }

    println!(
        "{}: htl bundle, format {}, built by {}",
        info.file,
        info.format,
        match &info.htl_version {
            Some(v) => format!("htl {v}"),
            None => "htl (version not recorded)".to_string(),
        }
    );
    println!("  payload:  {}", info.payload);
    let lua = match &info.lua {
        Some(h) => h.to_string(),
        None if !b.fingerprint.is_empty() => {
            format!("unreadable fingerprint ({} bytes)", b.fingerprint.len())
        }
        None if info.format == 1 => {
            "not recorded (a format 1 bundle carries no fingerprint)".into()
        }
        None => "any (source payload, no bytecode to bind)".into(),
    };
    println!("  lua:      {lua}");
    println!("  entry:    {}", info.entry);
    let modules: Vec<String> = info
        .modules
        .iter()
        .map(|m| {
            if info.payload == "mixed" {
                format!("{} ({})", m.name, m.kind)
            } else {
                m.name.clone()
            }
        })
        .collect();
    println!(
        "  modules:  {}",
        if modules.is_empty() {
            "(none)".to_string()
        } else {
            modules.join(", ")
        }
    );
    println!(
        "  host:     {}",
        if info.host_modules.is_empty() {
            "(none)".to_string()
        } else {
            info.host_modules.join(", ")
        }
    );
    Ok(ExitCode::SUCCESS)
}