termshot 1.2.0

Terminal screenshot CLI and MCP server with ANSI rendering, redaction, themes, and composition
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
//! Regex-based redaction engine.
//!
//! The redaction pass sits between vt100 parsing and PNG rendering:
//!
//! ```text
//! raw PTY bytes -> vt100 parser -> redaction pass -> render to PNG
//! ```
//!
//! It scans the parsed screen ([`crate::capture::CapturedScreen`], or any
//! [`ScreenView`]) cell
//! by cell -- every retained row, scrollback included, not just the last
//! screenful -- runs a set of regex rules against each row's text, and produces
//! a [`RedactionMap`] describing which cells must be masked. The renderer
//! consults that map and draws bright
//! red blocks (with an optional short label such as `[IP]`) in place of the
//! sensitive characters. The vt100 buffer itself is never mutated, which keeps
//! the pass side-effect free and avoids re-parsing fragile ANSI streams.
//!
//! The engine deliberately never records the *values* it redacts -- only the
//! per-rule match counts -- so audit logs cannot leak the very data they are
//! meant to protect.

use crate::capture::ScreenView;
use anyhow::{Context, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// A single user-configurable redaction rule as read from `config.toml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedactionRuleConfig {
    /// Unique rule name (also used to override a compiled-in builtin).
    pub name: String,
    /// Regex pattern to match against terminal row text.
    #[serde(default)]
    pub pattern: String,
    /// Text used to derive the audit label / replacement marker.
    #[serde(default = "default_replacement")]
    pub replacement: String,
    /// Whether the rule participates in redaction.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Optional per-rule redaction block color as `#RRGGBB`. Falls back to the
    /// engine-wide `[redaction] color` and then the built-in red.
    #[serde(default)]
    pub color: Option<String>,
    /// Optional minimum Shannon entropy (bits/char) of the matched text; a
    /// match with lower entropy is ignored. Used by YAML rule files to
    /// suppress low-randomness false positives.
    #[serde(default)]
    pub min_entropy: Option<f64>,
    /// Number of leading matched characters to leave unmasked (partial
    /// redaction). When set, the prefix renders normally and only the
    /// characters after it are blocked out, e.g. `AKIA████████████████`.
    #[serde(default)]
    pub keep_prefix: Option<usize>,
    /// Number of trailing matched characters to leave unmasked (partial
    /// redaction). When set, the suffix renders normally and only the
    /// characters before it are blocked out.
    #[serde(default)]
    pub keep_suffix: Option<usize>,
}

impl RedactionRuleConfig {
    /// Construct a rule with just the core fields set (used for builtins and
    /// ad-hoc/agent-supplied rules); optional fields default to `None`.
    pub fn new(name: &str, pattern: &str, replacement: &str) -> Self {
        Self {
            name: name.to_string(),
            pattern: pattern.to_string(),
            replacement: replacement.to_string(),
            enabled: true,
            color: None,
            min_entropy: None,
            keep_prefix: None,
            keep_suffix: None,
        }
    }
}

fn default_replacement() -> String {
    "[REDACTED]".to_string()
}

fn default_true() -> bool {
    true
}

/// Default redaction block color (bright red, `#d41919`).
pub const DEFAULT_BLOCK_COLOR: [u8; 3] = [212, 25, 25];
/// Default redaction label text color (black).
pub const DEFAULT_LABEL_COLOR: [u8; 3] = [0, 0, 0];

/// The `[redaction]` section of the config file.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RedactionConfig {
    /// Master switch: when false, `auto` redaction never runs (an explicit
    /// `--redact` / `redact: true` request still forces it on).
    pub enabled: bool,
    /// When true, redact every screenshot without needing an explicit flag.
    /// Off by default: a false positive silently corrupts a screenshot of
    /// ordinary output, which is worse than requiring `--redact` when you are
    /// capturing something sensitive.
    pub auto: bool,
    /// Default redaction block color as `#RRGGBB` (default red).
    #[serde(default)]
    pub color: Option<String>,
    /// Redaction label text color as `#RRGGBB` (default black).
    #[serde(default)]
    pub label_color: Option<String>,
    /// Optional directory of extra rule files (`.toml`, `.yaml`, `.yml`) to
    /// load in addition to the inline `rules` below. The generic YAML rule
    /// format is supported.
    #[serde(default)]
    pub rules_path: Option<String>,
    /// User rule overrides / additions. These are merged on top of the
    /// compiled-in builtin rules, keyed by `name`.
    pub rules: Vec<RedactionRuleConfig>,
}

impl Default for RedactionConfig {
    fn default() -> Self {
        Self {
            // The rules are available (so `--redact` / `redact: true` works out
            // of the box) but do not run unattended: automatic redaction of
            // every screenshot risks masking legitimate output, and a corrupted
            // capture is a worse default than an unmasked one. Opt in with
            // `auto = true` in config when you always want it.
            enabled: true,
            auto: false,
            color: None,
            label_color: None,
            rules_path: None,
            rules: Vec::new(),
        }
    }
}

/// Decide whether redaction should run for a single screenshot.
///
/// * an explicit "no redact" request always wins and disables redaction;
/// * `enabled = false` is the master switch: nothing runs, not even on an
///   explicit request (callers should surface that as an error rather than
///   silently hand back an unredacted image - see
///   [`explicit_request_is_blocked`]);
/// * an explicit "redact" request then forces redaction on, even when `auto`
///   is off;
/// * otherwise redaction runs only when it is both `enabled` and `auto`.
pub fn resolve_should_redact(cfg: &RedactionConfig, redact: bool, no_redact: bool) -> bool {
    if no_redact || !cfg.enabled {
        return false;
    }
    if redact {
        return true;
    }
    cfg.auto
}

/// True when the caller explicitly asked for redaction but the master switch
/// (`[redaction] enabled`) is off, so the request cannot be honored. Callers
/// must fail loudly in that case: quietly writing an unredacted screenshot for
/// someone who typed `--redact` is the worst possible outcome.
pub fn explicit_request_is_blocked(cfg: &RedactionConfig, redact: bool, no_redact: bool) -> bool {
    redact && !no_redact && !cfg.enabled
}

/// Error message for a blocked explicit request, shared by the CLI and MCP.
pub const REDACTION_DISABLED_MSG: &str = "redaction was requested but is disabled in config ([redaction] enabled = false); \
     set enabled = true to use --redact / redact: true";

/// A compiled rule ready to match against terminal text.
#[derive(Debug)]
struct CompiledRule {
    name: String,
    /// On-image label, or `None` to draw a plain block with no text overlay.
    label: Option<String>,
    regex: Regex,
    /// True when the pattern declares a `(?P<redact>...)` group. Such a rule
    /// may match surrounding context (to reject look-alikes such as `std::fs`)
    /// while only the captured group is masked.
    has_redact_group: bool,
    /// Optional predicate; when it returns true for a match the match is
    /// skipped (used to keep obviously non-sensitive values like `127.0.0.1`).
    skip: Option<fn(&str) -> bool>,
    /// When set, ignore matches whose Shannon entropy is below this threshold.
    min_entropy: Option<f64>,
    /// Block color for this rule's redactions.
    block_color: [u8; 3],
    /// Label text color for this rule's redactions.
    label_color: [u8; 3],
    /// Leading matched characters to leave unmasked (partial redaction).
    keep_prefix: usize,
    /// Trailing matched characters to leave unmasked (partial redaction).
    keep_suffix: usize,
}

impl CompiledRule {
    /// Byte ranges of this rule's matches in `line`. When the pattern declares
    /// a `redact` capture group, only that group's span is returned, so a rule
    /// can require surrounding context without masking it.
    fn match_spans(&self, line: &str) -> Vec<(usize, usize)> {
        if self.has_redact_group {
            self.regex
                .captures_iter(line)
                .filter_map(|caps| caps.name("redact").map(|m| (m.start(), m.end())))
                .collect()
        } else {
            self.regex
                .find_iter(line)
                .map(|m| (m.start(), m.end()))
                .collect()
        }
    }
}

/// A compiled set of redaction rules.
#[derive(Debug)]
pub struct RedactionEngine {
    rules: Vec<CompiledRule>,
}

impl RedactionEngine {
    /// Build an engine by merging the compiled-in builtin rules with any user
    /// overrides / additions from config. A user rule with the same `name` as
    /// a builtin overrides it (letting users tweak a pattern, disable a rule,
    /// or change its replacement); other user rules are appended.
    pub fn from_config(cfg: &RedactionConfig) -> Result<Self> {
        Self::from_config_with_labels(cfg, true)
    }

    /// Like [`from_config`](Self::from_config) but lets the caller suppress the
    /// on-image `[LABEL]` tags, drawing plain solid blocks instead.
    pub fn from_config_with_labels(cfg: &RedactionConfig, show_labels: bool) -> Result<Self> {
        // Start from the builtin defaults, preserving their order.
        let mut order: Vec<String> = Vec::new();
        let mut merged: HashMap<String, RedactionRuleConfig> = HashMap::new();
        for rule in builtin_rules() {
            order.push(rule.name.clone());
            merged.insert(rule.name.clone(), rule);
        }

        // Overlay user rules.
        for user in &cfg.rules {
            if let Some(existing) = merged.get_mut(&user.name) {
                // Override a builtin: an empty pattern means "keep the builtin
                // pattern but apply the other fields" (e.g. just disabling it).
                if !user.pattern.is_empty() {
                    existing.pattern = user.pattern.clone();
                }
                existing.replacement = user.replacement.clone();
                existing.enabled = user.enabled;
                existing.min_entropy = user.min_entropy;
                if user.color.is_some() {
                    existing.color = user.color.clone();
                }
                if user.keep_prefix.is_some() {
                    existing.keep_prefix = user.keep_prefix;
                }
                if user.keep_suffix.is_some() {
                    existing.keep_suffix = user.keep_suffix;
                }
            } else {
                order.push(user.name.clone());
                merged.insert(user.name.clone(), user.clone());
            }
        }

        // Resolve engine-wide default colors.
        let default_block = cfg
            .color
            .as_deref()
            .and_then(parse_hex_rgb)
            .unwrap_or(DEFAULT_BLOCK_COLOR);
        let default_label = cfg
            .label_color
            .as_deref()
            .and_then(parse_hex_rgb)
            .unwrap_or(DEFAULT_LABEL_COLOR);

        let ordered: Vec<RedactionRuleConfig> = order
            .into_iter()
            .map(|name| merged[&name].clone())
            .collect();
        Self::compile(&ordered, default_block, default_label, show_labels)
    }

    /// Build an engine from an explicit list of rules only (no builtins). Used
    /// for agent-driven, ad-hoc redaction where the caller supplies exactly the
    /// patterns to apply.
    pub fn from_rules(rules: &[RedactionRuleConfig]) -> Result<Self> {
        Self::from_rules_with_labels(rules, true)
    }

    /// Like [`from_rules`](Self::from_rules) but lets the caller suppress the
    /// on-image `[LABEL]` tags, drawing plain solid blocks instead.
    pub fn from_rules_with_labels(
        rules: &[RedactionRuleConfig],
        show_labels: bool,
    ) -> Result<Self> {
        Self::compile(rules, DEFAULT_BLOCK_COLOR, DEFAULT_LABEL_COLOR, show_labels)
    }

    /// Compile a fully-resolved rule list into an engine. When `show_labels` is
    /// false, every rule renders as a plain block with no text overlay.
    fn compile(
        rules: &[RedactionRuleConfig],
        default_block: [u8; 3],
        default_label: [u8; 3],
        show_labels: bool,
    ) -> Result<Self> {
        let mut compiled = Vec::new();
        for rc in rules {
            if !rc.enabled || rc.pattern.is_empty() {
                continue;
            }
            let regex = Regex::new(&rc.pattern)
                .with_context(|| format!("invalid regex for redaction rule '{}'", rc.name))?;
            let block_color = rc
                .color
                .as_deref()
                .and_then(parse_hex_rgb)
                .unwrap_or(default_block);
            let label = if show_labels {
                label_for(&rc.name, &rc.replacement)
            } else {
                None
            };
            compiled.push(CompiledRule {
                name: rc.name.clone(),
                label,
                has_redact_group: regex.capture_names().flatten().any(|n| n == "redact"),
                regex,
                skip: builtin_skip(&rc.name),
                min_entropy: rc.min_entropy,
                block_color,
                label_color: default_label,
                keep_prefix: rc.keep_prefix.unwrap_or(0),
                keep_suffix: rc.keep_suffix.unwrap_or(0),
            });
        }
        Ok(Self { rules: compiled })
    }

    /// Number of active (enabled, compiled) rules.
    pub fn rule_count(&self) -> usize {
        self.rules.len()
    }

    /// Names of the active (enabled, compiled) rules.
    pub fn rule_names(&self) -> Vec<&str> {
        self.rules.iter().map(|r| r.name.as_str()).collect()
    }

    /// Validate that every name in `requested` matches an active rule. Returns
    /// an error listing the unknown names so an explicit `--redact-rules`
    /// request fails loudly instead of silently selecting zero rules.
    pub fn validate_rule_names(&self, requested: &[String]) -> Result<()> {
        let unknown: Vec<&str> = requested
            .iter()
            .filter(|name| !self.rules.iter().any(|r| &r.name == *name))
            .map(|s| s.as_str())
            .collect();
        if !unknown.is_empty() {
            let available = self.rule_names().into_iter().collect::<Vec<_>>().join(", ");
            anyhow::bail!(
                "unknown redaction rule(s): {}. Available rules: {}",
                unknown.join(", "),
                available
            );
        }
        Ok(())
    }

    /// Scan a parsed screen and build the map of cells to redact.
    ///
    /// When `only` is `Some`, only rules whose name appears in the list are
    /// applied; otherwise every enabled rule runs.
    pub fn redact_screen<S: ScreenView + ?Sized>(
        &self,
        screen: &S,
        only: Option<&[String]>,
    ) -> RedactionMap {
        let mut map = RedactionMap::default();
        self.redact_screen_into(screen, only, &mut map);
        map
    }

    /// Scan a parsed screen and merge redactions into an existing map (so
    /// multiple engines / manual redactions can be combined).
    ///
    /// Rules run against *logical* lines: soft-wrapped physical rows are joined
    /// before matching, so a secret that crosses the right margin is still
    /// recognized. Every byte of the joined line keeps a `(row, column)`
    /// back-reference, so a match spanning the wrap masks cells on both rows.
    pub fn redact_screen_into<S: ScreenView + ?Sized>(
        &self,
        screen: &S,
        only: Option<&[String]>,
        map: &mut RedactionMap,
    ) {
        let mut counts: HashMap<String, usize> = HashMap::new();

        for (line, positions) in logical_lines(screen) {
            for rule in &self.rules {
                if let Some(names) = only
                    && !names.iter().any(|n| n == &rule.name)
                {
                    continue;
                }

                for (start, end) in rule.match_spans(&line) {
                    let matched = &line[start..end];
                    if let Some(skip) = rule.skip
                        && skip(matched)
                    {
                        continue;
                    }
                    if let Some(threshold) = rule.min_entropy
                        && shannon_entropy(matched) < threshold
                    {
                        continue;
                    }

                    // Collect the distinct cells this match covers, which may
                    // span more than one physical row when the line wrapped.
                    let mut match_cells: Vec<(u16, u16)> = Vec::new();
                    for &pos in &positions[start..end] {
                        if match_cells.last() != Some(&pos) {
                            match_cells.push(pos);
                        }
                    }
                    if match_cells.is_empty() {
                        continue;
                    }

                    // Partial redaction: leave the first `keep_prefix` and last
                    // `keep_suffix` matched cells visible, blocking only the
                    // middle. If the kept prefix/suffix cover the whole match
                    // there is nothing left to redact, so skip it entirely.
                    let start_idx = rule.keep_prefix.min(match_cells.len());
                    let end_idx = match_cells
                        .len()
                        .saturating_sub(rule.keep_suffix)
                        .max(start_idx);
                    let redact_cells = &match_cells[start_idx..end_idx];
                    if redact_cells.is_empty() {
                        continue;
                    }

                    map.apply_run(
                        redact_cells,
                        rule.label.as_deref(),
                        rule.block_color,
                        rule.label_color,
                    );
                    *counts.entry(rule.name.clone()).or_insert(0) += 1;
                }
            }
        }

        // Stable audit ordering: most frequent first, then alphabetical.
        let mut combined: HashMap<String, usize> = map.counts.iter().cloned().collect();
        for (name, count) in counts {
            *combined.entry(name).or_insert(0) += count;
        }
        let mut audit: Vec<(String, usize)> = combined.into_iter().collect();
        audit.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        map.counts = audit;
    }
}

/// Split a screen into logical lines, joining soft-wrapped physical rows.
///
/// Returns, for each logical line, its text and a parallel vector mapping every
/// *byte* of that text back to the `(row, column)` cell it came from. Wide
/// characters and empty cells both contribute exactly one cell.
fn logical_lines<S: ScreenView + ?Sized>(screen: &S) -> Vec<(String, Vec<(u16, u16)>)> {
    let (rows, cols) = screen.size();
    let mut lines = Vec::new();
    let mut row = 0u16;
    while row < rows {
        let mut line = String::new();
        let mut positions: Vec<(u16, u16)> = Vec::new();
        let mut last = row;
        loop {
            append_row(screen, last, cols, &mut line, &mut positions);
            // vt100 marks a row as "wrapped" when its content continues on the
            // next row; keep appending until the logical line ends.
            if last + 1 < rows && screen.row_wrapped(last) {
                last += 1;
            } else {
                break;
            }
        }
        lines.push((line, positions));
        row = last + 1;
    }
    lines
}

/// Append one physical row's text (and its byte -> cell mapping) to `line`.
fn append_row<S: ScreenView + ?Sized>(
    screen: &S,
    row: u16,
    cols: u16,
    line: &mut String,
    positions: &mut Vec<(u16, u16)>,
) {
    for col in 0..cols {
        let contents = screen
            .cell(row, col)
            .map(|c| c.contents())
            .unwrap_or_default();
        if contents.is_empty() {
            line.push(' ');
            positions.push((row, col));
        } else {
            for ch in contents.chars() {
                for _ in 0..ch.len_utf8() {
                    positions.push((row, col));
                }
                line.push(ch);
            }
        }
    }
}

/// A single redacted cell. `label_char` carries the glyph to draw over the red
/// block (e.g. the `[`, `I`, `P`, `]` of an `[IP]` tag); `None` means a plain
/// block. `block_color` / `label_color` are the RGB colors the renderer paints.
#[derive(Debug, Clone, Copy)]
pub struct RedactedCell {
    pub label_char: Option<char>,
    pub block_color: [u8; 3],
    pub label_color: [u8; 3],
}

/// The result of a redaction pass: which cells to mask and the per-rule audit
/// counts (never the redacted values themselves).
#[derive(Debug, Default)]
pub struct RedactionMap {
    cells: HashMap<(u16, u16), RedactedCell>,
    /// (rule name, match count), sorted most-frequent first.
    pub counts: Vec<(String, usize)>,
}

impl RedactionMap {
    /// Mask a run of cells, laying a `[LABEL]` tag over the start of the run
    /// when a label is given and it fits. Passing `None` (or a label that does
    /// not fit) draws plain blocks. Cells already redacted by an earlier
    /// (overlapping) match are left untouched. The run may span rows when the
    /// matched text crossed a soft line wrap.
    fn apply_run(
        &mut self,
        cells: &[(u16, u16)],
        label: Option<&str>,
        block_color: [u8; 3],
        label_color: [u8; 3],
    ) {
        let tag_chars: Vec<char> = match label {
            Some(l) if !l.is_empty() => format!("[{}]", l).chars().collect(),
            _ => Vec::new(),
        };
        let use_label = !tag_chars.is_empty() && cells.len() >= tag_chars.len();

        for (i, &(row, col)) in cells.iter().enumerate() {
            let label_char = if use_label && i < tag_chars.len() {
                Some(tag_chars[i])
            } else {
                None
            };
            self.cells.entry((row, col)).or_insert(RedactedCell {
                label_char,
                block_color,
                label_color,
            });
        }
    }

    /// Add a manual (coordinate-based) redaction spanning `[col_start, col_end)`
    /// on `row`, using the default colors. `label` is drawn over the block when
    /// `Some` (and it fits); `None` draws a plain block. Counted in the audit
    /// under the label when present, otherwise under `manual`.
    pub fn add_manual(&mut self, row: u16, col_start: u16, col_end: u16, label: Option<&str>) {
        self.add_manual_with_color(
            row,
            col_start,
            col_end,
            label,
            DEFAULT_BLOCK_COLOR,
            DEFAULT_LABEL_COLOR,
        );
    }

    /// [`RedactionMap::add_manual`] with explicit colors, so a caller-supplied
    /// per-redaction `color` paints this block without changing any other.
    pub fn add_manual_with_color(
        &mut self,
        row: u16,
        col_start: u16,
        col_end: u16,
        label: Option<&str>,
        block_color: [u8; 3],
        label_color: [u8; 3],
    ) {
        if col_end <= col_start {
            return;
        }
        let cells: Vec<(u16, u16)> = (col_start..col_end).map(|col| (row, col)).collect();
        self.apply_run(&cells, label, block_color, label_color);
        let name = match label {
            Some(l) if !l.is_empty() => format!("manual:{}", l),
            _ => "manual".to_string(),
        };
        if let Some(entry) = self.counts.iter_mut().find(|(n, _)| n == &name) {
            entry.1 += 1;
        } else {
            self.counts.push((name, 1));
        }
    }

    /// Look up a cell's redaction, if any.
    pub fn get(&self, row: u16, col: u16) -> Option<&RedactedCell> {
        self.cells.get(&(row, col))
    }

    /// True when nothing was redacted.
    pub fn is_empty(&self) -> bool {
        self.cells.is_empty()
    }

    /// Total number of redacted cells.
    pub fn cell_count(&self) -> usize {
        self.cells.len()
    }

    /// A human-readable audit summary such as `3x ipv4, 1x aws_key`.
    pub fn audit_summary(&self) -> String {
        self.counts
            .iter()
            .map(|(name, count)| format!("{}x {}", count, name))
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Produce a redaction-safe plain-text rendering of the screen, replacing
    /// masked cells with the full-block glyph so returned text never leaks the
    /// original values while preserving column alignment.
    pub fn redacted_plain_text<S: ScreenView + ?Sized>(&self, screen: &S) -> String {
        let (rows, cols) = screen.size();
        let mut out_rows: Vec<String> = Vec::with_capacity(rows as usize);
        for row in 0..rows {
            let mut line = String::new();
            for col in 0..cols {
                if self.cells.contains_key(&(row, col)) {
                    line.push('\u{2588}'); // â–ˆ
                } else {
                    let contents = screen
                        .cell(row, col)
                        .map(|c| c.contents())
                        .unwrap_or_default();
                    if contents.is_empty() {
                        line.push(' ');
                    } else {
                        line.push_str(contents);
                    }
                }
            }
            out_rows.push(line.trim_end().to_string());
        }
        out_rows.join("\n").trim_end().to_string()
    }
}

// ---------------------------------------------------------------------------
// Manual redaction specifications (shared by the CLI and the MCP server)
// ---------------------------------------------------------------------------

/// A single manual redaction: either a regex pattern (redacts every match) or
/// an explicit cell range.
///
/// This is the one representation of a caller-supplied redaction in termshot:
/// the MCP `redact_screenshot` tool decodes its `redactions` array into it, and
/// the CLI's repeatable `--redaction '<JSON>'` option parses the same JSON into
/// the same type, so both entry points accept exactly the same specifications
/// and apply them the same way.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum ManualRedactionSpec {
    /// Redact every match of a regex pattern.
    Pattern {
        /// Regex pattern to match against the terminal text.
        pattern: String,
        /// Replacement marker used to derive the on-image `[LABEL]` tag. May
        /// also be given as `label`. Omitted (or empty) draws a plain block
        /// with no text overlay.
        #[serde(default, alias = "label")]
        replacement: Option<String>,
        /// Number of leading matched characters to leave unmasked. When set,
        /// only the characters after the prefix are blocked out (e.g. show
        /// `AKIA****` for an AWS key). Defaults to 0 (mask everything).
        #[serde(default)]
        keep_prefix: Option<usize>,
        /// Number of trailing matched characters to leave unmasked. When set,
        /// only the characters before the suffix are blocked out. Defaults to
        /// 0 (mask everything).
        #[serde(default)]
        keep_suffix: Option<usize>,
        /// Block color for this redaction as `#RRGGBB`. Defaults to the
        /// built-in red.
        #[serde(default)]
        color: Option<String>,
    },
    /// Redact an explicit cell range on a single row (0-based).
    ///
    /// Coordinates are validated against the screenshot before anything is
    /// drawn: a row at or past its last row, a column at or past its last
    /// column, or a `col_start` that is not before `col_end` is rejected with
    /// an error naming the screenshot's real dimensions.
    Coordinate {
        /// Row index (0-based), counted in the screenshot as rendered: row 0 is
        /// the topmost line the PNG shows, which for a `head_lines` /
        /// `tail_lines` capture is the first line of that selection. Must be
        /// less than the number of rows the screenshot shows.
        row: u16,
        /// First column to redact (0-based, inclusive). Must be less than both
        /// `col_end` and the screenshot's width.
        col_start: u16,
        /// One past the last column to redact (exclusive). Must be greater than
        /// `col_start` and no greater than the screenshot's width.
        col_end: u16,
        /// Short label drawn over the redaction block.
        #[serde(default)]
        label: Option<String>,
        /// Block color for this redaction as `#RRGGBB`. Defaults to the
        /// built-in red.
        #[serde(default)]
        color: Option<String>,
    },
}

/// Field names a `pattern` redaction accepts, used to reject typos with a
/// message that names the alternatives.
const PATTERN_FIELDS: &[&str] = &[
    "pattern",
    "replacement",
    "label",
    "keep_prefix",
    "keep_suffix",
    "color",
];
/// The pattern fields that must be present.
const PATTERN_REQUIRED: &[&str] = &["pattern"];
/// Field names a coordinate redaction accepts.
const COORDINATE_FIELDS: &[&str] = &["row", "col_start", "col_end", "label", "color"];
/// The coordinate fields that must all be present.
const COORDINATE_REQUIRED: &[&str] = &["row", "col_start", "col_end"];

/// Description published for the `pattern` variant.
const PATTERN_DESCRIPTION: &str = "Redact every match of a regex pattern. \
     `replacement` (also accepted as `label`) is drawn as the on-image \
     `[LABEL]` tag; omitting it draws a plain block with no text overlay.";
/// Description published for the coordinate variant.
const COORDINATE_DESCRIPTION: &str = "Redact an explicit cell range on a single row (0-based). Coordinates are \
     validated against the screenshot before anything is drawn: a row at or past \
     its last row, a column at or past its last column, or a `col_start` that is \
     not before `col_end` is rejected with an error naming the screenshot's real \
     dimensions.";

/// The JSON Schema of one accepted field, by name.
///
/// The published schema is generated from the very lists the parser validates
/// against ([`PATTERN_FIELDS`], [`COORDINATE_FIELDS`]), so a field this crate
/// accepts cannot go unpublished and a field it refuses cannot be advertised.
fn field_schema(name: &str, is_pattern: bool) -> serde_json::Value {
    match name {
        "pattern" => serde_json::json!({
            "type": "string",
            "description": "Regex pattern to match against the terminal text.",
        }),
        "replacement" => serde_json::json!({
            "type": ["string", "null"],
            "default": null,
            "description": "Replacement marker used to derive the on-image `[LABEL]` tag. \
                            May also be given as `label`. Omitted (or empty) draws a plain \
                            block with no text overlay.",
        }),
        "label" if is_pattern => serde_json::json!({
            "type": ["string", "null"],
            "default": null,
            "description": "Alias for `replacement`: the on-image `[LABEL]` tag for this \
                            pattern. Pass one or the other, not both.",
        }),
        "label" => serde_json::json!({
            "type": ["string", "null"],
            "default": null,
            "description": "Short label drawn over the redaction block. Defaults to \
                            `REDACTED`.",
        }),
        "keep_prefix" => serde_json::json!({
            "type": ["integer", "null"],
            "format": "uint",
            "minimum": 0,
            "default": null,
            "description": "Number of leading matched characters to leave unmasked. When \
                            set, only the characters after the prefix are blocked out (e.g. \
                            show `AKIA****` for an AWS key). Defaults to 0 (mask everything).",
        }),
        "keep_suffix" => serde_json::json!({
            "type": ["integer", "null"],
            "format": "uint",
            "minimum": 0,
            "default": null,
            "description": "Number of trailing matched characters to leave unmasked. When \
                            set, only the characters before the suffix are blocked out. \
                            Defaults to 0 (mask everything).",
        }),
        "color" => serde_json::json!({
            "type": ["string", "null"],
            "default": null,
            "description": "Block color for this redaction as `#RRGGBB`. Defaults to the \
                            built-in red.",
        }),
        "row" => serde_json::json!({
            "type": "integer",
            "format": "uint16",
            "minimum": 0,
            "maximum": 65535,
            "description": "Row index (0-based), counted in the screenshot as rendered: row \
                            0 is the topmost line the PNG shows, which for a `head_lines` / \
                            `tail_lines` capture is the first line of that selection. Must \
                            be less than the number of rows the screenshot shows.",
        }),
        "col_start" => serde_json::json!({
            "type": "integer",
            "format": "uint16",
            "minimum": 0,
            "maximum": 65535,
            "description": "First column to redact (0-based, inclusive). Must be less than \
                            both `col_end` and the screenshot's width.",
        }),
        "col_end" => serde_json::json!({
            "type": "integer",
            "format": "uint16",
            "minimum": 0,
            "maximum": 65535,
            "description": "One past the last column to redact (exclusive). Must be greater \
                            than `col_start` and no greater than the screenshot's width.",
        }),
        other => unreachable!("no schema for redaction field {:?}", other),
    }
}

/// Build the schema of one variant: exactly the fields it accepts, exactly the
/// ones it requires, and nothing else (`additionalProperties: false`, matching
/// the parser, which names unknown keys rather than ignoring them).
fn variant_schema(
    description: &str,
    fields: &[&str],
    required: &[&str],
    is_pattern: bool,
) -> serde_json::Value {
    let properties: serde_json::Map<String, serde_json::Value> = fields
        .iter()
        .map(|field| ((*field).to_string(), field_schema(field, is_pattern)))
        .collect();
    serde_json::json!({
        "type": "object",
        "description": description,
        "properties": properties,
        "required": required,
        "additionalProperties": false,
    })
}

/// The published JSON Schema for a manual redaction, as `tools/list` shows it.
///
/// Hand-written rather than derived: the derive had no way to know about the
/// `label` alias a pattern accepts, and it published an untagged `anyOf` whose
/// branches allowed any extra property - so the schema promised to accept
/// specifications [`ManualRedactionSpec::from_value`] refuses, and hid one it
/// takes. A tool schema that disagrees with the parser is worse than none: the
/// client is told the call will work and only finds out otherwise at run time.
///
/// The two branches are mutually exclusive (`oneOf`), matching how the parser
/// discriminates: an object with `pattern` is a pattern redaction, one with
/// `row`/`col_start`/`col_end` is a coordinate redaction, and one with keys
/// from both is refused by either branch's `additionalProperties: false`.
pub fn manual_redaction_schema() -> serde_json::Value {
    serde_json::json!({
        "description": "A single manual redaction: either a regex pattern (redacts every \
                        match) or an explicit cell range. The CLI's repeatable \
                        `--redaction '<JSON>'` option takes exactly the same specification.",
        "oneOf": [
            variant_schema(PATTERN_DESCRIPTION, PATTERN_FIELDS, PATTERN_REQUIRED, true),
            variant_schema(
                COORDINATE_DESCRIPTION,
                COORDINATE_FIELDS,
                COORDINATE_REQUIRED,
                false,
            ),
        ],
    })
}

impl schemars::JsonSchema for ManualRedactionSpec {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "ManualRedactionSpec".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        concat!(module_path!(), "::ManualRedactionSpec").into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::Schema::try_from(manual_redaction_schema())
            .expect("the manual redaction schema is a JSON object")
    }
}

/// The `pattern` variant's fields, used to decode one after the object has
/// been recognized as a pattern redaction.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PatternFields {
    pattern: String,
    #[serde(default, alias = "label")]
    replacement: Option<String>,
    #[serde(default)]
    keep_prefix: Option<usize>,
    #[serde(default)]
    keep_suffix: Option<usize>,
    #[serde(default)]
    color: Option<String>,
}

/// The coordinate variant's fields.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CoordinateFields {
    row: u16,
    col_start: u16,
    col_end: u16,
    #[serde(default)]
    label: Option<String>,
    #[serde(default)]
    color: Option<String>,
}

impl ManualRedactionSpec {
    /// Parse one `--redaction '<JSON>'` argument.
    pub fn from_json(input: &str) -> Result<Self> {
        let value: serde_json::Value = serde_json::from_str(input).map_err(|e| {
            anyhow::anyhow!(
                "invalid redaction JSON: {}. Expected an object such as \
                 '{{\"pattern\":\"[a-f0-9]{{32}}\",\"replacement\":\"HASH\",\"keep_prefix\":4}}' \
                 or '{{\"row\":3,\"col_start\":12,\"col_end\":44,\"label\":\"SECRET\"}}', got: {}",
                e,
                input
            )
        })?;
        Self::from_value(value).with_context(|| format!("in redaction: {}", input))
    }

    /// Decode one redaction from an already-parsed JSON value.
    ///
    /// This is the single decoder both entry points use: the CLI reaches it
    /// through [`ManualRedactionSpec::from_json`] and the MCP server through the
    /// `Deserialize` implementation below, so a specification that one accepts
    /// the other accepts, with the same message when it does not.
    ///
    /// Deserializing an untagged enum directly would answer a typo with "data
    /// did not match any variant", so the object is inspected first: the
    /// variant is chosen by the keys present, unknown keys are named alongside
    /// the ones that variant accepts, and only then is the value decoded.
    pub fn from_value(value: serde_json::Value) -> Result<Self> {
        let object = value.as_object().ok_or_else(|| {
            anyhow::anyhow!(
                "a redaction must be a JSON object with either a \"pattern\" or \
                 \"row\"/\"col_start\"/\"col_end\""
            )
        })?;

        let is_pattern = object.contains_key("pattern");
        let allowed = if is_pattern {
            PATTERN_FIELDS
        } else if COORDINATE_REQUIRED
            .iter()
            .any(|field| object.contains_key(*field))
        {
            for field in COORDINATE_REQUIRED {
                if !object.contains_key(*field) {
                    anyhow::bail!(
                        "a coordinate redaction needs \"row\", \"col_start\" and \"col_end\"; \
                         \"{}\" is missing",
                        field
                    );
                }
            }
            COORDINATE_FIELDS
        } else {
            anyhow::bail!(
                "a redaction needs either a \"pattern\" or \"row\"/\"col_start\"/\"col_end\""
            );
        };

        let unknown: Vec<&str> = object
            .keys()
            .map(String::as_str)
            .filter(|key| !allowed.contains(key))
            .collect();
        if !unknown.is_empty() {
            anyhow::bail!(
                "unknown field(s) {} in redaction; this redaction accepts: {}",
                unknown.join(", "),
                allowed.join(", ")
            );
        }

        if is_pattern {
            let fields: PatternFields =
                serde_json::from_value(value).context("invalid pattern redaction")?;
            Ok(Self::Pattern {
                pattern: fields.pattern,
                replacement: fields.replacement,
                keep_prefix: fields.keep_prefix,
                keep_suffix: fields.keep_suffix,
                color: fields.color,
            })
        } else {
            let fields: CoordinateFields =
                serde_json::from_value(value).context("invalid coordinate redaction")?;
            Ok(Self::Coordinate {
                row: fields.row,
                col_start: fields.col_start,
                col_end: fields.col_end,
                label: fields.label,
                color: fields.color,
            })
        }
    }

    /// Parse every `--redaction` argument, in the order they were given.
    pub fn parse_all<S: AsRef<str>>(inputs: &[S]) -> Result<Vec<Self>> {
        inputs
            .iter()
            .enumerate()
            .map(|(i, input)| {
                Self::from_json(input.as_ref()).with_context(|| format!("--redaction #{}", i + 1))
            })
            .collect()
    }
}

/// Hand-written so an MCP `redact_screenshot` request is decoded by exactly the
/// same rules as a CLI `--redaction` argument: same accepted fields, same
/// `label` alias, same rejection of typos, and the same messages.
impl<'de> Deserialize<'de> for ManualRedactionSpec {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        Self::from_value(value).map_err(serde::de::Error::custom)
    }
}

/// One resolved [`ManualRedactionSpec::Coordinate`], with its color already parsed.
#[derive(Debug, Clone)]
pub struct CoordinateRedaction {
    pub row: u16,
    pub col_start: u16,
    pub col_end: u16,
    pub label: Option<String>,
    pub block_color: [u8; 3],
}

/// A validated set of manual redactions, ready to apply to a capture.
///
/// Built once from [`ManualRedactionSpec`]s (compiling every pattern and parsing
/// every color, so bad input fails before a command is run or an image is
/// written), then applied to the screen the renderer is about to draw. The CLI
/// and the MCP server both go through this type, so a given JSON specification
/// produces the same blocks, the same labels, and the same audit counts from
/// either entry point.
#[derive(Debug)]
pub struct ManualRedactions {
    /// Engine holding the caller's `pattern` specs, in order, named
    /// `custom_0`, `custom_1`, ... - the names the audit reports.
    engine: Option<RedactionEngine>,
    coordinates: Vec<CoordinateRedaction>,
    show_labels: bool,
}

impl ManualRedactions {
    /// Compile `specs` into an applicable set, rejecting an invalid regex, an
    /// unparseable color, or an empty coordinate range up front.
    ///
    /// `show_labels` mirrors the MCP `show_labels` parameter: when false every
    /// block is drawn plain, with no text overlay.
    pub fn new(specs: &[ManualRedactionSpec], show_labels: bool) -> Result<Self> {
        let mut pattern_rules: Vec<RedactionRuleConfig> = Vec::new();
        let mut coordinates: Vec<CoordinateRedaction> = Vec::new();

        for (i, spec) in specs.iter().enumerate() {
            match spec {
                ManualRedactionSpec::Pattern {
                    pattern,
                    replacement,
                    keep_prefix,
                    keep_suffix,
                    color,
                } => {
                    if pattern.is_empty() {
                        anyhow::bail!("redaction #{}: \"pattern\" must not be empty", i + 1);
                    }
                    Regex::new(pattern).with_context(|| {
                        format!("redaction #{}: invalid regex {:?}", i + 1, pattern)
                    })?;
                    // Use the caller-supplied `replacement` as the on-image
                    // label. When it is omitted, leave it empty so the block
                    // renders with no label (never a misleading built-in tag).
                    let replacement = replacement.clone().unwrap_or_default();
                    let mut rule =
                        RedactionRuleConfig::new(&format!("custom_{}", i), pattern, &replacement);
                    rule.keep_prefix = *keep_prefix;
                    rule.keep_suffix = *keep_suffix;
                    if let Some(color) = color {
                        parse_color(color, i)?;
                        rule.color = Some(color.clone());
                    }
                    pattern_rules.push(rule);
                }
                ManualRedactionSpec::Coordinate {
                    row,
                    col_start,
                    col_end,
                    label,
                    color,
                } => {
                    let block_color = match color {
                        Some(color) => parse_color(color, i)?,
                        None => DEFAULT_BLOCK_COLOR,
                    };
                    coordinates.push(CoordinateRedaction {
                        row: *row,
                        col_start: *col_start,
                        col_end: *col_end,
                        label: label.clone(),
                        block_color,
                    });
                }
            }
        }

        let engine = if pattern_rules.is_empty() {
            None
        } else {
            Some(RedactionEngine::from_rules_with_labels(
                &pattern_rules,
                show_labels,
            )?)
        };

        Ok(Self {
            engine,
            coordinates,
            show_labels,
        })
    }

    /// True when there is nothing to apply.
    pub fn is_empty(&self) -> bool {
        self.engine.is_none() && self.coordinates.is_empty()
    }

    /// The coordinate redactions, in the order they were given.
    pub fn coordinates(&self) -> &[CoordinateRedaction] {
        &self.coordinates
    }

    /// Check every coordinate range against the cells a render actually paints.
    ///
    /// A coordinate redaction is a promise to cover specific cells, so a range
    /// that lands outside the image must fail loudly: silently clamping it (or
    /// dropping it, as the redaction map does for an empty interval) would
    /// report "redacted" for a screenshot where the secret is still legible.
    /// The bounds are the *rendered* ones - the retained capture, narrowed to
    /// the head/tail selection it is drawn with, then to the rows and columns
    /// that survive trailing-blank trimming and `auto_crop` - not the PTY
    /// viewport and not the raw grid.
    ///
    /// This applies to manual coordinates only. Pattern redactions are matched
    /// against the capture itself, so a match on the rightmost content cell (or
    /// the continuation cell of a double-width character) is masked as usual:
    /// wherever text is drawn, the renderer is already inside these bounds.
    pub fn validate_bounds(&self, rendered_rows: u16, rendered_cols: u16) -> Result<()> {
        for coordinate in &self.coordinates {
            let CoordinateRedaction {
                row,
                col_start,
                col_end,
                ..
            } = *coordinate;
            let invalid = |detail: String| -> Result<()> {
                anyhow::bail!(
                    "invalid redaction coordinate (row {}, col_start {}, col_end {}): {}. \
                     The screenshot renders {} row(s) x {} column(s); rows are 0..{} and \
                     columns are 0..{} (col_end is exclusive). Cells outside that are \
                     retained by the capture but never drawn, so redacting them would \
                     change nothing.",
                    row,
                    col_start,
                    col_end,
                    detail,
                    rendered_rows,
                    rendered_cols,
                    rendered_rows,
                    rendered_cols
                )
            };
            if row >= rendered_rows {
                return invalid(format!("row {} is past the last rendered row", row));
            }
            if col_start >= col_end {
                return invalid(format!(
                    "col_start {} is not before col_end {}, so the range is empty",
                    col_start, col_end
                ));
            }
            if col_start >= rendered_cols {
                return invalid(format!(
                    "col_start {} is past the last rendered column",
                    col_start
                ));
            }
            if col_end > rendered_cols {
                return invalid(format!(
                    "col_end {} is past the last rendered column boundary",
                    col_end
                ));
            }
        }
        Ok(())
    }

    /// Apply these redactions to `screen`, merging them into `map`: pattern
    /// matches first (in the order the specs were given), then the coordinate
    /// ranges. Call [`ManualRedactions::validate_bounds`] first.
    pub fn apply_to<S: ScreenView + ?Sized>(&self, screen: &S, map: &mut RedactionMap) {
        if let Some(engine) = &self.engine {
            // Matched on the capture the renderer will draw, so a match found
            // here masks the cell it draws - including rows that scrolled out
            // of the viewport.
            engine.redact_screen_into(screen, None, map);
        }
        for coordinate in &self.coordinates {
            let label = if self.show_labels {
                coordinate.label.as_deref().or(Some("REDACTED"))
            } else {
                None
            };
            map.add_manual_with_color(
                coordinate.row,
                coordinate.col_start,
                coordinate.col_end,
                label,
                coordinate.block_color,
                DEFAULT_LABEL_COLOR,
            );
        }
    }
}

/// Parse a per-redaction `#RRGGBB` color, naming the offending redaction.
fn parse_color(color: &str, index: usize) -> Result<[u8; 3]> {
    parse_hex_rgb(color).ok_or_else(|| {
        anyhow::anyhow!(
            "redaction #{}: invalid color {:?}; expected a hex color such as \"#d41919\"",
            index + 1,
            color
        )
    })
}

/// Short visual label for a rule, used inside the redaction block.
/// Derive the on-image label for a rule, or `None` when the rule should render
/// as a plain solid block with no text overlay.
///
/// Built-in rules map to a short fixed tag (`ipv4` -> `IP`, ...). For any other
/// rule the label is derived from its `replacement` text (e.g.
/// `[REDACTED-TICKET]` -> `TICKET`), falling back to the rule name when the
/// replacement carries no usable text. An *empty* replacement means the caller
/// explicitly wants no label (used by ad-hoc `redact_screenshot` patterns that
/// omit `replacement`), so it returns `None`.
fn label_for(name: &str, replacement: &str) -> Option<String> {
    // An empty replacement is an explicit "no label" request.
    if replacement.is_empty() {
        return None;
    }

    let builtin = match name {
        "ipv4" | "ipv6" => Some("IP"),
        "mac" => Some("MAC"),
        "aws_key" | "aws_secret" | "api_key" => Some("KEY"),
        "private_key" => Some("KEY"),
        "jwt" => Some("JWT"),
        "email" => Some("EMAIL"),
        "hostname" => Some("HOST"),
        _ => None,
    };
    if let Some(l) = builtin {
        return Some(l.to_string());
    }

    // Derive a compact label from the replacement text, e.g.
    // "[REDACTED-IP]" -> "IP", falling back to the rule name.
    let cleaned: String = replacement
        .trim_matches(|c| c == '[' || c == ']')
        .replace("REDACTED", "")
        .trim_matches(|c: char| c == '-' || c == '_' || c.is_whitespace())
        .to_uppercase();
    let base = if cleaned.is_empty() {
        name.to_uppercase()
    } else {
        cleaned
    };
    Some(base.chars().take(6).collect())
}

/// Optional per-match skip predicate for a builtin rule.
fn builtin_skip(name: &str) -> Option<fn(&str) -> bool> {
    match name {
        "ipv4" => Some(is_ignorable_ipv4),
        "ipv6" => Some(is_ignorable_ipv6),
        _ => None,
    }
}

/// Keep obviously non-sensitive IPv4 addresses visible: `0.0.0.0`, the
/// loopback range `127.0.0.0/8`, and the broadcast address.
fn is_ignorable_ipv4(s: &str) -> bool {
    let octets: Vec<&str> = s.split('.').collect();
    if octets.len() != 4 {
        return false;
    }
    match s {
        "0.0.0.0" | "255.255.255.255" => return true,
        _ => {}
    }
    octets[0] == "127"
}

/// Reject IPv6 look-alikes so ordinary source code is never masked.
///
/// A candidate is ignored unless it parses as a real address, and even then
/// short compressed forms such as `d::f` (which `std::fs::read` contains) are
/// dropped: a genuine address carries at least four hex digits and either a
/// group of three or more digits or four or more groups. Loopback (`::1`) and
/// the unspecified address (`::`) are always kept visible, mirroring the IPv4
/// rule.
fn is_ignorable_ipv6(s: &str) -> bool {
    let addr: std::net::Ipv6Addr = match s.parse() {
        Ok(a) => a,
        Err(_) => return true,
    };
    if addr.is_loopback() || addr.is_unspecified() {
        return true;
    }
    let hex_digits = s.chars().filter(|c| c.is_ascii_hexdigit()).count();
    let groups: Vec<&str> = s.split(':').filter(|g| !g.is_empty()).collect();
    let longest = groups.iter().map(|g| g.len()).max().unwrap_or(0);
    hex_digits < 4 || (longest < 3 && groups.len() < 4)
}

/// The compiled-in default rule set. Users can override any of these by name in
/// their config (including disabling one via `enabled = false`).
///
// Built-in redaction rules. Patterns sourced from and inspired by:
// - Betterleaks (MIT) - https://github.com/betterleaks/betterleaks
// Additional patterns are original to this project.
fn builtin_rules() -> Vec<RedactionRuleConfig> {
    let r = |name: &str, pattern: &str, replacement: &str| {
        RedactionRuleConfig::new(name, pattern, replacement)
    };

    vec![
        // Context-guarded IPv4: the address must not be embedded in a longer
        // dotted/alphanumeric token, and a trailing `-<letter>` (as in
        // `1.2.3.4-beta`) marks a version string, not an address. Only the
        // `redact` group is masked; the surrounding context is left alone.
        r(
            "ipv4",
            r"(?:^|[^0-9A-Za-z.])(?P<redact>(?:(?:25[0-5]|2[0-4]\d|1?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1?\d\d?))(?:$|[^0-9A-Za-z.\-]|-(?:[^A-Za-z]|$))",
            "[REDACTED-IP]",
        ),
        // IPv6 is deliberately conservative: the loose alternation this rule
        // used to carry matched `::` inside ordinary code (`std::fs::read`,
        // `Error::new`). Matches must now be bounded by non-alphanumeric
        // context and additionally survive `is_ignorable_ipv6`, which parses
        // them as real addresses and rejects code-like look-alikes.
        r(
            "ipv6",
            r"(?i)(?:^|[^0-9A-Za-z:.])(?P<redact>::ffff:(?:\d{1,3}\.){3}\d{1,3}|(?:[0-9a-f]{1,4}:){2,7}[0-9a-f]{1,4}|(?:[0-9a-f]{1,4}:){1,7}:(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,6})?|::(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,7})?)(?:$|[^0-9A-Za-z:])",
            "[REDACTED-IPv6]",
        ),
        r(
            "mac",
            r"\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b",
            "[REDACTED-MAC]",
        ),
        r(
            "aws_key",
            r"\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA)[0-9A-Z]{16}\b",
            "[REDACTED-KEY]",
        ),
        r(
            "aws_secret",
            r#"(?i)(?:aws_secret_access_key|aws_secret)\s*[:=]\s*['"]?(?P<redact>[A-Za-z0-9/+=]{40})['"]?"#,
            "[REDACTED-KEY]",
        ),
        // PEM armor only. This rule used to carry an `[A-Za-z0-9+/]{60,}`
        // catch-all that masked any long alphanumeric run - hashes, git object
        // IDs, base64 fixtures, minified output - which made normal developer
        // screenshots unreadable.
        r(
            "private_key",
            r"-----(?:BEGIN|END)[A-Z0-9 ]*PRIVATE KEY-----",
            "[REDACTED-KEY]",
        ),
        r(
            "jwt",
            r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b",
            "[REDACTED-JWT]",
        ),
        r(
            "email",
            r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b",
            "[REDACTED-EMAIL]",
        ),
        r(
            "hostname",
            r"\b(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+(?:internal|local|corp|lan|intranet)\b",
            "[REDACTED-HOST]",
        ),
        // A `:` or `=` is required between the key name and the value: without
        // it, prose such as "rotate the api key regularly afterwards" matched.
        r(
            "api_key",
            r#"(?i)(?:api[_-]?key|apikey|access[_-]?token|secret[_-]?key|auth[_-]?token|bearer)\s*[:=]\s*['"]?(?P<redact>[A-Za-z0-9_\-\.]{16,})"#,
            "[REDACTED-KEY]",
        ),
        // --- Additional provider tokens (sourced from / inspired by Betterleaks, MIT) ---
        r(
            "github_token",
            r"\b(?:gh[opsu]_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{82})\b",
            "[REDACTED-TOKEN]",
        ),
        r(
            "slack_token",
            r"\bxox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[A-Za-z0-9]{24,34}\b",
            "[REDACTED-TOKEN]",
        ),
        r(
            "private_key_pem",
            r"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----",
            "[REDACTED-KEY]",
        ),
        r(
            "gcp_service_account",
            r#"(?i)"type"\s*:\s*"service_account""#,
            "[REDACTED-KEY]",
        ),
        r(
            "azure_client_secret",
            r"\b[A-Za-z0-9_~.]{3}[0-9]Q~[A-Za-z0-9_~.\-]{31,34}\b",
            "[REDACTED-SECRET]",
        ),
        r(
            "generic_api_key",
            r#"(?i)(?:api[_-]?key|apikey)\s*[:=]\s*['"]?(?P<redact>[A-Za-z0-9_\-]{20,})"#,
            "[REDACTED-KEY]",
        ),
        r(
            "bearer_token",
            r#"(?i)(?:bearer|authorization)\s*[:=]\s*['"]?(?P<redact>[A-Za-z0-9_\-.]{20,})"#,
            "[REDACTED-TOKEN]",
        ),
        r(
            "connection_string",
            r#"(?i)(?:connection.?string|conn.?str)\s*[:=]\s*['"]?(?P<redact>[^'";\s]{20,})"#,
            "[REDACTED-SECRET]",
        ),
        r(
            "discord_token",
            r"\b[MN][A-Za-z0-9]{23,}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}",
            "[REDACTED-TOKEN]",
        ),
        r(
            "hashicorp_vault_token",
            r"\bhvs\.[A-Za-z0-9]{24,}",
            "[REDACTED-TOKEN]",
        ),
    ]
}

/// Parse a `#RRGGBB` (or `RRGGBB`) hex string into an RGB triple.
pub fn parse_hex_rgb(hex: &str) -> Option<[u8; 3]> {
    let hex = hex.trim().trim_start_matches('#');
    // Check for ASCII hex digits before slicing: a six-*byte* string that
    // contains a multi-byte character would otherwise panic on a non-char
    // boundary.
    if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
    let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
    let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
    Some([r, g, b])
}

/// Shannon entropy of a string in bits per character.
fn shannon_entropy(s: &str) -> f64 {
    if s.is_empty() {
        return 0.0;
    }
    let mut counts: HashMap<char, usize> = HashMap::new();
    let mut total = 0usize;
    for ch in s.chars() {
        *counts.entry(ch).or_insert(0) += 1;
        total += 1;
    }
    let total = total as f64;
    -counts
        .values()
        .map(|&c| {
            let p = c as f64 / total;
            p * p.log2()
        })
        .sum::<f64>()
}

/// A single rule as declared in a YAML rule file. Only the
/// fields we map are captured; unknown fields are ignored.
#[derive(Debug, Clone, Deserialize)]
struct YamlRule {
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    pattern: Option<String>,
    #[serde(default)]
    regex: Option<String>,
    #[serde(default)]
    min_entropy: Option<f64>,
    #[serde(default)]
    confidence: Option<String>,
}

/// Top-level YAML rule document (`rules:` list).
#[derive(Debug, Clone, Deserialize)]
struct YamlRulesFile {
    #[serde(default)]
    rules: Vec<YamlRule>,
}

/// A `.toml` rule file: either a bare list of `[[rules]]` or a single rule.
#[derive(Debug, Clone, Deserialize)]
struct TomlRulesFile {
    #[serde(default)]
    rules: Vec<RedactionRuleConfig>,
}

impl YamlRule {
    /// Convert a YAML rule into our internal rule format. Returns `None`
    /// when the rule has no usable name/id or pattern.
    fn into_rule(self) -> Option<RedactionRuleConfig> {
        let name = self
            .name
            .clone()
            .or_else(|| self.id.clone())
            .filter(|n| !n.is_empty())?;
        let pattern = self.pattern.or(self.regex).filter(|p| !p.is_empty())?;
        // Map confidence to enabled: only an explicit "false"/"disabled"
        // confidence disables the rule; everything else stays enabled.
        let enabled = !matches!(
            self.confidence
                .as_deref()
                .map(str::to_ascii_lowercase)
                .as_deref(),
            Some("false") | Some("disabled") | Some("off")
        );
        Some(RedactionRuleConfig {
            name,
            pattern,
            replacement: default_replacement(),
            enabled,
            color: None,
            min_entropy: self.min_entropy,
            keep_prefix: None,
            keep_suffix: None,
        })
    }
}

/// Load extra redaction rules from a directory of `.toml` and `.yaml`/`.yml`
/// files. TOML files use our native rule format (`[[rules]]`); YAML files use
/// the generic YAML rule format (`rules:` list). Malformed files are logged and
/// skipped rather than failing the whole load.
pub fn load_rules_from_dir(dir: &std::path::Path) -> Vec<RedactionRuleConfig> {
    let mut out = Vec::new();
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(e) => {
            tracing::warn!("Failed to read rules dir {:?}: {}", dir, e);
            return out;
        }
    };
    let mut paths: Vec<std::path::PathBuf> =
        entries.filter_map(|e| e.ok().map(|e| e.path())).collect();
    paths.sort();
    for path in paths {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(str::to_ascii_lowercase);
        let contents = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!("Failed to read rules file {:?}: {}", path, e);
                continue;
            }
        };
        match ext.as_deref() {
            Some("toml") => match toml::from_str::<TomlRulesFile>(&contents) {
                Ok(f) => out.extend(f.rules),
                Err(e) => tracing::warn!("Failed to parse TOML rules {:?}: {}", path, e),
            },
            Some("yaml") | Some("yml") => {
                match serde_yaml_ng::from_str::<YamlRulesFile>(&contents) {
                    Ok(f) => out.extend(f.rules.into_iter().filter_map(YamlRule::into_rule)),
                    Err(e) => tracing::warn!("Failed to parse YAML rules {:?}: {}", path, e),
                }
            }
            _ => {}
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::capture::{CapturedScreen, DEFAULT_MAX_SCROLLBACK_LINES};
    use std::collections::BTreeSet;

    fn engine() -> RedactionEngine {
        RedactionEngine::from_config(&RedactionConfig::default()).unwrap()
    }

    /// Parse text into a capture so rules can be exercised end to end.
    fn screen_of(text: &str, cols: u16, rows: u16) -> CapturedScreen {
        CapturedScreen::parse(text.as_bytes(), rows, cols, DEFAULT_MAX_SCROLLBACK_LINES)
    }

    fn redact(text: &str) -> RedactionMap {
        let parser = screen_of(text, 120, 10);
        engine().redact_screen(&parser, None)
    }

    fn count_of(map: &RedactionMap, name: &str) -> usize {
        map.counts
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, c)| *c)
            .unwrap_or(0)
    }

    #[test]
    fn ipv4_matches_real_addresses() {
        let map = redact("host is 192.168.1.42 online");
        assert_eq!(count_of(&map, "ipv4"), 1);
    }

    #[test]
    fn ipv4_ignores_loopback_and_unspecified() {
        assert_eq!(count_of(&redact("localhost 127.0.0.1"), "ipv4"), 0);
        assert_eq!(count_of(&redact("bind 0.0.0.0:8080"), "ipv4"), 0);
        assert_eq!(count_of(&redact("bcast 255.255.255.255"), "ipv4"), 0);
    }

    #[test]
    fn ipv4_rejects_out_of_range_octets() {
        assert_eq!(count_of(&redact("version 999.999.1.1 here"), "ipv4"), 0);
    }

    #[test]
    fn ipv6_matches() {
        let map = redact("addr 2001:0db8:85a3:0000:0000:8a2e:0370:7334 up");
        assert!(count_of(&map, "ipv6") >= 1);
    }

    #[test]
    fn mac_matches_both_separators() {
        assert_eq!(count_of(&redact("mac 00:1a:2b:3c:4d:5e"), "mac"), 1);
        assert_eq!(count_of(&redact("mac 00-1A-2B-3C-4D-5E"), "mac"), 1);
    }

    #[test]
    fn aws_key_matches() {
        let map = redact("key AKIAIOSFODNN7EXAMPLE end");
        assert_eq!(count_of(&map, "aws_key"), 1);
    }

    #[test]
    fn aws_secret_matches_in_context() {
        let input = "AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
        let parser = screen_of(input, 120, 3);
        let map = engine().redact_screen(&parser, None);
        assert_eq!(count_of(&map, "aws_secret"), 1);
        let text = map.redacted_plain_text(&parser);
        assert!(text.contains("AWS_SECRET_ACCESS_KEY="));
        assert!(!text.contains("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"));
    }

    #[test]
    fn contextual_rules_preserve_key_names() {
        let input = concat!(
            "API_KEY=abcdefghijklmnopqrstuvwx\n",
            "Authorization=abcdefghijklmnopqrstuvwxyz012345\n",
            "CONNECTION_STRING=postgresql://user:secret@db.example/app"
        );
        let parser = screen_of(input, 120, 5);
        let map = engine().redact_screen(&parser, None);
        let text = map.redacted_plain_text(&parser);
        assert!(text.contains("API_KEY="));
        assert!(text.contains("Authorization="));
        assert!(text.contains("CONNECTION_STRING="));
        assert!(!text.contains("abcdefghijklmnopqrstuvwx"));
        assert!(!text.contains("abcdefghijklmnopqrstuvwxyz012345"));
        assert!(!text.contains("postgresql://user:secret@db.example/app"));
    }

    #[test]
    fn jwt_matches() {
        let jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N";
        let map = redact(&format!("token {}", jwt));
        assert_eq!(count_of(&map, "jwt"), 1);
    }

    #[test]
    fn private_key_marker_matches() {
        let map = redact("-----BEGIN RSA PRIVATE KEY-----");
        assert_eq!(count_of(&map, "private_key"), 1);
    }

    #[test]
    fn email_matches() {
        let map = redact("contact admin@example.com now");
        assert_eq!(count_of(&map, "email"), 1);
    }

    #[test]
    fn hostname_matches_internal_domains() {
        assert_eq!(count_of(&redact("ssh db01.internal"), "hostname"), 1);
        assert_eq!(count_of(&redact("ping fileserver.corp"), "hostname"), 1);
    }

    #[test]
    fn api_key_matches() {
        let map = redact("api_key=abcdef0123456789ABCDEF");
        assert_eq!(count_of(&map, "api_key"), 1);
    }

    #[test]
    fn plain_prose_is_not_redacted() {
        let map = redact("the quick brown fox jumps over the lazy dog");
        assert!(map.is_empty(), "unexpected redactions: {:?}", map.counts);
    }

    /// Realistic non-secret developer output must survive untouched: a false
    /// positive silently corrupts the screenshot people came for. Every line
    /// here was mangled by an earlier version of the rules.
    #[test]
    fn ordinary_developer_output_is_not_redacted() {
        let corpus = [
            "use std::fs::read;",
            "let path = std::path::PathBuf::from(\"/tmp/x\");",
            "std::cout << x << std::endl;",
            "Error::new(ErrorKind::Other, \"boom\")",
            "impl fmt::Display for Config {",
            "Foo::bar::baz(&mut self)",
            "termshot v1.2.3.4-beta released",
            "running 66 tests in 0.41s",
            "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
            "-rw-rw-r-- 1 adam adam 56917 Aug 25 13:07 Cargo.lock",
            "commit 25eabf1a9c4f1e0b7d5c3a2f8e6d4b0c9a7f5e31",
            "aGVsbG8gd29ybGQgdGhpcyBpcyBhIGxvbmcgYmFzZTY0IHN0cmluZyBmb3IgdGVzdGluZw==",
            "12:34:56 INFO server started",
            "Compiling termshot v0.1.0 (/home/adam/Desktop/termshot)",
            "rotate the api key regularly and store it somewhere safe",
        ];
        for line in corpus {
            let map = redact(line);
            assert!(
                map.is_empty(),
                "false positive on {:?}: {:?}",
                line,
                map.counts
            );
        }
    }

    /// The tightened IPv6 rule must still catch real addresses.
    #[test]
    fn ipv6_addresses_are_still_redacted() {
        for addr in [
            "inet6 fe80::1cb2:ff:fe00:1/64",
            "connecting to [2001:db8::1]:443",
            "addr 2001:0db8:85a3:0000:0000:8a2e:0370:7334 up",
            "peer fd00:1234:5678::abcd",
        ] {
            let map = redact(addr);
            assert!(count_of(&map, "ipv6") >= 1, "missed IPv6 in {:?}", addr);
        }
    }

    #[test]
    fn ipv6_ignores_loopback_and_unspecified() {
        assert_eq!(count_of(&redact("listening on ::1 port 80"), "ipv6"), 0);
        assert_eq!(count_of(&redact("bind :: port 80"), "ipv6"), 0);
    }

    /// A secret split across a soft line wrap must still be masked: it is
    /// exactly the long tokens (keys, JWTs) that wrap.
    #[test]
    fn wrapped_secret_is_redacted_across_rows() {
        // 24 columns forces "AKIAIOSFODNN7EXAMPLE" to straddle two rows.
        let parser = screen_of("token: AKIAIOSFODNN7EXAMPLE done", 24, 6);
        let map = engine().redact_screen(&parser, None);
        assert_eq!(count_of(&map, "aws_key"), 1, "wrapped key missed");

        let rows: Vec<u16> = (0..6)
            .filter(|&row| (0..24).any(|col| map.get(row, col).is_some()))
            .collect();
        assert!(
            rows.len() >= 2,
            "expected redaction on both wrapped rows, got {:?}",
            rows
        );
        assert!(!map.redacted_plain_text(&parser).contains("AKIA"));
    }

    /// Only *soft* wraps are joined. Two hard-separated lines whose text would
    /// form a match when concatenated must stay unmatched: joining them would
    /// scatter phantom redactions across ordinary output.
    #[test]
    fn hard_newlines_are_not_joined_into_a_match() {
        let rule = RedactionRuleConfig::new("hash", "[a-f0-9]{32}", "HASH");
        let engine = RedactionEngine::from_rules(&[rule]).unwrap();
        // Each half fits well inside the row, so neither line wrapped.
        let parser = screen_of("8846f7eaee8fb117ad06\r\nbdd830b7586c\r\n", 60, 6);
        let map = engine.redact_screen(&parser, None);
        assert!(
            map.is_empty(),
            "hard-separated lines were joined into a match: {}",
            map.audit_summary()
        );
    }

    /// The same two halves *are* one value when the terminal itself wrapped
    /// them, which is the case the join exists for.
    #[test]
    fn soft_wrapped_halves_are_joined_into_a_match() {
        let rule = RedactionRuleConfig::new("hash", "[a-f0-9]{32}", "HASH");
        let engine = RedactionEngine::from_rules(&[rule]).unwrap();
        // 20 columns splits the 32-character hash across two rows.
        let parser = screen_of("8846f7eaee8fb117ad06bdd830b7586c\r\n", 20, 6);
        let map = engine.redact_screen(&parser, None);
        assert_eq!(count_of(&map, "hash"), 1, "wrapped hash missed");
        assert!(map.get(0, 19).is_some(), "first row not masked");
        assert!(map.get(1, 0).is_some(), "second row not masked");
    }

    /// A `redact` capture group lets a rule require context without masking
    /// it: only the group's span is blocked out.
    #[test]
    fn only_the_redact_group_is_masked() {
        // "ip 10.0.0.9" -> the leading space is context, not part of the match.
        let parser = screen_of("ip 10.0.0.9!", 120, 3);
        let map = engine().redact_screen(&parser, None);
        assert!(map.get(0, 2).is_none(), "context space was masked");
        assert!(map.get(0, 3).is_some(), "address start not masked");
        assert!(map.get(0, 10).is_some(), "address end not masked");
        assert!(map.get(0, 11).is_none(), "trailing context was masked");
    }

    #[test]
    fn parse_hex_rgb_rejects_non_ascii() {
        // Six *bytes* but not six chars: must not panic on a slice boundary.
        assert_eq!(parse_hex_rgb("#abc\u{20ac}"), None);
        assert_eq!(parse_hex_rgb("#d41919"), Some([212, 25, 25]));
    }

    #[test]
    fn map_marks_correct_columns() {
        // "ip 10.0.0.9" -> address starts at column 3.
        let parser = screen_of("ip 10.0.0.9", 120, 3);
        let map = engine().redact_screen(&parser, None);
        assert!(map.get(0, 2).is_none()); // the space before
        for col in 3..11 {
            assert!(
                map.get(0, col).is_some(),
                "column {} should be redacted",
                col
            );
        }
    }

    #[test]
    fn keep_prefix_and_suffix_leave_edges_unmasked() {
        // A 32-char hash starting at column 3; keep first 4 visible.
        let mut rule = RedactionRuleConfig::new("hash", "[a-f0-9]{32}", "HASH");
        rule.keep_prefix = Some(4);
        let engine = RedactionEngine::from_rules(&[rule]).unwrap();
        let hash = "8846f7eaee8fb117ad06bdd830b7586c";
        let parser = screen_of(&format!("h: {}", hash), 120, 3);
        let map = engine.redact_screen(&parser, None);
        // Columns 3..7 (the first 4 hash chars) stay visible.
        for col in 3..7 {
            assert!(map.get(0, col).is_none(), "prefix col {} redacted", col);
        }
        // The remaining 28 columns (7..35) are masked.
        for col in 7..35 {
            assert!(map.get(0, col).is_some(), "col {} not redacted", col);
        }
    }

    #[test]
    fn keep_prefix_covering_whole_match_redacts_nothing() {
        let mut rule = RedactionRuleConfig::new("word", "[a-z]{4}", "W");
        rule.keep_prefix = Some(4);
        let engine = RedactionEngine::from_rules(&[rule]).unwrap();
        let parser = screen_of("abcd", 120, 3);
        let map = engine.redact_screen(&parser, None);
        assert!(map.is_empty(), "nothing should be redacted");
    }

    #[test]
    fn keep_suffix_leaves_trailing_chars_unmasked() {
        let mut rule = RedactionRuleConfig::new("digits", "[0-9]{6}", "N");
        rule.keep_suffix = Some(2);
        let engine = RedactionEngine::from_rules(&[rule]).unwrap();
        let parser = screen_of("123456", 120, 3);
        let map = engine.redact_screen(&parser, None);
        // First 4 masked, last 2 visible.
        for col in 0..4 {
            assert!(map.get(0, col).is_some(), "col {} not redacted", col);
        }
        for col in 4..6 {
            assert!(map.get(0, col).is_none(), "suffix col {} redacted", col);
        }
    }

    #[test]
    fn label_is_placed_over_block() {
        let parser = screen_of("ip 10.11.12.13 up", 120, 3);
        let map = engine().redact_screen(&parser, None);
        // "10.11.12.13" spans 11 columns starting at 3, so "[IP]" fits.
        let tag: String = (3..7)
            .filter_map(|c| map.get(0, c).and_then(|rc| rc.label_char))
            .collect();
        assert_eq!(tag, "[IP]");
    }

    #[test]
    fn only_filter_limits_rules() {
        let parser = screen_of("192.168.0.1 admin@example.com", 120, 3);
        let only = vec!["ipv4".to_string()];
        let map = engine().redact_screen(&parser, Some(&only));
        assert_eq!(count_of(&map, "ipv4"), 1);
        assert_eq!(count_of(&map, "email"), 0);
    }

    #[test]
    fn validate_rule_names_rejects_unknown() {
        let engine = engine();
        assert!(engine.validate_rule_names(&["ipv4".to_string()]).is_ok());
        let err = engine
            .validate_rule_names(&["ipv4".to_string(), "not_a_rule".to_string()])
            .unwrap_err()
            .to_string();
        assert!(err.contains("not_a_rule"), "error was: {}", err);
    }

    #[test]
    fn redacted_plain_text_hides_value() {
        let parser = screen_of("secret 203.0.113.7 host", 120, 3);
        let map = engine().redact_screen(&parser, None);
        let text = map.redacted_plain_text(&parser);
        assert!(!text.contains("203.0.113.7"), "text still leaks: {}", text);
        assert!(text.contains('\u{2588}'));
    }

    #[test]
    fn resolve_should_redact_logic() {
        let mut cfg = RedactionConfig {
            enabled: false,
            auto: false,
            ..Default::default()
        };
        // `enabled = false` is the master switch: nothing runs, and an
        // explicit request is reported as blocked instead of silently ignored.
        assert!(!resolve_should_redact(&cfg, false, false));
        assert!(!resolve_should_redact(&cfg, true, false));
        assert!(explicit_request_is_blocked(&cfg, true, false));
        assert!(!explicit_request_is_blocked(&cfg, false, false));
        // An explicit "no redact" is not a blocked request, just a no-op.
        assert!(!resolve_should_redact(&cfg, true, true));
        assert!(!explicit_request_is_blocked(&cfg, true, true));

        cfg.enabled = true;
        cfg.auto = true;
        assert!(resolve_should_redact(&cfg, false, false));
        assert!(!resolve_should_redact(&cfg, false, true)); // no_redact wins
        assert!(!explicit_request_is_blocked(&cfg, true, false));

        // The default config does NOT auto-redact: rules are available but
        // only run on an explicit request, so a false positive can never
        // silently mangle an ordinary capture.
        let default = RedactionConfig::default();
        assert!(default.enabled);
        assert!(!default.auto);
        assert!(!resolve_should_redact(&default, false, false));
        assert!(resolve_should_redact(&default, true, false));
    }

    #[test]
    fn all_builtin_patterns_are_valid_regexes() {
        // Every compiled-in pattern must be a valid Rust `regex` crate regex.
        for rule in builtin_rules() {
            assert!(
                Regex::new(&rule.pattern).is_ok(),
                "invalid regex for builtin '{}': {}",
                rule.name,
                rule.pattern
            );
        }

        // The full default engine (builtins + labels) must build cleanly and
        // expose every newly added Betterleaks-sourced rule by name.
        let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();
        let names = engine.rule_names();
        for expected in [
            "github_token",
            "slack_token",
            "private_key_pem",
            "gcp_service_account",
            "azure_client_secret",
            "generic_api_key",
            "bearer_token",
            "connection_string",
            "discord_token",
            "hashicorp_vault_token",
        ] {
            assert!(
                names.contains(&expected),
                "missing builtin rule '{}'",
                expected
            );
        }
    }

    #[test]
    fn new_builtin_rules_match_sample_secrets() {
        let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();
        // Each sample should trigger at least one redaction.
        let samples = [
            "ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            "xoxb-1234567890-1234567890-abcdefghijKLMNOPqrstuvwx",
            "-----BEGIN OPENSSH PRIVATE KEY-----",
            "token = hvs.ABCDEFGHIJKLMNOPQRSTUVWX01",
        ];
        for s in samples {
            let parser = screen_of(s, 120, 3);
            let map = engine.redact_screen(&parser, None);
            assert!(!map.is_empty(), "expected a redaction for sample: {}", s);
        }
    }

    #[test]
    fn user_rule_can_disable_builtin() {
        let cfg = RedactionConfig {
            enabled: true,
            auto: false,
            rules: vec![RedactionRuleConfig {
                name: "email".to_string(),
                pattern: String::new(),
                replacement: default_replacement(),
                enabled: false,
                color: None,
                min_entropy: None,
                keep_prefix: None,
                keep_suffix: None,
            }],
            ..Default::default()
        };
        let engine = RedactionEngine::from_config(&cfg).unwrap();
        let parser = screen_of("admin@example.com", 120, 3);
        let map = engine.redact_screen(&parser, None);
        assert_eq!(count_of(&map, "email"), 0);
    }

    #[test]
    fn overriding_builtin_keeps_partial_redaction_fields() {
        // Overriding a builtin (aws_key) with keep_prefix must preserve the
        // partial-redaction request, leaving the "AKIA" prefix visible.
        let cfg = RedactionConfig {
            enabled: true,
            auto: false,
            rules: vec![RedactionRuleConfig {
                name: "aws_key".to_string(),
                pattern: String::new(),
                replacement: default_replacement(),
                enabled: true,
                color: None,
                min_entropy: None,
                keep_prefix: Some(4),
                keep_suffix: None,
            }],
            ..Default::default()
        };
        let engine = RedactionEngine::from_config(&cfg).unwrap();
        let parser = screen_of("AKIAIOSFODNN7EXAMPLE", 120, 3);
        let map = engine.redact_screen(&parser, None);
        // First 4 columns ("AKIA") stay visible; the rest are masked.
        for col in 0..4 {
            assert!(map.get(0, col).is_none(), "prefix col {} redacted", col);
        }
        for col in 4..20 {
            assert!(map.get(0, col).is_some(), "col {} not redacted", col);
        }
    }

    #[test]
    fn custom_user_rule_is_applied() {
        let cfg = RedactionConfig {
            enabled: true,
            auto: false,
            rules: vec![RedactionRuleConfig {
                name: "ticket".to_string(),
                pattern: r"TICKET-\d+".to_string(),
                replacement: "[REDACTED-TICKET]".to_string(),
                enabled: true,
                color: None,
                min_entropy: None,
                keep_prefix: None,
                keep_suffix: None,
            }],
            ..Default::default()
        };
        let engine = RedactionEngine::from_config(&cfg).unwrap();
        let parser = screen_of("see TICKET-1234", 120, 3);
        let map = engine.redact_screen(&parser, None);
        assert_eq!(count_of(&map, "ticket"), 1);
    }

    #[test]
    fn per_rule_color_is_applied() {
        let mut rule = RedactionRuleConfig::new("ip", r"\b10\.0\.0\.\d+\b", "[REDACTED-IP]");
        rule.color = Some("#ff6600".to_string());
        let cfg = RedactionConfig {
            rules: vec![rule],
            ..Default::default()
        };
        let engine = RedactionEngine::from_config(&cfg).unwrap();
        let parser = screen_of("ip 10.0.0.5 up", 120, 3);
        let map = engine.redact_screen(&parser, Some(&["ip".to_string()]));
        let cell = map.get(0, 3).expect("redacted");
        assert_eq!(cell.block_color, [255, 102, 0]);
    }

    #[test]
    fn engine_wide_color_overrides_default() {
        let cfg = RedactionConfig {
            color: Some("#00ff00".to_string()),
            label_color: Some("#111111".to_string()),
            enabled: true,
            ..Default::default()
        };
        let engine = RedactionEngine::from_config(&cfg).unwrap();
        let parser = screen_of("ip 192.168.1.9 up", 120, 3);
        let map = engine.redact_screen(&parser, None);
        let cell = map.get(0, 3).expect("redacted");
        assert_eq!(cell.block_color, [0, 255, 0]);
        assert_eq!(cell.label_color, [17, 17, 17]);
    }

    #[test]
    fn min_entropy_filters_low_randomness_matches() {
        let mut rule = RedactionRuleConfig::new("token", r"\btok_[A-Za-z0-9]+\b", "[REDACTED]");
        rule.min_entropy = Some(3.0);
        let cfg = RedactionConfig {
            rules: vec![rule],
            ..Default::default()
        };
        let engine = RedactionEngine::from_config(&cfg).unwrap();
        // Low-entropy value is ignored...
        let low = screen_of("tok_aaaaaaaa", 120, 3);
        assert_eq!(count_of(&engine.redact_screen(&low, None), "token"), 0);
        // ...but a high-entropy value is redacted.
        let high = screen_of("tok_a8Xk2Qm9Zp", 120, 3);
        assert_eq!(count_of(&engine.redact_screen(&high, None), "token"), 1);
    }

    #[test]
    fn manual_coordinate_redaction() {
        let parser = screen_of("secret data here", 120, 3);
        let mut map = RedactionMap::default();
        map.add_manual(0, 0, 6, Some("SECRET"));
        for col in 0..6 {
            assert!(map.get(0, col).is_some(), "column {} redacted", col);
        }
        assert!(map.get(0, 6).is_none());
        let text = map.redacted_plain_text(&parser);
        assert!(!text.contains("secret"));
    }

    #[test]
    fn shannon_entropy_bounds() {
        assert_eq!(shannon_entropy(""), 0.0);
        assert_eq!(shannon_entropy("aaaa"), 0.0);
        // Two equally likely symbols -> 1 bit/char.
        assert!((shannon_entropy("abab") - 1.0).abs() < 1e-9);
    }

    #[test]
    fn yaml_rules_load() {
        let dir = std::path::Path::new("target/yaml-test-rules");
        std::fs::create_dir_all(dir).unwrap();
        let yaml = r#"
rules:
  - name: slack_token
    id: kf.slack
    pattern: 'xoxb-[0-9A-Za-z-]+'
    min_entropy: 3.0
    confidence: high
  - id: disabled_rule
    pattern: 'DISABLED-\d+'
    confidence: disabled
  - name: no_pattern
"#;
        std::fs::write(dir.join("kf.yaml"), yaml).unwrap();
        let rules = load_rules_from_dir(dir);
        // The rule with no pattern is dropped; the other two are loaded.
        assert_eq!(rules.len(), 2);
        let slack = rules.iter().find(|r| r.name == "slack_token").unwrap();
        assert_eq!(slack.min_entropy, Some(3.0));
        assert!(slack.enabled);
        let disabled = rules.iter().find(|r| r.name == "disabled_rule").unwrap();
        assert!(!disabled.enabled);
        std::fs::remove_dir_all(dir).ok();
    }

    /// The YAML backend moved from the archived `serde_yaml` to the maintained
    /// `serde_yaml_ng` fork. Pin the behavior that swap must not change:
    /// generic Kingfisher-style documents (anchors, aliases, quoted and block
    /// scalars, unknown keys) still load, and a malformed document is still
    /// skipped with a warning rather than aborting the whole directory.
    #[test]
    fn yaml_rules_keep_generic_syntax_and_rejection_semantics() {
        let dir = std::path::Path::new("target/yaml-ng-test-rules");
        std::fs::remove_dir_all(dir).ok();
        std::fs::create_dir_all(dir).unwrap();

        // Anchors/aliases, a block scalar, a flow mapping, and keys this type
        // does not model - all of which a generic rule file may carry.
        std::fs::write(
            dir.join("generic.yaml"),
            r#"
default_entropy: &entropy 3.5
rules:
  - name: anchored_rule
    pattern: 'ANCHOR-[0-9a-f]{8}'
    confidence: high
    min_entropy: *entropy
  - {id: flow_rule, regex: 'FLOW-\d+'}
  - name: block_rule
    pattern: >-
      BLOCK-[A-Z]+
    description: |
      A key the rule type does not model; it must be ignored, not rejected.
    tags: [one, two]
"#,
        )
        .unwrap();

        // Unparseable YAML: the file is skipped, the directory still loads.
        std::fs::write(
            dir.join("broken.yaml"),
            "rules:\n  - name: x\n   pattern: [\n",
        )
        .unwrap();
        // A `.yml` file is loaded too; a `.json` file is not.
        std::fs::write(
            dir.join("short.yml"),
            "rules:\n  - name: yml_rule\n    pattern: 'YML-\\d+'\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("ignored.json"),
            r#"{"rules":[{"name":"json_rule","pattern":"J-1"}]}"#,
        )
        .unwrap();

        let rules = load_rules_from_dir(dir);
        let names: BTreeSet<&str> = rules.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(
            names,
            BTreeSet::from(["anchored_rule", "flow_rule", "block_rule", "yml_rule"]),
            "malformed YAML is skipped, .yml loads, non-YAML extensions are ignored"
        );

        let anchored = rules.iter().find(|r| r.name == "anchored_rule").unwrap();
        assert_eq!(
            anchored.min_entropy,
            Some(3.5),
            "an aliased anchor value still populates the rule"
        );
        assert!(anchored.enabled);
        let block = rules.iter().find(|r| r.name == "block_rule").unwrap();
        assert_eq!(
            block.pattern, "BLOCK-[A-Z]+",
            "a folded block scalar keeps its exact pattern text"
        );

        std::fs::remove_dir_all(dir).ok();
    }

    #[test]
    fn toml_rules_dir_loads() {
        let dir = std::path::Path::new("target/toml-test-rules");
        std::fs::create_dir_all(dir).unwrap();
        let toml_src = r#"
[[rules]]
name = "ticket"
pattern = 'TICKET-\d+'
replacement = "[REDACTED-TICKET]"
"#;
        std::fs::write(dir.join("extra.toml"), toml_src).unwrap();
        let rules = load_rules_from_dir(dir);
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].name, "ticket");
        std::fs::remove_dir_all(dir).ok();
    }
    // ---------------------------------------------------------------------
    // Manual redaction specifications
    // ---------------------------------------------------------------------

    /// A pattern specification decodes every field the MCP tool documents,
    /// including `label` as an alias for `replacement`.
    #[test]
    fn pattern_specs_decode_every_documented_field() {
        let spec = ManualRedactionSpec::from_json(
            r##"{"pattern":"[a-f0-9]{32}","replacement":"HASH","keep_prefix":4,"keep_suffix":2,"color":"#00ff00"}"##,
        )
        .expect("valid pattern spec");
        match spec {
            ManualRedactionSpec::Pattern {
                pattern,
                replacement,
                keep_prefix,
                keep_suffix,
                color,
            } => {
                assert_eq!(pattern, "[a-f0-9]{32}");
                assert_eq!(replacement.as_deref(), Some("HASH"));
                assert_eq!(keep_prefix, Some(4));
                assert_eq!(keep_suffix, Some(2));
                assert_eq!(color.as_deref(), Some("#00ff00"));
            }
            other => panic!("expected a pattern spec, got {:?}", other),
        }

        // `label` is accepted as the on-image tag for a pattern too.
        match ManualRedactionSpec::from_json(r#"{"pattern":"x","label":"TAG"}"#).unwrap() {
            ManualRedactionSpec::Pattern { replacement, .. } => {
                assert_eq!(replacement.as_deref(), Some("TAG"))
            }
            other => panic!("expected a pattern spec, got {:?}", other),
        }
    }

    /// A coordinate specification decodes its range, label, and color.
    #[test]
    fn coordinate_specs_decode_their_range() {
        match ManualRedactionSpec::from_json(
            r##"{"row":3,"col_start":12,"col_end":44,"label":"SECRET","color":"#d41919"}"##,
        )
        .unwrap()
        {
            ManualRedactionSpec::Coordinate {
                row,
                col_start,
                col_end,
                label,
                color,
            } => {
                assert_eq!((row, col_start, col_end), (3, 12, 44));
                assert_eq!(label.as_deref(), Some("SECRET"));
                assert_eq!(color.as_deref(), Some("#d41919"));
            }
            other => panic!("expected a coordinate spec, got {:?}", other),
        }
    }

    /// The MCP path decodes through the same function, so JSON that the CLI
    /// refuses is refused identically when it arrives as a tool parameter.
    #[test]
    fn the_cli_and_serde_paths_share_one_decoder() {
        for bad in [
            r#"{"pattern":"x","replacment":"y"}"#,
            r#"{"row":0,"col_start":0}"#,
            r#"{"label":"x"}"#,
            r#"[1,2,3]"#,
        ] {
            let cli = ManualRedactionSpec::from_json(bad).expect_err("the CLI must refuse it");
            let serde = serde_json::from_str::<ManualRedactionSpec>(bad)
                .expect_err("the MCP path must refuse it too");
            let cli = cli.to_string();
            assert!(
                serde.to_string().contains(&cli) || cli.contains("in redaction"),
                "the two paths disagree about {bad}: {cli} vs {serde}"
            );
        }

        let good = r#"{"pattern":"x","keep_prefix":1}"#;
        assert!(serde_json::from_str::<ManualRedactionSpec>(good).is_ok());
        assert!(ManualRedactionSpec::from_json(good).is_ok());
    }

    /// Bad regexes and bad colors are refused when the set is compiled, before
    /// a command runs or an image is written.
    #[test]
    fn manual_redactions_reject_invalid_input_up_front() {
        let bad_regex = ManualRedactionSpec::from_json(r#"{"pattern":"([a-"}"#).unwrap();
        let err = ManualRedactions::new(&[bad_regex], true).unwrap_err();
        assert!(err.to_string().contains("invalid regex"), "{err}");

        let bad_color =
            ManualRedactionSpec::from_json(r#"{"pattern":"x","color":"nope"}"#).unwrap();
        let err = ManualRedactions::new(&[bad_color], true).unwrap_err();
        assert!(err.to_string().contains("invalid color"), "{err}");

        let bad_coord_color = ManualRedactionSpec::from_json(
            r#"{"row":0,"col_start":0,"col_end":1,"color":"12345"}"#,
        )
        .unwrap();
        let err = ManualRedactions::new(&[bad_coord_color], true).unwrap_err();
        assert!(err.to_string().contains("invalid color"), "{err}");
    }

    /// Coordinates are checked against the rendered bounds, and the message
    /// names both the request and the dimensions.
    #[test]
    fn manual_coordinates_are_bounds_checked() {
        let specs =
            vec![ManualRedactionSpec::from_json(r#"{"row":0,"col_start":0,"col_end":4}"#).unwrap()];
        let manual = ManualRedactions::new(&specs, true).unwrap();
        assert!(manual.validate_bounds(4, 8).is_ok());

        let err = manual.validate_bounds(4, 3).unwrap_err().to_string();
        assert!(
            err.contains("col_end 4 is past the last rendered column boundary"),
            "{err}"
        );
        assert!(err.contains("renders 4 row(s) x 3 column(s)"), "{err}");

        let err = ManualRedactions::new(&specs, true)
            .unwrap()
            .validate_bounds(0, 8)
            .unwrap_err()
            .to_string();
        assert!(err.contains("row 0 is past the last rendered row"), "{err}");
    }

    /// A compiled set masks a pattern (keeping its prefix) and a cell range in
    /// the caller's color, and names them in the audit the way the MCP tool
    /// reports them.
    #[test]
    fn manual_redactions_apply_patterns_and_coordinates() {
        let specs = vec![
            ManualRedactionSpec::from_json(
                r#"{"pattern":"AKIA[0-9A-Z]{16}","replacement":"KEY","keep_prefix":4}"#,
            )
            .unwrap(),
            ManualRedactionSpec::from_json(
                r##"{"row":0,"col_start":0,"col_end":4,"label":"SECRET","color":"#00ff00"}"##,
            )
            .unwrap(),
        ];
        let manual = ManualRedactions::new(&specs, true).unwrap();
        assert!(!manual.is_empty());
        assert_eq!(manual.coordinates().len(), 1);

        let mut parser = vt100::Parser::new(4, 40, 0);
        parser.process(
            b"user AKIAIOSFODNN7EXAMPLE
",
        );
        let mut map = RedactionMap::default();
        manual.apply_to(parser.screen(), &mut map);

        // The key is masked except for its first four characters.
        let text = map.redacted_plain_text(parser.screen());
        assert!(text.contains("AKIA\u{2588}"), "{text}");
        assert!(!text.contains("AKIAIOSFODNN7EXAMPLE"), "{text}");
        // The coordinate range is painted in the requested color.
        assert_eq!(map.get(0, 0).unwrap().block_color, [0, 255, 0]);
        // The pattern keeps the built-in red.
        assert_eq!(map.get(0, 9).unwrap().block_color, DEFAULT_BLOCK_COLOR);
        assert_eq!(
            map.audit_summary(),
            "1x custom_0, 1x manual:SECRET",
            "the audit must name the specs the way the MCP tool does"
        );
    }

    /// With labels suppressed every block is drawn plain, matching
    /// `show_labels: false`.
    #[test]
    fn manual_redactions_can_suppress_labels() {
        let specs =
            vec![ManualRedactionSpec::from_json(r#"{"row":0,"col_start":0,"col_end":4}"#).unwrap()];
        let manual = ManualRedactions::new(&specs, false).unwrap();
        let mut parser = vt100::Parser::new(2, 20, 0);
        parser.process(b"secret\r\n");
        let mut map = RedactionMap::default();
        manual.apply_to(parser.screen(), &mut map);
        for col in 0..4 {
            assert!(map.get(0, col).unwrap().label_char.is_none());
        }
    }

    // ---------------------------------------------------------------------
    // Published schema
    // ---------------------------------------------------------------------

    /// The two variants of the published schema, in order.
    fn schema_variants() -> (serde_json::Value, serde_json::Value) {
        let schema = manual_redaction_schema();
        let variants = schema["oneOf"]
            .as_array()
            .expect("the schema discriminates with oneOf, as the parser does")
            .clone();
        assert_eq!(variants.len(), 2, "expected two variants: {schema}");
        (variants[0].clone(), variants[1].clone())
    }

    /// Each variant publishes exactly the fields the parser accepts, exactly
    /// the ones it requires, and refuses anything else.
    #[test]
    fn the_schema_publishes_exactly_what_the_parser_accepts() {
        let (pattern, coordinate) = schema_variants();

        for (variant, fields, required) in [
            (&pattern, PATTERN_FIELDS, PATTERN_REQUIRED),
            (&coordinate, COORDINATE_FIELDS, COORDINATE_REQUIRED),
        ] {
            assert_eq!(variant["type"], "object", "{variant}");
            assert_eq!(
                variant.get("additionalProperties"),
                Some(&serde_json::Value::Bool(false)),
                "a variant that allows unknown fields promises what the parser refuses: \
                 {variant}"
            );

            let published: BTreeSet<&str> = variant["properties"]
                .as_object()
                .expect("properties is an object")
                .keys()
                .map(String::as_str)
                .collect();
            assert_eq!(
                published,
                fields.iter().copied().collect::<BTreeSet<&str>>(),
                "the published fields must be the accepted fields: {variant}"
            );

            let published_required: Vec<&str> = variant["required"]
                .as_array()
                .expect("required is an array")
                .iter()
                .map(|value| value.as_str().expect("a field name"))
                .collect();
            assert_eq!(published_required, required, "{variant}");

            // Every published field has a real schema, not an empty stub.
            for (name, field) in variant["properties"].as_object().unwrap() {
                assert!(
                    field.get("type").is_some(),
                    "field {name} has no type: {field}"
                );
                assert!(
                    field
                        .get("description")
                        .and_then(serde_json::Value::as_str)
                        .is_some_and(|d| !d.is_empty()),
                    "field {name} has no description: {field}"
                );
            }
        }

        // The pattern variant is the one carrying the `label` alias, and the
        // one keyed on `pattern`.
        assert!(pattern["properties"].get("pattern").is_some());
        assert!(pattern["properties"].get("label").is_some());
        assert!(coordinate["properties"].get("pattern").is_none());
    }

    /// The type's `JsonSchema` implementation is the schema above, so what
    /// `tools/list` publishes is what these tests check.
    #[test]
    fn the_json_schema_impl_publishes_the_same_document() {
        let mut generator = schemars::SchemaGenerator::default();
        let schema =
            <ManualRedactionSpec as schemars::JsonSchema>::json_schema(&mut generator).to_value();
        assert_eq!(schema, manual_redaction_schema());
        assert_eq!(
            <ManualRedactionSpec as schemars::JsonSchema>::schema_name(),
            "ManualRedactionSpec"
        );
    }
}