alef 0.62.3

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
//! `alef snippets` subcommand — discover, validate, audit, and gap-check documentation snippets.

use crate::snippets::audit::{AuditConfig, AuditSeverity, audit};
use crate::snippets::discovery;
use crate::snippets::gaps::{GapConfig, detect_gaps};
use crate::snippets::output;
use crate::snippets::runner::{RunnerConfig, run_validation};
use crate::snippets::session::SessionSpec;
use crate::snippets::types::{Language, SideEffectClass, SnippetStatus, ValidationLevel};
use crate::snippets::validators::ValidatorRegistry;
use clap::Subcommand;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

#[derive(Subcommand)]
pub enum SnippetsAction {
    /// List discovered snippets and a per-language count summary.
    List {
        #[arg(short, long, required = true, num_args = 1..)]
        snippets: Vec<PathBuf>,

        #[arg(short, long, value_delimiter = ',')]
        languages: Option<Vec<String>>,
    },

    /// Run the configured snippet discovery, validation, audit, and gap checks.
    Check {
        #[arg(short, long, default_value = "alef.toml")]
        config: PathBuf,
        #[arg(long)]
        strict: bool,
        #[arg(long, default_value = "on", value_parser = ["on", "off"])]
        cache: String,

        /// Validate only these languages, by fence tag (`--lang go --lang zig`, or
        /// `--lang go,zig`).
        ///
        /// Diagnosing one language's snippets otherwise means paying for all of them: a full
        /// consumer tree is thousands of snippets across sixteen toolchains, and every
        /// iteration on a single backend's codegen re-ran the lot. The audit and gap passes
        /// still see the whole corpus, because both are cross-language questions — an
        /// unreferenced snippet or a missing language variant cannot be judged from a subset.
        /// ~keep
        #[arg(long = "lang", value_delimiter = ',', num_args = 1..)]
        languages: Option<Vec<String>>,
    },

    /// Parse a single file and print its code blocks.
    Parse { file: PathBuf },

    /// Structural integrity audit (frontmatter, fences, include targets).
    Audit {
        #[arg(short, long, required = true, num_args = 1..)]
        snippets: Vec<PathBuf>,

        #[arg(short, long, num_args = 0..)]
        docs: Vec<PathBuf>,

        #[arg(long)]
        require_frontmatter: bool,
    },

    /// Coverage gap report (unreferenced snippets, missing language variants).
    Gaps {
        #[arg(short, long, required = true, num_args = 1..)]
        snippets: Vec<PathBuf>,

        #[arg(short, long, num_args = 0..)]
        docs: Vec<PathBuf>,

        #[arg(short = 'L', long, value_delimiter = ',')]
        required_languages: Option<Vec<String>>,

        /// Additional base paths to search when resolving `--8<--` include targets.
        ///
        /// Mirrors the `pymdownx.snippets` `base_path` list. Each target is
        /// resolved against these paths in order; the first match wins. When
        /// unset, only the docs root is searched (preserving the prior behaviour).
        #[arg(long = "include-base-path", num_args = 0..)]
        include_base_paths: Vec<PathBuf>,
    },
}

pub fn run(action: SnippetsAction) -> ExitCode {
    match action {
        SnippetsAction::List { snippets, languages } => run_list(&snippets, languages.as_ref()),
        SnippetsAction::Check {
            config,
            strict,
            cache,
            languages,
        } => run_check(&config, strict, cache != "off", languages.as_deref()),
        SnippetsAction::Parse { file } => run_parse(&file),
        SnippetsAction::Audit {
            snippets,
            docs,
            require_frontmatter,
        } => run_audit(&snippets, &docs, require_frontmatter),
        SnippetsAction::Gaps {
            snippets,
            docs,
            required_languages,
            include_base_paths,
        } => run_gaps(&snippets, &docs, required_languages.as_ref(), &include_base_paths),
    }
}

/// A resolved `--lang` selection, keeping rejects so the caller can name them.
struct LanguageFilter {
    recognised: Vec<Language>,
    unrecognised: Vec<String>,
}

/// Resolve `--lang` values to snippet languages.
///
/// Accepts session target names (`kotlin_android`, `node`, `wasm`) as well as fence tags, because
/// the name a user reaches for is the one they just read in their `alef.toml`, and those two
/// vocabularies do not coincide. ~keep
fn parse_language_filter(languages: Option<&[String]>) -> Option<LanguageFilter> {
    let languages = languages?;
    let mut recognised: Vec<Language> = Vec::new();
    let mut unrecognised: Vec<String> = Vec::new();
    for requested in languages {
        match Language::from_session_target(requested) {
            Language::Unknown => unrecognised.push(requested.clone()),
            language => {
                if !recognised.contains(&language) {
                    recognised.push(language);
                }
            }
        }
    }
    Some(LanguageFilter {
        recognised,
        unrecognised,
    })
}

/// Report `--lang` values that named nothing, so a typo cannot silently widen or empty the run.
fn reject_unrecognised_languages(filter: Option<&LanguageFilter>) -> Result<(), ExitCode> {
    let Some(filter) = filter else { return Ok(()) };
    if filter.unrecognised.is_empty() {
        return Ok(());
    }
    tracing::error!(
        "unrecognised --lang value(s): {:?}. Use a snippet fence tag (`go`, `kotlin`, ...) or a \
         session target name from alef.toml (`kotlin_android`, `node`, ...)",
        filter.unrecognised
    );
    Err(ExitCode::FAILURE)
}

fn run_list(snippets: &[PathBuf], languages: Option<&Vec<String>>) -> ExitCode {
    let filter = parse_language_filter(languages.map(Vec::as_slice));
    if let Err(code) = reject_unrecognised_languages(filter.as_ref()) {
        return code;
    }
    let selected = filter.as_ref().map(|filter| filter.recognised.as_slice());
    match discovery::discover_snippets(snippets, selected) {
        Ok(found) => {
            output::print_snippet_list(&found);
            crate::bin_cli::output::blank();
            for (language, count) in &discovery::count_by_language(&found) {
                crate::bin_cli::output::line(format!("  {language:<12} {count}"));
            }
            crate::bin_cli::output::blank();
            ExitCode::SUCCESS
        }
        Err(err) => {
            tracing::error!("discovering snippets: {err}");
            ExitCode::FAILURE
        }
    }
}

fn run_check(config_path: &Path, force_strict: bool, use_cache: bool, languages: Option<&[String]>) -> ExitCode {
    let (_, resolved) = match crate::bin_cli::helpers::load_config(config_path) {
        Ok(config) => config,
        Err(error) => {
            tracing::error!("loading snippet config: {error}");
            return ExitCode::FAILURE;
        }
    };
    let Some((crate_config, config)) = resolved
        .iter()
        .find_map(|krate| Some((krate, krate.docs.as_ref()?.snippets.as_ref()?)))
    else {
        tracing::error!("no [workspace.docs.snippets] or [crates.docs.snippets] configuration found");
        return ExitCode::FAILURE;
    };
    let root = config_path.parent().unwrap_or_else(|| Path::new("."));
    let excluded_paths: Vec<PathBuf> = config.exclude.iter().map(|excluded| root.join(excluded)).collect();
    let snippet_directories = resolved_roots(root, &config.dirs, &excluded_paths);
    let mut directories = snippet_directories.clone();
    directories.extend(resolved_roots(root, &config.inline_dirs, &excluded_paths));
    let docs_directories: Vec<PathBuf> = config.docs_dirs.iter().map(|path| root.join(path)).collect();
    let include_base_paths: Vec<PathBuf> = if config.include_base_paths.is_empty() {
        docs_directories.clone()
    } else {
        config.include_base_paths.iter().map(|path| root.join(path)).collect()
    };
    let required_languages = match config
        .required_languages
        .iter()
        .map(|language| language.parse::<Language>())
        .collect::<Result<Vec<Language>, _>>()
    {
        Ok(languages) => languages,
        Err(error) => {
            tracing::error!("invalid docs.snippets.required_languages entry: {error}");
            return ExitCode::FAILURE;
        }
    };
    let level = config
        .validation_level
        .as_deref()
        .unwrap_or("syntax")
        .parse::<ValidationLevel>()
        .unwrap_or(ValidationLevel::Syntax);
    let strict = force_strict || config.strict;
    // An unrecognised `--lang` must not silently widen the run back to everything: an
    // empty-but-`Some` filter reads to discovery as "match nothing", and the run would then exit
    // on "returned no snippets" naming the directories rather than the bad tag. ~keep
    let language_filter = parse_language_filter(languages);
    if let Err(code) = reject_unrecognised_languages(language_filter.as_ref()) {
        return code;
    }
    let selected = language_filter.as_ref().map(|filter| filter.recognised.as_slice());
    let found = match discovery::discover_snippets(&directories, selected) {
        Ok(found) if !found.is_empty() => found,
        Ok(_) => {
            match &language_filter {
                Some(filter) => tracing::error!("no snippets matched --lang {:?}", filter.recognised),
                None => tracing::error!("snippet discovery returned no snippets"),
            }
            return ExitCode::FAILURE;
        }
        Err(error) => {
            tracing::error!("discovering configured snippets: {error}");
            return ExitCode::FAILURE;
        }
    };
    let allowed_side_effects = config
        .allowed_side_effects
        .iter()
        .filter_map(|value| parse_side_effect(value))
        .collect();
    let runner = RunnerConfig {
        level,
        parallelism: std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get),
        timeout_secs: config.timeout_secs.unwrap_or(120),
        fail_fast: config.fail_fast,
        deny_unclassified: config.deny_unclassified || force_strict,
        allowed_side_effects,
        cache_dir: use_cache.then(|| root.join(config.cache_dir())),
        changed_only: use_cache,
        sessions: match configured_sessions(config, root, &crate_config.features) {
            Ok(sessions) => sessions,
            Err(error) => {
                tracing::error!("{error}");
                return ExitCode::FAILURE;
            }
        },
    };
    let summary = match run_validation(&found, &ValidatorRegistry::new(), &runner) {
        Ok(summary) => summary,
        Err(error) => {
            tracing::error!("running configured snippet validation: {error}");
            return ExitCode::FAILURE;
        }
    };
    output::print_summary(&summary, false);
    if let Some(path) = &config.report_output
        && let Err(error) = output::write_report(&summary, &root.join(path), false)
    {
        tracing::error!("writing snippet report: {error}");
        return ExitCode::FAILURE;
    }
    let strict_failure = strict && has_incomplete_coverage(&summary);
    let missing_generated = match missing_generated_snippets(&directories) {
        Ok(missing) => missing,
        Err(error) => {
            tracing::error!("reading generated snippet coverage: {error}");
            return ExitCode::FAILURE;
        }
    };
    for missing in &missing_generated {
        tracing::warn!(
            "generated snippet missing for fixture `{}` language `{}`: {}",
            missing.key.fixture_id,
            missing.key.language,
            missing.reason
        );
    }
    let content_collections: std::collections::BTreeMap<String, PathBuf> = config
        .content_collections
        .iter()
        .map(|(name, collection_root)| (name.clone(), root.join(collection_root)))
        .collect();
    let (audit_failure, gap_failure) = match run_configured_audit_and_gaps(&ConfiguredCheckInputs {
        snippet_directories: &snippet_directories,
        docs_directories: &docs_directories,
        include_base_paths: &include_base_paths,
        required_languages: &required_languages,
        exclude: &excluded_paths,
        readme: crate_config.readme.as_ref(),
        content_collections: &content_collections,
        workspace_root: root,
        require_frontmatter: config.require_frontmatter,
        strict,
    }) {
        Ok(result) => result,
        Err(error) => {
            tracing::error!("running configured snippet audit and gap checks: {error}");
            return ExitCode::FAILURE;
        }
    };
    if summary.has_failures()
        || strict_failure
        || strict && !missing_generated.is_empty()
        || audit_failure
        || gap_failure
    {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

/// Resolve configured snippet roots against `root`, dropping any that fall
/// under an excluded prefix.
fn resolved_roots(root: &Path, dirs: &[PathBuf], excluded: &[PathBuf]) -> Vec<PathBuf> {
    dirs.iter()
        .map(|path| root.join(path))
        .filter(|path| !excluded.iter().any(|prefix| path.starts_with(prefix)))
        .collect()
}

/// Inputs for `check`'s configured audit and gap pass, grouped into one
/// struct so the call stays under clippy's argument threshold.
struct ConfiguredCheckInputs<'a> {
    /// Snippet roots proper — `docs.snippets.dirs` only. `inline_dirs` are
    /// deliberately absent: they are prose documentation pages whose fenced
    /// blocks are validated as snippets, and they are never `--8<--` include
    /// targets, so gap-checking them would report every documentation page as
    /// an unreferenced snippet. Mirrors `docs/mod.rs::validate_snippets`,
    /// which likewise audits and gap-checks only the `dirs`-derived list.
    snippet_directories: &'a [PathBuf],
    docs_directories: &'a [PathBuf],
    include_base_paths: &'a [PathBuf],
    required_languages: &'a [Language],
    exclude: &'a [PathBuf],
    readme: Option<&'a crate::core::config::ReadmeConfig>,
    /// Astro content collection names mapped to their already-resolved roots.
    content_collections: &'a std::collections::BTreeMap<String, PathBuf>,
    workspace_root: &'a Path,
    require_frontmatter: bool,
    strict: bool,
}

/// Run the configured audit and gap checks against the configured snippet
/// roots, so `check` cannot disagree with `alef validate` about which files
/// are in scope.
///
/// References a snippet can legitimately have without any `--8<--` include
/// are collected from the same three sources as
/// `docs/mod.rs::validate_snippets`: `[crates.readme]` snippet mappings,
/// generated-snippet coverage ledgers, and Astro content collections queried
/// by a documentation page.
///
/// Audit issues of `AuditSeverity::Error` always fail the gate, and audit is
/// skipped entirely without a configured docs surface (matching the
/// precedent) so a snippets-only config is not failed by fence tags no
/// documentation ever renders. Gap findings split the same way `alef
/// validate`'s snippet gate already treats them: unreferenced snippets are
/// only a failure under `strict` (extra examples can be intentional), while
/// missing include targets, missing required language variants, undocumented
/// skips, and unknown fence languages always fail. Gaps are skipped entirely
/// when neither `docs_dirs` nor `required_languages` is configured —
/// otherwise every discovered snippet would read as "unreferenced" and a
/// `strict` config with no docs surface configured would flip from green to
/// red for a check that was never meaningful for it.
///
/// Coverage ledgers are read with missing fixture/language cells tolerated:
/// `run_check` already reports those through `missing_generated_snippets` and
/// only fails on them under `strict`, so rejecting them here would both
/// override that gate and misattribute the failure.
///
/// # Errors
///
/// Returns an error when a coverage ledger is broken, an Astro collection
/// root cannot be walked, or a documentation file cannot be read.
fn run_configured_audit_and_gaps(inputs: &ConfiguredCheckInputs<'_>) -> anyhow::Result<(bool, bool)> {
    let mut configured_references =
        crate::snippets::gaps::readme_snippet_references(inputs.workspace_root, inputs.readme);
    configured_references
        .extend(crate::snippets::gaps::coverage_ledger_references_allowing_missing_cells(inputs.snippet_directories)?);
    configured_references.extend(crate::snippets::gaps::astro_collection_references(
        inputs.docs_directories,
        inputs.content_collections,
    )?);

    let audit_failure = if inputs.docs_directories.is_empty() {
        false
    } else {
        report_audit(&audit(&AuditConfig {
            docs_dirs: inputs.docs_directories.to_vec(),
            snippet_dirs: inputs.snippet_directories.to_vec(),
            require_frontmatter: inputs.require_frontmatter,
            include_base_paths: inputs.include_base_paths.to_vec(),
            configured_references: configured_references.clone(),
            exclude: inputs.exclude.to_vec(),
        }))
    };

    if inputs.docs_directories.is_empty() && inputs.required_languages.is_empty() {
        return Ok((audit_failure, false));
    }
    let gap_report = detect_gaps(&GapConfig {
        docs_dirs: inputs.docs_directories.to_vec(),
        snippet_dirs: inputs.snippet_directories.to_vec(),
        required_languages: inputs.required_languages.to_vec(),
        include_base_paths: inputs.include_base_paths.to_vec(),
        configured_references,
        exclude: inputs.exclude.to_vec(),
    })?;
    let (gap_structural_failure, gap_has_unreferenced) = report_gaps(&gap_report);
    Ok((
        audit_failure,
        gap_structural_failure || (inputs.strict && gap_has_unreferenced),
    ))
}

fn report_audit(report: &crate::snippets::audit::AuditReport) -> bool {
    for issue in &report.issues {
        let message = format!(
            "snippet audit: {}:{} ({:?}) {}",
            issue.path.display(),
            issue.line,
            issue.kind,
            issue.message
        );
        match issue.severity {
            AuditSeverity::Error => tracing::error!("{message}"),
            AuditSeverity::Warning => tracing::warn!("{message}"),
        }
    }
    report.has_errors()
}

/// Logs every gap finding and returns `(structural_failure, has_unreferenced_snippets)`.
///
/// `structural_failure` covers missing include targets, missing required
/// language variants, undocumented skips, and unknown fence languages —
/// findings that are never intentional. Unreferenced snippets are reported
/// separately because they are only a failure under `strict`.
fn report_gaps(report: &crate::snippets::gaps::GapReport) -> (bool, bool) {
    for reference in &report.missing_references {
        tracing::error!(
            "snippet gap: missing include target {}:{} -> {}",
            reference.source.display(),
            reference.line,
            reference.target.display()
        );
    }
    for path in &report.unreferenced_snippets {
        tracing::warn!("snippet gap: unreferenced snippet {}", path.display());
    }
    for variant in &report.missing_language_variants {
        tracing::error!(
            "snippet gap: missing required language variant `{}` for {}",
            variant.language,
            variant.group.display()
        );
    }
    for location in &report.skips_without_reason {
        tracing::error!(
            "snippet gap: skip without reason {}:{} (block {})",
            location.path.display(),
            location.line,
            location.block_index
        );
    }
    for unknown in &report.unknown_languages {
        tracing::error!(
            "snippet gap: unknown fence language {}:{} tag=`{}`",
            unknown.path.display(),
            unknown.line,
            unknown.tag
        );
    }
    let structural_failure = !report.missing_references.is_empty()
        || !report.missing_language_variants.is_empty()
        || !report.skips_without_reason.is_empty()
        || !report.unknown_languages.is_empty();
    (structural_failure, !report.unreferenced_snippets.is_empty())
}

fn configured_sessions(
    config: &crate::core::config::DocsSnippetsConfig,
    root: &std::path::Path,
    crate_features: &[String],
) -> Result<std::collections::HashMap<String, SessionSpec>, String> {
    let root = if root.is_absolute() {
        root.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|error| format!("resolving current directory for snippet sessions: {error}"))?
            .join(root)
    };
    let mut sessions = std::collections::HashMap::new();
    for (target, session) in &config.sessions {
        let normalized = Language::normalize_session_target(target);
        let language = Language::from_session_target(&normalized);
        if language == Language::Unknown {
            return Err(format!("unknown docs.snippets session target `{target}`"));
        }
        let mut rust_features = session.rust_features.clone();
        if language == Language::Rust {
            rust_features.extend(crate_features.iter().cloned());
            rust_features.sort();
            rust_features.dedup();
        }
        let spec = SessionSpec {
            language,
            working_directory: root.join(&session.cwd),
            manifest: session.manifest.as_ref().map(|path| root.join(path)),
            before: session.before.clone(),
            env: session.env.clone(),
            include_paths: session.include_paths.iter().map(|path| root.join(path)).collect(),
            rust_features,
            rust_dependencies: session.rust_dependencies.clone(),
        };
        if sessions.insert(normalized.clone(), spec).is_some() {
            return Err(format!("duplicate docs.snippets session target `{normalized}`"));
        }
    }
    Ok(sessions)
}

fn missing_generated_snippets(directories: &[PathBuf]) -> anyhow::Result<Vec<crate::e2e::snippets::MissingSnippet>> {
    let mut missing = Vec::new();
    for directory in directories {
        let path = directory.join(crate::e2e::snippets::COVERAGE_MANIFEST);
        if !path.is_file() {
            continue;
        }
        let content = std::fs::read_to_string(&path)
            .map_err(|error| anyhow::anyhow!("failed to read {}: {error}", path.display()))?;
        let ledger: crate::e2e::snippets::SnippetCoverageLedger = serde_json::from_str(&content)
            .map_err(|error| anyhow::anyhow!("failed to parse {}: {error}", path.display()))?;
        missing.extend(ledger.missing);
    }
    missing.sort_by(|left, right| left.key.cmp(&right.key));
    Ok(missing)
}

fn has_incomplete_coverage(summary: &crate::snippets::types::RunSummary) -> bool {
    summary.results.iter().any(|result| is_incomplete_status(result.status))
}

fn is_incomplete_status(status: SnippetStatus) -> bool {
    matches!(
        status,
        SnippetStatus::Skip | SnippetStatus::Unavailable | SnippetStatus::Downgraded
    )
}

fn parse_side_effect(value: &str) -> Option<SideEffectClass> {
    match value.trim().to_ascii_lowercase().as_str() {
        "safe" => Some(SideEffectClass::Safe),
        "network" => Some(SideEffectClass::Network),
        "process" => Some(SideEffectClass::Process),
        "install" => Some(SideEffectClass::Install),
        "server" => Some(SideEffectClass::Server),
        _ => None,
    }
}

fn run_parse(file: &Path) -> ExitCode {
    match crate::snippets::parser::parse_code_blocks(file) {
        Ok(blocks) => {
            if blocks.is_empty() {
                crate::bin_cli::output::line(format!("No code blocks found in {}", file.display()));
            } else {
                for (index, block) in blocks.iter().enumerate() {
                    crate::bin_cli::output::line(format!("--- Block {} (line {}) ---", index + 1, block.start_line));
                    crate::bin_cli::output::line(format!("Language: {}", block.lang));
                    if let Some(title) = &block.title {
                        crate::bin_cli::output::line(format!("Title: {title}"));
                    }
                    if let Some(comment) = &block.preceding_comment {
                        crate::bin_cli::output::line(format!("Annotation: {comment}"));
                    }
                    crate::bin_cli::output::line(format!("Code ({} lines):", block.code.lines().count()));
                    crate::bin_cli::output::line(&block.code);
                    crate::bin_cli::output::blank();
                }
            }
            ExitCode::SUCCESS
        }
        Err(err) => {
            tracing::error!("parsing {}: {err}", file.display());
            ExitCode::FAILURE
        }
    }
}

fn run_audit(snippet_dirs: &[PathBuf], docs_dirs: &[PathBuf], require_frontmatter: bool) -> ExitCode {
    let configured_references = match crate::snippets::gaps::coverage_ledger_references(snippet_dirs) {
        Ok(references) => references,
        Err(error) => {
            tracing::error!("reading generated snippet coverage: {error}");
            return ExitCode::FAILURE;
        }
    };
    let config = AuditConfig {
        docs_dirs: docs_dirs.to_vec(),
        snippet_dirs: snippet_dirs.to_vec(),
        require_frontmatter,
        include_base_paths: docs_dirs.to_vec(),
        configured_references,
        exclude: Vec::new(),
    };
    let report = audit(&config);
    if report.issues.is_empty() {
        crate::bin_cli::output::line("Audit clean: no issues found.");
        return ExitCode::SUCCESS;
    }
    crate::bin_cli::output::line(format!("Audit found {} issue(s):", report.issues.len()));
    for issue in &report.issues {
        let severity = match issue.severity {
            AuditSeverity::Error => "ERROR",
            AuditSeverity::Warning => "WARN",
        };
        crate::bin_cli::output::line(format!(
            "  [{severity}] {}:{} ({:?}) {}",
            issue.path.display(),
            issue.line,
            issue.kind,
            issue.message
        ));
    }
    if report.has_errors() {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

fn run_gaps(
    snippet_dirs: &[PathBuf],
    docs_dirs: &[PathBuf],
    required_languages: Option<&Vec<String>>,
    include_base_paths: &[PathBuf],
) -> ExitCode {
    let required = required_languages
        .map(|languages| {
            languages
                .iter()
                .map(|language| Language::from_fence_tag(language))
                .filter(|language| *language != Language::Unknown)
                .collect()
        })
        .unwrap_or_default();
    let resolved_base_paths: Vec<PathBuf> = if include_base_paths.is_empty() {
        docs_dirs.to_vec()
    } else {
        include_base_paths.to_vec()
    };
    let configured_references = match crate::snippets::gaps::coverage_ledger_references(snippet_dirs) {
        Ok(references) => references,
        Err(error) => {
            tracing::error!("reading generated snippet coverage: {error}");
            return ExitCode::FAILURE;
        }
    };
    let config = GapConfig {
        docs_dirs: docs_dirs.to_vec(),
        snippet_dirs: snippet_dirs.to_vec(),
        required_languages: required,
        include_base_paths: resolved_base_paths,
        configured_references,
        exclude: Vec::new(),
    };
    let report = match detect_gaps(&config) {
        Ok(report) => report,
        Err(err) => {
            tracing::error!("detecting gaps: {err}");
            return ExitCode::FAILURE;
        }
    };
    if !report.has_gaps() {
        crate::bin_cli::output::line("No gaps found.");
        return ExitCode::SUCCESS;
    }
    if !report.missing_references.is_empty() {
        crate::bin_cli::output::line(format!(
            "Missing include targets ({}):",
            report.missing_references.len()
        ));
        for reference in &report.missing_references {
            crate::bin_cli::output::line(format!(
                "  {}:{}{}",
                reference.source.display(),
                reference.line,
                reference.target.display()
            ));
        }
    }
    if !report.unreferenced_snippets.is_empty() {
        crate::bin_cli::output::line(format!(
            "Unreferenced snippets ({}):",
            report.unreferenced_snippets.len()
        ));
        for path in &report.unreferenced_snippets {
            crate::bin_cli::output::line(format!("  {}", path.display()));
        }
    }
    if !report.missing_language_variants.is_empty() {
        crate::bin_cli::output::line(format!(
            "Missing language variants ({}):",
            report.missing_language_variants.len()
        ));
        for variant in &report.missing_language_variants {
            crate::bin_cli::output::line(format!("  {}{}", variant.group.display(), variant.language));
        }
    }
    if !report.skips_without_reason.is_empty() {
        crate::bin_cli::output::line(format!("Skips without reason ({}):", report.skips_without_reason.len()));
        for location in &report.skips_without_reason {
            crate::bin_cli::output::line(format!(
                "  {}:{} (block {})",
                location.path.display(),
                location.line,
                location.block_index
            ));
        }
    }
    if !report.unknown_languages.is_empty() {
        crate::bin_cli::output::line(format!("Unknown languages ({}):", report.unknown_languages.len()));
        for unknown in &report.unknown_languages {
            crate::bin_cli::output::line(format!(
                "  {}:{} tag={}",
                unknown.path.display(),
                unknown.line,
                unknown.tag
            ));
        }
    }
    ExitCode::FAILURE
}

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

    /// `--lang` narrows a run to one backend's snippets, so an unrecognised value has to be
    /// reported rather than dropped: dropping it leaves an empty-but-`Some` filter, which reads to
    /// discovery as "match nothing" and fails the run naming the directories, not the typo. ~keep
    #[test]
    fn a_language_filter_keeps_every_recognised_fence_tag() {
        let requested = ["go".to_string(), "typescript".to_string(), "zig".to_string()];
        let parsed = parse_language_filter(Some(&requested)).expect("a filter was requested");

        assert_eq!(
            parsed.recognised,
            vec![Language::Go, Language::TypeScript, Language::Zig]
        );
        assert!(parsed.unrecognised.is_empty(), "no recognised tag may be rejected");
    }

    /// The names in an `alef.toml` session table are session targets, not fence tags, and the two
    /// vocabularies differ. `--lang kotlin_android` has to reach the Kotlin snippets, or the only
    /// name a user has for that session selects nothing. ~keep
    #[test]
    fn a_language_filter_accepts_session_target_names_as_well_as_fence_tags() {
        let requested = [
            "kotlin_android".to_string(),
            "kotlin-android".to_string(),
            "node".to_string(),
            "wasm".to_string(),
        ];
        let parsed = parse_language_filter(Some(&requested)).expect("a filter was requested");

        assert!(parsed.unrecognised.is_empty(), "session target names must resolve");
        assert_eq!(
            parsed.recognised,
            vec![Language::Kotlin, Language::TypeScript],
            "aliases collapse to one entry each rather than repeating a language"
        );
    }

    #[test]
    fn a_language_filter_reports_an_unrecognised_tag_instead_of_dropping_it() {
        let requested = ["go".to_string(), "nosuchlang".to_string()];
        let parsed = parse_language_filter(Some(&requested)).expect("a filter was requested");

        assert_eq!(parsed.recognised, vec![Language::Go]);
        assert_eq!(parsed.unrecognised, vec!["nosuchlang".to_string()]);
        assert!(
            reject_unrecognised_languages(Some(&parsed)).is_err(),
            "an unrecognised tag must fail the run, not narrow it silently"
        );
    }

    #[test]
    fn no_language_argument_means_no_filter_at_all() {
        assert!(parse_language_filter(None).is_none());
        assert!(reject_unrecognised_languages(None).is_ok());
    }

    #[test]
    fn strict_coverage_rejects_every_non_validation_status() {
        assert!(is_incomplete_status(SnippetStatus::Skip));
        assert!(is_incomplete_status(SnippetStatus::Unavailable));
        assert!(is_incomplete_status(SnippetStatus::Downgraded));
        assert!(!is_incomplete_status(SnippetStatus::Pass));
    }

    #[test]
    fn configured_audit_is_skipped_without_a_docs_surface() {
        let directory = tempfile::tempdir().expect("temp directory");
        let snippets = directory.path().join("snippets");
        std::fs::create_dir_all(&snippets).expect("snippet directory");
        std::fs::write(snippets.join("weird.md"), "```gibberish\nvalue\n```\n").expect("write snippet");
        let snippet_directories = [snippets];

        let (audit_failure, gap_failure) = run_configured_audit_and_gaps(&ConfiguredCheckInputs {
            snippet_directories: &snippet_directories,
            docs_directories: &[],
            include_base_paths: &[],
            required_languages: &[],
            exclude: &[],
            readme: None,
            content_collections: &std::collections::BTreeMap::new(),
            workspace_root: directory.path(),
            require_frontmatter: false,
            strict: true,
        })
        .expect("audit and gap pass");

        assert!(
            !audit_failure,
            "a snippets-only config has no documentation surface to audit, so an unknown fence tag \
             must not fail the gate — `docs/mod.rs::validate_snippets` skips audit the same way"
        );
        assert!(
            !gap_failure,
            "gaps are meaningless without docs dirs or required languages"
        );
    }

    #[test]
    fn readme_snippet_mappings_count_as_references_for_the_strict_gate() {
        let directory = tempfile::tempdir().expect("temp directory");
        let snippets = directory.path().join("snippets");
        let docs = directory.path().join("docs");
        std::fs::create_dir_all(snippets.join("python")).expect("snippet directory");
        std::fs::create_dir_all(&docs).expect("docs directory");
        std::fs::write(snippets.join("python/hello.md"), "```python\nvalue = 1\n```\n").expect("write snippet");
        let snippet_directories = [snippets];
        let docs_directories = [docs];
        let content_collections = std::collections::BTreeMap::new();
        let readme = crate::core::config::ReadmeConfig {
            template_dir: None,
            snippets_dir: Some(PathBuf::from("snippets")),
            config: None,
            output_pattern: None,
            discord_url: None,
            banner_url: None,
            languages: std::collections::HashMap::from([(
                "python".to_string(),
                serde_json::json!({ "snippets": ["hello.md"] }),
            )]),
            targets: std::collections::HashMap::new(),
        };

        let (audit_failure, gap_failure) = run_configured_audit_and_gaps(&ConfiguredCheckInputs {
            snippet_directories: &snippet_directories,
            docs_directories: &docs_directories,
            include_base_paths: &docs_directories,
            required_languages: &[],
            exclude: &[],
            readme: Some(&readme),
            content_collections: &content_collections,
            workspace_root: directory.path(),
            require_frontmatter: false,
            strict: true,
        })
        .expect("audit and gap pass");

        assert!(!audit_failure);
        assert!(
            !gap_failure,
            "a snippet named by [crates.readme.languages.*].snippets is referenced even though no \
             documentation page `--8<--`-includes it"
        );

        let (_, gap_failure_without_readme) = run_configured_audit_and_gaps(&ConfiguredCheckInputs {
            snippet_directories: &snippet_directories,
            docs_directories: &docs_directories,
            include_base_paths: &docs_directories,
            required_languages: &[],
            exclude: &[],
            readme: None,
            content_collections: &content_collections,
            workspace_root: directory.path(),
            require_frontmatter: false,
            strict: true,
        })
        .expect("audit and gap pass");

        assert!(
            gap_failure_without_readme,
            "without the README source the same snippet reads as unreferenced, so this test would \
             pass vacuously if the reference sources were dropped"
        );
    }

    #[test]
    fn resolved_roots_drop_excluded_prefixes() {
        let root = Path::new("/workspace");
        let excluded = [root.join("snippets/vendored")];

        let resolved = resolved_roots(
            root,
            &[PathBuf::from("snippets"), PathBuf::from("snippets/vendored")],
            &excluded,
        );

        assert_eq!(resolved, vec![root.join("snippets")]);
    }

    #[test]
    fn generated_coverage_manifest_exposes_missing_cells() {
        let directory = tempfile::tempdir().expect("temp directory");
        let ledger = crate::e2e::snippets::SnippetCoverageLedger {
            expected: vec![crate::e2e::snippets::SnippetCoverageKey {
                fixture_id: "extension_only".into(),
                language: "python".into(),
            }],
            missing: vec![crate::e2e::snippets::MissingSnippet {
                key: crate::e2e::snippets::SnippetCoverageKey {
                    fixture_id: "extension_only".into(),
                    language: "python".into(),
                },
                reason: "no compatible recipe".into(),
            }],
            ..Default::default()
        };
        std::fs::write(
            directory.path().join(crate::e2e::snippets::COVERAGE_MANIFEST),
            serde_json::to_vec(&ledger).expect("serialize ledger"),
        )
        .expect("write ledger");

        let missing = missing_generated_snippets(&[directory.path().to_path_buf()]).expect("read ledger");
        assert_eq!(missing, ledger.missing);
    }

    #[test]
    fn configured_sessions_accept_binding_targets_and_reject_unknown_keys() {
        let root = std::env::current_dir()
            .expect("current directory")
            .join("neutral-workspace");
        let mut config = crate::core::config::DocsSnippetsConfig::default();
        config.sessions.insert(
            "wasm".into(),
            crate::core::config::output::DocsSnippetSessionConfig {
                cwd: "bindings/wasm".into(),
                ..Default::default()
            },
        );
        let sessions = configured_sessions(&config, &root, &[]).expect("known target");
        assert_eq!(sessions["wasm"].language, Language::TypeScript);
        assert_eq!(sessions["wasm"].working_directory, root.join("bindings/wasm"));

        config.sessions.insert(
            "unsupported-runtime".into(),
            crate::core::config::output::DocsSnippetSessionConfig::default(),
        );
        assert!(configured_sessions(&config, &root, &[]).is_err());
    }

    #[test]
    fn configured_rust_session_enables_crate_features_so_gated_modules_resolve() {
        let root = std::env::current_dir()
            .expect("current directory")
            .join("neutral-workspace");
        let mut config = crate::core::config::DocsSnippetsConfig::default();
        config.sessions.insert(
            "rust".into(),
            crate::core::config::output::DocsSnippetSessionConfig {
                cwd: "crates/sample-core".into(),
                rust_features: vec!["telemetry".into()],
                ..Default::default()
            },
        );
        config.sessions.insert(
            "wasm".into(),
            crate::core::config::output::DocsSnippetSessionConfig {
                cwd: "bindings/wasm".into(),
                ..Default::default()
            },
        );
        let crate_features = vec!["plugins".to_string(), "telemetry".to_string()];

        let sessions = configured_sessions(&config, &root, &crate_features).expect("known targets");

        assert_eq!(sessions["rust"].language, Language::Rust);
        assert_eq!(
            sessions["rust"].rust_features,
            vec!["plugins".to_string(), "telemetry".to_string()],
            "a Rust snippet session must build the path dependency with the crate's declared features, \
             otherwise snippets importing a feature-gated module fail with `unresolved import`"
        );
        assert!(
            sessions["wasm"].rust_features.is_empty(),
            "crate features must not leak into non-Rust sessions"
        );
    }
}