mant-core 0.4.0

Structured manual and Markdown document engine used by ManT
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
//! Composes local manuals and cached tldr content into one versioned query.

use std::{
    error::Error,
    ffi::{OsStr, OsString},
    fmt, fs,
    io::Read,
    path::{Path, PathBuf},
};

use mant_ast::{MantDocument, QueryBundle, QueryInput, QueryRequest, QuerySchema, TldrDocument};

use crate::{
    CommandRunner, ManualRequest, SystemCommandRunner, locate_manual_source, parse_groff_html,
    parse_manual_source, parse_markdown, read_cached_tldr_page, source::push_section_filter,
};

/// Upper bound on a single Markdown source, shared by every input path.
///
/// File and stdin readers both enforce this so an unbounded source (a pipe, a
/// character device such as `/dev/zero`, or a pathologically large file) cannot
/// exhaust memory. A file's reported length is not trusted: some sources report
/// zero yet stream without end, so readers cap the byte count directly.
pub const MAX_MARKDOWN_BYTES: u64 = 16 * 1024 * 1024;

/// A query cannot produce either authoritative manual content or a quick reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum QueryError {
    EmptyTopic,
    InvalidSection,
    EmptyMarkdownPath,
    Markdown { path: String, detail: String },
    EmptyMarkdown { label: String },
    Manual { topic: String, detail: String },
    NoReadableContent { topic: String },
}

/// Host execution policy kept outside the serialized request contract.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct QueryPolicy {
    /// Request direct libmandoc output for parser diagnostics.
    ///
    /// Libmandoc is the default backend. This diagnostic policy additionally
    /// rejects a tldr-only response when direct parsing cannot provide a
    /// readable manual.
    pub force_libmandoc: bool,
    /// Use `man -Thtml` + groff HTML parser instead of libmandoc.
    /// This code path has not been comprehensively tested.
    pub force_groff: bool,
}

impl fmt::Display for QueryError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyTopic => formatter.write_str("manual topic must not be empty"),
            Self::InvalidSection => formatter.write_str("manual section must not be empty"),
            Self::EmptyMarkdownPath => formatter.write_str("Markdown path must not be empty"),
            Self::Markdown { path, detail } => {
                write!(
                    formatter,
                    "could not load Markdown document '{path}': {detail}"
                )
            }
            Self::EmptyMarkdown { label } => {
                write!(
                    formatter,
                    "Markdown document '{label}' has no readable content"
                )
            }
            Self::Manual { detail, .. } => formatter.write_str(detail),
            Self::NoReadableContent { topic } => {
                write!(
                    formatter,
                    "no readable manual content was found for '{topic}'"
                )
            }
        }
    }
}

impl Error for QueryError {}

/// Query the local man database and optional offline tldr caches.
///
/// # Errors
///
/// Returns [`QueryError`] for invalid input or when neither source can produce
/// readable content.
pub fn query(request: &QueryRequest) -> Result<QueryBundle, QueryError> {
    query_with(request, QueryPolicy::default(), &SystemQueryHost)
}

/// Query with an explicit host policy such as native-parser-only diagnostics.
///
/// # Errors
///
/// Returns [`QueryError`] under the same conditions as [`query`].
pub fn query_with_policy(
    request: &QueryRequest,
    policy: QueryPolicy,
) -> Result<QueryBundle, QueryError> {
    query_with(request, policy, &SystemQueryHost)
}

trait QueryHost {
    fn locate_manual(&self, request: &ManualRequest) -> Result<PathBuf, String>;
    fn parse_manual(&self, path: &Path) -> Result<MantDocument, String>;
    fn render_groff(
        &self,
        request: &ManualRequest,
        source_path: Option<&Path>,
    ) -> Result<MantDocument, String>;
    fn read_tldr(&self, topic: &str) -> Result<Option<TldrDocument>, String>;
    fn read_markdown(&self, path: &Path) -> Result<String, String>;
}

struct SystemQueryHost;

impl QueryHost for SystemQueryHost {
    fn locate_manual(&self, request: &ManualRequest) -> Result<PathBuf, String> {
        locate_manual_source(request).map_err(|error| error.to_string())
    }

    fn parse_manual(&self, path: &Path) -> Result<MantDocument, String> {
        parse_manual_source(path).map_err(|error| error.to_string())
    }

    fn render_groff(
        &self,
        request: &ManualRequest,
        source_path: Option<&Path>,
    ) -> Result<MantDocument, String> {
        render_groff_document_with(request, source_path, &SystemCommandRunner)
    }

    fn read_tldr(&self, topic: &str) -> Result<Option<TldrDocument>, String> {
        read_cached_tldr_page(topic).map_err(|error| error.to_string())
    }

    fn read_markdown(&self, path: &Path) -> Result<String, String> {
        let file = fs::File::open(path).map_err(|error| error.to_string())?;
        read_capped_utf8(file, MAX_MARKDOWN_BYTES)
    }
}

/// Read at most `limit` bytes of UTF-8, rejecting anything larger.
///
/// The reader is bounded directly instead of trusting a reported length: a pipe
/// or character device such as `/dev/zero` reports no size yet streams without
/// end, so only capping the byte count keeps the read finite.
fn read_capped_utf8(reader: impl Read, limit: u64) -> Result<String, String> {
    let mut bytes = Vec::new();
    reader
        .take(limit + 1)
        .read_to_end(&mut bytes)
        .map_err(|error| error.to_string())?;
    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > limit {
        return Err(format!("Markdown document exceeds the {limit}-byte limit"));
    }
    String::from_utf8(bytes).map_err(|_| "Markdown document must be UTF-8".to_owned())
}

fn query_with(
    request: &QueryRequest,
    policy: QueryPolicy,
    host: &dyn QueryHost,
) -> Result<QueryBundle, QueryError> {
    match &request.input {
        QueryInput::Manual { topic, section } => {
            query_manual(topic, section.as_deref(), policy, host)
        }
        QueryInput::MarkdownFile { path } => query_markdown_file(path, policy, host),
    }
}

fn query_markdown_file(
    requested_path: &str,
    policy: QueryPolicy,
    host: &dyn QueryHost,
) -> Result<QueryBundle, QueryError> {
    let path = requested_path.trim();
    if path.is_empty() {
        return Err(QueryError::EmptyMarkdownPath);
    }
    if policy.force_libmandoc || policy.force_groff {
        return Err(QueryError::Markdown {
            path: path.to_owned(),
            detail: "manual renderer policies do not apply to Markdown input".to_owned(),
        });
    }
    let source = host
        .read_markdown(Path::new(path))
        .map_err(|detail| QueryError::Markdown {
            path: path.to_owned(),
            detail,
        })?;
    query_markdown_text(&source, Some(path.to_owned()))
}

/// Parse in-memory Markdown for the direct `mant -` command.
///
/// This helper intentionally sits outside [`QueryRequest`]: public protocol
/// requests reference local files and never embed arbitrary document content.
///
/// # Errors
///
/// Returns [`QueryError::EmptyMarkdown`] when parsing yields no visible blocks
/// or sections.
pub fn query_markdown_text(
    source: &str,
    source_path: Option<String>,
) -> Result<QueryBundle, QueryError> {
    let label = source_path.as_deref().map_or_else(
        || "stdin".to_owned(),
        |path| {
            Path::new(path)
                .file_name()
                .and_then(OsStr::to_str)
                .unwrap_or(path)
                .to_owned()
        },
    );
    let error_path = source_path.clone().unwrap_or_else(|| "stdin".to_owned());
    let parsed = parse_markdown(source, source_path).map_err(|error| QueryError::Markdown {
        path: error_path,
        detail: error.to_string(),
    })?;
    let document_is_empty =
        parsed.document.blocks.is_empty() && parsed.document.sections.is_empty();
    if document_is_empty && parsed.tldr.is_none() {
        return Err(QueryError::EmptyMarkdown {
            label: label.clone(),
        });
    }
    Ok(QueryBundle {
        schema: QuerySchema::V3,
        label,
        document: (!document_is_empty).then_some(parsed.document),
        tldr: parsed.tldr,
    })
}

fn query_manual(
    topic: &str,
    requested_section: Option<&str>,
    policy: QueryPolicy,
    host: &dyn QueryHost,
) -> Result<QueryBundle, QueryError> {
    let topic = topic.trim();
    if topic.is_empty() {
        return Err(QueryError::EmptyTopic);
    }
    let section = requested_section.map(str::trim);
    if section.is_some_and(str::is_empty) {
        return Err(QueryError::InvalidSection);
    }
    let section = section.map(ToOwned::to_owned);
    let manual_request = ManualRequest::new(topic, section.clone());

    // A malformed or unreadable community cache must never hide a valid man
    // page. It is an optional augmentation and is never updated during query.
    let tldr = host.read_tldr(topic).ok().flatten();
    let mut manual = load_manual(&manual_request, policy, host);

    // A renderer that cannot recover the section from the page itself (notably
    // the groff HTML fallback, whose metadata is empty) leaves meta.section
    // unset. Fall back to the requested section so labels stay `topic(N)`.
    if let (Ok(Some(document)), Some(section)) = (&mut manual, section.as_deref())
        && document.meta.section.is_none()
    {
        document.meta.section = Some(section.to_owned());
    }

    // Force-libmandoc mode is an explicit parser diagnostic request.
    // A tldr page may augment a successful manual, but must not turn a
    // failed native parse into an apparently successful tldr-only response.
    if policy.force_libmandoc || policy.force_groff {
        return match manual {
            Ok(Some(manual)) => Ok(QueryBundle {
                schema: QuerySchema::V3,
                label: topic.to_owned(),
                document: Some(manual),
                tldr,
            }),
            Ok(None) => Err(QueryError::NoReadableContent {
                topic: topic.to_owned(),
            }),
            Err(detail) => Err(QueryError::Manual {
                topic: topic.to_owned(),
                detail,
            }),
        };
    }

    match manual {
        Ok(Some(manual)) => Ok(QueryBundle {
            schema: QuerySchema::V3,
            label: topic.to_owned(),
            document: Some(manual),
            tldr,
        }),
        Ok(None) | Err(_) if tldr.is_some() => Ok(QueryBundle {
            schema: QuerySchema::V3,
            label: topic.to_owned(),
            document: None,
            tldr,
        }),
        Ok(None) => Err(QueryError::NoReadableContent {
            topic: topic.to_owned(),
        }),
        Err(detail) => Err(QueryError::Manual {
            topic: topic.to_owned(),
            detail,
        }),
    }
}

fn load_manual(
    request: &ManualRequest,
    policy: QueryPolicy,
    host: &dyn QueryHost,
) -> Result<Option<MantDocument>, String> {
    // The groff compatibility path needs the located source only as document
    // provenance. Do not parse it with libmandoc first: this switch is used to
    // isolate renderer differences and must not pay for or depend on native
    // lowering.
    if policy.force_groff {
        let source_path = host.locate_manual(request).ok();
        return match host.render_groff(request, source_path.as_deref()) {
            Ok(fallback) if !fallback.sections.is_empty() => Ok(Some(fallback)),
            Ok(_) => Ok(None),
            Err(error) => Err(error),
        };
    }

    let located = host.locate_manual(request);
    let (source_path, direct) = match located {
        Ok(path) => {
            let direct = host.parse_manual(&path);
            (Some(path), direct)
        }
        Err(error) => (None, Err(error)),
    };

    // Default (and --force-libmandoc): libmandoc only.
    let document = direct.map_err(|error| {
        format!(
            "could not load manual '{}': source/libmandoc: {error}",
            request.topic
        )
    })?;
    if document.sections.is_empty() {
        let path = source_path.as_deref().map_or_else(
            || "<unknown source>".to_owned(),
            |path| path.display().to_string(),
        );
        let diagnostics = document
            .diagnostics
            .iter()
            .map(|diagnostic| {
                let location = diagnostic.source.map_or_else(String::new, |source| {
                    format!(" at {}:{}", source.line, source.column)
                });
                format!("{:?}{location}: {}", diagnostic.level, diagnostic.message)
            })
            .collect::<Vec<_>>()
            .join("; ");
        let detail = if diagnostics.is_empty() {
            String::new()
        } else {
            format!("; diagnostics: {diagnostics}")
        };
        return Err(format!(
            "could not load manual '{}': libmandoc parsed {path} but produced no readable sections{detail}",
            request.topic,
        ));
    }
    Ok(Some(document))
}

fn render_groff_document_with(
    request: &ManualRequest,
    source_path: Option<&Path>,
    runner: &impl CommandRunner,
) -> Result<MantDocument, String> {
    let mut arguments = vec![OsString::from("-Thtml")];
    if let Some(section) = request.section.as_deref() {
        // Label the section with portable `-S`. A bare section operand collides
        // with the `--` terminator below on man-db (the terminator is parsed as
        // the page name), while lowercase `-s` is unavailable in BSD man.
        push_section_filter(&mut arguments, section);
    }
    // Terminate option parsing so a topic beginning with '-' stays a
    // positional operand rather than an option to man.
    arguments.push(OsString::from("--"));
    arguments.push(OsString::from(&request.topic));
    let output = runner
        .run(OsStr::new("man"), &arguments)
        .map_err(|error| format!("cannot run 'man -Thtml': {error}"))?;
    if output.exit_code != 0 {
        let detail = first_nonempty_line(&output.stderr)
            .unwrap_or_else(|| format!("man -Thtml failed with code {}", output.exit_code));
        return Err(detail);
    }
    let html = String::from_utf8_lossy(&output.stdout);
    if html.trim().is_empty() {
        return Err(format!("man produced no HTML for '{}'", request.topic));
    }
    Ok(parse_groff_html(
        &html,
        source_path.map(|path| path.to_string_lossy().into_owned()),
    ))
}

fn first_nonempty_line(output: &[u8]) -> Option<String> {
    String::from_utf8_lossy(output)
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())
        .map(ToOwned::to_owned)
}

#[cfg(test)]
mod tests {
    use std::{
        ffi::{OsStr, OsString},
        io,
        path::{Path, PathBuf},
        sync::Mutex,
    };

    use mant_ast::{
        Diagnostic, DiagnosticLevel, DocumentMeta, DocumentSchema, DocumentSource, MantDocument,
        Producer, QueryInput, QueryRequest, QueryView, RequestSchema, Section, SourceFormat,
        TldrDocument, TldrOrigin,
    };

    use crate::{CommandOutput, CommandRunner, ManualRequest};

    use super::{
        MAX_MARKDOWN_BYTES, QueryError, QueryHost, QueryPolicy, query_markdown_text, query_with,
        read_capped_utf8, render_groff_document_with,
    };

    #[derive(Clone)]
    struct StubHost {
        locate: Result<PathBuf, String>,
        direct: Result<MantDocument, String>,
        fallback: Result<MantDocument, String>,
        tldr: Result<Option<TldrDocument>, String>,
        markdown: Result<String, String>,
        calls: std::sync::Arc<Mutex<Vec<&'static str>>>,
    }

    impl QueryHost for StubHost {
        fn locate_manual(&self, _request: &ManualRequest) -> Result<PathBuf, String> {
            self.calls.lock().expect("calls lock").push("locate");
            self.locate.clone()
        }

        fn parse_manual(&self, _path: &Path) -> Result<MantDocument, String> {
            self.calls.lock().expect("calls lock").push("parse");
            self.direct.clone()
        }

        fn render_groff(
            &self,
            _request: &ManualRequest,
            _source_path: Option<&Path>,
        ) -> Result<MantDocument, String> {
            self.calls.lock().expect("calls lock").push("groff");
            self.fallback.clone()
        }

        fn read_tldr(&self, _topic: &str) -> Result<Option<TldrDocument>, String> {
            self.calls.lock().expect("calls lock").push("tldr");
            self.tldr.clone()
        }

        fn read_markdown(&self, _path: &Path) -> Result<String, String> {
            self.calls.lock().expect("calls lock").push("markdown");
            self.markdown.clone()
        }
    }

    fn document(format: SourceFormat, unsupported: bool, readable: bool) -> MantDocument {
        MantDocument {
            schema: DocumentSchema::V3,
            producer: Producer {
                name: "test".to_owned(),
                version: "1".to_owned(),
                engine: None,
            },
            source: DocumentSource {
                format,
                path: None,
                renderer: None,
            },
            meta: DocumentMeta::default(),
            diagnostics: unsupported
                .then_some(Diagnostic {
                    level: DiagnosticLevel::Unsupported,
                    code: None,
                    message: "unsupported request".to_owned(),
                    source: None,
                })
                .into_iter()
                .collect(),
            blocks: Vec::new(),
            sections: readable
                .then_some(Section {
                    id: "name-1".to_owned(),
                    title: "NAME".to_owned(),
                    spacing_before_lines: 0,
                    blocks: Vec::new(),
                    children: Vec::new(),
                    source: None,
                })
                .into_iter()
                .collect(),
        }
    }

    fn tldr() -> TldrDocument {
        TldrDocument {
            title: "tool".to_owned(),
            description: vec!["quick reference".to_owned()],
            more_information: None,
            examples: Vec::new(),
            platform: "common".to_owned(),
            language: "en".to_owned(),
            source_path: "/cache/pages/common/tool.md".to_owned(),
            origin: TldrOrigin::TldrPages,
        }
    }

    fn host(direct: Result<MantDocument, String>) -> StubHost {
        StubHost {
            locate: Ok(PathBuf::from("/man/tool.1")),
            direct,
            fallback: Err("fallback unavailable".to_owned()),
            tldr: Ok(None),
            markdown: Err("Markdown unavailable".to_owned()),
            calls: std::sync::Arc::default(),
        }
    }

    fn request() -> QueryRequest {
        QueryRequest {
            schema: RequestSchema::V3,
            input: QueryInput::Manual {
                topic: " tool ".to_owned(),
                section: None,
            },
            view: QueryView::Full {},
        }
    }

    #[test]
    fn ordinary_direct_document_does_not_start_groff() {
        let host = host(Ok(document(SourceFormat::Man, false, true)));
        let result = query_with(&request(), QueryPolicy::default(), &host).expect("query");

        assert_eq!(result.label, "tool");
        assert_eq!(
            result.document.expect("manual").source.format,
            SourceFormat::Man
        );
        assert_eq!(
            *host.calls.lock().expect("calls lock"),
            ["tldr", "locate", "parse"]
        );
    }

    #[test]
    fn requested_section_backfills_metadata_a_renderer_left_empty() {
        // The groff fallback yields DocumentMeta::default(), so meta.section is
        // None even though the caller asked for a specific section.
        let host = host(Ok(document(SourceFormat::GroffHtml, false, true)));
        let request = QueryRequest {
            schema: RequestSchema::V3,
            input: QueryInput::Manual {
                topic: "tool".to_owned(),
                section: Some("3".to_owned()),
            },
            view: QueryView::Full {},
        };

        let result = query_with(&request, QueryPolicy::default(), &host).expect("query");
        assert_eq!(
            result.document.expect("manual").meta.section.as_deref(),
            Some("3"),
            "requested section must label output when the renderer omits it"
        );
    }

    /// With the old groff-fallback architecture this test verified that an
    /// unsupported diagnostic did not trigger an unnecessary groff call.
    /// Now libmandoc is the sole default backend so groff is never called.
    #[test]
    fn complete_direct_document_survives_an_unsupported_finding() {
        let mut host = host(Ok(document(SourceFormat::Man, true, true)));
        host.fallback = Ok(document(SourceFormat::GroffHtml, false, true));
        let result = query_with(&request(), QueryPolicy::default(), &host).expect("query");

        assert_eq!(
            result.document.expect("manual").source.format,
            SourceFormat::Man
        );
        assert_eq!(
            *host.calls.lock().expect("calls lock"),
            ["tldr", "locate", "parse"]
        );
    }

    #[test]
    fn forced_libmandoc_never_starts_groff() {
        let mut host = host(Ok(document(SourceFormat::Man, true, true)));
        host.fallback = Ok(document(SourceFormat::GroffHtml, false, true));
        let result = query_with(
            &request(),
            QueryPolicy {
                force_libmandoc: true,
                force_groff: false,
            },
            &host,
        )
        .expect("forced native query");

        assert_eq!(
            result.document.expect("manual").source.format,
            SourceFormat::Man
        );
        assert_eq!(
            *host.calls.lock().expect("calls lock"),
            ["tldr", "locate", "parse"]
        );
    }

    #[test]
    fn forced_groff_never_starts_libmandoc() {
        let mut host = host(Err("libmandoc must not run".to_owned()));
        host.fallback = Ok(document(SourceFormat::GroffHtml, false, true));
        let result = query_with(
            &request(),
            QueryPolicy {
                force_libmandoc: false,
                force_groff: true,
            },
            &host,
        )
        .expect("forced groff query");

        assert_eq!(
            result.document.expect("manual").source.format,
            SourceFormat::GroffHtml
        );
        assert_eq!(
            *host.calls.lock().expect("calls lock"),
            ["tldr", "locate", "groff"]
        );
    }

    #[test]
    fn forced_libmandoc_failure_is_not_hidden_by_tldr() {
        let mut host = host(Ok(document(SourceFormat::Man, true, false)));
        host.tldr = Ok(Some(tldr()));
        host.fallback = Ok(document(SourceFormat::GroffHtml, false, true));

        let error = query_with(
            &request(),
            QueryPolicy {
                force_libmandoc: true,
                force_groff: false,
            },
            &host,
        )
        .expect_err("an optional tldr page must not hide native parser failure");

        let QueryError::Manual { detail, .. } = error else {
            panic!("expected the native parser diagnostic");
        };
        assert!(detail.contains("/man/tool.1"));
        assert!(detail.contains("Unsupported: unsupported request"));
        assert_eq!(
            *host.calls.lock().expect("calls lock"),
            ["tldr", "locate", "parse"]
        );
    }

    /// With the old groff-fallback architecture this test verified that a
    /// truncated native document fell back to groff. Now libmandoc is the
    /// default and an empty-sections document is an error.
    #[test]
    fn truncated_unsupported_document_is_an_error_by_default() {
        let host = host(Ok(document(SourceFormat::Man, true, false)));

        let QueryError::Manual { detail, .. } =
            query_with(&request(), QueryPolicy::default(), &host)
                .expect_err("empty-section document must error by default")
        else {
            panic!("expected Manual error");
        };
        assert!(detail.contains("produced no readable sections"));
    }

    #[test]
    fn failed_groff_retains_readable_best_effort_document() {
        let host = host(Ok(document(SourceFormat::Mdoc, true, true)));
        let result = query_with(&request(), QueryPolicy::default(), &host).expect("query");
        assert_eq!(
            result.document.expect("manual").source.format,
            SourceFormat::Mdoc
        );
    }

    #[test]
    fn cached_tldr_survives_total_manual_failure() {
        let mut host = host(Err("libmandoc failed".to_owned()));
        host.locate = Err("source not found".to_owned());
        host.tldr = Ok(Some(tldr()));
        let result =
            query_with(&request(), QueryPolicy::default(), &host).expect("tldr-only query");

        assert!(result.document.is_none());
        assert_eq!(result.tldr.expect("tldr").title, "tool");
    }

    #[test]
    fn reports_both_manual_paths_when_no_content_exists() {
        let mut host = host(Err("libmandoc failed".to_owned()));
        host.locate = Err("source not found".to_owned());
        let error = query_with(&request(), QueryPolicy::default(), &host)
            .expect_err("empty query must fail");
        assert_eq!(
            error.to_string(),
            "could not load manual 'tool': source/libmandoc: source not found"
        );
    }

    #[test]
    fn validates_before_touching_host_state() {
        let host = host(Ok(document(SourceFormat::Man, false, true)));
        assert_eq!(
            query_with(
                &QueryRequest {
                    schema: RequestSchema::V3,
                    input: QueryInput::Manual {
                        topic: " ".to_owned(),
                        section: None,
                    },
                    view: QueryView::Full {},
                },
                QueryPolicy::default(),
                &host
            ),
            Err(QueryError::EmptyTopic)
        );
        assert!(host.calls.lock().expect("calls lock").is_empty());
    }

    #[test]
    fn markdown_files_bypass_manual_and_tldr_sources() {
        let mut host = host(Err("manual parser must not run".to_owned()));
        host.markdown = Ok("# Tool\n\n## Options\n\n- `--help`: Show help.\n".to_owned());
        let result = query_with(
            &QueryRequest {
                schema: RequestSchema::V3,
                input: QueryInput::MarkdownFile {
                    path: "docs/tool.md".to_owned(),
                },
                view: QueryView::Full {},
            },
            QueryPolicy::default(),
            &host,
        )
        .expect("Markdown query");

        assert_eq!(result.label, "tool.md");
        assert!(result.tldr.is_none());
        let document = result.document.expect("document");
        assert_eq!(document.source.format, SourceFormat::Markdown);
        assert_eq!(document.source.path.as_deref(), Some("docs/tool.md"));
        assert_eq!(
            *host.calls.lock().expect("calls lock"),
            ["markdown"],
            "Markdown must not consult man or tldr"
        );
    }

    #[test]
    fn in_memory_markdown_is_available_without_a_protocol_content_field() {
        let result = query_markdown_text("# Piped\n\nBody.\n", None).expect("stdin Markdown query");

        assert_eq!(result.label, "stdin");
        assert!(result.tldr.is_none());
        let document = result.document.expect("document");
        assert_eq!(document.meta.title.as_deref(), Some("Piped"));
        assert_eq!(document.source.path, None);
    }

    #[test]
    fn leading_tldr_directives_are_independent_from_the_markdown_document() {
        let source = "\
:::tldr
# demo

> Concise embedded help.

- Run the demo:

`demo {{path}}`
:::

# Demo

Document overview.

## Options

- `--help`: Show help.
";
        let result =
            query_markdown_text(source, Some("docs/demo.md".to_owned())).expect("Markdown query");

        let tldr = result.tldr.expect("embedded tldr");
        assert_eq!(tldr.title, "demo");
        assert_eq!(tldr.origin, TldrOrigin::Embedded);
        assert_eq!(tldr.source_path, "docs/demo.md");
        assert_eq!(tldr.examples[0].command, "demo {{path}}");

        let document = result.document.expect("document body");
        assert_eq!(document.meta.title.as_deref(), Some("Demo"));
        assert_eq!(document.sections[0].title, "Options");
        assert!(
            document
                .blocks
                .iter()
                .any(|block| matches!(block, mant_ast::Block::Paragraph { .. }))
        );
        assert!(
            document
                .diagnostics
                .iter()
                .all(|diagnostic| !diagnostic.message.contains(":::tldr"))
        );
    }

    #[test]
    fn malformed_leading_tldr_directives_report_the_source_path() {
        let error = query_markdown_text(
            ":::tldr\n# demo\n\n- Run:\n\n`demo`\n",
            Some("docs/broken.md".to_owned()),
        )
        .expect_err("unterminated directive");

        assert_eq!(
            error.to_string(),
            "could not load Markdown document 'docs/broken.md': top-level :::tldr directive is missing its closing ::: marker"
        );
    }

    struct StubRunner {
        output: CommandOutput,
        calls: Mutex<Vec<(OsString, Vec<OsString>)>>,
    }

    impl CommandRunner for StubRunner {
        fn run(&self, program: &OsStr, arguments: &[OsString]) -> io::Result<CommandOutput> {
            self.calls
                .lock()
                .expect("runner calls lock")
                .push((program.to_owned(), arguments.to_vec()));
            Ok(self.output.clone())
        }
    }

    #[test]
    fn groff_renderer_passes_section_and_preserves_source_identity() {
        let runner = StubRunner {
            output: CommandOutput {
                stdout: b"<body><h2>NAME</h2><p>tool</p></body>".to_vec(),
                stderr: Vec::new(),
                exit_code: 0,
            },
            calls: Mutex::new(Vec::new()),
        };
        let document = render_groff_document_with(
            &ManualRequest::new("tool", Some("1".to_owned())),
            Some(Path::new("/man/tool.1.gz")),
            &runner,
        )
        .expect("groff document");

        assert_eq!(document.source.path.as_deref(), Some("/man/tool.1.gz"));
        assert_eq!(
            *runner.calls.lock().expect("runner calls lock"),
            [(
                OsString::from("man"),
                ["-Thtml", "-S", "1", "--", "tool"]
                    .map(OsString::from)
                    .to_vec()
            )]
        );
    }

    #[test]
    fn capped_read_accepts_input_up_to_the_limit() {
        let source = "abcd";
        assert_eq!(
            read_capped_utf8(source.as_bytes(), source.len() as u64).expect("within limit"),
            source
        );
    }

    #[test]
    fn capped_read_rejects_input_past_the_limit_without_buffering_it_whole() {
        // An unbounded stream (modelled by io::repeat) must fail fast on the
        // limit rather than read forever, matching the /dev/zero guard.
        let error = read_capped_utf8(io::repeat(b'a'), 8).expect_err("over limit");
        assert!(error.contains("exceeds the 8-byte limit"), "{error}");
    }

    #[test]
    fn capped_read_rejects_non_utf8_input() {
        let error =
            read_capped_utf8(&[0xff, 0xfe][..], MAX_MARKDOWN_BYTES).expect_err("invalid UTF-8");
        assert!(error.contains("must be UTF-8"), "{error}");
    }
}