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
use std::fs;
use std::io::{self, BufRead, Read, Write};

use serde::{Deserialize, Serialize};

pub use tirith_core::policy::TrustScopeKind as ScopeKind;

/// Default TTL for a `trust add` with neither `--ttl` nor `--permanent`. Trust
/// expires by default; permanent trust must be chosen explicitly.
const DEFAULT_TTL: &str = "30d";
const TRUST_STORE_MAX_BYTES: u64 = 1024 * 1024;

/// A single entry in trust.json.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrustEntry {
    pub pattern: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rule_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ttl_expires: Option<String>,
    pub added: String,
    pub source: String,
    /// Optional free-text reason recorded when the entry was added.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// The trust.json file format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrustStore {
    pub version: u32,
    pub entries: Vec<TrustEntry>,
}

impl Default for TrustStore {
    fn default() -> Self {
        Self {
            version: 1,
            entries: Vec::new(),
        }
    }
}

/// Classify how broad a trust pattern is.
pub fn classify_scope(pattern: &str) -> ScopeKind {
    tirith_core::policy::classify_trust_pattern(pattern)
}

/// A unified trust listing row shown by `trust list`.
#[derive(Debug, Clone, Serialize)]
struct TrustListRow {
    pattern: String,
    rule_id: Option<String>,
    source: String,
    expires: Option<String>,
    expired: bool,
    /// Machine-readable scope class.
    scope_kind: ScopeKind,
    /// One-line description of what the entry covers.
    scope_coverage: String,
    /// True when the entry is dangerously broad (wildcard / bare TLD).
    broad_warning: bool,
}

/// Print an error from a trust subcommand, with a "try --scope user" hint
/// when the error mentions "git repository" (i.e., `--scope repo` failed
/// because we are outside a git repo).
fn print_trust_error(subcmd: &str, err: &str, hint_pattern: Option<&str>) {
    eprintln!("{}", trust_error_line(subcmd, err));
    if err.contains("git repository") {
        if let Some(pattern) = hint_pattern {
            let display_pattern = human(pattern);
            let quoted = if display_pattern == pattern {
                tirith_core::safe_command::shell_single_quote(pattern)
                    .unwrap_or_else(|| "'[unsafe pattern]'".to_string())
            } else {
                "'[unsafe pattern]'".to_string()
            };
            eprintln!(
                "  try: tirith trust {} {} --scope user",
                human(subcmd),
                quoted
            );
        } else {
            eprintln!("  try: tirith trust {} --scope user", human(subcmd));
        }
    }
}

fn human(value: &str) -> String {
    super::sanitize_for_human_output(value, false)
}

fn human_multiline(value: &str) -> String {
    super::sanitize_for_human_output(value, true)
}

/// Render one trust-command error at the final human-output boundary. Both the
/// action and detail may originate outside the typed CLI path (library callers,
/// loaded parser diagnostics, environment-derived paths), so sanitize the
/// complete dynamic fields here instead of relying on validation upstream.
fn trust_error_line(action: &str, detail: &str) -> String {
    format!("tirith: trust {}: {}", human(action), human(detail))
}

fn unknown_scope_line(action: &str, scope: &str, allowed: &str) -> String {
    trust_error_line(action, &format!("unknown scope '{scope}' (use {allowed})"))
}

fn trust_prompt_line(domain: &str) -> String {
    format!(
        "Trust {}? [y/N/r(rule-scoped)/t(temporary 7d)] ",
        human(domain)
    )
}

/// Serialize `value` as pretty JSON to stdout. Returns `0` on success, `1` on a
/// serialization failure — surfaced as a non-zero exit so a consumer can tell
/// the output is incomplete rather than a misleading exit-0.
#[must_use]
fn print_json(value: &impl Serialize) -> i32 {
    match serde_json::to_string_pretty(value) {
        Ok(s) => {
            println!("{s}");
            0
        }
        Err(e) => {
            eprintln!(
                "tirith: JSON serialization failed: {}",
                human(&e.to_string())
            );
            1
        }
    }
}

/// Resolve the trust.json path for a given scope.
fn trust_store_path(scope: &str) -> Result<std::path::PathBuf, String> {
    match scope {
        "user" => {
            let config = tirith_core::policy::config_dir()
                .ok_or_else(|| "cannot determine config directory".to_string())?;
            Ok(config.join("trust.json"))
        }
        "repo" => {
            let repo_root = tirith_core::policy::find_repo_root(None)
                .ok_or_else(|| "not inside a git repository".to_string())?;
            Ok(repo_root.join(".tirith").join("trust.json"))
        }
        other => Err(format!("unknown scope: {other} (use 'user' or 'repo')")),
    }
}

/// Load the trust store from a path.
///
/// Returns `Ok(default)` if the file does not exist, or `Err` if the file
/// exists but cannot be parsed (prevents silent data loss on corruption).
fn load_store(path: &std::path::Path) -> Result<TrustStore, String> {
    let bytes = match tirith_core::util::read_text_no_follow_capped(path, TRUST_STORE_MAX_BYTES) {
        Ok(bytes) => bytes,
        Err(tirith_core::util::OpenRegularError::NotFound) => return Ok(TrustStore::default()),
        Err(tirith_core::util::OpenRegularError::NotRegularFile) => {
            return Err(format!(
                "refusing non-regular or symlinked trust store at {}",
                path.display()
            ))
        }
        Err(tirith_core::util::OpenRegularError::TooLarge) => {
            return Err(format!(
                "trust store at {} exceeds the {} byte limit",
                path.display(),
                TRUST_STORE_MAX_BYTES
            ))
        }
        Err(tirith_core::util::OpenRegularError::Io(error)) => {
            return Err(format!("cannot read {}: {error}", path.display()))
        }
    };
    serde_json::from_slice(&bytes)
        .map_err(|e| format!("corrupt trust store at {}: {e}", path.display()))
}

/// Write a user trust store crash-atomically. Repo stores use the stronger
/// descriptor-relative implementation below.
#[cfg(test)]
fn write_store(path: &std::path::Path, store: &TrustStore) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| format!("cannot create directory {}: {e}", parent.display()))?;
    }
    let json = serde_json::to_vec_pretty(store)
        .map_err(|e| format!("failed to serialize trust store: {e}"))?;
    if json.len() as u64 > TRUST_STORE_MAX_BYTES {
        return Err(format!(
            "refusing to write trust store above the {TRUST_STORE_MAX_BYTES} byte limit"
        ));
    }
    if let Ok(meta) = fs::symlink_metadata(path) {
        if meta.file_type().is_symlink() || !meta.is_file() {
            return Err(format!(
                "refusing non-regular or symlinked trust store at {}",
                path.display()
            ));
        }
    }
    let parent = path
        .parent()
        .ok_or_else(|| "trust store has no parent directory".to_string())?;
    let mut tmp = tempfile::NamedTempFile::new_in(parent)
        .map_err(|e| format!("failed to create trust-store temp file: {e}"))?;
    tmp.write_all(&json)
        .and_then(|()| tmp.as_file().sync_all())
        .map_err(|e| format!("failed to write trust-store temp file: {e}"))?;
    tmp.persist(path)
        .map_err(|e| format!("failed to publish {}: {}", path.display(), e.error))?;
    Ok(())
}

/// repo-0233: retained-parent cross-process lock for trust-store mutations. The
/// mutation sites load → modify → write; without a nonreplaceable lock two
/// processes can lose each other's entries after an atomic sidecar replacement.
struct TrustStoreLock {
    lock_destination: tirith_core::util::ContainedAtomicFile,
    data_destination: tirith_core::util::ContainedAtomicFile,
}

impl TrustStoreLock {
    fn data_destination(&self) -> &tirith_core::util::ContainedAtomicFile {
        &self.data_destination
    }

    fn publication_destination(&self) -> std::io::Result<tirith_core::util::ContainedAtomicFile> {
        let destination = self
            .lock_destination
            .prepare_sibling(std::ffi::OsStr::new("trust.json"))?;
        destination.inherit_observed_preimage(&self.data_destination)?;
        Ok(destination)
    }
}

fn trust_store_root<'a>(
    scope: &str,
    path: &'a std::path::Path,
) -> Result<&'a std::path::Path, String> {
    if scope == "repo" {
        path.parent().and_then(std::path::Path::parent)
    } else {
        path.parent()
    }
    .ok_or_else(|| "trust store has no containment root".to_string())
}

fn preflight_trust_store_mutation(scope: &str, path: &std::path::Path) -> Result<(), String> {
    let root = trust_store_root(scope, path)?;
    let policy = tirith_core::policy::Policy::discover_local_only(root.to_str());
    super::preflight_config_write_authorization(root, path, true, &policy, true)
        .map_err(|error| error.to_string())
}

fn lock_trust_store(scope: &str, path: &std::path::Path) -> Result<TrustStoreLock, String> {
    // Keep this primitive safe even if a future mutation caller forgets the
    // command-level preflight: no lock file or parent may be created first.
    preflight_trust_store_mutation(scope, path)?;
    let root = trust_store_root(scope, path)?;
    let lock_path = path.with_extension("lock");
    let destination = tirith_core::util::ContainedAtomicFile::prepare(root, &lock_path, true)
        .map_err(|error| format!("cannot bind trust-store lock: {error}"))?;
    destination
        .lock_parent_for_mutation()
        .map_err(|error| format!("cannot lock trust store: {error}"))?;
    let data_destination = destination
        .prepare_sibling(std::ffi::OsStr::new("trust.json"))
        .map_err(|error| format!("cannot bind trust-store data file: {error}"))?;
    Ok(TrustStoreLock {
        lock_destination: destination,
        data_destination,
    })
}

fn load_store_retained(
    destination: &tirith_core::util::ContainedAtomicFile,
    path: &std::path::Path,
) -> Result<TrustStore, String> {
    let bytes = match destination.read_capped(TRUST_STORE_MAX_BYTES) {
        Ok(bytes) => bytes,
        Err(tirith_core::util::OpenRegularError::NotFound) => return Ok(TrustStore::default()),
        Err(tirith_core::util::OpenRegularError::NotRegularFile) => {
            return Err(format!(
                "refusing non-regular or symlinked trust store at {}",
                path.display()
            ))
        }
        Err(tirith_core::util::OpenRegularError::TooLarge) => {
            return Err(format!(
                "trust store at {} exceeds the {} byte limit",
                path.display(),
                TRUST_STORE_MAX_BYTES
            ))
        }
        Err(tirith_core::util::OpenRegularError::Io(error)) => {
            return Err(format!("cannot read {}: {error}", path.display()))
        }
    };
    serde_json::from_slice(&bytes)
        .map_err(|error| format!("corrupt trust store at {}: {error}", path.display()))
}

fn load_store_scoped(scope: &str, path: &std::path::Path) -> Result<TrustStore, String> {
    if scope == "repo" {
        load_repo_store(path)
    } else {
        load_store(path)
    }
}

fn serialize_store_for_write(store: &TrustStore) -> Result<Vec<u8>, String> {
    let bytes = serde_json::to_vec_pretty(store)
        .map_err(|error| format!("failed to serialize trust store: {error}"))?;
    if bytes.len() as u64 > TRUST_STORE_MAX_BYTES {
        return Err(format!(
            "refusing to write trust store above the {TRUST_STORE_MAX_BYTES} byte limit"
        ));
    }
    Ok(bytes)
}

/// Publish while the caller's cross-process mutation lock remains held, but
/// require the task permit to bind the exact serialized store first.
#[cfg(test)]
fn write_store_scoped_permitted(
    scope: &str,
    path: &std::path::Path,
    store: &TrustStore,
) -> Result<(), String> {
    let root = trust_store_root(scope, path)?;
    let bytes = serialize_store_for_write(store)?;
    let policy = tirith_core::policy::Policy::discover_local_only(root.to_str());
    super::preflight_config_write_authorization(root, path, true, &policy, true)
        .map_err(|error| error.to_string())?;
    let destination = tirith_core::util::ContainedAtomicFile::prepare(root, path, true)
        .map_err(|error| error.to_string())?;
    super::write_prepared_config_file_permitted(
        root,
        path,
        destination,
        &bytes,
        true,
        &policy,
        true,
    )
    .map_err(|error| error.to_string())
}

fn write_store_scoped_permitted_locked(
    scope: &str,
    path: &std::path::Path,
    store: &TrustStore,
    lock: &TrustStoreLock,
) -> Result<(), String> {
    let root = trust_store_root(scope, path)?;
    let bytes = serialize_store_for_write(store)?;
    let policy = tirith_core::policy::Policy::discover_local_only(root.to_str());
    super::preflight_config_write_authorization(root, path, true, &policy, true)
        .map_err(|error| error.to_string())?;
    let destination = lock
        .publication_destination()
        .map_err(|error| error.to_string())?;
    super::write_prepared_config_file_permitted(
        root,
        path,
        destination,
        &bytes,
        true,
        &policy,
        true,
    )
    .map_err(|error| error.to_string())?;
    let read_back = lock
        .data_destination()
        .read_capped(bytes.len().saturating_add(1) as u64)
        .map_err(|_| "written trust store failed exact read-back validation".to_string())?;
    if read_back != bytes {
        return Err("written trust store failed exact read-back validation".to_string());
    }
    Ok(())
}

#[cfg(unix)]
fn open_repo_trust_dir(path: &std::path::Path, create: bool) -> Result<std::fs::File, String> {
    use std::ffi::CString;
    use std::os::fd::{AsRawFd, FromRawFd};
    use std::os::unix::fs::OpenOptionsExt as _;

    let root = path
        .parent()
        .and_then(std::path::Path::parent)
        .ok_or_else(|| "repo trust path is not <root>/.tirith/trust.json".to_string())?;
    // O_NOFOLLOW on the root too. Both callers derive it from
    // `find_repo_root(None)`, which starts at `std::env::current_dir()` —
    // `getcwd()`, whose result POSIX guarantees has no symlink components — and
    // then only ascends with `parent()`. So the root cannot be a symlink here
    // and this never costs a legitimate caller an ELOOP; it is free insurance
    // for any future caller that does not come from getcwd.
    let root_fd = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(root)
        .map_err(|e| format!("cannot open repository root {}: {e}", root.display()))?;
    let name = CString::new(".tirith").expect("static component has no NUL");
    if create {
        let rc = unsafe { libc::mkdirat(root_fd.as_raw_fd(), name.as_ptr(), 0o755) };
        if rc != 0 {
            let error = io::Error::last_os_error();
            if error.kind() != io::ErrorKind::AlreadyExists {
                return Err(format!("cannot create repo .tirith directory: {error}"));
            }
        }
    }
    let fd = unsafe {
        libc::openat(
            root_fd.as_raw_fd(),
            name.as_ptr(),
            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
        )
    };
    if fd < 0 {
        return Err(format!(
            "refusing repo trust path with a missing, symlinked, or non-directory .tirith component: {}",
            io::Error::last_os_error()
        ));
    }
    // SAFETY: `openat` returned a fresh owned descriptor.
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

#[cfg(unix)]
fn load_repo_store(path: &std::path::Path) -> Result<TrustStore, String> {
    use std::ffi::CString;
    use std::os::fd::{AsRawFd, FromRawFd};

    let dir = match open_repo_trust_dir(path, false) {
        Ok(dir) => dir,
        Err(error) => match path.parent().map(fs::symlink_metadata) {
            Some(Err(io_error)) if io_error.kind() == io::ErrorKind::NotFound => {
                return Ok(TrustStore::default())
            }
            _ => return Err(error),
        },
    };
    let name = CString::new("trust.json").expect("static component has no NUL");
    let fd = unsafe {
        libc::openat(
            dir.as_raw_fd(),
            name.as_ptr(),
            libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC,
        )
    };
    if fd < 0 {
        let error = io::Error::last_os_error();
        if error.kind() == io::ErrorKind::NotFound {
            return Ok(TrustStore::default());
        }
        return Err(format!(
            "refusing repo trust store {}: {error}",
            path.display()
        ));
    }
    // SAFETY: `openat` returned a fresh owned descriptor.
    let file = unsafe { std::fs::File::from_raw_fd(fd) };
    let meta = file
        .metadata()
        .map_err(|e| format!("cannot inspect repo trust store: {e}"))?;
    if !meta.is_file() {
        return Err("repo trust store is not a regular file".to_string());
    }
    if meta.len() > TRUST_STORE_MAX_BYTES {
        return Err(format!(
            "repo trust store exceeds the {TRUST_STORE_MAX_BYTES} byte limit"
        ));
    }
    let mut bytes = Vec::new();
    file.take(TRUST_STORE_MAX_BYTES + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| format!("cannot read repo trust store: {e}"))?;
    if bytes.len() as u64 > TRUST_STORE_MAX_BYTES {
        return Err(format!(
            "repo trust store exceeds the {TRUST_STORE_MAX_BYTES} byte limit"
        ));
    }
    serde_json::from_slice(&bytes)
        .map_err(|e| format!("corrupt trust store at {}: {e}", path.display()))
}

#[cfg(all(unix, test))]
fn write_repo_store(path: &std::path::Path, store: &TrustStore) -> Result<(), String> {
    use std::ffi::CString;
    use std::os::fd::{AsRawFd, FromRawFd};

    let dir = open_repo_trust_dir(path, true)?;
    let dest = CString::new("trust.json").expect("static component has no NUL");

    // Refuse an existing symlink, directory, FIFO, device, or socket. A later
    // destination swap is still safe: renameat replaces the directory entry and
    // never follows it.
    let existing_fd = unsafe {
        libc::openat(
            dir.as_raw_fd(),
            dest.as_ptr(),
            libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC,
        )
    };
    if existing_fd >= 0 {
        // SAFETY: `openat` returned a fresh owned descriptor.
        let existing = unsafe { std::fs::File::from_raw_fd(existing_fd) };
        if !existing
            .metadata()
            .map_err(|e| format!("cannot inspect repo trust destination: {e}"))?
            .is_file()
        {
            return Err("repo trust destination is not a regular file".to_string());
        }
    } else {
        let error = io::Error::last_os_error();
        if error.kind() != io::ErrorKind::NotFound {
            return Err(format!("refusing repo trust destination: {error}"));
        }
    }

    let bytes = serde_json::to_vec_pretty(store)
        .map_err(|e| format!("failed to serialize trust store: {e}"))?;
    if bytes.len() as u64 > TRUST_STORE_MAX_BYTES {
        return Err(format!(
            "refusing to write repo trust store above the {TRUST_STORE_MAX_BYTES} byte limit"
        ));
    }
    let temp_name = format!(".trust.json.{}.tmp", uuid::Uuid::new_v4());
    let temp = CString::new(temp_name.as_str()).expect("UUID temp name has no NUL");
    let temp_fd = unsafe {
        libc::openat(
            dir.as_raw_fd(),
            temp.as_ptr(),
            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC,
            0o666,
        )
    };
    if temp_fd < 0 {
        return Err(format!(
            "cannot create repo trust temp file: {}",
            io::Error::last_os_error()
        ));
    }
    // SAFETY: `openat` returned a fresh owned descriptor.
    let mut temp_file = unsafe { std::fs::File::from_raw_fd(temp_fd) };
    let publish = temp_file
        .write_all(&bytes)
        .and_then(|()| temp_file.sync_all())
        .and_then(|()| {
            let rc = unsafe {
                libc::renameat(
                    dir.as_raw_fd(),
                    temp.as_ptr(),
                    dir.as_raw_fd(),
                    dest.as_ptr(),
                )
            };
            if rc == 0 {
                Ok(())
            } else {
                Err(io::Error::last_os_error())
            }
        });
    if let Err(error) = publish {
        unsafe {
            libc::unlinkat(dir.as_raw_fd(), temp.as_ptr(), 0);
        }
        return Err(format!(
            "failed to atomically publish repo trust store: {error}"
        ));
    }
    dir.sync_all()
        .map_err(|e| format!("failed to sync repo trust directory: {e}"))?;
    Ok(())
}

#[cfg(windows)]
mod windows_repo_store {
    use super::{fs, io, Read, TrustStore, Write, TRUST_STORE_MAX_BYTES};
    use std::os::windows::ffi::OsStrExt as _;
    use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, RawHandle};
    use std::path::{Path, PathBuf};

    use windows::core::{HRESULT, PCWSTR};
    use windows::Win32::Foundation::{
        CloseHandle, ERROR_ALREADY_EXISTS, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, HANDLE,
    };
    use windows::Win32::Storage::FileSystem::{
        CreateDirectoryW, CreateFileW, FileDispositionInfo, GetFileInformationByHandle,
        GetFinalPathNameByHandleW, SetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
        CREATE_NEW, DELETE, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_NORMAL,
        FILE_ATTRIBUTE_REPARSE_POINT, FILE_DISPOSITION_INFO, FILE_FLAG_BACKUP_SEMANTICS,
        FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_LIST_DIRECTORY,
        FILE_READ_ATTRIBUTES, FILE_RENAME_INFO_0, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TRAVERSE,
        OPEN_EXISTING,
    };

    struct OwnedHandle(HANDLE);

    impl OwnedHandle {
        fn into_file(self) -> fs::File {
            let raw = self.0 .0 as RawHandle;
            std::mem::forget(self);
            // SAFETY: the handle is valid, uniquely owned, and forgotten above.
            unsafe { fs::File::from_raw_handle(raw) }
        }
    }

    impl Drop for OwnedHandle {
        fn drop(&mut self) {
            // SAFETY: `OwnedHandle` owns exactly one live Win32 handle.
            unsafe {
                let _ = CloseHandle(self.0);
            }
        }
    }

    struct RepoTrustDir {
        path: PathBuf,
        final_path: String,
        _root: OwnedHandle,
        directory: OwnedHandle,
    }

    #[derive(Clone, Copy, PartialEq, Eq)]
    struct FileIdentity {
        volume: u32,
        index: u64,
        size: u64,
        last_write: u64,
        attributes: u32,
    }

    #[repr(C)]
    struct TrustRenameInfo {
        _anonymous: FILE_RENAME_INFO_0,
        _root_directory: HANDLE,
        _file_name_length: u32,
        _file_name: [u16; 10],
    }

    const TRUST_FILE_NAME_UTF16: [u16; 10] = [
        b't' as u16,
        b'r' as u16,
        b'u' as u16,
        b's' as u16,
        b't' as u16,
        b'.' as u16,
        b'j' as u16,
        b's' as u16,
        b'o' as u16,
        b'n' as u16,
    ];

    fn wide(path: &Path) -> Vec<u16> {
        path.as_os_str().encode_wide().chain(Some(0)).collect()
    }

    fn is_win32(error: &windows::core::Error, code: u32) -> bool {
        error.code() == HRESULT::from_win32(code)
    }

    fn final_path(handle: HANDLE) -> Result<String, String> {
        let mut buffer = vec![0u16; 512];
        loop {
            let length =
                unsafe { GetFinalPathNameByHandleW(handle, &mut buffer, Default::default()) };
            if length == 0 {
                return Err(format!(
                    "cannot resolve path held by repo trust handle: {}",
                    io::Error::last_os_error()
                ));
            }
            if (length as usize) < buffer.len() {
                return Ok(String::from_utf16_lossy(&buffer[..length as usize]));
            }
            buffer.resize(length as usize + 1, 0);
        }
    }

    fn normalized_final_path(path: &str) -> String {
        let path = path.replace('/', "\\");
        let path = path
            .strip_prefix(r"\\?\UNC\")
            .map(|rest| format!(r"\\{rest}"))
            .or_else(|| path.strip_prefix(r"\\?\").map(str::to_owned))
            .unwrap_or(path);
        path.trim_end_matches('\\').to_lowercase()
    }

    fn is_exact_child(parent: &str, child: &str, name: &str) -> bool {
        let expected = format!("{}\\{}", normalized_final_path(parent), name.to_lowercase());
        normalized_final_path(child) == expected
    }

    fn inspect_directory(handle: HANDLE, path: &Path) -> Result<(), String> {
        let mut info = BY_HANDLE_FILE_INFORMATION::default();
        unsafe { GetFileInformationByHandle(handle, &mut info) }.map_err(|error| {
            format!(
                "cannot inspect repo trust directory {}: {error}",
                path.display()
            )
        })?;
        if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT.0 != 0
            || info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY.0 == 0
        {
            return Err(format!(
                "refusing reparse or non-directory repo trust component {}",
                path.display()
            ));
        }
        Ok(())
    }

    fn open_directory(path: &Path) -> Result<Option<OwnedHandle>, String> {
        let path_wide = wide(path);
        let handle = match unsafe {
            CreateFileW(
                PCWSTR(path_wide.as_ptr()),
                (FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES).0,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                None,
                OPEN_EXISTING,
                FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
                None,
            )
        } {
            Ok(handle) => handle,
            Err(error)
                if is_win32(&error, ERROR_FILE_NOT_FOUND.0)
                    || is_win32(&error, ERROR_PATH_NOT_FOUND.0) =>
            {
                return Ok(None);
            }
            Err(error) => {
                return Err(format!(
                    "cannot open repo trust directory {}: {error}",
                    path.display()
                ));
            }
        };
        let owned = OwnedHandle(handle);
        inspect_directory(handle, path)?;
        Ok(Some(owned))
    }

    fn split_path(path: &Path) -> Result<(&Path, &Path), String> {
        if path.file_name() != Some(std::ffi::OsStr::new("trust.json")) {
            return Err("repo trust path is not <root>/.tirith/trust.json".to_string());
        }
        let directory = path
            .parent()
            .filter(|parent| parent.file_name() == Some(std::ffi::OsStr::new(".tirith")))
            .ok_or_else(|| "repo trust path is not <root>/.tirith/trust.json".to_string())?;
        let root = directory
            .parent()
            .ok_or_else(|| "repo trust path is not <root>/.tirith/trust.json".to_string())?;
        Ok((root, directory))
    }

    fn open_repo_dir(path: &Path, create: bool) -> Result<Option<RepoTrustDir>, String> {
        let (root_path, directory_path) = split_path(path)?;
        let root = open_directory(root_path)?
            .ok_or_else(|| format!("repository root {} does not exist", root_path.display()))?;
        let root_final = final_path(root.0)?;

        let directory = match open_directory(directory_path)? {
            Some(directory) => directory,
            None if !create => return Ok(None),
            None => {
                let directory_wide = wide(directory_path);
                if let Err(error) =
                    unsafe { CreateDirectoryW(PCWSTR(directory_wide.as_ptr()), None) }
                {
                    if !is_win32(&error, ERROR_ALREADY_EXISTS.0) {
                        return Err(format!(
                            "cannot create repo trust directory {}: {error}",
                            directory_path.display()
                        ));
                    }
                }
                open_directory(directory_path)?.ok_or_else(|| {
                    format!(
                        "repo trust directory {} disappeared after creation",
                        directory_path.display()
                    )
                })?
            }
        };
        let directory_final = final_path(directory.0)?;
        if !is_exact_child(&root_final, &directory_final, ".tirith") {
            return Err(
                "repo trust directory resolves outside the held repository root".to_string(),
            );
        }
        Ok(Some(RepoTrustDir {
            path: directory_path.to_path_buf(),
            final_path: directory_final,
            _root: root,
            directory,
        }))
    }

    fn inspect_regular(handle: HANDLE, path: &Path) -> Result<FileIdentity, String> {
        let mut info = BY_HANDLE_FILE_INFORMATION::default();
        unsafe { GetFileInformationByHandle(handle, &mut info) }.map_err(|error| {
            format!("cannot inspect repo trust file {}: {error}", path.display())
        })?;
        if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT.0 != 0
            || info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY.0 != 0
        {
            return Err(format!(
                "refusing reparse or non-regular repo trust file {}",
                path.display()
            ));
        }
        Ok(FileIdentity {
            volume: info.dwVolumeSerialNumber,
            index: ((info.nFileIndexHigh as u64) << 32) | info.nFileIndexLow as u64,
            size: ((info.nFileSizeHigh as u64) << 32) | info.nFileSizeLow as u64,
            last_write: ((info.ftLastWriteTime.dwHighDateTime as u64) << 32)
                | info.ftLastWriteTime.dwLowDateTime as u64,
            attributes: info.dwFileAttributes,
        })
    }

    fn open_regular_file(
        directory: &RepoTrustDir,
        path: &Path,
    ) -> Result<Option<(fs::File, FileIdentity)>, String> {
        let path_wide = wide(path);
        let handle = match unsafe {
            CreateFileW(
                PCWSTR(path_wide.as_ptr()),
                (FILE_GENERIC_READ | FILE_READ_ATTRIBUTES).0,
                FILE_SHARE_READ,
                None,
                OPEN_EXISTING,
                FILE_FLAG_OPEN_REPARSE_POINT,
                None,
            )
        } {
            Ok(handle) => handle,
            Err(error)
                if is_win32(&error, ERROR_FILE_NOT_FOUND.0)
                    || is_win32(&error, ERROR_PATH_NOT_FOUND.0) =>
            {
                return Ok(None);
            }
            Err(error) => {
                return Err(format!(
                    "refusing repo trust file {}: {error}",
                    path.display()
                ));
            }
        };
        let owned = OwnedHandle(handle);
        let identity = inspect_regular(handle, path)?;
        let file_final = final_path(handle)?;
        if !is_exact_child(&directory.final_path, &file_final, "trust.json") {
            return Err("repo trust file resolves outside the held .tirith directory".to_string());
        }
        Ok(Some((owned.into_file(), identity)))
    }

    fn mark_held_file_for_deletion(file: &fs::File) -> Result<(), String> {
        let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
        unsafe {
            SetFileInformationByHandle(
                HANDLE(file.as_raw_handle()),
                FileDispositionInfo,
                (&disposition as *const FILE_DISPOSITION_INFO).cast(),
                std::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
            )
        }
        .map_err(|error| format!("cannot remove exact repo trust temp identity: {error}"))
    }

    fn cleanup_suffix(file: &fs::File) -> String {
        mark_held_file_for_deletion(file)
            .err()
            .map(|error| format!("; exact-handle cleanup also failed: {error}"))
            .unwrap_or_default()
    }

    pub(super) fn load(path: &Path) -> Result<TrustStore, String> {
        let Some(directory) = open_repo_dir(path, false)? else {
            return Ok(TrustStore::default());
        };
        let Some((mut file, before)) = open_regular_file(&directory, path)? else {
            return Ok(TrustStore::default());
        };
        if before.size > TRUST_STORE_MAX_BYTES {
            return Err(format!(
                "repo trust store exceeds the {TRUST_STORE_MAX_BYTES} byte limit"
            ));
        }
        let mut bytes = Vec::with_capacity(before.size as usize);
        (&mut file)
            .take(TRUST_STORE_MAX_BYTES + 1)
            .read_to_end(&mut bytes)
            .map_err(|error| format!("cannot read repo trust store: {error}"))?;
        if bytes.len() as u64 > TRUST_STORE_MAX_BYTES {
            return Err(format!(
                "repo trust store exceeds the {TRUST_STORE_MAX_BYTES} byte limit"
            ));
        }
        let after = inspect_regular(HANDLE(file.as_raw_handle()), path)?;
        if before != after || bytes.len() as u64 != after.size {
            return Err("repo trust store changed while being read".to_string());
        }
        serde_json::from_slice(&bytes)
            .map_err(|error| format!("corrupt trust store at {}: {error}", path.display()))
    }

    pub(super) fn write(path: &Path, store: &TrustStore) -> Result<(), String> {
        let bytes = serde_json::to_vec_pretty(store)
            .map_err(|error| format!("failed to serialize trust store: {error}"))?;
        if bytes.len() as u64 > TRUST_STORE_MAX_BYTES {
            return Err(format!(
                "refusing to write repo trust store above the {TRUST_STORE_MAX_BYTES} byte limit"
            ));
        }

        let directory = open_repo_dir(path, true)?
            .ok_or_else(|| "repo trust directory disappeared during creation".to_string())?;
        // Reject an existing reparse point or non-regular object. A later
        // destination swap is safe because publication replaces the directory
        // entry through the held temporary-file and parent-directory handles.
        drop(open_regular_file(&directory, path)?);

        let temp_name = format!(".trust.json.{}.tmp", uuid::Uuid::new_v4().simple());
        let temp_path = directory.path.join(&temp_name);
        let temp_wide = wide(&temp_path);
        let handle = unsafe {
            CreateFileW(
                PCWSTR(temp_wide.as_ptr()),
                (FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES | DELETE).0,
                Default::default(),
                None,
                CREATE_NEW,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
                None,
            )
        }
        .map_err(|error| format!("cannot create exclusive repo trust temp file: {error}"))?;
        let owned = OwnedHandle(handle);
        let temp_final = match final_path(handle) {
            Ok(path) => path,
            Err(error) => {
                let file = owned.into_file();
                let cleanup = cleanup_suffix(&file);
                return Err(format!("{error}{cleanup}"));
            }
        };
        if !is_exact_child(&directory.final_path, &temp_final, &temp_name) {
            let file = owned.into_file();
            let cleanup = cleanup_suffix(&file);
            return Err(format!(
                "repo trust temp file resolves outside the held .tirith directory{cleanup}"
            ));
        }
        let mut file = owned.into_file();
        if let Err(error) = file.write_all(&bytes).and_then(|()| file.sync_all()) {
            let cleanup = cleanup_suffix(&file);
            return Err(format!(
                "failed to write and sync repo trust temp file: {error}{cleanup}"
            ));
        }
        let temp_identity = match inspect_regular(HANDLE(file.as_raw_handle()), &temp_path) {
            Ok(identity) => identity,
            Err(error) => {
                let cleanup = cleanup_suffix(&file);
                return Err(format!("{error}{cleanup}"));
            }
        };
        if temp_identity.size != bytes.len() as u64 {
            let cleanup = cleanup_suffix(&file);
            return Err(format!(
                "repo trust temp file size changed before publication{cleanup}"
            ));
        }

        let mut rename_mode = FILE_RENAME_INFO_0::default();
        rename_mode.ReplaceIfExists = true;
        let rename = TrustRenameInfo {
            _anonymous: rename_mode,
            _root_directory: directory.directory.0,
            _file_name_length: (TRUST_FILE_NAME_UTF16.len() * std::mem::size_of::<u16>()) as u32,
            _file_name: TRUST_FILE_NAME_UTF16,
        };
        // The Win32 wrapper (SetFileInformationByHandle + FileRenameInfo)
        // rejects a non-NULL RootDirectory with ERROR_INVALID_PARAMETER: it
        // accepts full destination paths only. The retained directory handle
        // IS the anchor of this publish (no by-name re-resolution), so call
        // the NT service directly — FileRenameInformation honors
        // handle-relative names, and TrustRenameInfo's layout doubles as the
        // kernel struct (the pinned layout test below covers the shared
        // offsets).
        let mut io_status = windows::Win32::System::IO::IO_STATUS_BLOCK::default();
        let status = unsafe {
            windows::Wdk::Storage::FileSystem::NtSetInformationFile(
                HANDLE(file.as_raw_handle()),
                &mut io_status,
                (&rename as *const TrustRenameInfo).cast(),
                std::mem::size_of::<TrustRenameInfo>() as u32,
                windows::Wdk::Storage::FileSystem::FileRenameInformation,
            )
        };
        if status.0 < 0 {
            let code = unsafe { windows::Win32::Foundation::RtlNtStatusToDosError(status) };
            let error = std::io::Error::from_raw_os_error(code as i32);
            let cleanup = cleanup_suffix(&file);
            return Err(format!(
                "failed to atomically publish repo trust store: {error}{cleanup}"
            ));
        }
        Ok(())
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use windows::Win32::Storage::FileSystem::FILE_RENAME_INFO;

        #[test]
        fn fixed_rename_buffer_matches_win32_header_layout() {
            assert_eq!(
                std::mem::offset_of!(TrustRenameInfo, _anonymous),
                std::mem::offset_of!(FILE_RENAME_INFO, Anonymous)
            );
            assert_eq!(
                std::mem::offset_of!(TrustRenameInfo, _root_directory),
                std::mem::offset_of!(FILE_RENAME_INFO, RootDirectory)
            );
            assert_eq!(
                std::mem::offset_of!(TrustRenameInfo, _file_name_length),
                std::mem::offset_of!(FILE_RENAME_INFO, FileNameLength)
            );
            assert_eq!(
                std::mem::offset_of!(TrustRenameInfo, _file_name),
                std::mem::offset_of!(FILE_RENAME_INFO, FileName)
            );
            assert_eq!(
                std::mem::size_of::<TrustRenameInfo>(),
                std::mem::offset_of!(FILE_RENAME_INFO, FileName)
                    + std::mem::size_of_val(&TRUST_FILE_NAME_UTF16)
            );
        }
    }
}

#[cfg(windows)]
fn load_repo_store(path: &std::path::Path) -> Result<TrustStore, String> {
    windows_repo_store::load(path)
}

#[cfg(all(windows, test))]
fn write_repo_store(path: &std::path::Path, store: &TrustStore) -> Result<(), String> {
    windows_repo_store::write(path, store)
}

#[cfg(all(not(unix), not(windows)))]
fn load_repo_store(path: &std::path::Path) -> Result<TrustStore, String> {
    let parent = path
        .parent()
        .ok_or_else(|| "repo trust path has no parent".to_string())?;
    match fs::symlink_metadata(parent) {
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(TrustStore::default()),
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
            return Err("refusing symlinked or non-directory repo trust path".to_string())
        }
        Ok(_) => {}
        Err(error) => return Err(format!("cannot inspect repo trust directory: {error}")),
    }
    if matches!(fs::symlink_metadata(path), Err(error) if error.kind() == io::ErrorKind::NotFound) {
        return Ok(TrustStore::default());
    }
    Err(
        "repo-scoped trust requires descriptor-relative no-symlink filesystem operations, which are not available on this platform; use --scope user"
            .to_string(),
    )
}

#[cfg(all(not(unix), not(windows), test))]
fn write_repo_store(path: &std::path::Path, store: &TrustStore) -> Result<(), String> {
    let _ = (path, store);
    Err(
        "repo-scoped trust requires descriptor-relative no-symlink filesystem operations, which are not available on this platform; use --scope user"
            .to_string(),
    )
}

/// Parse a duration string like "1h", "7d", "30d" into an expiry timestamp.
fn parse_ttl(ttl: &str) -> Result<String, String> {
    let ttl = ttl.trim();
    if ttl.is_empty() {
        return Err("empty TTL".to_string());
    }

    let (num_str, unit) = if let Some(n) = ttl.strip_suffix('d') {
        (n, "d")
    } else if let Some(n) = ttl.strip_suffix('h') {
        (n, "h")
    } else if let Some(n) = ttl.strip_suffix('m') {
        (n, "m")
    } else {
        return Err(format!(
            "unsupported TTL format: {ttl} (use e.g. 1h, 7d, 30d)"
        ));
    };

    let num: u64 = num_str
        .parse()
        .map_err(|_| format!("invalid TTL number: {num_str}"))?;
    if num == 0 {
        return Err("TTL must be > 0".to_string());
    }

    let multiplier: u64 = match unit {
        "m" => 60,
        "h" => 3600,
        "d" => 86400,
        _ => unreachable!(),
    };

    let seconds = num
        .checked_mul(multiplier)
        .ok_or_else(|| format!("TTL value too large: {num}{unit}"))?;

    let seconds_i64 =
        i64::try_from(seconds).map_err(|_| format!("TTL value too large: {num}{unit}"))?;

    let expires = chrono::Utc::now() + chrono::Duration::seconds(seconds_i64);
    Ok(expires.to_rfc3339())
}

/// Check if an entry is expired. No `ttl_expires` (older/`--permanent` entries)
/// never expires; an unparseable `ttl_expires` is treated as NOT expired so a
/// malformed timestamp never silently revokes trust.
fn is_expired(entry: &TrustEntry) -> bool {
    if let Some(ref exp) = entry.ttl_expires {
        if let Ok(expiry) = chrono::DateTime::parse_from_rfc3339(exp) {
            return expiry < chrono::Utc::now();
        }
    }
    false
}

/// Format the time remaining until an RFC3339 expiry, e.g. "in 6d" / "in 2h".
/// Returns `None` for a permanent (no-TTL) entry, "expired" when already past.
fn humanize_expiry(ttl_expires: Option<&str>) -> Option<String> {
    let exp = ttl_expires?;
    let expiry = chrono::DateTime::parse_from_rfc3339(exp).ok()?;
    let now = chrono::Utc::now();
    let delta = expiry.signed_duration_since(now);
    if delta.num_seconds() <= 0 {
        return Some("expired".to_string());
    }
    let secs = delta.num_seconds();
    let human = if secs >= 86400 {
        format!("in {}d", secs / 86400)
    } else if secs >= 3600 {
        format!("in {}h", secs / 3600)
    } else if secs >= 60 {
        format!("in {}m", secs / 60)
    } else {
        format!("in {secs}s")
    };
    Some(human)
}

/// Validate a pattern for trust add.
fn validate_pattern(pattern: &str, policy: &tirith_core::policy::Policy) -> Result<(), String> {
    tirith_core::policy::validate_trust_pattern(pattern)?;
    if policy.is_blocklisted(pattern) {
        return Err(format!(
            "pattern '{pattern}' is in the blocklist and cannot be trusted"
        ));
    }
    Ok(())
}

/// `tirith trust add <pattern> [--rule <rule_id>] [--ttl <duration>]
/// [--permanent] [--broad] [--reason <text>] [--scope user|repo]`
#[allow(clippy::too_many_arguments)]
pub fn add(
    pattern: &str,
    rule_id: Option<&str>,
    ttl: Option<&str>,
    permanent: bool,
    broad: bool,
    reason: Option<&str>,
    scope: &str,
    json: bool,
) -> i32 {
    if let Some(rule_id) = rule_id {
        if human(rule_id) != rule_id {
            eprintln!("tirith: trust add: rule id contains unsafe display characters");
            return 1;
        }
    }
    if let Some(reason) = reason {
        if tirith_core::mcp::output_filter::sanitize_for_display(reason) != reason {
            eprintln!("tirith: trust add: reason contains unsafe display characters");
            return 1;
        }
    }
    // Validate against policy plus flat user/org blocklists loaded below.
    let mut policy = tirith_core::policy::Policy::discover(None);
    policy.load_user_lists();
    policy.load_org_lists(None);
    if let Err(e) = validate_pattern(pattern, &policy) {
        eprintln!("{}", trust_error_line("add", &e));
        return 1;
    }

    // --ttl and --permanent are mutually exclusive (clap enforces it too; guard
    // here for the library-call path).
    if permanent && ttl.is_some() {
        eprintln!("tirith: trust add: --permanent cannot be combined with --ttl");
        return 1;
    }

    // Narrow-trust-by-default: a broad pattern (domain/wildcard/bare-TLD) requires
    // an explicit `--broad` opt-in.
    let scope_kind = classify_scope(pattern);
    if scope_kind.is_broad() && !broad {
        eprintln!(
            "tirith: trust add: '{}' is a {} pattern — {}.",
            human(pattern),
            scope_kind.label(),
            scope_kind.coverage()
        );
        eprintln!(
            "  Trust the narrowest thing that works (a specific URL or path), \
             or pass --broad to accept this scope."
        );
        if scope_kind == ScopeKind::BareTld {
            eprintln!(
                "  Note: trusting a bare TLD allows EVERY host under '.{}' — \
                 this is almost never what you want.",
                human(pattern)
            );
        }
        return 1;
    }

    let path = match trust_store_path(scope) {
        Ok(p) => p,
        Err(e) => {
            print_trust_error("add", &e, Some(pattern));
            return 1;
        }
    };

    if let Err(error) = preflight_trust_store_mutation(scope, &path) {
        eprintln!("tirith: trust store mutation refused: {error}");
        return 1;
    }
    // repo-0233: hold the store lock across load → mutate → write.
    let store_lock = match lock_trust_store(scope, &path) {
        Ok(guard) => guard,
        Err(e) => {
            eprintln!("tirith: trust store lock failed: {e}");
            return 1;
        }
    };
    let mut store = match load_store_retained(store_lock.data_destination(), &path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{}", trust_error_line("add", &e));
            return 1;
        }
    };

    // Resolve the effective TTL:
    //   --permanent          -> no expiry
    //   --ttl <d>            -> that duration
    //   neither              -> DEFAULT_TTL (trust expires by default)
    let (ttl_expires, ttl_label): (Option<String>, Option<String>) = if permanent {
        (None, None)
    } else {
        let effective = ttl.unwrap_or(DEFAULT_TTL);
        match parse_ttl(effective) {
            Ok(exp) => (Some(exp), Some(effective.to_string())),
            Err(e) => {
                eprintln!("{}", trust_error_line("add", &e));
                return 1;
            }
        }
    };

    let entry = TrustEntry {
        pattern: pattern.to_string(),
        rule_id: rule_id.map(String::from),
        ttl_expires: ttl_expires.clone(),
        added: chrono::Utc::now().to_rfc3339(),
        source: "cli".to_string(),
        reason: reason.map(str::to_string),
    };

    store.entries.push(entry);

    if let Err(e) = write_store_scoped_permitted_locked(scope, &path, &store, &store_lock) {
        eprintln!("{}", trust_error_line("add", &e));
        return 1;
    }

    if let Err(error) =
        tirith_core::audit::log_trust_change(pattern, rule_id, "add", ttl_expires.as_deref(), scope)
    {
        eprintln!(
            "{}",
            trust_error_line(
                "add",
                &format!("trust store changed but audit append failed: {error}")
            )
        );
        return 1;
    }

    if json {
        let out = serde_json::json!({
            "added": pattern,
            "scope": scope,
            "rule_id": rule_id,
            "scope_kind": scope_kind,
            "scope_coverage": scope_kind.coverage(),
            "ttl": ttl_label,
            "ttl_expires": ttl_expires,
            "permanent": permanent,
            "reason": reason,
        });
        return print_json(&out);
    }
    let ttl_note = match &ttl_label {
        Some(t) => format!(", ttl: {t}"),
        None => ", permanent (no expiry)".to_string(),
    };
    eprintln!(
        "tirith: trusted '{}' (scope: {}, {} pattern{})",
        human(pattern),
        human(scope),
        scope_kind.label(),
        human(&ttl_note)
    );
    if scope_kind.is_dangerous() {
        eprintln!(
            "  warning: this is a {} entry — {}.",
            scope_kind.label(),
            scope_kind.coverage()
        );
    }
    0
}

/// `tirith trust list [--rule <id>] [--json] [--expired] [--scope user|repo|all]`
pub fn list(rule_filter: Option<&str>, json: bool, show_expired: bool, scope: &str) -> i32 {
    if !matches!(scope, "user" | "repo" | "all") {
        eprintln!(
            "{}",
            unknown_scope_line("list", scope, "'user', 'repo', or 'all'")
        );
        return 1;
    }

    let mut rows: Vec<TrustListRow> = match collect_rows(scope, show_expired) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("{}", trust_error_line("list", &e));
            return 1;
        }
    };

    if let Some(filter) = rule_filter {
        rows.retain(|r| {
            r.rule_id
                .as_ref()
                .map(|id| id.eq_ignore_ascii_case(filter))
                .unwrap_or(false)
        });
    }

    if json {
        return print_json(&rows);
    }
    if rows.is_empty() {
        eprintln!("tirith: no trust entries found");
    } else {
        let max_pat = rows
            .iter()
            .map(|r| human(&r.pattern).len())
            .max()
            .unwrap_or(7)
            .max(7);
        let max_src = rows
            .iter()
            .map(|r| human(&r.source).len())
            .max()
            .unwrap_or(6)
            .max(6);
        let max_rule = rows
            .iter()
            .map(|r| r.rule_id.as_ref().map(|s| human(s).len()).unwrap_or(1))
            .max()
            .unwrap_or(4)
            .max(4);
        // A '!' suffix marks a dangerously broad entry; size the SCOPE column
        // on the *rendered* string so the trailing '!' never breaks alignment.
        let scope_render = |row: &TrustListRow| -> String {
            if row.broad_warning {
                format!("{}!", row.scope_kind.label())
            } else {
                row.scope_kind.label().to_string()
            }
        };
        let max_scope = rows
            .iter()
            .map(|r| scope_render(r).len())
            .max()
            .unwrap_or(5)
            .max(5);

        eprintln!(
            "{:<max_pat$}  {:<max_rule$}  {:<max_scope$}  {:<max_src$}  EXPIRES",
            "PATTERN", "RULE", "SCOPE", "SOURCE"
        );
        let mut any_dangerous = false;
        for row in &rows {
            let pattern_display = human(&row.pattern);
            let rule_display = human(row.rule_id.as_deref().unwrap_or("-"));
            let source_display = human(&row.source);
            let expires_display = match (&row.expires, row.expired) {
                (Some(exp), true) => format!("{} (EXPIRED)", human(exp)),
                (Some(exp), false) => match humanize_expiry(Some(exp)) {
                    Some(h) => format!("{} ({})", human(exp), human(&h)),
                    None => human(exp),
                },
                (None, _) => "permanent".to_string(),
            };
            let scope_display = scope_render(row);
            if row.broad_warning {
                any_dangerous = true;
            }
            eprintln!(
                "{:<max_pat$}  {:<max_rule$}  {:<max_scope$}  {:<max_src$}  {}",
                pattern_display, rule_display, scope_display, source_display, expires_display
            );
        }
        if any_dangerous {
            eprintln!(
                "\ntirith: '!' marks dangerously broad entries (wildcard / bare TLD). \
                 Run 'tirith trust explain <pattern>' for detail."
            );
        }
    }

    0
}

/// Collect every trust-style row for the given scope. Shared by `list` and the
/// scope-visualisation paths. `show_expired` controls whether expired
/// TTL-bearing entries are included.
fn collect_rows(scope: &str, show_expired: bool) -> Result<Vec<TrustListRow>, String> {
    let mut rows: Vec<TrustListRow> = Vec::new();

    let scopes_to_load: Vec<&str> = match scope {
        "all" => vec!["user", "repo"],
        s => vec![s],
    };

    for s in &scopes_to_load {
        let path = match trust_store_path(s) {
            Ok(p) => p,
            Err(e) => {
                // "all" skips missing scopes (e.g., repo outside a git tree);
                // an explicit single scope is a hard error.
                if scope != "all" {
                    return Err(e);
                }
                continue;
            }
        };
        let store = load_store_scoped(s, &path)?;
        let source = format!("trust-{s}");
        for entry in &store.entries {
            let expired = is_expired(entry);
            if expired && !show_expired {
                continue;
            }
            rows.push(make_row(
                entry.pattern.clone(),
                entry.rule_id.clone(),
                source.clone(),
                entry.ttl_expires.clone(),
                expired,
            ));
        }
    }

    if scope == "all" {
        if let Some(config) = tirith_core::policy::config_dir() {
            let allowlist_path = config.join("allowlist");
            if let Ok(content) = fs::read_to_string(&allowlist_path) {
                for line in content.lines() {
                    let line = line.trim();
                    if !line.is_empty() && !line.starts_with('#') {
                        rows.push(make_row(
                            line.to_string(),
                            None,
                            "allowlist-user".to_string(),
                            None,
                            false,
                        ));
                    }
                }
            }
        }

        if let Some(repo_root) = tirith_core::policy::find_repo_root(None) {
            let allowlist_path = repo_root.join(".tirith").join("allowlist");
            if let Ok(content) = fs::read_to_string(&allowlist_path) {
                for line in content.lines() {
                    let line = line.trim();
                    if !line.is_empty() && !line.starts_with('#') {
                        rows.push(make_row(
                            line.to_string(),
                            None,
                            "allowlist-org".to_string(),
                            None,
                            false,
                        ));
                    }
                }
            }
        }

        let policy = tirith_core::policy::Policy::discover(None);
        for pattern in &policy.allowlist {
            // Skip patterns already surfaced from the flat allowlist files.
            if !rows
                .iter()
                .any(|r| r.pattern == *pattern && r.source.starts_with("allowlist"))
            {
                rows.push(make_row(
                    pattern.clone(),
                    None,
                    "policy".to_string(),
                    None,
                    false,
                ));
            }
        }
        for rule in &policy.allowlist_rules {
            for pattern in &rule.patterns {
                rows.push(make_row(
                    pattern.clone(),
                    Some(rule.rule_id.clone()),
                    "policy".to_string(),
                    None,
                    false,
                ));
            }
        }
    }

    Ok(rows)
}

/// Build a `TrustListRow`, computing the scope classification once.
fn make_row(
    pattern: String,
    rule_id: Option<String>,
    source: String,
    expires: Option<String>,
    expired: bool,
) -> TrustListRow {
    let scope_kind = classify_scope(&pattern);
    TrustListRow {
        pattern,
        rule_id,
        source,
        expires,
        expired,
        scope_kind,
        scope_coverage: scope_kind.coverage().to_string(),
        broad_warning: scope_kind.is_dangerous(),
    }
}

/// `tirith trust remove <pattern> [--rule <rule_id>] [--scope user|repo]`
pub fn remove(pattern: &str, rule_id: Option<&str>, scope: &str) -> i32 {
    let path = match trust_store_path(scope) {
        Ok(p) => p,
        Err(e) => {
            print_trust_error("remove", &e, Some(pattern));
            return 1;
        }
    };

    if let Err(error) = preflight_trust_store_mutation(scope, &path) {
        eprintln!("tirith: trust store mutation refused: {error}");
        return 1;
    }
    // repo-0233: hold the store lock across load → mutate → write.
    let store_lock = match lock_trust_store(scope, &path) {
        Ok(guard) => guard,
        Err(e) => {
            eprintln!("tirith: trust store lock failed: {e}");
            return 1;
        }
    };
    let mut store = match load_store_retained(store_lock.data_destination(), &path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{}", trust_error_line("remove", &e));
            return 1;
        }
    };
    let before_len = store.entries.len();

    store.entries.retain(|entry| {
        let pattern_matches = entry.pattern == pattern;
        let rule_matches = match (rule_id, &entry.rule_id) {
            (Some(filter), Some(entry_rule)) => filter.eq_ignore_ascii_case(entry_rule),
            (Some(_), None) => false,
            (None, _) => true,
        };
        !(pattern_matches && rule_matches)
    });

    let removed = before_len - store.entries.len();
    if removed == 0 {
        eprintln!(
            "tirith: trust remove: no matching entry found for '{}'",
            human(pattern)
        );
        return 1;
    }

    if let Err(e) = write_store_scoped_permitted_locked(scope, &path, &store, &store_lock) {
        eprintln!("{}", trust_error_line("remove", &e));
        return 1;
    }

    if let Err(error) =
        tirith_core::audit::log_trust_change(pattern, rule_id, "remove", None, scope)
    {
        eprintln!(
            "{}",
            trust_error_line(
                "remove",
                &format!("trust store changed but audit append failed: {error}"),
            )
        );
        return 1;
    }

    eprintln!(
        "tirith: removed {removed} trust entry/entries for '{}' (scope: {})",
        human(pattern),
        human(scope)
    );
    0
}

/// Read and JSON-parse `last_trigger.json` from the data dir.
///
/// Shared by `last()` (interactive prompt) and `from_last_trigger()` (suggest
/// ready-to-run commands). Returns the parsed value so each caller can pull the
/// fields it needs without re-reading the file. `Ok(None)` means there is no
/// recent trigger on disk (missing file); `Err` is a real read/parse failure.
fn load_last_trigger_value() -> Result<Option<serde_json::Value>, String> {
    super::last_trigger::load_last_trigger_record()?
        .map(|record| {
            serde_json::to_value(record)
                .map_err(|e| format!("failed to project structured last trigger: {e}"))
        })
        .transpose()
}

/// Extract `(target, rule_id)` PAIRS from a parsed `last_trigger.json`.
///
/// Pairing is PER FINDING: each finding carries its OWN `rule_id` and its own
/// `evidence`, so a target pulled from a finding's evidence is paired with THAT
/// finding's `rule_id` — never the flat top-level `rule_ids` array. Pairing
/// against the top-level array would form a cartesian product, so for a
/// multi-finding trigger `--apply` could trust URL A under rule B even though
/// rule B fired for a DIFFERENT target.
///
/// Each target prefers a FULL URL when the evidence carries one (a `raw` string
/// with a scheme that parses) so the suggested trust can be narrow; it falls
/// back to a bare host/domain otherwise. Per-finding `raw` is read before
/// `raw_host`, mirroring how `last()` walks findings. A finding with no
/// extractable rule_id yields `(target, None)`. Results are de-duped on the full
/// `(target, rule_id)` pair, so the same URL flagged by two different rules
/// keeps both pairings.
fn extract_target_rule_pairs(val: &serde_json::Value) -> Vec<(String, Option<String>)> {
    let mut pairs: Vec<(String, Option<String>)> = Vec::new();
    let push = |t: String, rid: &Option<String>, pairs: &mut Vec<(String, Option<String>)>| {
        if t.is_empty() {
            return;
        }
        let pair = (t, rid.clone());
        if !pairs.contains(&pair) {
            pairs.push(pair);
        }
    };
    if let Some(findings) = val.get("findings").and_then(|v| v.as_array()) {
        for finding in findings {
            // THIS finding's own rule id — paired with every target it produces.
            let rule_id = finding
                .get("rule_id")
                .and_then(|v| v.as_str())
                .map(String::from);
            if let Some(evidence) = finding.get("evidence").and_then(|v| v.as_array()) {
                for ev in evidence {
                    if let Some(raw) = ev.get("raw").and_then(|v| v.as_str()) {
                        // Prefer the full URL when `raw` is one; else fall back
                        // to the bare host so we still have something to trust.
                        if raw.contains("://") && url::Url::parse(raw).is_ok() {
                            push(raw.to_string(), &rule_id, &mut pairs);
                        } else if let Some(host) = extract_host(raw) {
                            push(host, &rule_id, &mut pairs);
                        }
                    }
                    if let Some(host) = ev.get("raw_host").and_then(|v| v.as_str()) {
                        push(host.to_string(), &rule_id, &mut pairs);
                    }
                }
            }
        }
    }

    pairs
}

/// Normalize a per-finding target to the bare host `last()` displays and
/// prompts on. `extract_target_rule_pairs` may yield a FULL URL or a bare host;
/// `last()`'s `domains` list is always a bare host (via `extract_host` /
/// `raw_host`). Reduce a URL target to its host so a pair can be matched back to
/// the host the user was actually asked about; a target that is already a bare
/// host (or any non-URL) maps to itself.
fn target_host(target: &str) -> String {
    extract_host(target).unwrap_or_else(|| target.to_string())
}

/// The rule_id(s) that actually fired for a single host in the last trigger.
///
/// Reuses `extract_target_rule_pairs` (the same per-finding source
/// `from_last_trigger` uses) as the single source of truth, then keeps only the
/// rules whose finding targeted `host`, never the flat top-level `rule_ids`
/// array. This is what stops `last()`'s rule-scoped choice from granting one
/// host every rule in the whole verdict. Results are de-duped, preserving order.
fn rules_for_host(val: &serde_json::Value, host: &str) -> Vec<String> {
    let mut rules: Vec<String> = Vec::new();
    for (target, rule_id) in extract_target_rule_pairs(val) {
        if target_host(&target) != host {
            continue;
        }
        if let Some(rid) = rule_id {
            if !rules.contains(&rid) {
                rules.push(rid);
            }
        }
    }
    rules
}

/// Read + parse + extract in one step: per-finding `(target, rule_id)` pairs.
///
/// Each target prefers a full URL, else a bare domain (see
/// `extract_target_rule_pairs`). `Err` covers both "no recent trigger" (so
/// callers can print a friendly note) and real read/parse failures.
fn read_last_trigger() -> Result<Vec<(String, Option<String>)>, String> {
    match load_last_trigger_value()? {
        Some(val) => Ok(extract_target_rule_pairs(&val)),
        None => Err("no recent trigger found".into()),
    }
}

/// Build the ready-to-run `tirith trust add` suggestion lines for each
/// per-finding `(target, rule_id)` pair. A full-URL target is narrow, so it is
/// suggested without `--broad`; a bare domain needs `--broad` because
/// `trust add` rejects broad scopes without the opt-in (see `add()` /
/// `classify_scope`). Each pair carries ITS OWN rule id, so a rule is never
/// suggested for a target it didn't fire on.
fn suggestion_lines(pairs: &[(String, Option<String>)]) -> Vec<String> {
    pairs
        .iter()
        .map(|(target, rule_id)| {
            // A target that classifies as broad (bare domain/wildcard/TLD) needs
            // `--broad`; a full URL (or any narrow pattern) does not.
            let needs_broad = classify_scope(target).is_broad();
            format_add_line(target, rule_id.as_deref(), needs_broad)
        })
        .collect()
}

fn format_add_line(target: &str, rule_id: Option<&str>, needs_broad: bool) -> String {
    // The target is attacker-controlled (a URL/host pulled from the trigger's
    // finding evidence) and this line is printed for the operator to copy/paste
    // into a shell. If display sanitization would alter any character, emit only
    // a static manual-review note: silently stripping an escape, bidi control, or
    // forged newline could turn untrusted data into a different runnable trust
    // command. Benign shell metacharacters remain unchanged here and are protected
    // by the single-quote below.
    if human(target) != target {
        return "# trust this target manually with `tirith trust add` \
                (it contains characters unsafe to embed in a suggested command)."
            .to_string();
    }
    let Some(quoted) = tirith_core::safe_command::shell_single_quote(target) else {
        return "# trust this target manually with `tirith trust add` \
                (it contains characters unsafe to embed in a suggested command)."
            .to_string();
    };
    let broad = if needs_broad { " --broad" } else { "" };
    match rule_id {
        Some(rid) => {
            if human(rid) != rid {
                return "# trust this target manually with `tirith trust add` \
                        (its rule id contains characters unsafe to embed in a suggested command)."
                    .to_string();
            }
            let rid = if rid
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))
                && !rid.is_empty()
            {
                rid.to_string()
            } else {
                let Some(quoted) = tirith_core::safe_command::shell_single_quote(rid) else {
                    return "# trust this target manually with `tirith trust add` \
                            (its rule id contains characters unsafe to embed in a suggested command)."
                        .to_string();
                };
                quoted
            };
            format!("tirith trust add {quoted}{broad} --rule {rid} --ttl {DEFAULT_TTL}")
        }
        None => format!("tirith trust add {quoted}{broad} --ttl {DEFAULT_TTL}"),
    }
}

/// `tirith trust from-last-trigger [--apply]` -- turn the most recent trigger
/// into trust commands. Default (suggest) prints ready-to-run `trust add`
/// lines so the operator can copy/paste the narrowest one; `--apply` runs them.
///
/// Print-only by default mirrors the codebase's `policy tune` stance: suggest,
/// don't mutate.
pub fn from_last_trigger(apply: bool) -> i32 {
    let pairs = match read_last_trigger() {
        Ok(v) => v,
        // A missing/empty trigger is not an error for this command -- it is the
        // common "nothing happened yet" case, so exit 0 with a friendly note.
        Err(e) if e == "no recent trigger found" => {
            eprintln!("tirith: no recent trigger to trust");
            return 0;
        }
        Err(e) => {
            eprintln!("{}", trust_error_line("from-last-trigger", &e));
            return 1;
        }
    };

    if pairs.is_empty() {
        eprintln!("tirith: no recent trigger to trust");
        return 0;
    }

    if !apply {
        eprintln!("Suggested trust commands (run the narrowest one that fits):");
        eprintln!();
        for line in suggestion_lines(&pairs) {
            println!("{}", human(&line));
        }
        eprintln!();
        eprintln!("Re-run with --apply to add these automatically.");
        return 0;
    }

    // --apply: actually add each per-finding entry, pairing each target with ITS
    // OWN rule id (never a rule that fired on a different target). A bare-domain
    // target is broad, so pass `broad = true`; a full-URL (narrow) one does not.
    let mut added = 0;
    let mut failed = 0;
    for (target, rule_id) in &pairs {
        let broad = classify_scope(target).is_broad();
        // Pass DEFAULT_TTL explicitly (not None) so the applied entry uses the
        // same source the printed suggestion's `--ttl {DEFAULT_TTL}` does. `add()`
        // would resolve None to DEFAULT_TTL anyway, but sharing the one constant
        // keeps suggest and apply from drifting on separate literals.
        if add(
            target,
            rule_id.as_deref(),
            Some(DEFAULT_TTL),
            false,
            broad,
            None,
            "user",
            false,
        ) == 0
        {
            added += 1;
        } else {
            failed += 1;
        }
    }

    eprintln!("tirith: added {added} trust entry/entries from last trigger");
    // A partial apply (some entries rejected by `add()`, e.g. a blocklisted or
    // control-char target) must NOT exit 0 and masquerade as a clean success --
    // surface the count and fail loud so the operator knows not every entry stuck.
    if failed > 0 {
        eprintln!("tirith: {failed} trust entry/entries could not be added");
        return 1;
    }
    0
}

/// `tirith trust last` -- show last trigger and offer to trust.
pub fn last() -> i32 {
    let val = match load_last_trigger_value() {
        Ok(Some(v)) => v,
        Ok(None) => {
            eprintln!("tirith: no recent trigger found");
            return 1;
        }
        Err(e) => {
            eprintln!("{}", trust_error_line("last", &e));
            return 1;
        }
    };

    if let Some(ts) = val.get("timestamp").and_then(|v| v.as_str()) {
        eprintln!("Last trigger at: {}", human(ts));
    }
    if let Some(cmd) = val.get("command_redacted").and_then(|v| v.as_str()) {
        eprintln!("Command: {}", human(cmd));
    }

    let mut domains: Vec<String> = Vec::new();
    if let Some(findings) = val.get("findings").and_then(|v| v.as_array()) {
        for finding in findings {
            if let Some(title) = finding.get("title").and_then(|v| v.as_str()) {
                eprintln!("  - {}", human(title));
            }
            if let Some(evidence) = finding.get("evidence").and_then(|v| v.as_array()) {
                for ev in evidence {
                    if let Some(raw) = ev.get("raw").and_then(|v| v.as_str()) {
                        if let Some(host) = extract_host(raw) {
                            if !domains.contains(&host) {
                                domains.push(host);
                            }
                        }
                    }
                    if let Some(host) = ev.get("raw_host").and_then(|v| v.as_str()) {
                        let h = host.to_string();
                        if !domains.contains(&h) {
                            domains.push(h);
                        }
                    }
                }
            }
        }
    }

    if domains.is_empty() {
        eprintln!("\ntirith: no domain/URL found in last trigger to trust");
        return 0;
    }

    for domain in &domains {
        let display_domain = human(domain);
        eprintln!();
        eprint!("{}", trust_prompt_line(domain));
        let _ = io::stderr().flush();

        let stdin = io::stdin();
        let mut line = String::new();
        if stdin.lock().read_line(&mut line).is_err() {
            continue;
        }
        let choice = line.trim().to_lowercase();

        match choice.as_str() {
            "y" | "yes" => {
                // A bare `y` trusts the whole domain — keep that affordance,
                // but it is a broad scope, so pass `broad = true` explicitly.
                add(domain, None, None, false, true, None, "user", false);
            }
            "r" | "rule" => {
                // Pair this host with ONLY the rule(s) that actually fired for
                // it (per-finding, from `extract_target_rule_pairs`), not every
                // top-level rule in the verdict. Trusting one host under a rule
                // that fired on a DIFFERENT target would be over-broad.
                let host_rules = rules_for_host(&val, domain);
                if host_rules.is_empty() {
                    eprintln!("tirith: no rule IDs for {display_domain}, adding global trust");
                    add(domain, None, None, false, true, None, "user", false);
                } else {
                    for rid in &host_rules {
                        // Rule-scoped trust is narrow by construction.
                        add(domain, Some(rid), None, false, true, None, "user", false);
                    }
                }
            }
            "t" | "temp" | "temporary" => {
                add(domain, None, Some("7d"), false, true, None, "user", false);
            }
            _ => {
                eprintln!("tirith: skipped {display_domain}");
            }
        }
    }

    0
}

/// `tirith trust gc [--expired] [--scope user|repo|all]`
///
/// `--expired` is the default and only collection mode today; it is accepted
/// explicitly so the command reads clearly and leaves room for future modes.
pub fn gc(expired: bool, scope: &str, json: bool) -> i32 {
    gc_with_action("gc", expired, scope, json)
}

/// `tirith trust prune` — spec-named alias for `gc` (M6 ch3). Both
/// invoke the same backing implementation; only the audit `trust_action`
/// field differs so an operator can tell which command the user actually
/// typed.
pub fn prune(expired: bool, scope: &str, json: bool) -> i32 {
    gc_with_action("prune", expired, scope, json)
}

fn gc_with_action(action_label: &str, expired: bool, scope: &str, json: bool) -> i32 {
    if !matches!(scope, "user" | "repo" | "all") {
        eprintln!(
            "{}",
            unknown_scope_line(action_label, scope, "'user', 'repo', or 'all'"),
        );
        return 1;
    }
    // `--expired` is currently the only mode; if a caller explicitly passes
    // nothing we still collect expired entries (documented default).
    let _ = expired;

    let scopes: Vec<&str> = match scope {
        "all" => vec!["user", "repo"],
        s => vec![s],
    };

    let mut total_removed = 0;
    let mut per_scope: Vec<(String, usize)> = Vec::new();

    for s in scopes {
        let path = match trust_store_path(s) {
            Ok(p) => p,
            Err(e) => {
                if scope != "all" {
                    print_trust_error(action_label, &e, None);
                    return 1;
                }
                continue;
            }
        };

        if let Err(error) = preflight_trust_store_mutation(s, &path) {
            eprintln!("{}", trust_error_line(action_label, &error));
            return 1;
        }
        // repo-0233: hold the store lock across load → mutate → write.
        let store_lock = match lock_trust_store(s, &path) {
            Ok(guard) => guard,
            Err(e) => {
                eprintln!("{}", trust_error_line(action_label, &e));
                return 1;
            }
        };
        let mut store = match load_store_retained(store_lock.data_destination(), &path) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}", trust_error_line(action_label, &e));
                return 1;
            }
        };
        let before = store.entries.len();
        // Capture removed entries so each lands in the audit log under the right
        // `trust_action` (M6 ch3) — otherwise gc/prune sweeps are invisible there.
        let expired_entries: Vec<TrustEntry> = store
            .entries
            .iter()
            .filter(|entry| is_expired(entry))
            .cloned()
            .collect();
        store.entries.retain(|entry| !is_expired(entry));
        let removed = before - store.entries.len();

        if removed > 0 {
            if let Err(e) = write_store_scoped_permitted_locked(s, &path, &store, &store_lock) {
                eprintln!("{}", trust_error_line(action_label, &e));
                return 1;
            }
            for entry in &expired_entries {
                if let Err(error) = tirith_core::audit::log_trust_change(
                    &entry.pattern,
                    entry.rule_id.as_deref(),
                    action_label,
                    entry.ttl_expires.as_deref(),
                    s,
                ) {
                    eprintln!(
                        "{}",
                        trust_error_line(
                            action_label,
                            &format!("trust store changed but audit append failed: {error}"),
                        )
                    );
                    return 1;
                }
            }
            if !json {
                eprintln!(
                    "tirith: {}: removed {removed} expired entries from {} scope",
                    human(action_label),
                    human(s),
                );
            }
        }

        per_scope.push((s.to_string(), removed));
        total_removed += removed;
    }

    if json {
        let out = serde_json::json!({
            "removed_total": total_removed,
            "by_scope": per_scope
                .iter()
                .map(|(s, n)| serde_json::json!({ "scope": s, "removed": n }))
                .collect::<Vec<_>>(),
        });
        return print_json(&out);
    }
    if total_removed == 0 {
        eprintln!("tirith: {}: no expired entries found", human(action_label));
    }

    0
}

// --- trust explain ---------------------------------------------------------

/// `tirith trust explain <pattern> [--scope ...]` — explain one trust entry:
/// what it covers, how broad it is, when it expires, and why it was added.
#[derive(Debug, Serialize)]
struct ExplainReport {
    pattern: String,
    /// True when no matching trust/allowlist entry exists.
    found: bool,
    /// One report per matching entry (a pattern may appear in several scopes).
    matches: Vec<ExplainMatch>,
}

#[derive(Debug, Serialize)]
struct ExplainMatch {
    source: String,
    rule_id: Option<String>,
    scope_kind: ScopeKind,
    scope_coverage: String,
    /// True when this entry is dangerously broad.
    broad_warning: bool,
    added: Option<String>,
    reason: Option<String>,
    ttl_expires: Option<String>,
    /// Human "in 6d" / "expired" / `None` for permanent.
    expires_in: Option<String>,
    expired: bool,
    permanent: bool,
}

/// `tirith trust explain <pattern>`.
pub fn explain(pattern: &str, scope: &str, json: bool) -> i32 {
    if !matches!(scope, "user" | "repo" | "all") {
        eprintln!(
            "{}",
            unknown_scope_line("explain", scope, "'user', 'repo', or 'all'")
        );
        return 1;
    }
    if pattern.is_empty() {
        eprintln!("tirith: trust explain: pattern must not be empty");
        return 1;
    }

    // Gather full entry detail (reason/added) from the trust stores, plus
    // bare allowlist/policy rows. Show expired entries too — `explain` is for
    // understanding an entry, including a stale one.
    let mut matches: Vec<ExplainMatch> = Vec::new();

    let scopes: Vec<&str> = match scope {
        "all" => vec!["user", "repo"],
        s => vec![s],
    };
    for s in &scopes {
        let path = match trust_store_path(s) {
            Ok(p) => p,
            Err(e) => {
                if scope != "all" {
                    print_trust_error("explain", &e, None);
                    return 1;
                }
                continue;
            }
        };
        let store = match load_store_scoped(s, &path) {
            Ok(st) => st,
            Err(e) => {
                eprintln!("{}", trust_error_line("explain", &e));
                return 1;
            }
        };
        for entry in &store.entries {
            if entry.pattern == pattern {
                let kind = classify_scope(&entry.pattern);
                matches.push(ExplainMatch {
                    source: format!("trust-{s}"),
                    rule_id: entry.rule_id.clone(),
                    scope_kind: kind,
                    scope_coverage: kind.coverage().to_string(),
                    broad_warning: kind.is_dangerous(),
                    added: Some(entry.added.clone()),
                    reason: entry.reason.clone(),
                    ttl_expires: entry.ttl_expires.clone(),
                    expires_in: humanize_expiry(entry.ttl_expires.as_deref()),
                    expired: is_expired(entry),
                    permanent: entry.ttl_expires.is_none(),
                });
            }
        }
    }

    // Also surface a match coming purely from policy / flat allowlist files.
    if scope == "all" {
        if let Ok(rows) = collect_rows("all", true) {
            for r in rows {
                let from_allowlist_or_policy =
                    r.source.starts_with("allowlist") || r.source == "policy";
                if r.pattern == pattern && from_allowlist_or_policy {
                    matches.push(ExplainMatch {
                        source: r.source,
                        rule_id: r.rule_id,
                        scope_kind: r.scope_kind,
                        scope_coverage: r.scope_coverage,
                        broad_warning: r.broad_warning,
                        added: None,
                        reason: None,
                        ttl_expires: None,
                        expires_in: None,
                        expired: false,
                        permanent: true,
                    });
                }
            }
        }
    }

    let report = ExplainReport {
        pattern: pattern.to_string(),
        found: !matches.is_empty(),
        matches,
    };

    if json {
        return print_json(&report);
    }

    if !report.found {
        // Still explain what *would* happen if this pattern were trusted.
        let kind = classify_scope(pattern);
        eprintln!(
            "tirith: '{}' is not currently trusted in scope '{}'.",
            human(pattern),
            human(scope)
        );
        eprintln!(
            "  If added, it would be a {} entry — {}.",
            kind.label(),
            kind.coverage()
        );
        if kind.is_broad() {
            eprintln!("  That is a broad scope; `trust add` would require --broad to accept it.");
        }
        return 0;
    }

    println!("trust explain: {}", human(pattern));
    for (i, m) in report.matches.iter().enumerate() {
        if i > 0 {
            println!();
        }
        println!("  source:   {}", human(&m.source));
        println!(
            "  scope:    {} — {}",
            m.scope_kind.label(),
            human(&m.scope_coverage)
        );
        if let Some(rid) = &m.rule_id {
            println!("  rule:     {} (suppresses this rule only)", human(rid));
        } else {
            println!("  rule:     (global — suppresses every rule)");
        }
        if let Some(added) = &m.added {
            println!("  added:    {}", human(added));
        }
        match &m.reason {
            Some(r) => println!("  reason:   {}", human_multiline(r)),
            None => println!("  reason:   (none recorded)"),
        }
        match (&m.ttl_expires, m.permanent) {
            (_, true) => println!("  expires:  never (permanent)"),
            (Some(exp), false) => {
                let suffix = m
                    .expires_in
                    .as_deref()
                    .map(|h| format!(" ({h})"))
                    .unwrap_or_default();
                println!("  expires:  {}{}", human(exp), human(&suffix));
            }
            (None, false) => println!("  expires:  never (permanent)"),
        }
        if m.expired {
            println!("  status:   EXPIRED — run 'tirith trust gc --expired' to remove it");
        }
        if m.broad_warning {
            println!(
                "  warning:  dangerously broad — {}",
                m.scope_kind.coverage()
            );
        }
    }
    0
}

// --- trust diff ------------------------------------------------------------

/// File name for the append-only trust snapshot history used by `trust diff`.
const TRUST_HISTORY_FILE: &str = "trust-history.jsonl";
/// Hard cap on retained snapshot lines — keeps the file tiny and bounded.
const TRUST_HISTORY_MAX_LINES: usize = 64;

/// One observation of the full trust set, appended to the history file.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TrustSnapshot {
    /// RFC3339 timestamp when this snapshot was recorded.
    recorded_at: String,
    /// Every trusted pattern at observation time, as `source\u{1f}pattern\u{1f}rule`.
    /// A stable, sorted, flattened key list — enough to diff set membership.
    entries: Vec<String>,
}

/// Resolve the trust snapshot history file path under the state dir.
fn trust_history_path() -> Option<std::path::PathBuf> {
    tirith_core::policy::state_dir().map(|d| d.join(TRUST_HISTORY_FILE))
}

/// Stable flattened key for one trust row: `source\u{1f}pattern\u{1f}rule`.
fn row_key(r: &TrustListRow) -> String {
    format!(
        "{}\u{1f}{}\u{1f}{}",
        r.source,
        r.pattern,
        r.rule_id.as_deref().unwrap_or("")
    )
}

/// Decompose a `row_key` back into `(source, pattern, rule)` for display.
fn split_key(key: &str) -> (String, String, Option<String>) {
    let mut it = key.split('\u{1f}');
    let source = it.next().unwrap_or("").to_string();
    let pattern = it.next().unwrap_or("").to_string();
    let rule = it.next().filter(|s| !s.is_empty()).map(String::from);
    (source, pattern, rule)
}

/// Build a snapshot of the current full trust set (all scopes, including
/// expired entries — diff cares about set membership, not expiry).
fn current_trust_snapshot() -> TrustSnapshot {
    let mut entries: Vec<String> = collect_rows("all", true)
        .unwrap_or_default()
        .iter()
        .map(row_key)
        .collect();
    entries.sort();
    entries.dedup();
    TrustSnapshot {
        recorded_at: chrono::Utc::now().to_rfc3339(),
        entries,
    }
}

/// Load all retained trust snapshots, oldest first (unparseable lines skipped).
/// Returns `(snapshots, read_error)`: a missing file → empty + `None`; a file
/// that exists but can't be read → empty + `Some(msg)` so `diff` can say "could
/// not read history" instead of falsely reporting "first observation".
fn load_trust_history() -> (Vec<TrustSnapshot>, Option<String>) {
    let Some(path) = trust_history_path() else {
        return (Vec::new(), None);
    };
    let content = match fs::read_to_string(&path) {
        Ok(c) => c,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return (Vec::new(), None),
        Err(e) => {
            return (
                Vec::new(),
                Some(format!(
                    "could not read trust snapshot history at {} ({e}) — check file \
                     permissions; the diff below cannot use any earlier snapshot",
                    path.display()
                )),
            );
        }
    };
    let snapshots = content
        .lines()
        .filter(|l| !l.trim().is_empty())
        .filter_map(|l| serde_json::from_str::<TrustSnapshot>(l).ok())
        .collect();
    (snapshots, None)
}

/// Atomic write (temp file + rename) so a torn write can never leave a partial
/// snapshot history. Mirrors `threatdb_cmd::record_snapshot`.
fn atomic_write(dest: &std::path::Path, data: &[u8]) -> Result<(), String> {
    let parent = dest
        .parent()
        .ok_or_else(|| "cannot determine parent directory".to_string())?;
    fs::create_dir_all(parent).map_err(|e| format!("failed to create directory: {e}"))?;

    let mut tmp = tempfile::NamedTempFile::new_in(parent)
        .map_err(|e| format!("failed to create temp file: {e}"))?;
    tmp.write_all(data)
        .map_err(|e| format!("failed to write temp file: {e}"))?;
    tmp.flush()
        .map_err(|e| format!("failed to flush temp file: {e}"))?;
    tmp.persist(dest)
        .map_err(|e| format!("failed to rename temp file: {e}"))?;
    Ok(())
}

/// Append `snapshot` to the trust history file if its entry set differs from
/// the most recent snapshot. Best-effort: any I/O error is silently ignored —
/// the history is a convenience for `diff`, never load-bearing for analysis.
fn record_trust_snapshot(snapshot: &TrustSnapshot) {
    let Some(path) = trust_history_path() else {
        return;
    };
    // Read-error note is irrelevant: recording rewrites the whole file regardless.
    let (mut history, _) = load_trust_history();
    // Dedup on entry set so an unchanged trust set doesn't append a line every call.
    if history
        .last()
        .map(|s| s.entries == snapshot.entries)
        .unwrap_or(false)
    {
        return;
    }
    history.push(snapshot.clone());
    if history.len() > TRUST_HISTORY_MAX_LINES {
        let drop = history.len() - TRUST_HISTORY_MAX_LINES;
        history.drain(0..drop);
    }
    let mut body = String::new();
    for s in &history {
        if let Ok(line) = serde_json::to_string(s) {
            body.push_str(&line);
            body.push('\n');
        }
    }
    let _ = atomic_write(&path, body.as_bytes());
}

/// Take a snapshot of the current trust set and fold it into the history file.
/// Called by the read-only `trust list` / `trust diff` paths so a diff trail
/// accrues over time without any extra user action.
pub fn snapshot_current_trust() {
    record_trust_snapshot(&current_trust_snapshot());
}

#[derive(Debug, Serialize)]
struct DiffEntry {
    pattern: String,
    source: String,
    rule_id: Option<String>,
    scope_kind: ScopeKind,
}

#[derive(Debug, Serialize)]
struct TrustDiffReport {
    /// RFC3339 time of the baseline snapshot, if one was found.
    baseline_recorded_at: Option<String>,
    /// Entries present now but not in the baseline.
    added: Vec<DiffEntry>,
    /// Entries present in the baseline but not now.
    removed: Vec<DiffEntry>,
    /// True when nothing changed.
    unchanged: bool,
    /// Set when the diff could not be produced against a real baseline.
    note: Option<String>,
}

fn diff_entry_of(key: &str) -> DiffEntry {
    let (source, pattern, rule_id) = split_key(key);
    let scope_kind = classify_scope(&pattern);
    DiffEntry {
        pattern,
        source,
        rule_id,
        scope_kind,
    }
}

/// `tirith trust audit` — show recorded trust-store mutations (M6 ch3).
///
/// Walks the audit-log JSONL and filters entries with
/// `entry_type == "trust_change"`. Optionally trims the window with
/// `--since <duration>` (e.g. `7d`, `24h`, `15m`).
pub fn audit(since: Option<&str>, json: bool) -> i32 {
    let cutoff = match since {
        Some(s) => match parse_relative_duration(s) {
            Ok(c) => Some(c),
            Err(e) => {
                eprintln!(
                    "{}",
                    trust_error_line("audit", &format!("invalid --since value: {e}"))
                );
                return 1;
            }
        },
        None => None,
    };

    let Some(log_path) = tirith_core::audit::audit_log_path() else {
        eprintln!("tirith: trust audit: cannot resolve audit log path (no data dir)");
        return 1;
    };

    if !log_path.exists() {
        if json {
            // Same envelope shape as the normal path so consumers never special-case
            // "no log yet": `entries` always an array, `skipped_lines` always present.
            let _ = print_json(&serde_json::json!({"entries": [], "skipped_lines": 0_usize}));
        } else {
            eprintln!(
                "{}",
                trust_error_line(
                    "audit",
                    &format!("no audit log yet at {}", log_path.display())
                )
            );
        }
        return 0;
    }

    // Reuse the superset reader so missing fields on older entries parse cleanly.
    let result = match tirith_core::audit_aggregator::read_log(&log_path) {
        Ok(r) => r,
        Err(e) => {
            eprintln!(
                "{}",
                trust_error_line(
                    "audit",
                    &format!("cannot read audit log at {}: {e}", log_path.display())
                )
            );
            return 1;
        }
    };

    // Surface malformed-line skips so a corrupted log isn't invisible to an
    // operator chasing a missing entry. JSON shape includes it in the envelope below.
    if result.skipped_lines > 0 && !json {
        eprintln!(
            "{}",
            trust_error_line(
                "audit",
                &format!(
                    "skipped {} malformed audit log line(s) at {}",
                    result.skipped_lines,
                    log_path.display()
                )
            )
        );
    }

    #[derive(Serialize)]
    struct TrustAuditRow {
        timestamp: String,
        action: String,
        scope: String,
        pattern: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        rule_id: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        ttl_expires: Option<String>,
    }

    let mut rows: Vec<TrustAuditRow> = Vec::new();
    for entry in result.records {
        if entry.entry_type != "trust_change" {
            continue;
        }
        if let Some(cutoff_ts) = cutoff {
            if let Ok(ts) = chrono::DateTime::parse_from_rfc3339(&entry.timestamp) {
                if ts.to_utc() < cutoff_ts {
                    continue;
                }
            }
        }
        rows.push(TrustAuditRow {
            timestamp: entry.timestamp,
            action: entry.trust_action.unwrap_or_else(|| "?".to_string()),
            scope: entry.trust_scope.unwrap_or_else(|| "?".to_string()),
            pattern: entry.trust_pattern.unwrap_or_default(),
            rule_id: entry.trust_rule_id,
            ttl_expires: entry.trust_ttl_expires,
        });
    }

    if json {
        // Skipped-line count lets a JSON consumer detect a corrupted log without parsing stderr.
        return print_json(&serde_json::json!({
            "entries": rows,
            "skipped_lines": result.skipped_lines,
        }));
    }

    if rows.is_empty() {
        eprintln!("tirith: trust audit: no trust-store mutations recorded");
        return 0;
    }
    println!("{:<26} {:<8} {:<6} pattern", "timestamp", "action", "scope");
    for r in &rows {
        let rule_suffix = match &r.rule_id {
            Some(rid) => format!("  [rule: {rid}]"),
            None => String::new(),
        };
        println!(
            "{:<26} {:<8} {:<6} {}{}",
            human(&r.timestamp),
            human(&r.action),
            human(&r.scope),
            human(&r.pattern),
            human(&rule_suffix)
        );
    }
    0
}

/// Parse a relative-duration string (`7d`, `24h`, `15m`) into the UTC
/// timestamp that the duration is "ago from now".
fn parse_relative_duration(s: &str) -> Result<chrono::DateTime<chrono::Utc>, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("empty duration".into());
    }
    let (num_str, unit) = s.split_at(
        s.find(|c: char| !c.is_ascii_digit())
            .ok_or_else(|| format!("missing unit suffix (use e.g. '7d', '24h', '15m'): {s}"))?,
    );
    let n: i64 = num_str
        .parse()
        .map_err(|_| format!("not a number: {num_str:?}"))?;
    let seconds = match unit {
        "d" => n.checked_mul(86_400),
        "h" => n.checked_mul(3_600),
        "m" => n.checked_mul(60),
        "s" => Some(n),
        other => {
            return Err(format!(
                "unknown duration unit {other:?} (use 'd', 'h', 'm', or 's')",
            ))
        }
    }
    .ok_or_else(|| format!("duration overflow: {s}"))?;
    Ok(chrono::Utc::now() - chrono::Duration::seconds(seconds))
}

/// `tirith trust diff` — show what changed in the trust set since the previous
/// recorded snapshot.
pub fn diff(json: bool) -> i32 {
    let (history, history_read_error) = load_trust_history();
    let current = current_trust_snapshot();

    // Baseline = the literal last recorded snapshot (not "last that differs"),
    // which keeps repeated `trust diff` calls idempotent.
    let baseline = history.last();

    let report = match baseline {
        None => TrustDiffReport {
            baseline_recorded_at: None,
            added: Vec::new(),
            removed: Vec::new(),
            unchanged: true,
            // A history file that exists but could not be read must not be
            // reported as "first observation" — surface the read failure.
            note: Some(history_read_error.clone().unwrap_or_else(|| {
                "No earlier trust snapshot to compare against — this is the first \
                 observation. Run a 'tirith trust' command again later to build a \
                 diff trail."
                    .to_string()
            })),
        },
        Some(base) => {
            let base_set: std::collections::BTreeSet<&String> = base.entries.iter().collect();
            let cur_set: std::collections::BTreeSet<&String> = current.entries.iter().collect();

            let added: Vec<DiffEntry> = cur_set
                .difference(&base_set)
                .map(|k| diff_entry_of(k))
                .collect();
            let removed: Vec<DiffEntry> = base_set
                .difference(&cur_set)
                .map(|k| diff_entry_of(k))
                .collect();
            let unchanged = added.is_empty() && removed.is_empty();
            TrustDiffReport {
                baseline_recorded_at: Some(base.recorded_at.clone()),
                added,
                removed,
                unchanged,
                note: None,
            }
        }
    };

    // Record the current snapshot AFTER computing the diff so the next `diff`
    // has a fresh baseline.
    record_trust_snapshot(&current);

    if json {
        return print_json(&report);
    }

    match &report.baseline_recorded_at {
        Some(ts) => println!("trust diff (since {})", human(ts)),
        None => println!("trust diff"),
    }
    if let Some(note) = &report.note {
        println!("  note: {}", human_multiline(note));
        return 0;
    }
    if report.unchanged {
        println!("  no changes since the last snapshot");
        return 0;
    }
    if !report.added.is_empty() {
        println!("  added ({}):", report.added.len());
        for e in &report.added {
            let rule = e
                .rule_id
                .as_deref()
                .map(|r| format!(" [rule: {r}]"))
                .unwrap_or_default();
            println!(
                "    + {} ({}, {}){}",
                human(&e.pattern),
                human(&e.source),
                e.scope_kind.label(),
                human(&rule)
            );
        }
    }
    if !report.removed.is_empty() {
        println!("  removed ({}):", report.removed.len());
        for e in &report.removed {
            let rule = e
                .rule_id
                .as_deref()
                .map(|r| format!(" [rule: {r}]"))
                .unwrap_or_default();
            println!(
                "    - {} ({}, {}){}",
                human(&e.pattern),
                human(&e.source),
                e.scope_kind.label(),
                human(&rule)
            );
        }
    }
    0
}

/// Extract a hostname from a URL string for trust prompts.
fn extract_host(raw: &str) -> Option<String> {
    // Only trust url::Url when the input has a scheme — schemeless inputs
    // parse into unusable shapes.
    if raw.contains("://") {
        if let Ok(parsed) = url::Url::parse(raw) {
            return parsed.host_str().map(String::from);
        }
    }
    // Schemeless fallback: take the prefix up to the first '/'.
    let candidate = raw.split('/').next()?;
    let candidate = candidate.trim();
    if candidate.contains('.') && !candidate.contains(' ') {
        let host = if let Some((h, port)) = candidate.rsplit_once(':') {
            if port.chars().all(|c| c.is_ascii_digit()) && !port.is_empty() {
                h
            } else {
                candidate
            }
        } else {
            candidate
        };
        Some(host.to_string())
    } else {
        None
    }
}

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

    #[cfg(unix)]
    #[test]
    fn repo_trust_dir_refuses_a_symlinked_tirith_component() {
        use std::os::unix::fs::symlink;

        // The root itself is opened O_NOFOLLOW as well, which costs nothing:
        // both callers derive it from find_repo_root(None) -> current_dir(),
        // and getcwd() never returns a path with symlink components.
        let holder = tempfile::tempdir().unwrap();
        let root = holder.path().join("checkout");
        std::fs::create_dir(&root).unwrap();
        std::fs::create_dir(root.join(".tirith")).unwrap();
        open_repo_trust_dir(&root.join(".tirith").join("trust.json"), false)
            .expect("an ordinary repository root opens");

        // The component that carries repository content refuses a symlink.
        let hostile = holder.path().join("hostile");
        std::fs::create_dir(&hostile).unwrap();
        let swapped = holder.path().join("swapped");
        std::fs::create_dir(&swapped).unwrap();
        symlink(&hostile, swapped.join(".tirith")).unwrap();
        let error = open_repo_trust_dir(&swapped.join(".tirith").join("trust.json"), false)
            .expect_err("a symlinked .tirith component must be refused");
        assert!(error.contains("symlinked"), "unexpected error: {error}");
    }

    #[test]
    fn test_parse_ttl_days() {
        let result = parse_ttl("7d");
        assert!(result.is_ok());
        let expiry = chrono::DateTime::parse_from_rfc3339(&result.unwrap()).unwrap();
        let expected_min = chrono::Utc::now() + chrono::Duration::days(6);
        assert!(expiry > expected_min);
    }

    #[test]
    fn test_parse_ttl_hours() {
        let result = parse_ttl("1h");
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_ttl_minutes() {
        let result = parse_ttl("30m");
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_ttl_invalid() {
        assert!(parse_ttl("").is_err());
        assert!(parse_ttl("0d").is_err());
        assert!(parse_ttl("abc").is_err());
        assert!(parse_ttl("7x").is_err());
    }

    #[test]
    fn test_default_ttl_parses() {
        // The compiled-in default must always be a valid TTL.
        assert!(parse_ttl(DEFAULT_TTL).is_ok());
    }

    #[test]
    fn test_is_expired_no_ttl() {
        let entry = TrustEntry {
            pattern: "example.com".to_string(),
            rule_id: None,
            ttl_expires: None,
            added: chrono::Utc::now().to_rfc3339(),
            source: "cli".to_string(),
            reason: None,
        };
        assert!(!is_expired(&entry));
    }

    #[test]
    fn test_is_expired_future() {
        let future = chrono::Utc::now() + chrono::Duration::hours(1);
        let entry = TrustEntry {
            pattern: "example.com".to_string(),
            rule_id: None,
            ttl_expires: Some(future.to_rfc3339()),
            added: chrono::Utc::now().to_rfc3339(),
            source: "cli".to_string(),
            reason: None,
        };
        assert!(!is_expired(&entry));
    }

    #[test]
    fn test_is_expired_past() {
        let past = chrono::Utc::now() - chrono::Duration::hours(1);
        let entry = TrustEntry {
            pattern: "example.com".to_string(),
            rule_id: None,
            ttl_expires: Some(past.to_rfc3339()),
            added: chrono::Utc::now().to_rfc3339(),
            source: "cli".to_string(),
            reason: None,
        };
        assert!(is_expired(&entry));
    }

    #[test]
    fn test_is_expired_unparseable_ttl_is_not_expired() {
        // A malformed timestamp must never silently revoke trust.
        let entry = TrustEntry {
            pattern: "example.com".to_string(),
            rule_id: None,
            ttl_expires: Some("not-a-timestamp".to_string()),
            added: chrono::Utc::now().to_rfc3339(),
            source: "cli".to_string(),
            reason: None,
        };
        assert!(!is_expired(&entry));
    }

    #[test]
    fn test_validate_pattern_empty() {
        let policy = tirith_core::policy::Policy::default();
        assert!(validate_pattern("", &policy).is_err());
    }

    #[test]
    fn test_validate_pattern_control_chars() {
        let policy = tirith_core::policy::Policy::default();
        assert!(validate_pattern("hello\x00world", &policy).is_err());
        assert!(validate_pattern("hello\x01world", &policy).is_err());
    }

    #[test]
    fn test_validate_pattern_rejects_tab_and_deceptive_unicode() {
        let policy = tirith_core::policy::Policy::default();
        assert!(validate_pattern("hello\tworld", &policy).is_err());
        assert!(validate_pattern("hello\u{202e}world", &policy).is_err());
        assert!(validate_pattern("hello\u{200b}world", &policy).is_err());
    }

    #[test]
    fn test_validate_pattern_blocklisted() {
        let policy = tirith_core::policy::Policy {
            blocklist: vec!["evil.com".to_string()],
            ..Default::default()
        };
        assert!(validate_pattern("evil.com", &policy).is_err());
    }

    #[test]
    fn test_validate_pattern_ok() {
        let policy = tirith_core::policy::Policy::default();
        assert!(validate_pattern("example.com", &policy).is_ok());
    }

    #[test]
    fn test_extract_host_full_url() {
        assert_eq!(
            extract_host("https://example.com/path"),
            Some("example.com".to_string())
        );
    }

    #[test]
    fn test_extract_host_schemeless() {
        assert_eq!(
            extract_host("example.com/path"),
            Some("example.com".to_string())
        );
    }

    #[test]
    fn test_extract_host_with_port() {
        assert_eq!(
            extract_host("example.com:8080/path"),
            Some("example.com".to_string())
        );
    }

    #[test]
    fn test_extract_host_no_dot() {
        assert_eq!(extract_host("localhost"), None);
    }

    #[test]
    fn test_store_roundtrip() {
        let _global = crate::cli::test_harness::ENV_LOCK
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("trust.json");

        let store = TrustStore {
            version: 1,
            entries: vec![TrustEntry {
                pattern: "example.com".to_string(),
                rule_id: Some("shortened_url".to_string()),
                ttl_expires: None,
                added: "2026-04-03T12:00:00Z".to_string(),
                source: "cli".to_string(),
                reason: Some("internal mirror".to_string()),
            }],
        };

        write_store(&path, &store).unwrap();
        let loaded = load_store(&path).unwrap();

        assert_eq!(loaded.version, 1);
        assert_eq!(loaded.entries.len(), 1);
        assert_eq!(loaded.entries[0].pattern, "example.com");
        assert_eq!(loaded.entries[0].rule_id.as_deref(), Some("shortened_url"));
        assert_eq!(loaded.entries[0].reason.as_deref(), Some("internal mirror"));
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn repo_store_roundtrip_is_atomic_and_leaves_no_temp_files() {
        let _global = crate::cli::test_harness::ENV_LOCK
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join(".tirith/trust.json");
        assert!(load_repo_store(&path).unwrap().entries.is_empty());
        let store = TrustStore {
            version: 1,
            entries: vec![TrustEntry {
                pattern: "https://example.com/install.sh".into(),
                rule_id: None,
                ttl_expires: None,
                added: "2026-07-31T00:00:00Z".into(),
                source: "cli".into(),
                reason: None,
            }],
        };
        write_repo_store(&path, &store).unwrap();
        assert_eq!(load_repo_store(&path).unwrap().entries.len(), 1);
        write_repo_store(&path, &TrustStore::default()).unwrap();
        assert!(load_repo_store(&path).unwrap().entries.is_empty());
        let names: Vec<_> = fs::read_dir(root.path().join(".tirith"))
            .unwrap()
            .map(|entry| entry.unwrap().file_name())
            .collect();
        assert_eq!(names, vec![std::ffi::OsString::from("trust.json")]);
    }

    #[cfg(unix)]
    #[test]
    fn repo_store_rejects_symlinked_directory_component() {
        use std::os::unix::fs::symlink;

        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let outside_store = outside.path().join("trust.json");
        fs::write(&outside_store, r#"{"version":1,"entries":[]}"#).unwrap();
        symlink(outside.path(), root.path().join(".tirith")).unwrap();
        let path = root.path().join(".tirith/trust.json");
        let before = fs::read(&outside_store).unwrap();

        assert!(load_repo_store(&path).is_err());
        assert!(write_repo_store(&path, &TrustStore::default()).is_err());
        assert_eq!(fs::read(&outside_store).unwrap(), before);
    }

    #[cfg(unix)]
    #[test]
    fn repo_store_rejects_symlinked_destination() {
        use std::os::unix::fs::symlink;

        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::NamedTempFile::new().unwrap();
        fs::write(outside.path(), r#"{"version":1,"entries":[]}"#).unwrap();
        fs::create_dir(root.path().join(".tirith")).unwrap();
        let path = root.path().join(".tirith/trust.json");
        symlink(outside.path(), &path).unwrap();
        let before = fs::read(outside.path()).unwrap();

        assert!(load_repo_store(&path).is_err());
        assert!(write_repo_store(&path, &TrustStore::default()).is_err());
        assert_eq!(fs::read(outside.path()).unwrap(), before);
    }

    #[cfg(windows)]
    #[test]
    fn repo_store_rejects_windows_reparse_directory_component() {
        use std::os::windows::fs::symlink_dir;

        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let outside_store = outside.path().join("trust.json");
        fs::write(&outside_store, r#"{"version":1,"entries":[]}"#).unwrap();
        if let Err(error) = symlink_dir(outside.path(), root.path().join(".tirith")) {
            if error.kind() == io::ErrorKind::PermissionDenied || error.raw_os_error() == Some(1314)
            {
                return;
            }
            panic!("cannot create Windows directory symlink fixture: {error}");
        }
        let path = root.path().join(".tirith/trust.json");
        let before = fs::read(&outside_store).unwrap();

        assert!(load_repo_store(&path).is_err());
        assert!(write_repo_store(&path, &TrustStore::default()).is_err());
        assert_eq!(fs::read(&outside_store).unwrap(), before);
    }

    #[cfg(windows)]
    #[test]
    fn repo_store_rejects_windows_reparse_destination() {
        use std::os::windows::fs::symlink_file;

        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::NamedTempFile::new().unwrap();
        fs::write(outside.path(), r#"{"version":1,"entries":[]}"#).unwrap();
        fs::create_dir(root.path().join(".tirith")).unwrap();
        let path = root.path().join(".tirith/trust.json");
        if let Err(error) = symlink_file(outside.path(), &path) {
            if error.kind() == io::ErrorKind::PermissionDenied || error.raw_os_error() == Some(1314)
            {
                return;
            }
            panic!("cannot create Windows file symlink fixture: {error}");
        }
        let before = fs::read(outside.path()).unwrap();

        assert!(load_repo_store(&path).is_err());
        assert!(write_repo_store(&path, &TrustStore::default()).is_err());
        assert_eq!(fs::read(outside.path()).unwrap(), before);
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn repo_store_rejects_oversized_and_non_regular_files() {
        let root = tempfile::tempdir().unwrap();
        fs::create_dir(root.path().join(".tirith")).unwrap();
        let path = root.path().join(".tirith/trust.json");
        fs::write(&path, vec![b'x'; TRUST_STORE_MAX_BYTES as usize + 1]).unwrap();
        assert!(load_repo_store(&path).is_err());

        fs::remove_file(&path).unwrap();
        fs::create_dir(&path).unwrap();
        assert!(load_repo_store(&path).is_err());
        assert!(write_repo_store(&path, &TrustStore::default()).is_err());
    }

    #[cfg(all(not(unix), not(windows)))]
    #[test]
    fn repo_store_is_empty_when_absent_and_mutation_fails_closed() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join(".tirith/trust.json");
        assert!(load_repo_store(&path).unwrap().entries.is_empty());
        fs::create_dir(path.parent().unwrap()).unwrap();
        assert!(load_repo_store(&path).unwrap().entries.is_empty());
        assert!(write_repo_store(&path, &TrustStore::default()).is_err());
        assert!(!path.exists());

        fs::write(&path, br#"{"version":1,"entries":[]}"#).unwrap();
        let before = fs::read(&path).unwrap();
        assert!(load_repo_store(&path).is_err());
        assert!(write_repo_store(&path, &TrustStore::default()).is_err());
        assert_eq!(fs::read(&path).unwrap(), before);
    }

    #[test]
    fn human_trust_fields_strip_terminal_forgery_but_json_stays_raw() {
        let raw = "safe\u{1b}]52;c;Y2xpcA\u{7}\u{1b}[2J\nFORGED\u{202e}\u{200b}";
        let one_line = human(raw);
        let multiline = human_multiline(raw);
        for rendered in [&one_line, &multiline] {
            assert!(!rendered.contains('\u{1b}'));
            assert!(!rendered.contains('\u{202e}'));
            assert!(!rendered.contains('\u{200b}'));
        }
        assert!(!one_line.contains('\n'));
        assert!(multiline.contains("\n  FORGED"));

        let structured = serde_json::to_string(&serde_json::json!({"pattern": raw})).unwrap();
        let decoded: serde_json::Value = serde_json::from_str(&structured).unwrap();
        assert_eq!(decoded["pattern"], raw);
        assert!(
            !structured.contains('\u{1b}'),
            "JSON must escape raw ESC bytes"
        );
    }

    fn assert_safe_single_line(rendered: &str) {
        for forbidden in ['\u{1b}', '\u{7}', '\u{202e}', '\u{200b}'] {
            assert!(
                !rendered.contains(forbidden),
                "forbidden terminal/deception character {forbidden:?} survived in {rendered:?}"
            );
        }
        assert!(
            !rendered.contains('\n'),
            "forged line survived: {rendered:?}"
        );
        assert!(!rendered.contains('\r'), "bare CR survived: {rendered:?}");
    }

    #[test]
    fn hostile_scope_action_and_prompt_are_safe_at_the_final_sink() {
        let hostile = "repo\u{1b}]52;c;Y2xpcA\u{7}\u{1b}[2J\nFORGED\u{202e}\u{200b}";
        let scope_line = unknown_scope_line(hostile, hostile, "'user', 'repo', or 'all'");
        let prompt = trust_prompt_line(hostile);
        assert_safe_single_line(&scope_line);
        assert_safe_single_line(&prompt);
        assert_eq!(
            unknown_scope_line("list", "staging", "'user', 'repo', or 'all'"),
            "tirith: trust list: unknown scope 'staging' (use 'user', 'repo', or 'all')"
        );
        assert_eq!(
            trust_prompt_line("example.com"),
            "Trust example.com? [y/N/r(rule-scoped)/t(temporary 7d)] "
        );
    }

    #[cfg(unix)]
    #[test]
    fn corrupt_store_error_sanitizes_hostile_path_and_parser_diagnostic_at_sink() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir
            .path()
            .join("trust\u{1b}]52;c;Y2xpcA\u{7}\nFORGED\u{202e}\u{200b}.json");
        fs::write(&path, b"{ definitely-not-json").unwrap();

        let error = load_store(&path).unwrap_err();
        let rendered = trust_error_line("list", &error);
        assert_safe_single_line(&rendered);
        assert!(rendered.contains("tirith: trust list: corrupt trust store at"));
        assert!(rendered.contains("definitely-not-json") || rendered.contains("key"));
    }

    #[test]
    fn test_load_legacy_store_without_reason() {
        // An older trust.json has no `reason` field — it must still load and
        // deserialize `reason` as None (backward compatibility).
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("trust.json");
        let legacy = r#"{
  "version": 1,
  "entries": [
    {
      "pattern": "old.example.com",
      "added": "2026-01-01T00:00:00Z",
      "source": "cli"
    }
  ]
}"#;
        fs::write(&path, legacy).unwrap();
        let loaded = load_store(&path).unwrap();
        assert_eq!(loaded.entries.len(), 1);
        assert_eq!(loaded.entries[0].pattern, "old.example.com");
        assert!(loaded.entries[0].reason.is_none());
        assert!(loaded.entries[0].ttl_expires.is_none());
        // A legacy entry with no TTL is treated as permanent — never expired.
        assert!(!is_expired(&loaded.entries[0]));
    }

    #[test]
    fn test_gc_removes_expired() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("trust.json");

        let past = chrono::Utc::now() - chrono::Duration::hours(1);
        let future = chrono::Utc::now() + chrono::Duration::hours(1);

        let store = TrustStore {
            version: 1,
            entries: vec![
                TrustEntry {
                    pattern: "expired.com".to_string(),
                    rule_id: None,
                    ttl_expires: Some(past.to_rfc3339()),
                    added: chrono::Utc::now().to_rfc3339(),
                    source: "cli".to_string(),
                    reason: None,
                },
                TrustEntry {
                    pattern: "valid.com".to_string(),
                    rule_id: None,
                    ttl_expires: Some(future.to_rfc3339()),
                    added: chrono::Utc::now().to_rfc3339(),
                    source: "cli".to_string(),
                    reason: None,
                },
                TrustEntry {
                    pattern: "forever.com".to_string(),
                    rule_id: None,
                    ttl_expires: None,
                    added: chrono::Utc::now().to_rfc3339(),
                    source: "cli".to_string(),
                    reason: None,
                },
            ],
        };

        write_store(&path, &store).unwrap();

        let mut loaded = load_store(&path).unwrap();
        loaded.entries.retain(|e| !is_expired(e));
        write_store(&path, &loaded).unwrap();

        let after = load_store(&path).unwrap();
        assert_eq!(after.entries.len(), 2);
        assert!(after.entries.iter().any(|e| e.pattern == "valid.com"));
        assert!(after.entries.iter().any(|e| e.pattern == "forever.com"));
        assert!(!after.entries.iter().any(|e| e.pattern == "expired.com"));
    }

    // --- scope classification ---------------------------------------------

    #[test]
    fn test_classify_scope_exact_url() {
        assert_eq!(
            classify_scope("https://example.com/install.sh"),
            ScopeKind::Exact
        );
        assert_eq!(
            classify_scope("raw.githubusercontent.com/org/repo/main/get.sh"),
            ScopeKind::Exact
        );
    }

    #[test]
    fn test_classify_scope_domain() {
        assert_eq!(classify_scope("github.com"), ScopeKind::Domain);
        assert_eq!(classify_scope("api.github.com"), ScopeKind::Domain);
        assert_eq!(classify_scope("get.docker.com"), ScopeKind::Domain);
    }

    #[test]
    fn test_classify_scope_wildcard() {
        assert_eq!(classify_scope("*.example.com"), ScopeKind::Wildcard);
        assert_eq!(classify_scope("*.internal.corp.net"), ScopeKind::Wildcard);
    }

    #[test]
    fn test_classify_scope_bare_tld() {
        assert_eq!(classify_scope("com"), ScopeKind::BareTld);
        assert_eq!(classify_scope("dev"), ScopeKind::BareTld);
        assert_eq!(classify_scope("io"), ScopeKind::BareTld);
        assert_eq!(classify_scope("zip"), ScopeKind::BareTld);
        assert_eq!(classify_scope("co.uk"), ScopeKind::BareTld);
        // A wildcard over a bare TLD is the worst case — still bare-TLD.
        assert_eq!(classify_scope("*.com"), ScopeKind::BareTld);
    }

    #[test]
    fn test_classify_scope_substring() {
        // A non-domain, non-TLD bare token is a substring fragment.
        assert_eq!(classify_scope("get-pip"), ScopeKind::Substring);
    }

    #[test]
    fn test_scope_kind_broad_and_dangerous() {
        assert!(!ScopeKind::Exact.is_broad());
        assert!(ScopeKind::Substring.is_broad());
        assert!(ScopeKind::Domain.is_broad());
        assert!(ScopeKind::Wildcard.is_broad());
        assert!(ScopeKind::BareTld.is_broad());

        assert!(!ScopeKind::Domain.is_dangerous());
        assert!(ScopeKind::Wildcard.is_dangerous());
        assert!(ScopeKind::BareTld.is_dangerous());
    }

    #[test]
    fn test_humanize_expiry() {
        assert_eq!(humanize_expiry(None), None);
        let future = chrono::Utc::now() + chrono::Duration::days(6) + chrono::Duration::hours(2);
        let h = humanize_expiry(Some(&future.to_rfc3339())).unwrap();
        assert!(h.starts_with("in 6d"), "got {h}");
        let past = chrono::Utc::now() - chrono::Duration::hours(1);
        assert_eq!(
            humanize_expiry(Some(&past.to_rfc3339())),
            Some("expired".to_string())
        );
    }

    // --- trust diff snapshot keys -----------------------------------------

    #[test]
    fn test_row_key_roundtrip() {
        let row = make_row(
            "github.com".to_string(),
            Some("shortened_url".to_string()),
            "trust-user".to_string(),
            None,
            false,
        );
        let key = row_key(&row);
        let (source, pattern, rule) = split_key(&key);
        assert_eq!(source, "trust-user");
        assert_eq!(pattern, "github.com");
        assert_eq!(rule.as_deref(), Some("shortened_url"));
    }

    #[test]
    fn test_row_key_roundtrip_no_rule() {
        let row = make_row(
            "example.com".to_string(),
            None,
            "policy".to_string(),
            None,
            false,
        );
        let (source, pattern, rule) = split_key(&row_key(&row));
        assert_eq!(source, "policy");
        assert_eq!(pattern, "example.com");
        assert_eq!(rule, None);
    }

    #[test]
    fn test_diff_set_logic() {
        // Baseline has A and B; current has B and C.
        let base: std::collections::BTreeSet<&str> = ["A", "B"].into_iter().collect();
        let cur: std::collections::BTreeSet<&str> = ["B", "C"].into_iter().collect();
        let added: Vec<_> = cur.difference(&base).collect();
        let removed: Vec<_> = base.difference(&cur).collect();
        assert_eq!(added, vec![&"C"]);
        assert_eq!(removed, vec![&"A"]);
    }

    /// Redirect every base directory this module resolves at runtime into one
    /// temp root, and hand the root back so a caller can seed or inspect it.
    ///
    /// `data_dir()` (where `last_trigger.json` lives) is only half of it. The
    /// trust store itself is `config_dir()/trust.json`, and
    /// `from_last_trigger(--apply)` calls `add()`, so leaving `XDG_CONFIG_HOME`
    /// alone appended a real allowlist entry to the operator's own
    /// `~/.config/tirith/trust.json` on every `cargo test --workspace`. That
    /// file is read on the analysis hot path by `Policy::load_trust_entries`,
    /// so the residue suppresses a rule for the operator and for every later
    /// test that analyzes a matching URL. Both values are returned so the
    /// caller keeps them alive.
    ///
    /// Deliberately NOT `HOME`/`USERPROFILE`: every base directory this module
    /// resolves goes through an XDG variable on unix and `%APPDATA%` on
    /// Windows, so redirecting the home directory buys nothing here, and
    /// `cli::daemon`'s tests remove `HOME` without holding `ENV_LOCK`. A second
    /// unsynchronized writer of that variable would trade one race for another.
    fn isolated_base_dirs() -> (tempfile::TempDir, Vec<crate::cli::test_harness::EnvGuard>) {
        use crate::cli::test_harness::EnvGuard;
        let dir = tempfile::tempdir().expect("tempdir");
        let guards = [
            "XDG_DATA_HOME",
            "XDG_CONFIG_HOME",
            "XDG_STATE_HOME",
            "XDG_CACHE_HOME",
            "APPDATA",
            "LOCALAPPDATA",
        ]
        .into_iter()
        .map(|key| EnvGuard::set(key, dir.path()))
        .collect();
        (dir, guards)
    }

    /// Plant a `last_trigger.json` under a temp data dir and run `f` with every
    /// base directory pointed at it. Holds `ENV_LOCK` (process-global env
    /// mutation) and restores each variable on Drop. `data_dir()` honors
    /// `XDG_DATA_HOME` on Unix but `%APPDATA%` on Windows (etcetera), so both
    /// spellings are set.
    fn with_seeded_last_trigger<F: FnOnce()>(json: &str, f: F) {
        use crate::cli::test_harness::ENV_LOCK;
        let _lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());

        let (dir, _guards) = isolated_base_dirs();

        let tirith_data = dir.path().join("tirith");
        fs::create_dir_all(&tirith_data).expect("create data dir");
        fs::write(tirith_data.join("last_trigger.json"), json).expect("write last_trigger.json");

        f();
    }

    /// Same env isolation, but plant NO `last_trigger.json` (empty data dir).
    fn with_empty_data_dir<F: FnOnce()>(f: F) {
        use crate::cli::test_harness::ENV_LOCK;
        let _lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());

        let (_dir, _guards) = isolated_base_dirs();
        f();
    }

    /// The harness has to move the STORE, not just the trigger file.
    ///
    /// `from_last_trigger_apply_partial_failure_returns_one` calls
    /// `from_last_trigger(true)`, which calls `add()`, which writes
    /// `config_dir()/trust.json`. While the harness redirected only
    /// `XDG_DATA_HOME`/`APPDATA` that write landed in the operator's real
    /// `~/.config/tirith/trust.json`, one live 30-day allowlist entry per
    /// `cargo test --workspace`. `Policy::load_trust_entries` reads that file on
    /// the analysis hot path, so the residue silently suppresses a rule for the
    /// operator and for any later test that analyzes a matching URL.
    #[test]
    fn the_trust_harness_never_resolves_the_operators_own_store() {
        use crate::cli::test_harness::ENV_LOCK;
        let _lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());

        // Resolved under the lock and BEFORE the guards, so this is the real
        // path the binary would use on this machine.
        let operator_store = trust_store_path("user").expect("operator trust store path");

        let (dir, _guards) = isolated_base_dirs();
        let harness_store = trust_store_path("user").expect("harness trust store path");

        assert!(
            harness_store.starts_with(dir.path()),
            "the trust harness resolves {}, which is outside its temp root {}",
            harness_store.display(),
            dir.path().display()
        );
        assert_ne!(
            harness_store, operator_store,
            "the trust harness would write the operator's own store"
        );
    }

    /// A full-URL evidence target is suggested NARROW: a copy/paste-ready
    /// `tirith trust add '<url>' --rule <rule_id> --ttl 30d` line (URL
    /// single-quoted) with NO `--broad`.
    #[test]
    fn from_last_trigger_suggests_narrow_url_without_broad() {
        let json = r#"{
            "rule_ids": ["shortened_url"],
            "severity": "high",
            "command_redacted": "curl https://example.com/install.sh | sh",
            "timestamp": "2026-06-10T00:00:00Z",
            "findings": [
                {
                    "rule_id": "shortened_url",
                    "title": "Shortened URL",
                    "evidence": [
                        { "raw": "https://example.com/install.sh" }
                    ]
                }
            ]
        }"#;

        with_seeded_last_trigger(json, || {
            // read_last_trigger prefers the FULL URL as the target and pairs it
            // with THAT finding's rule_id.
            let pairs = read_last_trigger().expect("read_last_trigger");
            assert_eq!(
                pairs,
                vec![(
                    "https://example.com/install.sh".to_string(),
                    Some("shortened_url".to_string())
                )]
            );

            // The suggested line is the narrow, single-quoted, no-`--broad` form.
            let lines = suggestion_lines(&pairs);
            let expected =
                "tirith trust add 'https://example.com/install.sh' --rule shortened_url --ttl 30d";
            assert!(
                lines.iter().any(|l| l == expected),
                "expected narrow single-quoted URL suggestion {expected:?}, got: {lines:?}"
            );
            assert!(
                lines.iter().all(|l| !l.contains("--broad")),
                "a full-URL target must NOT be suggested with --broad: {lines:?}"
            );

            // The real entry point runs clean in suggest (print-only) mode.
            assert_eq!(from_last_trigger(false), 0);
        });
    }

    /// A bare-domain target (only `raw_host`, no URL) needs `--broad` because
    /// `trust add` rejects broad scopes without the opt-in.
    #[test]
    fn from_last_trigger_bare_domain_gets_broad() {
        let json = r#"{
            "rule_ids": ["homograph"],
            "findings": [
                { "rule_id": "homograph", "title": "Homograph", "evidence": [ { "raw_host": "example.com" } ] }
            ]
        }"#;

        with_seeded_last_trigger(json, || {
            let pairs = read_last_trigger().expect("read_last_trigger");
            assert_eq!(
                pairs,
                vec![("example.com".to_string(), Some("homograph".to_string()))]
            );

            let lines = suggestion_lines(&pairs);
            let expected = "tirith trust add 'example.com' --broad --rule homograph --ttl 30d";
            assert!(
                lines.iter().any(|l| l == expected),
                "expected single-quoted bare-domain suggestion with --broad {expected:?}, got: {lines:?}"
            );
        });
    }

    /// F2 (P1): a MULTI-finding trigger must pair each target with ITS OWN
    /// finding's rule_id — never the cartesian product of all targets × all
    /// top-level `rule_ids`. Here finding A (rule `shortened_url`) fired for
    /// `https://a.example/x`, finding B (rule `plain_http_to_sink`) for
    /// `http://b.example/y`. The wrong (old) behavior would suggest trusting A
    /// under `plain_http_to_sink` and B under `shortened_url`.
    #[test]
    fn from_last_trigger_pairs_each_target_with_its_own_rule() {
        let json = r#"{
            "rule_ids": ["shortened_url", "plain_http_to_sink"],
            "findings": [
                {
                    "rule_id": "shortened_url",
                    "title": "Shortened URL",
                    "evidence": [ { "raw": "https://a.example/x" } ]
                },
                {
                    "rule_id": "plain_http_to_sink",
                    "title": "Plain HTTP",
                    "evidence": [ { "raw": "http://b.example/y" } ]
                }
            ]
        }"#;

        with_seeded_last_trigger(json, || {
            let pairs = read_last_trigger().expect("read_last_trigger");
            assert_eq!(
                pairs,
                vec![
                    (
                        "https://a.example/x".to_string(),
                        Some("shortened_url".to_string())
                    ),
                    (
                        "http://b.example/y".to_string(),
                        Some("plain_http_to_sink".to_string())
                    ),
                ],
                "each target must keep its own finding's rule_id (no cartesian product)"
            );

            let lines = suggestion_lines(&pairs);
            // Exactly the two correct pairings — and NO cross-paired line.
            assert!(
                lines.iter().any(|l| l
                    == "tirith trust add 'https://a.example/x' --rule shortened_url --ttl 30d"),
                "A must pair with shortened_url: {lines:?}"
            );
            assert!(
                lines.iter().any(|l| l
                    == "tirith trust add 'http://b.example/y' --rule plain_http_to_sink --ttl 30d"),
                "B must pair with plain_http_to_sink: {lines:?}"
            );
            assert_eq!(
                lines.len(),
                2,
                "exactly two lines, no cartesian product: {lines:?}"
            );
            assert!(
                !lines.iter().any(
                    |l| l.contains("'https://a.example/x'") && l.contains("plain_http_to_sink")
                ),
                "A must NOT be cross-paired with plain_http_to_sink: {lines:?}"
            );
            assert!(
                !lines
                    .iter()
                    .any(|l| l.contains("'http://b.example/y'") && l.contains("shortened_url")),
                "B must NOT be cross-paired with shortened_url: {lines:?}"
            );
        });
    }

    /// `--apply` must fail loud on a PARTIAL apply: if `add()` rejects even one
    /// entry, the command exits non-zero instead of 0, so a partial result never
    /// masquerades as a clean success. Here the first finding's target is a valid
    /// narrow URL (`add()` accepts it -> stored), while the second's `raw_host`
    /// carries a control byte (0x07 BEL) that `validate_pattern` rejects ->
    /// `add()` returns 1 for that entry. Both reach the apply loop, so one
    /// succeeds and one fails: the overall exit must be 1.
    #[test]
    fn from_last_trigger_apply_partial_failure_returns_one() {
        let json = "{\
            \"rule_ids\": [\"shortened_url\", \"homograph\"],\
            \"findings\": [\
                {\
                    \"rule_id\": \"shortened_url\",\
                    \"title\": \"Shortened URL\",\
                    \"evidence\": [ { \"raw\": \"https://good.example/install.sh\" } ]\
                },\
                {\
                    \"rule_id\": \"homograph\",\
                    \"title\": \"Homograph\",\
                    \"evidence\": [ { \"raw_host\": \"evil.example\\u0007\" } ]\
                }\
            ]\
        }";

        with_seeded_last_trigger(json, || {
            // Both targets survive extraction: the good URL and the control-char
            // host (raw_host is pushed verbatim, no validation at read time).
            let pairs = read_last_trigger().expect("read_last_trigger");
            assert_eq!(
                pairs,
                vec![
                    (
                        "https://good.example/install.sh".to_string(),
                        Some("shortened_url".to_string())
                    ),
                    (
                        "evil.example\u{0007}".to_string(),
                        Some("homograph".to_string())
                    ),
                ],
                "both entries must reach the apply loop so one can succeed and one fail"
            );

            // Suggest (print-only) still exits 0 -- it never calls `add()`.
            assert_eq!(from_last_trigger(false), 0);

            // --apply: the good URL is stored, the control-char host is rejected
            // by `validate_pattern` inside `add()`. A partial apply must exit 1.
            assert_eq!(
                from_last_trigger(true),
                1,
                "a partial apply (one entry rejected by add) must fail loud, not exit 0"
            );
        });
    }

    /// F1 (HIGH): the suggestion line is copy/paste-ready, so a hostile target
    /// carrying shell metacharacters must be single-quoted; a target that can't
    /// be safely quoted (newline) must NOT yield a runnable command.
    #[test]
    fn from_last_trigger_shell_quotes_hostile_target() {
        // `extract_host` is applied to a schemeless `raw`; use `raw_host` so the
        // hostile bytes survive verbatim into the suggested line.
        let json = r#"{
            "rule_ids": ["confusable_domain"],
            "findings": [
                {
                    "rule_id": "confusable_domain",
                    "title": "Confusable",
                    "evidence": [ { "raw_host": "evil.example/$(touch X)" } ]
                }
            ]
        }"#;
        with_seeded_last_trigger(json, || {
            let pairs = read_last_trigger().expect("read_last_trigger");
            let lines = suggestion_lines(&pairs);
            let line = lines
                .iter()
                .find(|l| l.contains("tirith trust add"))
                .expect("a suggestion line");
            assert!(
                line.contains("'evil.example/$(touch X)'"),
                "hostile target must be single-quoted so $(touch X) cannot execute: {line}"
            );
            assert!(
                !line.replace("'evil.example/$(touch X)'", "").contains("$("),
                "no bare $( may survive outside the quoted token: {line}"
            );
        });

        // A target with a newline cannot be single-quoted as one token → no
        // runnable command, just the safe manual-trust note.
        assert_eq!(
            format_add_line("evil.example/a\nrm -rf ~", Some("confusable_domain"), true),
            "# trust this target manually with `tirith trust add` \
             (it contains characters unsafe to embed in a suggested command)."
        );

        // ANSI/OSC and deceptive Unicode must never be silently stripped into a
        // different runnable trust command. The sink emits only the static,
        // non-runnable manual-review note.
        let osc = format_add_line(
            "evil.example/\u{1b}]0;pwned\u{7}\u{1b}[31m",
            Some("confusable_domain"),
            true,
        );
        assert_eq!(
            osc,
            "# trust this target manually with `tirith trust add` \
             (it contains characters unsafe to embed in a suggested command)."
        );
        assert_eq!(
            format_add_line(
                "evil.example/\u{202e}txt.exe\u{200b}",
                Some("confusable_domain"),
                true,
            ),
            "# trust this target manually with `tirith trust add` \
             (it contains characters unsafe to embed in a suggested command)."
        );
    }

    /// `last()`'s rule-scoped ("r") choice must trust a host under ONLY the
    /// rule(s) that fired for THAT host, never every top-level rule in the
    /// verdict. `rules_for_host` is the per-host lookup that branch uses; here
    /// finding A (rule `shortened_url`) fired for `a.example`, finding B (rule
    /// `plain_http_to_sink`) for `b.example`. The old `last()` would have added
    /// BOTH rules to BOTH hosts (over-broad). `rules_for_host` must return each
    /// host's own single rule.
    #[test]
    fn rules_for_host_returns_only_that_hosts_rules() {
        let val: serde_json::Value = serde_json::from_str(
            r#"{
            "rule_ids": ["shortened_url", "plain_http_to_sink"],
            "findings": [
                {
                    "rule_id": "shortened_url",
                    "title": "Shortened URL",
                    "evidence": [ { "raw": "https://a.example/x" } ]
                },
                {
                    "rule_id": "plain_http_to_sink",
                    "title": "Plain HTTP",
                    "evidence": [ { "raw": "http://b.example/y" } ]
                }
            ]
        }"#,
        )
        .unwrap();

        // The display loop / prompt key on the bare host (via `extract_host`).
        assert_eq!(rules_for_host(&val, "a.example"), vec!["shortened_url"]);
        assert_eq!(
            rules_for_host(&val, "b.example"),
            vec!["plain_http_to_sink"]
        );
        // A host that did not trigger gets no rules (falls back to global trust).
        assert!(rules_for_host(&val, "c.example").is_empty());
    }

    /// When ONE host triggers MULTIPLE rules, the rule-scoped choice must add
    /// each of that host's own rules (and de-dupe), not collapse to one.
    #[test]
    fn rules_for_host_returns_all_own_rules_deduped() {
        let val: serde_json::Value = serde_json::from_str(
            r#"{
            "rule_ids": ["shortened_url", "plain_http_to_sink", "homograph"],
            "findings": [
                {
                    "rule_id": "shortened_url",
                    "evidence": [ { "raw": "https://a.example/x" }, { "raw_host": "a.example" } ]
                },
                {
                    "rule_id": "plain_http_to_sink",
                    "evidence": [ { "raw": "http://a.example/y" } ]
                },
                {
                    "rule_id": "homograph",
                    "evidence": [ { "raw_host": "b.example" } ]
                }
            ]
        }"#,
        )
        .unwrap();

        // a.example fired on two distinct rules across its findings; both are
        // returned, de-duped despite the repeated `raw`/`raw_host` evidence.
        assert_eq!(
            rules_for_host(&val, "a.example"),
            vec!["shortened_url", "plain_http_to_sink"],
            "a host with multiple rules keeps all of its own rules, deduped"
        );
        // b.example's unrelated rule must NOT leak onto a.example.
        assert_eq!(rules_for_host(&val, "b.example"), vec!["homograph"]);
    }

    /// A finding with evidence but no `rule_id` yields a host with no rules, so
    /// the rule-scoped branch falls back to global trust for that host. (Mirrors
    /// the old "no rule IDs in last trigger" path, now scoped per-host.)
    #[test]
    fn rules_for_host_empty_when_finding_has_no_rule_id() {
        let val: serde_json::Value = serde_json::from_str(
            r#"{
            "findings": [
                { "title": "Mystery", "evidence": [ { "raw_host": "a.example" } ] }
            ]
        }"#,
        )
        .unwrap();
        assert!(rules_for_host(&val, "a.example").is_empty());
    }

    /// A missing/empty trigger is the common "nothing happened yet" case:
    /// `from_last_trigger` returns 0 (friendly note), not an error.
    #[test]
    fn from_last_trigger_missing_returns_zero() {
        with_empty_data_dir(|| {
            assert_eq!(from_last_trigger(false), 0);
            // read_last_trigger surfaces the no-trigger sentinel for callers.
            assert_eq!(
                read_last_trigger().unwrap_err(),
                "no recent trigger found".to_string()
            );
        });
    }

    /// The refactor must keep `last()` behavior identical: with no trigger on
    /// disk it still returns 1 (its non-interactive, stdin-free path).
    #[test]
    fn last_unchanged_without_trigger_returns_one() {
        with_empty_data_dir(|| {
            assert_eq!(last(), 1);
        });
    }

    #[cfg(unix)]
    #[test]
    fn repo_lock_refuses_symlinked_store_directory_without_outside_creation() {
        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        std::os::unix::fs::symlink(outside.path(), root.path().join(".tirith")).unwrap();
        let path = root.path().join(".tirith/trust.json");

        assert!(
            lock_trust_store("repo", &path).is_err(),
            "symlinked lock directory must refuse"
        );

        assert!(!outside.path().join("trust.lock").exists());
    }

    #[test]
    fn repo_policy_change_deny_creates_no_trust_lock_or_store() {
        let root = tempfile::tempdir().unwrap();
        fs::create_dir(root.path().join(".git")).unwrap();
        let config = root.path().join(".tirith");
        fs::create_dir(&config).unwrap();
        fs::write(
            config.join("policy.yaml"),
            b"task_gate:\n  mode: enforce\n  effects_denied_for_untrusted_sources: [policy_change]\n",
        )
        .unwrap();
        let path = config.join("trust.json");

        if lock_trust_store("repo", &path).is_ok() {
            panic!("PolicyChange denial must happen before lock creation");
        }

        assert!(!config.join("trust.lock").exists());
        assert!(!path.exists());
    }

    #[cfg(unix)]
    #[test]
    fn repo_lock_refuses_a_final_symlink() {
        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::NamedTempFile::new().unwrap();
        let config = root.path().join(".tirith");
        fs::create_dir(&config).unwrap();
        fs::write(outside.path(), b"outside\n").unwrap();
        std::os::unix::fs::symlink(outside.path(), config.join("trust.lock")).unwrap();
        let path = config.join("trust.json");

        assert!(lock_trust_store("repo", &path).is_err());
        assert_eq!(fs::read(outside.path()).unwrap(), b"outside\n");
    }

    #[cfg(unix)]
    #[test]
    fn user_store_refuses_symlinked_config_root_without_outside_publication() {
        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let config = root.path().join("tirith-config");
        std::os::unix::fs::symlink(outside.path(), &config).unwrap();
        let path = config.join("trust.json");

        write_store_scoped_permitted("user", &path, &TrustStore::default())
            .expect_err("symlinked user config root must refuse");

        assert!(!outside.path().join("trust.json").exists());
    }

    #[cfg(unix)]
    #[test]
    fn trust_lock_and_data_capability_cannot_split_after_parent_swap() {
        let root = tempfile::tempdir().unwrap();
        let config = root.path().join(".tirith");
        let displaced = root.path().join(".tirith-displaced");
        fs::create_dir(&config).unwrap();
        let path = config.join("trust.json");
        let lock = lock_trust_store("repo", &path).unwrap();
        fs::rename(&config, &displaced).unwrap();
        fs::create_dir(&config).unwrap();

        write_store_scoped_permitted_locked("repo", &path, &TrustStore::default(), &lock)
            .expect_err("a replacement visible parent must not split lock and data authority");

        assert!(!path.exists());
        assert!(!displaced.join("trust.json").exists());
    }

    #[cfg(unix)]
    #[test]
    fn trust_lock_remains_serialized_after_legacy_sidecar_replacement() {
        let root = tempfile::tempdir().unwrap();
        let config = root.path().join(".tirith");
        fs::create_dir(&config).unwrap();
        let path = config.join("trust.json");
        let first = lock_trust_store("repo", &path).unwrap();
        let sidecar = config.join("trust.lock");
        fs::write(&sidecar, b"decoy").unwrap();
        fs::rename(&sidecar, config.join("displaced.lock")).unwrap();
        fs::write(&sidecar, b"replacement").unwrap();

        let competing_path = path.clone();
        let (sender, receiver) = std::sync::mpsc::channel();
        let contender = std::thread::spawn(move || {
            let acquired = lock_trust_store("repo", &competing_path);
            sender.send(acquired.is_ok()).unwrap();
        });
        assert!(matches!(
            receiver.recv_timeout(std::time::Duration::from_millis(100)),
            Err(std::sync::mpsc::RecvTimeoutError::Timeout)
        ));
        drop(first);
        assert!(receiver
            .recv_timeout(std::time::Duration::from_secs(2))
            .unwrap());
        contender.join().unwrap();
    }
}