xberg 1.0.6

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 98+ formats and 306 programming languages via tree-sitter code intelligence with async/sync APIs.
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
//! Per-page pre-screen for adaptive layout detection ([`LayoutStrategy::Auto`]).
//!
//! Grades every page from cheap geometry the PDF already carries (text-span
//! boxes, straight lines, raster and vector graphics, widget annotations) and
//! decides whether the expensive render + ONNX layout pass can pay off there.
//!
//! The gate is recall-biased: any structure evidence, sparse or absent text,
//! or a failure to gather signals selects the page for the model. Only pages
//! that positively look like plain single-column text are skipped, and a
//! skipped page processes exactly like a page where the model ran and found
//! no regions.
//!
//! All signal gathering is advisory and pixel-free, in the same shape as
//! [`super::scan_detect`]: a page that cannot be inspected must never abort
//! extraction, it just runs the model.
//!
//! [`LayoutStrategy::Auto`]: crate::core::config::layout::LayoutStrategy::Auto

use pdf_oxide::PdfDocument;
use pdf_oxide::annotation_types::AnnotationSubtype;
use pdf_oxide::document::ReadingOrder;

/// Pages with fewer spans than this look like slides, posters, or covers:
/// too little text to trust geometry, so the model runs.
const SPARSE_PAGE_MAX_SPANS: usize = 8;

/// Pages whose text layer carries fewer non-whitespace characters than this
/// are treated as having no usable text layer, so the model runs.
const TEXT_LAYER_MIN_CHARS: usize = 40;

/// Minimum width of an empty vertical band read as a column gutter, in points.
const COLUMN_GUTTER_MIN_WIDTH_PTS: f32 = 12.0;

/// Minimum spans fully on each side of a candidate gutter.
///
/// Deliberately far below the production column splitter's floor: a missed
/// split corrupts reading order, so the gate over-selects rather than trusts
/// the precision-tuned extraction constants.
const COLUMN_SIDE_MIN_SPANS: usize = 4;

/// Each side of a gutter must span at least this fraction of the text height.
const COLUMN_SIDE_MIN_HEIGHT_FRACTION: f32 = 0.15;

/// Horizontal tolerance when clustering span edges into table column anchors.
const GRID_EDGE_ALIGN_TOLERANCE_PTS: f32 = 3.0;

/// A span edge cluster must recur on this many distinct rows to count as a
/// table column anchor.
const GRID_MIN_ROWS: usize = 3;

/// Distinct aligned column anchors needed to read a page as table-bearing.
///
/// Two suffices (key-value blocks, two-column financial tables); the
/// production detector requires three, which the gate deliberately relaxes.
const GRID_MIN_COLS: usize = 2;

/// Rows are clustered on span vertical centers within this tolerance, points.
const GRID_ROW_TOLERANCE_PTS: f32 = 5.0;

/// Row clustering widens to this fraction of the span height for large fonts.
const GRID_ROW_TOLERANCE_HEIGHT_FRACTION: f32 = 0.6;

/// Straight lines shorter than this are decoration, not rules, in points.
const RULED_LINE_MIN_LENGTH_PTS: f32 = 20.0;

/// Ruled-line evidence needs at least this many rules per orientation, so a
/// single underline or divider does not select the page.
const RULED_LINES_MIN_PER_ORIENTATION: usize = 2;

/// Combined raster and vector coverage at or above this fraction reads the
/// page as figure- or chart-bearing.
const GRAPHICS_COVERAGE_MIN: f32 = 0.15;

/// Why the gate selected (or skipped) a page.
///
/// Recorded per page so `Auto` runs are auditable from extraction metadata.
#[cfg_attr(alef, alef(skip))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum GateReason {
    /// Too little text to trust geometry signals.
    SparseText,
    /// No usable native text layer; the model is the only structure source.
    NoTextLayer,
    /// An empty vertical band splits the text into two populated columns.
    MultiColumn,
    /// Span edges align into recurring column anchors across rows.
    TableGrid,
    /// Horizontal and vertical rules suggest a grid or form.
    RuledLines,
    /// Raster plus vector graphics cover a meaningful page fraction.
    GraphicsHeavy,
    /// The page carries interactive form widgets.
    FormWidgets,
    /// Signal gathering failed; the gate must not guess.
    SignalsUnavailable,
    /// Plain single-column text: the model has nothing to find.
    PlainText,
}

impl GateReason {
    /// Snake_case wire name recorded in extraction metadata.
    pub(crate) fn wire_name(self) -> &'static str {
        match self {
            Self::SparseText => "sparse_text",
            Self::NoTextLayer => "no_text_layer",
            Self::MultiColumn => "multi_column",
            Self::TableGrid => "table_grid",
            Self::RuledLines => "ruled_lines",
            Self::GraphicsHeavy => "graphics_heavy",
            Self::FormWidgets => "form_widgets",
            Self::SignalsUnavailable => "signals_unavailable",
            Self::PlainText => "plain_text",
        }
    }
}

/// One page's gate outcome.
#[cfg_attr(alef, alef(skip))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PageGateDecision {
    /// Whether the layout model runs on this page.
    pub run_layout: bool,
    /// The dominant reason for the decision.
    pub reason: GateReason,
}

impl PageGateDecision {
    fn run(reason: GateReason) -> Self {
        Self {
            run_layout: true,
            reason,
        }
    }

    fn skip() -> Self {
        Self {
            run_layout: false,
            reason: GateReason::PlainText,
        }
    }
}

/// Axis-aligned span box in PDF points, the only geometry the gate reads.
#[cfg_attr(alef, alef(skip))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct SpanBox {
    pub left: f32,
    pub bottom: f32,
    pub right: f32,
    pub top: f32,
}

impl SpanBox {
    fn height(&self) -> f32 {
        (self.top - self.bottom).abs()
    }

    fn vertical_center(&self) -> f32 {
        (self.top + self.bottom) / 2.0
    }
}

/// Everything [`decide_page`] needs, gathered without decoding any pixels.
#[cfg_attr(alef, alef(skip))]
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PageGateSignals {
    /// Text-span boxes in PDF points.
    pub spans: Vec<SpanBox>,
    /// Non-whitespace characters in the native text layer.
    pub text_chars: usize,
    /// Horizontal rules at least [`RULED_LINE_MIN_LENGTH_PTS`] long.
    pub horizontal_rules: usize,
    /// Vertical rules at least [`RULED_LINE_MIN_LENGTH_PTS`] long.
    pub vertical_rules: usize,
    /// Fraction of the page under raster images plus vector paths, `[0, 1]`.
    ///
    /// Overlaps are summed, not unioned: an upper bound that can over-select
    /// a page for the model, never under-select one.
    pub graphics_coverage: f32,
    /// Whether the page carries widget (form field) annotations.
    pub has_form_widgets: bool,
}

/// Decide one page from its signals. Pure, so it is testable without a
/// [`PdfDocument`].
///
/// Checks are ordered cheapest-first; the page is skipped only when every
/// run-condition stays quiet.
pub(crate) fn decide_page(signals: &PageGateSignals) -> PageGateDecision {
    if signals.text_chars < TEXT_LAYER_MIN_CHARS {
        return PageGateDecision::run(GateReason::NoTextLayer);
    }
    if signals.spans.len() < SPARSE_PAGE_MAX_SPANS {
        return PageGateDecision::run(GateReason::SparseText);
    }
    if signals.has_form_widgets {
        return PageGateDecision::run(GateReason::FormWidgets);
    }
    if signals.horizontal_rules >= RULED_LINES_MIN_PER_ORIENTATION
        && signals.vertical_rules >= RULED_LINES_MIN_PER_ORIENTATION
    {
        return PageGateDecision::run(GateReason::RuledLines);
    }
    if signals.graphics_coverage >= GRAPHICS_COVERAGE_MIN {
        return PageGateDecision::run(GateReason::GraphicsHeavy);
    }
    if has_column_split(&signals.spans) {
        return PageGateDecision::run(GateReason::MultiColumn);
    }
    if has_aligned_grid(&signals.spans) {
        return PageGateDecision::run(GateReason::TableGrid);
    }
    PageGateDecision::skip()
}

/// Whether an empty vertical band splits the spans into two populated sides.
///
/// Sweeps the x-projection of all span intervals: a maximal gap wider than
/// [`COLUMN_GUTTER_MIN_WIDTH_PTS`] with [`COLUMN_SIDE_MIN_SPANS`] spans on
/// each side, both sides covering [`COLUMN_SIDE_MIN_HEIGHT_FRACTION`] of the
/// text height, reads as a column gutter.
///
/// A single full-width span crossing the gutter (a heading over two columns)
/// hides the gap from this projection; such pages are still selected through
/// the [`has_aligned_grid`] backstop, since column bodies share left anchors
/// across many rows.
fn has_column_split(spans: &[SpanBox]) -> bool {
    if spans.len() < COLUMN_SIDE_MIN_SPANS * 2 {
        return false;
    }
    let text_height = vertical_extent(spans.iter());
    if text_height <= f32::EPSILON {
        return false;
    }

    let mut by_left: Vec<&SpanBox> = spans.iter().collect();
    by_left.sort_by(|a, b| a.left.total_cmp(&b.left));

    let mut covered_right = by_left[0].right;
    for (index, span) in by_left.iter().enumerate().skip(1) {
        let gap = span.left - covered_right;
        if gap >= COLUMN_GUTTER_MIN_WIDTH_PTS && sides_populated(&by_left, index, text_height) {
            return true;
        }
        covered_right = covered_right.max(span.right);
    }
    false
}

/// Whether both sides of the gap before `split_index` hold enough spans and
/// vertical coverage to be real columns.
fn sides_populated(by_left: &[&SpanBox], split_index: usize, text_height: f32) -> bool {
    let (left, right) = by_left.split_at(split_index);
    if left.len() < COLUMN_SIDE_MIN_SPANS || right.len() < COLUMN_SIDE_MIN_SPANS {
        return false;
    }
    let min_height = text_height * COLUMN_SIDE_MIN_HEIGHT_FRACTION;
    vertical_extent(left.iter().copied()) >= min_height && vertical_extent(right.iter().copied()) >= min_height
}

fn vertical_extent<'a>(spans: impl Iterator<Item = &'a SpanBox>) -> f32 {
    let mut bottom = f32::INFINITY;
    let mut top = f32::NEG_INFINITY;
    for span in spans {
        bottom = bottom.min(span.bottom);
        top = top.max(span.top);
    }
    if top > bottom { top - bottom } else { 0.0 }
}

/// Whether span left or right edges recur in aligned column anchors across
/// enough rows to look table-bearing.
fn has_aligned_grid(spans: &[SpanBox]) -> bool {
    let rows = cluster_rows(spans);
    let multi_span_rows: Vec<&Vec<&SpanBox>> = rows.iter().filter(|row| row.len() >= GRID_MIN_COLS).collect();
    if multi_span_rows.len() < GRID_MIN_ROWS {
        return false;
    }

    let left_anchors = recurring_edge_clusters(&multi_span_rows, |span| span.left);
    if left_anchors >= GRID_MIN_COLS {
        return true;
    }
    let right_anchors = recurring_edge_clusters(&multi_span_rows, |span| span.right);
    right_anchors >= GRID_MIN_COLS
}

/// Group spans into rows on vertical centers within [`GRID_ROW_TOLERANCE_PTS`].
fn cluster_rows(spans: &[SpanBox]) -> Vec<Vec<&SpanBox>> {
    let mut by_center: Vec<&SpanBox> = spans.iter().collect();
    by_center.sort_by(|a, b| a.vertical_center().total_cmp(&b.vertical_center()));

    let mut rows: Vec<Vec<&SpanBox>> = Vec::new();
    for span in by_center {
        match rows.last_mut() {
            Some(row)
                if (span.vertical_center() - row[0].vertical_center()).abs()
                    <= GRID_ROW_TOLERANCE_PTS.max(span.height() * GRID_ROW_TOLERANCE_HEIGHT_FRACTION) =>
            {
                row.push(span);
            }
            _ => rows.push(vec![span]),
        }
    }
    rows
}

/// Count edge positions that recur on at least [`GRID_MIN_ROWS`] rows.
///
/// Edges are clustered within [`GRID_EDGE_ALIGN_TOLERANCE_PTS`] of the
/// cluster's first edge, anchored rather than chained: adjacent edges 3pt
/// apart must not link scattered prose-span edges into one wide false anchor.
/// Each cluster counts the number of distinct rows contributing to it.
fn recurring_edge_clusters(rows: &[&Vec<&SpanBox>], edge: fn(&SpanBox) -> f32) -> usize {
    let mut edges: Vec<(f32, usize)> = rows
        .iter()
        .enumerate()
        .flat_map(|(row_index, row)| row.iter().map(move |span| (edge(span), row_index)))
        .collect();
    edges.sort_by(|a, b| a.0.total_cmp(&b.0));

    let mut anchors = 0usize;
    let mut cluster_start = 0usize;
    for index in 1..=edges.len() {
        let cluster_ended =
            index == edges.len() || edges[index].0 - edges[cluster_start].0 > GRID_EDGE_ALIGN_TOLERANCE_PTS;
        if cluster_ended {
            let mut row_indices: Vec<usize> = edges[cluster_start..index].iter().map(|(_, row)| *row).collect();
            row_indices.sort_unstable();
            row_indices.dedup();
            if row_indices.len() >= GRID_MIN_ROWS {
                anchors += 1;
            }
            cluster_start = index;
        }
    }
    anchors
}

/// Gather one page's signals from `doc`, or `None` when inspection fails.
///
/// Failures are advisory (matching [`super::scan_detect`]): the caller maps
/// `None` to [`GateReason::SignalsUnavailable`] and runs the model.
fn page_signals(doc: &PdfDocument, page_index: usize) -> Option<PageGateSignals> {
    let page_text = super::oxide::guard_oxide_panic(
        || {
            doc.extract_page_text_with_options(page_index, ReadingOrder::ColumnAware)
                .map_err(|error| error.to_string())
        },
        |message| message,
    )
    .ok()?;

    let spans: Vec<SpanBox> = page_text
        .spans
        .iter()
        .filter(|span| !span.text.trim().is_empty())
        .map(|span| SpanBox {
            left: span.bbox.x,
            bottom: span.bbox.y,
            right: span.bbox.x + span.bbox.width,
            top: span.bbox.y + span.bbox.height,
        })
        .collect();
    let text_chars = page_text
        .spans
        .iter()
        .map(|span| span.text.chars().filter(|c| !c.is_whitespace()).count())
        .sum();

    // One content-stream path parse serves both the rule counter and the
    // vector-coverage signal; pdf_oxide's extract_lines would re-run
    // extract_paths internally. ~keep
    let paths = super::oxide::guard_oxide_panic(
        || doc.extract_paths(page_index).map_err(|error| error.to_string()),
        |message| message,
    )
    .ok()?;
    let (horizontal_rules, vertical_rules) = count_rules(&paths);

    Some(PageGateSignals {
        spans,
        text_chars,
        horizontal_rules,
        vertical_rules,
        graphics_coverage: graphics_coverage(doc, page_index, &paths)?,
        has_form_widgets: has_form_widgets(doc, page_index)?,
    })
}

/// Count horizontal and vertical rules at least [`RULED_LINE_MIN_LENGTH_PTS`]
/// long. A rule must also be thin (minor bbox dimension within
/// [`GRID_EDGE_ALIGN_TOLERANCE_PTS`]) so long diagonals on chart-heavy pages
/// do not count.
fn count_rules(paths: &[pdf_oxide::elements::PathContent]) -> (usize, usize) {
    let mut horizontal = 0usize;
    let mut vertical = 0usize;
    for path in paths.iter().filter(|path| path.is_straight_line()) {
        let width = path.bbox.width.abs();
        let height = path.bbox.height.abs();
        if width >= RULED_LINE_MIN_LENGTH_PTS && height <= GRID_EDGE_ALIGN_TOLERANCE_PTS {
            horizontal += 1;
        } else if height >= RULED_LINE_MIN_LENGTH_PTS && width <= GRID_EDGE_ALIGN_TOLERANCE_PTS {
            vertical += 1;
        }
    }
    (horizontal, vertical)
}

/// Fraction of the page under raster images plus stroked or filled vector
/// paths, without decoding pixels. Summed, not unioned: an upper bound.
fn graphics_coverage(doc: &PdfDocument, page_index: usize, paths: &[pdf_oxide::elements::PathContent]) -> Option<f32> {
    let (x0, y0, x1, y1) = doc.get_page_media_box(page_index).ok()?;
    let page_area = ((x1 - x0) * (y1 - y0)).abs();
    if page_area <= f32::EPSILON {
        return None;
    }

    let raster: f32 = doc
        .page_image_handles(page_index)
        .ok()?
        .iter()
        .map(|handle| (handle.bbox.width * handle.bbox.height).abs())
        .sum();
    let vector: f32 = paths
        .iter()
        .filter(|path| !path.is_straight_line())
        .map(|path| (path.bbox.width * path.bbox.height).abs())
        .sum();

    Some(((raster + vector) / page_area).clamp(0.0, 1.0))
}

fn has_form_widgets(doc: &PdfDocument, page_index: usize) -> Option<bool> {
    let annotations = super::oxide::guard_oxide_panic(
        || doc.get_annotations(page_index).map_err(|error| error.to_string()),
        |message| message,
    )
    .ok()?;
    Some(
        annotations
            .iter()
            .any(|annotation| annotation.subtype_enum == AnnotationSubtype::Widget),
    )
}

/// Decide every page of `doc`.
///
/// Infallible: a page whose signals cannot be gathered runs the model with
/// [`GateReason::SignalsUnavailable`] rather than failing extraction.
pub(crate) fn decide_pages(doc: &PdfDocument, page_count: usize) -> Vec<PageGateDecision> {
    (0..page_count)
        .map(|page_index| match page_signals(doc, page_index) {
            Some(signals) => decide_page(&signals),
            None => PageGateDecision::run(GateReason::SignalsUnavailable),
        })
        .collect()
}

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

    fn span(left: f32, bottom: f32, right: f32, top: f32) -> SpanBox {
        SpanBox {
            left,
            bottom,
            right,
            top,
        }
    }

    /// A believable single-column prose page: one span per line, common margins.
    fn prose_spans(lines: usize) -> Vec<SpanBox> {
        (0..lines)
            .map(|line| {
                let top = 720.0 - line as f32 * 14.0;
                span(72.0, top - 10.0, 540.0, top)
            })
            .collect()
    }

    fn prose_signals() -> PageGateSignals {
        PageGateSignals {
            spans: prose_spans(40),
            text_chars: 2_000,
            horizontal_rules: 0,
            vertical_rules: 0,
            graphics_coverage: 0.0,
            has_form_widgets: false,
        }
    }

    #[test]
    fn plain_prose_page_is_skipped() {
        let decision = decide_page(&prose_signals());
        assert!(!decision.run_layout);
        assert_eq!(decision.reason, GateReason::PlainText);
    }

    #[test]
    fn missing_text_layer_runs_the_model() {
        let signals = PageGateSignals {
            text_chars: 0,
            spans: Vec::new(),
            ..prose_signals()
        };
        let decision = decide_page(&signals);
        assert!(decision.run_layout);
        assert_eq!(decision.reason, GateReason::NoTextLayer);
    }

    #[test]
    fn sparse_slide_like_page_runs_the_model() {
        let signals = PageGateSignals {
            spans: prose_spans(3),
            text_chars: 120,
            ..prose_signals()
        };
        let decision = decide_page(&signals);
        assert!(decision.run_layout);
        assert_eq!(decision.reason, GateReason::SparseText);
    }

    #[test]
    fn two_column_page_runs_the_model() {
        let mut spans = Vec::new();
        for line in 0..20 {
            let top = 720.0 - line as f32 * 14.0;
            spans.push(span(72.0, top - 10.0, 290.0, top));
            spans.push(span(322.0, top - 10.0, 540.0, top));
        }
        let signals = PageGateSignals {
            spans,
            ..prose_signals()
        };
        let decision = decide_page(&signals);
        assert!(decision.run_layout);
        assert_eq!(decision.reason, GateReason::MultiColumn);
    }

    #[test]
    fn margin_note_alone_is_not_a_column_split() {
        let mut spans = prose_spans(30);
        // Three short notes in the right margin: populated side too thin. ~keep
        for note in 0..3 {
            let top = 700.0 - note as f32 * 200.0;
            spans.push(span(560.0, top - 8.0, 600.0, top));
        }
        // The gap between body (right edge 540) and notes (left 560) is 20pts
        // wide, but the note side has fewer than COLUMN_SIDE_MIN_SPANS spans. ~keep
        let signals = PageGateSignals {
            spans,
            ..prose_signals()
        };
        assert!(!decide_page(&signals).run_layout);
    }

    #[test]
    fn aligned_word_grid_runs_the_model() {
        // A 4-row, 3-column borderless table embedded under prose. ~keep
        let mut spans = prose_spans(20);
        for row in 0..4 {
            let top = 400.0 - row as f32 * 18.0;
            for column in 0..3 {
                let left = 90.0 + column as f32 * 150.0;
                spans.push(span(left, top - 10.0, left + 60.0, top));
            }
        }
        let signals = PageGateSignals {
            spans,
            ..prose_signals()
        };
        let decision = decide_page(&signals);
        assert!(decision.run_layout);
        assert_eq!(decision.reason, GateReason::TableGrid);
    }

    #[test]
    fn prose_left_margin_alignment_is_not_a_grid() {
        // Every prose line shares one left anchor; one anchor is below
        // GRID_MIN_COLS so justified prose must not read as a table. ~keep
        assert!(!has_aligned_grid(&prose_spans(40)));
    }

    #[test]
    fn prose_lines_split_into_scattered_spans_are_not_a_grid() {
        // Kerning and style changes split real prose lines into several
        // spans whose edges land at unaligned x positions. Anchored edge
        // clustering must not chain them into false column anchors. ~keep
        let mut spans = Vec::new();
        for line in 0..20 {
            let top = 720.0 - line as f32 * 14.0;
            // Left anchor plus two mid-line breaks drifting 2pts per line:
            // chained clustering would merge the drift into wide anchors. ~keep
            let drift = line as f32 * 2.0;
            spans.push(span(72.0, top - 10.0, 200.0 + drift, top));
            spans.push(span(202.0 + drift, top - 10.0, 380.0 - drift, top));
            spans.push(span(382.0 - drift, top - 10.0, 540.0, top));
        }
        let signals = PageGateSignals {
            spans,
            text_chars: 2_000,
            horizontal_rules: 0,
            vertical_rules: 0,
            graphics_coverage: 0.0,
            has_form_widgets: false,
        };
        let decision = decide_page(&signals);
        assert!(
            !decision.run_layout,
            "drifting mid-line span edges must not read as a table grid, got {:?}",
            decision.reason
        );
    }

    #[test]
    fn full_width_heading_over_two_columns_still_runs_the_model() {
        // The heading span crosses the gutter, hiding it from the
        // x-projection; the aligned-grid backstop must still select the page. ~keep
        let mut spans = vec![span(72.0, 710.0, 540.0, 726.0)];
        for line in 0..20 {
            let top = 690.0 - line as f32 * 14.0;
            spans.push(span(72.0, top - 10.0, 290.0, top));
            spans.push(span(322.0, top - 10.0, 540.0, top));
        }
        let signals = PageGateSignals {
            spans,
            text_chars: 2_000,
            horizontal_rules: 0,
            vertical_rules: 0,
            graphics_coverage: 0.0,
            has_form_widgets: false,
        };
        assert!(decide_page(&signals).run_layout);
    }

    #[test]
    fn ruled_grid_runs_the_model() {
        let signals = PageGateSignals {
            horizontal_rules: 5,
            vertical_rules: 4,
            ..prose_signals()
        };
        let decision = decide_page(&signals);
        assert!(decision.run_layout);
        assert_eq!(decision.reason, GateReason::RuledLines);
    }

    #[test]
    fn horizontal_dividers_alone_do_not_run_the_model() {
        let signals = PageGateSignals {
            horizontal_rules: 3,
            vertical_rules: 0,
            ..prose_signals()
        };
        assert!(!decide_page(&signals).run_layout);
    }

    #[test]
    fn graphics_heavy_page_runs_the_model() {
        let signals = PageGateSignals {
            graphics_coverage: 0.4,
            ..prose_signals()
        };
        let decision = decide_page(&signals);
        assert!(decision.run_layout);
        assert_eq!(decision.reason, GateReason::GraphicsHeavy);
    }

    #[test]
    fn small_inline_figure_does_not_run_the_model() {
        let signals = PageGateSignals {
            graphics_coverage: 0.05,
            ..prose_signals()
        };
        assert!(!decide_page(&signals).run_layout);
    }

    #[test]
    fn form_widgets_run_the_model() {
        let signals = PageGateSignals {
            has_form_widgets: true,
            ..prose_signals()
        };
        let decision = decide_page(&signals);
        assert!(decision.run_layout);
        assert_eq!(decision.reason, GateReason::FormWidgets);
    }
}