tirith 0.3.3

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

use serde::{Deserialize, Serialize};

/// 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";

/// 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(),
        }
    }
}

/// How broad a trust pattern is, declared narrowest-first so the derived `Ord`
/// agrees: `ScopeKind::Exact < ScopeKind::BareTld` (broader = riskier).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ScopeKind {
    /// A specific URL, path, or checksum-like literal — trusts exactly one thing.
    Exact,
    /// A non-domain substring fragment (e.g. `repo/get-pip.py`) — trusts any
    /// URL/command containing that substring.
    Substring,
    /// A whole domain and all its subdomains (e.g. `github.com`).
    Domain,
    /// A wildcard domain (e.g. `*.example.com`).
    Wildcard,
    /// A bare top-level domain (e.g. `com`, `dev`) — trusts every host under
    /// that TLD. Almost always a mistake.
    BareTld,
}

impl ScopeKind {
    /// Short human label for listings.
    fn label(self) -> &'static str {
        match self {
            ScopeKind::Exact => "exact",
            ScopeKind::Substring => "substring",
            ScopeKind::Domain => "domain",
            ScopeKind::Wildcard => "wildcard",
            ScopeKind::BareTld => "bare-TLD",
        }
    }

    /// One-line description of what an entry of this kind covers.
    fn coverage(self) -> &'static str {
        match self {
            ScopeKind::Exact => "matches this exact string only",
            ScopeKind::Substring => "matches any URL or command containing this substring",
            ScopeKind::Domain => "matches this domain and every subdomain under it",
            ScopeKind::Wildcard => "matches every subdomain of this domain",
            ScopeKind::BareTld => "matches every host under this entire top-level domain",
        }
    }

    /// True when an entry of this kind is broad enough that `trust add` should
    /// require an explicit `--broad` opt-in.
    fn is_broad(self) -> bool {
        matches!(
            self,
            ScopeKind::Domain | ScopeKind::Wildcard | ScopeKind::BareTld
        )
    }

    /// True when an entry of this kind is dangerously broad and deserves a
    /// standing warning wherever it is shown.
    fn is_dangerous(self) -> bool {
        matches!(self, ScopeKind::Wildcard | ScopeKind::BareTld)
    }
}

/// Small set of public suffixes to distinguish a *bare* TLD (`com`) from a
/// registrable domain (`example.com`). Not a full PSL — just enough to reject
/// `trust add com` by default.
const KNOWN_TLDS: &[&str] = &[
    "com", "net", "org", "io", "dev", "sh", "co", "ai", "app", "xyz", "info", "biz", "me", "us",
    "uk", "de", "fr", "ru", "cn", "jp", "in", "br", "ca", "au", "eu", "gov", "edu", "mil", "tv",
    "cc", "ws", "to", "gg", "fm", "site", "online", "tech", "cloud", "store", "live", "run", "id",
];

/// Classify how broad a trust pattern is.
pub fn classify_scope(pattern: &str) -> ScopeKind {
    let p = pattern.trim().to_lowercase();

    if let Some(rest) = p.strip_prefix("*.") {
        // `*.com` is a bare-TLD wildcard — still the worst case.
        if !rest.contains('.') && KNOWN_TLDS.contains(&rest) {
            return ScopeKind::BareTld;
        }
        return ScopeKind::Wildcard;
    }

    // A scheme, path, query, or fragment pins a specific URL/resource → Exact.
    if p.contains("://") || p.contains('/') || p.contains('?') || p.contains('#') {
        return ScopeKind::Exact;
    }

    // Bare token, no dot: a bare TLD or a non-domain substring fragment.
    if !p.contains('.') {
        if KNOWN_TLDS.contains(&p.as_str()) {
            return ScopeKind::BareTld;
        }
        return ScopeKind::Substring;
    }

    // At least one dot, no path: a `host.tld`-shaped registrable domain.
    let labels: Vec<&str> = p.split('.').filter(|l| !l.is_empty()).collect();
    if labels.len() >= 2 {
        ScopeKind::Domain
    } else {
        // Trailing-dot oddity → substring.
        ScopeKind::Substring
    }
}

/// 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!("tirith: trust {subcmd}: {err}");
    if err.contains("git repository") {
        if let Some(pattern) = hint_pattern {
            eprintln!("  try: tirith trust {subcmd} {pattern} --scope user");
        } else {
            eprintln!("  try: tirith trust {subcmd} --scope user");
        }
    }
}

/// 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: {e}");
            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> {
    match fs::read_to_string(path) {
        Ok(content) => serde_json::from_str(&content)
            .map_err(|e| format!("corrupt trust store at {}: {e}", path.display())),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(TrustStore::default()),
        Err(e) => Err(format!("cannot read {}: {e}", path.display())),
    }
}

/// Write the trust store to a path, creating parent directories as needed.
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_string_pretty(store)
        .map_err(|e| format!("failed to serialize trust store: {e}"))?;
    fs::write(path, json).map_err(|e| format!("failed to write {}: {e}", path.display()))?;
    Ok(())
}

/// 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> {
    if pattern.is_empty() {
        return Err("pattern must not be empty".to_string());
    }
    // Reject control chars (< 0x20, except tab) to stop ANSI escapes / NULs in entries.
    for (i, b) in pattern.bytes().enumerate() {
        if b < 0x20 && b != b'\t' {
            return Err(format!(
                "pattern contains control character at byte offset {i} (0x{b:02x})"
            ));
        }
    }
    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 {
    // 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!("tirith: trust 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: '{pattern}' is a {} 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 '.{pattern}' — \
                 this is almost never what you want."
            );
        }
        return 1;
    }

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

    let mut store = match load_store(&path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("tirith: trust 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!("tirith: trust 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(&path, &store) {
        eprintln!("tirith: trust add: {e}");
        return 1;
    }

    tirith_core::audit::log_trust_change(pattern, rule_id, "add", ttl_expires.as_deref(), scope);

    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 '{pattern}' (scope: {scope}, {} pattern{ttl_note})",
        scope_kind.label()
    );
    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!("tirith: trust list: unknown scope '{scope}' (use 'user', 'repo', or 'all')");
        return 1;
    }

    let mut rows: Vec<TrustListRow> = match collect_rows(scope, show_expired) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("tirith: trust 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| r.pattern.len())
            .max()
            .unwrap_or(7)
            .max(7);
        let max_src = rows
            .iter()
            .map(|r| r.source.len())
            .max()
            .unwrap_or(6)
            .max(6);
        let max_rule = rows
            .iter()
            .map(|r| r.rule_id.as_ref().map(|s| 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 rule_display = row.rule_id.as_deref().unwrap_or("-");
            let expires_display = match (&row.expires, row.expired) {
                (Some(exp), true) => format!("{exp} (EXPIRED)"),
                (Some(exp), false) => match humanize_expiry(Some(exp)) {
                    Some(h) => format!("{exp} ({h})"),
                    None => exp.clone(),
                },
                (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$}  {}",
                row.pattern, rule_display, scope_display, row.source, 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(&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;
        }
    };

    let mut store = match load_store(&path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("tirith: trust 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 '{pattern}'");
        return 1;
    }

    if let Err(e) = write_store(&path, &store) {
        eprintln!("tirith: trust remove: {e}");
        return 1;
    }

    tirith_core::audit::log_trust_change(pattern, rule_id, "remove", None, scope);

    eprintln!("tirith: removed {removed} trust entry/entries for '{pattern}' (scope: {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> {
    let data_dir = tirith_core::policy::data_dir()
        .ok_or_else(|| "cannot determine data directory".to_string())?;
    let path = data_dir.join("last_trigger.json");
    if !path.exists() {
        return Ok(None);
    }
    let content =
        fs::read_to_string(&path).map_err(|e| format!("failed to read last trigger: {e}"))?;
    let val: serde_json::Value =
        serde_json::from_str(&content).map_err(|e| format!("failed to parse last trigger: {e}"))?;
    Ok(Some(val))
}

/// 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. Scrub terminal-control bytes first, then shell-single-quote.
    // The scrub (`sanitize_text_str`, same filter `output.rs::write_block_advisories`
    // applies to blocklist URLs) strips ANSI/OSC/zero-width bytes so the target
    // cannot repaint the operator's terminal at suggest time. The single-quote
    // then keeps a target carrying `$( )`, backticks, `;`, spaces, a `>` redirect,
    // or a glob from executing on paste. If it can't be safely quoted (e.g. it
    // contains a newline), do NOT emit a runnable command — print a safe
    // manual-trust note instead. The `--rule <rid>` is a snake_case enum Display
    // (not attacker-controlled), so it needs no quoting. The printed `--ttl` uses
    // `DEFAULT_TTL`, the same value `--apply` resolves to (see `from_last_trigger`),
    // so the suggestion and the applied entry can't drift.
    let scrubbed = tirith_core::mcp::output_filter::sanitize_text_str(target);
    let Some(quoted) = tirith_core::safe_command::shell_single_quote(&scrubbed) 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) => 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!("tirith: trust 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!("{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!("tirith: {e}");
            return 1;
        }
    };

    if let Some(ts) = val.get("timestamp").and_then(|v| v.as_str()) {
        eprintln!("Last trigger at: {ts}");
    }
    if let Some(cmd) = val.get("command_redacted").and_then(|v| v.as_str()) {
        eprintln!("Command: {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!("  - {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 {
        eprintln!();
        eprint!("Trust {domain}? [y/N/r(rule-scoped)/t(temporary 7d)] ");
        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 {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 {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!(
            "tirith: trust {action_label}: unknown scope '{scope}' (use '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 !path.exists() {
            continue;
        }

        let mut store = match load_store(&path) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("tirith: trust {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(&path, &store) {
                eprintln!("tirith: trust {action_label}: {e}");
                return 1;
            }
            for entry in &expired_entries {
                tirith_core::audit::log_trust_change(
                    &entry.pattern,
                    entry.rule_id.as_deref(),
                    action_label,
                    entry.ttl_expires.as_deref(),
                    s,
                );
            }
            if !json {
                eprintln!(
                    "tirith: {action_label}: removed {removed} expired entries from {s} scope",
                );
            }
        }

        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: {action_label}: no expired entries found");
    }

    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!("tirith: trust explain: unknown scope '{scope}' (use '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(&path) {
            Ok(st) => st,
            Err(e) => {
                eprintln!("tirith: trust 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: '{pattern}' is not currently trusted in scope '{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: {pattern}");
    for (i, m) in report.matches.iter().enumerate() {
        if i > 0 {
            println!();
        }
        println!("  source:   {}", m.source);
        println!(
            "  scope:    {}{}",
            m.scope_kind.label(),
            m.scope_coverage
        );
        if let Some(rid) = &m.rule_id {
            println!("  rule:     {rid} (suppresses this rule only)");
        } else {
            println!("  rule:     (global — suppresses every rule)");
        }
        if let Some(added) = &m.added {
            println!("  added:    {added}");
        }
        match &m.reason {
            Some(r) => println!("  reason:   {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:  {exp}{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!("tirith: trust audit: 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!(
                "tirith: trust audit: 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!(
                "tirith: trust audit: 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!(
            "tirith: trust audit: 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} {}{}",
            r.timestamp, r.action, r.scope, r.pattern, 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 {ts})"),
        None => println!("trust diff"),
    }
    if let Some(note) = &report.note {
        println!("  note: {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!(
                "    + {} ({}, {}){rule}",
                e.pattern,
                e.source,
                e.scope_kind.label()
            );
        }
    }
    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!(
                "    - {} ({}, {}){rule}",
                e.pattern,
                e.source,
                e.scope_kind.label()
            );
        }
    }
    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::*;

    #[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_tab_ok() {
        let policy = tirith_core::policy::Policy::default();
        assert!(validate_pattern("hello\tworld", &policy).is_ok());
    }

    #[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 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"));
    }

    #[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);
        // 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"]);
    }

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

        let dir = tempfile::tempdir().expect("tempdir");
        let _xdg = EnvGuard::set("XDG_DATA_HOME", dir.path());
        let _appdata = EnvGuard::set("APPDATA", dir.path());

        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::{EnvGuard, ENV_LOCK};
        let _lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());

        let dir = tempfile::tempdir().expect("tempdir");
        let _xdg = EnvGuard::set("XDG_DATA_HOME", dir.path());
        let _appdata = EnvGuard::set("APPDATA", dir.path());
        f();
    }

    /// 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)."
        );

        // Defense-in-depth: ANSI/OSC escape bytes in the target are scrubbed
        // BEFORE quoting (single-quoting blocks shell execution, but a raw ESC
        // could still spoof the operator's terminal as the line is printed). The
        // emitted line must carry no raw ESC (0x1B) byte.
        let osc = format_add_line(
            "evil.example/\u{1b}]0;pwned\u{7}\u{1b}[31m",
            Some("confusable_domain"),
            true,
        );
        assert!(
            !osc.contains('\u{1b}'),
            "ESC (0x1B) must be scrubbed before the suggestion is printed: {osc:?}"
        );
        // The scrub strips the control bytes but keeps the printable remainder,
        // so this is still a runnable (single-quoted) trust command.
        assert!(
            osc.contains("tirith trust add"),
            "scrubbed target should still yield a runnable trust line: {osc:?}"
        );
    }

    /// `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);
        });
    }
}