rustai-core 0.4.0

Zero-cost local research pipeline: async search routing, TLS-fingerprint-aware fetching, SIMD DOM denoising and BM25 context slimming for local LLMs.
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
//! Markdown writer.
//!
//! The output is deliberately plain — ATX headings, `-` bullets, fenced code,
//! pipe tables — because it is fed to a small local model, not rendered. Every
//! block becomes a [`Unit`], which is the granularity the context slimmer
//! later ranks and selects.

use url::Url;

use crate::denoise::{DenoiseConfig, DenoiseStats, is_noise};
use crate::parse::dom::{Doc, Id, decode_entities};
use crate::parse::{Unit, UnitKind};
use crate::text;

const INLINE_TAGS: &[&str] = &[
    "a", "abbr", "b", "bdi", "bdo", "big", "cite", "code", "data", "del", "dfn", "em", "font", "i",
    "img", "ins", "kbd", "mark", "q", "s", "samp", "small", "span", "strike", "strong", "sub",
    "sup", "time", "tt", "u", "var", "wbr", "br", "ruby", "rt", "rp",
];

const HEADINGS: &[&str] = &["h1", "h2", "h3", "h4", "h5", "h6"];

/// Above this serialised size, an "inline" element is checked for block-level
/// content before being believed.
///
/// Inline elements are small by nature. A `<span>` carrying 50 KB of markup is
/// not emphasis — it is an unclosed tag that swallowed the rest of the page,
/// and flattening it would turn the whole document into one paragraph. The
/// size gate keeps the check off the hot path: `html_len` is O(1) and the vast
/// majority of inline nodes never pay for the descendant walk.
const INLINE_INSPECT_BYTES: u32 = 2048;

/// Language names accepted from a bare `class="rust"`-style attribute.
///
/// A whitelist rather than a pattern, because that attribute is shared with
/// styling hooks: `hljs`, `notranslate` and `prettyprint` all look exactly like
/// a language name to anything less strict.
const KNOWN_LANGUAGES: &[&str] = &[
    "bash",
    "c",
    "clojure",
    "cpp",
    "cs",
    "csharp",
    "css",
    "dart",
    "diff",
    "dockerfile",
    "elixir",
    "elm",
    "erlang",
    "fsharp",
    "go",
    "graphql",
    "groovy",
    "haskell",
    "hcl",
    "html",
    "ini",
    "java",
    "javascript",
    "js",
    "json",
    "json5",
    "jsx",
    "julia",
    "kotlin",
    "latex",
    "less",
    "lisp",
    "lua",
    "makefile",
    "markdown",
    "matlab",
    "nginx",
    "nim",
    "objectivec",
    "ocaml",
    "perl",
    "php",
    "powershell",
    "protobuf",
    "python",
    "r",
    "ruby",
    "rust",
    "sass",
    "scala",
    "scss",
    "shell",
    "sh",
    "sql",
    "svelte",
    "swift",
    "terraform",
    "toml",
    "ts",
    "tsx",
    "typescript",
    "vim",
    "vue",
    "xml",
    "yaml",
    "zig",
    "zsh",
];

/// Options that change what ends up in the Markdown.
#[derive(Debug, Clone)]
pub struct RenderOptions {
    /// Keep `[text](href)` links instead of flattening to text.
    pub include_links: bool,
    /// Keep `![alt](src)` images.
    pub include_images: bool,
    /// Render `<table>` as a pipe table.
    pub include_tables: bool,
}

impl Default for RenderOptions {
    fn default() -> Self {
        RenderOptions { include_links: true, include_images: false, include_tables: true }
    }
}

pub(crate) struct Writer<'d, 'a> {
    doc: &'d Doc<'a>,
    cfg: &'d DenoiseConfig,
    opts: &'d RenderOptions,
    base: Option<Url>,
    heading_stack: Vec<(u8, String)>,
    list_depth: usize,
    pub(crate) units: Vec<Unit>,
    pub(crate) stats: DenoiseStats,
}

impl<'d, 'a> Writer<'d, 'a> {
    pub(crate) fn new(
        doc: &'d Doc<'a>,
        cfg: &'d DenoiseConfig,
        opts: &'d RenderOptions,
        base: Option<Url>,
    ) -> Self {
        Writer {
            doc,
            cfg,
            opts,
            base,
            heading_stack: Vec::new(),
            list_depth: 0,
            units: Vec::new(),
            stats: DenoiseStats::default(),
        }
    }

    /// Walk the chosen content root, without re-judging the root itself.
    ///
    /// The root arrives already decided: the content scorer picked it, or it
    /// is `<body>` as a fallback. Re-asking the boilerplate heuristics about
    /// it reopens a settled question with the wrong test — an article
    /// container that also holds the navigation it is about to drop reads as
    /// a link farm by raw density, and rejecting it discards the whole
    /// document to save the part that was leaving anyway.
    pub(crate) fn walk_root(&mut self, id: Id) {
        self.walk_inner(id, false);
    }

    /// Walk a subtree, emitting units.
    pub(crate) fn walk(&mut self, id: Id) {
        self.walk_inner(id, true);
    }

    fn walk_inner(&mut self, id: Id, judge: bool) {
        self.stats.nodes_visited += 1;
        if judge && is_noise(self.doc, id, self.cfg) {
            self.stats.nodes_dropped += self.doc.descendants(id).len();
            return;
        }
        let name = self.doc.tag_name(id);

        if let Some(level) = heading_level(name) {
            let inline = self.render_children_inline(id);
            let t = text::normalize_ws(&inline);
            if !t.is_empty() {
                // The plain form has to lose the link syntax, the same as a
                // paragraph's does. Modern documentation wraps every heading
                // in its own anchor, so leaving it in puts the whole URL into
                // the text that BM25 scores and an embedding model reads --
                // and into every breadcrumb built from the heading path.
                let plain = strip_markdown(&t);
                self.push_heading(level, &plain);
                let md = format!("{} {}", "#".repeat(level as usize), t);
                self.emit(UnitKind::Heading, level, plain, md);
            }
            return;
        }

        match name {
            "" => {
                // Bare text directly under a container.
                if let Some(tl::Node::Raw(_)) = self.doc.node(id) {
                    let t = text::normalize_ws(&self.render_inline(id));
                    if text::visible_len(&t) >= self.cfg.min_block_len as usize {
                        self.emit(UnitKind::Paragraph, 0, t.clone(), t);
                    }
                }
            }
            // A paragraph is only a paragraph if it holds no block-level
            // element. HTML forbids that nesting, but lenient parsers -- this
            // one included -- do not insert the implied `</p>` that a browser
            // would, so an unclosed `<p>` can end up owning the rest of the
            // document. Recursing costs one check and turns that failure into
            // ordinary output.
            "p" | "dd" | "dt" | "figcaption" | "summary" | "address" => {
                if self.doc.is_leaf_block(id) {
                    let t = text::normalize_ws(&self.render_children_inline(id));
                    if !t.is_empty() {
                        let plain = strip_markdown(&t);
                        self.emit(UnitKind::Paragraph, 0, plain, t);
                    }
                } else {
                    self.walk_children(id);
                }
            }
            "pre" => self.emit_code(id),
            "blockquote" if !self.doc.is_leaf_block(id) => self.walk_children(id),
            "blockquote" => {
                let inner = self.doc.inner_text(id);
                if !inner.is_empty() {
                    let md = inner.lines().map(|l| format!("> {l}")).collect::<Vec<_>>().join("\n");
                    self.emit(UnitKind::Quote, 0, inner, md);
                }
            }
            "ul" | "ol" | "dl" => {
                self.list_depth += 1;
                self.walk_children(id);
                self.list_depth = self.list_depth.saturating_sub(1);
            }
            "li" => self.emit_list_item(id),
            // A table holding headings, sections or other tables is laying out
            // a page, not tabulating data. Rendering one as a pipe table turns
            // a whole document into a single unreadable row — and lenient HTML
            // parsers, this one included, will happily put an entire page
            // inside a `<table>` whose close tag they failed to match.
            "table" if self.is_data_table(id) => {
                if self.opts.include_tables {
                    self.emit_table(id);
                }
            }
            "table" => self.walk_children(id),
            "hr" | "br" => {}
            _ => self.walk_children(id),
        }
    }

    fn walk_children(&mut self, id: Id) {
        // Group runs of inline children into implicit paragraphs so that text
        // sitting loose inside a `<div>` is not lost.
        let mut run: Vec<Id> = Vec::new();
        for child in self.doc.children(id) {
            if self.is_inline(child) {
                run.push(child);
            } else {
                self.flush_inline_run(&mut run);
                self.walk(child);
            }
        }
        self.flush_inline_run(&mut run);
    }

    fn flush_inline_run(&mut self, run: &mut Vec<Id>) {
        if run.is_empty() {
            return;
        }
        // An image is a block in its own right, so a run that carries one is
        // kept whatever its alt text weighs; the length gate exists to drop
        // stray words, not figures the caller explicitly asked for.
        let has_image =
            self.opts.include_images && run.iter().any(|&id| self.doc.tag_name(id) == "img");
        let mut buf = String::new();
        for id in run.drain(..) {
            buf.push_str(&self.render_inline(id));
        }
        let t = text::normalize_ws(&buf);
        let plain = strip_markdown(&t);
        if has_image || text::visible_len(&plain) >= self.cfg.min_block_len as usize {
            self.emit(UnitKind::Paragraph, 0, plain, t);
        }
    }

    fn is_inline(&self, id: Id) -> bool {
        match self.doc.node(id) {
            Some(tl::Node::Raw(_)) => true,
            Some(tl::Node::Tag(tag)) => {
                if !INLINE_TAGS.contains(&tag.name().as_utf8_str().to_ascii_lowercase().as_str()) {
                    return false;
                }
                self.doc.html_len(id) <= INLINE_INSPECT_BYTES || self.doc.is_leaf_block(id)
            }
            _ => false,
        }
    }

    fn emit_list_item(&mut self, id: Id) {
        // Only the inline run becomes the bullet. Block children — nested
        // lists, but also the paragraphs and tables that `<li>` is allowed to
        // contain — are walked so they keep their own structure. Flattening
        // them with `inner_text` is how a single mis-nested `<li>` ends up
        // holding an entire page.
        let mut inline_run: Vec<Id> = Vec::new();
        let mut blocks: Vec<Id> = Vec::new();
        for child in self.doc.children(id) {
            if self.is_inline(child) {
                inline_run.push(child);
            } else {
                blocks.push(child);
            }
        }

        let mut buf = String::new();
        for child in inline_run {
            buf.push_str(&self.render_inline(child));
        }
        let t = text::normalize_ws(&buf);
        if !t.is_empty() {
            let depth = self.list_depth.saturating_sub(1).min(6);
            let md = format!("{}- {}", "  ".repeat(depth), t);
            self.emit(UnitKind::ListItem, depth as u8, strip_markdown(&t), md);
        }
        for child in blocks {
            self.walk(child);
        }
    }

    fn emit_code(&mut self, id: Id) {
        let raw = self.doc.raw_text(id);
        let body = raw.trim_end_matches('\n');
        if body.trim().is_empty() {
            return;
        }
        let lang = self.detect_language(id);
        // A body carrying its own fence would close this one early and let
        // whatever follows render as document structure, so the fence has to
        // be longer than the longest backtick run inside it.
        let fence = "`".repeat(longest_backtick_run(body).max(2) + 1);
        let md = format!("{fence}{lang}\n{body}\n{fence}");
        self.emit(UnitKind::Code, 0, body.to_string(), md);
    }

    /// Work out what language a code block is in.
    ///
    /// There is no single convention. Highlighters write `language-rust`,
    /// `lang-rust` or a bare `rust`; GitHub writes `highlight-source-rust` on a
    /// wrapper *above* the `<pre>`; others use `data-lang`. A fenced block
    /// without its language is markedly less useful to a model reading it, so
    /// this checks all of them — ancestors included — rather than the first
    /// class attribute it happens to find.
    fn detect_language(&self, id: Id) -> String {
        let mut candidates: Vec<Id> = vec![id];
        candidates.extend(self.doc.descendants(id).into_iter().skip(1).take(8));
        candidates.extend(self.doc.ancestors(id, 2));

        for node in candidates {
            for key in ["class", "data-lang", "data-language", "data-code-language"] {
                let Some(value) = self.doc.attr(node, key) else { continue };
                if key != "class" {
                    if let Some(lang) = normalize_language(&value) {
                        return lang;
                    }
                    continue;
                }
                for token in value.split_whitespace() {
                    let stripped = token
                        .strip_prefix("language-")
                        .or_else(|| token.strip_prefix("lang-"))
                        .or_else(|| token.strip_prefix("highlight-source-"))
                        .or_else(|| token.strip_prefix("highlight-text-"))
                        .or_else(|| token.strip_prefix("sourceCode-"));
                    if let Some(lang) = stripped.and_then(normalize_language) {
                        return lang;
                    }
                    // A bare class name, but only if it names a language we
                    // recognise — `hljs`, `prettyprint` and `notranslate` all
                    // sit in the same attribute.
                    if let Some(lang) = normalize_language(token)
                        && KNOWN_LANGUAGES.contains(&lang.as_str())
                    {
                        return lang;
                    }
                }
            }
        }
        String::new()
    }

    /// Is this a table of data, or a table used for layout?
    ///
    /// Structural content inside cells is the giveaway. The caps are a second
    /// line of defence against a `<table>` whose close tag the parser never
    /// found, which swallows the rest of the document.
    ///
    /// Only the text cap speaks to context budget, and it is the tighter of
    /// the two by far. The node cap has to stay well clear of what a real
    /// table costs: a 223-row table of national GDP figures, six columns of
    /// linked and footnoted cells, comes to 4,522 nodes around 6.4 KB of
    /// text. Rejecting that emits nothing at all -- walking a data table as
    /// ordinary blocks yields cells too short to survive as paragraphs -- so a
    /// cap set near real tables does not degrade the output, it deletes it.
    fn is_data_table(&self, id: Id) -> bool {
        const MAX_TABLE_TEXT: u32 = 20_000;
        const MAX_TABLE_NODES: usize = 30_000;

        if self.doc.text_len(id) > MAX_TABLE_TEXT {
            return false;
        }
        let descendants = self.doc.descendants(id);
        if descendants.len() > MAX_TABLE_NODES {
            return false;
        }
        !descendants.iter().skip(1).any(|&d| {
            matches!(
                self.doc.tag_name(d),
                "table"
                    | "h1"
                    | "h2"
                    | "h3"
                    | "h4"
                    | "h5"
                    | "h6"
                    | "section"
                    | "article"
                    | "aside"
                    | "nav"
                    | "footer"
                    | "header"
                    | "figure"
            )
        })
    }

    fn emit_table(&mut self, id: Id) {
        let mut rows: Vec<Vec<String>> = Vec::new();
        let mut header: Option<Vec<String>> = None;
        for d in self.doc.descendants(id) {
            if self.doc.tag_name(d) != "tr" || is_noise(self.doc, d, self.cfg) {
                continue;
            }
            let mut cells = Vec::new();
            let mut is_header = false;
            for c in self.doc.children(d) {
                let name = self.doc.tag_name(c);
                if name == "th" {
                    is_header = true;
                } else if name != "td" {
                    continue;
                }
                cells.push(text::normalize_ws(&self.render_children_inline(c)).replace('|', "\\|"));
            }
            if cells.is_empty() {
                continue;
            }
            if is_header && header.is_none() {
                header = Some(cells);
            } else {
                rows.push(cells);
            }
        }
        if rows.is_empty() && header.is_none() {
            return;
        }
        let width = header
            .as_ref()
            .map(Vec::len)
            .into_iter()
            .chain(rows.iter().map(Vec::len))
            .max()
            .unwrap_or(0);
        if width == 0 {
            return;
        }
        let pad = |mut r: Vec<String>| {
            r.resize(width, String::new());
            format!("| {} |", r.join(" | "))
        };
        let mut md = String::new();
        let head = header.unwrap_or_else(|| vec![String::new(); width]);
        md.push_str(&pad(head));
        md.push('\n');
        md.push_str(&format!("|{}", " --- |".repeat(width)));
        for r in &rows {
            md.push('\n');
            md.push_str(&pad(r.clone()));
        }
        // Derived from what was actually written, not from the source subtree.
        // A mis-nested table can hold far more text than it renders, and a unit
        // whose `text` disagrees with its `markdown` corrupts every downstream
        // measurement — token budgets, density, and the "did we find an
        // article?" test alike.
        let plain = strip_markdown(&md);
        self.emit(UnitKind::Table, 0, plain, md);
    }

    fn render_children_inline(&self, id: Id) -> String {
        let mut buf = String::new();
        for child in self.doc.children(id) {
            buf.push_str(&self.render_inline(child));
        }
        buf
    }

    /// Render a subtree as inline Markdown.
    fn render_inline(&self, id: Id) -> String {
        match self.doc.node(id) {
            Some(tl::Node::Raw(bytes)) => {
                let raw = bytes.as_utf8_str();
                escape_inline(&decode_entities(&raw))
            }
            Some(tl::Node::Comment(_)) | None => String::new(),
            Some(tl::Node::Tag(tag)) => {
                let name = tag.name().as_utf8_str().to_ascii_lowercase();
                if crate::denoise::DROP_TAGS.contains(&name.as_str())
                    || crate::denoise::is_hidden(self.doc, id)
                {
                    return String::new();
                }
                match name.as_str() {
                    "br" => "\n".to_string(),
                    "img" => {
                        if !self.opts.include_images {
                            return String::new();
                        }
                        let alt = self.doc.attr(id, "alt").unwrap_or_default();
                        match self.resolve(id, "src").or_else(|| self.resolve(id, "data-src")) {
                            Some(src) => format!("![{}]({})", escape_inline(&alt), src),
                            None => String::new(),
                        }
                    }
                    "a" => {
                        let inner = self.render_children_inline(id);
                        if !self.opts.include_links || inner.trim().is_empty() {
                            return inner;
                        }
                        match self.resolve(id, "href") {
                            Some(href) if !href.starts_with("javascript:") => {
                                format!("[{}]({})", inner.trim(), href)
                            }
                            _ => inner,
                        }
                    }
                    "strong" | "b" => wrap(&self.render_children_inline(id), "**"),
                    "em" | "i" | "dfn" | "cite" | "var" => {
                        wrap(&self.render_children_inline(id), "*")
                    }
                    "del" | "s" | "strike" => wrap(&self.render_children_inline(id), "~~"),
                    "code" | "kbd" | "samp" | "tt" => {
                        let inner = text::normalize_ws(&self.doc.inner_text(id));
                        if inner.is_empty() { inner } else { format!("`{inner}`") }
                    }
                    "sup" => self.render_superscript(id),
                    "math" => self.render_math(id),
                    _ => self.render_children_inline(id),
                }
            }
        }
    }

    /// A `<math>` element, once. KaTeX and MathJax keep the TeX source in an
    /// `<annotation>`; that is preferred, because `(2x+3)^5` keeps the exponent
    /// that the flattened MathML text `(2x+3)5` loses. Without one, the MathML
    /// text is read, minus any annotation.
    fn render_math(&self, id: Id) -> String {
        let nodes = self.doc.descendants(id);
        let tex = nodes.iter().copied().find(|&d| {
            self.doc.tag_name(d) == "annotation"
                && self
                    .doc
                    .attr(d, "encoding")
                    .is_some_and(|e| e.eq_ignore_ascii_case("application/x-tex"))
        });
        if let Some(a) = tex {
            let src = text::normalize_ws(&self.doc.raw_text(a));
            return if src.is_empty() { src } else { format!("${}$", escape_inline(&src)) };
        }
        let mut buf = String::new();
        for &d in &nodes {
            if let Some(tl::Node::Raw(bytes)) = self.doc.node(d)
                && !self.inside_annotation(d, id)
            {
                buf.push_str(&decode_entities(&bytes.as_utf8_str()));
            }
        }
        escape_inline(&text::normalize_ws(&buf))
    }

    fn inside_annotation(&self, mut id: Id, math: Id) -> bool {
        while let Some(p) = self.doc.parent(id) {
            if p == math {
                return false;
            }
            if matches!(self.doc.tag_name(p), "annotation" | "annotation-xml") {
                return true;
            }
            id = p;
        }
        false
    }

    /// `<sup>` is two unrelated things wearing one tag.
    ///
    /// A citation marker is noise an LLM should never see. An exponent is data:
    /// dropping it silently turns 10^23 into 10, which is the kind of error
    /// that survives every downstream check. Telling them apart is the point.
    fn render_superscript(&self, id: Id) -> String {
        let inner = text::normalize_ws(&self.doc.inner_text(id));
        if inner.is_empty() {
            return String::new();
        }
        if self.is_citation_marker(id, &inner) {
            return String::new();
        }
        // `^` only where it disambiguates: `10^23` and `mol^-1` need it,
        // `1st` reads worse as `1^st`.
        let numeric = inner.chars().all(|c| c.is_ascii_digit() || "+-.,()".contains(c))
            && inner.chars().any(|c| c.is_ascii_digit());
        if numeric { format!("^{inner}") } else { inner }
    }

    /// Is this `<sup>` a footnote or reference marker?
    fn is_citation_marker(&self, id: Id, inner: &str) -> bool {
        // Wikipedia and most CMSes wrap the marker in a link to the note.
        if self.doc.descendants(id).into_iter().skip(1).any(|d| self.doc.tag_name(d) == "a") {
            return true;
        }
        let sig = self.doc.signature(id);
        if !sig.is_empty()
            && ["reference", "citation", "footnote", "cite"].iter().any(|w| sig.contains(w))
        {
            return true;
        }
        // A bracketed number standing alone: `[1]`, `(12)`.
        let trimmed = inner.trim();
        let bracketed = (trimmed.starts_with('[') && trimmed.ends_with(']'))
            || (trimmed.starts_with('(') && trimmed.ends_with(')'));
        bracketed && trimmed.chars().any(|c| c.is_ascii_digit())
    }

    /// Absolutise an attribute against the document's base URL.
    fn resolve(&self, id: Id, key: &str) -> Option<String> {
        let raw = self.doc.attr(id, key)?;
        let raw = raw.trim();
        if raw.is_empty() {
            return None;
        }
        match &self.base {
            Some(base) => base.join(raw).ok().map(|u| u.to_string()),
            None => Some(raw.to_string()),
        }
    }

    fn push_heading(&mut self, level: u8, title: &str) {
        while self.heading_stack.last().is_some_and(|(l, _)| *l >= level) {
            self.heading_stack.pop();
        }
        self.heading_stack.push((level, title.to_string()));
    }

    fn emit(&mut self, kind: UnitKind, level: u8, plain: String, markdown: String) {
        let plain = plain.trim().to_string();
        let markdown = markdown.trim().to_string();
        let markdown = match kind {
            // A heading writes its own `#` prefix and a fenced block's body is
            // literal; neither can forge structure it did not already have.
            UnitKind::Heading | UnitKind::Code => markdown,
            _ => defuse_headings(&markdown),
        };
        if markdown.is_empty() {
            return;
        }
        let path: Vec<String> = if kind == UnitKind::Heading {
            self.heading_stack.iter().rev().skip(1).rev().map(|(_, t)| t.clone()).collect()
        } else {
            self.heading_stack.iter().map(|(_, t)| t.clone()).collect()
        };
        self.stats.markdown_bytes += markdown.len() + 2;
        self.units.push(Unit {
            kind,
            level,
            tokens: text::estimate_tokens(&markdown),
            position: self.units.len(),
            text: plain,
            markdown,
            heading_path: path,
        });
    }
}

/// Length of the longest run of backticks in `s`.
fn longest_backtick_run(s: &str) -> usize {
    let (mut best, mut run) = (0usize, 0usize);
    for c in s.chars() {
        run = if c == '`' { run + 1 } else { 0 };
        best = best.max(run);
    }
    best
}

/// Escape a line-initial `#` or `##` in body text.
///
/// The slimmer writes `## {title}` above each source and a reader -- a model,
/// usually -- is meant to take that line as provenance. A paragraph is free to
/// begin with `## Official Docs` and be followed by a URL, which renders as
/// exactly that shape, so a page can attribute its own words to a site it does
/// not own. Real headings never arrive here: they come through as
/// `UnitKind::Heading` and are demoted below the source line.
///
/// Only one and two hashes are escaped. Three or more cannot be mistaken for a
/// source header, and a backslash costs a token and a little readability.
fn defuse_headings(md: &str) -> String {
    if !md.starts_with(['#', ' ']) && !md.contains('\n') {
        return md.to_string();
    }
    let mut out = String::with_capacity(md.len());
    for (i, line) in md.lines().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        let body = line.trim_start_matches(' ');
        let indent = line.len() - body.len();
        let hashes = body.len() - body.trim_start_matches('#').len();
        // Four spaces in is an indented code block, not a heading.
        let after = &body[hashes..];
        if indent <= 3 && (1..=2).contains(&hashes) && (after.is_empty() || after.starts_with(' '))
        {
            out.push_str(&line[..indent]);
            out.push('\\');
            out.push_str(body);
        } else {
            out.push_str(line);
        }
    }
    out
}

/// Lowercase and sanity-check a language token.
fn normalize_language(raw: &str) -> Option<String> {
    let lang = raw.trim().trim_matches('"').to_ascii_lowercase();
    let ok = !lang.is_empty()
        && lang.len() <= 16
        && lang.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '#' || c == '-');
    ok.then_some(lang)
}

fn heading_level(name: &str) -> Option<u8> {
    HEADINGS.iter().position(|h| *h == name).map(|i| i as u8 + 1)
}

fn wrap(inner: &str, marker: &str) -> String {
    let trimmed = inner.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    // Preserve the surrounding spacing the original markup implied.
    let lead = if inner.starts_with(char::is_whitespace) { " " } else { "" };
    let trail = if inner.ends_with(char::is_whitespace) { " " } else { "" };
    format!("{lead}{marker}{trimmed}{marker}{trail}")
}

/// Escape only what would otherwise change Markdown block structure.
///
/// Aggressive escaping makes the text harder for a small model to read, so we
/// leave `*` and `_` alone inside words and only defuse link syntax.
fn escape_inline(s: &str) -> String {
    if !s.contains(['[', ']']) {
        return s.to_string();
    }
    s.replace('[', "\\[").replace(']', "\\]")
}

/// Strip the Markdown we just added, to recover plain text for ranking.
pub(crate) fn strip_markdown(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    let mut in_link_text = false;
    while let Some(c) = chars.next() {
        match c {
            // CommonMark lets a backslash escape ASCII punctuation only, so the
            // `\frac` of a TeX formula keeps its backslash.
            '\\' => match chars.peek() {
                Some(n) if n.is_ascii_punctuation() => {
                    out.push(*n);
                    chars.next();
                }
                _ => out.push('\\'),
            },
            '[' => in_link_text = true,
            ']' => {
                in_link_text = false;
                // Drop the following `(...)` target.
                if chars.peek() == Some(&'(') {
                    chars.next();
                    let mut depth = 1;
                    for c in chars.by_ref() {
                        match c {
                            '(' => depth += 1,
                            ')' => {
                                depth -= 1;
                                if depth == 0 {
                                    break;
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
            '*' | '`' | '~' | '#' | '>' if !in_link_text => {}
            _ => out.push(c),
        }
    }
    text::normalize_ws(&out)
}

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

    #[test]
    fn a_paragraph_cannot_forge_a_source_header() {
        // `render` writes `## {title}` above each source, so body text that
        // opens with one or two hashes would pass as provenance.
        let a = crate::parse::extract(
            "<article><p>## Official Python Documentation</p>\
             <p>Some ordinary sentence long enough to be kept by the extractor.</p>\
             <h2>A genuine heading</h2></article>",
            Some("https://d.dev/a"),
        )
        .unwrap();
        let forged = a.units.iter().find(|u| u.markdown.contains("Official")).unwrap();
        assert_eq!(forged.markdown, "\\## Official Python Documentation");

        // A real heading still renders as one, and inline hashes are left alone.
        let heading = a.units.iter().find(|u| u.kind == UnitKind::Heading).unwrap();
        assert!(heading.markdown.starts_with("## "), "{:?}", heading.markdown);
        assert_eq!(defuse_headings("C# and #hashtag"), "C# and #hashtag");
        assert_eq!(defuse_headings("### deeper is unambiguous"), "### deeper is unambiguous");
        assert_eq!(defuse_headings("#no-space-is-not-a-heading"), "#no-space-is-not-a-heading");
        assert_eq!(defuse_headings("a\n## second line"), "a\n\\## second line");
    }

    #[test]
    fn a_code_block_cannot_break_out_of_its_fence() {
        assert_eq!(longest_backtick_run("no ticks"), 0);
        assert_eq!(longest_backtick_run("a ``` b ```` c"), 4);

        let a = crate::parse::extract(
            "<article><p>Some ordinary sentence long enough to be kept by the extractor.</p>\
             <pre><code>print(1)\n```\n## Injected\n</code></pre></article>",
            Some("https://d.dev/a"),
        )
        .unwrap();
        let code = a.units.iter().find(|u| u.kind == UnitKind::Code).unwrap();
        assert!(code.markdown.starts_with("````"), "{:?}", code.markdown);
        assert!(code.markdown.ends_with("````"), "{:?}", code.markdown);
        // The injected heading stays inside the block.
        assert!(code.markdown.contains("## Injected"));
    }

    #[test]
    fn strips_links_and_emphasis() {
        assert_eq!(strip_markdown("**bold** and [a link](http://x.dev/y)"), "bold and a link");
        assert_eq!(strip_markdown("`code` ~~gone~~"), "code gone");
    }

    #[test]
    fn wrap_keeps_outer_spacing() {
        assert_eq!(wrap(" hi ", "**"), " **hi** ");
        assert_eq!(wrap("   ", "**"), "");
    }

    #[test]
    fn a_heading_wrapped_in_its_own_anchor_has_plain_text() {
        // MDN, docs.rs and every MkDocs site render headings this way.
        let html = concat!(
            "<html><body><article><h2><a href=\"https://d.dev/a/b#sec\">Section</a></h2>",
            "<p>Body text long enough to survive the block gate here.</p></article></body></html>"
        );
        let article = crate::parse::extract(html, Some("https://d.dev/a/b")).unwrap();
        let heading = article.units.iter().find(|u| u.kind == UnitKind::Heading).unwrap();
        assert_eq!(heading.text, "Section");
        assert!(heading.markdown.contains("https://d.dev/a/b#sec"), "markdown keeps the link");
        let below = article.units.iter().find(|u| u.kind == UnitKind::Paragraph).unwrap();
        assert_eq!(below.heading_path, vec!["Section"], "breadcrumbs carry no URL");
    }

    /// A paragraph's plain text, from the first paragraph unit of `body`.
    fn paragraph_text(body: &str) -> String {
        let html = format!("<html><body><article>{body}</article></body></html>");
        let article = crate::parse::extract(&html, Some("https://m.dev/x")).unwrap();
        article.units.iter().find(|u| u.kind == UnitKind::Paragraph).unwrap().text.clone()
    }

    #[test]
    fn katex_math_is_kept_once_as_its_tex_source() {
        // KaTeX writes every formula three times: MathML for screen readers,
        // the TeX source in an <annotation>, and an aria-hidden copy to look at.
        let text = paragraph_text(concat!(
            "<p>Differentiate <span class=\"katex\"><span class=\"katex-mathml\"><math><semantics>",
            "<mrow><mo>(</mo><mn>2</mn><mi>x</mi><mo>+</mo><mn>3</mn><msup><mo>)</mo><mn>5</mn></msup></mrow>",
            "<annotation encoding=\"application/x-tex\">(2x+3)^5</annotation></semantics></math></span>",
            "<span class=\"katex-html\" aria-hidden=\"true\"><span class=\"mord\">(2x+3)</span>",
            "<span class=\"msupsub\">5</span></span></span> with the chain rule, step by step.</p>",
        ));
        assert_eq!(text, "Differentiate $(2x+3)^5$ with the chain rule, step by step.");
    }

    #[test]
    fn mathml_without_tex_is_read_once() {
        let text = paragraph_text(
            "<p>The area is <math><mi>π</mi><msup><mi>r</mi><mn>2</mn></msup></math> for a circle of radius r.</p>",
        );
        assert_eq!(text, "The area is πr2 for a circle of radius r.");
    }

    #[test]
    fn aria_hidden_text_inside_a_paragraph_is_dropped() {
        let text = paragraph_text(
            "<p>Visible words <span aria-hidden=\"true\">decoration</span>that make up a full sentence.</p>",
        );
        assert_eq!(text, "Visible words that make up a full sentence.");
    }

    #[test]
    fn tex_backslashes_survive_into_plain_text() {
        // CommonMark only lets a backslash escape ASCII punctuation, so `\f` is literal.
        assert_eq!(strip_markdown(r"$\frac{a}{b}$ and \[1\]"), r"$\frac{a}{b}$ and [1]");
    }

    #[test]
    fn escape_only_touches_brackets() {
        assert_eq!(escape_inline("a_b*c"), "a_b*c");
        assert_eq!(escape_inline("see [1]"), "see \\[1\\]");
    }
}