alef 0.74.0

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
//! Tests for [`super`], the snippet generation driver.
//!
//! Split out of `mod.rs`, which the inline `mod tests` accounted for 1,913 of 2,945 lines of.
//! This half covers the write/mock-harness guards, path resolution and frontmatter; the
//! coverage-ledger and per-language recipe half lives in [`coverage`], which reuses the fixture
//! helpers defined here.

use super::mock_harness_guard::reject_mock_harness_scaffolding;
use super::*;

mod adapter_handled;
mod binding_excluded;
mod coverage;
mod curated;
mod mock_only;
mod rust_crate_requirements;
mod sample_urls;

#[test]
fn is_snippet_coverage_manifest_path_matches_only_the_exact_ledger_name() {
    assert!(is_snippet_coverage_manifest_path(Path::new(
        "docs/snippets/.alef-snippet-coverage.json"
    )));
    assert!(is_snippet_coverage_manifest_path(Path::new(COVERAGE_MANIFEST)));
    assert!(
        !is_snippet_coverage_manifest_path(Path::new("docs/snippets/.alef-snippet-coverage.json.bak")),
        "a name that merely contains the ledger name must not match"
    );
    assert!(
        !is_snippet_coverage_manifest_path(Path::new("packages/php/composer.json")),
        "an unrelated unmarkable manifest must not match"
    );
}

/// The provenance block `docs::render::with_html_header` prepends to every snippet,
/// spelled out literally so the whole-document assertions below stay whole-document.
///
/// Written out rather than derived from `with_html_header` so the tests fail if that
/// emitter's text changes: the marker string is what the ownership guard and
/// `alef verify` match on, so it is a contract with the read side, not an
/// implementation detail either side may re-spell. ~keep
const SNIPPET_HEADER: &str = "<!-- This file is auto-generated by alef — DO NOT EDIT. -->\n\
<!-- To regenerate: alef e2e generate -->\n\
<!-- To verify freshness: alef verify -->\n\n";

struct FixtureExtension {
    body: &'static str,
}

impl crate::Extension for FixtureExtension {
    fn name(&self) -> &str {
        "fixture"
    }

    fn render_e2e_snippet(
        &self,
        _fixture: &Fixture,
        _e2e_config: &E2eConfig,
        _config: &ResolvedCrateConfig,
        _language: &str,
        _type_defs: &[TypeDef],
        _enums: &[EnumDef],
    ) -> Result<Option<String>> {
        Ok(Some(self.body.to_string()))
    }
}

fn documented_fixture() -> Fixture {
    Fixture {
        id: "extension_owned".into(),
        description: "Extension-owned example".into(),
        docs: Some(FixtureDocs {
            sample_url: None,
            topic: "api".into(),
            stem: None,
            paths: BTreeMap::new(),
            title: None,
            description: None,
            input: None,
            shows: Vec::new(),
            error: None,
            presentation: None,
            client: None,
            side_effects: SideEffectClass::Safe,
            coverage_exceptions: BTreeMap::new(),
            sample_url_vars: Default::default(),
            body_file: None,
        }),
        ..Fixture::default()
    }
}

#[test]
fn mock_harness_scaffolding_is_rejected_for_every_language() {
    let fixture = Fixture {
        id: "rate_limit_429".into(),
        ..Fixture::default()
    };
    let leaks = [
        "var url = System.getenv(\"MOCK_SERVER_URL\") + \"/fixtures/rate_limit_429\";",
        "let url = std.c.getenv(\"MOCK_SERVER_RATE_LIMIT_429\");",
        "var url = System.getProperty(\"mockServerUrl\");",
        "let base = System.getProperty(\"mockServer.rate_limit_429\");",
        "let hosts = process.env.MOCK_SERVERS;",
        "let url = \"https://api.example.com/fixtures/rate_limit_429\";",
    ];
    for leak in leaks {
        let error = reject_mock_harness_scaffolding(leak, &fixture, "zig")
            .expect_err("mock-server scaffolding must not reach a published snippet");
        let message = format!("{error:#}");
        assert!(message.contains("rate_limit_429"), "error omits the fixture: {message}");
        assert!(message.contains("zig"), "error omits the language: {message}");
    }
}

#[test]
fn a_reader_facing_snippet_passes_the_mock_harness_guard() {
    let fixture = Fixture {
        id: "rate_limit_429".into(),
        ..Fixture::default()
    };
    let body = "var apiKey = System.getenv(\"API_KEY\");\nvar client = Sample.createClient(apiKey, null);";
    assert!(reject_mock_harness_scaffolding(body, &fixture, "java").is_ok());
}

fn snippet_report_for(fixture: Fixture, languages: &[&str], body: &'static str) -> Result<SnippetGenerationReport> {
    let extensions: Vec<Box<dyn crate::Extension>> = vec![Box::new(FixtureExtension { body })];
    let e2e = E2eConfig::default();
    let crate_config = ResolvedCrateConfig::default();
    let snippet_config = SnippetConfig {
        output: "docs/snippets".into(),
        ..SnippetConfig::default()
    };
    let context = SnippetRenderContext {
        e2e: &e2e,
        crate_config: &crate_config,
        type_defs: &[],
        enums: &[],
        functions: &[],
        errors: &[],
    };
    let languages: Vec<String> = languages.iter().map(|language| (*language).to_string()).collect();
    generate_snippet_report_with_extensions(&[fixture], &languages, &snippet_config, &context, &extensions)
}

/// The decisive test for the guard's *failure mode*, not for the guard's predicate. ~keep
///
/// Asserting that the rejected snippet is absent from the report would pass whether the
/// run reported the rejection or dropped it on the floor — that vacuity is precisely how
/// the silent deletion stayed hidden. So assert the report exists, and that it carries
/// per-language and per-marker attribution.
#[test]
fn a_guard_rejected_snippet_is_a_reported_failure_not_a_silent_absence() {
    let leaking_body = "var url = System.getenv(\"MOCK_SERVER_URL\") + \"/fixtures/extension_owned\";";

    let error = snippet_report_for(documented_fixture(), &["java", "rust"], leaking_body)
        .expect_err("a guard-rejected snippet must abort generation");

    let message = format!("{error:#}");
    assert!(
        message.contains("rejected by the mock-harness guard"),
        "the failure must name the guard: {message}"
    );
    assert!(
        message.contains("2 documentation snippet(s)"),
        "the failure must count every rejection: {message}"
    );
    assert!(
        message.contains("\n  java (1):"),
        "the failure must attribute per language: {message}"
    );
    assert!(
        message.contains("\n  rust (1):"),
        "the failure must attribute per language: {message}"
    );
    assert!(
        message.contains("`MOCK_SERVER_URL` (1): extension_owned"),
        "the failure must attribute per reason and fixture: {message}"
    );
}

/// A `docs.coverage_exceptions` entry says "this language cannot express this recipe". ~keep
/// It must not also retire "this generator emitted harness scaffolding": one is a
/// documented limitation, the other a defect. Conflating them is what let an exception
/// authored for an unrelated capability gap delete a snippet with no signal.
#[test]
fn a_documented_coverage_exception_cannot_retire_a_guard_rejection() {
    let mut fixture = documented_fixture();
    fixture
        .docs
        .as_mut()
        .expect("documented fixture has docs")
        .coverage_exceptions
        .insert(
            "rust".into(),
            crate::e2e::fixture::SnippetCoverageException {
                reason: "the sample backend cannot express this recipe".into(),
                documentation: "docs/limitations.md".into(),
            },
        );
    let leaking_body = "let url = std::env::var(\"MOCK_SERVER_URL\").unwrap();";

    let error = snippet_report_for(fixture, &["rust"], leaking_body)
        .expect_err("a coverage exception must not absorb a guard rejection");

    let message = format!("{error:#}");
    assert!(
        message.contains("rejected by the mock-harness guard"),
        "the exception silently absorbed the rejection: {message}"
    );
    assert!(
        message.contains("cannot retire a guard rejection"),
        "the failure must explain why the exception did not apply: {message}"
    );
}

/// A `coverage_exceptions` entry declared under `"c"` must still apply when the fixture
/// is generated for the backend running as `"ffi"` -- the same generator under an alias
/// spelling. Before the shared canonicalisation authority, `coverage_exceptions.get(*language)`
/// compared the raw strings and this exception silently never fired.
#[test]
fn coverage_exception_declared_as_c_applies_to_ffi_backend() {
    let mut fixture = documented_fixture();
    fixture.requirements = vec!["feature:unavailable_in_c".into()];
    fixture
        .docs
        .as_mut()
        .expect("documented fixture has docs")
        .coverage_exceptions
        .insert(
            "c".into(),
            crate::e2e::fixture::SnippetCoverageException {
                reason: "the C binding cannot express this recipe".into(),
                documentation: "docs/limitations.md".into(),
            },
        );
    let body = "int main(void) { return 0; }";

    let report = snippet_report_for(fixture, &["ffi"], body)
        .expect("a documented exception must retire the gap instead of failing the run");

    assert!(
        report.coverage.missing.is_empty(),
        "the `c` exception must apply while the backend runs as `ffi`: {:?}",
        report.coverage.missing
    );
    assert_eq!(report.coverage.documented_exceptions.len(), 1);
    assert_eq!(
        report.coverage.documented_exceptions[0].reason,
        "the C binding cannot express this recipe"
    );
}

#[test]
fn validate_coverage_exceptions_rejects_unknown_language() {
    let mut fixture = documented_fixture();
    fixture
        .docs
        .as_mut()
        .expect("documented fixture has docs")
        .coverage_exceptions
        .insert(
            "csharpp".into(),
            crate::e2e::fixture::SnippetCoverageException {
                reason: "typo'd language key".into(),
                documentation: "docs/limitations.md".into(),
            },
        );

    let error = validate_coverage_exceptions(&fixture).expect_err("an unknown language key must hard-fail");
    let message = error.to_string();
    assert!(message.contains("csharpp"), "error must name the bad key: {message}");
    assert!(
        message.contains("c (also accepted: c_ffi, ffi)"),
        "error must name the C backend's accepted spellings: {message}"
    );
    assert!(
        message.contains("rust (also accepted: core, rust_core)"),
        "error must name the Rust backend's accepted spellings: {message}"
    );
}

#[test]
fn validate_coverage_exceptions_accepts_alias_spellings() {
    for alias in ["c", "c_ffi", "ffi", "rust", "core", "rust_core"] {
        let mut fixture = documented_fixture();
        fixture
            .docs
            .as_mut()
            .expect("documented fixture has docs")
            .coverage_exceptions
            .insert(
                alias.to_string(),
                crate::e2e::fixture::SnippetCoverageException {
                    reason: "documented limitation".into(),
                    documentation: "docs/limitations.md".into(),
                },
            );
        assert!(
            validate_coverage_exceptions(&fixture).is_ok(),
            "`{alias}` is an accepted spelling and must pass validation"
        );
    }
}

/// Positive control: the guard is armed on the same path, so a clean body must still ~keep
/// render. Without this, making the guard reject everything would pass the test above.
#[test]
fn a_clean_snippet_still_renders_while_the_guard_is_armed() {
    let clean_body =
        "let api_key = std::env::var(\"API_KEY\").unwrap();\nlet client = sample::create_client(api_key)?;";

    let report =
        snippet_report_for(documented_fixture(), &["rust"], clean_body).expect("a clean snippet must still render");

    assert!(report.guard_rejections.is_empty());
    assert!(report.coverage.missing.is_empty());
    assert_eq!(report.coverage.generated, report.coverage.expected);
    assert_eq!(report.snippets.len(), 1);
    assert!(
        report.snippets[0]
            .file
            .content
            .contains("sample::create_client(api_key)?")
    );
}

#[test]
fn capability_decision_reports_missing_requirements_deterministically() {
    let fixture = Fixture {
        requirements: vec!["service:api".into(), "feature:json".into()],
        ..Fixture::default()
    };
    let capabilities = BTreeSet::from(["feature:json".to_string()]);
    assert_eq!(
        snippet_inclusion(&fixture, &capabilities),
        SnippetInclusion::Exclude {
            missing_requirements: vec!["service:api".into()]
        }
    );
}

/// A call declaring `skip_languages` for a target must be excluded identically by both real
/// production consumers of that decision: [`crate::e2e::codegen::fixture_inclusion`] (the
/// executable e2e suite generator) and the documentation-snippet generator
/// (`generate_snippet_report_with_extensions`, exercised here through no extension at all so
/// the fixture reaches the same skip check the loop in `super` applies before falling back to
/// a built-in recipe). Before `call_skip_reason` was introduced, the snippet generator
/// never consulted `call.skip_languages` at all and attempted a real C render for a call this
/// backend cannot represent -- the built-in engine-factory recipe then fell back to raw
/// `MOCK_SERVER_URL` scaffolding (no `url`/`batch_urls` is declared on the fixture below) and
/// `reject_mock_harness_scaffolding` aborted the whole run. This test drives both real
/// functions over one shared call config and asserts they agree: neither generator ever
/// attempts to speak for a call the target language was explicitly told to skip. ~keep
#[test]
fn snippet_generator_and_executable_suite_agree_on_a_call_level_language_skip() {
    let cfg_str = r#"
[workspace]
languages = ["c"]
[[crates]]
name = "example-core"
sources = ["src/lib.rs"]
[crates.ffi]
prefix = "sample"
[crates.e2e]
fixtures = "fixtures"
[crates.e2e.call]
function = "scrape"
module = "example_api"
[crates.e2e.calls.batch_stream]
function = "batch_stream"
module = "example_api"
select_when = { category = "batch" }
skip_languages = ["c"]

[crates.e2e.calls.batch_stream.overrides.c]
function = "batch_stream"
result_type = "BatchResults"
raw_c_result_type = "BatchResults"
c_engine_factory = "EngineConfig"
"#;
    let cfg: crate::core::config::NewAlefConfig = toml::from_str(cfg_str).expect("config parses");
    let e2e = cfg.crates[0].e2e.clone().expect("e2e config");
    let crate_config = cfg.resolve().expect("config resolves").remove(0);

    let mut fixture = Fixture {
        id: "batch_stream_basic".into(),
        description: "Stream a batch of items".into(),
        category: Some("batch".into()),
        docs: Some(FixtureDocs {
            sample_url: None,
            topic: "batch".into(),
            stem: Some("batch-stream-basic".into()),
            paths: BTreeMap::new(),
            title: None,
            description: None,
            input: None,
            shows: Vec::new(),
            error: None,
            presentation: None,
            client: None,
            side_effects: SideEffectClass::Safe,
            coverage_exceptions: BTreeMap::new(),
            sample_url_vars: Default::default(),
            body_file: None,
        }),
        input: serde_json::json!({}),
        ..Fixture::default()
    };
    fixture.call = Some("batch_stream".into());

    // Real production function #1: the executable e2e suite generator's inclusion check.
    let suite_decision = crate::e2e::codegen::fixture_inclusion(&fixture, "c", &e2e);
    assert_eq!(
        suite_decision,
        crate::e2e::codegen::InclusionDecision::Exclude("call skips language"),
        "the executable suite must exclude a call-level language skip"
    );

    // Real production function #2: the documentation-snippet generator, unaided by any
    // extension, so it falls through to the same built-in recipe real generation uses.
    let snippet_config = SnippetConfig {
        output: "docs/snippets".into(),
        ..SnippetConfig::default()
    };
    let context = SnippetRenderContext {
        e2e: &e2e,
        crate_config: &crate_config,
        type_defs: &[],
        enums: &[],
        functions: &[],
        errors: &[],
    };
    let report =
        generate_snippet_report_with_extensions(&[fixture], &["c".to_string()], &snippet_config, &context, &[])
            .expect("a call-level language skip must not reach the mock-harness guard");

    assert!(
        report.snippets.is_empty(),
        "a call skipped for `c` must never render a snippet: {:?}",
        report.snippets
    );
    assert!(
        report.coverage.expected.is_empty(),
        "a call skipped for `c` must never enter the coverage ledger as expected: {:?}",
        report.coverage.expected
    );
    assert!(report.guard_rejections.is_empty());
}

mod path_resolution;

/// Controls for `generated_docs_use_validator_canonical_language_identity`.
///
/// ~keep Each case varies exactly one frontmatter input and pins the whole rendered
/// document. A renderer that emitted a bogus or constant `requires`, `side_effect` or
/// `level` would satisfy a `contains`-style probe but fails here, which is the property
/// the exact-equality assertion exists to hold.
#[test]
fn frontmatter_fields_are_pinned_by_exact_equality() {
    let render = |fixture: &Fixture, side_effects: SideEffectClass, target: &str| {
        let docs = FixtureDocs {
            sample_url: None,
            topic: "api".into(),
            stem: None,
            paths: BTreeMap::new(),
            title: None,
            description: None,
            input: None,
            shows: Vec::new(),
            error: None,
            presentation: None,
            client: None,
            side_effects,
            coverage_exceptions: BTreeMap::new(),
            sample_url_vars: Default::default(),
            body_file: None,
        };
        render_snippet_markdown(
            "example()",
            fixture,
            &docs,
            target,
            DocumentationLanguage::Binding(Language::Node),
        )
    };

    let baseline = documented_fixture();

    // `side_effect` tracks the docs class rather than a hardcoded "safe".
    assert_eq!(
        render(&baseline, SideEffectClass::Network, "node"),
        format!(
            "---\nid: fixture_node_extension_owned\nlanguage: typescript\ntarget: node\nlevel: typecheck\nrequires: []\nside_effect: network\n---\n\n{SNIPPET_HEADER}Extension-owned example\n\n```typescript title=\"TypeScript\"\nexample()\n```\n"
        )
    );
    assert_eq!(
        render(&baseline, SideEffectClass::Install, "node"),
        format!(
            "---\nid: fixture_node_extension_owned\nlanguage: typescript\ntarget: node\nlevel: typecheck\nrequires: []\nside_effect: install\n---\n\n{SNIPPET_HEADER}Extension-owned example\n\n```typescript title=\"TypeScript\"\nexample()\n```\n"
        )
    );

    // `requires` tracks the fixture's declared requirements rather than a hardcoded `[]`.
    let required = Fixture {
        requirements: vec!["feature:json".into(), "service:api".into()],
        ..documented_fixture()
    };
    assert_eq!(
        render(&required, SideEffectClass::Safe, "node"),
        format!(
            "---\nid: fixture_node_extension_owned\nlanguage: typescript\ntarget: node\nrequires: [\"feature:json\",\"service:api\"]\nside_effect: safe\n---\n\n{SNIPPET_HEADER}Extension-owned example\n\n```typescript title=\"TypeScript\"\nexample()\n```\n"
        )
    );
}

/// `render_snippet_markdown` OMITS the `level:` key for `Safe` side effects instead of the
/// unconditional `typecheck` `94d09809d` introduced, so `SnippetMetadata::level` resolves to
/// `None` and `effective_validation_level` (`src/snippets/runner.rs`) has nothing of the
/// front matter's own to fold the requested level down against.
#[test]
fn safe_side_effects_snippet_is_not_level_capped() {
    let docs = FixtureDocs {
        sample_url: None,
        topic: "api".into(),
        stem: None,
        paths: BTreeMap::new(),
        title: None,
        description: None,
        input: None,
        shows: Vec::new(),
        error: None,
        presentation: None,
        client: None,
        side_effects: SideEffectClass::Safe,
        coverage_exceptions: BTreeMap::new(),
        sample_url_vars: Default::default(),
        body_file: None,
    };
    let rendered = render_snippet_markdown(
        "example()",
        &documented_fixture(),
        &docs,
        "node",
        DocumentationLanguage::Binding(Language::Node),
    );

    assert!(
        !rendered.contains("\nlevel:"),
        "a safe snippet must declare no level cap at all -- the key is OMITTED rather than \
         rendered `level: null`, because these are Astro content entries and Astro types \
         `level` as an optional STRING: an absent key validates, an explicit YAML null does \
         not. Both spellings deserialise to `SnippetMetadata::level == None` on alef's side. \
         got: {rendered}"
    );

    let front_matter = rendered
        .split("---\n")
        .nth(1)
        .expect("rendered snippet has front matter");
    let metadata: crate::snippets::types::SnippetMetadata =
        serde_yaml::from_str(front_matter).expect("front matter is valid YAML");
    assert_eq!(metadata.level, None, "safe snippet must resolve to no declared level");
}

/// The `typecheck` cap `94d09809d` introduced for side-effecting fixtures survives: it is
/// exactly the fixtures this test conditions on that the e2e harness cannot safely execute
/// unattended, so they must still resolve to a declared `TypeCheck` ceiling.
#[test]
fn unsafe_side_effects_snippet_keeps_the_typecheck_cap() {
    for side_effects in [
        SideEffectClass::Network,
        SideEffectClass::Process,
        SideEffectClass::Install,
        SideEffectClass::Server,
    ] {
        let docs = FixtureDocs {
            sample_url: None,
            topic: "api".into(),
            stem: None,
            paths: BTreeMap::new(),
            title: None,
            description: None,
            input: None,
            shows: Vec::new(),
            error: None,
            presentation: None,
            client: None,
            side_effects,
            coverage_exceptions: BTreeMap::new(),
            sample_url_vars: Default::default(),
            body_file: None,
        };
        let rendered = render_snippet_markdown(
            "example()",
            &documented_fixture(),
            &docs,
            "node",
            DocumentationLanguage::Binding(Language::Node),
        );

        assert!(
            rendered.contains("\nlevel: typecheck\n"),
            "unsafe snippet ({side_effects:?}) must keep the typecheck cap, got: {rendered}"
        );

        let front_matter = rendered
            .split("---\n")
            .nth(1)
            .expect("rendered snippet has front matter");
        let metadata: crate::snippets::types::SnippetMetadata =
            serde_yaml::from_str(front_matter).expect("front matter is valid YAML");
        assert_eq!(
            metadata.level,
            Some(crate::snippets::types::ValidationLevel::TypeCheck),
            "unsafe snippet ({side_effects:?}) must resolve to the typecheck cap"
        );
    }
}

/// A snippet exactly as `generate_snippet_report` emits it, for the ownership tests below.
fn rendered_snippet() -> String {
    let docs = FixtureDocs {
        sample_url: None,
        topic: "api".into(),
        stem: None,
        paths: BTreeMap::new(),
        title: None,
        description: None,
        input: None,
        shows: Vec::new(),
        error: None,
        presentation: None,
        client: None,
        side_effects: SideEffectClass::Safe,
        coverage_exceptions: BTreeMap::new(),
        sample_url_vars: Default::default(),
        body_file: None,
    };
    render_snippet_markdown(
        "example()",
        &documented_fixture(),
        &docs,
        "python",
        DocumentationLanguage::Binding(Language::Python),
    )
}

/// The same document with the provenance block removed, for use as a negative control.
fn rendered_snippet_without_header() -> String {
    let rendered = rendered_snippet();
    let stripped = rendered.replace(SNIPPET_HEADER, "");
    assert_ne!(stripped, rendered, "control must actually remove the header");
    stripped
}

/// No generated snippet may emit an explicit YAML `null` for ANY front-matter key.
///
/// These files are Astro content entries. Astro's collection schema types the optional keys as
/// strings, and zod distinguishes "absent" from "present and null": an absent key validates, an
/// explicit null does not (`level: Expected type "string", received "object"`). A SINGLE bad
/// entry aborts the whole `astro build`, so one snippet takes the entire docs site down -- 810
/// generated snippets in one consumer carried `level: null` and the build died on the first.
///
/// The four exact-equality front-matter pins nearby did NOT catch this: they all encoded the
/// broken spelling as expected output, so they agreed with the bug. This asserts the PROPERTY
/// the consumer actually depends on rather than a golden string. ~keep
#[test]
fn no_front_matter_key_renders_an_explicit_yaml_null() {
    for side_effects in [SideEffectClass::Safe, SideEffectClass::Server] {
        let docs = FixtureDocs {
            sample_url: None,
            topic: "api".into(),
            stem: None,
            paths: BTreeMap::new(),
            title: None,
            description: None,
            input: None,
            shows: Vec::new(),
            error: None,
            presentation: None,
            client: None,
            side_effects,
            coverage_exceptions: BTreeMap::new(),
            sample_url_vars: Default::default(),
            body_file: None,
        };
        let rendered = render_snippet_markdown(
            "example()",
            &documented_fixture(),
            &docs,
            "python",
            DocumentationLanguage::Binding(Language::Python),
        );
        let front_matter = rendered.split("---\n").nth(1).expect("front matter");
        let offenders: Vec<&str> = front_matter
            .lines()
            .filter(|line| line.trim_end().ends_with(": null"))
            .collect();
        assert!(
            offenders.is_empty(),
            "{side_effects:?} snippet emits an explicit YAML null, which Astro's content schema \
             rejects and which fails the consumer's entire docs build: {offenders:?}"
        );
    }
}

/// The marker alef emits into a snippet must be one the read side matches.
///
/// `content_has_alef_marker` is the single definition of "alef owns this file's
/// provenance" — the write guard, `alef verify`'s walk and the stamping pass all call it —
/// so this is the assertion that the header is not merely present but recognised. ~keep
#[test]
fn rendered_snippet_carries_a_marker_the_read_side_recognises() {
    assert!(crate::core::hash::content_has_alef_marker(&rendered_snippet()));
}

/// Negative control for the test above: without the header the same document is NOT
/// recognised, so recognition is attributable to the header and not to anything else the
/// snippet happens to contain. Without this, the positive test proves nothing. ~keep
#[test]
fn read_side_does_not_recognise_a_snippet_without_the_header() {
    assert!(!crate::core::hash::content_has_alef_marker(
        &rendered_snippet_without_header()
    ));
}

/// `content_has_alef_marker` only scans a fixed window of leading lines, and the snippet
/// front matter — which must stay first in the file for Astro/Starlight — consumes almost
/// all of it. This pins the remaining budget: the marker lands on the last line still
/// inside the window, and one extra front-matter line pushes it out. A regression here is
/// silent (the marker stays in the file; nothing reads it), which is why the control that
/// the window is genuinely the binding constraint is asserted alongside. ~keep
#[test]
fn snippet_marker_lands_inside_the_read_side_scan_window() {
    let rendered = rendered_snippet();
    let marker_index = rendered
        .lines()
        .position(|line| line.contains("auto-generated by alef"))
        .expect("rendered snippet carries the marker");
    assert_eq!(
        marker_index, 8,
        "a snippet that omits `level:` has a 7-line front matter, leaving one line of slack"
    );

    // The zero-slack case is a snippet that DOES declare a level: 8 front-matter lines put the
    // marker on index 9, the last line the window reads. That is the budget worth pinning. ~keep
    let with_level = rendered.replacen("\ntarget: ", "\nlevel: typecheck\ntarget: ", 1);
    let level_marker_index = with_level
        .lines()
        .position(|line| line.contains("auto-generated by alef"))
        .expect("rendered snippet carries the marker");
    assert_eq!(
        level_marker_index, 9,
        "a snippet declaring `level:` must still land on the last line of the scan window"
    );
    assert!(
        crate::core::hash::content_has_alef_marker(&with_level),
        "the zero-slack case must still be recognised"
    );

    let widened = with_level.replacen("\nlevel: typecheck\n", "\nlevel: typecheck\nextra: value\n", 1);
    assert!(
        !crate::core::hash::content_has_alef_marker(&widened),
        "one extra front-matter line beyond the level-carrying case must push the marker out \
         of the scan window -- the budget this test guards is exactly zero lines"
    );
}

/// Every generator hands `render_snippet_markdown` a body that already ends in a newline, and
/// the template emits its own before the closing fence. Passing the body through verbatim put
/// a blank line inside all several-thousand generated code fences — invisible in a diff,
/// visible on every rendered docs page. ~keep
#[test]
fn a_body_ending_in_a_newline_does_not_open_a_blank_line_before_the_closing_fence() {
    let docs = FixtureDocs {
        sample_url: None,
        topic: "smoke".into(),
        stem: None,
        paths: BTreeMap::new(),
        title: None,
        description: None,
        input: None,
        shows: Vec::new(),
        error: None,
        presentation: None,
        client: None,
        side_effects: SideEffectClass::Safe,
        coverage_exceptions: BTreeMap::new(),
        sample_url_vars: Default::default(),
        body_file: None,
    };
    let rendered = render_snippet_markdown(
        "example()\n",
        &documented_fixture(),
        &docs,
        "python",
        DocumentationLanguage::Binding(Language::Python),
    );

    assert!(
        rendered.ends_with("example()\n```\n"),
        "closing fence must follow the last code line directly: {rendered:?}"
    );
    let blocks = crate::snippets::parser::extract_fenced_blocks(&rendered);
    assert_eq!(blocks.len(), 1);
    assert_eq!(blocks[0].code, "example()");
}

/// The header must not disturb the two structures the snippet pipeline parses out of these
/// files: the YAML front matter (which must remain the first bytes) and the single fenced
/// block. It must also not be mistaken for a `<!-- snippet:... -->` annotation, which
/// `parser::extract_fenced_blocks` reads from the line immediately preceding a fence. ~keep
#[test]
fn snippet_header_preserves_frontmatter_and_fence_structure() {
    let rendered = rendered_snippet();
    assert!(rendered.starts_with("---\nid: fixture_python_extension_owned\n"));
    assert_eq!(
        crate::snippets::parser::frontmatter_status(&rendered),
        crate::snippets::parser::FrontmatterStatus::Present
    );

    let blocks = crate::snippets::parser::extract_fenced_blocks(&rendered);
    assert_eq!(blocks.len(), 1);
    assert_eq!(blocks[0].lang, "python");
    assert_eq!(blocks[0].code, "example()");
    assert_eq!(
        blocks[0].preceding_comment, None,
        "the provenance block must not be read as a snippet annotation"
    );
}

/// The marker also has to survive `alef verify`'s stamping round trip: `finalize_hashes`
/// injects the `alef:hash:` line directly after the marker, and a marked file whose hash
/// cannot be read back is reported stale with `<missing>` on every verify. ~keep
#[test]
fn snippet_marker_survives_hash_stamping() {
    let rendered = rendered_snippet();
    let stamped = crate::core::hash::inject_hash_line(&rendered, "abc123");

    assert!(crate::core::hash::content_has_alef_marker(&stamped));
    assert_eq!(crate::core::hash::extract_hash(&stamped).as_deref(), Some("abc123"));
    assert!(stamped.contains("<!-- alef:hash:abc123 -->"));
    assert_eq!(crate::core::hash::strip_hash_line(&stamped), rendered);
}

/// The stamping pass selects files by `carries_alef_marker`, not by `generated_header`.
/// Snippets are emitted `generated_header: false`, so this is what routes them into
/// `finalize_hashes` and keeps verify from reporting them as unstamped. ~keep
#[test]
fn generated_snippet_file_is_claimed_by_the_stamping_pass() {
    let file = crate::core::backend::GeneratedFile {
        path: PathBuf::from("docs/snippets/python/api/example.md"),
        content: rendered_snippet(),
        generated_header: false,
    };
    assert!(file.carries_alef_marker());
}

/// End-to-end proof against the real guard, which is the only thing that settles whether
/// the marker actually unfreezes these files: the guard is asked to overwrite a
/// pre-existing snippet whose content differs, once with the header on disk and once
/// without. Asserting on `content_has_alef_marker` alone would not — the guard also
/// consults the ownership record, and a test that never exercised it could pass for the
/// wrong reason. Neither temp dir carries a `.alef-ownership.toml`, so the marker is the
/// only proof available in either case. ~keep
#[test]
fn write_guard_accepts_a_marked_snippet_and_refuses_an_unmarked_one() {
    let relative = PathBuf::from("docs/snippets/python/api/example.md");
    let updated = rendered_snippet().replace("example()", "updated_example()");

    let write_over = |existing: &str| {
        let directory = tempfile::tempdir().expect("temporary output directory");
        let full_path = directory.path().join(&relative);
        std::fs::create_dir_all(full_path.parent().expect("snippet parent")).expect("snippet directory");
        std::fs::write(&full_path, existing).expect("pre-existing snippet");
        let report = crate::cli::pipeline::write_scaffold_files_report(
            &[crate::core::backend::GeneratedFile {
                path: relative.clone(),
                content: updated.clone(),
                generated_header: false,
            }],
            directory.path(),
            true,
        )
        .expect("scaffold write report");
        (
            report.changed_paths.contains(&full_path),
            report.refused_paths.contains(&full_path),
            std::fs::read_to_string(&full_path).expect("snippet still readable"),
        )
    };

    let (marked_written, marked_refused, marked_content) = write_over(&rendered_snippet());
    assert!(marked_written, "a marked snippet must be regenerable");
    assert!(!marked_refused);
    assert!(marked_content.contains("updated_example()"));

    let unmarked_existing = rendered_snippet_without_header();
    let (unmarked_written, unmarked_refused, unmarked_content) = write_over(&unmarked_existing);
    assert!(!unmarked_written, "an unmarked snippet has no proof of authorship");
    assert!(unmarked_refused);
    assert_eq!(
        unmarked_content, unmarked_existing,
        "a refused file must be left byte-identical"
    );
}

/// The companion to the test above, and the only end-to-end proof that the ledger disjunct in
/// `write_scaffold_files_report` actually unfreezes anything: the same unmarked, pre-existing
/// snippet the guard refuses above is written when the previous run's coverage ledger records
/// it. The negative half lives in the test above -- its temp dirs carry no ledger, so it
/// already pins that an unrecorded unmarked snippet stays refused. Both halves matter: a
/// disjunct that claimed every unmarked `.md` would pass this test alone. ~keep
#[test]
fn write_guard_accepts_an_unmarked_snippet_the_previous_run_recorded_in_the_ledger() {
    let relative = PathBuf::from("docs/snippets/python/api/example.md");
    let sibling = PathBuf::from("docs/snippets/python/api/hand-written.md");
    let updated = rendered_snippet().replace("example()", "updated_example()");
    let existing = rendered_snippet_without_header();

    let directory = tempfile::tempdir().expect("temporary output directory");
    let root = directory.path().join("docs/snippets");
    for path in [&relative, &sibling] {
        let full = directory.path().join(path);
        std::fs::create_dir_all(full.parent().expect("snippet parent")).expect("snippet directory");
        std::fs::write(&full, &existing).expect("pre-existing snippet");
    }

    let key = SnippetCoverageKey {
        fixture_id: "example".into(),
        language: "python".into(),
    };
    let ledger = SnippetCoverageLedger {
        format_version: COVERAGE_MANIFEST_VERSION,
        generated_paths: vec![PathBuf::from("python/api/example.md")],
        generated_metadata: vec![GeneratedSnippetMetadata {
            key: key.clone(),
            path: PathBuf::from("python/api/example.md"),
            language: "python".into(),
            target: "python".into(),
            session: "python".into(),
            requires: Vec::new(),
            side_effect: SideEffectClass::Safe,
        }],
        expected: vec![key.clone()],
        generated: vec![key],
        missing: Vec::new(),
        documented_exceptions: Vec::new(),
    };
    std::fs::write(
        root.join(COVERAGE_MANIFEST),
        serde_json::to_string(&ledger).expect("serialize ledger"),
    )
    .expect("write ledger");
    super::ownership::snapshot_pre_run_ledger(&root);

    let report = crate::cli::pipeline::write_scaffold_files_report(
        &[
            crate::core::backend::GeneratedFile {
                path: relative.clone(),
                content: updated.clone(),
                generated_header: false,
            },
            crate::core::backend::GeneratedFile {
                path: sibling.clone(),
                content: updated.clone(),
                generated_header: false,
            },
        ],
        directory.path(),
        true,
    )
    .expect("scaffold write report");

    let recorded = directory.path().join(&relative);
    let unrecorded = directory.path().join(&sibling);
    assert!(
        report.changed_paths.contains(&recorded),
        "a snippet the previous run recorded must be regenerable"
    );
    assert!(
        report.refused_paths.contains(&unrecorded),
        "a hand-written sibling under the same root has no record and must stay refused"
    );
    assert_eq!(
        std::fs::read_to_string(&unrecorded).expect("sibling still readable"),
        existing,
        "a refused file must be left byte-identical"
    );
}