redact-secret 0.1.0-beta.15

Deterministic secret detection and redaction for runtime data and AI context: scans text locally before it reaches logs, storage, telemetry, tools, or model context. Side-effect free: no runtime network, filesystem, environment, telemetry, secret storage, or UI.
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
//! Shared low-level scanning helpers for hand-written detector grammars.
//!
//! The core crate depends on nothing outside `std`
//! (`workspace.metadata.redact-secret.allowed-dependencies` is empty), so every
//! detector parses its grammar by hand instead of through a regex engine.
//! These helpers centralize the small pieces of ECMAScript character-class
//! semantics that more than one ported grammar depends on, operating on
//! UTF-8 byte offsets throughout ([`crate::RANGE_UNIT`]).

/// `true` for a character ECMAScript's `\s` class matches outside Unicode
/// mode: `WhiteSpace` or `LineTerminator`. Rust's `char::is_whitespace`
/// covers the same `White_Space` code points except the byte-order-mark,
/// which ECMAScript's `WhiteSpace` production also includes.
pub(super) fn is_js_whitespace(ch: char) -> bool {
    ch.is_whitespace() || ch == '\u{FEFF}'
}

/// `true` for a character ECMAScript treats as a `LineTerminator`.
pub(super) fn is_js_line_terminator(ch: char) -> bool {
    matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
}

/// `true` for [`is_js_whitespace`] excluding [`is_js_line_terminator`]:
/// horizontal whitespace only. Unlike the ECMAScript `\s` class this mirrors
/// elsewhere, a contextual assignment's name-operator-value grammar must not
/// treat a line terminator as ordinary filler, or an operator with no value
/// on its own line reads the next physical line's first token as the value
/// (see `docs/specs/contextual-detection.md`).
pub(super) fn is_horizontal_js_whitespace(ch: char) -> bool {
    is_js_whitespace(ch) && !is_js_line_terminator(ch)
}

/// The character starting at byte offset `pos`, or `None` past the end of
/// `input` or when `pos` is not on a character boundary.
pub(super) fn char_at(input: &str, pos: usize) -> Option<char> {
    input.get(pos..)?.chars().next()
}

/// The character immediately before byte offset `pos`, or `None` at the
/// start of `input` or when `pos` is not on a character boundary.
pub(super) fn prev_char(input: &str, pos: usize) -> Option<char> {
    input.get(..pos)?.chars().next_back()
}

/// `true` when `pos` is a multiline-mode `^` position: the start of `input`
/// or immediately after a [`is_js_line_terminator`] character.
pub(super) fn is_line_start(input: &str, pos: usize) -> bool {
    pos == 0 || prev_char(input, pos).is_some_and(is_js_line_terminator)
}

/// Where the line that starts at `start` ends, and where the next one
/// starts (`bytes.len() + 1` when there is none).
///
/// A line ends at `\n`, which belongs to neither line, or after a lone `\r`
/// (one followed by anything but `\n`), which stays at the end of its line
/// the way the `\r` of a CRLF pair does. These are the line ends the
/// incremental session closes a unit at, so a detector that reads context
/// from "the same line" or from a bounded number of earlier lines sees the
/// same lines whether it scans one unit or the whole input (issue #990).
/// A `\r` that ends the input stays in its line, as it did before, so on
/// input with only LF or CRLF line endings the lines are unchanged.
pub(super) fn line_end_from(bytes: &[u8], start: usize) -> (usize, usize) {
    let mut at = start;
    while at < bytes.len() {
        match bytes[at] {
            b'\n' => return (at, at + 1),
            b'\r' if bytes.get(at + 1).is_some_and(|&next| next != b'\n') => {
                return (at + 1, at + 1);
            }
            _ => at += 1,
        }
    }
    (bytes.len(), bytes.len() + 1)
}

/// Every line of `input` as a byte range, per [`line_end_from`]: without its
/// `\n`, with a trailing `\r` (of a CRLF pair or a lone one) kept. Each byte
/// belongs to at most one range, so bounded work per line is bounded work
/// overall. An input ending in `\n` yields a final empty line.
///
/// Every keyword-gated detector walks the whole input through this, so the
/// search for the next `\n` or `\r` reads eight bytes per step
/// ([`next_line_byte`]).
pub(super) fn lines(input: &str) -> impl Iterator<Item = (usize, usize)> + '_ {
    let bytes = input.as_bytes();
    let mut start = 0usize;
    std::iter::from_fn(move || {
        if start > bytes.len() {
            return None;
        }
        let at = next_line_byte(bytes, start);
        let (end, next) = match (bytes.get(at), bytes.get(at + 1)) {
            (Some(b'\n'), _) => (at, at + 1),
            // The `\r` of a CRLF pair stays in its line.
            (Some(_), Some(b'\n')) => (at + 1, at + 2),
            // A lone `\r` ends its line after itself.
            (Some(_), Some(_)) => (at + 1, at + 1),
            // No terminator left, or a `\r` that ends the input.
            (Some(_), None) | (None, _) => (bytes.len(), bytes.len() + 1),
        };
        let line = (start, end);
        start = next;
        Some(line)
    })
}

/// The index of the first `\n` or `\r` at or after `from`, or `bytes.len()`.
///
/// Eight bytes are tested per step with the word-at-a-time zero-byte test:
/// in `v - 0x01..01 & !v & 0x80..80` the lowest set bit marks the first zero
/// byte of `v` exactly (a borrow can only mark bytes above it), so XOR-ing the
/// word with each terminator and taking the lowest mark of either finds the
/// first terminator. This keeps the per-line search as cheap for a short
/// line as a byte loop and several times cheaper for a long one.
fn next_line_byte(bytes: &[u8], from: usize) -> usize {
    const ONES: u64 = u64::from_le_bytes([0x01; 8]);
    const HIGHS: u64 = u64::from_le_bytes([0x80; 8]);
    const NEWLINES: u64 = u64::from_le_bytes([b'\n'; 8]);
    const RETURNS: u64 = u64::from_le_bytes([b'\r'; 8]);
    let mut at = from;
    while let Some(chunk) = bytes.get(at..at + 8) {
        let mut word = [0u8; 8];
        word.copy_from_slice(chunk);
        let word = u64::from_le_bytes(word);
        let newline = word ^ NEWLINES;
        let carriage_return = word ^ RETURNS;
        let found = ((newline.wrapping_sub(ONES) & !newline)
            | (carriage_return.wrapping_sub(ONES) & !carriage_return))
            & HIGHS;
        if found != 0 {
            return at + (found.trailing_zeros() / 8) as usize;
        }
        at += 8;
    }
    bytes[at.min(bytes.len())..]
        .iter()
        .position(|&byte| byte == b'\n' || byte == b'\r')
        .map_or(bytes.len(), |offset| at + offset)
}

/// The line ([`lines`]) that holds `start..end`, a span with no line break
/// inside it, as a byte range. Only that line is read.
pub(super) fn line_around(input: &str, start: usize, end: usize) -> (usize, usize) {
    let bytes = input.as_bytes();
    // A lone `\r` right before `start` ends the previous line.
    let line_start = if start > 0 && bytes[start - 1] == b'\r' && bytes.get(start) != Some(&b'\n') {
        start
    } else {
        line_start_before(input, start)
    };
    (line_start, line_end_from(bytes, end).0)
}

/// Where the line that ends at `end` starts: after the last line break
/// before it, a `\n` or a lone `\r` ([`line_end_from`]). A `\r` at
/// `end - 1` is not a break here: it is followed by `\n`, by the end of the
/// input, or it is the break that ends this line's predecessor at `end`.
/// Both searches are `memrchr` scans over this line alone.
pub(super) fn line_start_before(input: &str, end: usize) -> usize {
    let head = &input[..end];
    let after_newline = head.rfind('\n').map_or(0, |at| at + 1);
    // No `\n` lies between `after_newline` and `end`, so every `\r` there
    // but the last byte is followed by another byte of the line: a lone one.
    let line = &input[after_newline..end];
    let line = line.strip_suffix('\r').unwrap_or(line);
    line.rfind('\r')
        .map_or(after_newline, |offset| after_newline + offset + 1)
}

/// The last `count` lines of `input` per [`lines`], oldest first, after
/// dropping one trailing `\n`: the complete lines a retention hint reads
/// back over. Only the tail is read, so the cost is the length of those
/// lines, not of `input`.
#[cfg(test)]
pub(super) fn last_lines(input: &str, count: usize) -> Vec<&str> {
    let complete = input.strip_suffix('\n').unwrap_or(input);
    let bytes = complete.as_bytes();
    let mut tail = Vec::with_capacity(count);
    let mut end = bytes.len();
    while tail.len() < count {
        let start = line_start_before(complete, end);
        tail.push(&complete[start..end]);
        if start == 0 {
            break;
        }
        end = if bytes[start - 1] == b'\n' {
            start - 1
        } else {
            start
        };
    }
    tail.reverse();
    tail
}

/// The last `count` lines of `tail`, a [`last_lines`] result for a count at
/// least `count`: exactly `last_lines(input, count)` over the same input,
/// since both walk back from the same end and stop at the same first line.
/// The incremental session computes one tail for every lookback hint and
/// each hint reads its own window from it (issue #1060).
pub(super) fn tail_lines<'t, 'a>(tail: &'t [&'a str], count: usize) -> &'t [&'a str] {
    &tail[tail.len().saturating_sub(count)..]
}

/// Advances `start` past every consecutive character matching `pred`.
pub(super) fn skip_while_chars(input: &str, start: usize, pred: fn(char) -> bool) -> usize {
    let mut cursor = start;
    while let Some(ch) = char_at(input, cursor) {
        if pred(ch) {
            cursor += ch.len_utf8();
        } else {
            break;
        }
    }
    cursor
}

/// Retreats `end` past every consecutive character matching `pred`, scanning
/// backward from byte offset `end`.
pub(super) fn rskip_while_chars(input: &str, end: usize, pred: fn(char) -> bool) -> usize {
    let mut cursor = end;
    while let Some(ch) = prev_char(input, cursor) {
        if pred(ch) {
            cursor -= ch.len_utf8();
        } else {
            break;
        }
    }
    cursor
}

/// Length in bytes of the maximal run of `pred`-matching bytes starting at
/// `start`. Every predicate used with this helper matches ASCII bytes only,
/// so byte and character boundaries coincide.
pub(super) fn ascii_run_len(bytes: &[u8], start: usize, pred: fn(u8) -> bool) -> usize {
    let mut end = start;
    while end < bytes.len() && pred(bytes[end]) {
        end += 1;
    }
    end - start
}

/// Case-insensitive ASCII literal match at byte offset `pos`. Byte
/// comparison never requires `pos` to be on a character boundary.
pub(super) fn starts_with_ci(input: &str, pos: usize, literal: &str) -> bool {
    let literal = literal.as_bytes();
    input
        .as_bytes()
        .get(pos..pos + literal.len())
        .is_some_and(|window| window.eq_ignore_ascii_case(literal))
}

/// The first offset at or after `from` where the ASCII `needle` occurs
/// case-insensitively in `bytes`, or `None`. An empty needle matches at
/// `from` when `from <= bytes.len()`.
///
/// The first needle byte is searched eight bytes at a time (the word-at-a-time
/// zero-byte test of [`next_line_byte`]) in both its cases when it is a
/// letter, and each candidate window is then compared in full, so the result
/// equals a per-offset [`starts_with_ci`] scan. Byte comparison never needs a
/// character boundary; a found offset starts with an ASCII byte when the
/// needle does.
pub(super) fn find_ci(bytes: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
    const ONES: u64 = u64::from_le_bytes([0x01; 8]);
    const HIGHS: u64 = u64::from_le_bytes([0x80; 8]);
    let Some(&first) = needle.first() else {
        return (from <= bytes.len()).then_some(from);
    };
    let last_start = bytes.len().checked_sub(needle.len())?;
    let lower = first.to_ascii_lowercase();
    let upper = first.to_ascii_uppercase();
    let lower_word = u64::from_le_bytes([lower; 8]);
    let upper_word = u64::from_le_bytes([upper; 8]);
    let mut at = from;
    while at <= last_start {
        // Skip to the next candidate first byte.
        let mut found = None;
        while at <= last_start {
            if let Some(chunk) = bytes.get(at..at + 8) {
                let mut word = [0u8; 8];
                word.copy_from_slice(chunk);
                let word = u64::from_le_bytes(word);
                let lo = word ^ lower_word;
                let up = word ^ upper_word;
                let marks = ((lo.wrapping_sub(ONES) & !lo) | (up.wrapping_sub(ONES) & !up)) & HIGHS;
                if marks == 0 {
                    at += 8;
                    continue;
                }
                at += (marks.trailing_zeros() / 8) as usize;
                found = Some(at);
                break;
            }
            if bytes[at] == lower || bytes[at] == upper {
                found = Some(at);
                break;
            }
            at += 1;
        }
        let candidate = found?;
        if candidate > last_start {
            return None;
        }
        if bytes[candidate..candidate + needle.len()].eq_ignore_ascii_case(needle) {
            return Some(candidate);
        }
        at = candidate + 1;
    }
    None
}

/// `true` when the ASCII `needle` occurs anywhere in `haystack`,
/// case-insensitively ([`find_ci`]).
pub(super) fn contains_ci(haystack: &str, needle: &str) -> bool {
    find_ci(haystack.as_bytes(), 0, needle.as_bytes()).is_some()
}

/// Case-insensitive ASCII literal suffix match.
pub(super) fn ends_with_ci(value: &str, suffix: &str) -> bool {
    let bytes = value.as_bytes();
    let suffix = suffix.as_bytes();
    bytes.len() >= suffix.len() && bytes[bytes.len() - suffix.len()..].eq_ignore_ascii_case(suffix)
}

/// `true` when `value` is entirely built from words already on `exact_words`
/// (case-insensitively), closing trivial lexical variants of an
/// already-excluded word — a leading/trailing separator, an appended digit
/// to a word on `digit_suffix_words`, or two listed words joined with
/// `-`/`_` — without falling back to raw substring containment (see
/// `docs/specs/contextual-detection.md`).
///
/// `value` is split into maximal runs of ASCII alphanumeric characters
/// (every other byte is a separator). Two independent checks then apply:
///
/// - the tokens, concatenated in order with no separator, spell out exactly
///   one word on `exact_words` (`replace_me`, `my-secret-password` ->
///   `replaceme`, `mysecretpassword`); or
/// - every token is itself a word on `exact_words`, or, once a trailing run
///   of ASCII digits is stripped, a word on `digit_suffix_words`
///   (`changeme2` -> `changeme`; `REDACTED-EXAMPLE` -> `redacted` +
///   `example`).
///
/// `digit_suffix_words` must be a subset of `exact_words` restricted to
/// words distinctive enough that an appended digit is still unambiguously a
/// placeholder — generic role names such as `secret` or `password` belong
/// only on `exact_words`, since `password1` or `secret01` are common real
/// (if weak) credential shapes, not placeholder text, and must keep being
/// reported.
///
/// A value with no alphanumeric characters at all never matches. Digit
/// stripping only trims the end of a token, so a word embedded in a larger
/// alphanumeric run (`mySecretKeyAbc123`) is never split out and stays a
/// false negative by design, not an exclusion.
pub(super) fn matches_placeholder_vocabulary(
    value: &str,
    exact_words: &[&str],
    digit_suffix_words: &[&str],
) -> bool {
    fn strip_trailing_digits(token: &str) -> &str {
        token.trim_end_matches(|ch: char| ch.is_ascii_digit())
    }
    let is_listed =
        |token: &str, words: &[&str]| words.iter().any(|word| token.eq_ignore_ascii_case(word));
    let token_is_placeholder = |token: &str| {
        is_listed(token, exact_words) || {
            let core = strip_trailing_digits(token);
            core.len() < token.len() && is_listed(core, digit_suffix_words)
        }
    };

    // Streaming over the tokens instead of collecting them and a joined
    // `String` (#1121): the joined word is compared byte-wise against each
    // listed word without being built.
    let tokens = || {
        value
            .split(|ch: char| !ch.is_ascii_alphanumeric())
            .filter(|token| !token.is_empty())
    };
    let joined_len: usize = tokens().map(str::len).sum();
    if joined_len == 0 {
        return false;
    }
    let joined_is_listed = exact_words.iter().any(|word| {
        word.len() == joined_len
            && word
                .bytes()
                .zip(tokens().flat_map(str::bytes))
                .all(|(a, b)| a.eq_ignore_ascii_case(&b))
    });
    joined_is_listed || tokens().all(token_is_placeholder)
}

/// `true` for a value made of the same character repeated three or more
/// times (`xxxxxxxxxxxx`, `00000000000`, `••••••••`) -- classic
/// redaction-style filler used in documentation and masked terminal/UI
/// echoes to mean "value omitted", structurally unlike a real secret.
///
/// Compares by Unicode scalar value, not raw byte, so a multi-byte filler
/// character (`•`, U+2022) is recognized the same as a single-byte one
/// (`*`). Shared by the connection-string and generic-token detectors so
/// the exclusion stays consistent between them (see #256, #264).
pub(super) fn is_repeated_character_filler(value: &str) -> bool {
    let mut chars = value.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    let mut count = 1usize;
    for ch in chars {
        if ch != first {
            return false;
        }
        count += 1;
    }
    count >= 3
}

/// Words that open a documentation placeholder asking the reader to supply
/// their own credential (`YOUR_ACCESS_TOKEN`, `INSERT_API_KEY`).
const PLACEHOLDER_LEAD_WORDS: &[&str] = &["your", "insert", "enter", "paste", "replace"];

/// Words that name the kind of credential a placeholder stands for. Every
/// word after the lead word must come from this list.
///
/// Issue #993 adds the qualifiers provider documentation puts in front of a
/// credential noun (`your-bot-token-here`, `whsec_YOUR_SIGNING_SECRET`,
/// `ntn_yourinternalintegrationtokenhere`): `account`, `admin`, `bot`,
/// `deploy`, `integration`, `internal`, `org`, `project`, `signing` and
/// `webhook`.
const PLACEHOLDER_CREDENTIAL_WORDS: &[&str] = &[
    "access",
    "account",
    "admin",
    "api",
    "app",
    "auth",
    "bearer",
    "bot",
    "client",
    "deploy",
    "id",
    "integration",
    "internal",
    "jwt",
    "key",
    "oauth",
    "oauth2",
    "org",
    "personal",
    "project",
    "refresh",
    "secret",
    "service",
    "session",
    "signing",
    "token",
    "user",
    "webhook",
    "here",
    "with",
];

/// Provider names a documentation placeholder may carry between its lead word
/// and the credential words (`YOUR_DEEPGRAM_API_KEY`,
/// `replace-with-your-mistral-key`). A closed list of the AI-inference and
/// developer-credential providers the built-in detectors name, not a
/// vocabulary. Issue #774; `convex` and `fal` were added with their exact
/// credential names in issue #919 (`FAL_KEY=your_fal_key`); `exa` was added
/// in issue #1203 (`EXA_API_KEY=your_exa_api_key_here`); `figma` was added in
/// issue #1209 (`X-Figma-Token: YOUR_FIGMA_TOKEN`). Since issue
/// #993 every provider segment of `generic-token`'s rule-2 list
/// ([`is_placeholder_provider_word`]) also counts (`YOUR_MAILGUN_API_KEY`,
/// `your-travis-api-token`); a provider outside both lists
/// (`YOUR_ACMECLOUD_API_KEY`) is one word off and stays detected.
const PLACEHOLDER_PROVIDER_WORDS: &[&str] = &[
    "ai",
    "ai21",
    "anthropic",
    "cohere",
    "convex",
    "deepgram",
    "deepseek",
    "elevenlabs",
    "exa",
    "fal",
    "figma",
    "fireworks",
    "gemini",
    "groq",
    "huggingface",
    "mistral",
    "openai",
    "openrouter",
    "perplexity",
    "replicate",
    "tavily",
    "together",
    "xai",
];

/// The password-family nouns an instructional placeholder may name
/// (`YOUR_PASSWORD`, `enter-your-passphrase`). Issue #1234. Kept apart from
/// [`PLACEHOLDER_CREDENTIAL_WORDS`] on purpose: only the bare-value rule
/// [`is_instructional_token_placeholder`], which needs a lead word, reads
/// this list, so `placeholder-password` or `my` + `password` (a common weak
/// real password) and the glued and vendor-prefixed rules keep their
/// behavior. FN cost: a real password spelled exactly as a lead word plus
/// these nouns (`your_password`), which no issuer generates.
const PLACEHOLDER_PASSWORD_WORDS: &[&str] = &["password", "passwd", "pwd", "passphrase"];

/// Product, service and credential-scope words a bare-value instructional
/// placeholder may carry between its lead word and its credential nouns
/// (`YOUR_ZOOM_CLIENT_SECRET`, `YOUR_DATABASE_PASSWORD`,
/// `YOUR_PRIVATE_API_KEY`). Issue #1234 follow-up: the Batch 2 provider
/// documentation spells its placeholders with these words, and the shorter
/// forms `YOUR_USER_PASSWORD` and `YOUR_APP_SECRET` were already silent while
/// `YOUR_DB_PASSWORD` was a high `redact` finding.
///
/// A closed list, never an open wildcard: a later word off every list still
/// keeps the value detected. Kept apart from
/// [`PLACEHOLDER_PROVIDER_WORDS`] on purpose, like
/// [`PLACEHOLDER_PASSWORD_WORDS`]: only the bare-value rule
/// [`is_instructional_token_placeholder`], which needs a lead word, a
/// separator between every word and a credential noun, reads this list, so
/// the glued rule (`yourdbkey` behind a vendor prefix) and the `my` rules keep
/// their behavior. FN cost: a real value spelled exactly as a lead word plus
/// these words and a noun, which no issuer generates.
const PLACEHOLDER_SERVICE_WORDS: &[&str] = &[
    "adobe",
    "airtable",
    "asana",
    "atlas",
    "box",
    "canva",
    "contentful",
    "database",
    "db",
    "dropbox",
    "elastic",
    "hubspot",
    "instagram",
    "jfrog",
    "meta",
    "mongodb",
    "private",
    "salesforce",
    "spotify",
    "zendesk",
    "zoom",
];

/// `true` for a [`PLACEHOLDER_CREDENTIAL_WORDS`] entry, case-insensitively.
pub(super) fn is_placeholder_credential_word(word: &str) -> bool {
    PLACEHOLDER_CREDENTIAL_WORDS
        .iter()
        .any(|listed| word.eq_ignore_ascii_case(listed))
}

/// Credential nouns a placeholder must name at least once, so a lead word
/// followed only by qualifiers (`YOUR_PERSONAL_ACCESS`) is not enough.
const PLACEHOLDER_CREDENTIAL_NOUNS: &[&str] = &["jwt", "key", "secret", "token"];

/// `true` for a provider word a placeholder may carry
/// ([`PLACEHOLDER_PROVIDER_WORDS`] or a segment of `generic-token`'s
/// provider list), case-insensitively.
fn is_placeholder_provider_word(word: &str) -> bool {
    PLACEHOLDER_PROVIDER_WORDS
        .iter()
        .chain(super::generic_token::DEDICATED_PROVIDER_SEGMENTS)
        .any(|listed| word.eq_ignore_ascii_case(listed))
}

/// `true` for an instructional placeholder written as one glued word, such
/// as `yourkey`, `yourapikey` or `YourSigningKeyHere` (issue #949): ASCII
/// letters only, opening with a [`PLACEHOLDER_LEAD_WORDS`] entry, and the
/// rest splitting exactly into [`PLACEHOLDER_CREDENTIAL_WORDS`],
/// [`PLACEHOLDER_PROVIDER_WORDS`], provider segments or lead words, with at least
/// one [`PLACEHOLDER_CREDENTIAL_NOUNS`] entry, all case-insensitively.
///
/// Without separators the word boundaries are ambiguous, so this is only
/// applied behind a vendor prefix (`re_yourkey`), never to a bare value. A
/// letter left over (`yourkeyq`) or any digit keeps the value detected.
pub(super) fn is_glued_instructional_placeholder(value: &str) -> bool {
    // Values past the stack bound take the original heap implementation, so
    // no accepted length is truncated (#1162).
    if value.len() > GLUED_PLACEHOLDER_STACK_BOUND {
        return is_glued_instructional_placeholder_heap(value);
    }
    if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_alphabetic()) {
        return false;
    }
    let bytes = value.as_bytes();
    let Some(lead) = PLACEHOLDER_LEAD_WORDS
        .iter()
        .find(|lead| starts_with_ascii_ci(bytes, lead.as_bytes()))
    else {
        return false;
    };
    glued_placeholder_split(&bytes[lead.len()..])
}

/// The word-split DP over the text after the lead word, on two stack arrays.
/// A separate function so the early rejections above never pay for its frame.
fn glued_placeholder_split(rest: &[u8]) -> bool {
    let len = rest.len();
    debug_assert!(len <= GLUED_PLACEHOLDER_STACK_BOUND);
    // reachable[i]: rest[..i] splits into listed words; with_noun[i]: one
    // such split names a credential noun. Both live on the stack.
    let mut reachable = [false; GLUED_PLACEHOLDER_STACK_BOUND + 1];
    let mut with_noun = [false; GLUED_PLACEHOLDER_STACK_BOUND + 1];
    reachable[0] = true;
    for start in 0..len {
        if !reachable[start] {
            continue;
        }
        for word in glued_placeholder_words() {
            if starts_with_ascii_ci(&rest[start..], word.as_bytes()) {
                let end = start + word.len();
                reachable[end] = true;
                with_noun[end] |= with_noun[start] || PLACEHOLDER_CREDENTIAL_NOUNS.contains(word);
            }
        }
    }
    len > 0 && reachable[len] && with_noun[len]
}

/// Longest value the stack-bounded form of
/// [`is_glued_instructional_placeholder`] handles; longer values fall back
/// to the heap implementation.
const GLUED_PLACEHOLDER_STACK_BOUND: usize = 256;

fn starts_with_ascii_ci(haystack: &[u8], prefix: &[u8]) -> bool {
    haystack.len() >= prefix.len() && haystack[..prefix.len()].eq_ignore_ascii_case(prefix)
}

fn glued_placeholder_words() -> impl Iterator<Item = &'static &'static str> {
    PLACEHOLDER_CREDENTIAL_WORDS
        .iter()
        .chain(PLACEHOLDER_PROVIDER_WORDS)
        .chain(super::generic_token::DEDICATED_PROVIDER_SEGMENTS)
        .chain(PLACEHOLDER_LEAD_WORDS)
}

/// The original heap implementation: the fallback above the stack bound and
/// the differential-test oracle for the bounded form.
fn is_glued_instructional_placeholder_heap(value: &str) -> bool {
    if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_alphabetic()) {
        return false;
    }
    let lower = value.to_ascii_lowercase();
    let Some(rest) = PLACEHOLDER_LEAD_WORDS
        .iter()
        .find_map(|lead| lower.strip_prefix(lead))
    else {
        return false;
    };
    let words = || {
        PLACEHOLDER_CREDENTIAL_WORDS
            .iter()
            .chain(PLACEHOLDER_PROVIDER_WORDS)
            .chain(super::generic_token::DEDICATED_PROVIDER_SEGMENTS)
            .chain(PLACEHOLDER_LEAD_WORDS)
    };
    // reachable[i]: rest[..i] splits into listed words; with_noun[i]: one
    // such split names a credential noun. Bounded by the value's length
    // times the fixed word lists.
    let len = rest.len();
    let mut reachable = vec![false; len + 1];
    let mut with_noun = vec![false; len + 1];
    reachable[0] = true;
    for start in 0..len {
        if !reachable[start] {
            continue;
        }
        for word in words() {
            if rest[start..].starts_with(word) {
                let end = start + word.len();
                reachable[end] = true;
                with_noun[end] |= with_noun[start] || PLACEHOLDER_CREDENTIAL_NOUNS.contains(word);
            }
        }
    }
    len > 0 && reachable[len] && with_noun[len]
}

/// `true` for an instructional placeholder written as a phrase of plain
/// words (issue #1042): `your_key_for_ci_pipeline_test_fixture_only`, the
/// word fixture the #860 evidence lists behind the `rpa_` prefix. Two or more
/// words split on `_` or `-`, each ASCII letters only and in one case, the
/// first a [`PLACEHOLDER_LEAD_WORDS`] entry and at least one a
/// [`PLACEHOLDER_CREDENTIAL_NOUNS`] entry; the other words may be any
/// letters. Unlike [`is_instructional_token_placeholder`] the later words are
/// not listed, so this is applied only behind a vendor prefix, never to a
/// bare value. A digit, a mixed-case word, or a missing lead word or noun
/// keeps the value detected.
pub(super) fn is_lead_word_phrase_placeholder(value: &str) -> bool {
    let one_case = |word: &str| {
        !word.is_empty()
            && (word.bytes().all(|byte| byte.is_ascii_lowercase())
                || word.bytes().all(|byte| byte.is_ascii_uppercase()))
    };
    let listed =
        |word: &str, words: &[&str]| words.iter().any(|listed| word.eq_ignore_ascii_case(listed));
    // One pass over the words, no collected `Vec` (#1121).
    let mut words = value.split(['_', '-']);
    let Some(lead) = words.next() else {
        return false;
    };
    if !one_case(lead) || !listed(lead, PLACEHOLDER_LEAD_WORDS) {
        return false;
    }
    let mut later = 0usize;
    let mut has_noun = false;
    for word in words {
        if !one_case(word) {
            return false;
        }
        later += 1;
        has_noun |= listed(word, PLACEHOLDER_CREDENTIAL_NOUNS);
    }
    later >= 1 && has_noun
}

/// `true` for a documentation placeholder glued as `my` + credential words
/// (issue #1042): `mykeysecret` and `mykeyid`, the `ClickHouse` Cloud docs'
/// `KEY_SECRET`/`KEY_ID` examples the #860 evidence lists. Lowercase ASCII
/// letters only, `my`, then an exact split into two or more
/// [`PLACEHOLDER_CREDENTIAL_WORDS`] with at least one
/// [`PLACEHOLDER_CREDENTIAL_NOUNS`] entry. One word after `my` (`mysecret`,
/// `mykey`) is a common weak real password and stays reported, as does any
/// leftover letter, digit or uppercase letter.
pub(super) fn is_glued_my_placeholder(value: &str) -> bool {
    let Some(rest) = value.strip_prefix("my") else {
        return false;
    };
    if rest.is_empty() || !rest.bytes().all(|byte| byte.is_ascii_lowercase()) {
        return false;
    }
    // reached[i][many][noun]: rest[..i] splits into listed words, `many`
    // when two or more, `noun` when one is a credential noun. Bounded by the
    // value's length times the fixed word list.
    let len = rest.len();
    let mut reached = vec![[[false; 2]; 2]; len + 1];
    reached[0][0][0] = true;
    for start in 0..len {
        for word in PLACEHOLDER_CREDENTIAL_WORDS {
            if !rest[start..].starts_with(word) {
                continue;
            }
            let end = start + word.len();
            let is_noun = PLACEHOLDER_CREDENTIAL_NOUNS.contains(word);
            for many in 0..2 {
                for noun in 0..2 {
                    if reached[start][many][noun] {
                        let next_many = usize::from(many == 1 || start > 0);
                        reached[end][next_many][usize::from(noun == 1 || is_noun)] = true;
                    }
                }
            }
        }
    }
    reached[len][1][1]
}

/// `true` for an instructional placeholder such as `YOUR_ACCESS_TOKEN`,
/// `INSERT_ACCESS_TOKEN`, `YOUR_API_KEY`, or `your-oauth-token-here`: the
/// value splits on `_`, `-`, and `.` into two or more words, the first is a
/// [`PLACEHOLDER_LEAD_WORDS`] entry, every later word is a
/// [`PLACEHOLDER_CREDENTIAL_WORDS`], [`PLACEHOLDER_PROVIDER_WORDS`] or
/// lead-word entry (`ENTER_YOUR_ACCESS_TOKEN_HERE`), and at least one later word is a
/// [`PLACEHOLDER_CREDENTIAL_NOUNS`] entry, all matched case-insensitively.
///
/// Shared by `bearer-token` (issue #745) and `generic-token` (issue #756,
/// `apiKey: "YOUR_API_KEY"`), so both detectors agree on what an
/// instructional placeholder is. Any byte outside `[A-Za-z0-9._-]`, any word off the lists, or a word
/// glued to random material (`YOUR_ACCESS_TOKEN9f2c`) keeps the value
/// detected, so a real token is never excluded for merely starting with
/// `your`.
pub(super) fn is_instructional_token_placeholder(value: &str) -> bool {
    let is_listed =
        |word: &str, words: &[&str]| words.iter().any(|listed| word.eq_ignore_ascii_case(listed));
    let mut words = value.split(['_', '-', '.']);
    let Some(lead) = words.next() else {
        return false;
    };
    if !is_listed(lead, PLACEHOLDER_LEAD_WORDS) {
        return false;
    }
    let mut saw_noun = false;
    let mut count = 0usize;
    for word in words {
        if !is_listed(word, PLACEHOLDER_CREDENTIAL_WORDS)
            && !is_listed(word, PLACEHOLDER_PASSWORD_WORDS)
            && !is_listed(word, PLACEHOLDER_SERVICE_WORDS)
            && !is_listed(word, PLACEHOLDER_LEAD_WORDS)
            && !is_placeholder_provider_word(word)
        {
            return false;
        }
        saw_noun |= is_listed(word, PLACEHOLDER_CREDENTIAL_NOUNS)
            || is_listed(word, PLACEHOLDER_PASSWORD_WORDS);
        count += 1;
    }
    count > 0 && saw_noun
}

/// Hash-algorithm names that, written directly in front of an opaque value
/// with a `=` or `:` separator, label that value as a digest (issue #744).
/// Matched case-insensitively.
const DIGEST_ALGORITHM_LABELS: &[&str] = &[
    "md5", "sha1", "sha-1", "sha224", "sha-224", "sha256", "sha-256", "sha384", "sha-384",
    "sha512", "sha-512", "sha3-256", "sha3-512", "blake2b", "blake2s", "blake3",
];

/// `true` when `value` itself opens with a hash-algorithm label and `:` or
/// `=`, optionally behind `hmac-` (`hmac-sha256:<hex>`, `sha256:<hex>`): an
/// audit-log HMAC or content digest, not a credential (issue #702).
pub(super) fn starts_with_digest_label(value: &str) -> bool {
    // Case-insensitive byte comparison; no lowercased copy (#1121).
    let bytes = value.as_bytes();
    let rest = match bytes.split_at_checked("hmac-".len()) {
        Some((head, rest)) if head.eq_ignore_ascii_case(b"hmac-") => rest,
        _ => bytes,
    };
    DIGEST_ALGORITHM_LABELS.iter().any(|label| {
        rest.split_at_checked(label.len())
            .is_some_and(|(head, after)| {
                head.eq_ignore_ascii_case(label.as_bytes())
                    && matches!(after.first(), Some(b':' | b'='))
            })
    })
}

/// `true` when the value starting at byte offset `start` of `input` is
/// introduced by a hash-algorithm label: one of [`DIGEST_ALGORITHM_LABELS`],
/// then `=` or `:`, then optional spaces or tabs, directly before the value
/// (`md5=<hex>`, `image@sha256:<hex>`, `sha256: <hex>`). The label itself
/// must not continue a wider identifier on its left (`xmd5=` does not
/// count), though a `_`, `-`, `@`, or any other non-alphanumeric byte may
/// precede it.
///
/// A value introduced this way is a published checksum or content digest,
/// not a credential, so the keyword-gated bare-value detectors
/// (`twilio-auth-token`, `twilio-api-key-secret`,
/// `confluent-cloud-api-secret-legacy`) skip it even when their provider's
/// name is on the same line. The label must sit immediately in front of the
/// value: a digest label elsewhere on the line proves nothing about an
/// unrelated value.
pub(super) fn is_labelled_digest(input: &str, start: usize) -> bool {
    let bytes = input.as_bytes();
    let mut cursor = start;
    while cursor > 0 && matches!(bytes[cursor - 1], b' ' | b'\t') {
        cursor -= 1;
    }
    if cursor == 0 || !matches!(bytes[cursor - 1], b'=' | b':') {
        return false;
    }
    let label_end = cursor - 1;
    DIGEST_ALGORITHM_LABELS.iter().any(|label| {
        label_end >= label.len()
            && starts_with_ci(input, label_end - label.len(), label)
            && (label_end == label.len()
                || !bytes[label_end - label.len() - 1].is_ascii_alphanumeric())
    })
}

// --- interpolation / environment-reference exclusions -------------------
//
// Shared by `generic_token` and `connection_string` (issue #279, #292,
// #469) so a value that is a pointer to a runtime-resolved secret --
// rather than the secret itself -- is treated the same way regardless of
// which detector's grammar reaches it.

/// `true` when `value` is exactly `open` followed by anything followed by
/// `close` -- the whole-value delimiter shape `is_template_reference` uses,
/// generalized to an arbitrary delimiter pair. A value that only starts
/// with `open`, or that carries the pair embedded inside a larger string,
/// does not satisfy this and stays detected.
pub(super) fn is_fully_delimited(value: &str, open: &str, close: &str) -> bool {
    value.starts_with(open) && value.ends_with(close) && value.len() >= open.len() + close.len()
}

/// `true` when the whole value is delimited by `{{` and `}}`
/// (`^\{\{.*\}\}$`) -- the idiomatic Jinja/Helm/Go-template reference syntax
/// Ansible, Helm, Salt, and Go templates use for a vaulted or injected value
/// (`{{ vault_db_password }}`, `{{ .Values.postgresql.auth.password }}`).
pub(super) fn is_template_reference(value: &str) -> bool {
    is_fully_delimited(value, "{{", "}}")
}

/// `true` for a POSIX/shell, `Makefile`, or Kustomize variable or
/// command-substitution reference (`$(registryPassword)`,
/// `$(pass show db/prod)`): the value names a variable or command to
/// resolve at runtime, not a secret.
pub(super) fn is_command_substitution_reference(value: &str) -> bool {
    is_fully_delimited(value, "$(", ")")
}

/// `true` for a Ruby string-interpolation reference
/// (`#{ENV['DB_PASSWORD']}`).
pub(super) fn is_ruby_interpolation_reference(value: &str) -> bool {
    is_fully_delimited(value, "#{", "}")
}

/// Openers of the opencode config substitutions, `{env:...}` and
/// `{file:...}`, resolved from the environment or a file at load time rather
/// than containing a secret directly. Static, so a check allocates nothing
/// (issue #984).
pub(super) const OPENCODE_REFERENCE_OPENERS: &[&str] = &["{env:", "{file:"];

/// `true` for an opencode `{env:VAR}` or `{file:path}` substitution.
pub(super) fn is_opencode_reference(value: &str) -> bool {
    OPENCODE_REFERENCE_OPENERS
        .iter()
        .any(|open| is_fully_delimited(value, open, "}"))
}

/// `true` for a bare shell or PowerShell environment-variable reference:
/// `$` immediately followed by an identifier-start character
/// (`$DB_PASSWORD`, `$env:DB_PASSWORD` -- PowerShell's drive-qualified
/// `env:` provider, itself a valid identifier-start run). Unlike
/// [`is_fully_delimited`]'s whole-value checks, this is intentionally a
/// prefix match: a shell variable reference consumes to the right for as
/// long as the identifier continues, so the entire captured value is the
/// reference regardless of what trails the identifier.
pub(super) fn starts_with_bare_dollar_reference(value: &str) -> bool {
    value.as_bytes().first() == Some(&b'$')
        && char_at(value, 1).is_some_and(|second| second.is_ascii_alphabetic() || second == '_')
}

/// `true` for a byte allowed inside an environment-variable identifier:
/// ASCII letter, digit, or `_`, matching shell/POSIX identifier rules.
pub(super) fn is_env_var_identifier(value: &str) -> bool {
    let mut chars = value.chars();
    match chars.next() {
        Some(first) if first.is_ascii_alphabetic() || first == '_' => {}
        _ => return false,
    }
    chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
}

/// `true` for a cmd.exe/batch-style Windows environment-variable reference
/// (`%DB_PASSWORD%`): the whole value is `%` + an identifier + `%`, expanded
/// by the shell at runtime rather than a secret. `%` is common enough
/// punctuation on its own (a percentage-bounded range) that a bare
/// delimiter-pair check like [`is_fully_delimited`] would exclude values
/// that merely start and end with one, so the content between the
/// delimiters must itself look like an identifier.
pub(super) fn is_windows_env_reference(value: &str) -> bool {
    value
        .strip_prefix('%')
        .and_then(|rest| rest.strip_suffix('%'))
        .is_some_and(is_env_var_identifier)
}

/// Last key-name segments that name a public identifier, a location or an
/// account attribute rather than the credential itself (`OKTA_ORG_URL`,
/// `MAILGUN_DOMAIN`, `TWILIO_ACCOUNT_SID`).
const NON_CREDENTIAL_KEY_SEGMENTS: &[&str] = &[
    "id", "ids", "uuid", "sid", "name", "url", "uri", "host", "hostname", "domain", "region",
    "org", "site", "endpoint", "email", "user", "username", "account", "project", "version",
    "slug", "commit", "sha", "branch", "tag", "number",
];

/// `true` for a byte of an assignment key name: `[A-Za-z0-9_.-]`.
fn is_assignment_key_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')
}

/// The key a value starting at `value_start` of `line` is assigned to: the
/// run of [`is_assignment_key_byte`] bytes left of a gap of spaces, tabs,
/// quotes and at least one `=` or `:`. `None` when no operator joins them.
pub(super) fn assignment_key(line: &[u8], value_start: usize) -> Option<&[u8]> {
    let mut end = value_start.min(line.len());
    let mut has_operator = false;
    while end > 0 && matches!(line[end - 1], b' ' | b'\t' | b'"' | b'\'' | b'=' | b':') {
        has_operator |= matches!(line[end - 1], b'=' | b':');
        end -= 1;
    }
    let mut start = end;
    while start > 0 && is_assignment_key_byte(line[start - 1]) {
        start -= 1;
    }
    (has_operator && start < end).then_some(&line[start..end])
}

/// `true` when the value starting at byte `value_start` of `line` is
/// assigned to a key whose last normalized segment names an identifier, a
/// location or an account attribute ([`NON_CREDENTIAL_KEY_SEGMENTS`]):
/// `TRAVIS_REPO_SLUG=`, `build_id:`, `"projectUrl":`.
pub(super) fn is_non_credential_assignment(line: &str, value_start: usize) -> bool {
    assignment_key(line.as_bytes(), value_start)
        .and_then(|key| std::str::from_utf8(key).ok())
        .is_some_and(|key| {
            super::generic_token::normalize_name(key)
                .rsplit('_')
                .next()
                .is_some_and(|segment| NON_CREDENTIAL_KEY_SEGMENTS.contains(&segment))
        })
}

/// `true` when the value starting at byte `value_start` of `line` is the
/// value of an assignment that names the provider's credential (issue #702):
///
/// - the key, after [`super::generic_token::normalize_name`], contains one
///   of `keywords` (`MAILCHIMP_API_KEY`, `okta.api_token`,
///   `"mailgunApiKey"`), unless its last segment is one of
///   [`NON_CREDENTIAL_KEY_SEGMENTS`]; or
/// - the key is a generic high-signal name (`api_key`, `auth_token`,
///   `secret`) and `line` also names one of `keywords`.
///
/// Context-gated detectors report such a value at high confidence. The name
/// is the same evidence `generic-token` already redacts at high confidence,
/// so without this the provider's own medium finding would lose the span to
/// the generic one, or leave it at `warn`. `keywords` are lowercase and
/// already in normalized form (`new_relic`, `newrelic`).
pub(super) fn is_provider_named_assignment(
    line: &str,
    value_start: usize,
    keywords: &[&str],
) -> bool {
    let Some(key) = assignment_key(line.as_bytes(), value_start) else {
        return false;
    };
    let Ok(key) = std::str::from_utf8(key) else {
        return false;
    };
    let normalized = super::generic_token::normalize_name(key);
    if normalized
        .rsplit('_')
        .next()
        .is_some_and(|segment| NON_CREDENTIAL_KEY_SEGMENTS.contains(&segment))
    {
        return false;
    }
    if keywords.iter().any(|keyword| normalized.contains(keyword)) {
        return true;
    }
    super::generic_token::is_high_signal_name(&normalized)
        && keywords.iter().any(|keyword| contains_ci(line, keyword))
}

// --- Keyed environment stores (issue #1038) ---------------------------------

/// Last callee segments that store `(name, value)` into an environment:
/// Python `os.environ.setdefault` and `os.putenv`, and `setenv`.
const ENV_STORE_CALLEES: &[&str] = &["setdefault", "putenv", "setenv"];

/// Most bytes between a value and the `[` or `(` that opens its keyed store
/// (`["` + a 128-byte name + `"] = "`).
const MAX_STORE_PREFIX: usize = 160;

/// A keyed-store prefix: the name span and the offset where the value
/// starts, which is its opening quote.
pub(super) struct StorePrefix {
    pub(super) name_start: usize,
    pub(super) name_end: usize,
    pub(super) value_start: usize,
    /// The prefix is a `(name, value)` call, where only a quoted literal
    /// value counts.
    pub(super) call: bool,
}

/// Parses a keyed store opening at byte `open` of `input` (issue #1038),
/// read as the assignment `NAME = <value>`:
///
/// - `<target>["NAME"] = ` (single quotes too): `os.environ["NAME"] =`,
///   `process.env['NAME'] =`, Ruby `ENV["NAME"] =`, `settings["api_key"] =`.
///   The `[` follows an identifier byte or a closing `)`/`]`, and the `=`
///   is not part of `==`.
/// - `<callee>("NAME", ` where the callee's last segment is one of
///   [`ENV_STORE_CALLEES`]: `os.environ.setdefault("NAME", `,
///   `os.putenv("NAME", `.
///
/// The name is `[A-Za-z_][A-Za-z0-9_.-]*`, at most 128 bytes, between
/// matching quotes. `value_start` must hold a quote for the caller to read
/// a literal; the prefix never crosses a line end.
pub(super) fn keyed_store_prefix(input: &str, open: usize) -> Option<StorePrefix> {
    let bytes = input.as_bytes();
    let call = match bytes.get(open)? {
        b'[' => {
            let target = *bytes.get(open.checked_sub(1)?)?;
            if !(target.is_ascii_alphanumeric() || matches!(target, b'_' | b')' | b']')) {
                return None;
            }
            false
        }
        b'(' => {
            let callee_end = open;
            let callee_start = callee_end
                - bytes[..callee_end]
                    .iter()
                    .rev()
                    .take_while(|&&byte| byte.is_ascii_alphanumeric() || byte == b'_')
                    .count();
            if !ENV_STORE_CALLEES.contains(&&input[callee_start..callee_end]) {
                return None;
            }
            true
        }
        _ => return None,
    };
    let horizontal = |byte: u8| matches!(byte, b' ' | b'\t');
    let mut at = open + 1;
    if call {
        at += ascii_run_len(bytes, at, horizontal);
    }
    let quote = *bytes
        .get(at)
        .filter(|&&byte| matches!(byte, b'"' | b'\''))?;
    at += 1;
    let name_start = at;
    if !bytes
        .get(at)
        .is_some_and(|&byte| byte.is_ascii_alphabetic() || byte == b'_')
    {
        return None;
    }
    at += ascii_run_len(bytes, at, |byte| {
        byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')
    });
    let name_end = at;
    if name_end - name_start > 128 || bytes.get(at) != Some(&quote) {
        return None;
    }
    at += 1;
    at += ascii_run_len(bytes, at, horizontal);
    if call {
        if bytes.get(at) != Some(&b',') {
            return None;
        }
        at += 1;
    } else {
        if bytes.get(at) != Some(&b']') {
            return None;
        }
        at += 1;
        at += ascii_run_len(bytes, at, horizontal);
        if bytes.get(at) != Some(&b'=') || bytes.get(at + 1) == Some(&b'=') {
            return None;
        }
        at += 1;
    }
    at += ascii_run_len(bytes, at, horizontal);
    Some(StorePrefix {
        name_start,
        name_end,
        value_start: at,
        call,
    })
}

/// The name of the keyed store (issue #1038, [`keyed_store_prefix`]) whose
/// quoted literal value opens at byte `value_start` of `line`, the byte
/// after the opening quote.
pub(super) fn keyed_store_name(line: &str, value_start: usize) -> Option<&str> {
    let bytes = line.as_bytes();
    let quote_at = value_start.checked_sub(1)?;
    if !matches!(bytes.get(quote_at), Some(b'"' | b'\'')) {
        return None;
    }
    let floor = quote_at.saturating_sub(MAX_STORE_PREFIX);
    for open in (floor..quote_at).rev() {
        if !matches!(bytes[open], b'[' | b'(') {
            continue;
        }
        if let Some(prefix) = keyed_store_prefix(line, open)
            && prefix.value_start == quote_at
        {
            return Some(&line[prefix.name_start..prefix.name_end]);
        }
    }
    None
}

// --- YAML list-item `name:`/`value:` pairs (issue #1016) -------------------

/// One `key:` line of a YAML block sequence or mapping, as
/// [`list_item_paired_name`] reads it.
pub(super) struct ItemKeyLine<'a> {
    /// Byte column of the key within its line.
    pub(super) column: usize,
    /// The key follows the `- ` that opens a sequence item.
    pub(super) item_start: bool,
    pub(super) key: &'a str,
    /// Where the text after the `:` starts, within the line.
    pub(super) rest: usize,
}

/// Parses `^ *(- +)?[A-Za-z_][A-Za-z0-9_]*:( |\t|$)`: spaces only for the
/// indentation (YAML forbids tabs there), an optional sequence-item dash,
/// a plain key and its `:` indicator. A trailing `\r` counts as the line end.
pub(super) fn item_key_line(line: &str) -> Option<ItemKeyLine<'_>> {
    let bytes = line.as_bytes();
    let mut at = bytes.iter().take_while(|&&byte| byte == b' ').count();
    let mut item_start = false;
    if bytes.get(at) == Some(&b'-') && bytes.get(at + 1) == Some(&b' ') {
        item_start = true;
        at += 1;
        at += bytes[at..].iter().take_while(|&&byte| byte == b' ').count();
    }
    let column = at;
    if !bytes
        .get(at)
        .is_some_and(|&byte| byte.is_ascii_alphabetic() || byte == b'_')
    {
        return None;
    }
    at += bytes[at..]
        .iter()
        .take_while(|&&byte| byte.is_ascii_alphanumeric() || byte == b'_')
        .count();
    let key = &line[column..at];
    if bytes.get(at) != Some(&b':') {
        return None;
    }
    at += 1;
    match bytes.get(at) {
        None | Some(b' ' | b'\t' | b'\r') => Some(ItemKeyLine {
            column,
            item_start,
            key,
            rest: at,
        }),
        _ => None,
    }
}

/// The plain or quoted scalar after `name:` when it is a whole environment-
/// style name (`[A-Za-z_][A-Za-z0-9_.-]*`, at most 128 bytes), optionally
/// followed by a `#` comment.
pub(super) fn item_name_scalar(line: &str, rest: usize) -> Option<&str> {
    let bytes = line.as_bytes();
    let mut at = rest + ascii_run_len(bytes, rest, |byte| matches!(byte, b' ' | b'\t'));
    let quote = bytes
        .get(at)
        .copied()
        .filter(|&byte| matches!(byte, b'"' | b'\''));
    if quote.is_some() {
        at += 1;
    }
    let start = at;
    if !bytes
        .get(at)
        .is_some_and(|&byte| byte.is_ascii_alphabetic() || byte == b'_')
    {
        return None;
    }
    at += ascii_run_len(bytes, at, |byte| {
        byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')
    });
    let end = at;
    if end - start > 128 {
        return None;
    }
    if let Some(quote) = quote {
        if bytes.get(at) != Some(&quote) {
            return None;
        }
        at += 1;
    }
    let tail = line[at..].trim_start_matches([' ', '\t']);
    (tail.is_empty() || tail == "\r" || tail.starts_with('#')).then_some(&line[start..end])
}

/// The line ([`lines`]) before the one starting at `line_start`.
pub(super) fn previous_line(input: &str, line_start: usize) -> Option<(usize, usize)> {
    if line_start == 0 {
        return None;
    }
    // A `\n` ends the previous line outside it; a lone `\r` stays in it.
    let end = if input.as_bytes()[line_start - 1] == b'\n' {
        line_start - 1
    } else {
        line_start
    };
    Some((line_start_before(input, end), end))
}

/// The shortest run of [`is_long_run_byte`] bytes any bare-shape detector can
/// match: twilio and datadog need 32, new-relic 32 to 40, heroku, pinecone 36,
/// confluent 64, mailchimp 32 plus a datacenter suffix (issue #1075).
const LONG_RUN_MIN: usize = 32;

/// `[A-Za-z0-9+/=_-]`: the union of every alphabet a bare-shape detector
/// matches its body in (hex, alphanumeric, base64 body, hex-or-dash).
const fn long_run_table() -> [bool; 256] {
    let mut table = [false; 256];
    let mut byte = 0u8;
    loop {
        table[byte as usize] =
            byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'=' | b'_' | b'-');
        if byte == u8::MAX {
            break;
        }
        byte += 1;
    }
    table
}

static LONG_RUN_BYTES: [bool; 256] = long_run_table();

/// The [`lines`] of `input` that hold a run of at least [`LONG_RUN_MIN`]
/// `[A-Za-z0-9+/=_-]` bytes, in order, as byte ranges only (issue #1075).
///
/// A line with no such run cannot hold a bare-shape match, so a detector
/// whose every match is one may skip it. Any run of `LONG_RUN_MIN` bytes
/// covers a position that is `LONG_RUN_MIN - 1` modulo `LONG_RUN_MIN`, so
/// only those are probed; a probe inside the alphabet is grown to the run's
/// ends, and a line already recorded is jumped past. Every byte is read at
/// most once when growing, so the cost stays linear and, on prose whose
/// words are short, reads about one byte in 32.
pub(super) fn long_run_line_spans(input: &str) -> Vec<(usize, usize)> {
    let bytes = input.as_bytes();
    let mut spans = Vec::new();
    // Bytes before `floor` were already examined: a run never crosses it,
    // because it is a byte outside the alphabet or the end of a line.
    let mut floor = 0usize;
    let mut probe = LONG_RUN_MIN - 1;
    while probe < bytes.len() {
        if probe < floor {
            probe += LONG_RUN_MIN * (floor - probe).div_ceil(LONG_RUN_MIN);
            continue;
        }
        if !LONG_RUN_BYTES[usize::from(bytes[probe])] {
            probe += LONG_RUN_MIN;
            continue;
        }
        let mut start = probe;
        while start > floor && LONG_RUN_BYTES[usize::from(bytes[start - 1])] {
            start -= 1;
        }
        let mut end = probe + 1;
        while end < bytes.len() && LONG_RUN_BYTES[usize::from(bytes[end])] {
            end += 1;
        }
        floor = end;
        if end - start >= LONG_RUN_MIN {
            let (line_end, next) = line_end_from(bytes, end);
            spans.push((line_start_before(input, line_end), line_end));
            // The next line starts at `next` (or is a lone `\r`'s successor).
            floor = next.min(bytes.len());
        }
    }
    spans
}

/// The old, line-by-line answer of [`long_run_line_spans`]: every line whose
/// longest run of [`LONG_RUN_BYTES`] bytes reaches [`LONG_RUN_MIN`]. Debug
/// builds and tests check the fast walk against it.
#[cfg(any(debug_assertions, test))]
pub(super) fn long_run_line_spans_by_line(input: &str) -> Vec<(usize, usize)> {
    lines(input)
        .filter(|&(start, end)| {
            let mut run = 0usize;
            input.as_bytes()[start..end].iter().any(|&byte| {
                run = if LONG_RUN_BYTES[usize::from(byte)] {
                    run + 1
                } else {
                    0
                };
                run >= LONG_RUN_MIN
            })
        })
        .collect()
}

/// The up to `count` [`lines`] before the one starting at `line_start`,
/// oldest first, as the same text `lines(input)` yields for them.
pub(super) fn preceding_lines(input: &str, line_start: usize, count: usize) -> Vec<&str> {
    let mut previous = Vec::with_capacity(count);
    let mut at = line_start;
    while previous.len() < count {
        let Some((start, end)) = previous_line(input, at) else {
            break;
        };
        previous.push(&input[start..end]);
        at = start;
    }
    previous.reverse();
    previous
}

/// Calls `visit` with the byte range of each [`lines`] line that may hold a
/// bare-shape match, in order: every line of `input`, or, when `input` is the
/// scan copy being scanned, only those [`long_run_line_spans`] lists, built
/// once for all detectors that ask (issue #1075).
pub(super) fn for_each_long_run_line(input: &str, mut visit: impl FnMut(usize, usize)) {
    if let Some(spans) = super::prefilter::long_run_lines(input) {
        for &(start, end) in spans.iter() {
            visit(start, end);
        }
    } else {
        for (start, end) in lines(input) {
            visit(start, end);
        }
    }
}

/// The line ([`lines`]) after the one ending at `line_end`.
pub(super) fn next_line(input: &str, line_end: usize) -> Option<(usize, usize)> {
    let bytes = input.as_bytes();
    let start = match bytes.get(line_end) {
        Some(b'\n') => line_end + 1,
        // A lone `\r` ended the line inside it: the next one starts here.
        Some(_) if line_end > 0 && bytes[line_end - 1] == b'\r' => line_end,
        _ => return None,
    };
    Some((start, line_end_from(bytes, start).0.min(bytes.len())))
}

/// Issue #1016: the credential name a Kubernetes-style `env` entry gives
/// the value on `line` (a [`lines`] range), when that line is the
/// `value:` key of a YAML sequence item whose sibling `name:` key sits on
/// the adjacent line at the same key column:
///
/// ```yaml
/// env:
///   - name: DEEPGRAM_API_KEY
///     value: "..."
/// ```
///
/// Either order is read (`- value:` then `name:`), but only the two keys of
/// one item: exactly one of the two lines opens the item with `- `, the
/// other continues it, and nothing else sits between them. A later
/// unrelated key, a value on a separate item, another indentation, a flow
/// mapping (`- {name: A, value: b}`) or a JSON document are not paired.
/// `valueFrom:` is a different key and never pairs. The detectors read the
/// pair as the one-line assignment `<name>=<value>`, so every value
/// exclusion of that form still applies.
pub(super) fn list_item_paired_name(input: &str, line: (usize, usize)) -> Option<&str> {
    let value_line = item_key_line(&input[line.0..line.1])?;
    if value_line.key != "value" {
        return None;
    }
    let other = if value_line.item_start {
        next_line(input, line.1)?
    } else {
        previous_line(input, line.0)?
    };
    let other_text = &input[other.0..other.1];
    let name_line = item_key_line(other_text)?;
    (name_line.key == "name"
        && name_line.item_start != value_line.item_start
        && name_line.column == value_line.column)
        .then(|| item_name_scalar(other_text, name_line.rest))
        .flatten()
}

/// Internal retention hint for [`list_item_paired_name`] (issue #1016):
/// `true` when the last complete line of `input` opens a YAML sequence item
/// with a `name:` or `value:` key, so the incremental session holds it open
/// for the one following line that can complete the pair. Holding a line
/// that never pairs only delays its output by one line.
#[cfg(test)]
pub(crate) fn has_open_list_item_pair(input: &str) -> bool {
    has_open_list_item_pair_in(&super::lookback_tail(input))
}

/// [`has_open_list_item_pair`] over a [`super::lookback_tail`].
pub(crate) fn has_open_list_item_pair_in(tail: &[&str]) -> bool {
    tail_lines(tail, 1).first().is_some_and(|line| {
        item_key_line(line)
            .is_some_and(|parsed| parsed.item_start && matches!(parsed.key, "name" | "value"))
    })
}

#[cfg(test)]
mod provider_named_assignment_tests {
    use super::is_provider_named_assignment;

    const VALUE: &str = "SYNTHETIC_REVOKED_VALUE";

    fn value_start(line: &str) -> usize {
        line.find(VALUE).unwrap()
    }

    #[test]
    fn a_key_naming_the_provider_qualifies() {
        for line in [
            format!("MAILCHIMP_API_KEY={VALUE}"),
            format!("mailchimp.api_key: {VALUE}"),
            format!("{{\"mailchimpApiKey\": \"{VALUE}\"}}"),
            format!("export MAILCHIMP_KEY='{VALUE}'"),
        ] {
            assert!(
                is_provider_named_assignment(&line, value_start(&line), &["mailchimp"]),
                "{line}"
            );
        }
    }

    #[test]
    fn a_high_signal_key_on_a_line_naming_the_provider_qualifies() {
        let line = format!("mailchimp.setConfig({{ apiKey: \"{VALUE}\" }})");
        assert!(is_provider_named_assignment(
            &line,
            value_start(&line),
            &["mailchimp"]
        ));
    }

    #[test]
    fn identifier_keys_prose_and_other_keys_do_not_qualify() {
        for line in [
            format!("MAILCHIMP_LIST_ID={VALUE}"),
            format!("MAILCHIMP_SERVER_URL={VALUE}"),
            format!("# Mailchimp API key {VALUE}"),
            format!("list_id: {VALUE} # mailchimp"),
            format!("MAILCHIMP_API_KEY {VALUE}"),
            format!("SENDGRID_API_KEY={VALUE}"),
        ] {
            assert!(
                !is_provider_named_assignment(&line, value_start(&line), &["mailchimp"]),
                "{line}"
            );
        }
    }
}

#[cfg(test)]
mod line_tests {
    use super::{last_lines, line_around, lines};

    fn split(input: &str) -> Vec<&str> {
        lines(input)
            .map(|(start, end)| &input[start..end])
            .collect()
    }

    #[test]
    fn lines_end_at_a_newline_and_after_a_lone_carriage_return() {
        assert_eq!(split("a\nb"), ["a", "b"]);
        assert_eq!(split("a\r\nb\r\n"), ["a\r", "b\r", ""]);
        assert_eq!(split("a\rb\rc"), ["a\r", "b\r", "c"]);
        assert_eq!(split("a\r\rb"), ["a\r", "\r", "b"]);
        // A `\r` that ends the input stays in its line.
        assert_eq!(split("a\r"), ["a\r"]);
        assert_eq!(split(""), [""]);
    }

    /// Every string of up to six symbols over `a`, `\r`, `\n` and a
    /// three-byte code point, each also with a run of `a` in the middle so
    /// the terminators fall on both sides of the short-line walk's window.
    fn generated_inputs() -> Vec<String> {
        let alphabet = ["a", "\r", "\n", "\u{597D}"];
        let mut inputs = Vec::new();
        for len in 0..=6u32 {
            for mut code in 0..4usize.pow(len) {
                let mut symbols = Vec::new();
                for _ in 0..len {
                    symbols.push(alphabet[code % 4]);
                    code /= 4;
                }
                let (head, tail) = symbols.split_at(symbols.len() / 2);
                for padding in [0, 28, 31, 32, 33, 40] {
                    inputs.push(format!(
                        "{}{}{}",
                        head.concat(),
                        "a".repeat(padding),
                        tail.concat()
                    ));
                }
            }
        }
        inputs
    }

    #[test]
    fn lines_agree_with_the_byte_by_byte_line_end_over_generated_inputs() {
        for input in generated_inputs() {
            let mut expected = Vec::new();
            let mut start = 0;
            while start <= input.len() {
                let (end, next) = super::line_end_from(input.as_bytes(), start);
                expected.push((start, end));
                start = next;
            }
            assert_eq!(lines(&input).collect::<Vec<_>>(), expected, "{input:?}");
        }
    }

    /// The oracle for a skipped line: its longest run is under the minimum.
    fn long_run_inputs() -> Vec<String> {
        let mut inputs = generated_inputs();
        let pieces = [
            "a",
            "-",
            "=",
            "+",
            "/",
            "_",
            " ",
            "\r",
            "\n",
            "\r\n",
            "\u{e9}",
            "\u{597D}",
            "0123456789abcdef",
            "Z",
        ];
        let mut state = 0x2545_f491_4f6c_dd1du64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            usize::try_from(state >> 33).unwrap()
        };
        for _ in 0..3000 {
            let mut input = String::new();
            for _ in 0..(next() % 24) {
                let piece = pieces[next() % pieces.len()];
                let repeat = if next() % 4 == 0 { 1 + next() % 40 } else { 1 };
                for _ in 0..repeat {
                    input.push_str(piece);
                }
            }
            inputs.push(input);
        }
        inputs
    }

    #[test]
    fn long_run_line_spans_agree_with_the_line_by_line_walk() {
        for input in long_run_inputs() {
            assert_eq!(
                super::long_run_line_spans(&input),
                super::long_run_line_spans_by_line(&input),
                "{input:?}"
            );
        }
        assert!(super::long_run_line_spans("").is_empty());
    }

    #[test]
    fn preceding_lines_are_the_lines_before_the_line_start() {
        for input in long_run_inputs().iter().take(4000) {
            let all: Vec<(usize, usize)> = lines(input).collect();
            for (index, &(start, _)) in all.iter().enumerate() {
                for count in [0, 1, 3, 5] {
                    let expected: Vec<&str> = all[index.saturating_sub(count)..index]
                        .iter()
                        .map(|&(from, to)| &input[from..to])
                        .collect();
                    assert_eq!(
                        super::preceding_lines(input, start, count),
                        expected,
                        "{input:?} {index} {count}"
                    );
                }
            }
        }
    }

    #[test]
    fn the_last_lines_are_the_tail_of_lines_over_generated_inputs() {
        for input in generated_inputs() {
            let complete = input.strip_suffix('\n').unwrap_or(&input);
            let all = split(complete);
            for count in 1..=4 {
                let expected = &all[all.len().saturating_sub(count)..];
                assert_eq!(last_lines(&input, count), expected, "{input:?} {count}");
            }
        }
    }

    #[test]
    fn every_hint_window_of_the_shared_lookback_tail_is_its_own_last_lines() {
        // Issue #1060: the session computes one tail and each lookback hint
        // reads its own window of it.
        for input in generated_inputs() {
            let tail = crate::detectors::lookback_tail(&input);
            for count in 1..=super::super::MAX_LOOKBACK_LINES {
                assert_eq!(
                    super::tail_lines(&tail, count),
                    last_lines(&input, count),
                    "{input:?} {count}"
                );
            }
        }
    }

    #[test]
    fn the_inline_lookback_tail_is_last_lines_for_every_count() {
        // Issue #1074: the session reads 2 lines while an open tail check
        // holds the unit, and the full window otherwise.
        for input in generated_inputs() {
            for count in 0..=super::super::MAX_LOOKBACK_LINES + 1 {
                let inline = crate::detectors::lookback_tail_lines(&input, count);
                let expected = last_lines(&input, count.min(super::super::MAX_LOOKBACK_LINES));
                assert_eq!(inline.as_slice(), expected, "{input:?} {count}");
            }
        }
        assert!(
            crate::detectors::LookbackTail::empty()
                .as_slice()
                .is_empty()
        );
    }

    #[test]
    fn the_line_around_a_span_is_the_line_that_holds_it() {
        let input = "x\ra \"k\" b\r\ny";
        let at = input.find("\"k\"").unwrap();
        let (start, end) = line_around(input, at, at + 3);
        assert_eq!(&input[start..end], "a \"k\" b\r");
    }
}

#[cfg(test)]
mod list_item_pair_tests {
    use super::{has_open_list_item_pair, lines, list_item_paired_name};

    /// The paired name for the last non-empty line of `input`.
    fn paired(input: &str) -> Option<&str> {
        let line = lines(input)
            .filter(|&(start, end)| start < end && !input[start..end].trim().is_empty())
            .last()?;
        list_item_paired_name(input, line)
    }

    #[test]
    fn the_value_key_pairs_with_the_adjacent_name_of_its_item() {
        assert_eq!(
            paired("  - name: API_TOKEN\n    value: x\n"),
            Some("API_TOKEN")
        );
        assert_eq!(
            paired("- name: 'CO_API_KEY'\r\n  value: x\r\n"),
            Some("CO_API_KEY")
        );
        assert_eq!(paired("- name: A\r  value: x\r"), Some("A"));
        let reverse = "- value: x\n  name: B # c\n";
        assert_eq!(list_item_paired_name(reverse, (0, 10)), Some("B"));
    }

    #[test]
    fn anything_but_the_two_keys_of_one_item_is_not_a_pair() {
        for input in [
            "- name: A\n- value: x\n",
            "- name: A\n    value: x\n",
            "- name: A\n  image: b\n  value: x\n",
            "name: A\nvalue: x\n",
            "- {name: A, value: x}\n",
            "- name: A\n  valueFrom: x\n",
            "- name: two words\n  value: x\n",
            "- name: A\n\t value: x\n",
        ] {
            assert_eq!(paired(input), None, "{input:?}");
        }
    }

    #[test]
    fn the_retention_hint_holds_exactly_an_item_opening_name_or_value_line() {
        for open in [
            "- name: A\n",
            "env:\n  - name: A\n",
            "  - value: x\r\n",
            "- name: A\r",
        ] {
            assert!(has_open_list_item_pair(open), "{open:?}");
        }
        for closed in [
            "",
            "- name: A\n  value: x\n",
            "- name: A\n\n",
            "  name: A\n",
            "- image: A\n",
            "- {name: A}\n",
        ] {
            assert!(!has_open_list_item_pair(closed), "{closed:?}");
        }
    }
}

#[cfg(test)]
mod keyed_store_tests {
    use super::{keyed_store_name, keyed_store_prefix};

    #[test]
    fn subscript_and_call_stores_name_their_value() {
        let line = "os.environ[\"API_TOKEN\"] = \"v\"";
        let prefix = keyed_store_prefix(line, 10).unwrap();
        assert_eq!(&line[prefix.name_start..prefix.name_end], "API_TOKEN");
        assert_eq!(prefix.value_start, line.len() - 3);
        assert!(!prefix.call);
        assert_eq!(keyed_store_name(line, line.len() - 2), Some("API_TOKEN"));
        let call = "os.putenv( 'API_TOKEN' , 'v')";
        assert_eq!(keyed_store_name(call, call.len() - 3), Some("API_TOKEN"));
        assert!(keyed_store_prefix(call, 9).unwrap().call);
    }

    #[test]
    fn comparisons_reads_and_other_callees_are_not_stores() {
        for (line, open) in [
            ("x[\"A\"] == \"v\"", 1),
            ("x[\"A\"]", 1),
            (" [\"A\"] = \"v\"", 1),
            ("x[A] = \"v\"", 1),
            ("x[\"A'] = \"v\"", 1),
            ("x[\"1A\"] = \"v\"", 1),
            ("get(\"A\", \"v\")", 3),
            ("setdefault(\"A\" \"v\")", 10),
        ] {
            assert!(keyed_store_prefix(line, open).is_none(), "{line}");
        }
        assert_eq!(keyed_store_name("x = \"v\"", 5), None);
    }
}

#[cfg(test)]
mod find_ci_tests {
    use super::{contains_ci, find_ci, starts_with_ci};

    /// The pre-#1073 per-offset scan every detector used to carry.
    fn find_oracle(haystack: &str, from: usize, needle: &str) -> Option<usize> {
        let len = haystack.len();
        if needle.len() > len {
            return None;
        }
        (from..=len - needle.len()).find(|&pos| starts_with_ci(haystack, pos, needle))
    }

    #[test]
    fn find_ci_equals_the_per_offset_oracle_on_random_and_boundary_inputs() {
        let pieces = [
            "a",
            "K",
            "e",
            "y",
            "KEY",
            "api",
            "Token",
            "tOkEn",
            "twilio",
            "TWILIO",
            "-",
            "_",
            " ",
            "\u{e9}",
            "\u{1F511}",
            "\n",
            "0",
            "\u{212A}",
            "secret",
        ];
        let needles = [
            "key",
            "token",
            "twilio",
            "api-key",
            "secret",
            "a",
            "k",
            "0",
            "dd-app-key",
            "-x",
            "",
        ];
        let mut state: u64 = 0xD1B5_4A32_D192_ED03;
        let mut next = move || {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            (state >> 33) as usize
        };
        for _ in 0..4000 {
            let mut input = String::new();
            for _ in 0..next() % 40 {
                input.push_str(pieces[next() % pieces.len()]);
            }
            for needle in needles {
                let from = if input.is_empty() {
                    0
                } else {
                    next() % (input.len() + 1)
                };
                assert_eq!(
                    find_ci(input.as_bytes(), from, needle.as_bytes()),
                    find_oracle(&input, from, needle),
                    "{input:?} {needle:?} {from}"
                );
                assert_eq!(
                    contains_ci(&input, needle),
                    find_oracle(&input, 0, needle).is_some()
                );
            }
        }
    }

    #[test]
    fn find_ci_handles_short_empty_and_out_of_range_inputs() {
        assert_eq!(find_ci(b"", 0, b"key"), None);
        assert_eq!(find_ci(b"", 0, b""), Some(0));
        assert_eq!(find_ci(b"ab", 5, b"a"), None);
        assert_eq!(find_ci(b"xxxxxxxxxxxxxxxKEY", 0, b"key"), Some(15));
        assert_eq!(find_ci(b"xxxxxxxxxxxxxxxKE", 0, b"key"), None);
    }
}

/// Differential tests for #1121: the allocation-free forms of the placeholder
/// and digest-label checks must agree with the collecting implementations
/// they replaced, on seeded strings with repeated, empty and extra separators.
#[cfg(test)]
mod residual_allocation_tests {
    use super::*;
    use crate::test_rng::XorShift32;

    const PIECES: &[&str] = &[
        "your",
        "insert",
        "enter",
        "paste",
        "replace",
        "key",
        "secret",
        "token",
        "jwt",
        "api",
        "KEY",
        "YOUR",
        "Token",
        "example",
        "EXAMPLE",
        "changeme",
        "change",
        "me",
        "redacted",
        "password",
        "12",
        "7",
        "_",
        "-",
        "_",
        "-",
        "__",
        ".",
        ":",
        "=",
        " ",
        "md5",
        "sha256",
        "SHA-256",
        "hmac-",
        "HMAC-",
        "sha3-512",
        "blake3",
        "\u{e9}",
        "\u{212a}",
        "\u{1f600}",
        "x",
    ];

    fn old_vocabulary(value: &str, exact: &[&str], digit: &[&str]) -> bool {
        fn strip(token: &str) -> &str {
            token.trim_end_matches(|ch: char| ch.is_ascii_digit())
        }
        let is_listed =
            |token: &str, words: &[&str]| words.iter().any(|word| token.eq_ignore_ascii_case(word));
        let token_is_placeholder = |token: &str| {
            is_listed(token, exact) || {
                let core = strip(token);
                core.len() < token.len() && is_listed(core, digit)
            }
        };
        let tokens: Vec<&str> = value
            .split(|ch: char| !ch.is_ascii_alphanumeric())
            .filter(|token| !token.is_empty())
            .collect();
        if tokens.is_empty() {
            return false;
        }
        let joined: String = tokens.concat();
        is_listed(&joined, exact) || tokens.iter().all(|token| token_is_placeholder(token))
    }

    fn old_digest_label(value: &str) -> bool {
        let lower = value.to_ascii_lowercase();
        let rest = lower.strip_prefix("hmac-").unwrap_or(&lower);
        DIGEST_ALGORITHM_LABELS.iter().any(|label| {
            rest.strip_prefix(label)
                .is_some_and(|after| after.starts_with(':') || after.starts_with('='))
        })
    }

    fn old_lead_phrase(value: &str) -> bool {
        let words: Vec<&str> = value.split(['_', '-']).collect();
        let one_case = |word: &str| {
            !word.is_empty()
                && (word.bytes().all(|byte| byte.is_ascii_lowercase())
                    || word.bytes().all(|byte| byte.is_ascii_uppercase()))
        };
        let listed = |word: &str, words: &[&str]| {
            words.iter().any(|listed| word.eq_ignore_ascii_case(listed))
        };
        words.len() >= 2
            && words.iter().all(|word| one_case(word))
            && listed(words[0], PLACEHOLDER_LEAD_WORDS)
            && words[1..]
                .iter()
                .any(|word| listed(word, PLACEHOLDER_CREDENTIAL_NOUNS))
    }

    #[test]
    fn vocabulary_matches_collecting_form() {
        let exact = [
            "example",
            "replaceme",
            "changeme",
            "redacted",
            "yourkey",
            "password",
        ];
        let digit = ["example", "changeme", "redacted"];
        let mut rng = XorShift32::new(0x1121_0001);
        let mut matched = 0;
        for _ in 0..20_000 {
            let value = rng.text(PIECES, 6);
            let expected = old_vocabulary(&value, &exact, &digit);
            matched += usize::from(expected);
            assert_eq!(
                matches_placeholder_vocabulary(&value, &exact, &digit),
                expected,
                "{value:?}"
            );
        }
        assert!(matched > 100, "generator must reach the accepting branch");
    }

    #[test]
    fn digest_label_matches_lowercasing_form() {
        let mut rng = XorShift32::new(0x1121_0002);
        let mut matched = 0;
        for _ in 0..20_000 {
            let lead = ["", "hmac-", "HMAC-", "Hmac-"][rng.below(4)];
            let label = ["md5", "SHA256", "sha-256", "sha3-512", "Blake3", "shax"][rng.below(6)];
            let sep = [":", "=", "-", " ", ""][rng.below(5)];
            let value = format!("{lead}{label}{sep}{}", rng.text(PIECES, 3));
            let expected = old_digest_label(&value);
            matched += usize::from(expected);
            assert_eq!(starts_with_digest_label(&value), expected, "{value:?}");
        }
        assert!(matched > 100, "generator must reach the accepting branch");
        for fixed in [
            "", "hmac", "hmac-", "sha256", "sha256:", "SHA256=", "xsha256:",
        ] {
            assert_eq!(
                starts_with_digest_label(fixed),
                old_digest_label(fixed),
                "{fixed:?}"
            );
        }
    }

    #[test]
    fn lead_phrase_matches_collecting_form() {
        let mut rng = XorShift32::new(0x1121_0003);
        let mut matched = 0;
        for _ in 0..30_000 {
            let lead = ["your", "YOUR", "Insert", "paste", "x"][rng.below(5)];
            let sep = ["_", "-", "", "__"][rng.below(4)];
            let noun = ["key", "KEY", "secret", "Token", "jwt", "api", "id"][rng.below(7)];
            let value = format!("{lead}{sep}{noun}{}", rng.text(PIECES, 4));
            let expected = old_lead_phrase(&value);
            matched += usize::from(expected);
            assert_eq!(
                is_lead_word_phrase_placeholder(&value),
                expected,
                "{value:?}"
            );
        }
        assert!(matched > 50, "generator must reach the accepting branch");
        for fixed in [
            "",
            "_",
            "your",
            "your_key",
            "your__key",
            "your_key_",
            "YOUR-KEY",
            "Your_key",
        ] {
            assert_eq!(
                is_lead_word_phrase_placeholder(fixed),
                old_lead_phrase(fixed),
                "{fixed:?}"
            );
        }
    }
}

/// Differential tests for #1162: the stack-bounded glued-placeholder check
/// must agree with the heap implementation it falls back to, including at
/// and around the 256-byte bound.
#[cfg(test)]
mod glued_placeholder_stack_tests {
    use super::*;
    use crate::test_rng::XorShift32;

    const PIECES: &[&str] = &[
        "your", "YOUR", "Insert", "enter", "paste", "replace", "key", "secret", "TOKEN", "jwt",
        "api", "access", "openai", "github", "stripe", "x", "zz", "_", "9", "\u{212a}", "\u{e9}",
        "example", "my",
    ];

    fn assert_same(value: &str) {
        assert_eq!(
            is_glued_instructional_placeholder(value),
            is_glued_instructional_placeholder_heap(value),
            "{value:?}"
        );
    }

    #[test]
    fn word_lists_are_lowercase_ascii() {
        // The borrowed case-insensitive compare equals the lowercased-copy
        // compare only while every listed word is already lowercase ASCII.
        for word in glued_placeholder_words() {
            assert!(
                word.is_ascii() && !word.bytes().any(|b| b.is_ascii_uppercase()),
                "{word} must be ASCII without uppercase"
            );
        }
    }

    #[test]
    fn seeded_values_match_heap_implementation() {
        let mut rng = XorShift32::new(0x1162);
        for _ in 0..20_000 {
            assert_same(&rng.text(PIECES, 12));
        }
        let mut accepted = 0;
        for _ in 0..20_000 {
            let value = format!("your{}", rng.text(&PIECES[4..18], 10));
            assert_same(&value);
            accepted += usize::from(is_glued_instructional_placeholder(&value));
        }
        assert!(accepted > 100, "generator must reach accepted values");
    }

    #[test]
    fn known_values_and_boundaries() {
        for value in [
            "",
            "your",
            "yourkey",
            "YourSecretToken",
            "yourapikey",
            "yourkeyx",
            "replaceopenaikey",
            "your_key",
            "yourK",
            "pasteyourjwt",
            "yourgithubtoken",
            "yourdummy",
        ] {
            assert_same(value);
        }
        assert!(is_glued_instructional_placeholder("YourSecretToken"));
        assert!(!is_glued_instructional_placeholder("your"));
        assert!(!is_glued_instructional_placeholder("yourk\u{212a}ey"));
    }

    #[test]
    fn lengths_around_the_stack_bound_match() {
        for unit in ["key", "token", "jwtapi"] {
            for target in 240..=300 {
                let mut value = String::from("your");
                while value.len() < target {
                    value.push_str(unit);
                }
                for cut in [0, 1, 2] {
                    let mut candidate = value.clone();
                    candidate.truncate(candidate.len() - cut);
                    assert_same(&candidate);
                    // A non-word tail keeps the value just outside the grammar.
                    candidate.push('q');
                    assert_same(&candidate);
                    candidate.make_ascii_uppercase();
                    assert_same(&candidate);
                }
            }
        }
        let exact = format!("your{}", "key".repeat(84));
        assert_eq!(exact.len(), 256);
        assert!(is_glued_instructional_placeholder(&exact));
        let over = format!("your{}", "key".repeat(85));
        assert_eq!(over.len(), 259);
        assert!(is_glued_instructional_placeholder(&over));
        let long_non_ascii = format!("your{}\u{e9}", "key".repeat(100));
        assert!(!is_glued_instructional_placeholder(&long_non_ascii));
    }
}