aft-base 0.67.1

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

use std::borrow::Cow;
use std::sync::LazyLock;

use regex::{Captures, Regex, Replacer};

/// Replacement for a token-shaped secret. Matches the CLI sanitizer.
pub const SECRET_PLACEHOLDER: &str = "<REDACTED_SECRET>";
/// Replacement for URL userinfo. Matches the CLI sanitizer.
pub const URL_CREDENTIAL_PLACEHOLDER: &str = "***";

/// A `key=` query value shorter than this is treated as an ordinary word.
const KEY_VALUE_MIN_SECRET_LEN: usize = 16;

fn compile(pattern: &str) -> Regex {
    Regex::new(pattern).expect("log redaction pattern must compile")
}

static AUTHORIZATION_HEADER: LazyLock<Regex> = LazyLock::new(|| {
    compile(
        r"(?i)\b((?:proxy-)?authorization[^\S\r\n]*:[^\S\r\n]*(?:bearer|basic|token)[^\S\r\n]+)[A-Za-z0-9._~+/-]+=*",
    )
});
static API_KEY_HEADER: LazyLock<Regex> =
    LazyLock::new(|| compile(r"(?i)\b(x-api-key[^\S\r\n]*:[^\S\r\n]*)[^\s<>]+"));
static SECRET_JSON_FIELD: LazyLock<Regex> = LazyLock::new(|| {
    compile(&format!(
        r#"(?i)("(?:{JSON_SECRET_LABELS})"\s*:\s*")((?:\\.|[^"\\])+)(")"#
    ))
});
/// The opening of a [`SECRET_JSON_FIELD`] value, up to and including its quote.
static SECRET_JSON_OPENING: LazyLock<Regex> =
    LazyLock::new(|| compile(&format!(r#"(?i)"(?:{JSON_SECRET_LABELS})"\s*:\s*""#)));
const JSON_SECRET_LABELS: &str = "password|passwd|pwd|api[_-]?key|apikey|x-api-key|aws_secret_access_key|awsSecretAccessKey|secret_access_key";
static AWS_SECRET_FIELD: LazyLock<Regex> = LazyLock::new(|| {
    compile(
        r#"(?i)\b((?:aws_secret_access_key|secret_access_key)[^\S\r\n]*[=:][^\S\r\n]*)[^\s"'<>]+"#,
    )
});
static SLACK_TOKEN: LazyLock<Regex> = LazyLock::new(|| compile(r"\bxox[baprs]-[A-Za-z0-9-]+\b"));
static PRIVATE_KEY: LazyLock<Regex> = LazyLock::new(|| {
    compile(
        r"(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|\z)",
    )
});

static GITHUB_PAT: LazyLock<Regex> = LazyLock::new(|| compile(r"\bgithub_pat_[A-Za-z0-9_]+\b"));
static GITHUB_TOKEN: LazyLock<Regex> =
    LazyLock::new(|| compile(r"\bgh[pousr]_[A-Za-z0-9_]{16,}\b"));
static SK_API_KEY: LazyLock<Regex> = LazyLock::new(|| {
    compile(r"\bsk-(?:live-[A-Za-z0-9][A-Za-z0-9_-]{7,}|[A-Za-z0-9][A-Za-z0-9_-]{19,})\b")
});
static JWT: LazyLock<Regex> =
    LazyLock::new(|| compile(r"\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b"));
static AWS_ACCESS_KEY_ID: LazyLock<Regex> =
    LazyLock::new(|| compile(r"\b(?:AKIA|ASIA|AGPA|AIDA|AROA)[A-Z0-9]{16}\b"));
static URL_USERINFO: LazyLock<Regex> =
    LazyLock::new(|| compile(r"(?i)\b([a-z][a-z0-9+.-]*://)[^@\s/?#]+@"));
/// Query parameters whose name alone says the value is a credential. The value
/// stops at the next parameter, fragment, whitespace, quote or angle bracket;
/// excluding `<` keeps an already-masked value from matching again.
static CREDENTIAL_QUERY: LazyLock<Regex> = LazyLock::new(|| {
    compile(
        r#"(?i)([?&](?:[a-z0-9_-]*token|api[_-]?key|apikey|[a-z0-9_-]*secret|password|passwd|pwd)=)[^&\s#"'<>]+"#,
    )
});
/// `key=` is too generic to mask on its name alone; see [`looks_like_secret`].
static KEY_QUERY: LazyLock<Regex> = LazyLock::new(|| compile(r#"(?i)([?&]key=)([^&\s#"'<>]+)"#));
// Value-shape checks are restricted to explicit shell command text.
static INLINE_ASSIGNMENT: LazyLock<Regex> = LazyLock::new(|| {
    compile(r#"\b(([A-Za-z_][A-Za-z0-9_]*)=)("[^"\r\n]+"|'[^'\r\n]+'|[^\s,;&|<>()'"]+)"#)
});
// Also protects log lines from older versions that recorded raw commands.
static SHORT_PASSWORD_ASSIGNMENT: LazyLock<Regex> = LazyLock::new(|| {
    compile(
        r#"(?i)\b(((?:[A-Za-z_][A-Za-z0-9_]*_)?(?:PW|PASS))=)("[^"\r\n]+"|'[^'\r\n]+'|[^\s,;&|<>()'"]+)"#,
    )
});

/// Mask credentials in `text`. Returns the input unchanged (borrowed) when it
/// contains nothing to mask, so the common case allocates nothing.
pub fn aft_redactor(text: &str) -> Cow<'_, str> {
    redact_with_range(text, None, RangeMapping::Watch)
}

const SHELL_FORMAT_TRIGGERS: &[&str] = &[
    "PRIVATE KEY-----",
    "xox",
    "x-api-key",
    "\"",
    "secret_access_key",
    "authorization",
    "github_pat_",
    "ghp_",
    "gho_",
    "ghu_",
    "ghs_",
    "ghr_",
    "sk-",
    "eyJ",
    "AKIA",
    "ASIA",
    "AGPA",
    "AIDA",
    "AROA",
    "://",
    "?",
    "&",
    // Short password assignments (`PW=`, `DB_PASS=`): the name must end in
    // PW or PASS directly before `=`.
    "pw=",
    "pass=",
];

/// A conservative prefilter, not a second masker. A complete capture with no
/// trigger cannot contain any format recognized by `redact_with_range`.
pub fn shells_may_need_format_context(text: &str) -> bool {
    SHELL_FORMAT_TRIGGERS
        .iter()
        .any(|trigger| contains_ignore_ascii_case(text, trigger))
}

pub fn shells_format_scan_overlap() -> usize {
    SHELL_FORMAT_TRIGGERS
        .iter()
        .map(|trigger| trigger.len())
        .max()
        .unwrap_or(1)
        - 1
}

static SHELL_PRIVATE_BOUNDARY: LazyLock<Regex> =
    LazyLock::new(|| compile(r"-----(?:BEGIN|END) [A-Z0-9 ]*PRIVATE KEY-----"));

pub fn shells_private_boundary_before(text: &str, before: usize) -> bool {
    SHELL_PRIVATE_BOUNDARY
        .find_iter(text)
        .any(|marker| marker.end() <= before)
}

// Shell-command credential shapes. These are applied only to command text
// (see [`redact_command`]), not to every log line: AFT's own structured log
// fields are lowercase `key=value` pairs and must stay readable.
//
// The leading `(^|[^...])` group stands in for a look-behind, which the regex
// crate lacks; replacements re-emit it.

/// One whole shell word, as the shell would read it: single-quoted runs,
/// double-quoted runs with backslash escapes, backslash-escaped characters
/// and plain characters, concatenated (`'a'"b"c`, `my\ pass`), up to the
/// next unquoted whitespace or shell operator. A quote left open runs to the
/// end of the text. `<` ends a word, so an already-masked value is never
/// matched again.
macro_rules! shell_word {
    () => {
        r#"(?:'[^']*'?|"(?:\\[\s\S]|[^"\\])*"?|\\[\s\S]?|[^\s;&|<>()'"\\])+"#
    };
}

/// `NAME=value` where NAME is UPPER_SNAKE and contains a credential word,
/// at its start or after other letters, followed by `=` or `_` (`TOKEN=`,
/// `GITHUB_TOKEN=`, `export DB_PASSWORD=`, `AWS_SECRET_ACCESS_KEY_ID=`).
/// Plain substrings do not count: `MAX_TOKENS`, `TOKENIZERS_PARALLELISM`,
/// `GIT_AUTHOR_NAME` and `GH_SHIM_BYPASS` stay.
static COMMAND_SECRET_ASSIGNMENT: LazyLock<Regex> = LazyLock::new(|| {
    compile(concat!(
        r#"(^|[^A-Za-z0-9_])((?:(?:[A-Z][A-Z0-9_]*?)?(?:TOKEN|SECRET|PASSWORD|PASSWD|PASSPHRASE|CREDENTIALS?|APIKEY|API_KEY|ACCESS_KEY|PRIVATE_KEY|AUTH_KEY|_KEY|_PAT|_AUTH)(?:_[A-Z0-9]+)*|(?:[A-Z_][A-Z0-9_]*_)?(?:PW|PASS))=)("#,
        shell_word!(),
        ")"
    ))
});
/// Assignment names ending in one of these name where a credential lives or
/// who owns it, not the credential (`SSH_KEY_PATH=`, `AWS_ACCESS_KEY_ID=`).
const COMMAND_NON_SECRET_NAME_SUFFIXES: [&str; 16] = [
    "_PATH=",
    "_FILE=",
    "_DIR=",
    "_NAME=",
    "_URL=",
    "_ID=",
    "_HOST=",
    "_PORT=",
    "_USER=",
    "_USERNAME=",
    "_ENV=",
    "_COUNT=",
    "_LEN=",
    "_LENGTH=",
    "_TTL=",
    "_MODE=",
];
/// Long options whose value is a credential, as `--flag=value` or
/// `--flag value`. `--secret` is deliberately absent: gcloud and others use it
/// for a secret's name.
static COMMAND_SECRET_FLAG: LazyLock<Regex> = LazyLock::new(|| {
    compile(concat!(
        r#"(^|[^A-Za-z0-9_-])(--(?:password|passwd|pass|token|api-key|apikey|client-secret|auth-token|access-token|bearer)(?:=|[ \t]+))("#,
        shell_word!(),
        ")"
    ))
});
/// How deep [`mask_tool_passwords`] looks into quoted strings and
/// substitutions that hold a command of their own (`bash -c "curl ..."`,
/// `$(curl ...)`). A quoted substitution (`"$(...)"`) takes two levels.
const QUOTED_COMMAND_DEPTH: usize = 8;

/// The longest command prefix [`mask_tool_passwords`] scans. Anything past
/// it is masked whole rather than logged unscanned, which keeps the work on
/// a huge command bounded without letting its tail through.
const MAX_SCANNED_COMMAND_BYTES: usize = 1 << 20;

#[derive(Clone, Copy, PartialEq, Eq)]
enum ShellTokenKind {
    Word,
    /// A redirection with its target (`<f`, `> f`, `2>&1`, `<<<word`). It is
    /// neither an argument nor the value of the option before it.
    Redirect,
}

#[derive(Clone)]
struct ShellToken {
    kind: ShellTokenKind,
    range: std::ops::Range<usize>,
}

/// Bytes that separate words without ending the command: every ASCII
/// whitespace byte except the newline (space, tab, carriage return, vertical
/// tab, form feed; `u8::is_ascii_whitespace` leaves out the vertical tab).
/// The command loop skips exactly these and the word scan stops at exactly
/// these, so every byte a word stops at is one the loop around it consumes.
fn is_shell_blank(byte: u8) -> bool {
    matches!(byte, b' ' | b'\t' | b'\r' | b'\x0b' | b'\x0c')
}

/// Bytes that end a word: blanks, plus the bytes that start an operator or
/// end a command. The command loop has an arm for each of them.
fn ends_shell_word(byte: u8) -> bool {
    is_shell_blank(byte) || matches!(byte, b'\n' | b';' | b'&' | b'|' | b'<' | b'>' | b'(' | b')')
}

/// Whether a process substitution (`<(` or `>(`) starts at `at`.
fn starts_process_substitution(bytes: &[u8], at: usize) -> bool {
    matches!(bytes.get(at), Some(b'<' | b'>')) && bytes.get(at + 1) == Some(&b'(')
}

/// The index of the `)` that closes a substitution whose body starts at
/// `from`, or the end of `text` when it never closes. Quotes, backticks and
/// escapes inside are skipped; nested parentheses are counted.
fn substitution_end(text: &str, from: usize) -> usize {
    let bytes = text.as_bytes();
    let mut depth = 1;
    let mut at = from;
    while at < bytes.len() {
        note_shell_scan_steps(1);
        match bytes[at] {
            b'\\' => at += 2,
            b'\'' => at = skip_single_quoted(text, at),
            b'"' => at = skip_double_quoted(bytes, at),
            b'`' => at = backtick_end(bytes, at + 1) + 1,
            b'(' => {
                depth += 1;
                at += 1;
            }
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return at;
                }
                at += 1;
            }
            _ => at += 1,
        }
    }
    bytes.len()
}

/// The index just past the single-quoted run opening at `at`.
fn skip_single_quoted(text: &str, at: usize) -> usize {
    text[at + 1..]
        .find('\'')
        .map_or(text.len(), |offset| at + 1 + offset + 1)
}

/// The index just past the double-quoted run opening at `at`.
fn skip_double_quoted(bytes: &[u8], at: usize) -> usize {
    let mut close = at + 1;
    while close < bytes.len() && bytes[close] != b'"' {
        close += if bytes[close] == b'\\' { 2 } else { 1 };
    }
    (close + 1).min(bytes.len())
}

/// The index of the backtick that closes a substitution whose body starts
/// at `from`, or the end of the text.
fn backtick_end(bytes: &[u8], from: usize) -> usize {
    let mut at = from;
    while at < bytes.len() && bytes[at] != b'`' {
        at += if bytes[at] == b'\\' { 2 } else { 1 };
    }
    at.min(bytes.len())
}

/// Split `text` into simple commands of words and redirections, reading it
/// as the shell would: quotes and backslashes keep operators inside a word;
/// a command substitution (`$( ... )`, backticks) or process substitution
/// (`<( ... )`, `>( ... )`) is part of the word it appears in, so the
/// command around it carries on after it closes; an unquoted `;`, `&`, `|`,
/// newline, `(` or `)` ends a command (a subshell is a command of its own);
/// a backslash-newline continues the line; redirections may be attached to
/// a word or spaced from it. Also returns the inside of every quoted run and
/// substitution, which [`collect_tool_password_masks`] scans as a command of
/// its own one level down.
fn split_shell_commands(text: &str) -> (Vec<Vec<ShellToken>>, Vec<std::ops::Range<usize>>) {
    let bytes = text.as_bytes();
    let mut commands = vec![Vec::new()];
    let mut quoted = Vec::new();
    let end_command = |commands: &mut Vec<Vec<ShellToken>>| {
        if !commands.last().is_some_and(Vec::is_empty) {
            commands.push(Vec::new());
        }
    };
    let mut at = 0;
    while at < bytes.len() {
        note_shell_scan_steps(1);
        let before = at;
        match bytes[at] {
            byte if is_shell_blank(byte) => at += 1,
            b'\\' if bytes.get(at + 1) == Some(&b'\n') => at += 2,
            b'\n' | b';' | b'(' | b')' => {
                end_command(&mut commands);
                at += 1;
            }
            b'|' => {
                end_command(&mut commands);
                at += 1 + usize::from(matches!(bytes.get(at + 1), Some(b'|' | b'&')));
            }
            b'&' if bytes.get(at + 1) != Some(&b'>') => {
                end_command(&mut commands);
                at += 1 + usize::from(bytes.get(at + 1) == Some(&b'&'));
            }
            b'&' | b'<' | b'>' if !starts_process_substitution(bytes, at) => {
                let (token, next) = scan_redirect(text, at, &mut quoted);
                commands.last_mut().unwrap().push(token);
                at = next;
            }
            _ => {
                let next = scan_shell_word(text, at, &mut quoted);
                // A file-descriptor number attached to a redirection (`2>`).
                if text[at..next].bytes().all(|byte| byte.is_ascii_digit())
                    && matches!(bytes.get(next), Some(b'<' | b'>'))
                {
                    let (mut token, after) = scan_redirect(text, next, &mut quoted);
                    token.range.start = at;
                    commands.last_mut().unwrap().push(token);
                    at = after;
                } else {
                    commands.last_mut().unwrap().push(ShellToken {
                        kind: ShellTokenKind::Word,
                        range: at..next,
                    });
                    at = next;
                }
            }
        }
        // Every arm above consumes at least one byte: the word arm is only
        // reached on a byte that does not end a word, or on the `<(` / `>(`
        // that opens a process substitution, which the word scan consumes
        // whole. Should a future change
        // break that, step over one character rather than loop forever on
        // a spawn path.
        if at <= before {
            debug_assert!(false, "shell scan stalled at byte {before} of {text:?}");
            at = before + text[before..].chars().next().map_or(1, char::len_utf8);
        }
    }
    (commands, quoted)
}

/// The end of the shell word starting at `start`, recording the inside of
/// each quoted run. An unclosed quote runs to the end of `text`.
fn scan_shell_word(text: &str, start: usize, quoted: &mut Vec<std::ops::Range<usize>>) -> usize {
    let bytes = text.as_bytes();
    let mut at = start;
    while at < bytes.len() {
        note_shell_scan_steps(1);
        match bytes[at] {
            b'\'' => {
                let close = text[at + 1..]
                    .find('\'')
                    .map_or(bytes.len(), |off| at + 1 + off);
                quoted.push(at + 1..close);
                at = (close + 1).min(bytes.len());
            }
            b'"' => {
                let mut close = at + 1;
                while close < bytes.len() && bytes[close] != b'"' {
                    close += if bytes[close] == b'\\' { 2 } else { 1 };
                }
                let close = close.min(bytes.len());
                quoted.push(at + 1..close);
                at = (close + 1).min(bytes.len());
            }
            b'\\' => at = (at + 2).min(bytes.len()),
            // A substitution belongs to the word around it; its body is
            // scanned as a command one level down.
            b'$' if bytes.get(at + 1) == Some(&b'(') => {
                let close = substitution_end(text, at + 2);
                quoted.push(at + 2..close);
                at = (close + 1).min(bytes.len());
            }
            b'<' | b'>' if starts_process_substitution(bytes, at) => {
                let close = substitution_end(text, at + 2);
                quoted.push(at + 2..close);
                at = (close + 1).min(bytes.len());
            }
            b'`' => {
                let close = backtick_end(bytes, at + 1);
                quoted.push(at + 1..close);
                at = (close + 1).min(bytes.len());
            }
            byte if ends_shell_word(byte) => break,
            _ => at += 1,
        }
    }
    // Stay on a character boundary after a backslash before a multibyte char.
    while !text.is_char_boundary(at) {
        at += 1;
    }
    at
}

/// A redirection operator at `start` (`<`, `>>`, `<<<`, `>&`, `&>`, `>|`,
/// `<<-`) and its target word, attached or after spaces, if one follows.
fn scan_redirect(
    text: &str,
    start: usize,
    quoted: &mut Vec<std::ops::Range<usize>>,
) -> (ShellToken, usize) {
    let bytes = text.as_bytes();
    let mut at = start + usize::from(bytes[start] == b'&');
    let mut arrows = 0;
    while arrows < 3 && matches!(bytes.get(at), Some(b'<' | b'>')) {
        at += 1;
        arrows += 1;
    }
    if matches!(bytes.get(at), Some(b'&' | b'|' | b'-')) {
        at += 1;
    }
    let mut target = at;
    while bytes.get(target).is_some_and(|byte| is_shell_blank(*byte)) {
        target += 1;
    }
    let starts_word = bytes
        .get(target)
        .is_some_and(|byte| !ends_shell_word(*byte));
    if starts_word {
        at = scan_shell_word(text, target, quoted);
    }
    (
        ShellToken {
            kind: ShellTokenKind::Redirect,
            range: start..at,
        },
        at,
    )
}

/// A shell word as the program sees it: quotes removed, escapes resolved.
fn unquote_shell_word(word: &str) -> String {
    let mut out = String::with_capacity(word.len());
    let mut chars = word.chars();
    let mut quote = None;
    while let Some(ch) = chars.next() {
        match (quote, ch) {
            (None, '\'' | '"') => quote = Some(ch),
            (Some(open), _) if ch == open => quote = None,
            (Some('\''), _) => out.push(ch),
            (_, '\\') => {
                if let Some(next) = chars.next() {
                    if next != '\n' {
                        out.push(next);
                    }
                }
            }
            _ => out.push(ch),
        }
    }
    out
}

/// Mask the passwords that curl (`-u`/`--user`), the MySQL family (`-p<pw>`)
/// and sshpass (`-p pw`) take on the command line, wherever those programs
/// run in `command`: after assignments or wrappers (`env`, `sudo`,
/// `command`), inside subshells and substitutions, across continuation
/// lines, and inside a quoted string handed to another shell.
fn mask_tool_passwords(command: &str) -> Cow<'_, str> {
    if !["curl", "mysql", "mariadb", "sshpass"]
        .iter()
        .any(|program| command.contains(program))
    {
        return Cow::Borrowed(command);
    }
    let mut masks = Vec::new();
    let scanned = crate::compress::generic::floor_char_boundary(
        command,
        command.len().min(MAX_SCANNED_COMMAND_BYTES),
    );
    collect_tool_password_masks(&command[..scanned], 0, 0, &mut masks);
    if scanned < command.len() {
        masks.push((scanned..command.len(), SECRET_PLACEHOLDER.to_string()));
    }
    if masks.is_empty() {
        return Cow::Borrowed(command);
    }
    masks.sort_by_key(|(range, _): &(std::ops::Range<usize>, String)| range.start);
    let mut out = String::with_capacity(command.len());
    let mut copied = 0;
    for (range, replacement) in masks {
        if range.start < copied {
            // Overlaps a span already replaced: drop the rest of this span
            // too, so no byte of either one is written out.
            copied = copied.max(range.end);
            continue;
        }
        out.push_str(&command[copied..range.start]);
        out.push_str(&replacement);
        copied = range.end;
    }
    out.push_str(&command[copied..]);
    if out == command {
        Cow::Borrowed(command)
    } else {
        Cow::Owned(out)
    }
}

#[cfg(any(test, feature = "test-support"))]
thread_local! {
    /// Bytes tokenized plus tokens visited by the tool-password scan, so a
    /// test can check the work stays linear in the command's length.
    static SHELL_SCAN_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    /// A test's step budget: exceeding it panics at once, so a superlinear
    /// scan fails quickly instead of running for hours on a large command.
    static SHELL_SCAN_BUDGET: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
}

#[cfg(any(test, feature = "test-support"))]
fn note_shell_scan_steps(steps: usize) {
    let total = SHELL_SCAN_STEPS.with(|count| {
        count.set(count.get().saturating_add(steps));
        count.get()
    });
    let budget = SHELL_SCAN_BUDGET.with(std::cell::Cell::get);
    assert!(
        total <= budget,
        "shell scan took {total} steps, over its budget of {budget}"
    );
}

#[cfg(not(any(test, feature = "test-support")))]
fn note_shell_scan_steps(_steps: usize) {}

/// Where sshpass's own options stand in one command.
#[derive(Clone, Copy, PartialEq, Eq)]
enum SshpassOptions {
    NotSeen,
    Reading,
    /// The next word is the value of `-f`, `-d` or `-P`.
    SkipValue,
    /// The next word is the password given to `-p`.
    PasswordNext,
    /// The wrapped command has started; its `-p` is not sshpass's.
    Done,
}

/// Find the tool passwords in `text` (one level of quoting) in a single pass
/// over each command's tokens, then in the quoted runs, at most
/// [`QUOTED_COMMAND_DEPTH`] levels down. Quoted runs at one level do not
/// overlap, so each byte is tokenized at most once per level.
fn collect_tool_password_masks(
    text: &str,
    base: usize,
    depth: usize,
    masks: &mut Vec<(std::ops::Range<usize>, String)>,
) {
    let (commands, quoted) = split_shell_commands(text);
    note_shell_scan_steps(1);
    let mut local = Vec::new();
    for tokens in &commands {
        note_shell_scan_steps(tokens.len());
        // A program's arguments run to the end of its command, as the
        // shell passes them; each program seen so far keeps reading them.
        let (mut curl, mut mysql) = (false, false);
        let mut curl_user_next = false;
        let mut sshpass = SshpassOptions::NotSeen;
        for token in tokens {
            if token.kind == ShellTokenKind::Redirect {
                // An option followed by a redirection has no value here.
                curl_user_next = false;
                if sshpass == SshpassOptions::PasswordNext || sshpass == SshpassOptions::SkipValue {
                    sshpass = SshpassOptions::Done;
                }
                continue;
            }
            let raw = &text[token.range.clone()];
            if curl_user_next {
                curl_user_next = false;
                if let Some(masked) = mask_curl_password(raw) {
                    local.push((token.range.clone(), masked));
                }
                continue;
            }
            match sshpass {
                SshpassOptions::PasswordNext => {
                    if !command_value_is_reference(raw) {
                        local.push((token.range.clone(), SECRET_PLACEHOLDER.to_string()));
                    }
                    sshpass = SshpassOptions::Done;
                    continue;
                }
                SshpassOptions::SkipValue => {
                    sshpass = SshpassOptions::Reading;
                    continue;
                }
                _ => {}
            }
            let plain = unquote_shell_word(raw);
            let program = plain.rsplit('/').next().unwrap_or_default();
            let program = program.strip_suffix(".exe").unwrap_or(program);
            let is_curl = program == "curl";
            let is_mysql = matches!(program, "mysql" | "mariadb" | "mysqladmin" | "mysqldump");
            if (is_curl || is_mysql) && sshpass == SshpassOptions::Reading {
                // The command sshpass wraps has started.
                sshpass = SshpassOptions::Done;
            }
            match program {
                _ if is_curl => {
                    curl = true;
                    continue;
                }
                _ if is_mysql => {
                    mysql = true;
                    continue;
                }
                "sshpass" => {
                    sshpass = SshpassOptions::Reading;
                    continue;
                }
                _ => {}
            }
            if curl {
                if plain == "-u" || plain == "--user" {
                    curl_user_next = true;
                    continue;
                }
                if plain.starts_with("--user=") {
                    curl_attached_mask(text, token, "--user=", &mut local);
                } else if plain.starts_with("-u") && !plain.starts_with("--") {
                    curl_attached_mask(text, token, "-u", &mut local);
                }
            }
            if mysql && plain.starts_with("-p") {
                mask_attached_password(text, token, "-p", &mut local);
            }
            if sshpass == SshpassOptions::Reading {
                sshpass = match plain.as_str() {
                    "-p" => SshpassOptions::PasswordNext,
                    "-f" | "-d" | "-P" => SshpassOptions::SkipValue,
                    _ if plain.starts_with("-p") => {
                        mask_attached_password(text, token, "-p", &mut local);
                        SshpassOptions::Done
                    }
                    _ if plain.starts_with('-') => SshpassOptions::Reading,
                    _ => SshpassOptions::Done,
                };
            }
        }
    }
    masks.extend(
        local
            .into_iter()
            .map(|(range, replacement)| (range.start + base..range.end + base, replacement)),
    );
    for inner in quoted {
        if depth < QUOTED_COMMAND_DEPTH {
            collect_tool_password_masks(&text[inner.clone()], base + inner.start, depth + 1, masks);
        } else if !inner.is_empty() {
            // Too deep to scan: mask the whole body instead of logging it
            // unscanned, so a credential nested past the limit never leaks.
            masks.push((
                base + inner.start..base + inner.end,
                SECRET_PLACEHOLDER.to_string(),
            ));
        }
    }
}

/// The value attached to an option word (`-uadmin:pw`, `--user=admin:pw`,
/// `-ppw`) after `prefix`, as a range of `text`, when the word starts with
/// the option as typed. A word whose option part is itself quoted
/// (`"-ppw"`) yields `None` and is masked whole by the caller.
fn attached_option_value(
    text: &str,
    token: &ShellToken,
    prefix: &str,
) -> Option<std::ops::Range<usize>> {
    let raw = &text[token.range.clone()];
    (raw.len() > prefix.len() && raw.starts_with(prefix))
        .then(|| token.range.start + prefix.len()..token.range.end)
}

/// Mask the password half of an attached curl user value. When the option
/// itself is quoted, the whole word becomes the placeholder: every byte that
/// stays in the log is then one the command really had.
fn curl_attached_mask(
    text: &str,
    token: &ShellToken,
    prefix: &str,
    masks: &mut Vec<(std::ops::Range<usize>, String)>,
) {
    match attached_option_value(text, token, prefix) {
        Some(range) => {
            if let Some(masked) = mask_curl_password(&text[range.clone()]) {
                masks.push((range, masked));
            }
        }
        None => {
            let plain = unquote_shell_word(&text[token.range.clone()]);
            let value = plain.strip_prefix(prefix).unwrap_or_default();
            if mask_curl_password(value).is_some() {
                masks.push((token.range.clone(), SECRET_PLACEHOLDER.to_string()));
            }
        }
    }
}

/// Push a placeholder over an attached option value unless it is a
/// reference; a quoted option word is masked whole.
fn mask_attached_password(
    text: &str,
    token: &ShellToken,
    prefix: &str,
    masks: &mut Vec<(std::ops::Range<usize>, String)>,
) {
    match attached_option_value(text, token, prefix) {
        Some(range) => {
            if !command_value_is_reference(&text[range.clone()]) {
                masks.push((range, SECRET_PLACEHOLDER.to_string()));
            }
        }
        None => {
            let plain = unquote_shell_word(&text[token.range.clone()]);
            let value = plain.strip_prefix(prefix).unwrap_or_default();
            if !command_value_is_reference(value) {
                masks.push((token.range.clone(), SECRET_PLACEHOLDER.to_string()));
            }
        }
    }
}

/// Mask what follows the first `:` of a `user:password` word, keeping the
/// user and a quote pair that wraps the whole word (`"admin:<masked>"`).
/// A word without a password, or whose password is a reference, is kept.
fn mask_curl_password(word: &str) -> Option<String> {
    let quote = word
        .chars()
        .next()
        .filter(|first| matches!(first, '"' | '\'') && word.len() > 1 && word.ends_with(*first));
    let body = match quote {
        Some(_) => &word[1..word.len() - 1],
        None => word,
    };
    let (user, password) = body.split_once(':')?;
    if command_value_is_reference(password) {
        return None;
    }
    let quote = quote.map(String::from).unwrap_or_default();
    Some(format!("{quote}{user}:{SECRET_PLACEHOLDER}{quote}"))
}

/// A value that names another value instead of holding one: a variable or
/// command substitution (`$GH_TOKEN`, `"$(gcloud secrets ...)"`), an empty
/// string, a placeholder this module already wrote, or the next option.
fn command_value_is_reference(value: &str) -> bool {
    let unquoted = value.trim_matches(|ch| ch == '"' || ch == '\'');
    unquoted.is_empty() || unquoted.starts_with(['$', '<', '-'])
}

/// Mask credentials typed inline in a shell command, for logs that quote the
/// command. Applies [`aft_redactor`] plus command-only shapes: secret-named
/// `NAME=value` assignments (including after `export` or `env`), credential
/// long options, MySQL's `-p<value>`, `sshpass -p` and `curl -u user:pass`.
/// Mask the whole command before shortening it for a log line: a token cut
/// short no longer matches its pattern.
pub fn redact_command(command: &str) -> Cow<'_, str> {
    // Runs first, on the command as typed: the shapes below write
    // placeholders that read as redirections to the shell-word scan.
    let mut out = mask_tool_passwords(command);
    let mapping = RangeMapping::Watch;
    if command.contains('=') {
        out = replace_in(
            out,
            None,
            &COMMAND_SECRET_ASSIGNMENT,
            |caps: &Captures<'_>| {
                let name = &caps[2];
                if command_value_is_reference(&caps[3])
                    || COMMAND_NON_SECRET_NAME_SUFFIXES
                        .iter()
                        .any(|suffix| name.ends_with(suffix))
                {
                    caps[0].to_string()
                } else {
                    format!("{}{name}{SECRET_PLACEHOLDER}", &caps[1])
                }
            },
            mapping,
        );
        out = replace_in(
            out,
            None,
            &INLINE_ASSIGNMENT,
            |caps: &Captures<'_>| {
                if looks_like_assignment_secret(caps[3].trim_matches(['\'', '"'])) {
                    masked_assignment(caps)
                } else {
                    caps[0].to_string()
                }
            },
            mapping,
        );
    }
    if command.contains("--") {
        out = replace_in(
            out,
            None,
            &COMMAND_SECRET_FLAG,
            |caps: &Captures<'_>| {
                if command_value_is_reference(&caps[3]) {
                    caps[0].to_string()
                } else {
                    format!("{}{}{SECRET_PLACEHOLDER}", &caps[1], &caps[2])
                }
            },
            mapping,
        );
    }
    match aft_redactor(&out) {
        Cow::Borrowed(_) => out,
        Cow::Owned(masked) => Cow::Owned(masked),
    }
}

// Separate limits bound byte scanning and expensive candidate hashes. Long
// non-hex verdict lines need no hashes and can still retain their placeholders.
pub const TICKET_REDACTION_BYTES: usize = 50 * 1024;
pub const TICKET_REDACTION_WINDOWS: usize = 8 * 1024;

// A 4 KiB range plus both 31-byte halos remains below the existing ticket
// scanner's byte and candidate budgets, including an all-hex source window.
const SHELL_TICKET_RANGE_BYTES: usize = 4 * 1024;

pub fn shells_ticket_range(
    text: &str,
    range: std::ops::Range<usize>,
    digest: Option<&str>,
) -> Result<String, TicketRedactionBudgetExceeded> {
    if digest.is_none() {
        return Ok(text[range].to_owned());
    }
    let mut output = String::new();
    let mut from = range.start;
    while from < range.end {
        let to = crate::compress::generic::floor_char_boundary(
            text,
            (from + SHELL_TICKET_RANGE_BYTES).min(range.end),
        );
        let start = crate::compress::generic::floor_char_boundary(
            text,
            from.saturating_sub(TICKET_HALO_BYTES),
        );
        let end = crate::compress::generic::ceil_char_boundary(
            text,
            (to + TICKET_HALO_BYTES).min(text.len()),
        );
        let source = &text[start..end];
        let mut low = (from - start)..(from - start);
        let mut high = (to - start)..(to - start);
        let masked = redact_ticket_digest_range(source, &mut low, digest)?;
        let _ = redact_ticket_digest_range(source, &mut high, digest)?;
        output.push_str(
            masked
                .get(low.end..high.end)
                .ok_or(TicketRedactionBudgetExceeded)?,
        );
        from = to;
    }
    Ok(output)
}
pub const TICKET_HALO_BYTES: usize = 31;

#[derive(Debug)]
pub struct TicketRedactionBudgetExceeded;

/// Redact only a 32-hex candidate whose BLAKE3 digest matches this task's stored
/// ticket digest. This keeps ordinary hashes and identifiers unchanged in previews.
pub fn redact_ticket_digest<'a>(
    text: &'a str,
    digest: Option<&str>,
) -> Result<Cow<'a, str>, TicketRedactionBudgetExceeded> {
    redact_ticket_digest_with_range(text, None, digest)
}

#[cfg(any(test, feature = "test-support"))]
thread_local! {
    pub static TICKET_HASH_PROBE: std::cell::RefCell<Option<Box<dyn FnMut()>>> = const { std::cell::RefCell::new(None) };
}

/// Range-aware form used when a watch match is anchored in captured output.
pub fn redact_ticket_digest_range<'a>(
    text: &'a str,
    range: &mut std::ops::Range<usize>,
    digest: Option<&str>,
) -> Result<Cow<'a, str>, TicketRedactionBudgetExceeded> {
    redact_ticket_digest_with_range(text, Some(range), digest)
}

fn redact_ticket_digest_with_range<'a>(
    text: &'a str,
    mut range: Option<&mut std::ops::Range<usize>>,
    digest: Option<&str>,
) -> Result<Cow<'a, str>, TicketRedactionBudgetExceeded> {
    let Some(digest) = digest else {
        return Ok(Cow::Borrowed(text));
    };
    if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Ok(Cow::Borrowed(text));
    }
    // Refuse before hashing any candidate. A caller must withhold the rendered
    // region rather than fall back to the unmasked input on budget exhaustion.
    if text.len() > TICKET_REDACTION_BYTES || ticket_digest_windows(text) > TICKET_REDACTION_WINDOWS
    {
        return Err(TicketRedactionBudgetExceeded);
    }
    let bytes = text.as_bytes();
    if bytes.len() < 32 {
        return Ok(Cow::Borrowed(text));
    }
    let mut spans: Vec<std::ops::Range<usize>> = Vec::new();
    let mut cursor = 0;
    while cursor < bytes.len() {
        if !bytes[cursor].is_ascii_hexdigit() {
            cursor += 1;
            continue;
        }
        let run_start = cursor;
        while cursor < bytes.len() && bytes[cursor].is_ascii_hexdigit() {
            cursor += 1;
        }
        let run_end = cursor;
        if run_end - run_start < 32 {
            continue;
        }
        for start in run_start..=(run_end - 32) {
            let end = start + 32;
            let candidate = &text[start..end];
            #[cfg(any(test, feature = "test-support"))]
            TICKET_HASH_PROBE.with(|probe| {
                if let Some(probe) = probe.borrow_mut().as_mut() {
                    probe();
                }
            });
            if blake3::hash(candidate.as_bytes()).to_hex().as_str() != digest {
                continue;
            }
            if let Some(previous) = spans.last_mut() {
                if start < previous.end {
                    previous.end = previous.end.max(end);
                    continue;
                }
            }
            spans.push(start..end);
        }
    }
    if spans.is_empty() {
        return Ok(Cow::Borrowed(text));
    }
    let mut masked = String::with_capacity(text.len());
    let mut copied = 0;
    for span in spans {
        masked.push_str(&text[copied..span.start]);
        let replacement_start = masked.len();
        masked.push_str(SECRET_PLACEHOLDER);
        if let Some(range) = range.as_deref_mut() {
            map_redacted_range(
                range,
                replacement_start,
                replacement_start + span.len(),
                SECRET_PLACEHOLDER.len(),
            );
        }
        copied = span.end;
    }
    masked.push_str(&text[copied..]);
    Ok(Cow::Owned(masked))
}

pub fn ticket_digest_windows(text: &str) -> usize {
    text.as_bytes()
        .split(|byte| !byte.is_ascii_hexdigit())
        .map(|run| run.len().saturating_sub(31))
        .sum()
}

#[derive(Clone, Copy)]
enum RangeMapping {
    Watch,
    Stream,
}

fn redact_with_range<'a>(
    text: &'a str,
    mut range: Option<&mut std::ops::Range<usize>>,
    mapping: RangeMapping,
) -> Cow<'a, str> {
    let mut out = Cow::Borrowed(text);
    if text.contains("PRIVATE KEY-----") {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &PRIVATE_KEY,
            SECRET_PLACEHOLDER,
            mapping,
        );
    }
    if text.contains("xox") {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &SLACK_TOKEN,
            SECRET_PLACEHOLDER,
            mapping,
        );
    }
    if contains_ignore_ascii_case(text, "x-api-key") {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &API_KEY_HEADER,
            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}", &caps[1]),
            mapping,
        );
    }
    if text.contains('"') {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &SECRET_JSON_FIELD,
            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}{}", &caps[1], &caps[3]),
            mapping,
        );
    }
    if contains_ignore_ascii_case(text, "secret_access_key") {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &AWS_SECRET_FIELD,
            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}", &caps[1]),
            mapping,
        );
    }
    if contains_ignore_ascii_case(text, "authorization") {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &AUTHORIZATION_HEADER,
            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}", &caps[1]),
            mapping,
        );
    }
    if text.contains("github_pat_") {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &GITHUB_PAT,
            SECRET_PLACEHOLDER,
            mapping,
        );
    }
    if needs_github_token_scan(text) {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &GITHUB_TOKEN,
            SECRET_PLACEHOLDER,
            mapping,
        );
    }
    if text.contains("sk-") {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &SK_API_KEY,
            SECRET_PLACEHOLDER,
            mapping,
        );
    }
    if text.contains("eyJ") {
        out = replace_in(out, range.as_deref_mut(), &JWT, SECRET_PLACEHOLDER, mapping);
    }
    if ["AKIA", "ASIA", "AGPA", "AIDA", "AROA"]
        .iter()
        .any(|prefix| text.contains(prefix))
    {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &AWS_ACCESS_KEY_ID,
            SECRET_PLACEHOLDER,
            mapping,
        );
    }
    if text.contains("://") {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &URL_USERINFO,
            |caps: &Captures<'_>| format!("{}{URL_CREDENTIAL_PLACEHOLDER}@", &caps[1]),
            mapping,
        );
    }
    if text.contains('=') && (text.contains('?') || text.contains('&')) {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &CREDENTIAL_QUERY,
            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}", &caps[1]),
            mapping,
        );
        out = replace_in(
            out,
            range.as_deref_mut(),
            &KEY_QUERY,
            |caps: &Captures<'_>| {
                if looks_like_secret(&caps[2]) {
                    format!("{}{SECRET_PLACEHOLDER}", &caps[1])
                } else {
                    caps[0].to_string()
                }
            },
            mapping,
        );
    }
    if text.contains('=') {
        out = replace_in(
            out,
            range.as_deref_mut(),
            &SHORT_PASSWORD_ASSIGNMENT,
            |caps: &Captures<'_>| {
                let raw = &caps[3];
                let value = raw.trim_matches(['\'', '"']);
                if is_short_password_name(&caps[2]) && !value.starts_with(['$', '<']) {
                    masked_assignment(caps)
                } else {
                    caps[0].to_string()
                }
            },
            mapping,
        );
    }
    out
}

fn masked_assignment(caps: &Captures<'_>) -> String {
    let raw = &caps[3];
    let quote = if raw.starts_with(['\'', '"']) {
        &raw[..1]
    } else {
        ""
    };
    format!("{}{quote}{SECRET_PLACEHOLDER}{quote}", &caps[1])
}

fn is_short_password_name(key: &str) -> bool {
    let suffix = key.rsplit('_').next().unwrap_or(key);
    suffix.eq_ignore_ascii_case("PW") || suffix.eq_ignore_ascii_case("PASS")
}

/// A command's credential values, retained only with its live in-memory task.
/// Deliberately has no Debug or serialization implementation.
#[derive(Default)]
pub struct SecretValues(Vec<String>);

/// Whether an environment variable name marks its value as a completion secret.
pub fn is_secret_environment_key(key: &str) -> bool {
    if key.eq_ignore_ascii_case(crate::gh_shim_paths::GH_SHIM_TICKET_ENV) {
        return true;
    }
    // The SSH agent's socket path is an address, not credential material.
    if key.eq_ignore_ascii_case("SSH_AUTH_SOCK") {
        return false;
    }
    // Git's numbered config variables carry a setting NAME in GIT_CONFIG_KEY_<n>
    // (AFT itself injects core.hooksPath this way). The name is not a secret,
    // and dropping it alone while GIT_CONFIG_COUNT and GIT_CONFIG_VALUE_<n>
    // stay makes every git child exit with "missing config key".
    if key
        .get(.."GIT_CONFIG_KEY_".len())
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("GIT_CONFIG_KEY_"))
    {
        return false;
    }
    ["TOKEN", "SECRET", "KEY", "PASSWORD", "PASSWD", "CREDENTIAL"]
        .iter()
        .any(|part| contains_ignore_ascii_case(key, part))
        || is_short_password_name(key)
        || names_auth(key)
}

/// Whether `key` contains "AUTH" other than as the word AUTHOR, which names a
/// person rather than a credential: GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
/// AFT_GIT_CO_AUTHOR, the co-author trailer AFT itself gives every governed
/// child. Counting those made every such child look like it carried a secret,
/// so its output previews were withheld after a daemon restart. AUTHOR counts
/// as a word only at the end of the name or before an underscore; AUTHORITY,
/// AUTHORIZATION, AUTH_TOKEN and NPM_AUTH still count.
fn names_auth(key: &str) -> bool {
    let key = key.as_bytes();
    (0..key.len()).any(|at| {
        let rest = &key[at..];
        if rest.len() < 4 || !rest[..4].eq_ignore_ascii_case(b"AUTH") {
            return false;
        }
        let author_word = rest.len() >= 6
            && rest[4..6].eq_ignore_ascii_case(b"OR")
            && matches!(rest.get(6), None | Some(b'_'));
        !author_word
    })
}

impl SecretValues {
    pub fn longest_value_len(&self) -> usize {
        self.0.iter().map(String::len).max().unwrap_or(0)
    }
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
    /// Whether a value contains a newline, so it can cross a cut made at one.
    pub fn has_multiline_value(&self) -> bool {
        self.0.iter().any(|value| value.contains('\n'))
    }

    /// Byte ranges in `text` of every occurrence of a value that contains a
    /// newline. Only these occurrences can cross a cut made at a newline.
    pub fn cross_line_spans(&self, text: &str) -> Vec<std::ops::Range<usize>> {
        let mut spans = Vec::new();
        for value in self.0.iter().filter(|value| value.contains('\n')) {
            let mut start = 0;
            while let Some(offset) = text[start..].find(value.as_str()) {
                let from = start + offset;
                spans.push(from..from + value.len());
                start = from + text[from..].chars().next().unwrap().len_utf8();
            }
        }
        spans
    }

    pub fn from_environment<'a>(
        env: impl IntoIterator<Item = (&'a std::ffi::OsStr, &'a std::ffi::OsStr)>,
    ) -> Self {
        let mut values = Vec::new();
        for (key, value) in env {
            let (Some(key), Some(value)) = (key.to_str(), value.to_str()) else {
                continue;
            };
            if value.chars().count() >= 8 && is_secret_environment_key(key) {
                values.push(value.to_owned());
            }
        }
        values.sort_unstable_by_key(|value| std::cmp::Reverse(value.len()));
        values.dedup();
        Self(values)
    }

    pub fn redact<'a>(&self, text: &'a str) -> Cow<'a, str> {
        self.redact_range(text, None)
    }

    pub fn redact_range<'a>(
        &self,
        text: &'a str,
        range: Option<&mut std::ops::Range<usize>>,
    ) -> Cow<'a, str> {
        self.redact_range_with_mapping(text, range, RangeMapping::Watch)
    }

    pub fn redact_stream_range<'a>(
        &self,
        text: &'a str,
        range: &mut std::ops::Range<usize>,
    ) -> Cow<'a, str> {
        self.redact_range_with_mapping(text, Some(range), RangeMapping::Stream)
    }

    fn redact_range_with_mapping<'a>(
        &self,
        text: &'a str,
        mut range: Option<&mut std::ops::Range<usize>>,
        mapping: RangeMapping,
    ) -> Cow<'a, str> {
        // Exact matches run first: a format-based replacement inside an opaque
        // value must not leave the rest of that value visible.
        let mut spans = Vec::new();
        for value in &self.0 {
            let mut start = 0;
            while let Some(offset) = text[start..].find(value) {
                let from = start + offset;
                spans.push((from, from + value.len()));
                start = from + text[from..].chars().next().unwrap().len_utf8();
            }
        }
        let out = if spans.is_empty() {
            Cow::Borrowed(text)
        } else {
            spans.sort_unstable();
            let mut masked = String::new();
            let mut copied = 0;
            let mut spans = spans.into_iter().peekable();
            while let Some((start, mut end)) = spans.next() {
                while spans.peek().is_some_and(|(next, _)| *next <= end) {
                    end = end.max(spans.next().unwrap().1);
                }
                masked.push_str(&text[copied..start]);
                if let Some(range) = range.as_deref_mut() {
                    match mapping {
                        RangeMapping::Watch => map_redacted_range(
                            range,
                            masked.len(),
                            masked.len() + end - start,
                            SECRET_PLACEHOLDER.len(),
                        ),
                        RangeMapping::Stream => map_stream_range(
                            range,
                            masked.len(),
                            masked.len() + end - start,
                            SECRET_PLACEHOLDER.len(),
                        ),
                    }
                }
                masked.push_str(SECRET_PLACEHOLDER);
                copied = end;
            }
            masked.push_str(&text[copied..]);
            Cow::Owned(masked)
        };
        match redact_with_range(&out, range, mapping) {
            Cow::Borrowed(_) => out,
            Cow::Owned(masked) => Cow::Owned(masked),
        }
    }
}

fn needs_github_token_scan(text: &str) -> bool {
    ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"]
        .iter()
        .any(|prefix| text.contains(prefix))
}

// How far a match can reach. A caller that masks a slice of a larger capture
// (a watch preview) cuts that slice at newlines. The cut is safe for a pattern
// only if none of its matches can contain a newline:
// - AUTHORIZATION_HEADER, API_KEY_HEADER and AWS_SECRET_FIELD separate their
//   parts with `[^\S\r\n]` (spaces and tabs only) and their values exclude `\s`;
// - SLACK_TOKEN, GITHUB_PAT, GITHUB_TOKEN, SK_API_KEY, JWT and
//   AWS_ACCESS_KEY_ID consist of letters, digits, `_`, `-` and `.` only;
// - URL_USERINFO, CREDENTIAL_QUERY and KEY_QUERY values exclude `\s`.
// Two patterns can cross a newline, and the functions below report them:
// - SECRET_JSON_FIELD allows `\s*` (including newlines) around its colon and a
//   raw newline inside the quoted value;
// - PRIVATE_KEY (`(?s)`) runs from its BEGIN line to the END line, or to the end
//   of the text when no END line follows.
// Exact credential values (see SecretValues) cross a newline only when the
// value itself contains one.

/// Byte ranges of the masked JSON secret fields in `text`. A field can span
/// lines, so a slice cut at a newline may hold only part of one.
pub fn json_secret_field_spans(text: &str) -> Vec<std::ops::Range<usize>> {
    if !text.contains('"') {
        return Vec::new();
    }
    SECRET_JSON_FIELD
        .find_iter(text)
        .map(|found| found.range())
        .collect()
}

/// Byte ranges of the masked private-key blocks in `text`. A block ends at its
/// END line or, without one, at the end of `text`.
pub fn private_key_spans(text: &str) -> Vec<std::ops::Range<usize>> {
    if !text.contains("PRIVATE KEY-----") {
        return Vec::new();
    }
    PRIVATE_KEY
        .find_iter(text)
        .map(|found| found.range())
        .collect()
}

/// Whether `text` holds a private-key BEGIN or END line. Without one, `text`
/// alone cannot tell whether it starts inside a key block.
pub fn has_private_key_marker(text: &str) -> bool {
    text.contains("PRIVATE KEY-----")
}

/// Whether `line` has the shape of a PEM private-key body line: 40 to 76
/// base64 characters mixing upper case, lower case and digits. Lower-case hex
/// digests and ordinary words do not qualify; a mixed-case hex string can.
pub fn looks_like_private_key_body(line: &str) -> bool {
    let line = line.trim_end_matches('\r');
    (40..=76).contains(&line.len())
        && line
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'='))
        && line.bytes().any(|byte| byte.is_ascii_uppercase())
        && line.bytes().any(|byte| byte.is_ascii_lowercase())
        && line.bytes().any(|byte| byte.is_ascii_digit())
}

/// Whether a JSON secret value that opens before byte `before` is still open
/// at the end of `text`. Its closing quote, and so the match, may lie past the
/// end of `text`; masking `text` alone would then show the value.
pub fn json_secret_value_open_at_end(text: &str, before: usize) -> bool {
    if !text.contains('"') {
        return false;
    }
    SECRET_JSON_OPENING
        .find_iter(text)
        .take_while(|opening| opening.start() < before)
        .any(|opening| {
            // Mirror the value grammar `(?:\\.|[^"\\])+`: a backslash escapes
            // any character except a newline, and an unescaped quote closes it.
            let mut chars = text[opening.end()..].chars();
            loop {
                match chars.next() {
                    None => return true,
                    Some('"') => return false,
                    Some('\\') => match chars.next() {
                        None => return true,
                        Some('\n') => return false,
                        Some(_) => {}
                    },
                    Some(_) => {}
                }
            }
        })
}

static SECRET_JSON_LABEL_AT_END: LazyLock<Regex> =
    LazyLock::new(|| compile(&format!(r#"(?i)"(?:{JSON_SECRET_LABELS})"\s*(?::\s*)?\z"#)));

/// Whether `text` ends after a JSON secret field's label (and possibly its
/// colon) but before the opening quote of its value. The value, and so the
/// [`SECRET_JSON_FIELD`] match, would start past the end of `text`.
pub fn json_secret_label_open_at_end(text: &str) -> bool {
    text.contains('"') && SECRET_JSON_LABEL_AT_END.is_match(text)
}

/// Byte-level entry point for the log sink. Invalid UTF-8 is decoded with
/// replacement characters before masking so malformed bytes cannot bypass it.
pub fn aft_redact_bytes(bytes: &[u8]) -> Cow<'_, [u8]> {
    let Ok(text) = std::str::from_utf8(bytes) else {
        return Cow::Owned(
            aft_redactor(&String::from_utf8_lossy(bytes))
                .into_owned()
                .into_bytes(),
        );
    };
    match aft_redactor(text) {
        Cow::Borrowed(_) => Cow::Borrowed(bytes),
        Cow::Owned(masked) => Cow::Owned(masked.into_bytes()),
    }
}

/// Cut `text` to at most `max_bytes` (on a char boundary) and note how much
/// was dropped as `…(+N bytes)`. Used for payloads that are useful to glimpse
/// in a debug line but can be arbitrarily large (LSP params, parser errors).
pub fn truncate_for_log(text: &str, max_bytes: usize) -> Cow<'_, str> {
    if text.len() <= max_bytes {
        return Cow::Borrowed(text);
    }
    let mut cut = max_bytes;
    while !text.is_char_boundary(cut) {
        cut -= 1;
    }
    Cow::Owned(format!("{}…(+{} bytes)", &text[..cut], text.len() - cut))
}

/// Describe a request line that must not itself be logged: its byte length and
/// a short SHA-256 prefix, enough to correlate with a copy the caller kept.
pub fn unlogged_input_summary(input: &str) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(input.as_bytes());
    let short: String = digest[..6]
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    format!("bytes={} sha256={short}", input.len())
}

/// A `key=` value is treated as a secret when it is long, uses only
/// token-safe characters, and mixes digits with upper- and lower-case letters
/// (an API key such as `AIzaSy…`). Words, paths and single-case hex hashes do
/// not qualify.
fn looks_like_secret(value: &str) -> bool {
    value.len() >= KEY_VALUE_MIN_SECRET_LEN
        && value
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || "_-.~+/=".contains(ch))
        && value.chars().any(|ch| ch.is_ascii_digit())
        && value.chars().any(|ch| ch.is_ascii_uppercase())
        && value.chars().any(|ch| ch.is_ascii_lowercase())
}

/// Paths and URLs in command assignments are useful diagnostics, not tokens.
/// Keep this rule identical to the CLI sanitizer. Query keys instead use
/// [`looks_like_secret`] without the path-prefix exclusions.
fn looks_like_assignment_secret(value: &str) -> bool {
    !["/", "~/", "./", "../"]
        .iter()
        .any(|prefix| value.starts_with(prefix))
        && !value.contains("://")
        && looks_like_secret(value)
}

fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
    haystack
        .as_bytes()
        .windows(needle.len())
        .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
}

/// Apply one pattern, keeping the borrowed input when nothing changed. A match
/// can re-produce its own text (an already-masked `***@`, or a `key=` value
/// that does not look secret), so equality is checked, not just match count.
fn replace_in<'a, R: Replacer>(
    text: Cow<'a, str>,
    mut range: Option<&mut std::ops::Range<usize>>,
    pattern: &Regex,
    mut replacer: R,
    mapping: RangeMapping,
) -> Cow<'a, str> {
    // Capture storage is allocated by replace_all even when it finds no match.
    // Keep the overwhelmingly common no-secret path allocation-free.
    if !pattern.is_match(&text) {
        return text;
    }
    let mut masked = String::new();
    let mut copied = 0;
    for caps in pattern.captures_iter(&text) {
        let found = caps.get(0).unwrap();
        masked.push_str(&text[copied..found.start()]);
        let from = masked.len();
        replacer.replace_append(&caps, &mut masked);
        if masked[from..] != *found.as_str() {
            if let Some(range) = range.as_deref_mut() {
                match mapping {
                    RangeMapping::Watch => {
                        map_redacted_range(range, from, from + found.len(), masked.len() - from)
                    }
                    RangeMapping::Stream => {
                        let before = found.as_str();
                        let after = &masked[from..];
                        let prefix = before
                            .chars()
                            .zip(after.chars())
                            .take_while(|(a, b)| a == b)
                            .map(|(ch, _)| ch.len_utf8())
                            .sum::<usize>();
                        let suffix = before[prefix..]
                            .chars()
                            .rev()
                            .zip(after[prefix..].chars().rev())
                            .take_while(|(a, b)| a == b)
                            .map(|(ch, _)| ch.len_utf8())
                            .sum::<usize>();
                        map_stream_range(
                            range,
                            from + prefix,
                            from + before.len() - suffix,
                            after.len() - prefix - suffix,
                        );
                    }
                }
            }
        }
        copied = found.end();
    }
    masked.push_str(&text[copied..]);
    if masked == *text {
        text
    } else {
        Cow::Owned(masked)
    }
}

/// Assign a replacement to the raw range containing its first changed byte.
/// Unchanged prefix and suffix bytes keep their original stream positions.
fn map_stream_range(
    range: &mut std::ops::Range<usize>,
    from: usize,
    to: usize,
    replacement_len: usize,
) {
    let position = |at: usize| {
        if at <= from {
            at
        } else if at >= to {
            at - (to - from) + replacement_len
        } else {
            from + replacement_len
        }
    };
    range.start = position(range.start);
    range.end = position(range.end);
}

/// Keep a watch's raw match anchored when a replacement changes byte lengths.
/// A match touching a secret expands to cover the entire visible placeholder.
fn map_redacted_range(
    range: &mut std::ops::Range<usize>,
    from: usize,
    to: usize,
    replacement_len: usize,
) {
    let shift = |position: usize| {
        position
            .saturating_sub(to - from)
            .saturating_add(replacement_len)
    };
    if range.start >= to {
        range.start = shift(range.start);
        range.end = shift(range.end);
    } else if range.end > from {
        range.start = range.start.min(from);
        range.end = if range.end >= to {
            shift(range.end)
        } else {
            from + replacement_len
        };
    }
}

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

    #[test]
    fn only_json_fields_and_private_keys_match_across_a_newline() {
        let line_anchored: [(&str, &Regex); 14] = [
            ("AUTHORIZATION_HEADER", &AUTHORIZATION_HEADER),
            ("API_KEY_HEADER", &API_KEY_HEADER),
            ("AWS_SECRET_FIELD", &AWS_SECRET_FIELD),
            ("SLACK_TOKEN", &SLACK_TOKEN),
            ("GITHUB_PAT", &GITHUB_PAT),
            ("GITHUB_TOKEN", &GITHUB_TOKEN),
            ("SK_API_KEY", &SK_API_KEY),
            ("JWT", &JWT),
            ("AWS_ACCESS_KEY_ID", &AWS_ACCESS_KEY_ID),
            ("URL_USERINFO", &URL_USERINFO),
            ("CREDENTIAL_QUERY", &CREDENTIAL_QUERY),
            ("KEY_QUERY", &KEY_QUERY),
            ("INLINE_ASSIGNMENT", &INLINE_ASSIGNMENT),
            ("SHORT_PASSWORD_ASSIGNMENT", &SHORT_PASSWORD_ASSIGNMENT),
        ];
        let samples = [
            "Authorization: Bearer opaque-auth-value".to_string(),
            "Proxy-Authorization:\tBasic dXNlcjpwYXNz==".to_string(),
            "x-api-key: opaque-api-key-value".to_string(),
            "aws_secret_access_key = abc/def+ghi".to_string(),
            "xoxb-12345-slack-token".to_string(),
            "github_pat_11ABCDEFG0123456789_abcdef".to_string(),
            format!("ghp_{}", "a".repeat(36)),
            "sk-abcdefghijklmnopqrstuvwxyz0123456789".to_string(),
            "eyJhbGciOi.eyJzdWIiOi.c2lnbmF0dXJl".to_string(),
            "AKIAABCDEFGHIJKLMNOP".to_string(),
            "https://user:password@example.com/path".to_string(),
            "https://e.com/p?access_token=opaque&key=AbCdEfGh12345678Zz".to_string(),
            "PW=opaque X=\"AbCdEfGh12345678Zz\"".to_string(),
        ];
        for sample in &samples {
            for (cut, _) in sample.char_indices().skip(1) {
                let text = format!("{}\n{}", &sample[..cut], &sample[cut..]);
                for (name, pattern) in line_anchored {
                    for found in pattern.find_iter(&text) {
                        assert!(
                            !found.as_str().contains('\n'),
                            "{name} crossed a newline in {text:?}"
                        );
                    }
                }
            }
        }
        // The two exceptions, which watch previews widen their region for.
        assert!(SECRET_JSON_FIELD.is_match("{\"api_key\":\n  \"value\"}"));
        assert!(SECRET_JSON_FIELD.is_match("{\"api_key\":\"first\nsecond\"}"));
        assert!(PRIVATE_KEY.is_match("-----BEGIN PRIVATE KEY-----\nbody\n"));
    }

    #[test]
    fn json_secret_value_open_at_end_follows_the_value_grammar() {
        let opening = "{\"api_key\": \"";
        let open = |text: &str| json_secret_value_open_at_end(text, text.len());
        assert!(open(&format!("{opening}abc\ndef")));
        assert!(open(&format!("{opening}abc\\")));
        assert!(!open(&format!("{opening}abc\\\"def\" more")));
        // A backslash before a newline ends the value without a match.
        assert!(!open(&format!("{opening}abc\\\ndef")));
        // Openings at or after `before` are outside the caller's region.
        assert!(!json_secret_value_open_at_end(
            &format!("x {opening}abc"),
            1
        ));
    }

    #[test]
    fn ticket_digest_budget_refuses_before_hashing() {
        let digest = blake3::hash(b"0123456789abcdef0123456789abcdef")
            .to_hex()
            .to_string();
        TICKET_HASH_PROBE.with(|probe| {
            *probe.borrow_mut() = Some(Box::new(|| panic!("over-budget input was hashed")))
        });
        assert!(
            redact_ticket_digest(&"a".repeat(TICKET_REDACTION_WINDOWS + 32), Some(&digest))
                .is_err()
        );
        TICKET_HASH_PROBE.with(|probe| *probe.borrow_mut() = None);
    }

    #[test]
    fn ticket_digest_hashes_only_complete_hex_windows() {
        let digest = blake3::hash(b"0123456789abcdef0123456789abcdef")
            .to_hex()
            .to_string();
        let count = std::rc::Rc::new(std::cell::Cell::new(0));
        let probe_count = count.clone();
        TICKET_HASH_PROBE.with(|probe| {
            *probe.borrow_mut() = Some(Box::new(move || probe_count.set(probe_count.get() + 1)))
        });
        let text = format!(
            "{} {} {} {}",
            "a".repeat(31),
            "g".repeat(1024),
            "a".repeat(32),
            "F".repeat(33)
        );
        assert_eq!(redact_ticket_digest(&text, Some(&digest)).unwrap(), text);
        TICKET_HASH_PROBE.with(|probe| *probe.borrow_mut() = None);
        assert_eq!(count.get(), 3);
    }

    #[test]
    fn completion_exact_env_values_are_case_sensitive_and_overlap_safe() {
        let environment = [
            ("DEPLOY_tOkEn", "abcdefgh"),
            ("MY_SECRET", "fghijklm"),
            ("api_KEY", "key-value-long"),
            ("PASSWORD", "password-value"),
            ("PASSWD", "passwd-value"),
            ("CREDENTIALS", "credential-value"),
            ("AUTHORIZATION", "auth-value"),
            ("tiny_TOKEN", "short"),
            ("NORMAL_VALUE", "public-value"),
        ];
        let secrets = SecretValues::from_environment(
            environment
                .iter()
                .map(|(key, value)| (std::ffi::OsStr::new(key), std::ffi::OsStr::new(value))),
        );
        assert_eq!(
            secrets.redact("abcdefghijklm/abcdefgh"),
            format!("{SECRET_PLACEHOLDER}/{SECRET_PLACEHOLDER}")
        );
        for (_, value) in &environment[..7] {
            assert_eq!(
                secrets.redact(&format!("before{value}after")),
                format!("before{SECRET_PLACEHOLDER}after")
            );
        }
        assert!(matches!(
            secrets.redact("ABCDEFGH short public-value"),
            Cow::Borrowed(_)
        ));
    }

    #[test]
    fn short_password_environment_names_do_not_include_pwd_or_bypass() {
        for key in ["PW", "PASS", "DB_PW", "DB_PASS", "db_pw", "db_pass"] {
            assert!(is_secret_environment_key(key), "missed {key}");
        }
        for key in ["PWD", "BYPASS", "COMPASS"] {
            assert!(!is_secret_environment_key(key), "mangled {key}");
        }
    }

    #[test]
    fn completion_non_secret_corpus_stays_borrowed() {
        for text in [
            "running 42 tests\ntest task::sk-settings ... ok\ntest result: ok. 42 passed; 0 failed\n",
            "commit 0f78c1bcb3ab4d501d6ebc491617b097416f9138\nAuthor: Example <user@example.com>\n    add task-settings\n",
            "added 42 packages, and audited 128 packages in 2s\n12 packages are looking for funding\nfound 0 vulnerabilities\n",
            "request 550e8400-e29b-41d4-a716-446655440000 fixture SGVsbG8gd29ybGQhYWJjZGVmZ2g=\n",
            "sk-settings sk-something sk-words docs say sk- is a prefix; https://example.com/path\n",
        ] {
            assert!(matches!(SecretValues::default().redact(text), Cow::Borrowed(_)), "mangled: {text}");
        }
    }

    #[test]
    fn completion_64k_noop_is_allocation_free() {
        let mut text = "running 42 tests\ntest task::sk-settings ... ok\n{\"status\":\"ok\"}\nhttps://example.com/path\n".repeat(1024);
        text.truncate(64 * 1024);
        let secrets = SecretValues::default();
        let _ = secrets.redact(&text); // Initialize regex automata outside the measurement.
        let start = std::time::Instant::now();
        let (out, allocations) = crate::test_allocations::count(|| secrets.redact(&text));
        assert!(matches!(out, Cow::Borrowed(_)));
        assert_eq!(allocations, 0);
        eprintln!(
            "64 KiB completion redaction: {:?}, {allocations} allocations",
            start.elapsed()
        );
    }
    #[test]
    fn github_prefilter_only_scans_actual_token_prefixes() {
        for ordinary in [
            "high throughput",
            "right path",
            "bright light",
            "github repository",
        ] {
            assert!(
                !super::needs_github_token_scan(ordinary),
                "unnecessary scan: {ordinary}"
            );
        }
        for prefix in ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"] {
            let token = format!("{prefix}1234567890abcdefghij");
            assert!(super::needs_github_token_scan(&token));
            assert_eq!(super::aft_redactor(&token), super::SECRET_PLACEHOLDER);
        }
    }

    #[derive(serde::Deserialize)]
    struct Fixture {
        masked: Vec<MaskedCase>,
        untouched: Vec<String>,
        command_masked: Vec<MaskedCase>,
        command_untouched: Vec<String>,
    }

    #[derive(serde::Deserialize)]
    struct MaskedCase {
        input: String,
        expected: String,
    }

    #[derive(serde::Deserialize)]
    struct CommandFixture {
        masked: Vec<MaskedCase>,
        untouched: Vec<String>,
    }

    /// Credentials typed inline in shell commands are masked, and none of the
    /// ordinary commands beside them change: the untouched list holds every
    /// command line from this repository's scripts, workflows and package.json
    /// scripts plus common cargo, git, npm, ssh and docker invocations.
    #[test]
    fn command_credentials_are_masked_without_touching_ordinary_commands() {
        let fixture: CommandFixture = serde_json::from_str(include_str!(
            "../../aft/tests/fixtures/command_redaction_cases.json"
        ))
        .expect("command redaction fixture parses");
        assert_eq!(fixture.masked.len(), 119);
        assert!(fixture.untouched.len() > 800);
        for case in &fixture.masked {
            let masked = redact_command(&case.input);
            assert_eq!(masked, case.expected, "input: {}", case.input);
            assert_eq!(redact_command(&masked), masked, "not idempotent");
        }
        // A few corpus lines hold URL userinfo (`ssh://git@host`), which the
        // shared log patterns already mask in every log line. The command
        // shapes themselves must change nothing.
        let mangled: Vec<_> = fixture
            .untouched
            .iter()
            .filter(|command| redact_command(command) != aft_redactor(command))
            .map(|command| format!("{command} -> {}", redact_command(command)))
            .collect();
        assert!(mangled.is_empty(), "{}", mangled.join("\n"));
    }

    /// The curl, MySQL and sshpass rules as they were before commands were
    /// read as shell words: the span ran to the first `;`, `&`, `|` or
    /// newline, quoted or not.
    fn line_pattern_tool_passwords(command: &str) -> String {
        static PATTERNS: LazyLock<[Regex; 4]> = LazyLock::new(|| {
            [
                compile(r"\bcurl\b[^;&|\n]*"),
                compile(concat!(
                    r"(^|\s)(-u[ \t]*|--user(?:=|[ \t]+))(",
                    shell_word!(),
                    ")"
                )),
                compile(concat!(
                    r"\b((?:mysql|mariadb|mysqladmin|mysqldump)\b[^;&|\n]*?\s-p)(",
                    shell_word!(),
                    ")"
                )),
                compile(concat!(r"\b(sshpass[ \t]+-p[ \t]*)(", shell_word!(), ")")),
            ]
        });
        let [segment, user_option, mysql, sshpass] = &*PATTERNS;
        let out = segment.replace_all(command, |segment: &Captures<'_>| {
            user_option
                .replace_all(
                    &segment[0],
                    |caps: &Captures<'_>| match mask_curl_password(&caps[3]) {
                        Some(masked) => format!("{}{}{masked}", &caps[1], &caps[2]),
                        None => caps[0].to_string(),
                    },
                )
                .into_owned()
        });
        let mut out = out.into_owned();
        for pattern in [mysql, sshpass] {
            out = pattern
                .replace_all(&out, |caps: &Captures<'_>| {
                    if command_value_is_reference(&caps[2]) {
                        caps[0].to_string()
                    } else {
                        format!("{}{SECRET_PLACEHOLDER}", &caps[1])
                    }
                })
                .into_owned();
        }
        out
    }

    /// Reading commands as shell words must not lose a password the earlier
    /// line patterns caught: on every fixture command, each placeholder the
    /// line patterns wrote is also written by the shell-word scan, at the
    /// same place.
    #[test]
    fn shell_word_scan_masks_everything_the_line_patterns_did() {
        let fixture: CommandFixture = serde_json::from_str(include_str!(
            "../../aft/tests/fixtures/command_redaction_cases.json"
        ))
        .expect("command redaction fixture parses");
        let mut compared = 0;
        let mut lost = Vec::new();
        for command in fixture
            .masked
            .iter()
            .map(|case| &case.input)
            .chain(&fixture.untouched)
        {
            let legacy = line_pattern_tool_passwords(command);
            if legacy == *command {
                continue;
            }
            compared += 1;
            let scanned = mask_tool_passwords(command);
            // Every byte the line patterns masked must be masked by the scan
            // too: each of their masked spans lies inside one of the scan's.
            let legacy_spans = masked_ranges(command, &legacy).expect("line patterns only mask");
            let scanned_spans = masked_ranges(command, &scanned).expect("scan only masks");
            for span in legacy_spans {
                if !scanned_spans
                    .iter()
                    .any(|scanned| scanned.start <= span.start && span.end <= scanned.end)
                {
                    lost.push(format!(
                        "{command:?}\n  line patterns: {legacy}\n  shell words:   {scanned}"
                    ));
                }
            }
        }
        assert!(lost.is_empty(), "{}", lost.join("\n"));
        eprintln!("{compared} fixture commands masked by the line patterns; none lost");
        assert!(compared > 40, "{compared}");
    }

    /// Whether `output` is `input` with some spans replaced by placeholders
    /// and every other byte unchanged and in order.
    fn only_placeholders_changed(input: &str, output: &str) -> bool {
        masked_ranges(input, output).is_some()
    }

    /// The spans of `input` that `output` replaced with placeholders, if
    /// `output` is `input` with only such replacements (each other piece
    /// matched at its earliest place).
    fn masked_ranges(input: &str, output: &str) -> Option<Vec<std::ops::Range<usize>>> {
        // Split `output` at its placeholders. Each placeholder's next
        // occurrence is searched for only after the previous one is passed,
        // so splitting a megabyte output stays linear.
        let placeholders = [SECRET_PLACEHOLDER, URL_CREDENTIAL_PLACEHOLDER];
        let find_from =
            |from: usize, placeholder: &str| output[from..].find(placeholder).map(|at| from + at);
        let mut next: Vec<Option<usize>> = placeholders
            .iter()
            .map(|placeholder| find_from(0, placeholder))
            .collect();
        let mut pieces = Vec::new();
        let mut copied = 0;
        loop {
            let nearest = next
                .iter()
                .enumerate()
                .filter_map(|(index, at)| at.map(|at| (at, index)))
                .min();
            let Some((at, index)) = nearest else {
                pieces.push(&output[copied..]);
                break;
            };
            pieces.push(&output[copied..at]);
            copied = at + placeholders[index].len();
            for (slot, placeholder) in next.iter_mut().zip(placeholders) {
                if slot.is_some_and(|found| found < copied) {
                    *slot = find_from(copied, placeholder);
                }
            }
        }
        if pieces.len() == 1 {
            return (input == output).then(Vec::new);
        }
        let (first, last) = (pieces[0], pieces[pieces.len() - 1]);
        if first.len() + last.len() > input.len()
            || !input.starts_with(first)
            || !input.ends_with(last)
        {
            return None;
        }
        let limit = input.len() - last.len();
        let mut cursor = first.len();
        let mut ranges = Vec::new();
        for piece in &pieces[1..pieces.len() - 1] {
            if cursor > limit {
                return None;
            }
            let at = input[cursor..limit].find(piece)?;
            ranges.push(cursor..cursor + at);
            cursor += at + piece.len();
        }
        (cursor <= limit).then(|| {
            ranges.push(cursor..limit);
            ranges
        })
    }

    /// The command redactor runs on every spawned command, so it must never
    /// panic, whatever the command holds. Twenty thousand seeded random
    /// commands mix quotes, backslashes, substitutions, operators, every
    /// ASCII whitespace byte, Unicode spaces and multibyte text (combining
    /// marks, emoji), with unterminated quotes and trailing backslashes. Each
    /// command runs under a linear step budget, so a stalled scan fails.
    /// Each output must be `input` with only placeholder replacements.
    #[test]
    fn command_redaction_never_panics_and_changes_only_masked_bytes() {
        const PIECES: [&str; 54] = [
            "'",
            "\"",
            "\\",
            "$(",
            ")",
            "(",
            "`",
            "<",
            ">",
            "&",
            "|",
            ";",
            "\n",
            " ",
            "\t",
            "é",
            "中",
            "🙂",
            "e\u{301}",
            "\u{301}",
            "\u{200d}",
            "curl",
            "mysql",
            "sshpass",
            "-u",
            "-p",
            "--user=",
            "--password",
            "-ppw",
            "admin:pw",
            ":",
            "a",
            "1",
            "=",
            "TOKEN=",
            "$X",
            "2>&1",
            "<<<",
            "\\\n",
            "-f",
            "env",
            "sudo",
            "\"-u",
            "x'y",
            "\x0c",
            "\x0b",
            "\r",
            "\u{a0}",
            "\u{85}",
            "\u{2028}",
            "\u{2029}",
            "\u{3000}",
            "\u{feff}",
            "\u{1680}",
        ];
        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };
        let redactors: [(&str, fn(&str) -> Cow<'_, str>); 2] = [
            ("mask_tool_passwords", mask_tool_passwords),
            ("redact_command", redact_command),
        ];
        let mut failures = Vec::new();
        let mut masked = 0;
        for case in 0..20_000 {
            let mut input = String::new();
            for _ in 0..next() % 40 {
                input.push_str(PIECES[(next() % PIECES.len() as u64) as usize]);
            }
            if case % 7 == 0 {
                input.push('\\');
            }
            for (name, redact) in redactors {
                // Under the same linear step budget as the 1 MB test, so a
                // scan that stops advancing fails here instead of hanging.
                SHELL_SCAN_STEPS.with(|steps| steps.set(0));
                SHELL_SCAN_BUDGET
                    .with(|budget| budget.set(3 * (QUOTED_COMMAND_DEPTH + 1) * input.len() + 16));
                let result = std::panic::catch_unwind(|| redact(&input).into_owned());
                SHELL_SCAN_BUDGET.with(|budget| budget.set(usize::MAX));
                match result {
                    Err(_) => failures.push(format!("{name} panicked on {input:?}")),
                    Ok(output) => {
                        assert!(std::str::from_utf8(output.as_bytes()).is_ok());
                        masked += usize::from(output != input);
                        if !only_placeholders_changed(&input, &output) {
                            failures.push(format!(
                                "{name} changed other bytes: {input:?} -> {output:?}"
                            ));
                        }
                    }
                }
            }
        }
        assert!(
            failures.is_empty(),
            "{} failures, first: {}",
            failures.len(),
            failures
                .iter()
                .take(10)
                .cloned()
                .collect::<Vec<_>>()
                .join("\n")
        );
        // The generator must reach the masking paths, not only ordinary text.
        assert!(masked > 1_000, "{masked} outputs masked");
    }

    /// One command of a megabyte or more, in shapes that would make a
    /// rescanning or per-program-word design quadratic, is scanned in steps
    /// linear in its length: each nesting level tokenizes each byte once and
    /// visits each token once, and quoted commands nest at most
    /// QUOTED_COMMAND_DEPTH levels below the top.
    #[test]
    fn tool_password_scan_work_is_linear_on_a_megabyte_command() {
        const MEGABYTE: usize = 1 << 20;
        let repeat = |unit: &str| unit.repeat(MEGABYTE / unit.len() + 1);
        let inputs = [
            repeat("curl "),
            repeat("curl -u a:b --next -u "),
            repeat("mysql -ppw sshpass -p x "),
            format!("bash -c \"{}", repeat("sh -c 'curl \\\"x ")),
            format!("curl {}", repeat("\"'")),
            format!("curl '{}", repeat("é中🙂 \"' ")),
            format!("curl {}", repeat("\\")),
            format!("curl {}", repeat("<<<")),
            format!("curl \"{}\"", repeat("'\\\"`$( curl -u a:b ) ")),
            format!("\"'\"'\"'{}", repeat("curl -u a:b ")),
            // Substitutions that never close, each nested in the last.
            format!("curl {}", repeat("$(echo -u a:b ")),
            format!("curl {}", repeat("\"$(curl `mysql -ppw ")),
            repeat("curl $(printf x) -u a:b "),
        ];
        for input in &inputs {
            let bound = 3 * (QUOTED_COMMAND_DEPTH + 1) * input.len();
            SHELL_SCAN_STEPS.with(|steps| steps.set(0));
            SHELL_SCAN_BUDGET.with(|budget| budget.set(bound));
            let started = std::time::Instant::now();
            let masked = mask_tool_passwords(input);
            SHELL_SCAN_BUDGET.with(|budget| budget.set(usize::MAX));
            let steps = SHELL_SCAN_STEPS.with(std::cell::Cell::get);
            let elapsed = started.elapsed();
            assert!(
                steps <= bound,
                "{steps} steps for {} bytes (bound {bound}) starting {:?}",
                input.len(),
                input.chars().take(40).collect::<String>()
            );
            assert!(only_placeholders_changed(input, &masked));
            let started = std::time::Instant::now();
            let _ = redact_command(input);
            eprintln!(
                "{} bytes starting {:?}: {steps} scan steps, scan {elapsed:?}, full redaction {:?}",
                input.len(),
                input.chars().take(12).collect::<String>(),
                started.elapsed()
            );
        }
    }

    /// Run `mask_tool_passwords` under a step budget linear in the
    /// command's length, so a scan that stops advancing panics at once.
    fn mask_within_budget(command: &str) -> String {
        let bound = 3 * (QUOTED_COMMAND_DEPTH + 1) * command.len() + 16;
        SHELL_SCAN_STEPS.with(|steps| steps.set(0));
        SHELL_SCAN_BUDGET.with(|budget| budget.set(bound));
        let masked = std::panic::catch_unwind(|| mask_tool_passwords(command).into_owned());
        SHELL_SCAN_BUDGET.with(|budget| budget.set(usize::MAX));
        masked.unwrap_or_else(|_| panic!("scan stalled or panicked on {command:?}"))
    }

    /// A command longer than the scanned prefix has its tail masked whole: a
    /// credential after the cut-off, or one the cut-off splits, never
    /// reaches the log unscanned.
    #[test]
    fn command_tail_past_the_scan_limit_is_masked_not_logged() {
        let padding = "x".repeat(MAX_SCANNED_COMMAND_BYTES - 10);
        let after = format!("echo {padding} && curl -u admin:hunter2 h");
        let split = format!(
            "curl {} -u admin:hunter2 h",
            "y".repeat(MAX_SCANNED_COMMAND_BYTES - 18)
        );
        for command in [&after, &split] {
            assert!(command.len() > MAX_SCANNED_COMMAND_BYTES);
            for masked in [
                mask_within_budget(command),
                redact_command(command).into_owned(),
            ] {
                assert!(
                    !masked.contains("hunter2"),
                    "credential after the cut-off logged"
                );
                assert!(!masked.contains("hun"), "part of a split credential logged");
                assert!(masked.ends_with(SECRET_PLACEHOLDER));
                assert!(only_placeholders_changed(command, &masked));
            }
        }
    }

    /// A byte that ends a word must be consumed by the loop around the word,
    /// or the scan stops advancing. A form feed did exactly that: words
    /// ended at any ASCII whitespace, while the command loop skipped only
    /// space, tab and carriage return. Every ASCII whitespace byte and a few
    /// Unicode spaces, inside a quoted argument (scanned again as a command)
    /// and between words, must keep the scan moving.
    #[test]
    fn every_ascii_and_unicode_space_keeps_the_scan_advancing() {
        let ascii = ["\x0c", "\x0b", "\r", "\t", " "];
        let unicode = [
            "\u{a0}", "\u{85}", "\u{2028}", "\u{2029}", "\u{3000}", "\u{feff}",
        ];
        for space in ascii.iter().chain(&unicode) {
            let quoted = format!("curl \"a{space}b\" -u admin:hunter2 h");
            assert_eq!(
                mask_within_budget(&quoted),
                format!("curl \"a{space}b\" -u admin:{SECRET_PLACEHOLDER} h"),
                "{space:?}"
            );
            for command in [
                format!("curl{space}-u admin:hunter2 h"),
                format!("curl -u admin:hunter2{space}h"),
                format!("mysql{space}-phunter2 db"),
                format!("sshpass -p hunter2{space}ssh h"),
                format!("{space}{space}curl{space}{space}"),
            ] {
                let masked = mask_within_budget(&command);
                if ascii.contains(space) {
                    assert!(!masked.contains("hunter2"), "{command:?} -> {masked:?}");
                }
            }
        }
    }

    fn fixture() -> Fixture {
        serde_json::from_str(include_str!(
            "../../aft/tests/fixtures/log_redaction_cases.json"
        ))
        .expect("shared redaction fixture parses")
    }

    #[test]
    fn shells_v1_format_context_prefilter_covers_real_redaction_corpus() {
        for case in fixture().masked {
            assert!(
                shells_may_need_format_context(&case.input),
                "{}",
                case.input
            );
        }
        assert!(!shells_may_need_format_context(&"o".repeat(70_000)));
        for input in [
            "-----BEGIN PRIVATE KEY-----\nbody",
            "\"password\":\"value\"",
            "Authorization: Bearer token",
        ] {
            assert!(shells_may_need_format_context(input));
        }
    }

    #[test]
    fn shells_v1_ticket_range_streams_large_chunks_without_repeating_a_placeholder() {
        let ticket = "0123456789abcdef0123456789abcdef";
        let digest = blake3::hash(ticket.as_bytes()).to_hex().to_string();
        let prefix = "x".repeat(61);
        let suffix = format!("-{}", "o".repeat(65_536 - prefix.len() - ticket.len() - 1));
        let raw = format!("{prefix}{ticket}{suffix}");
        let first = shells_ticket_range(&raw, 0..64, Some(&digest)).unwrap();
        let second = shells_ticket_range(&raw, 64..raw.len(), Some(&digest)).unwrap();
        assert_eq!(
            first + &second,
            format!("{prefix}{SECRET_PLACEHOLDER}{suffix}")
        );
    }

    #[test]
    fn shared_fixture_masked_cases_match_the_cli_sanitizer_output() {
        let fixture = fixture();
        assert!(!fixture.masked.is_empty());
        for case in fixture.masked {
            assert_eq!(
                aft_redactor(&case.input),
                case.expected,
                "input: {}",
                case.input
            );
            assert_eq!(
                redact_command(&case.input),
                case.expected,
                "command: {}",
                case.input
            );
        }
    }

    #[test]
    fn shared_fixture_untouched_cases_are_borrowed_unchanged() {
        let fixture = fixture();
        assert!(!fixture.untouched.is_empty());
        for input in fixture.untouched {
            let out = aft_redactor(&input);
            assert!(matches!(out, Cow::Borrowed(_)), "mangled: {input} -> {out}");
        }
    }

    #[test]
    fn shared_fixture_command_shapes_do_not_redact_structured_fields() {
        let fixture = fixture();
        assert!(!fixture.command_masked.is_empty());
        for case in fixture.command_masked {
            assert_eq!(aft_redactor(&case.input), case.input);
            assert_eq!(
                redact_command(&case.input),
                case.expected,
                "command: {}",
                case.input
            );
        }
        assert!(!fixture.command_untouched.is_empty());
        for command in fixture.command_untouched {
            assert_eq!(redact_command(&command), command);
        }
    }

    #[test]
    fn masks_each_github_token_prefix() {
        let body = "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8";
        for prefix in ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"] {
            let line = format!("token {prefix}{body} end");
            assert_eq!(
                aft_redactor(&line),
                "token <REDACTED_SECRET> end",
                "{prefix}"
            );
        }
        assert_eq!(
            aft_redactor("x github_pat_11AB_cd34 y"),
            "x <REDACTED_SECRET> y"
        );
    }

    #[test]
    fn masks_url_userinfo_for_any_scheme() {
        assert_eq!(
            aft_redactor("https://user:pass@host.example/path"),
            "https://***@host.example/path"
        );
        assert_eq!(
            aft_redactor("ssh://deploy@host.example:22/repo"),
            "ssh://***@host.example:22/repo"
        );
    }

    #[test]
    fn masks_credential_query_parameters() {
        assert_eq!(
            aft_redactor("u?token=abc&access_token=def&api_key=ghi&client_secret=jkl"),
            "u?token=<REDACTED_SECRET>&access_token=<REDACTED_SECRET>&api_key=<REDACTED_SECRET>&client_secret=<REDACTED_SECRET>"
        );
        assert_eq!(
            aft_redactor("u?key=AIzaSyA1b2C3d4E5f6G7h8I9j0 done"),
            "u?key=<REDACTED_SECRET> done"
        );
    }

    #[test]
    fn masks_header_jwt_sk_and_aws_shapes() {
        assert_eq!(
            aft_redactor("Authorization: Bearer abc.def-ghi"),
            "Authorization: Bearer <REDACTED_SECRET>"
        );
        assert_eq!(
            aft_redactor("jwt eyJhbGciOi.eyJzdWIiOi.c2lnbmF0dXJl end"),
            "jwt <REDACTED_SECRET> end"
        );
        assert_eq!(
            aft_redactor("key sk-live-abcdefgh123"),
            "key <REDACTED_SECRET>"
        );
        assert_eq!(
            aft_redactor("id AKIAABCDEFGHIJKLMNOP"),
            "id <REDACTED_SECRET>"
        );
    }

    #[test]
    fn redaction_is_idempotent() {
        for case in fixture().masked {
            let once = aft_redactor(&case.input).into_owned();
            assert!(matches!(aft_redactor(&once), Cow::Borrowed(_)), "{once}");
        }
    }

    #[test]
    fn ordinary_log_content_is_not_mangled() {
        for line in [
            "[aft] index_event kind=ready plane=search root=/Users/me/proj key=search:v3",
            "[aft] format: src/main.rs (rustfmt)",
            "sha256=9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
            "blake3 AF1349B9F5F9A1A6A0404DEA36DCC9499BCB25C9ADC112B7CC9A93CAE41F3262",
            "task_id=bgb_0123456789 session=ses_abcDEF0123456789",
            "https://example.com/search?key=ab12CD34&q=tokenizer",
            "url https://example.com/a?page_size=10&sort=asc",
            "ghost gh_pages ghp_tooShort",
        ] {
            let out = aft_redactor(line);
            assert!(matches!(out, Cow::Borrowed(_)), "mangled: {line} -> {out}");
        }
    }

    #[test]
    fn truncate_for_log_bounds_bytes_and_reports_the_remainder() {
        assert_eq!(truncate_for_log("short", 10), "short");
        assert_eq!(truncate_for_log("abcdefghij", 4), "abcd…(+6 bytes)");
        // "é" is two bytes; the cut backs off to the char boundary.
        assert_eq!(truncate_for_log("aéb", 2), "a…(+3 bytes)");
    }

    #[test]
    fn unlogged_input_summary_carries_length_and_hash_only() {
        let input = "{\"command\":\"secret\"";
        let summary = unlogged_input_summary(input);
        let prefix = format!("bytes={} sha256=", input.len());
        assert!(summary.starts_with(&prefix), "{summary}");
        assert_eq!(summary.len(), prefix.len() + 12);
        assert!(!summary.contains("secret"));
    }

    #[test]
    fn contextual_secret_formats_are_masked() {
        for (input, secret) in [
            ("x-api-key: private-key-value", "private-key-value"),
            (
                "Authorization: Token private-token-value",
                "private-token-value",
            ),
            (
                r#"{"password":"private-password-value"}"#,
                "private-password-value",
            ),
            (
                "token xoxb-12345-private-slack-value",
                "xoxb-12345-private-slack-value",
            ),
            (
                "-----BEGIN RSA PRIVATE KEY-----\nprivate-pem-value\n-----END RSA PRIVATE KEY-----",
                "private-pem-value",
            ),
            (
                "AWS_SECRET_ACCESS_KEY=private-aws-secret-value",
                "private-aws-secret-value",
            ),
        ] {
            let masked = aft_redactor(input);
            assert!(!masked.contains(secret), "secret survived: {input}");
            assert!(masked.contains(SECRET_PLACEHOLDER));
            assert_eq!(aft_redactor(&masked), masked);
        }
        assert_eq!(
            aft_redactor("plain private-aws-secret-value"),
            "plain private-aws-secret-value"
        );
    }

    #[test]
    fn invalid_utf8_does_not_bypass_masking() {
        let mut bytes = vec![0xff];
        bytes.extend_from_slice(b" ghp_1234567890abcdefghij");
        let masked = aft_redact_bytes(&bytes);
        assert!(!String::from_utf8_lossy(&masked).contains("ghp_"));
        assert!(std::str::from_utf8(&masked).is_ok());
    }

    #[test]
    fn non_utf8_bytes_are_safely_decoded() {
        let bytes = [0xff, 0xfe, b'g', b'h'];
        assert_eq!(aft_redact_bytes(&bytes).as_ref(), "��gh".as_bytes());
    }

    #[test]
    fn git_numbered_config_names_are_not_secret_names() {
        // Scrubbing GIT_CONFIG_KEY_0 alone leaves GIT_CONFIG_COUNT pointing at a
        // missing key, and git refuses to run.
        for key in ["GIT_CONFIG_KEY_0", "GIT_CONFIG_KEY_12", "git_config_key_1"] {
            assert!(!is_secret_environment_key(key), "{key}");
        }
        for key in [
            "GITHUB_TOKEN",
            "NPM_AUTH",
            "AWS_SECRET_ACCESS_KEY",
            "API_KEY",
        ] {
            assert!(is_secret_environment_key(key), "{key}");
        }
    }

    #[test]
    fn author_names_are_not_secret_names() {
        for key in [
            "AFT_GIT_CO_AUTHOR",
            "GIT_AUTHOR_NAME",
            "git_author_email",
            "AUTHOR",
        ] {
            assert!(!is_secret_environment_key(key), "{key}");
        }
        for key in [
            "AUTH",
            "NPM_AUTH",
            "AUTH_HEADER",
            "HTTP_AUTHORIZATION",
            "XAUTHORITY",
            "AUTHORS_FILE",
            "GIT_AUTHOR_TOKEN",
            "AUTHOR_AUTH",
        ] {
            assert!(is_secret_environment_key(key), "{key}");
        }
    }

    #[test]
    fn git_runs_after_the_secret_name_scrub() {
        let mut command = std::process::Command::new("git");
        command
            .args(["config", "--get", "core.hooksPath"])
            .env("GIT_CONFIG_COUNT", "1")
            .env("GIT_CONFIG_KEY_0", "core.hooksPath")
            .env("GIT_CONFIG_VALUE_0", "/dev/null");
        for key in ["GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"] {
            if is_secret_environment_key(key) {
                command.env_remove(key);
            }
        }
        let output = command.output().expect("git runs");
        assert!(
            output.status.success(),
            "git failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "/dev/null");
    }
}