mant 0.11.0

Local-first TUI, structured CLI, and MCP server for manuals and Markdown
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
//! Read-only installation diagnostics for the native CLI.

#[cfg(feature = "roff")]
use std::path::Path;
use std::{collections::BTreeSet, fmt::Write as _, fs};

use anstyle::{AnsiColor, Style};
use mant_protocol::{DoctorCheck, DoctorCheckStatus, DoctorEnvironment, DoctorReport, Producer};
use mant_sources::{
    ConfiguredSourceInspection, DocumentPaths, RegisteredDocumentOrigin, SourceInstallationStatus,
    SourceTransport,
};

const OK_STYLE: Style = AnsiColor::Green.on_default().bold();
const INFO_STYLE: Style = AnsiColor::Cyan.on_default().bold();
const WARNING_STYLE: Style = AnsiColor::Yellow.on_default().bold();
const ERROR_STYLE: Style = AnsiColor::Red.on_default().bold();

struct DoctorBuilder {
    environment: DoctorEnvironment,
    checks: Vec<DoctorCheck>,
}

impl DoctorBuilder {
    fn new() -> Self {
        Self {
            environment: DoctorEnvironment {
                os: std::env::consts::OS.to_owned(),
                arch: std::env::consts::ARCH.to_owned(),
                data_root: None,
                config_path: None,
                documents_root: None,
                sources_root: None,
                manual_roots: Vec::new(),
                tldr_roots: Vec::new(),
            },
            checks: Vec::new(),
        }
    }

    fn push(
        &mut self,
        code: &str,
        status: DoctorCheckStatus,
        message: impl Into<String>,
    ) -> &mut DoctorCheck {
        self.checks.push(DoctorCheck {
            code: code.to_owned(),
            subject: None,
            status,
            message: message.into(),
            details: Vec::new(),
            remediation: None,
        });
        self.checks.last_mut().expect("doctor check was appended")
    }

    fn finish(self) -> DoctorReport {
        DoctorReport::new(
            Producer {
                name: "mant".to_owned(),
                version: env!("CARGO_PKG_VERSION").to_owned(),
                engine: None,
            },
            self.environment,
            self.checks,
        )
    }
}

/// Inspect the current installation without creating storage, acquiring
/// update locks, invoking external programs, or accessing the network.
pub(crate) fn inspect_system() -> DoctorReport {
    let mut builder = DoctorBuilder::new();
    builder.push(
        "runtime.platform",
        DoctorCheckStatus::Ok,
        format!(
            "ManT {} on {}-{}",
            env!("CARGO_PKG_VERSION"),
            std::env::consts::ARCH,
            std::env::consts::OS
        ),
    );
    inspect_libmandoc(&mut builder);
    inspect_sources(&mut builder);
    inspect_manuals(&mut builder);
    inspect_tldr(&mut builder);
    builder.finish()
}

#[cfg(feature = "roff")]
fn inspect_libmandoc(builder: &mut DoctorBuilder) {
    let probe = b".TH MANT-DOCTOR 1\n.SH NAME\nmant-doctor \\- installation probe\n";
    match mant_loader::parse_manual_bytes(Path::new("mant-doctor.1"), probe) {
        Ok(document) if !document.sections.is_empty() => {
            builder.push(
                "runtime.libmandoc",
                DoctorCheckStatus::Ok,
                "libmandoc parsed the built-in roff probe",
            );
        }
        Ok(_) => {
            builder.push(
                "runtime.libmandoc",
                DoctorCheckStatus::Error,
                "libmandoc returned an empty document for the built-in roff probe",
            );
        }
        Err(error) => {
            let check = builder.push(
                "runtime.libmandoc",
                DoctorCheckStatus::Error,
                "libmandoc could not parse the built-in roff probe",
            );
            check.details.push(error.to_string());
        }
    }
}

#[cfg(not(feature = "roff"))]
fn inspect_libmandoc(builder: &mut DoctorBuilder) {
    builder.push(
        "runtime.libmandoc",
        DoctorCheckStatus::Info,
        "native roff parsing is not enabled in this build",
    );
}

fn inspect_sources(builder: &mut DoctorBuilder) {
    let paths = match mant_sources::document_paths() {
        Ok(paths) => paths,
        Err(error) => {
            let check = builder.push(
                "paths.data-root",
                DoctorCheckStatus::Error,
                "the ManT data root could not be derived",
            );
            check.details.push(error.to_string());
            check.remediation = Some("set the platform user-data environment variable".to_owned());
            return;
        }
    };
    record_paths(builder, &paths);
    inspect_data_root(builder, &paths);

    let inspection = match mant_sources::inspect_document_sources() {
        Ok(inspection) => inspection,
        Err(error) => {
            let check = builder.push(
                "sources.configuration",
                DoctorCheckStatus::Error,
                "document-source configuration could not be loaded",
            );
            check.details.push(error.to_string());
            check.remediation = Some("fix or remove the reported sources.toml".to_owned());
            return;
        }
    };
    let configured = inspection.sources.len();
    builder.push(
        "sources.configuration",
        if inspection.config_exists {
            DoctorCheckStatus::Ok
        } else {
            DoctorCheckStatus::Info
        },
        if inspection.config_exists {
            format!("loaded {configured} configured source(s)")
        } else {
            "sources.toml is absent; no managed sources are configured".to_owned()
        },
    );
    inspect_registered_documents(builder);

    let git_required = inspection
        .sources
        .iter()
        .any(|source| source.transport == SourceTransport::Git);
    for source in &inspection.sources {
        push_configured_source(builder, source);
    }
    for source in &inspection.orphaned {
        let check = builder.push(
            "sources.orphaned",
            DoctorCheckStatus::Warning,
            if source.removable {
                "an updater-owned source is absent from sources.toml"
            } else {
                "an unconfigured source entry cannot be verified for pruning"
            },
        );
        check.subject = Some(source.source.clone());
        check.details.push(source.path.clone());
        if let Some(error) = &source.error {
            check.details.push(error.clone());
        }
        check.remediation = Some(if source.removable {
            maintenance_hint("mant --prune-docs --dry-run")
        } else {
            "inspect the reported entry manually".to_owned()
        });
    }
    if git_required && cfg!(feature = "update") {
        if let Some(path) = mant_loader::find_host_executable("git") {
            let check = builder.push(
                "tools.git",
                DoctorCheckStatus::Ok,
                "Git is available for configured sources",
            );
            check.details.push(path.to_string_lossy().into_owned());
        } else {
            let check = builder.push(
                "tools.git",
                DoctorCheckStatus::Warning,
                "Git is required by a configured source but was not found on PATH",
            );
            check.remediation = Some("install Git and ensure it is on PATH".to_owned());
        }
    }
}

fn record_paths(builder: &mut DoctorBuilder, paths: &DocumentPaths) {
    builder.environment.data_root = Some(paths.root.to_string_lossy().into_owned());
    builder.environment.config_path = Some(paths.config.to_string_lossy().into_owned());
    builder.environment.documents_root = Some(paths.documents.to_string_lossy().into_owned());
    builder.environment.sources_root = Some(paths.sources.to_string_lossy().into_owned());
}

fn inspect_data_root(builder: &mut DoctorBuilder, paths: &DocumentPaths) {
    match fs::symlink_metadata(&paths.root) {
        Ok(metadata) if metadata.file_type().is_dir() => {
            builder.push(
                "paths.data-root",
                DoctorCheckStatus::Ok,
                "the ManT data root is a directory",
            );
        }
        Ok(_) => {
            let check = builder.push(
                "paths.data-root",
                DoctorCheckStatus::Error,
                "the ManT data root is not a directory",
            );
            check
                .details
                .push(paths.root.to_string_lossy().into_owned());
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            builder.push(
                "paths.data-root",
                DoctorCheckStatus::Info,
                "the ManT data root has not been created yet",
            );
        }
        Err(error) => {
            let check = builder.push(
                "paths.data-root",
                DoctorCheckStatus::Error,
                "the ManT data root could not be inspected",
            );
            check.details.push(error.to_string());
        }
    }
}

fn inspect_registered_documents(builder: &mut DoctorBuilder) {
    match mant_sources::list_registered_documents() {
        Ok(documents) => {
            let personal = documents
                .iter()
                .filter(|document| document.origin == RegisteredDocumentOrigin::Documents)
                .count();
            let managed = documents.len().saturating_sub(personal);
            builder.push(
                "documents.registry",
                if documents.is_empty() {
                    DoctorCheckStatus::Info
                } else {
                    DoctorCheckStatus::Ok
                },
                format!("indexed {personal} personal and {managed} managed document(s)"),
            );
        }
        Err(error) => {
            let check = builder.push(
                "documents.registry",
                DoctorCheckStatus::Error,
                "the registered Markdown catalog could not be built",
            );
            check.details.push(error.to_string());
        }
    }
}

fn push_configured_source(builder: &mut DoctorBuilder, source: &ConfiguredSourceInspection) {
    let (status, message, remediation) = match source.status {
        SourceInstallationStatus::Ready => (
            DoctorCheckStatus::Ok,
            "configured source is installed and consistent with local configuration",
            None,
        ),
        SourceInstallationStatus::Missing => (
            DoctorCheckStatus::Warning,
            "configured source is not installed",
            Some("mant --update-docs"),
        ),
        SourceInstallationStatus::Stale => (
            DoctorCheckStatus::Warning,
            "installed source does not match its active configuration",
            Some("mant --update-docs"),
        ),
        SourceInstallationStatus::Invalid => (
            DoctorCheckStatus::Warning,
            "installed source is invalid or unreadable",
            Some("mant --update-docs"),
        ),
    };
    let check = builder.push("sources.installation", status, message);
    check.subject = Some(source.source.clone());
    check.details.push(format!(
        "transport={}, priority={}",
        match source.transport {
            SourceTransport::Git => "git",
            SourceTransport::Archive => "archive",
        },
        source.priority
    ));
    if let Some(revision) = &source.revision {
        check.details.push(format!("revision={revision}"));
    }
    if let Some(documents) = source.documents {
        check.details.push(format!("documents={documents}"));
    }
    if source.status == SourceInstallationStatus::Ready {
        check
            .details
            .push("remote freshness was not checked".to_owned());
    }
    if let Some(detail) = &source.detail {
        check.details.push(detail.clone());
    }
    check.remediation = remediation.map(maintenance_hint);
}

fn inspect_manuals(builder: &mut DoctorBuilder) {
    let discovery = mant_loader::inspect_manual_roots();
    for diagnostic in &discovery.diagnostics {
        push_manual_path_diagnostic(builder, diagnostic);
    }
    let roots = discovery.roots;
    builder.environment.manual_roots = roots
        .iter()
        .map(|root| root.to_string_lossy().into_owned())
        .collect();
    let existing = roots.iter().filter(|root| root.is_dir()).count();
    let index = mant_loader::ManualIndex::from_roots(roots);
    let pages = index.pages().len();
    let sections = index
        .pages()
        .iter()
        .map(|page| page.section.as_str())
        .collect::<BTreeSet<_>>()
        .len();
    let status = if pages > 0 {
        DoctorCheckStatus::Ok
    } else if cfg!(windows) {
        DoctorCheckStatus::Info
    } else {
        DoctorCheckStatus::Warning
    };
    let check = builder.push(
        "manuals.index",
        status,
        format!(
            "indexed {pages} native manual page(s) in {sections} section(s) from {existing} existing root(s)"
        ),
    );
    if pages == 0 && !cfg!(windows) {
        check.remediation = Some("install manual pages or set MANT_MANPATH".to_owned());
    }
}

fn push_manual_path_diagnostic(
    builder: &mut DoctorBuilder,
    diagnostic: &mant_loader::ManualPathDiagnostic,
) {
    let check = builder.push(
        "manuals.configuration",
        DoctorCheckStatus::Warning,
        &diagnostic.message,
    );
    check.subject = Some(diagnostic.config_path.to_string_lossy().into_owned());
    if let Some(line) = diagnostic.line {
        check.details.push(format!("line={line}"));
    }
    check.remediation = Some("fix or remove the reported man.conf directive".to_owned());
}

fn inspect_tldr(builder: &mut DoctorBuilder) {
    let environment = std::env::vars().collect::<std::collections::BTreeMap<_, _>>();
    let platform = match mant_loader::HostPlatform::current() {
        Ok(platform) => platform,
        Err(error) => {
            let check = builder.push(
                "tldr.cache",
                DoctorCheckStatus::Info,
                "tldr cache conventions are unavailable on this platform",
            );
            check.details.push(error.to_string());
            return;
        }
    };
    let client = mant_loader::find_host_executable("tldr");
    let roots =
        match mant_loader::get_tldr_read_cache_dirs(&environment, platform, client.is_some()) {
            Ok(roots) => roots,
            Err(error) => {
                let check = builder.push(
                    "tldr.cache",
                    DoctorCheckStatus::Warning,
                    "tldr cache paths could not be derived",
                );
                check.details.push(error.to_string());
                return;
            }
        };
    builder.environment.tldr_roots = roots
        .iter()
        .map(|root| root.to_string_lossy().into_owned())
        .collect();
    let readable = roots.iter().filter(|root| root.is_dir()).count();
    let explicit_override = environment
        .keys()
        .any(|name| name.eq_ignore_ascii_case("MANT_TLDR_DIR"));
    let status = if readable > 0 {
        DoctorCheckStatus::Ok
    } else if explicit_override {
        DoctorCheckStatus::Warning
    } else {
        DoctorCheckStatus::Info
    };
    let check = builder.push(
        "tldr.cache",
        status,
        if readable > 0 {
            format!("found {readable} readable tldr cache root(s)")
        } else {
            "no readable tldr cache root was found".to_owned()
        },
    );
    if let Some(client) = client {
        check
            .details
            .push(format!("client={}", client.to_string_lossy()));
    }
    if readable == 0 {
        check.remediation = Some(maintenance_hint("mant --update-tldr"));
    }
}

fn maintenance_hint(command: &str) -> String {
    if cfg!(feature = "update") {
        command.to_owned()
    } else {
        format!("use a ManT build with the update feature to run {command}")
    }
}

/// Render a bounded copy-friendly report. Only fixed status labels receive
/// terminal styling; inspected values remain ordinary text.
pub(crate) fn render_text(report: &DoctorReport, color: bool) -> String {
    let mut output = String::from("ManT doctor\n\n");
    for check in &report.checks {
        let label = match check.status {
            DoctorCheckStatus::Ok => "ok",
            DoctorCheckStatus::Info => "info",
            DoctorCheckStatus::Warning => "warning",
            DoctorCheckStatus::Error => "error",
        };
        let subject = check
            .subject
            .as_deref()
            .map_or_else(String::new, |subject| {
                format!(" [{}]", terminal_safe(subject))
            });
        let code = terminal_safe(&check.code);
        let message = terminal_safe(&check.message);
        if color {
            let style = match check.status {
                DoctorCheckStatus::Ok => OK_STYLE,
                DoctorCheckStatus::Info => INFO_STYLE,
                DoctorCheckStatus::Warning => WARNING_STYLE,
                DoctorCheckStatus::Error => ERROR_STYLE,
            };
            writeln!(
                output,
                "{style}[{label}]{style:#} {code}{subject}: {message}"
            )
            .expect("writing to String cannot fail");
        } else {
            writeln!(output, "[{label}] {code}{subject}: {message}")
                .expect("writing to String cannot fail");
        }
        for detail in &check.details {
            writeln!(output, "       {}", terminal_safe(detail))
                .expect("writing to String cannot fail");
        }
        if let Some(remediation) = &check.remediation {
            let remediation = terminal_safe(remediation);
            if color {
                writeln!(
                    output,
                    "       {INFO_STYLE}hint:{INFO_STYLE:#} {remediation}"
                )
                .expect("writing to String cannot fail");
            } else {
                writeln!(output, "       hint: {remediation}")
                    .expect("writing to String cannot fail");
            }
        }
    }
    writeln!(
        output,
        "\n{} ok, {} info, {} warning(s), {} error(s)",
        report.summary.ok, report.summary.info, report.summary.warnings, report.summary.errors
    )
    .expect("writing to String cannot fail");
    output
}

fn terminal_safe(value: &str) -> String {
    let mut safe = String::with_capacity(value.len());
    for character in value.chars() {
        if character.is_control() {
            safe.extend(character.escape_default());
        } else {
            safe.push(character);
        }
    }
    safe
}

#[cfg(test)]
mod tests {
    use mant_protocol::{
        DoctorCheck, DoctorCheckStatus, DoctorEnvironment, DoctorReport, Producer,
    };
    use mant_sources::{ConfiguredSourceInspection, SourceInstallationStatus, SourceTransport};

    use super::{
        DoctorBuilder, push_configured_source, push_manual_path_diagnostic, render_text,
        terminal_safe,
    };

    fn report() -> DoctorReport {
        DoctorReport::new(
            Producer {
                name: "mant".to_owned(),
                version: "0.9.0".to_owned(),
                engine: None,
            },
            DoctorEnvironment {
                os: "linux".to_owned(),
                arch: "x86_64".to_owned(),
                data_root: None,
                config_path: None,
                documents_root: None,
                sources_root: None,
                manual_roots: Vec::new(),
                tldr_roots: Vec::new(),
            },
            vec![DoctorCheck {
                code: "sources.installation".to_owned(),
                subject: Some("team".to_owned()),
                status: DoctorCheckStatus::Warning,
                message: "configured source is not installed".to_owned(),
                details: vec!["transport=git, priority=1".to_owned()],
                remediation: Some("mant --update-docs".to_owned()),
            }],
        )
    }

    #[test]
    fn text_report_is_copy_friendly_and_colors_only_terminal_labels() {
        let plain = render_text(&report(), false);
        assert!(plain.contains("[warning] sources.installation [team]"));
        assert!(plain.contains("hint: mant --update-docs"));
        assert!(!plain.contains('\u{1b}'));

        let colored = render_text(&report(), true);
        assert!(colored.contains('\u{1b}'));
        assert!(colored.contains("sources.installation [team]"));
    }

    #[test]
    fn terminal_report_escapes_dynamic_control_characters() {
        assert_eq!(
            terminal_safe("path\u{1b}[2J\nnext"),
            "path\\u{1b}[2J\\nnext"
        );
    }

    #[test]
    fn ready_sources_claim_only_local_consistency() {
        let mut builder = DoctorBuilder::new();
        push_configured_source(
            &mut builder,
            &ConfiguredSourceInspection {
                source: "team".to_owned(),
                transport: SourceTransport::Git,
                priority: 1,
                status: SourceInstallationStatus::Ready,
                revision: Some("0123456789abcdef".to_owned()),
                documents: Some(42),
                detail: None,
            },
        );

        let check = builder.checks.first().expect("source check");
        assert_eq!(
            check.message,
            "configured source is installed and consistent with local configuration"
        );
        assert!(
            check
                .details
                .iter()
                .any(|detail| detail == "remote freshness was not checked")
        );
        assert!(!check.message.contains("current"));
    }

    #[test]
    fn maintenance_remediation_respects_the_compiled_capability() {
        let hint = super::maintenance_hint("mant --update-tldr");
        if cfg!(feature = "update") {
            assert_eq!(hint, "mant --update-tldr");
        } else {
            assert_eq!(
                hint,
                "use a ManT build with the update feature to run mant --update-tldr"
            );
        }
    }

    #[test]
    fn invalid_manual_configuration_is_visible_without_stopping_the_index() {
        let mut builder = DoctorBuilder::new();
        push_manual_path_diagnostic(
            &mut builder,
            &mant_loader::ManualPathDiagnostic {
                config_path: std::path::PathBuf::from(r"C:\Users\demo\man.conf"),
                line: Some(7),
                message: "manual path must be absolute".to_owned(),
            },
        );

        let check = builder.checks.first().expect("manual configuration check");
        assert_eq!(check.code, "manuals.configuration");
        assert_eq!(check.status, DoctorCheckStatus::Warning);
        assert_eq!(check.details, ["line=7"]);
        assert_eq!(
            check.remediation.as_deref(),
            Some("fix or remove the reported man.conf directive")
        );
    }
}