pdf-untangle 0.3.0

Untangle garbled PDF text: layout-aware extraction that reconstructs reading order, strips page furniture, and splits documents into structured, citable sections
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
//! Layer 3 — blocks → provisions, driven by a [`Profile`].
//!
//! Applies the profile's heading/history/skip patterns to Layer-2 lines,
//! assembles provisions, parses effective dates (never-null fallback chain:
//! parsed history date → document adoption date → [`SENTINEL_DATE`]),
//! computes per-provision confidence, and keeps full coverage accounting so
//! silent text loss is impossible: every input line ends the pipeline as
//! exactly one of
//!
//! - **consumed** — part of a provision (heading, text, or history),
//! - **skipped** — inside a region a profile `skip_patterns` regex opened,
//!   in a block whose first line a `skip_block_patterns` regex matched,
//!   after a `stop_patterns` marker ended detection, or part of a discarded
//!   table-of-contents pass (`toc_restart`) — all recorded in the counts,
//!   never lost,
//! - **furniture** — stripped by Layer 2 as a running header/footer/page
//!   number (see [`Layout::furniture`]), or
//! - **unconsumed** — none of the above; listed verbatim on
//!   [`Document::unconsumed_lines`].
//!
//! [`Document::line_coverage`] is the accounted fraction
//! (`1 − unconsumed/total`); `pdf-untangle check` fails below 0.98.
//!
//! # Heading detection
//!
//! A line becomes a provision start when it passes every stage:
//!
//! 1. one of the profile's `heading_patterns` matches (named captures:
//!    `num` required, `heading`/`title` optional);
//! 2. the **x0 cluster** keeps it (when `heading_x0_cluster` is on and there
//!    are ≥ 3 candidates): real headings share a left edge, while in-text
//!    cross-references that happen to start a wrapped line sit at body
//!    indents — candidates farther than 1.25 em from the dominant candidate
//!    x0 are rejected. This keys on [`Line::x0`], which is reliable under
//!    every backend;
//! 3. optional `heading_style` hints pass — hints that need
//!    backend-dependent facts degrade gracefully (`bold` is only enforced
//!    when the backend reported bold somewhere in the document);
//! 4. the **monotonic-number guard** passes (when `monotonic_numbers` is
//!    on): the parsed number must exceed the last accepted one, which
//!    rejects TOC entries and same-or-backward cross-references.
//!
//! A rejected candidate is ordinary text and flows into the current
//! provision (or skip region) like any other line — with one exception:
//! when `toc_restart` is on and the FIRST accepted number reappears, the
//! whole pass so far is reclassified as a skipped table-of-contents pass
//! and detection restarts there (at most once per document; see
//! [`Profile::toc_restart`]).
//!
//! # History lines
//!
//! A line matching `history_patterns` (re-)opens a history block: it and
//! the following lines of the same Layer-2 block are captured as the
//! provision's history (wrapped credit lines included) and scanned for
//! dates, never merged into the text. Families that print credits both
//! after the heading and after the body (Connecticut) therefore keep both
//! in `history`.
//!
//! # Confidence
//!
//! `confidence = coverage × citation_factor × date_factor`, rounded to two
//! decimals, where `coverage` is the document's [`Document::line_coverage`],
//! `citation_factor` is 1.0 when every citation placeholder resolved (0.85
//! otherwise), and `date_factor` is 1.0 for a date parsed from history
//! lines, 0.97 for the document-level adoption date, and 0.9 for the
//! sentinel. The inputs are restated in `confidence_basis`.

pub(crate) mod dates;

use anyhow::{Context, Result};
use chrono::NaiveDate;
use regex::Regex;

use crate::layout::{Layout, Line};
use crate::output::{Document, Provision, SENTINEL_DATE};
use crate::profile::Profile;

use dates::DateScanner;

/// Where a provision's `effective_date` came from (feeds confidence).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DateSource {
    /// Parsed from a history line inside the provision.
    Parsed,
    /// The document-level adoption date (detected or profile-declared).
    Adoption,
    /// The corpus-standard [`SENTINEL_DATE`].
    Sentinel,
}

/// A heading-pattern match on one line.
struct Candidate {
    num: String,
    heading: Option<String>,
    title: Option<String>,
    /// Text remaining after the full pattern match, when the heading
    /// pattern does not span the whole line (e.g. a consolidated-PDF
    /// caption that ends "… — " with the rule's body continuing on the
    /// same physical line). Must be replayed as the first text line of the
    /// provision — see bug #274: silently dropping it lost the opening
    /// fragment of the rule text.
    text_head: Option<String>,
}

/// A provision being assembled during the line walk.
struct Builder {
    num: String,
    heading: Option<String>,
    title: Option<String>,
    text_lines: Vec<String>,
    last_text_block: Option<usize>,
    history_lines: Vec<String>,
    /// Block index of the open history block, if one is open: a
    /// history-pattern hit (re-)opens the block it sits in, and non-matching
    /// lines of the same block are captured as wrapped continuations. Any
    /// other line closes the block. Re-opening matters for families that
    /// print credits both after the heading and after the body (Connecticut):
    /// history lines never leak into the provision text.
    history_block: Option<usize>,
    dates: Vec<NaiveDate>,
    first_page: usize,
    last_page: usize,
    warnings: Vec<String>,
}

impl Builder {
    fn new(cand: Candidate, page: usize, block: usize) -> Self {
        // Bug #274: a heading pattern that doesn't span the whole line
        // (caption ending in an em dash, body continuing on that same
        // line) leaves a remainder that belongs to the provision's text,
        // not to the discarded part of the heading line. Seed text_lines
        // with it and record the block so a same-block continuation line
        // doesn't get a spurious paragraph break inserted before it.
        let (text_lines, last_text_block) = match &cand.text_head {
            Some(head) => (vec![head.clone()], Some(block)),
            None => (Vec::new(), None),
        };
        Self {
            num: cand.num,
            heading: cand.heading,
            title: cand.title,
            text_lines,
            last_text_block,
            history_lines: Vec::new(),
            history_block: None,
            dates: Vec::new(),
            first_page: page,
            last_page: page,
            warnings: Vec::new(),
        }
    }

    fn touch_page(&mut self, line: &Line) {
        for &p in &line.pages {
            self.first_page = self.first_page.min(p);
            self.last_page = self.last_page.max(p);
        }
    }

    fn push_text(&mut self, line: &Line, block: usize) {
        if self.last_text_block != Some(block) && !self.text_lines.is_empty() {
            self.text_lines.push(String::new()); // paragraph break
        }
        self.text_lines.push(line.text.trim_end().to_string());
        self.last_text_block = Some(block);
    }
}

/// Compiled per-profile machinery for [`detect`].
struct Engine {
    heading: Vec<Regex>,
    history: Vec<Regex>,
    skip: Vec<Regex>,
    skip_block: Vec<Regex>,
    stop: Vec<Regex>,
    empty_doc: Vec<Regex>,
    adoption: Vec<Regex>,
    title: Vec<Regex>,
    scanner: DateScanner,
}

impl Engine {
    fn new(profile: &Profile) -> Result<Self> {
        let compile = |pats: &[String]| -> Result<Vec<Regex>> {
            pats.iter()
                .map(|p| Regex::new(p).with_context(|| format!("profile regex {p:?}")))
                .collect()
        };
        Ok(Self {
            heading: compile(&profile.heading_patterns)?,
            history: compile(&profile.history_patterns)?,
            skip: compile(&profile.skip_patterns)?,
            skip_block: compile(&profile.skip_block_patterns)?,
            stop: compile(&profile.stop_patterns)?,
            empty_doc: compile(&profile.empty_doc_patterns)?,
            adoption: compile(&profile.adoption_patterns)?,
            title: compile(&profile.title_patterns)?,
            scanner: DateScanner::new(&profile.date_formats)?,
        })
    }

    /// Layer-2 line text can carry stray leading/trailing spaces (backends
    /// pad run joins), so every pattern matches against the trimmed text.
    fn candidate(&self, text: &str) -> Option<Candidate> {
        let text = text.trim();
        for re in &self.heading {
            if let Some(caps) = re.captures(text) {
                let num = caps.name("num")?.as_str().to_string();
                let grab = |name: &str| {
                    caps.name(name)
                        .map(|m| m.as_str().trim().to_string())
                        .filter(|s| !s.is_empty())
                };
                // The pattern need not consume the whole line (e.g. a
                // caption ending "… — " with the body continuing on the
                // same line). Whatever the match leaves unconsumed is the
                // start of the rule's text, not lost front matter.
                let text_head = caps
                    .get(0)
                    .map(|m| text[m.end()..].trim().to_string())
                    .filter(|s| !s.is_empty());
                return Some(Candidate {
                    num,
                    heading: grab("heading"),
                    title: grab("title"),
                    text_head,
                });
            }
        }
        None
    }

    fn is_history(&self, text: &str) -> bool {
        let text = text.trim();
        self.history.iter().any(|re| re.is_match(text))
    }

    fn is_skip(&self, text: &str) -> bool {
        let text = text.trim();
        self.skip.iter().any(|re| re.is_match(text))
    }

    fn is_skip_block(&self, first_line: &str) -> bool {
        let text = first_line.trim();
        self.skip_block.iter().any(|re| re.is_match(text))
    }

    fn is_stop(&self, text: &str) -> bool {
        let text = text.trim();
        self.stop.iter().any(|re| re.is_match(text))
    }
}

/// Sortable key for a provision number: segments split on `.` and `-`, each
/// a number plus an alphabetic tail, so every corpus numbering scheme orders
/// correctly — dotted rules ("23.1" < "24"), lettered rules ("4A" between
/// "4" and "5"), and Connecticut's chapter-section form, where the tail is
/// positional ("1-9A" < "1-10", "32-12" < "32a-1" < "33-1"). Parts with no
/// leading digits land in the trailing suffix.
fn num_key(num: &str) -> (Vec<(u64, String)>, String) {
    let mut segs: Vec<(u64, String)> = Vec::new();
    let mut suffix = String::new();
    for part in num.split(['.', '-']) {
        let digits: String = part.chars().take_while(char::is_ascii_digit).collect();
        let rest: &str = &part[digits.len()..];
        match digits.parse::<u64>() {
            Ok(n) => segs.push((n, rest.to_string())),
            Err(_) => suffix.push_str(part),
        }
    }
    (segs, suffix)
}

/// The x0-cluster filter: keep candidates within `1.25 em` of the dominant
/// candidate line-start x0 (the em is the median candidate font size).
/// Returns a keep/reject flag per candidate, in input order.
fn x0_cluster(cands: &[(f32, f32)]) -> Vec<bool> {
    if cands.len() < 3 {
        return vec![true; cands.len()];
    }
    let mut sizes: Vec<f32> = cands.iter().map(|&(_, size)| size).collect();
    sizes.sort_by(|a, b| a.total_cmp(b));
    let tol = 1.25 * sizes[sizes.len() / 2];

    let mut best_center = cands[0].0;
    let mut best_count = 0usize;
    for &(center, _) in cands {
        let count = cands
            .iter()
            .filter(|&&(x, _)| (x - center).abs() <= tol)
            .count();
        if count > best_count || (count == best_count && center < best_center) {
            best_center = center;
            best_count = count;
        }
    }
    cands
        .iter()
        .map(|&(x, _)| (x - best_center).abs() <= tol)
        .collect()
}

/// Detect provisions in a reconstructed [`Layout`] using `profile`.
///
/// `source_file` is recorded verbatim on every provision. See the
/// [module docs](self) for the pipeline and the accounting guarantees.
pub fn detect(layout: &Layout, profile: &Profile, source_file: &str) -> Result<Document> {
    let engine = Engine::new(profile)?;

    // Flatten blocks into ordered lines, remembering block membership.
    let flat: Vec<(usize, &Line)> = layout
        .blocks
        .iter()
        .enumerate()
        .flat_map(|(bi, b)| b.lines.iter().map(move |l| (bi, l)))
        .collect();

    // Block-scoped skips (see [`Profile::skip_block_patterns`]): a block
    // whose first line matches is skipped whole, and its lines are never
    // heading candidates.
    let block_skipped: Vec<bool> = layout
        .blocks
        .iter()
        .map(|b| {
            b.lines
                .first()
                .is_some_and(|l| engine.is_skip_block(&l.text))
        })
        .collect();

    // Stage 1-3: heading candidates, x0 cluster, style hints.
    let doc_has_bold = flat.iter().any(|(_, l)| l.bold);
    let mut candidates: Vec<Option<Candidate>> = flat
        .iter()
        .map(|(bi, l)| {
            if block_skipped[*bi] {
                None
            } else {
                engine.candidate(&l.text)
            }
        })
        .collect();
    if profile.heading_x0_cluster {
        let feats: Vec<(f32, f32)> = flat
            .iter()
            .zip(&candidates)
            .filter(|(_, c)| c.is_some())
            .map(|((_, l), _)| (l.x0, l.font_size))
            .collect();
        let keep = x0_cluster(&feats);
        let mut k = keep.iter();
        for cand in candidates.iter_mut() {
            if cand.is_some() && !*k.next().expect("one flag per candidate") {
                *cand = None;
            }
        }
    }
    if let Some(style) = &profile.heading_style {
        for ((_, line), cand) in flat.iter().zip(candidates.iter_mut()) {
            if cand.is_none() {
                continue;
            }
            let bold_ok = match style.bold {
                // Graceful degradation: only enforce when the backend saw
                // bold anywhere (the pure backend never reports it).
                Some(want) if doc_has_bold => line.bold == want,
                _ => true,
            };
            let centered_ok = style.centered.map_or(true, |want| line.centered == want);
            let min_ok = style.min_size.map_or(true, |s| line.font_size >= s);
            let max_ok = style.max_size.map_or(true, |s| line.font_size <= s);
            if !(bold_ok && centered_ok && min_ok && max_ok) {
                *cand = None;
            }
        }
    }

    // Stage 4: the ordered walk with the monotonic-number guard.
    let mut builders: Vec<Builder> = Vec::new();
    let mut current: Option<Builder> = None;
    let mut skipping = false;
    let mut consumed = 0usize;
    let mut skipped = 0usize;
    let mut unconsumed_lines: Vec<String> = Vec::new();
    let mut first_key: Option<(Vec<(u64, String)>, String)> = None;
    let mut restart_note: Option<String> = None;

    let mut stopped = false;

    for ((block, line), cand) in flat.iter().zip(candidates) {
        // A stop marker ends detection for good: no more headings, and no
        // more date feeding — trailing back matter (form appendices, tables)
        // must not attach to the final provision.
        if stopped {
            skipped += 1;
            continue;
        }
        if engine.is_stop(&line.text) {
            stopped = true;
            if let Some(done) = current.take() {
                builders.push(done);
            }
            skipped += 1;
            continue;
        }
        // Block-scoped skip: record the line as skipped; history-matching
        // lines still feed date parsing.
        if block_skipped[*block] {
            if let Some(b) = current.as_mut() {
                b.touch_page(line);
                if engine.is_history(&line.text) {
                    b.dates.extend(engine.scanner.scan(&line.text));
                }
            }
            skipped += 1;
            continue;
        }
        let mut accepted = None;
        if let Some(c) = cand {
            let monotonic_ok = !profile.monotonic_numbers
                || current
                    .as_ref()
                    .map(|b| num_key(&c.num) > num_key(&b.num))
                    .unwrap_or(true);
            if monotonic_ok {
                accepted = Some(c);
            } else if profile.toc_restart
                && restart_note.is_none()
                && first_key.as_ref() == Some(&num_key(&c.num))
            {
                // The document's first provision number has come around
                // again: everything accepted so far was a table-of-contents
                // pass whose entries mirror the real headings. Reclassify it
                // as skipped front matter and restart at this line.
                let discarded = builders.len() + usize::from(current.is_some());
                restart_note = Some(format!(
                    "table-of-contents pass discarded: {discarded} provision(s) \
                     reclassified as front matter; detection restarted at {}",
                    c.num
                ));
                builders.clear();
                current = None;
                skipped += consumed;
                consumed = 0;
                accepted = Some(c);
            }
        }
        if let Some(cand) = accepted {
            if first_key.is_none() {
                first_key = Some(num_key(&cand.num));
            }
            if let Some(done) = current.take() {
                builders.push(done);
            }
            let mut b = Builder::new(cand, line.pages.first().copied().unwrap_or(0), *block);
            b.touch_page(line);
            current = Some(b);
            skipping = false;
            consumed += 1;
            continue;
        }
        if engine.is_skip(&line.text) {
            skipping = true;
        }
        if let Some(b) = current.as_mut() {
            b.touch_page(line);
            let history_hit = engine.is_history(&line.text);
            if history_hit {
                // History lines feed date parsing wherever they sit — even
                // inside a skipped commentary region.
                b.dates.extend(engine.scanner.scan(&line.text));
            }
            if skipping {
                skipped += 1;
                continue;
            }
            if history_hit {
                // A history line (re-)opens the history block it sits in, so
                // credits printed after the body never leak into the text.
                b.history_lines.push(line.text.trim().to_string());
                b.history_block = Some(*block);
            } else if b.history_block == Some(*block) {
                // Continuation of the open history block (wrapped credit
                // line); scan it for dates too.
                b.history_lines.push(line.text.trim().to_string());
                b.dates.extend(engine.scanner.scan(&line.text));
            } else {
                b.history_block = None;
                b.push_text(line, *block);
            }
            consumed += 1;
        } else if skipping {
            skipped += 1;
        } else {
            unconsumed_lines.push(line.text.trim_end().to_string());
        }
    }
    if let Some(done) = current.take() {
        builders.push(done);
    }

    // Coverage accounting: every line is consumed, skipped, furniture, or
    // listed as unconsumed.
    let furniture = layout.furniture.len();
    let total = flat.len() + furniture;
    let line_coverage = if total == 0 {
        1.0
    } else {
        1.0 - unconsumed_lines.len() as f32 / total as f32
    };

    // Document-level facts scanned across ALL lines, furniture included:
    // the adoption date (running footers often carry it) and the {title}
    // citation placeholder (running heads usually carry it).
    let all_lines = flat.iter().map(|(_, l)| *l).chain(layout.furniture.iter());
    let mut adoption: Option<NaiveDate> = None;
    let mut doc_title: Option<String> = None;
    for line in all_lines {
        let text = line.text.trim();
        if adoption.is_none() {
            for re in &engine.adoption {
                if let Some(caps) = re.captures(text) {
                    let target = caps.name("date").map_or(text, |m| m.as_str());
                    if let Some(d) = engine.scanner.scan(target).into_iter().next() {
                        adoption = Some(d);
                        break;
                    }
                }
            }
        }
        if doc_title.is_none() {
            for re in &engine.title {
                if let Some(m) = re.captures(text).and_then(|c| c.name("title")) {
                    doc_title = Some(m.as_str().to_string());
                    break;
                }
            }
        }
        if adoption.is_some() && doc_title.is_some() {
            break;
        }
    }
    if adoption.is_none() {
        adoption = profile
            .adoption_date
            .as_deref()
            .and_then(|d| NaiveDate::parse_from_str(d, "%Y-%m-%d").ok());
    }

    // Structure integrity: sequence sanity over the accepted numbers.
    let mut warnings: Vec<String> = Vec::new();
    if let Some(note) = restart_note {
        warnings.push(note);
    }
    let mut sequence_gaps: Vec<String> = Vec::new();
    let mut sequence_duplicates: Vec<String> = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for b in &builders {
        if !seen.insert(num_key(&b.num)) {
            sequence_duplicates.push(b.num.clone());
            warnings.push(format!("duplicate provision number {}", b.num));
        }
    }
    for pair in builders.windows(2) {
        let (prev, next) = (&pair[0], &pair[1]);
        let (pk, nk) = (num_key(&prev.num), num_key(&next.num));
        if nk < pk {
            warnings.push(format!(
                "provisions out of order: {} follows {}",
                next.num, prev.num
            ));
            continue;
        }
        if let (Some(p), Some(n)) = (pk.0.first(), nk.0.first()) {
            for missing in (p.0 + 1)..n.0 {
                let m = missing.to_string();
                if !profile.expected_gaps.contains(&m) {
                    warnings.push(format!(
                        "sequence gap: {m} missing between {} and {}",
                        prev.num, next.num
                    ));
                    sequence_gaps.push(m);
                }
            }
        }
    }
    // Zero provisions is either a failure or — when a profile-declared
    // empty-document marker is present (a whole-chapter "[Repealed by …]"
    // stub) — a recognized, valid empty document. Only consulted when
    // nothing was detected, so a marker-shaped line inside a normal
    // document can never flip its status.
    let empty_doc_marker = if builders.is_empty() {
        flat.iter()
            .map(|(_, l)| *l)
            .chain(layout.furniture.iter())
            .map(|l| l.text.trim())
            .find(|t| engine.empty_doc.iter().any(|re| re.is_match(t)))
            .map(str::to_string)
    } else {
        None
    };
    if builders.is_empty() {
        match &empty_doc_marker {
            Some(m) => warnings.push(format!("recognized empty document: {m}")),
            None => warnings.push("no provisions detected".to_string()),
        }
    }

    // Assemble the output records.
    let wants_title = profile.citation_template.contains("{title}");
    let provisions = builders
        .into_iter()
        .map(|b| {
            let mut prov_warnings = b.warnings;
            let mut citation = profile.citation_template.replace("{num}", &b.num);
            let mut citation_clean = true;
            if wants_title {
                match b.title.clone().or_else(|| doc_title.clone()) {
                    Some(t) => citation = citation.replace("{title}", &t),
                    None => {
                        citation_clean = false;
                        prov_warnings.push(
                            "citation {title} unresolved: no title capture matched".to_string(),
                        );
                    }
                }
            }
            let (date, source) = match (b.dates.last(), adoption) {
                (Some(&d), _) => (d, DateSource::Parsed),
                (None, Some(d)) => (d, DateSource::Adoption),
                (None, None) => (
                    NaiveDate::parse_from_str(SENTINEL_DATE, "%Y-%m-%d").expect("sentinel"),
                    DateSource::Sentinel,
                ),
            };
            let (confidence, confidence_basis) = confidence(line_coverage, citation_clean, source);
            let history = if b.history_lines.is_empty() {
                None
            } else {
                Some(b.history_lines.join(" "))
            };
            Provision {
                jurisdiction: profile.jurisdiction.clone(),
                kind: profile.kind.clone(),
                citation,
                number: b.num,
                heading: b.heading,
                text: b.text_lines.join("\n").trim().to_string(),
                history,
                effective_date: date.format("%Y-%m-%d").to_string(),
                language: profile.language.clone(),
                confidence,
                confidence_basis,
                source_file: source_file.to_string(),
                pages: [b.first_page as u32 + 1, b.last_page as u32 + 1],
                profile: profile.name.clone(),
                warnings: prov_warnings,
            }
        })
        .collect();

    Ok(Document {
        provisions,
        line_coverage,
        unconsumed_lines,
        warnings,
        lines_total: total,
        lines_consumed: consumed,
        lines_skipped: skipped,
        lines_furniture: furniture,
        sequence_gaps,
        sequence_duplicates,
        empty_doc_marker,
    })
}

/// The documented confidence formula (see the [module docs](self)).
fn confidence(coverage: f32, citation_clean: bool, source: DateSource) -> (f32, String) {
    let citation_factor: f64 = if citation_clean { 1.0 } else { 0.85 };
    let (date_factor, date_note): (f64, &str) = match source {
        DateSource::Parsed => (1.0, "date parsed from history"),
        DateSource::Adoption => (0.97, "date from document adoption"),
        DateSource::Sentinel => (0.9, "date sentinel (none found)"),
    };
    let raw = f64::from(coverage.clamp(0.0, 1.0)) * citation_factor * date_factor;
    let rounded = ((raw * 100.0).round() / 100.0) as f32;
    let basis = format!(
        "coverage={:.1}%; citation {}; {}",
        coverage * 100.0,
        if citation_clean {
            "clean"
        } else {
            "unresolved"
        },
        date_note
    );
    (rounded.max(0.05), basis)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::{Block, Line};

    fn line(text: &str, x0: f32, page: usize) -> Line {
        Line {
            text: text.to_string(),
            x0,
            baseline: 0.0,
            indent: 0,
            font_size: 11.0,
            bold: false,
            centered: false,
            column: 0,
            pages: vec![page],
        }
    }

    fn block(lines: Vec<Line>) -> Block {
        Block { lines }
    }

    fn layout(blocks: Vec<Block>) -> Layout {
        Layout {
            blocks,
            furniture: Vec::new(),
        }
    }

    fn profile(extra: &str) -> Profile {
        let src = format!(
            r#"
name = "test"
jurisdiction = "guam"
kind = "rule"
citation_template = "G. R. {{num}}"
heading_patterns = ['^Rule\s+(?P<num>\d+(?:\.\d+)?)\.?\s+(?P<heading>\S.*)$']
date_formats = ["%B %d, %Y"]
{extra}
"#
        );
        Profile::from_toml(&src).expect("test profile")
    }

    #[test]
    fn splits_provisions_and_renders_citations() {
        let l = layout(vec![
            block(vec![line("Rule 1. Scope.", 72.0, 0)]),
            block(vec![line("These rules govern.", 72.0, 0)]),
            block(vec![line("Rule 2. One Form of Action.", 72.0, 1)]),
            block(vec![line("There is one form of action.", 72.0, 1)]),
        ]);
        let doc = detect(&l, &profile(""), "x.pdf").unwrap();
        assert_eq!(doc.provisions.len(), 2);
        let p = &doc.provisions[0];
        assert_eq!(p.citation, "G. R. 1");
        assert_eq!(p.number, "1");
        assert_eq!(p.heading.as_deref(), Some("Scope."));
        assert_eq!(p.text, "These rules govern.");
        assert_eq!(p.pages, [1, 1]);
        assert_eq!(doc.provisions[1].pages, [2, 2]);
        assert!((doc.line_coverage - 1.0).abs() < 1e-6);
        assert!(doc.unconsumed_lines.is_empty());
        assert_eq!(doc.lines_consumed, 4);
    }

    /// Regression test for bug #274: when a heading pattern's match does not
    /// span the whole line (e.g. a consolidated-PDF caption that ends with
    /// an em dash, body text continuing on the same physical line), the
    /// unmatched remainder must survive as the start of the provision's
    /// text — never silently dropped.
    #[test]
    fn heading_line_remainder_after_match_becomes_body_text() {
        let ri_profile = {
            let src = r#"
name = "test-ri"
jurisdiction = "rhode_island"
kind = "rule"
citation_template = "R.I. Super. R. Civ. P. {num}"
heading_patterns = ['^(?P<num>\d+\.\d+)\.\s+(?P<heading>[^—]+)—\s*']
date_formats = ["%B %d, %Y"]
"#;
            Profile::from_toml(src).expect("test profile")
        };
        let l = layout(vec![block(vec![
            line(
                "23.1. Derivative actions by shareholders — In a derivative action brought by",
                72.0,
                0,
            ),
            line(
                "one (1) or more shareholders to enforce a right of the corporation.",
                72.0,
                0,
            ),
        ])]);
        let doc = detect(&l, &ri_profile, "x.pdf").unwrap();
        assert_eq!(doc.provisions.len(), 1);
        let p = &doc.provisions[0];
        assert_eq!(
            p.heading.as_deref(),
            Some("Derivative actions by shareholders")
        );
        assert_eq!(
            p.text,
            "In a derivative action brought by\n\
             one (1) or more shareholders to enforce a right of the corporation."
        );
    }

    #[test]
    fn text_keeps_paragraph_breaks_between_blocks() {
        let l = layout(vec![
            block(vec![line("Rule 1. Scope.", 72.0, 0)]),
            block(vec![line("First paragraph.", 72.0, 0)]),
            block(vec![line("Second paragraph.", 72.0, 0)]),
        ]);
        let doc = detect(&l, &profile(""), "x.pdf").unwrap();
        assert_eq!(
            doc.provisions[0].text,
            "First paragraph.\n\nSecond paragraph."
        );
    }

    #[test]
    fn preamble_without_skip_rule_is_unconsumed_and_hurts_coverage() {
        let l = layout(vec![
            block(vec![line("SOME COVER PAGE", 72.0, 0)]),
            block(vec![line("Rule 1. Scope.", 72.0, 1)]),
            block(vec![line("Body.", 72.0, 1)]),
        ]);
        let doc = detect(&l, &profile(""), "x.pdf").unwrap();
        assert_eq!(doc.unconsumed_lines, vec!["SOME COVER PAGE".to_string()]);
        assert!(doc.line_coverage < 1.0);
    }

    #[test]
    fn skip_region_runs_until_the_next_accepted_heading() {
        let l = layout(vec![
            block(vec![line("E-FILED", 72.0, 0)]),
            block(vec![line("TABLE OF CONTENTS", 72.0, 0)]),
            block(vec![line("Rule 1. Scope.", 72.0, 1)]),
            block(vec![
                line("Body.", 72.0, 1),
                line("Notes", 72.0, 1),
                line("[1] A committee note.", 72.0, 1),
            ]),
            block(vec![line("Rule 2. Next.", 72.0, 2)]),
            block(vec![line("More body.", 72.0, 2)]),
        ]);
        let doc = detect(
            &l,
            &profile("skip_patterns = ['^E-FILED$', '^Notes$']"),
            "x.pdf",
        )
        .unwrap();
        assert_eq!(doc.provisions.len(), 2);
        assert_eq!(doc.provisions[0].text, "Body.");
        assert_eq!(doc.provisions[1].text, "More body.");
        assert!(
            doc.unconsumed_lines.is_empty(),
            "{:?}",
            doc.unconsumed_lines
        );
        assert_eq!(doc.lines_skipped, 4); // E-FILED, TOC, Notes, [1] …
        assert!((doc.line_coverage - 1.0).abs() < 1e-6);
    }

    #[test]
    fn monotonic_guard_rejects_backward_and_equal_numbers() {
        let l = layout(vec![
            block(vec![line("Rule 23.1. Derivative Actions.", 72.0, 0)]),
            block(vec![line(
                "Rule 23.1 applies when a shareholder sues.",
                72.0,
                0,
            )]),
            block(vec![line("Rule 24. Intervention.", 72.0, 0)]),
            block(vec![line(
                "Rule 12. A cross-reference, not a rule.",
                72.0,
                0,
            )]),
        ]);
        // "Rule 12. …" matches the heading pattern but 12 < 24: rejected.
        let p = profile("heading_x0_cluster = false");
        let doc = detect(&l, &p, "x.pdf").unwrap();
        let nums: Vec<&str> = doc.provisions.iter().map(|p| p.number.as_str()).collect();
        assert_eq!(nums, vec!["23.1", "24"]);
        assert!(doc.provisions[0]
            .text
            .contains("applies when a shareholder"));
        assert!(doc.provisions[1].text.contains("cross-reference"));
    }

    #[test]
    fn x0_cluster_rejects_candidates_at_body_indents() {
        let l = layout(vec![
            block(vec![line("Rule 1. Scope.", 144.0, 0)]),
            block(vec![line("Body text.", 208.8, 0)]),
            block(vec![line("Rule 2. Service.", 144.0, 0)]),
            // A wrapped cross-reference at a body indent, number in sequence:
            // only the x0 cluster can reject it.
            block(vec![line(
                "Rule 3. By order of the court, service may",
                208.8,
                0,
            )]),
            block(vec![line("Rule 3. Commencement.", 144.0, 0)]),
            block(vec![line("Rule 4. Summons.", 144.0, 0)]),
        ]);
        let doc = detect(&l, &profile(""), "x.pdf").unwrap();
        let nums: Vec<&str> = doc.provisions.iter().map(|p| p.number.as_str()).collect();
        assert_eq!(nums, vec!["1", "2", "3", "4"]);
        assert!(doc.provisions[1].text.contains("By order of the court"));
    }

    #[test]
    fn slightly_indented_heading_stays_in_the_cluster() {
        // "Rule 7.1" sits ~9pt right of the other headings in the real CNMI
        // corpus; 1.25 em (13.75pt at 11pt) must keep it.
        let l = layout(vec![
            block(vec![line("Rule 7. Pleadings.", 144.0, 0)]),
            block(vec![line("Rule 7.1 Disclosure Statement.", 153.1, 0)]),
            block(vec![line("Rule 8. General Rules.", 144.0, 0)]),
        ]);
        let doc = detect(&l, &profile(""), "x.pdf").unwrap();
        let nums: Vec<&str> = doc.provisions.iter().map(|p| p.number.as_str()).collect();
        assert_eq!(nums, vec!["7", "7.1", "8"]);
    }

    #[test]
    fn history_block_is_captured_and_excluded_from_text() {
        let l = layout(vec![
            block(vec![line("Rule 5. Service.", 72.0, 0)]),
            block(vec![line("Body of the rule.", 72.0, 0)]),
            block(vec![
                line("Source: PL 1-8, tit. 1, § 1; amended by PL", 72.0, 0),
                line("13-1, § 4(a), effective March 2, 2004.", 72.0, 0),
            ]),
        ]);
        let doc = detect(&l, &profile("history_patterns = ['^Source:']"), "x.pdf").unwrap();
        let p = &doc.provisions[0];
        assert_eq!(p.text, "Body of the rule.");
        assert_eq!(
            p.history.as_deref(),
            Some(
                "Source: PL 1-8, tit. 1, § 1; amended by PL 13-1, § 4(a), effective March 2, 2004."
            )
        );
        assert_eq!(p.effective_date, "2004-03-02");
        assert!(p.confidence_basis.contains("date parsed from history"));
    }

    #[test]
    fn last_history_date_wins() {
        let l = layout(vec![
            block(vec![line("Rule 5. Service.", 72.0, 0)]),
            block(vec![line(
                "Adopted January 9, 1998; amended effective March 2, 2004.",
                72.0,
                0,
            )]),
        ]);
        let doc = detect(
            &l,
            &profile("history_patterns = ['(?i)adopted|amended']"),
            "x.pdf",
        )
        .unwrap();
        assert_eq!(doc.provisions[0].effective_date, "2004-03-02");
    }

    #[test]
    fn history_dates_inside_skipped_regions_still_count() {
        let l = layout(vec![
            block(vec![line("Rule 5. Service.", 72.0, 0)]),
            block(vec![line("Body.", 72.0, 0)]),
            block(vec![line("Commission Comment: history follows.", 72.0, 0)]),
            block(vec![line(
                "PL 13-1 took effect February 13, 2002.",
                72.0,
                0,
            )]),
        ]);
        let doc = detect(
            &l,
            &profile(
                "history_patterns = ['(?i)took effect']\nskip_patterns = ['^Commission Comment:']",
            ),
            "x.pdf",
        )
        .unwrap();
        let p = &doc.provisions[0];
        assert_eq!(p.effective_date, "2002-02-13");
        assert_eq!(p.text, "Body.", "skipped lines stay out of the text");
        assert!(
            p.history.is_none(),
            "skipped lines stay out of the history field"
        );
        assert_eq!(doc.lines_skipped, 2);
    }

    #[test]
    fn adoption_date_chain_pattern_then_static_then_sentinel() {
        let mk = || {
            layout(vec![
                block(vec![line("Effective January 9, 2019", 72.0, 0)]),
                block(vec![line("Rule 1. Scope.", 72.0, 0)]),
                block(vec![line("Body.", 72.0, 0)]),
            ])
        };
        // Detected from the document (the preamble line is unconsumed but
        // still scanned).
        let doc = detect(
            &mk(),
            &profile("adoption_patterns = ['^Effective\\s+(?P<date>.+)$']"),
            "x.pdf",
        )
        .unwrap();
        assert_eq!(doc.provisions[0].effective_date, "2019-01-09");
        assert!(doc.provisions[0]
            .confidence_basis
            .contains("date from document adoption"));

        // Static profile field when no pattern matches.
        let doc = detect(&mk(), &profile("adoption_date = \"2002-02-13\""), "x.pdf").unwrap();
        assert_eq!(doc.provisions[0].effective_date, "2002-02-13");

        // Sentinel when nothing is declared.
        let doc = detect(&mk(), &profile(""), "x.pdf").unwrap();
        assert_eq!(doc.provisions[0].effective_date, SENTINEL_DATE);
        assert!(doc.provisions[0].confidence_basis.contains("sentinel"));
    }

    #[test]
    fn title_placeholder_resolves_from_furniture() {
        let mut l = layout(vec![
            block(vec![line("Rule 1. Scope.", 72.0, 0)]),
            block(vec![line("Body.", 72.0, 0)]),
        ]);
        l.furniture.push(line("TITLE 1: GOVERNMENT", 200.0, 0));
        let p = Profile::from_toml(
            r#"
name = "t"
jurisdiction = "northern_mariana_islands"
kind = "statute"
citation_template = "{title} CMC § {num}"
heading_patterns = ['^Rule\s+(?P<num>\d+)\.\s+(?P<heading>.+)$']
title_patterns = ['^TITLE\s+(?P<title>\d+)\b']
"#,
        )
        .unwrap();
        let doc = detect(&l, &p, "x.pdf").unwrap();
        assert_eq!(doc.provisions[0].citation, "1 CMC § 1");
        assert!(doc.provisions[0].warnings.is_empty());

        // Unresolvable {title}: warning + confidence ding, template visible.
        l.furniture.clear();
        let doc = detect(&l, &p, "x.pdf").unwrap();
        let prov = &doc.provisions[0];
        assert_eq!(prov.citation, "{title} CMC § 1");
        assert!(prov.warnings[0].contains("{title} unresolved"));
        assert!(prov.confidence_basis.contains("citation unresolved"));
    }

    #[test]
    fn sequence_gaps_and_expected_gaps() {
        let l = layout(vec![
            block(vec![line("Rule 1. A.", 72.0, 0)]),
            block(vec![line("Rule 2. B.", 72.0, 0)]),
            block(vec![line("Rule 5. C.", 72.0, 0)]),
        ]);
        let doc = detect(&l, &profile(""), "x.pdf").unwrap();
        assert_eq!(doc.sequence_gaps, vec!["3", "4"]);
        assert!(doc.warnings.iter().any(|w| w.contains("sequence gap: 3")));

        let doc = detect(&l, &profile("expected_gaps = ['3', '4']"), "x.pdf").unwrap();
        assert!(doc.sequence_gaps.is_empty());
        assert!(doc.warnings.is_empty());
    }

    #[test]
    fn duplicates_flagged_when_monotonic_is_off() {
        let l = layout(vec![
            block(vec![line("Rule 1. A.", 72.0, 0)]),
            block(vec![line("Rule 1. A again.", 72.0, 0)]),
        ]);
        let doc = detect(&l, &profile("monotonic_numbers = false"), "x.pdf").unwrap();
        assert_eq!(doc.provisions.len(), 2);
        assert_eq!(doc.sequence_duplicates, vec!["1"]);
        assert!(doc.warnings.iter().any(|w| w.contains("duplicate")));
    }

    #[test]
    fn bold_style_hint_degrades_without_backend_support() {
        let mut heading = line("Rule 1. Scope.", 72.0, 0);
        heading.bold = false; // pure backend: nothing is ever bold
        let l = layout(vec![
            block(vec![heading]),
            block(vec![line("Body.", 72.0, 0)]),
        ]);
        let p = profile("[heading_style]\nbold = true");
        let doc = detect(&l, &p, "x.pdf").unwrap();
        assert_eq!(
            doc.provisions.len(),
            1,
            "hint must not fire without bold data"
        );

        // With bold data present, the hint is enforced.
        let mut bold_body = line("Rule 2. Not a heading, just bold-less.", 72.0, 0);
        bold_body.bold = false;
        let mut bold_somewhere = line("Something bold.", 72.0, 0);
        bold_somewhere.bold = true;
        let l = layout(vec![block(vec![bold_somewhere]), block(vec![bold_body])]);
        let doc = detect(&l, &p, "x.pdf").unwrap();
        assert!(doc.provisions.is_empty(), "non-bold heading rejected");
    }

    #[test]
    fn confidence_formula_is_the_documented_product() {
        let (c, basis) = confidence(1.0, true, DateSource::Parsed);
        assert_eq!(c, 1.0);
        assert!(basis.contains("coverage=100.0%"));
        let (c, _) = confidence(0.99, true, DateSource::Adoption);
        assert_eq!(c, 0.96); // 0.99 × 1.0 × 0.97 = 0.9603 → 0.96
        let (c, _) = confidence(1.0, false, DateSource::Sentinel);
        assert_eq!(c, 0.77); // 1.0 × 0.85 × 0.9 = 0.765 → 0.77
    }

    #[test]
    fn num_key_orders_dotted_and_suffixed_numbers() {
        assert!(num_key("7.1") > num_key("7"));
        assert!(num_key("8") > num_key("7.1"));
        assert!(num_key("23.2") > num_key("23.1"));
        assert!(num_key("24") > num_key("23.2"));
        assert!(num_key("12a") > num_key("12"));
        assert_eq!(
            num_key("23.1"),
            (vec![(23, String::new()), (1, String::new())], String::new())
        );
    }

    #[test]
    fn num_key_orders_lettered_and_chapter_section_numbers() {
        // Maine: lettered rules sort between their neighbors.
        assert!(num_key("4") < num_key("4A"));
        assert!(num_key("4A") < num_key("4B"));
        assert!(num_key("4C") < num_key("5"));
        // Connecticut Practice Book: chapter-section with letter suffixes on
        // either part; the letter is positional, not a trailing tiebreak.
        assert!(num_key("1-9") < num_key("1-9A"));
        assert!(num_key("1-9A") < num_key("1-10"));
        assert!(num_key("1-25") < num_key("2-1"));
        assert!(num_key("32-12") < num_key("32a-1"));
        assert!(num_key("32a-1") < num_key("33-1"));
        assert!(num_key("34a-20") < num_key("35-1"));
        // KRS dotted section numbers keep working.
        assert!(num_key("362.150") < num_key("362.155"));
    }

    #[test]
    fn toc_restart_reclassifies_the_first_pass_as_front_matter() {
        // A TOC whose entries are typographically identical to the real
        // headings (Guam GCA, consolidated Maine rules): the first pass is
        // discarded when Rule 1 comes around again.
        let l = layout(vec![
            block(vec![
                line("Rule 1. Scope.", 72.0, 0),
                line("Rule 2. One Form of Action.", 72.0, 0),
                line("Rule 3. Commencement.", 72.0, 0),
            ]),
            block(vec![line("Rule 1. Scope.", 72.0, 1)]),
            block(vec![line("These rules govern.", 72.0, 1)]),
            block(vec![line("Rule 2. One Form of Action.", 72.0, 1)]),
            block(vec![line("There is one form of action.", 72.0, 1)]),
            block(vec![line("Rule 3. Commencement.", 72.0, 2)]),
            block(vec![line("An action commences by filing.", 72.0, 2)]),
        ]);
        let doc = detect(&l, &profile("toc_restart = true"), "x.pdf").unwrap();
        let nums: Vec<&str> = doc.provisions.iter().map(|p| p.number.as_str()).collect();
        assert_eq!(nums, vec!["1", "2", "3"]);
        assert_eq!(doc.provisions[0].text, "These rules govern.");
        assert_eq!(doc.provisions[0].pages, [2, 2], "TOC page discarded");
        assert_eq!(doc.lines_skipped, 3, "the TOC pass is skipped, not lost");
        assert!(doc.unconsumed_lines.is_empty());
        assert!((doc.line_coverage - 1.0).abs() < 1e-6);
        assert!(doc
            .warnings
            .iter()
            .any(|w| w.contains("table-of-contents pass discarded: 3 provision(s)")));

        // Without the flag, the TOC pass wins and the body is swallowed.
        let doc = detect(&l, &profile(""), "x.pdf").unwrap();
        assert_eq!(doc.provisions.len(), 3);
        assert!(doc.provisions[2].text.contains("These rules govern."));
    }

    #[test]
    fn toc_restart_fires_at_most_once() {
        let l = layout(vec![
            block(vec![
                line("Rule 1. Scope.", 72.0, 0),
                line("Rule 2. One Form.", 72.0, 0),
            ]),
            block(vec![line("Rule 1. Scope.", 72.0, 1)]),
            block(vec![line("Body one.", 72.0, 1)]),
            block(vec![line("Rule 2. One Form.", 72.0, 1)]),
            // A later in-text repeat of "Rule 1." must NOT discard the body.
            block(vec![line("Rule 1. Scope. governs this rule too.", 72.0, 1)]),
            block(vec![line("Rule 3. Commencement.", 72.0, 2)]),
            block(vec![line("Body three.", 72.0, 2)]),
        ]);
        let p = profile("toc_restart = true\nheading_x0_cluster = false");
        let doc = detect(&l, &p, "x.pdf").unwrap();
        let nums: Vec<&str> = doc.provisions.iter().map(|p| p.number.as_str()).collect();
        assert_eq!(nums, vec!["1", "2", "3"]);
        assert!(doc.provisions[1].text.contains("governs this rule too"));
    }

    #[test]
    fn skip_block_patterns_skip_exactly_the_matching_block() {
        // Connecticut-style chapter index set beside body text: a region
        // skip would swallow the body continuation that follows the index.
        let l = layout(vec![
            block(vec![line("Rule 1. Scope.", 72.0, 0)]),
            block(vec![line("Body starts here and", 72.0, 0)]),
            block(vec![
                line("Sec.", 313.0, 0),
                line("1-12. Court Opening", 313.0, 0),
                line("1-13. Recess and Adjournment", 313.0, 0),
            ]),
            block(vec![line("continues after the index.", 313.0, 0)]),
        ]);
        let doc = detect(
            &l,
            &profile(r#"skip_block_patterns = ['^Sec\.$']"#),
            "x.pdf",
        )
        .unwrap();
        assert_eq!(doc.provisions.len(), 1);
        assert_eq!(
            doc.provisions[0].text,
            "Body starts here and\n\ncontinues after the index."
        );
        assert_eq!(doc.lines_skipped, 3);
        assert!(doc.unconsumed_lines.is_empty());
    }

    #[test]
    fn stop_marker_ends_detection_and_date_feeding() {
        // Trailing back matter (a forms appendix) carries credit lines that
        // match the history patterns; after the stop marker they must not
        // feed the final provision's dates, and no heading is accepted.
        let l = layout(vec![
            block(vec![line("Rule 1. Scope.", 72.0, 0)]),
            block(vec![line("Body.", 72.0, 0)]),
            block(vec![line("(Amended June 20, 2011.)", 72.0, 0)]),
            block(vec![line("APPENDIX OF FORMS", 72.0, 1)]),
            block(vec![line("(Amended June 12, 2025.)", 72.0, 1)]),
            block(vec![line("Rule 9. A form caption, not a rule.", 72.0, 1)]),
        ]);
        let doc = detect(
            &l,
            &profile(
                r#"history_patterns = ['^\(Amended']
stop_patterns = ['^APPENDIX OF FORMS$']"#,
            ),
            "x.pdf",
        )
        .unwrap();
        assert_eq!(doc.provisions.len(), 1);
        let p = &doc.provisions[0];
        assert_eq!(p.effective_date, "2011-06-20");
        assert_eq!(p.text, "Body.");
        assert_eq!(doc.lines_skipped, 3);
        assert!(doc.unconsumed_lines.is_empty());
    }

    #[test]
    fn history_reopens_so_trailing_credits_stay_out_of_text() {
        // Connecticut shape: credits after the heading AND after the body.
        let l = layout(vec![
            block(vec![line("Rule 1. Scope.", 72.0, 0)]),
            block(vec![line(
                "(Amended June 20, 2011, to take effect January 1, 2012.)",
                72.0,
                0,
            )]),
            block(vec![line("The rules govern practice.", 72.0, 0)]),
            block(vec![
                line(
                    "(P.B. 1978-1997, Sec. 1.) (Amended June 26, 2000, to take",
                    72.0,
                    0,
                ),
                line("effect January 1, 2001.)", 72.0, 0),
            ]),
        ]);
        let doc = detect(
            &l,
            &profile(r#"history_patterns = ['^\(P\.B\.', '^\(Amended']"#),
            "x.pdf",
        )
        .unwrap();
        let p = &doc.provisions[0];
        assert_eq!(p.text, "The rules govern practice.");
        let history = p.history.as_deref().unwrap();
        assert!(history.starts_with("(Amended June 20, 2011"));
        assert!(history.ends_with("effect January 1, 2001.)"));
        // The wrapped continuation's date is scanned: last date in text
        // order of the credit block wins over the inline one.
        assert_eq!(p.effective_date, "2001-01-01");
    }

    #[test]
    fn empty_layout_yields_empty_document_with_warning() {
        let doc = detect(&layout(vec![]), &profile(""), "x.pdf").unwrap();
        assert!(doc.provisions.is_empty());
        assert!((doc.line_coverage - 1.0).abs() < 1e-6);
        assert!(doc.warnings.iter().any(|w| w.contains("no provisions")));
        assert!(doc.empty_doc_marker.is_none());
    }

    #[test]
    fn declared_empty_doc_marker_recognizes_repealed_stub() {
        // The ND shape: a chapter PDF whose entire content is the chapter
        // heading plus one bracketed disposition line — a valid empty
        // document, not an extraction failure.
        let p = profile(
            r#"skip_patterns = ['^CHAPTER\s']
empty_doc_patterns = ['^\[(Repealed|Superseded)\b']"#,
        );
        let l = layout(vec![
            block(vec![line("CHAPTER 2-01", 200.0, 0)]),
            block(vec![line("REGULATION", 220.0, 0)]),
            block(vec![line("[Repealed by S.L. 1947, ch. 1, § 18]", 72.0, 0)]),
        ]);
        let doc = detect(&l, &p, "t02c01.pdf").unwrap();
        assert!(doc.provisions.is_empty());
        assert_eq!(
            doc.empty_doc_marker.as_deref(),
            Some("[Repealed by S.L. 1947, ch. 1, § 18]")
        );
        assert!(
            doc.warnings
                .iter()
                .any(|w| w.contains("recognized empty document")),
            "warnings: {:?}",
            doc.warnings
        );
        assert!(
            !doc.warnings.iter().any(|w| w.contains("no provisions")),
            "a recognized empty document must not also warn as a failure"
        );
        // The disposition line sits in the CHAPTER skip region — coverage
        // accounting is unchanged by the marker scan.
        assert!((doc.line_coverage - 1.0).abs() < 1e-6);
    }

    #[test]
    fn zero_provisions_without_marker_still_warns() {
        let p = profile(r#"empty_doc_patterns = ['^\[Repealed\b']"#);
        let l = layout(vec![block(vec![line("Some stray content.", 72.0, 0)])]);
        let doc = detect(&l, &p, "x.pdf").unwrap();
        assert!(doc.provisions.is_empty());
        assert!(doc.empty_doc_marker.is_none());
        assert!(doc.warnings.iter().any(|w| w.contains("no provisions")));
    }

    #[test]
    fn marker_line_in_a_document_with_provisions_is_ignored() {
        let p = profile(r#"empty_doc_patterns = ['^\[Repealed\b']"#);
        let l = layout(vec![
            block(vec![line("Rule 1. Scope.", 72.0, 0)]),
            block(vec![line("[Repealed by S.L. 1947, ch. 1, § 18]", 72.0, 0)]),
        ]);
        let doc = detect(&l, &p, "x.pdf").unwrap();
        assert_eq!(doc.provisions.len(), 1);
        assert!(
            doc.empty_doc_marker.is_none(),
            "empty_doc_patterns must only apply to provision-less documents"
        );
    }
}