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
//! Bounded incremental sanitizer session.
//!
//! A session consumes text in chunks and returns, from each [`append`] and
//! from [`finalize`], only the sanitized text and findings whose detection
//! window is closed: a chunk boundary, a minimum token length, or a
//! provisional match is never a closing boundary by itself. An open logical
//! line, structural authorization header, contextual assignment, PEM-style
//! private-key block, or bounded provider layout awaiting its token line (a
//! Heroku `.netrc` entry, `heroku auth:token` command or `heroku
//! authorizations` table, a `twilio` CLI table with an `Auth Token` column,
//! or a Confluent properties block) is retained until it closes or a
//! configured limit fails. Because retained plaintext is scanned fresh only once per
//! closed unit and never rescanned once finalized, whole-input acceptance
//! does not depend on how the caller partitions it into chunks.
//!
//! The state machine has four terminally distinct states: `accepting` may
//! receive [`append`], `finalize` (exactly once), or [`abort`]; `finalized`,
//! `aborted`, and `failed` are terminal and reject every further call. A
//! limit, detector, policy, or placeholder failure discards retained
//! plaintext and enters `failed`.
//!
//! # Partition invariance
//!
//! For every input this API accepts, the concatenated text, the findings and
//! their actions, their order, IDs and absolute UTF-8 byte ranges, and
//! placeholder numbering are identical to the whole-input reference
//! ([`scan`](crate::scan) then [`redact`](crate::redact)) at every partition
//! of that input — at every UTF-8 byte boundary and at every host-native
//! `&str` boundary. Only the distribution of safe output across [`append`]
//! and [`finalize`] results varies; what those results concatenate to does
//! not. `tests/incremental_partitions.rs` enumerates both boundary kinds
//! over the canonical corpus in `conformance/fixtures/incremental-corpus.json`,
//! and `tests/adversarial_bounds.rs` holds the adversarial tier of
//! `conformance/fixtures/synchronous-corpus.json` to its declared input,
//! finding-count, and runtime caps.
//!
//! # Unsupported extensions
//!
//! Two whole-input capabilities are deliberately outside this API, because
//! neither can be evaluated before the end of the input is known:
//!
//! - **Custom synchronous detectors.** No constructor accepts a
//!   [`DetectorRegistry`]; a session always runs one profile's built-in
//!   detectors only — [`IncrementalSanitizer::new`] and
//!   [`IncrementalSanitizer::with_policy_and_formatter`] select `full`,
//!   [`IncrementalSanitizer::with_common_built_in`] and
//!   [`IncrementalSanitizer::with_common_built_in_policy_and_formatter`]
//!   select `common`
//!   (`decision-define-detector-profile-and-pack-contract`). A custom
//!   [`Detector`](crate::Detector) carries no retention declaration, so a
//!   session could not bound how long it must hold an open construct for
//!   it. Register custom detectors on the whole-input [`scan`](crate::scan)
//!   path instead.
//! - **Whole-input count-dependent policies.** [`PolicyContext`] carries the
//!   total finalized finding count; [`IncrementalPolicyContext`]
//!   deliberately does not, because a progressive evaluation cannot know how
//!   many findings the whole session will produce. A [`Policy`] whose action
//!   depends on [`PolicyContext::finding_count`] therefore has no
//!   incremental equivalent: adapting it to [`IncrementalPolicy`] must
//!   substitute the running index, which yields a different result. Policies
//!   used incrementally must be count-independent, as [`DefaultPolicy`] is.
//!
//! [`append`]: IncrementalSanitizer::append
//! [`finalize`]: IncrementalSanitizer::finalize
//! [`abort`]: IncrementalSanitizer::abort

use std::borrow::Cow;

use crate::composition::Composition;
use crate::detectors::{
    LookbackTail, MAX_LOOKBACK_LINES, PrivateKeyRetentionTracker, carries_aws_access_key_id,
    continues_previous_line, has_open_aws_secret_candidate_line_in, has_open_bearer_authorization,
    has_open_confluent_properties_in, has_open_contextual_assignment, has_open_curl_command,
    has_open_deepgram_request_in, has_open_heroku_legacy_context_in, has_open_list_item_pair_in,
    has_open_provider_sibling_in, has_open_scoped_context_in, has_open_twilio_cli_table_in,
    is_open_tail_neutral, lookback_tail_lines,
};
#[cfg(test)]
use crate::detectors::{
    has_open_aws_secret_candidate_line, has_open_confluent_properties, has_open_deepgram_request,
    has_open_heroku_legacy_context, has_open_list_item_pair, has_open_provider_sibling,
    has_open_scoped_context, has_open_twilio_cli_table,
};
use crate::error::{PolicyFailure, SecretScanError, SecretScanErrorCode};
use crate::evidence::shadow::ShadowComparison;
use crate::limits::WholeInputLimits;
use crate::normalize::NormalizedInput;
use crate::pii::PiiSelection;
#[cfg(test)]
use crate::pipeline::detect;
use crate::pipeline::detect_units;
use crate::policy::DefaultPolicy;
use crate::redact::{default_placeholder_formatter, redact_shifted_into};
use crate::registry::{DetectorRegistry, Profile};
use crate::selection::DetectionSelection;
use crate::types::{
    Action, ByteRange, DetectedFinding, Finding, PlaceholderFormatter, Policy, PolicyContext,
    ScanResult,
};

/// Reserve in bytes for the longest built-in fixed match and its boundary
/// lookaround, that `max_buffered_bytes` must accommodate on top of the
/// larger of `max_token_bytes` and `max_multiline_bytes`.
///
/// This is retention tuning, not a public contract: it tracks the built-in
/// detector set and changes with it. Callers ask
/// [`IncrementalLimits::minimum_buffered_bytes`] for the derived requirement
/// instead of reproducing this arithmetic.
const LOOKAROUND_BYTES: usize = 128;

/// The built-in detector whose multi-line `.netrc` and `heroku auth:token`
/// layouts need a retention hint; a session whose profile omits it (the
/// `common` profile) never holds a unit open for them.
const HEROKU_LEGACY_DETECTOR_ID: &str = "heroku-api-key-legacy";

/// The built-in detectors whose previous-line layouts (issue #933) need a
/// retention hint: a `twilio` CLI table's Auth Token column, and a Confluent
/// Schema Registry properties block. A session without the detector never
/// holds a unit open for its layout.
const TWILIO_AUTH_TOKEN_DETECTOR_ID: &str = "twilio-auth-token";
const CONFLUENT_LEGACY_DETECTOR_ID: &str = "confluent-cloud-api-secret-legacy";

/// The built-in detector that reads an AWS access key ID on the line above a
/// secret access key (issue #1028). A line carrying an ID is released when
/// it closes; the session keeps a copy of it to scan the next unit below it
/// ([`IncrementalSanitizer::lead_after`], issue #1040).
const AWS_SECRET_ACCESS_KEY_DETECTOR_ID: &str = "aws-secret-access-key";

/// Explicit, positive byte limits every incremental session requires. There
/// are no environment-derived or silent defaults.
///
/// `max_buffered_bytes` must be at least
/// [`minimum_buffered_bytes`](Self::minimum_buffered_bytes) for the construct
/// limits it accompanies. A construct that reaches its limit without a
/// closing boundary is not reclassified as ordinary text: the session fails
/// before any of its bytes are emitted.
///
/// # Examples
///
/// ```
/// use redact_secret::IncrementalLimits;
///
/// let (token, multiline) = (4_096, 16_384);
/// let limits = IncrementalLimits::new(
///     1 << 20,
///     IncrementalLimits::minimum_buffered_bytes(token, multiline),
///     token,
///     multiline,
/// )?;
/// assert_eq!(limits.max_token_bytes(), token);
/// # Ok::<(), redact_secret::SecretScanError>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[allow(clippy::struct_field_names)]
pub struct IncrementalLimits {
    max_input_bytes: usize,
    max_buffered_bytes: usize,
    max_token_bytes: usize,
    max_multiline_bytes: usize,
}

impl IncrementalLimits {
    /// The smallest `max_buffered_bytes` [`new`](Self::new) accepts
    /// alongside these construct limits: the larger of the two plus the
    /// boundary lookaround the built-in detectors need to decide whether a
    /// construct is still open.
    ///
    /// The lookaround reserve itself is an implementation detail that tracks
    /// the built-in detector set. Deriving the limit through this function
    /// keeps a caller correct when that reserve changes.
    #[must_use]
    pub const fn minimum_buffered_bytes(
        max_token_bytes: usize,
        max_multiline_bytes: usize,
    ) -> usize {
        let construct_max = if max_token_bytes > max_multiline_bytes {
            max_token_bytes
        } else {
            max_multiline_bytes
        };
        construct_max.saturating_add(LOOKAROUND_BYTES)
    }

    /// Validates and creates a limit set.
    ///
    /// # Errors
    ///
    /// Returns [`SecretScanErrorCode::InvalidLimits`] when any limit is
    /// zero, when `max_token_bytes` or `max_multiline_bytes` exceeds
    /// `max_input_bytes`, or when `max_buffered_bytes` is below
    /// [`minimum_buffered_bytes`](Self::minimum_buffered_bytes).
    pub fn new(
        max_input_bytes: usize,
        max_buffered_bytes: usize,
        max_token_bytes: usize,
        max_multiline_bytes: usize,
    ) -> Result<Self, SecretScanError> {
        let construct_max = max_token_bytes.max(max_multiline_bytes);
        let invalid = max_input_bytes == 0
            || max_buffered_bytes == 0
            || max_token_bytes == 0
            || max_multiline_bytes == 0
            || max_token_bytes > max_input_bytes
            || max_multiline_bytes > max_input_bytes
            || construct_max > usize::MAX - LOOKAROUND_BYTES
            || max_buffered_bytes
                < Self::minimum_buffered_bytes(max_token_bytes, max_multiline_bytes);
        if invalid {
            return Err(SecretScanErrorCode::InvalidLimits.into());
        }
        Ok(Self {
            max_input_bytes,
            max_buffered_bytes,
            max_token_bytes,
            max_multiline_bytes,
        })
    }

    /// Total logical input this session accepts across every `append` call.
    #[must_use]
    pub const fn max_input_bytes(self) -> usize {
        self.max_input_bytes
    }

    /// Unresolved plaintext this session may retain but not yet have
    /// emitted.
    #[must_use]
    pub const fn max_buffered_bytes(self) -> usize {
        self.max_buffered_bytes
    }

    /// Bound for an open logical line, single-line credential, or other
    /// delimiter-terminated token.
    #[must_use]
    pub const fn max_token_bytes(self) -> usize {
        self.max_token_bytes
    }

    /// Bound for an open PEM-style private-key block.
    #[must_use]
    pub const fn max_multiline_bytes(self) -> usize {
        self.max_multiline_bytes
    }
}

/// Position information an incremental policy receives.
///
/// Unlike [`PolicyContext`], there is no total finding count: progressive
/// evaluation cannot know how many findings the whole session will
/// eventually produce.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct IncrementalPolicyContext {
    finding_index: usize,
}

impl IncrementalPolicyContext {
    /// Creates a context for the given zero-based finalized finding index.
    #[must_use]
    pub const fn new(finding_index: usize) -> Self {
        Self { finding_index }
    }

    /// Zero-based position among findings finalized so far in this session.
    #[must_use]
    pub const fn finding_index(self) -> usize {
        self.finding_index
    }
}

/// Maps a finalized finding to an [`Action`] within an incremental session.
///
/// A policy never sees the input, a matched value, or a total finding
/// count.
pub trait IncrementalPolicy {
    /// Chooses the action for `finding`.
    ///
    /// # Errors
    ///
    /// Returns [`PolicyFailure`] on any internal failure. The session
    /// reports it as [`SecretScanErrorCode::PolicyFailure`] and fails.
    fn evaluate(
        &self,
        finding: &DetectedFinding,
        context: &IncrementalPolicyContext,
    ) -> Result<Action, PolicyFailure>;
}

impl<F> IncrementalPolicy for F
where
    F: Fn(&DetectedFinding, &IncrementalPolicyContext) -> Result<Action, PolicyFailure>,
{
    fn evaluate(
        &self,
        finding: &DetectedFinding,
        context: &IncrementalPolicyContext,
    ) -> Result<Action, PolicyFailure> {
        self(finding, context)
    }
}

/// The default incremental policy has the same action mapping as
/// [`DefaultPolicy`]'s whole-input evaluation: it does not depend on
/// [`PolicyContext`], so adapting it to [`IncrementalPolicyContext`] changes
/// nothing observable.
impl IncrementalPolicy for DefaultPolicy {
    fn evaluate(
        &self,
        finding: &DetectedFinding,
        _context: &IncrementalPolicyContext,
    ) -> Result<Action, PolicyFailure> {
        Policy::evaluate(self, finding, &PolicyContext::new(0, 0))
    }
}

/// The terminally distinct lifecycle states of an [`IncrementalSanitizer`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SessionState {
    /// May receive `append`, `finalize`, or `abort`.
    Accepting,
    /// Reached by exactly one successful `finalize`. Terminal.
    Finalized,
    /// Reached by `abort`. Terminal.
    Aborted,
    /// Reached by a limit, detector, policy, or placeholder failure.
    /// Terminal.
    Failed,
}

/// The sanitized text and final findings produced by one `append` or
/// `finalize` call.
///
/// This is [`ScanResult`] under the name the incremental API reports it by:
/// the whole-input and chunked paths return the same shape, so a host can
/// carry one result type. [`text`](ScanResult::text) is the safe output this
/// call releases — concatenating every `append`/`finalize` result's text, in
/// call order, reconstructs the whole sanitized output — and
/// [`findings`](ScanResult::findings) are the findings this call finalized,
/// with absolute UTF-8 byte offsets into the logical whole-session input.
pub type IncrementalResult = ScanResult;

/// Text and findings released by one `append` or `finalize` call so far.
#[derive(Default)]
struct Released {
    text: String,
    findings: Vec<Finding>,
}

/// `found` with its range moved `by` bytes later; every other field is
/// moved, not rebuilt (issue #1060).
fn offset_by(found: DetectedFinding, by: usize) -> Result<DetectedFinding, SecretScanError> {
    let range = found.range();
    let range = ByteRange::new(range.start() + by, range.end() + by)
        .ok_or(SecretScanErrorCode::InvalidCandidate)?;
    Ok(found.with_range(range))
}

/// Detects the unit `input[lead..]` alone, as
/// [`detect`](crate::pipeline::detect) does, but with the released line
/// above it, a nonzero `input[..lead]`, scanned as a read-only unit (issue
/// #1040). When a candidate would cross from the lead into the unit, the
/// unit is scanned without it, as it was before the lead existed. The lead
/// and the unit are contiguous in the session's buffer, so neither is
/// copied (issue #1060).
fn detect_after(
    input: &str,
    lead: usize,
    registry: &DetectorRegistry,
    mut shadow: Option<&mut Vec<ShadowComparison>>,
) -> Result<Vec<DetectedFinding>, SecretScanError> {
    if lead > 0
        && let Some(detected) = detect_units(input, lead, registry, &[lead], shadow.as_deref_mut())?
    {
        return Ok(detected);
    }
    detect_units(&input[lead..], 0, registry, &[], shadow).map(Option::unwrap_or_default)
}

/// Detects the closed units of `input[lead..]`, ending at `unit_ends`
/// (offsets in `input`), together ([`detect_units`]), with the released
/// line above them, a nonzero `input[..lead]`, scanned as a read-only unit
/// (issue #1040). `None` when the units are not separable or detection
/// fails; the caller then scans unit by unit.
fn detect_batch(
    input: &str,
    lead: usize,
    unit_ends: &[usize],
    registry: &DetectorRegistry,
    shadow: Option<&mut Vec<ShadowComparison>>,
) -> Option<Vec<DetectedFinding>> {
    let detected = if lead > 0 {
        let mut ends = Vec::with_capacity(unit_ends.len() + 1);
        ends.push(lead);
        ends.extend_from_slice(unit_ends);
        detect_units(input, lead, registry, &ends, shadow)
    } else {
        detect_units(input, 0, registry, unit_ends, shadow)
    };
    detected.ok().flatten()
}

/// Which open-construct checks hold the current unit open: the AWS
/// secret-candidate hold (issue #1044) is kept apart, because a unit held
/// only by it may be split before its last line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct OpenConstructs {
    other: bool,
    aws_secret_candidate: bool,
}

/// Where the last line of `text` starts: after the line terminator before
/// its own (`\n`, `\r\n` or a lone `\r`), or 0.
fn last_line_start(text: &str) -> usize {
    let body = text.strip_suffix('\n').unwrap_or(text);
    let body = body.strip_suffix('\r').unwrap_or(body);
    body.rfind(['\n', '\r']).map_or(0, |at| at + 1)
}

/// The last line of `text`, with its terminator.
fn last_line(text: &str) -> &str {
    &text[last_line_start(text)..]
}

/// Finds the byte offset of the next `\n` or `\r` at or after `from`, or
/// `None` when `chunk` has no more line terminators.
fn find_next_newline(chunk: &str, from: usize) -> Option<usize> {
    chunk.as_bytes()[from..]
        .iter()
        .position(|&byte| byte == b'\n' || byte == b'\r')
        .map(|index| index + from)
}

/// The last result of the two open-construct checks whose backward scan is
/// unbounded, [`has_open_contextual_assignment`] and
/// [`has_open_bearer_authorization`]: whether either reports an open construct
/// over the first `checked_len` bytes of the unit's scan copy. Both are
/// unchanged by appended whitespace ([`is_open_tail_neutral`]), so the result
/// is recomputed only when a closed line brings other content, and every gap
/// of blank lines is crossed once instead of once per line (issue #986).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct OpenTailCache {
    checked_len: usize,
    open: bool,
}

/// Which lookback retention hints apply: whether the registry holds the
/// detector each one serves. The registry never changes after construction,
/// so this is decided once instead of on every closed line.
#[derive(Clone, Copy, Debug)]
#[allow(clippy::struct_excessive_bools)]
struct LookbackHints {
    heroku_legacy: bool,
    twilio_auth_token: bool,
    confluent_legacy: bool,
    list_item_pair: bool,
    provider_sibling: bool,
    deepgram_request: bool,
    scoped_context: bool,
    curl_user: bool,
    aws_secret_access_key: bool,
}

impl LookbackHints {
    /// Whether any hint but the AWS one applies.
    const fn any_other(self) -> bool {
        self.heroku_legacy
            || self.twilio_auth_token
            || self.confluent_legacy
            || self.list_item_pair
            || self.provider_sibling
            || self.deepgram_request
            || self.scoped_context
    }

    fn of(registry: &DetectorRegistry) -> Self {
        Self {
            heroku_legacy: registry.contains(HEROKU_LEGACY_DETECTOR_ID),
            twilio_auth_token: registry.contains(TWILIO_AUTH_TOKEN_DETECTOR_ID),
            confluent_legacy: registry.contains(CONFLUENT_LEGACY_DETECTOR_ID),
            list_item_pair: reads_list_item_pairs(registry),
            provider_sibling: reads_provider_siblings(registry),
            deepgram_request: registry.contains(DEEPGRAM_DETECTOR_ID),
            scoped_context: registry.contains(GENERIC_TOKEN_DETECTOR_ID),
            curl_user: registry.contains(GENERIC_TOKEN_DETECTOR_ID),
            aws_secret_access_key: registry.contains(AWS_SECRET_ACCESS_KEY_DETECTOR_ID),
        }
    }
}

/// Detectors that read a Kubernetes-style `env` entry's `name:`/`value:`
/// pair across two lines (issue #1016).
const LIST_ITEM_PAIR_DETECTOR_IDS: &[&str] = &[
    "generic-token",
    "mistral-api-key",
    "cohere-api-key",
    "ai21-api-key",
    "deepgram-api-key",
];

fn reads_list_item_pairs(registry: &DetectorRegistry) -> bool {
    LIST_ITEM_PAIR_DETECTOR_IDS
        .iter()
        .any(|id| registry.contains(id))
}

/// The keyword-gated detectors, which read a sibling `provider:` key above
/// a credential key (issue #1017).
fn reads_provider_siblings(registry: &DetectorRegistry) -> bool {
    LIST_ITEM_PAIR_DETECTOR_IDS[1..]
        .iter()
        .any(|id| registry.contains(id))
}

/// `deepgram-api-key` also reads the request line or `Host:` header above
/// a token header (issue #1017).
const DEEPGRAM_DETECTOR_ID: &str = "deepgram-api-key";

/// `generic-token` also reads a scoped name beside a sibling member within a
/// few lines (`has_open_scoped_context_in`, issues #1228 to #1230), and the
/// password argument of a `curl` command whose line continues or whose quote
/// is still open (`has_open_curl_command`, issue #1247).
const GENERIC_TOKEN_DETECTOR_ID: &str = "generic-token";

/// A bounded, side-effect-free incremental sanitizer session over built-in
/// detectors. Custom detectors are not accepted: each has no retention
/// declaration, so the session cannot bound what it must hold open.
///
/// # Examples
///
/// ```
/// use redact_secret::{IncrementalLimits, IncrementalSanitizer, SessionState};
///
/// let (token, multiline) = (8_192, 16_384);
/// let limits = IncrementalLimits::new(
///     1 << 20,
///     IncrementalLimits::minimum_buffered_bytes(token, multiline),
///     token,
///     multiline,
/// )?;
/// let mut session = IncrementalSanitizer::new(limits)?;
///
/// let mut output = String::new();
/// // A value split across chunks is held until its detection window closes.
/// for chunk in ["API_KEY=ghp_SYNTHETIC", "REVOKED00000000000000000000\ntail"] {
///     output.push_str(session.append(chunk)?.text());
/// }
/// output.push_str(session.finalize()?.text());
///
/// assert_eq!(output, "API_KEY=<SECRET_1>\ntail");
/// assert_eq!(session.state(), SessionState::Finalized);
/// # Ok::<(), redact_secret::SecretScanError>(())
/// ```
pub struct IncrementalSanitizer {
    registry: DetectorRegistry,
    policy: Box<dyn IncrementalPolicy>,
    formatter: Box<dyn PlaceholderFormatter>,
    limits: IncrementalLimits,
    state: SessionState,
    /// The released line above the batch ([`Self::lead_after`]), when one is
    /// kept, then the closed units waiting in the current batch, then the
    /// current unit. The lead sits in front of the batch so the two scan as
    /// one contiguous slice (issue #1060).
    retained: String,
    /// How many bytes at the start of `retained` are the lead: a copy of the
    /// released line directly above the batch, kept only while a detector
    /// reads it from the next unit. It is never emitted again and counts
    /// toward no limit.
    lead_len: usize,
    /// Where the current unit starts in `retained`.
    unit_start: usize,
    /// Where each closed unit in the batch ends in `retained`, ascending;
    /// the last one is `unit_start`.
    unit_ends: Vec<usize>,
    /// The scan copy of the current unit, normalized piece by piece as it is
    /// appended. Held only once a piece of this unit actually lost an
    /// invisible code point; until then the scan copy is the unit itself, so
    /// an ordinary unit is never copied (issue #986).
    scanned: Option<String>,
    open_tail: OpenTailCache,
    lookbacks: LookbackHints,
    /// When the current unit is open only because its last line holds an
    /// unclaimed AWS secret-shaped run (issue #1044): where that line starts,
    /// relative to `unit_start`.
    aws_held_line: Option<usize>,
    finalized_bytes: usize,
    total_input_bytes: usize,
    finding_count: usize,
    placeholder_count: usize,
    private_key: PrivateKeyRetentionTracker,
    multiline_open: bool,
    multiline_detected: bool,
    /// Shadow comparisons of every finalized unit's findings, in session
    /// coordinates, when a maintainer-local caller asked for them (#771).
    /// Always `None` for a session built through the public API, so the
    /// scorer never runs on the public incremental path.
    #[cfg(test)]
    shadow: Option<Vec<ShadowComparison>>,
    /// Processes every unit as soon as it closes, as before batching: the
    /// reference the batched path is compared with (issue #985).
    #[cfg(test)]
    unbatched: bool,
    /// Units detected together in one pipeline call so far.
    #[cfg(test)]
    batched_units: usize,
    /// The most bytes `retained` has held.
    #[cfg(test)]
    peak_retained: usize,
}

impl std::fmt::Debug for IncrementalSanitizer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IncrementalSanitizer")
            .field("state", &self.state)
            .field("limits", &self.limits)
            .finish_non_exhaustive()
    }
}

impl IncrementalSanitizer {
    /// Creates a session using [`DefaultPolicy`] and
    /// [`default_placeholder_formatter`].
    ///
    /// # Errors
    ///
    /// Returns [`SecretScanErrorCode::InvalidDetector`] only if the
    /// built-in detector registry itself is malformed, which cannot happen
    /// for the detectors this crate ships.
    pub fn new(limits: IncrementalLimits) -> Result<Self, SecretScanError> {
        Self::with_policy_and_formatter(
            limits,
            Box::new(DefaultPolicy),
            Box::new(default_placeholder_formatter),
        )
    }

    /// Creates a session with an explicit policy and placeholder formatter.
    ///
    /// # Errors
    ///
    /// Returns [`SecretScanErrorCode::InvalidDetector`] only if the
    /// built-in detector registry itself is malformed, which cannot happen
    /// for the detectors this crate ships.
    pub fn with_policy_and_formatter(
        limits: IncrementalLimits,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry = DetectorRegistry::with_built_in([])?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    /// Creates a session over the `common` profile's built-in detectors
    /// (`decision-define-detector-profile-and-pack-contract`), using
    /// [`DefaultPolicy`] and [`default_placeholder_formatter`].
    ///
    /// The whole-input and incremental paths select their built-in
    /// detectors the same way: this constructor pairs with
    /// [`DetectorRegistry::with_common_built_in`] exactly as [`Self::new`]
    /// pairs with [`DetectorRegistry::with_built_in`].
    ///
    /// # Errors
    ///
    /// Returns [`SecretScanErrorCode::InvalidDetector`] only if the
    /// built-in detector registry itself is malformed, which cannot happen
    /// for the detectors this crate ships.
    pub fn with_common_built_in(limits: IncrementalLimits) -> Result<Self, SecretScanError> {
        Self::with_common_built_in_policy_and_formatter(
            limits,
            Box::new(DefaultPolicy),
            Box::new(default_placeholder_formatter),
        )
    }

    /// Creates a session over the `common` profile's built-in detectors,
    /// with an explicit policy and placeholder formatter.
    ///
    /// # Errors
    ///
    /// Returns [`SecretScanErrorCode::InvalidDetector`] only if the
    /// built-in detector registry itself is malformed, which cannot happen
    /// for the detectors this crate ships.
    pub fn with_common_built_in_policy_and_formatter(
        limits: IncrementalLimits,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry = DetectorRegistry::with_common_built_in([])?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    /// Creates a `full` session that captures `selection` at construction.
    ///
    /// # Errors
    ///
    /// Returns [`SecretScanErrorCode::InvalidDetector`] if registration fails.
    pub fn with_built_in_and_pii(
        limits: IncrementalLimits,
        selection: &PiiSelection,
    ) -> Result<Self, SecretScanError> {
        Self::with_built_in_and_pii_policy_and_formatter(
            limits,
            selection,
            Box::new(DefaultPolicy),
            Box::new(default_placeholder_formatter),
        )
    }

    /// Creates a `full` PII-aware session with explicit callbacks.
    ///
    /// # Errors
    ///
    /// Returns [`SecretScanErrorCode::InvalidDetector`] if registration fails.
    pub fn with_built_in_and_pii_policy_and_formatter(
        limits: IncrementalLimits,
        selection: &PiiSelection,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry = DetectorRegistry::with_built_in_and_pii(selection)?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    /// Creates a `common` session that captures `selection` at construction.
    ///
    /// # Errors
    ///
    /// Returns [`SecretScanErrorCode::InvalidDetector`] if registration fails.
    pub fn with_common_built_in_and_pii_policy_and_formatter(
        limits: IncrementalLimits,
        selection: &PiiSelection,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry = DetectorRegistry::with_common_built_in_and_pii(selection)?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    /// Creates a `full` session over the built-in detectors `detection`
    /// leaves enabled (issue #1251), with PII off.
    ///
    /// The session captures that configuration here, once, for its whole
    /// life: no later call, selection or registry can change what it
    /// detects, and it takes no custom detector and no ruleset, so there is
    /// no new claim that incremental accepts either. With
    /// [`DetectionSelection::all`] it is exactly
    /// [`Self::with_policy_and_formatter`].
    ///
    /// # Errors
    ///
    /// [`SecretScanErrorCode::InvalidDetectionConfig`] when `detection`
    /// names an unknown, not-included or repeated id, and
    /// [`SecretScanErrorCode::EmptyDetectionSet`] when it leaves nothing
    /// enabled.
    pub fn with_detection_policy_and_formatter(
        limits: IncrementalLimits,
        detection: &DetectionSelection,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry = DetectorRegistry::with_built_in([])?.with_detection(detection)?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    /// The `common` analogue of [`Self::with_detection_policy_and_formatter`].
    /// A `common` session never makes the `full` constructor reachable.
    ///
    /// # Errors
    ///
    /// As [`Self::with_detection_policy_and_formatter`].
    pub fn with_common_built_in_detection_policy_and_formatter(
        limits: IncrementalLimits,
        detection: &DetectionSelection,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry = DetectorRegistry::with_common_built_in([])?.with_detection(detection)?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    /// The `full` PII-aware analogue of
    /// [`Self::with_detection_policy_and_formatter`]: the session captures
    /// `selection` and `detection` together at construction.
    ///
    /// # Errors
    ///
    /// As [`Self::with_detection_policy_and_formatter`].
    pub fn with_built_in_and_pii_detection_policy_and_formatter(
        limits: IncrementalLimits,
        selection: &PiiSelection,
        detection: &DetectionSelection,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry =
            DetectorRegistry::with_built_in_and_pii(selection)?.with_detection(detection)?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    /// The `common` PII-aware analogue of
    /// [`Self::with_built_in_and_pii_detection_policy_and_formatter`].
    ///
    /// # Errors
    ///
    /// As [`Self::with_detection_policy_and_formatter`].
    pub fn with_common_built_in_and_pii_detection_policy_and_formatter(
        limits: IncrementalLimits,
        selection: &PiiSelection,
        detection: &DetectionSelection,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry =
            DetectorRegistry::with_common_built_in_and_pii(selection)?.with_detection(detection)?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    /// The analogue of [`Self::with_detection_policy_and_formatter`] over a
    /// static custom [`Composition`] (issue #1253): the session runs exactly
    /// the composition's detectors, narrowed by `detection`, and never makes
    /// another built-in detector reachable.
    ///
    /// # Errors
    ///
    /// As [`Self::with_detection_policy_and_formatter`].
    pub fn with_composition_detection_policy_and_formatter(
        limits: IncrementalLimits,
        composition: &Composition,
        detection: &DetectionSelection,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry =
            DetectorRegistry::with_composition(composition, [])?.with_detection(detection)?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    /// The PII-aware analogue of
    /// [`Self::with_composition_detection_policy_and_formatter`].
    ///
    /// # Errors
    ///
    /// As [`Self::with_detection_policy_and_formatter`].
    pub fn with_composition_and_pii_detection_policy_and_formatter(
        limits: IncrementalLimits,
        composition: &Composition,
        selection: &PiiSelection,
        detection: &DetectionSelection,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Result<Self, SecretScanError> {
        let registry = DetectorRegistry::with_composition_and_pii(composition, selection, [])?
            .with_detection(detection)?;
        Ok(Self::from_registry(registry, limits, policy, formatter))
    }

    pub(crate) fn from_registry(
        registry: DetectorRegistry,
        limits: IncrementalLimits,
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> Self {
        let lookbacks = LookbackHints::of(&registry);
        Self {
            registry,
            policy,
            formatter,
            limits,
            state: SessionState::Accepting,
            retained: String::new(),
            lead_len: 0,
            unit_start: 0,
            unit_ends: Vec::new(),
            scanned: None,
            open_tail: OpenTailCache::default(),
            lookbacks,
            aws_held_line: None,
            finalized_bytes: 0,
            total_input_bytes: 0,
            finding_count: 0,
            placeholder_count: 0,
            private_key: PrivateKeyRetentionTracker::new(),
            multiline_open: false,
            multiline_detected: false,
            #[cfg(test)]
            shadow: None,
            #[cfg(test)]
            unbatched: false,
            #[cfg(test)]
            batched_units: 0,
            #[cfg(test)]
            peak_retained: 0,
        }
    }

    /// Starts recording the shadow comparison of every finding this session
    /// finalizes from now on.
    #[cfg(test)]
    pub(crate) fn record_shadow(&mut self) {
        self.shadow = Some(Vec::new());
    }

    /// The shadow comparisons recorded so far, in session coordinates.
    #[cfg(test)]
    pub(crate) fn take_shadow(&mut self) -> Vec<ShadowComparison> {
        self.shadow.take().unwrap_or_default()
    }

    /// The session's current lifecycle state.
    #[must_use]
    pub const fn state(&self) -> SessionState {
        self.state
    }

    /// Which profile this session's built-in detectors were selected from.
    #[must_use]
    pub const fn profile(&self) -> Option<Profile> {
        self.registry.profile()
    }

    /// Canonical activation captured when this session was constructed.
    #[must_use]
    pub fn activation_identity(&self) -> &str {
        self.registry.activation_identity()
    }

    fn require_accepting(&self) -> Result<(), SecretScanError> {
        if matches!(self.state, SessionState::Accepting) {
            Ok(())
        } else {
            Err(SecretScanErrorCode::InvalidState.into())
        }
    }

    /// Discards retained plaintext and every parser state derived from it.
    ///
    /// The buffer is released rather than truncated: `clear` would leave the
    /// discarded bytes alive in a reusable allocation, and the retention
    /// contract is to drop them.
    fn discard_retained(&mut self) {
        self.retained = String::new();
        self.lead_len = 0;
        self.unit_start = 0;
        self.unit_ends = Vec::new();
        self.reset_unit_state();
    }

    /// Clears the parser state derived from the current unit: at a unit
    /// boundary, and with the plaintext it was derived from.
    fn reset_unit_state(&mut self) {
        self.scanned = None;
        self.aws_held_line = None;
        self.open_tail = OpenTailCache::default();
        self.private_key.reset();
        self.multiline_open = false;
        self.multiline_detected = false;
    }

    /// Discards retained plaintext and parser state and transitions to
    /// `failed`, returning `error` unchanged so callers can propagate it
    /// with `return Err(self.fail_with(error))`.
    fn fail_with(&mut self, error: SecretScanError) -> SecretScanError {
        self.discard_retained();
        self.state = SessionState::Failed;
        error
    }

    /// Judges the current unit the way the pipeline will scan it: on the
    /// scan copy. Judged on the raw buffer, a keyword split by an invisible
    /// code point at a line end would not read as an open construct, the
    /// unit would close early, and the same input would yield different
    /// findings under a different partition.
    ///
    /// The scan copy is maintained as pieces arrive rather than rebuilt here,
    /// and the two tail checks, whose backward scan crosses any run of blank
    /// lines, reuse their last result when only whitespace has arrived since
    /// (issue #986). The four lookback checks read a bounded number of lines
    /// and run as before. Only the current unit is judged: closed units
    /// waiting in the batch are never part of it (issue #985).
    fn has_open_single_line_construct(&mut self) -> OpenConstructs {
        let scanned = self
            .scanned
            .as_deref()
            .unwrap_or(&self.retained[self.unit_start..]);
        if !is_open_tail_neutral(&scanned[self.open_tail.checked_len..]) {
            self.open_tail.open =
                has_open_contextual_assignment(scanned) || has_open_bearer_authorization(scanned);
        }
        self.open_tail.checked_len = scanned.len();

        let scanned = self
            .scanned
            .as_deref()
            .unwrap_or(&self.retained[self.unit_start..]);
        let lookbacks = self.lookbacks;
        // Every lookback hint reads its own last lines of one shared tail,
        // walked once per closed line (issue #1060).
        // While an open tail check already holds the unit, only the AWS hint
        // reads it, and it reads two lines (issue #1074).
        let others_read = !self.open_tail.open && lookbacks.any_other();
        let tail = if others_read || lookbacks.aws_secret_access_key {
            lookback_tail_lines(scanned, if others_read { MAX_LOOKBACK_LINES } else { 2 })
        } else {
            LookbackTail::empty()
        };
        let tail = tail.as_slice();
        let open = OpenConstructs {
            other: self.open_tail.open
                || (lookbacks.heroku_legacy && has_open_heroku_legacy_context_in(tail))
                || (lookbacks.twilio_auth_token && has_open_twilio_cli_table_in(tail))
                || (lookbacks.confluent_legacy && has_open_confluent_properties_in(tail))
                || (lookbacks.list_item_pair && has_open_list_item_pair_in(tail))
                || (lookbacks.provider_sibling && has_open_provider_sibling_in(tail))
                || (lookbacks.deepgram_request && has_open_deepgram_request_in(tail))
                || (lookbacks.scoped_context && has_open_scoped_context_in(tail))
                || (lookbacks.curl_user && has_open_curl_command(scanned)),
            aws_secret_candidate: lookbacks.aws_secret_access_key
                && has_open_aws_secret_candidate_line_in(tail, || {
                    self.line_above_unit_carries_aws_id()
                }),
        };
        #[cfg(test)]
        self.assert_open_construct_matches_the_rescan(open);
        open
    }

    /// Whether the line directly above the current unit carries an AWS access
    /// key ID: the last line of the closed units waiting in the batch, or the
    /// released lead ([`Self::lead_after`]), which is kept exactly when its
    /// line carries one.
    fn line_above_unit_carries_aws_id(&self) -> bool {
        let above = &self.retained[self.lead_len..self.unit_start];
        // Only the `\n` of a CRLF pair whose `\r` closed the lead's unit:
        // the line above is still the lead's.
        if above.is_empty() || (above == "\n" && self.retained[..self.lead_len].ends_with('\r')) {
            self.lead_len > 0
        } else {
            carries_aws_access_key_id(&NormalizedInput::new(last_line(above)).into_text())
        }
    }

    /// Ends the current unit before its last line and starts the next unit
    /// with that line (issue #1044). Called when the line above it was held
    /// only for an AWS secret-shaped run ([`has_open_aws_secret_candidate_line`])
    /// and the new last line, which carries no access key ID, holds another
    /// one: the earlier line's run is settled, so a run of such lines never
    /// accumulates. The earlier unit closes exactly where it would have closed
    /// without that hold.
    fn split_before_last_line(&mut self, released: &mut Released) -> Result<(), SecretScanError> {
        let line_start = self.unit_start + last_line_start(&self.retained[self.unit_start..]);
        let line = self.retained.split_off(line_start);
        if let Some(scanned) = self.scanned.as_mut() {
            let line_scanned = NormalizedInput::new(&line).into_text();
            scanned.truncate(scanned.len() - line_scanned.len());
        }
        self.close_unit(released)
            .map_err(|error| self.fail_with(error))?;
        self.append_retained(&line, true, released)
    }

    /// Differential check (issue #986): the maintained scan copy and the
    /// cached tail result equal what a fresh normalization and rescan of the
    /// whole current unit report, after every closed line of every test that
    /// drives a session.
    #[cfg(test)]
    fn assert_open_construct_matches_the_rescan(&self, open: OpenConstructs) {
        let unit = &self.retained[self.unit_start..];
        let rescanned = NormalizedInput::new(unit).into_text();
        assert_eq!(
            self.scanned.as_deref().unwrap_or(unit),
            rescanned,
            "maintained scan copy"
        );
        let tail_open =
            has_open_contextual_assignment(&rescanned) || has_open_bearer_authorization(&rescanned);
        assert_eq!(self.open_tail.open, tail_open, "cached tail checks");
        let reference = tail_open
            || (self.registry.contains(HEROKU_LEGACY_DETECTOR_ID)
                && has_open_heroku_legacy_context(&rescanned))
            || (self.registry.contains(TWILIO_AUTH_TOKEN_DETECTOR_ID)
                && has_open_twilio_cli_table(&rescanned))
            || (self.registry.contains(CONFLUENT_LEGACY_DETECTOR_ID)
                && has_open_confluent_properties(&rescanned))
            || (reads_list_item_pairs(&self.registry) && has_open_list_item_pair(&rescanned))
            || (reads_provider_siblings(&self.registry) && has_open_provider_sibling(&rescanned))
            || (self.registry.contains(DEEPGRAM_DETECTOR_ID)
                && has_open_deepgram_request(&rescanned))
            || (self.registry.contains(GENERIC_TOKEN_DETECTOR_ID)
                && has_open_scoped_context(&rescanned))
            || (self.registry.contains(GENERIC_TOKEN_DETECTOR_ID)
                && has_open_curl_command(&rescanned));
        assert_eq!(open.other, reference, "open single-line construct");
        let aws_reference = self.registry.contains(AWS_SECRET_ACCESS_KEY_DETECTOR_ID)
            && has_open_aws_secret_candidate_line(&rescanned, || {
                self.line_above_unit_carries_aws_id()
            });
        assert_eq!(
            open.aws_secret_candidate, aws_reference,
            "open AWS secret candidate line"
        );
    }

    /// Adds `piece` to the current unit and enforces the limits on it.
    ///
    /// Every limit is measured on the current unit alone, exactly as when
    /// each unit was processed as soon as it closed: closed units waiting in
    /// the batch are not retained constructs. They are processed first
    /// whenever the buffer would otherwise outgrow `max_buffered_bytes`, and
    /// before any limit failure, so a failure in an earlier unit is still
    /// the one reported (issue #985).
    fn append_retained(
        &mut self,
        piece: &str,
        closes_line: bool,
        released: &mut Released,
    ) -> Result<(), SecretScanError> {
        // The lead was already released: it is not buffered input.
        if !self.unit_ends.is_empty()
            && self.retained.len() - self.lead_len + piece.len() > self.limits.max_buffered_bytes()
        {
            self.flush_batch(released)
                .map_err(|error| self.fail_with(error))?;
        }

        // The tracker and the open-construct checks read the scan copy, as
        // the detectors will. A piece is whole code points, so normalizing
        // piece by piece equals normalizing the unit. Every limit below is a
        // memory bound and stays measured in original bytes.
        let normalized = NormalizedInput::new(piece).into_text();
        match (&mut self.scanned, &normalized) {
            (Some(scanned), _) => scanned.push_str(&normalized),
            (None, Cow::Owned(normalized)) => {
                let unit = &self.retained[self.unit_start..];
                let mut scanned = String::with_capacity(unit.len() + normalized.len());
                scanned.push_str(unit);
                scanned.push_str(normalized);
                self.scanned = Some(scanned);
            }
            (None, Cow::Borrowed(_)) => {}
        }
        self.retained.push_str(piece);
        #[cfg(test)]
        {
            self.peak_retained = self.peak_retained.max(self.retained.len() - self.lead_len);
        }
        let (has_begin, has_open) = self.private_key.append(&normalized);
        self.multiline_detected |= has_begin;
        self.multiline_open = has_open;

        let construct_limit = if self.multiline_detected {
            self.limits.max_multiline_bytes()
        } else {
            self.limits.max_token_bytes()
        };
        let unit_length = self.retained.len() - self.unit_start;
        let open_length = if closes_line {
            unit_length - 1
        } else {
            unit_length
        };
        let exceeded = if open_length > construct_limit {
            Some(if self.multiline_detected {
                SecretScanErrorCode::MultilineLimitExceeded
            } else {
                SecretScanErrorCode::TokenLimitExceeded
            })
        } else if unit_length > self.limits.max_buffered_bytes() {
            Some(SecretScanErrorCode::BufferLimitExceeded)
        } else {
            None
        };
        if let Some(code) = exceeded {
            let error = self.flush_batch(released).err().unwrap_or(code.into());
            return Err(self.fail_with(error));
        }
        Ok(())
    }

    /// Ends the current unit at the end of the buffer and adds it to the
    /// batch of closed units (issue #985).
    ///
    /// A unit that a detector could bind to the text before it starts a new
    /// batch instead ([`starts_new_batch`](Self::starts_new_batch)), so every
    /// batch scans each of its units exactly as that unit alone would scan.
    fn close_unit(&mut self, released: &mut Released) -> Result<(), SecretScanError> {
        if !self.unit_ends.is_empty() && self.starts_new_batch() {
            self.flush_batch(released)?;
        }
        self.unit_ends.push(self.retained.len());
        self.unit_start = self.retained.len();
        self.reset_unit_state();
        #[cfg(test)]
        if self.unbatched {
            self.flush_batch(released)?;
        }
        Ok(())
    }

    /// Whether the current unit, about to close behind at least one closed
    /// unit, must not share a batch with the units before it. See the audit
    /// in [`docs/audits/evidence/985/README.md`](https://github.com/redact-secret/redact-secret/blob/2816897f96c405c3eb8c87a0c70eba5df273c121/docs/audits/evidence/985/README.md).
    ///
    /// That is a unit whose text starts with a construct a detector continues
    /// from the text before it ([`continues_previous_line`]).
    ///
    /// A unit after a lone `\r` used to start a new batch too, because
    /// several detectors split lines at `\n` only and read two
    /// `\r`-separated units as one line. Every detector now ends a line at a
    /// lone `\r` as well, as the session ends a unit there (issue #990), so
    /// such units batch like any others.
    fn starts_new_batch(&self) -> bool {
        let unit = &self.retained[self.unit_start..];
        continues_previous_line(self.scanned.as_deref().unwrap_or(unit))
    }

    /// Detects, applies policy to and redacts every closed unit in the batch,
    /// then drops their plaintext.
    ///
    /// Detection runs once over the whole batch when its units are
    /// separable ([`detect_units`]); otherwise, or when that call fails, each
    /// unit is scanned alone, which reproduces the failure in the order
    /// unit-by-unit processing would meet it. Policy and redaction always run
    /// unit by unit, so every callback sees the same calls in the same order
    /// and every per-unit bound (`redact`'s input, finding and placeholder
    /// checks) applies to the same text as before.
    fn flush_batch(&mut self, released: &mut Released) -> Result<(), SecretScanError> {
        if self.unit_ends.is_empty() {
            return Ok(());
        }
        // The line above the batch, already released, when a detector reads
        // it (issue #1040): it sits in front of the batch in `retained` and
        // is scanned again as a read-only lead instead of being held back.
        let lead_len = self.lead_len;
        let batch_end = self.unit_start;
        let batch_length = batch_end - lead_len;
        // The released text is about as long as the batch: size it once
        // instead of regrowing it unit by unit (issue #1087).
        released.text.reserve(batch_length);
        #[cfg(test)]
        let (finding_offset, mut batch_shadow) =
            (self.finding_count, self.shadow.as_ref().map(|_| Vec::new()));

        let batched = if self.unit_ends.len() > 1 || lead_len > 0 {
            #[cfg(test)]
            let shadow = batch_shadow.as_mut();
            #[cfg(not(test))]
            let shadow = None;
            detect_batch(
                &self.retained[..batch_end],
                lead_len,
                &self.unit_ends,
                &self.registry,
                shadow,
            )
        } else {
            None
        };
        // Where the next lead starts in `retained`: it always ends where the
        // batch does. A batch that is only the `\n` of a CRLF pair whose `\r`
        // closed the lead's unit completes that same line, which stays the
        // lead.
        let batch = &self.retained[lead_len..batch_end];
        let next_lead_start =
            if lead_len > 0 && self.retained[..lead_len].ends_with('\r') && batch == "\n" {
                Some(0)
            } else {
                self.lead_after(batch).map(|length| batch_end - length)
            };

        let unit_ends = std::mem::take(&mut self.unit_ends);
        // Unit offsets below are relative to the batch start, `lead_len`.
        let mut unit_begin = 0;
        if let Some(detected) = batched {
            #[cfg(test)]
            {
                self.batched_units += unit_ends.len();
            }
            let mut detected = detected.into_iter().peekable();
            for &unit_end in &unit_ends {
                let unit_end = unit_end - lead_len;
                // The unit takes the leading findings that start before its
                // end straight from the batch's iterator: no vector per unit
                // (issue #1095).
                let mut unit_findings = std::iter::from_fn(|| {
                    detected.next_if(|found| found.range().start() < unit_end)
                });
                self.finalize_unit(unit_begin, unit_end, &mut unit_findings, released)?;
                unit_begin = unit_end;
            }
            #[cfg(test)]
            self.record_unit_shadow(batch_shadow, finding_offset, self.finalized_bytes)?;
        } else {
            // The lead of each unit: the batch's lead, then the last line of
            // the unit before, when it is kept. Either ends where the unit
            // starts, so the two scan as one slice of `retained`.
            let mut unit_lead_start = (lead_len > 0).then_some(0);
            for &unit_end in &unit_ends {
                let unit_start = lead_len + unit_begin;
                let input_start = unit_lead_start.unwrap_or(unit_start);
                let input = &self.retained[input_start..unit_end];
                let lead = unit_start - input_start;
                #[cfg(test)]
                let (finding_offset, mut unit_shadow) =
                    (self.finding_count, self.shadow.as_ref().map(|_| Vec::new()));
                #[cfg(test)]
                let detected = detect_after(input, lead, &self.registry, unit_shadow.as_mut())?;
                #[cfg(not(test))]
                let detected = detect_after(input, lead, &self.registry, None)?;
                let detected = detected
                    .into_iter()
                    .map(|found| offset_by(found, unit_begin))
                    .collect::<Result<Vec<_>, _>>()?;
                unit_lead_start = self
                    .lead_after(&self.retained[unit_start..unit_end])
                    .map(|length| unit_end - length);
                let unit_end = unit_end - lead_len;
                self.finalize_unit(unit_begin, unit_end, &mut detected.into_iter(), released)?;
                #[cfg(test)]
                self.record_unit_shadow(
                    unit_shadow,
                    finding_offset,
                    self.finalized_bytes + unit_begin,
                )?;
                unit_begin = unit_end;
            }
        }

        self.finalized_bytes += batch_length;
        let keep_from = next_lead_start.unwrap_or(batch_end);
        self.retained = if keep_from == self.retained.len() {
            String::new()
        } else {
            self.retained[keep_from..].to_owned()
        };
        self.lead_len = batch_end - keep_from;
        self.unit_start = self.lead_len;
        self.unit_ends = unit_ends;
        self.unit_ends.clear();
        Ok(())
    }

    /// The length of the last line of `text` when a later unit must be
    /// scanned below it: it carries an AWS access key ID and the session runs
    /// `aws-secret-access-key`, which claims a secret on the line directly
    /// below an ID (issue #1028). The line is released as soon as it closes
    /// and only a copy is kept, for the next unit's scan (issue #1040), in
    /// front of the retained text (issue #1060).
    fn lead_after(&self, text: &str) -> Option<usize> {
        if !self.lookbacks.aws_secret_access_key {
            return None;
        }
        let line = last_line(text);
        carries_aws_access_key_id(&NormalizedInput::new(line).into_text()).then_some(line.len())
    }

    /// Applies policy to and redacts the closed unit `begin..end` of the
    /// batch (offsets after the lead in `retained`), given its findings with
    /// ranges in batch coordinates, and appends the result to `released`.
    ///
    /// Each detected finding is moved into its global form (issue #1060),
    /// straight into `released` (issue #1095). Redaction then takes that tail
    /// of `released.findings` as it is, with the unit's global start as the
    /// shift between the findings' ranges and the unit's text, and the
    /// placeholders issued so far as the numbering base (issue #1125): the
    /// formatter is handed the global findings themselves, so no unit-local
    /// copy of them is built and no callback is mapped back to its finding.
    fn finalize_unit(
        &mut self,
        begin: usize,
        end: usize,
        detected: &mut dyn Iterator<Item = DetectedFinding>,
        released: &mut Released,
    ) -> Result<(), SecretScanError> {
        let input_offset = self.finalized_bytes;
        // Global findings go straight into `released`: they are the unit's
        // tail there (issue #1095).
        let first_global = released.findings.len();
        for found in detected {
            let range = found.range();
            let global_range =
                ByteRange::new(range.start() + input_offset, range.end() + input_offset)
                    .ok_or(SecretScanErrorCode::InvalidCandidate)?;
            let id = format!("finding-{}", self.finding_count + 1);
            let global_detected = found.with_range(global_range).with_id(id);
            let context = IncrementalPolicyContext::new(self.finding_count);
            let action = self
                .policy
                .evaluate(&global_detected, &context)
                .map_err(|_| SecretScanError::from(SecretScanErrorCode::PolicyFailure))?;
            released.findings.push(global_detected.with_action(action));
            self.finding_count += 1;
        }

        let base = self.lead_len;
        if first_global == released.findings.len() {
            // Nothing to replace: `redact` would check the input limit, find
            // no forbidden text to build, and return the unit unchanged, so
            // skip the copy it makes (issue #1074).
            let unit = &self.retained[base + begin..base + end];
            WholeInputLimits::default().check_input(unit)?;
            released.text.push_str(unit);
            return Ok(());
        }

        let replaced = redact_shifted_into(
            &self.retained[base + begin..base + end],
            &released.findings[first_global..],
            input_offset + begin,
            self.placeholder_count,
            self.formatter.as_ref(),
            &WholeInputLimits::default(),
            &mut released.text,
        )?;
        self.placeholder_count += replaced;
        Ok(())
    }

    /// Appends the shadow comparisons of findings finalized from
    /// `finding_offset`, found in text starting at `input_offset`.
    #[cfg(test)]
    fn record_unit_shadow(
        &mut self,
        unit_shadow: Option<Vec<ShadowComparison>>,
        finding_offset: usize,
        input_offset: usize,
    ) -> Result<(), SecretScanError> {
        if let (Some(recorded), Some(unit_shadow)) = (self.shadow.as_mut(), unit_shadow) {
            for comparison in unit_shadow {
                recorded.push(
                    comparison
                        .shifted(finding_offset, input_offset)
                        .ok_or(SecretScanErrorCode::InvalidCandidate)?,
                );
            }
        }
        Ok(())
    }

    /// Appends `chunk` to the logical input.
    ///
    /// Returns only text and findings whose detection window is closed: a
    /// complete logical line with no open single-line construct or private
    /// key block. Remaining retained plaintext is held until a later
    /// `append` closes it or `finalize` supplies the end-of-input boundary.
    ///
    /// # Errors
    ///
    /// - [`SecretScanErrorCode::InvalidState`] outside the `accepting`
    ///   state.
    /// - [`SecretScanErrorCode::InputLimitExceeded`] when accepting `chunk`
    ///   would exceed `max_input_bytes`.
    /// - [`SecretScanErrorCode::BufferLimitExceeded`],
    ///   [`SecretScanErrorCode::TokenLimitExceeded`], or
    ///   [`SecretScanErrorCode::MultilineLimitExceeded`] when retained
    ///   plaintext exceeds the applicable limit.
    /// - [`SecretScanErrorCode::DetectorFailure`],
    ///   [`SecretScanErrorCode::InvalidCandidate`],
    ///   [`SecretScanErrorCode::PolicyFailure`],
    ///   [`SecretScanErrorCode::PlaceholderFailure`], or
    ///   [`SecretScanErrorCode::InvalidPlaceholder`] when finalizing a
    ///   closed unit fails.
    ///
    /// Every error discards retained plaintext and enters `failed`; no
    /// error carries input or a matched value.
    pub fn append(&mut self, chunk: &str) -> Result<IncrementalResult, SecretScanError> {
        self.require_accepting()?;

        let remaining = self
            .limits
            .max_input_bytes()
            .saturating_sub(self.total_input_bytes);
        if chunk.len() > remaining {
            return Err(self.fail_with(SecretScanErrorCode::InputLimitExceeded.into()));
        }
        self.total_input_bytes += chunk.len();

        // Lines that close in this call are collected into one batch and
        // processed together at the end of the call (issue #985).
        let mut released = Released::default();
        let mut cursor = 0usize;
        while cursor < chunk.len() {
            let Some(newline) = find_next_newline(chunk, cursor) else {
                self.append_retained(&chunk[cursor..], false, &mut released)?;
                break;
            };
            self.append_retained(&chunk[cursor..=newline], true, &mut released)?;

            if self.multiline_open {
                self.aws_held_line = None;
            } else {
                let open = self.has_open_single_line_construct();
                let line_start = last_line_start(&self.retained[self.unit_start..]);
                if !open.other && !open.aws_secret_candidate {
                    self.close_unit(&mut released)
                        .map_err(|error| self.fail_with(error))?;
                } else if !open.other && self.aws_held_line.is_some_and(|held| held != line_start) {
                    // A new line after the held one (not the `\n` that
                    // completes its CRLF) holds another run.
                    self.split_before_last_line(&mut released)?;
                }
                self.aws_held_line = (!open.other && open.aws_secret_candidate)
                    .then(|| last_line_start(&self.retained[self.unit_start..]));
            }
            cursor = newline + 1;
        }
        self.flush_batch(&mut released)
            .map_err(|error| self.fail_with(error))?;
        Ok(IncrementalResult::new(released.text, released.findings))
    }

    /// Supplies the end-of-input boundary, finalizing any remaining
    /// retained plaintext. May be called exactly once, from the `accepting`
    /// state.
    ///
    /// # Errors
    ///
    /// The same codes as [`append`](Self::append), for finalizing the last
    /// retained unit, plus [`SecretScanErrorCode::InvalidState`] outside
    /// the `accepting` state (including a second `finalize`).
    pub fn finalize(&mut self) -> Result<IncrementalResult, SecretScanError> {
        self.require_accepting()?;
        // Every `append` leaves the batch empty, so the last unit is
        // processed alone.
        let mut released = Released::default();
        self.unit_ends.push(self.retained.len());
        self.unit_start = self.retained.len();
        self.flush_batch(&mut released)
            .map_err(|error| self.fail_with(error))?;
        self.discard_retained();
        self.state = SessionState::Finalized;
        Ok(IncrementalResult::new(released.text, released.findings))
    }

    /// Discards retained plaintext and emits no further text or findings.
    ///
    /// # Errors
    ///
    /// Returns [`SecretScanErrorCode::InvalidState`] outside the
    /// `accepting` state.
    pub fn abort(&mut self) -> Result<(), SecretScanError> {
        self.require_accepting()?;
        self.discard_retained();
        self.state = SessionState::Aborted;
        Ok(())
    }
}

#[cfg(test)]
#[path = "incremental/batch_tests.rs"]
mod batch_tests;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{FormatterFailure, PlaceholderContext};

    /// Marker for a retained, unresolved value. It is not credential-shaped
    /// on its own; the surrounding assignment is what a detector matches.
    const MARKER: &str = "SYNTHETIC_REVOKED_RETENTION_MARKER";

    fn generous_limits() -> IncrementalLimits {
        IncrementalLimits::new(1_000_000, 16_512, 8_192, 16_384).unwrap()
    }

    fn session_with(
        policy: Box<dyn IncrementalPolicy>,
        formatter: Box<dyn PlaceholderFormatter>,
    ) -> IncrementalSanitizer {
        IncrementalSanitizer::with_policy_and_formatter(generous_limits(), policy, formatter)
            .unwrap()
    }

    fn default_session() -> IncrementalSanitizer {
        session_with(
            Box::new(DefaultPolicy),
            Box::new(default_placeholder_formatter),
        )
    }

    /// Every discarding transition must leave the session holding no
    /// plaintext and no parser state derived from it.
    fn assert_nothing_retained(sanitizer: &IncrementalSanitizer) {
        assert_eq!(sanitizer.retained, "");
        assert_eq!(sanitizer.retained.capacity(), 0);
        assert_eq!(sanitizer.lead_len, 0);
        assert_eq!(sanitizer.unit_start, 0);
        assert!(sanitizer.unit_ends.is_empty());
        assert!(sanitizer.scanned.is_none());
        assert!(sanitizer.aws_held_line.is_none());
        assert_eq!(sanitizer.open_tail, OpenTailCache::default());
        assert!(!sanitizer.multiline_open);
        assert!(!sanitizer.multiline_detected);
    }

    /// [`assert_nothing_retained`], and no allocation behind the unit list
    /// either: what every terminal transition leaves. A mid-session flush
    /// clears the list but keeps its allocation, which holds offsets, never
    /// text. Structural only: no claim is made about the freed bytes.
    fn assert_terminal_state_holds_nothing(sanitizer: &IncrementalSanitizer) {
        assert_nothing_retained(sanitizer);
        assert_eq!(sanitizer.unit_ends.capacity(), 0);
    }

    #[test]
    fn abort_discards_an_open_construct() {
        let mut sanitizer = default_session();
        sanitizer.append(&format!("api_key={MARKER}")).unwrap();
        assert!(sanitizer.retained.contains(MARKER));

        sanitizer.abort().unwrap();

        assert_eq!(sanitizer.state, SessionState::Aborted);
        assert_nothing_retained(&sanitizer);
    }

    #[test]
    fn abort_discards_an_open_private_key_block() {
        let mut sanitizer = default_session();
        sanitizer
            .append(&format!("-----BEGIN PRIVATE KEY-----\n{MARKER}\n"))
            .unwrap();
        assert!(sanitizer.multiline_open);

        sanitizer.abort().unwrap();

        assert_nothing_retained(&sanitizer);
    }

    #[test]
    fn a_limit_failure_discards_the_construct_that_reached_it() {
        let limits = IncrementalLimits::new(1_000_000, 160, 32, 32).unwrap();
        let mut sanitizer = IncrementalSanitizer::new(limits).unwrap();

        let error = sanitizer.append(&format!("api_key={MARKER}")).unwrap_err();

        assert_eq!(error.code(), SecretScanErrorCode::TokenLimitExceeded);
        assert_eq!(sanitizer.state, SessionState::Failed);
        assert_nothing_retained(&sanitizer);
    }

    #[test]
    fn an_input_limit_failure_discards_everything_retained_so_far() {
        let limits = IncrementalLimits::new(64, 200, 32, 32).unwrap();
        let mut sanitizer = IncrementalSanitizer::new(limits).unwrap();
        sanitizer.append("api_key").unwrap();
        assert_eq!(sanitizer.retained, "api_key");

        let error = sanitizer.append(&"x".repeat(64)).unwrap_err();

        assert_eq!(error.code(), SecretScanErrorCode::InputLimitExceeded);
        assert_nothing_retained(&sanitizer);
    }

    #[test]
    fn a_policy_failure_discards_the_unit_it_was_evaluating() {
        let failing = |_: &DetectedFinding, _: &IncrementalPolicyContext| Err(PolicyFailure);
        let mut sanitizer =
            session_with(Box::new(failing), Box::new(default_placeholder_formatter));

        let error = sanitizer
            .append(&format!("api_key={MARKER}\n"))
            .unwrap_err();

        assert_eq!(error.code(), SecretScanErrorCode::PolicyFailure);
        assert_eq!(sanitizer.state, SessionState::Failed);
        assert_nothing_retained(&sanitizer);
    }

    #[test]
    fn a_formatter_failure_discards_the_unit_it_was_redacting() {
        let failing = |_: &Finding, _: &PlaceholderContext| Err(FormatterFailure);
        let mut sanitizer = session_with(Box::new(DefaultPolicy), Box::new(failing));

        let error = sanitizer
            .append(&format!("api_key={MARKER}\n"))
            .unwrap_err();

        assert_eq!(error.code(), SecretScanErrorCode::PlaceholderFailure);
        assert_nothing_retained(&sanitizer);
    }

    #[test]
    fn the_formatter_sees_global_ids_and_ranges_in_every_unit() {
        // The unit-local view handed to `redact_into` carries no id (issue
        // #1095): the formatter must still see each finding's global form.
        use std::sync::{Arc, Mutex};
        let seen = Arc::new(Mutex::new(Vec::new()));
        let log = Arc::clone(&seen);
        let formatter = move |finding: &Finding, context: &PlaceholderContext| {
            log.lock().unwrap().push((
                finding.id().to_string(),
                finding.range().start(),
                finding.range().end(),
                context.placeholder_index(),
            ));
            Ok(format!("[R{}]", context.placeholder_index()))
        };
        let mut sanitizer = session_with(Box::new(DefaultPolicy), Box::new(formatter));
        let lines = format!("x=1\napi_key={MARKER}\nplain é\npassword={MARKER}\n");
        let result = sanitizer.append(&lines).unwrap();
        let tail = sanitizer.finalize().unwrap();
        let mut findings: Vec<Finding> = result.findings().to_vec();
        findings.extend(tail.findings().iter().cloned());

        let seen = seen.lock().unwrap();
        assert!(!seen.is_empty());
        assert_eq!(seen.len(), findings.len());
        for (n, (finding, (id, start, end, index))) in findings.iter().zip(seen.iter()).enumerate()
        {
            assert_eq!(finding.id(), format!("finding-{}", n + 1));
            assert_eq!(id, finding.id());
            assert_eq!(
                (*start, *end),
                (finding.range().start(), finding.range().end())
            );
            assert_eq!(*index, n + 1);
            assert!(finding.range().start() > 0);
        }
    }

    #[test]
    fn an_invalid_placeholder_discards_the_unit_it_was_redacting() {
        let reproducing = |_: &Finding, _: &PlaceholderContext| Ok(MARKER.to_string());
        let mut sanitizer = session_with(Box::new(DefaultPolicy), Box::new(reproducing));

        let error = sanitizer
            .append(&format!("api_key={MARKER}\n"))
            .unwrap_err();

        assert_eq!(error.code(), SecretScanErrorCode::InvalidPlaceholder);
        assert_nothing_retained(&sanitizer);
    }

    #[test]
    fn a_state_failure_leaves_nothing_retained_to_discard() {
        let mut sanitizer = default_session();
        sanitizer.append(&format!("api_key={MARKER}")).unwrap();
        sanitizer.abort().unwrap();

        let error = sanitizer.append("ignored").unwrap_err();

        assert_eq!(error.code(), SecretScanErrorCode::InvalidState);
        assert_eq!(sanitizer.state, SessionState::Aborted);
        assert_nothing_retained(&sanitizer);
    }

    #[test]
    fn finalize_discards_what_it_resolves_and_what_was_derived_from_it() {
        let mut sanitizer = default_session();
        sanitizer
            .append(&format!("-----BEGIN PRIVATE KEY-----\n{MARKER}-"))
            .unwrap();
        assert!(sanitizer.multiline_open);
        assert!(sanitizer.retained.contains(MARKER));

        sanitizer.finalize().unwrap();

        assert_eq!(sanitizer.state, SessionState::Finalized);
        assert_terminal_state_holds_nothing(&sanitizer);
        // The tracker's fields are private to the detector module, so its
        // reset is observed through what it reports: no block, no `BEGIN`.
        assert_eq!(sanitizer.private_key.append(""), (false, false));
    }

    #[test]
    fn a_failure_while_finalizing_discards_the_last_unit() {
        let failing = |_: &DetectedFinding, _: &IncrementalPolicyContext| Err(PolicyFailure);
        let mut sanitizer =
            session_with(Box::new(failing), Box::new(default_placeholder_formatter));
        // No line end: the unit stays retained until `finalize` judges it.
        sanitizer.append(&format!("api_key={MARKER}")).unwrap();
        assert!(sanitizer.retained.contains(MARKER));

        let error = sanitizer.finalize().unwrap_err();

        assert_eq!(error.code(), SecretScanErrorCode::PolicyFailure);
        assert_eq!(sanitizer.state, SessionState::Failed);
        assert_terminal_state_holds_nothing(&sanitizer);
    }

    #[test]
    fn a_terminal_transition_discards_the_normalized_scan_copy() {
        // A zero-width space inside the name: the unit's scan copy differs
        // from the unit, so the session holds a second, owned copy of it.
        let unit = format!("api\u{200b}_key={MARKER}");
        for finalize in [false, true] {
            let mut sanitizer = default_session();
            sanitizer.append(&unit).unwrap();
            assert!(sanitizer.scanned.is_some(), "precondition: owned scan copy");

            if finalize {
                sanitizer.finalize().unwrap();
            } else {
                sanitizer.abort().unwrap();
            }

            assert_terminal_state_holds_nothing(&sanitizer);
        }
    }

    #[test]
    fn the_released_line_kept_as_a_lead_is_discarded_on_every_terminal_transition() {
        // A line carrying an AWS access key ID is released at once, but a
        // copy stays in front of the retained text while the next unit may
        // read it (issue #1040). It is retained past its release.
        let line = "AKIAIOSFODNN7EXAMPLE\n";
        for finalize in [false, true] {
            let mut sanitizer = default_session();
            sanitizer.append(line).unwrap();
            assert_eq!(sanitizer.lead_len, line.len(), "precondition: a lead");
            assert_eq!(sanitizer.retained, line);

            if finalize {
                sanitizer.finalize().unwrap();
            } else {
                sanitizer.abort().unwrap();
            }

            assert_terminal_state_holds_nothing(&sanitizer);
        }
    }

    #[test]
    fn a_flush_keeps_only_the_open_tail_of_the_buffer() {
        let mut sanitizer = default_session();

        let released = sanitizer
            .append(&format!("api_key={MARKER}\nopen_tail"))
            .unwrap();

        assert!(!released.text().contains(MARKER));
        assert_eq!(sanitizer.retained, "open_tail");
        assert_eq!(sanitizer.lead_len, 0);
        assert_eq!(sanitizer.unit_start, 0);
        assert!(sanitizer.unit_ends.is_empty());
    }

    #[test]
    fn a_finalized_unit_is_discarded_once_its_offsets_are_recorded() {
        let mut sanitizer = default_session();
        let unit = format!("api_key={MARKER}\n");

        sanitizer.append(&unit).unwrap();

        assert_eq!(sanitizer.finalized_bytes, unit.len());
        assert_nothing_retained(&sanitizer);
    }

    #[test]
    fn the_debug_representation_never_carries_retained_plaintext() {
        let mut sanitizer = default_session();
        sanitizer.append(&format!("api_key={MARKER}")).unwrap();

        let rendered = format!("{sanitizer:?}");

        assert!(!rendered.contains(MARKER));
        assert!(rendered.starts_with("IncrementalSanitizer {"));
    }

    #[test]
    fn full_and_common_sessions_report_the_profile_they_were_built_from() {
        assert_eq!(default_session().profile(), Some(Profile::Full));
        let common = IncrementalSanitizer::with_common_built_in(generous_limits()).unwrap();
        assert_eq!(common.profile(), Some(Profile::Common));
    }

    /// Runs `input` split at every char boundary into two chunks, and once
    /// a char at a time, through a `full` and a PII-aware session. Every
    /// closed line runs [`IncrementalSanitizer::assert_open_construct_matches_the_rescan`],
    /// and every partition must reproduce the one-chunk output.
    fn assert_every_partition_matches_the_rescan(input: &str) {
        fn run(sanitizer: &mut IncrementalSanitizer, chunks: &[&str]) -> (String, Vec<Finding>) {
            let mut text = String::new();
            let mut findings = Vec::new();
            for chunk in chunks {
                let result = sanitizer.append(chunk).unwrap();
                text.push_str(result.text());
                findings.extend_from_slice(result.findings());
            }
            let result = sanitizer.finalize().unwrap();
            text.push_str(result.text());
            findings.extend_from_slice(result.findings());
            (text, findings)
        }
        let selection = PiiSelection::parse(&["pii:global"]).unwrap();
        let sessions: [fn(&PiiSelection) -> IncrementalSanitizer; 2] = [
            |_| default_session(),
            |selection| {
                IncrementalSanitizer::with_built_in_and_pii(generous_limits(), selection).unwrap()
            },
        ];
        for session in sessions {
            let reference = run(&mut session(&selection), &[input]);
            let mut boundaries: Vec<usize> = (1..input.len())
                .filter(|&at| input.is_char_boundary(at))
                .collect();
            if input.len() > 512 {
                boundaries.retain(|at| at % 61 == 0 || input.as_bytes()[at - 1] == b'\n');
            }
            for at in boundaries {
                let chunks = [&input[..at], &input[at..]];
                assert_eq!(run(&mut session(&selection), &chunks), reference, "{at}");
            }
            let mut chars = Vec::new();
            let mut rest = input;
            while let Some(ch) = rest.chars().next() {
                chars.push(&rest[..ch.len_utf8()]);
                rest = &rest[ch.len_utf8()..];
            }
            assert_eq!(run(&mut session(&selection), &chars), reference);
        }
    }

    #[test]
    fn the_maintained_open_construct_state_matches_a_rescan_over_generated_inputs() {
        // Deterministic pseudo-random sequences of the pieces the five checks
        // react to: names, operators, quotes, header words, layout lines,
        // every kind of whitespace they skip, and invisible code points. Each
        // runs whole, one char per chunk, and at a few split points, under
        // `full` and `pii:global`; every closed line asserts the rescan.
        const PIECES: &[&str] = &[
            "api_key",
            "API_KEY",
            "password",
            "\"token\"",
            "`secret`",
            "k",
            "\"kty\":\"oct\",",
            "Authorization",
            "x-authorization",
            "Proxy-Authorization",
            "bearer",
            "Bearer",
            "=",
            ":",
            "=\n",
            ":\n",
            "api_key:\n",
            "Authorization:\n",
            "\n  ",
            ":=",
            "\\\"",
            "'",
            "{",
            "(",
            ",",
            ";",
            "#",
            "&",
            "?",
            "value",
            MARKER,
            " ",
            "  ",
            "\t",
            "\n",
            "\n",
            "\r",
            "\r\n",
            "\u{2028}",
            "\u{FEFF}",
            "\u{00A0}",
            "\u{200B}",
            "\u{00AD}",
            "machine api.heroku.com",
            "login user@example.invalid",
            "$ twilio api:core:accounts:list",
            "SID  Auth Token",
            "heroku auth:token",
            "schema.registry.url=https://psrc.example.invalid",
            "basic.auth.user.info=KEY:",
            "-----BEGIN PRIVATE KEY-----",
            "-----END PRIVATE KEY-----",
            "\u{e9}",
            "\u{65e5}",
        ];
        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
        let mut next = |bound: usize| {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            usize::try_from(state >> 33).unwrap() % bound
        };
        for _ in 0..300 {
            let length = 1 + next(14);
            let input: String = (0..length).map(|_| PIECES[next(PIECES.len())]).collect();
            assert_every_partition_matches_the_rescan(&input);
        }
    }

    #[test]
    fn a_curl_command_window_holds_the_unit_exactly_as_a_rescan_does() {
        // Pieces of a curl command line: the command word, the credential
        // flags, quotes, escapes, continuations of both line-ending kinds,
        // and the command and line ends that close a window (issue #1247).
        // Every closed line asserts the rescan; every partition must equal
        // the one-chunk output.
        const PIECES: &[&str] = &[
            "curl ",
            "curl.exe ",
            "/usr/bin/curl ",
            "-u ",
            "-U ",
            "--user ",
            "--user=",
            "--proxy-user ",
            "-sSfLku",
            "svc:",
            "svc",
            ":",
            MARKER,
            "-u svc:SYNTHETIC_REVOKED_RETENTION_MARKER ",
            "--user=\"svc:SYNTHETIC_REVOKED_RETENTION_MARKER\" ",
            "-sSu 'svc:SYNTHETIC_REVOKED_RETENTION_MARKER' ",
            "\"",
            "'",
            "\\",
            "\\\n",
            "\\\r\n",
            "\\\r",
            "\r",
            "\n",
            "\r\n",
            ";",
            "&&",
            "|",
            " ",
            "\t",
            "$(",
            ")",
            "@",
            "\u{e9}",
            "\u{65e5}",
            "\u{200B}",
            "https://api.example.invalid/v1 ",
            "docker run ",
            "--digest ",
        ];
        let mut state: u64 = 0xC0DE_1247_C0DE_1247;
        let mut next = |bound: usize| {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            usize::try_from(state >> 33).unwrap() % bound
        };
        let mut read = 0usize;
        for round in 0..400 {
            let length = 1 + next(16);
            let mut input: String = (0..length).map(|_| PIECES[next(PIECES.len())]).collect();
            // Half of the inputs start from a command word, so that most of
            // them have a window to hold open.
            if round % 2 == 0 {
                input.insert_str(0, "curl ");
            }
            if crate::detectors::curl_user_candidate_count(&input) > 0 {
                read += 1;
            }
            assert_every_partition_matches_the_rescan(&input);
        }
        assert!(read > 20, "the generator must exercise real reads: {read}");
    }

    #[test]
    fn the_maintained_open_construct_state_matches_a_rescan_across_whitespace_gaps() {
        // Whitespace-only lines keep the cached tail result; the line that
        // brings content re-evaluates it. The gaps mix every whitespace kind
        // the tail checks skip, and an invisible code point makes the scan
        // copy diverge mid-unit.
        let gaps = [
            "\n\n\n",
            "        \n        \n",
            "\r\n \t\r\n",
            "\u{2028}\n\u{FEFF}\u{00A0}\n",
            "\u{200B}\n \u{200B} \n",
        ];
        for gap in gaps {
            for input in [
                format!("API_KEY={gap}{MARKER}\nnext\n"),
                format!("API_KEY{gap}={gap}{MARKER}\n"),
                format!("API_\u{200B}KEY={gap}{MARKER}\n"),
                format!("config \"token\":{gap}{MARKER}\n"),
                format!("Authorization:{gap}Bearer {MARKER}\n"),
                format!("x-authorization{gap}Bearer {MARKER}\n"),
                format!("plain words{gap}api_key={gap}={gap}{MARKER}\n"),
                format!(
                    "machine api.heroku.com{gap}login user@example.invalid{gap}password {MARKER}\n"
                ),
                format!(
                    "$ twilio api:core:accounts:list{gap}SID  Auth Token{gap}AC{MARKER}  {MARKER}\n"
                ),
                format!(
                    "schema.registry.url=https://psrc.example.invalid{gap}basic.auth.user.info=KEY:{MARKER}\n"
                ),
                format!(
                    "-----BEGIN PRIVATE KEY-----{gap}{MARKER}{gap}-----END PRIVATE KEY-----{gap}api_key={gap}{MARKER}\n"
                ),
            ] {
                assert_every_partition_matches_the_rescan(&input);
            }
        }
    }

    // Whether a `common` incremental session's cumulative output matches
    // the whole-input path ([`crate::scan_and_redact`] over a `common`
    // registry) is a public-API-level contract
    // (`decision-define-detector-profile-and-pack-contract`), covered by
    // `tests/public_api.rs`'s
    // `common_profile_incremental_session_selects_the_same_built_ins_as_the_whole_input_path`,
    // not repeated here.
}