alef 0.107.5

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
//! Tests for [`super::real_formatter_drift_with`], via this file's own `real_formatter_drift`
//! convenience wrapper bound to the real `is_tool_available` (alef#436's second half) -- split
//! into its own module for the same reason `helpers/drift_tests.rs` splits out of
//! `helpers/tests.rs`: this repository's 1,000-line file cap, and this concern (comparing a
//! non-`.rs`/`.md` render against disk through a real formatter) is self-contained. Also covers
//! [`super::render_predicts_final_bytes`] and [`super::drifted_managed_paths_with`]'s alef#458
//! poly-availability gate on the `.rs`/`.md` fast path -- the closely related concern of deciding
//! whether that fast path may run at all before falling back to the real-formatter tier this
//! module otherwise covers. ~keep

use super::*;

/// A minimal resolved config for the drift tests: no `[crates.e2e]` block, so
/// `formatting_owner` never reaches its override branch and every path is classified by poly
/// coverage and the residual table alone -- which is what these tests are about. ~keep
fn drift_test_config() -> crate::core::config::ResolvedCrateConfig {
    let cfg: crate::core::config::NewAlefConfig = toml::from_str(
        r#"
[workspace]
languages = ["rust"]
[[crates]]
name = "sample"
sources = ["src/lib.rs"]
"#,
    )
    .expect("valid config");
    cfg.resolve().expect("resolvable").remove(0)
}

fn e2e_poly_config() -> crate::core::config::ResolvedCrateConfig {
    let cfg: crate::core::config::NewAlefConfig = toml::from_str(
        r#"
[workspace]
languages = ["rust"]
[[crates]]
name = "sample"
sources = ["src/lib.rs"]
[crates.e2e]
fixtures = "fixtures"
output = "e2e"
[crates.e2e.call]
function = "run"
[crates.e2e.registry]
output = "test_apps"
"#,
    )
    .expect("valid config");
    cfg.resolve().expect("resolvable").remove(0)
}

#[test]
fn poly_probe_roots_match_the_e2e_writers_per_language_working_directories() {
    let dir = tempfile::tempdir().expect("tempdir");
    for relative in ["e2e/java", "e2e/python", "test_apps/java"] {
        std::fs::create_dir_all(dir.path().join(relative)).unwrap();
    }

    assert_eq!(
        poly_probe_roots(&e2e_poly_config(), dir.path()),
        vec![
            dir.path().to_path_buf(),
            dir.path().join("e2e/java"),
            dir.path().join("e2e/python"),
            dir.path().join("test_apps/java"),
        ]
    );
}

/// Test-only convenience wrapper around [`real_formatter_drift_with`], bound to the real
/// [`crate::cli::pipeline::is_tool_available`] -- production has no call site for this exact
/// binding since alef#458 threads a single `is_available` closure through both
/// [`drifted_managed_paths_with`]'s tiers instead of resolving it twice, so this exists purely to
/// keep the tests below (which only ever care about the real binary, not the injectable seam)
/// from repeating that argument at every call site. ~keep
fn real_formatter_drift(
    candidates: Vec<RealFormatCandidate>,
    base_dir: &std::path::Path,
) -> (Vec<String>, FormatDriftStats) {
    real_formatter_drift_with(candidates, base_dir, &crate::cli::pipeline::is_tool_available)
}

fn candidate(full_path: &std::path::Path, disk_content: &str, rendered_content: &str) -> RealFormatCandidate {
    RealFormatCandidate {
        full_path: full_path.to_path_buf(),
        disk_content: disk_content.to_string(),
        rendered_content: rendered_content.to_string(),
        format_context: full_path.parent().unwrap_or(full_path).to_path_buf(),
    }
}

/// THE LOUD SKIP (see the module doc's `prove-the-check-fired` reference): with no seam into the
/// real `is_tool_available`, this must be provable without depending on whether the host running
/// the suite happens to have `poly` installed -- so it drives the injectable
/// `real_formatter_drift_with` directly, the same seam `format_generated_reporting_with`'s own
/// strict tests use for the identical reason.
#[test]
fn skips_and_counts_every_candidate_when_poly_is_unavailable() {
    let dir = tempfile::tempdir().expect("tempdir");
    let candidates = vec![
        candidate(&dir.path().join("a.toml"), "[a]\nx = 1\n", "[a]\nx=1\n"),
        candidate(&dir.path().join("b.py"), "x = 1\n", "x=1\n"),
    ];

    let (drifted, stats) = real_formatter_drift_with(candidates, dir.path(), &|_tool| false);

    assert!(
        drifted.is_empty(),
        "a skipped comparison must never manufacture a drift finding: {drifted:?}"
    );
    assert_eq!(
        stats,
        FormatDriftStats {
            compared: 0,
            skipped_missing_formatter: 2,
            skipped_staging_error: 0,
            skipped_formatter_error: 0,
            skipped_no_faithful_prediction: 0,
            matched_render_exactly: 0,
            content_verified_paths: HashSet::new(),
        },
        "every candidate must be counted as skipped, never silently dropped, when poly is absent"
    );
}

/// An empty candidate list is a trivial 0/0 -- there was nothing to compare, and that must read
/// as "nothing to compare", not as either an examined-clean or a skipped tree.
#[test]
fn is_a_trivial_no_op_on_an_empty_candidate_list() {
    let dir = tempfile::tempdir().expect("tempdir");

    let (drifted, stats) = real_formatter_drift_with(Vec::new(), dir.path(), &|_tool| true);

    assert!(drifted.is_empty());
    assert_eq!(stats, FormatDriftStats::default());
}

/// THE CORE MECHANISM, against the real `poly` binary: a TOML file whose rendered content
/// genuinely differs from disk, even after real formatting, must be reported drifted --
/// something `normalize_content` could never catch for TOML (see the module doc for why this
/// runs the real formatter instead of predicting its output). Skips itself when `poly` is not on
/// the host running the suite, the same guard this codebase's own `alef fmt`/`mix format`
/// integration tests use (see `cli::pipeline::commands::lint::tests`) for a real-subprocess
/// assertion with no injectable seam underneath it.
#[test]
fn catches_a_toml_file_whose_rendered_value_genuinely_differs_from_disk() {
    let Some(_poly) = crate::test_support::tool_available_with_stable_path("poly") else {
        return;
    };
    let dir = tempfile::tempdir().expect("tempdir");
    let real_path = dir.path().join("pyproject.toml");
    std::fs::write(&real_path, "[project]\nname = \"old\"\n").unwrap();
    let candidates = vec![candidate(
        &real_path,
        "[project]\nname = \"old\"\n",
        "[project]\nname=\"new\"\n",
    )];

    let (drifted, stats) = real_formatter_drift(candidates, dir.path());

    assert_eq!(drifted, vec![real_path.display().to_string()]);
    assert_eq!(
        stats,
        FormatDriftStats {
            compared: 1,
            skipped_missing_formatter: 0,
            skipped_staging_error: 0,
            skipped_formatter_error: 0,
            skipped_no_faithful_prediction: 0,
            matched_render_exactly: 0,
            content_verified_paths: HashSet::from([real_path.clone()]),
        }
    );
}

/// THE CONTROL for the mechanism above: once poly's real formatting of the rendered content
/// converges to exactly what is already on disk, nothing must be reported -- otherwise every
/// up-to-date non-`.rs`/`.md` file would fail `alef verify` forever. Builds the disk fixture by
/// running the SAME rendered content through the SAME real formatter first (rather than
/// hand-formatting a fixture), so this stays correct regardless of which poly version or TOML
/// formatting opinion the host running the suite has installed.
#[test]
fn is_silent_once_poly_fmt_converges_the_render_to_match_disk() {
    let Some(_poly) = crate::test_support::tool_available_with_stable_path("poly") else {
        return;
    };
    let dir = tempfile::tempdir().expect("tempdir");
    let real_path = dir.path().join("pyproject.toml");
    let rendered = "[project]\nname=\"same\"\n";
    let (_drifted, _stats) = real_formatter_drift(
        vec![candidate(&real_path, "placeholder -- overwritten below", rendered)],
        dir.path(),
    );
    // The call above formats a temp copy, not `real_path` itself (it never exists on disk yet in
    // this test) -- reconstruct the converged disk fixture the same way `alef all` would, by
    // running the identical rendered bytes through the real formatter and writing the result.
    let formatted_once = format_once_for_test(rendered, dir.path());
    std::fs::write(&real_path, &formatted_once).unwrap();

    let (drifted, stats) = real_formatter_drift(vec![candidate(&real_path, &formatted_once, rendered)], dir.path());

    assert!(
        drifted.is_empty(),
        "an already-converged file must not be reported drifted: {drifted:?}"
    );
    assert_eq!(stats.compared, 1);
}

/// Poly selects these E2E manifest formatters by the canonical filename, not just the suffix.
/// Verification must therefore preserve that filename when it stages a fresh render, or it
/// compares formatter-canonical disk bytes against the raw render and reports permanent drift. ~keep
#[test]
fn formatter_managed_e2e_manifests_verify_after_generation_formatting() {
    let dir = tempfile::tempdir().expect("tempdir");
    let cases = [
        "test_apps/csharp/Xberg.E2eTests.csproj",
        "test_apps/java/pom.xml",
        "test_apps/zig/build.zig.zon",
    ];

    let mut candidates = Vec::new();
    for relative in cases {
        let path = dir.path().join(relative);
        std::fs::create_dir_all(path.parent().expect("manifest parent")).expect("create manifest parent");
        std::fs::write(&path, "formatted\n").expect("write formatted manifest");
        candidates.push(candidate(&path, "formatted\n", "raw render\n"));
    }

    let run_filename_keyed_formatter = |paths: &[std::path::PathBuf], _base: &std::path::Path| {
        let mut formatted = 0usize;
        for path in paths {
            let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();
            if matches!(name, "Xberg.E2eTests.csproj" | "pom.xml" | "build.zig.zon") {
                std::fs::write(path, "formatted\n")?;
                formatted += 1;
            }
        }
        anyhow::ensure!(
            formatted == paths.len(),
            "formatter reached {formatted} of {} canonical manifest names",
            paths.len()
        );
        Ok(())
    };
    let (drifted, stats) = real_formatter_drift_with_runner(
        candidates,
        dir.path(),
        &|tool| tool == "poly",
        &run_filename_keyed_formatter,
    );

    assert!(
        drifted.is_empty(),
        "freshly generated and formatted E2E manifests must verify without false drift: {drifted:?}"
    );
    assert_eq!(
        stats.compared, 3,
        "all three formatter-managed manifests must be compared"
    );
}

/// The E2E writer runs poly from `<output>/<language>`, not from the repository root. This is
/// observable when the repo config excludes `**/e2e/**`: root-relative discovery declines Java
/// packages containing an `e2e` component, while language-local discovery formats them. ~keep
#[test]
fn formatter_candidates_run_in_the_same_language_context_as_the_e2e_writer() {
    let dir = tempfile::tempdir().expect("tempdir");
    let language_root = dir.path().join("e2e/java");
    let real_path = language_root.join("src/test/java/io/example/e2e/SmokeTest.java");
    std::fs::create_dir_all(real_path.parent().expect("test parent")).unwrap();
    std::fs::write(&real_path, "formatted\n").unwrap();
    let mut item = candidate(&real_path, "formatted\n", "raw render\n");
    item.format_context = language_root.clone();

    let runner = |paths: &[std::path::PathBuf], context: &std::path::Path| {
        anyhow::ensure!(
            context == language_root,
            "wrong formatter context: {}",
            context.display()
        );
        anyhow::ensure!(paths.len() == 1, "expected one staged path, got {}", paths.len());
        std::fs::write(&paths[0], "formatted\n")?;
        Ok(())
    };
    let (drifted, stats) = real_formatter_drift_with_runner(vec![item], dir.path(), &|tool| tool == "poly", &runner);

    assert!(
        drifted.is_empty(),
        "writer-context formatting must converge: {drifted:?}"
    );
    assert_eq!(stats.compared, 1);
}

/// A staged file is not content-verified when its formatter fails: comparing the untouched raw
/// render would certify bytes the writer never promises to leave on disk. ~keep
#[test]
fn failed_formatter_candidates_are_not_reported_as_content_verified() {
    let dir = tempfile::tempdir().expect("tempdir");
    let real_path = dir.path().join("pyproject.toml");
    std::fs::write(&real_path, "[project]\nname = \"old\"\n").expect("seed candidate");
    let candidate = candidate(&real_path, "[project]\nname = \"old\"\n", "[project]\nname=\"new\"\n");

    let (drifted, stats) = real_formatter_drift_with_runner(
        vec![candidate],
        dir.path(),
        &|tool| tool == "poly",
        &|_paths, _context| anyhow::bail!("formatter failed"),
    );

    assert!(drifted.is_empty());
    assert_eq!(stats.compared, 0);
    assert_eq!(stats.skipped_formatter_error, 1);
    assert!(stats.content_verified_paths.is_empty());
}

#[test]
fn real_poly_formats_a_gitignored_staged_e2e_render() {
    let Some(_poly) = crate::test_support::tool_available_with_stable_path("poly") else {
        return;
    };
    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::write(dir.path().join("poly.toml"), "[discovery]\nexclude = [\"**/e2e/**\"]\n").unwrap();
    std::fs::write(dir.path().join(".gitignore"), "e2e/python/alef-verify-drift-*/\n").unwrap();
    let language_root = dir.path().join("e2e/python");
    let real_path = language_root.join("test_smoke.py");
    std::fs::create_dir_all(real_path.parent().expect("test parent")).unwrap();
    let raw = "value=1\n";
    std::fs::write(&real_path, raw).unwrap();
    for args in [
        vec!["init", "--quiet"],
        vec!["config", "user.email", "alef-tests@example.invalid"],
        vec!["config", "user.name", "Alef Tests"],
        vec!["add", "poly.toml", ".gitignore"],
        vec!["add", "e2e/python/test_smoke.py"],
        vec!["commit", "--quiet", "-m", "fixture"],
    ] {
        let status = std::process::Command::new("git")
            .args(args)
            .current_dir(dir.path())
            .status()
            .expect("git must run");
        assert!(status.success(), "git fixture setup must succeed");
    }
    crate::cli::pipeline::poly_format_strict(&[std::path::PathBuf::from(".")], &language_root)
        .expect("the writer-context formatter must run");
    let formatted = std::fs::read_to_string(&real_path).unwrap();
    assert_ne!(formatted, raw, "fixture must prove the real Python formatter ran");

    let mut item = candidate(&real_path, &formatted, raw);
    item.format_context = language_root;
    let saw_ignored_staging_path = std::cell::Cell::new(false);
    let runner = |paths: &[std::path::PathBuf], context: &std::path::Path| {
        assert_eq!(paths.len(), 1, "one staged candidate must reach poly");
        let ignored = std::process::Command::new("git")
            .args(["check-ignore", "--quiet", "--"])
            .arg(&paths[0])
            .current_dir(dir.path())
            .status()?;
        assert!(ignored.success(), "the staging directory must be gitignored");
        saw_ignored_staging_path.set(true);
        crate::cli::pipeline::poly_format_strict_including_excluded(paths, context)
    };
    let (drifted, stats) = real_formatter_drift_with_runner(vec![item], dir.path(), &|tool| tool == "poly", &runner);

    assert!(
        drifted.is_empty(),
        "a gitignored staged copy must converge to the writer's real output: {drifted:?}"
    );
    assert!(
        saw_ignored_staging_path.get(),
        "the gitignore negative control must run"
    );
    assert_eq!(stats.compared, 1);
}

/// The writer compares before formatting. When the fresh render already matches the stamped
/// file, it performs no write; poly then preserves that hash-stamped file unless explicitly
/// given `--fix-generated`. The verifier must not format an unstamped copy and invent output
/// the writer can never produce. ~keep
#[test]
fn unchanged_stamped_render_bypasses_the_formatter_prediction() {
    let Some(_poly) = crate::test_support::tool_available_with_stable_path("poly") else {
        return;
    };
    let dir = tempfile::tempdir().expect("tempdir");
    let file = crate::core::backend::GeneratedFile {
        path: std::path::PathBuf::from("pyproject.toml"),
        content: "[build-system]\nrequires=[\"setuptools>=68\",\"wheel\"]\n".to_owned(),
        generated_header: true,
    };
    let rendered = crate::cli::commands::adopt::managed_outputs(std::slice::from_ref(&file), dir.path())
        .pop()
        .expect("one managed output")
        .content;

    let probe_dir = dir.path().join("probe");
    std::fs::create_dir_all(&probe_dir).unwrap();
    let probe = probe_dir.join("pyproject.toml");
    std::fs::write(&probe, &rendered).unwrap();
    crate::cli::pipeline::poly_format_strict(std::slice::from_ref(&probe), &probe_dir)
        .expect("poly must format the negative-control render");
    assert_ne!(
        std::fs::read_to_string(&probe).unwrap(),
        rendered,
        "negative control must prove that formatting the unstamped render changes it"
    );

    let hash = crate::core::hash::hash_content(&rendered);
    std::fs::write(
        dir.path().join(&file.path),
        crate::core::hash::inject_hash_line(&rendered, &hash),
    )
    .unwrap();
    let (drifted, stats) =
        drifted_managed_paths_with(std::slice::from_ref(&file), dir.path(), &drift_test_config(), &|tool| {
            tool == "poly"
        });

    assert!(
        drifted.is_empty(),
        "an unchanged writer input cannot be formatter drift"
    );
    assert_eq!(stats.matched_render_exactly, 1);
    assert_eq!(stats.compared, 0, "the impossible formatter pass must not run");
}

#[test]
fn drift_check_ignores_create_once_seeds_even_if_an_older_copy_has_a_marker() {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join(".gitattributes");
    let old = "# Generated by alef scaffold.\nold/** linguist-generated=true\n";
    let old = crate::cli::pipeline::ensure_generated_header(&path, old);
    let hash = crate::core::hash::compute_file_hash(&old);
    std::fs::write(&path, crate::core::hash::inject_hash_line(&old, &hash)).unwrap();
    let seed = crate::core::backend::GeneratedFile {
        path: std::path::PathBuf::from(".gitattributes"),
        content: "# Generated by alef scaffold.\nnew/** linguist-generated=true\n".to_string(),
        generated_header: false,
    };
    assert!(
        !crate::cli::commands::adopt::is_create_once_seed(&seed),
        "fixture must reproduce the self-marker that defeats the generic seed classifier"
    );

    let (drifted, stats) = drifted_managed_paths_with(
        std::slice::from_ref(&seed),
        dir.path(),
        &drift_test_config(),
        &|_tool| false,
    );

    assert!(
        drifted.is_empty(),
        "create-once content is consumer-owned after creation"
    );
    assert_eq!(stats, FormatDriftStats::default());
}

/// Helper for the control test above: format `content` once through the real `poly fmt --fix`,
/// the same way [`real_formatter_drift`] itself does internally, so the test's disk fixture is
/// built from the identical mechanism under test rather than a hand-written guess at poly's
/// canonical TOML layout.
fn format_once_for_test(content: &str, base_dir: &std::path::Path) -> String {
    let scratch = base_dir.join("scratch.toml");
    std::fs::write(&scratch, content).unwrap();
    crate::cli::pipeline::poly_format_strict(std::slice::from_ref(&scratch), base_dir).expect("poly fmt must succeed");
    let formatted = std::fs::read_to_string(&scratch).unwrap();
    std::fs::remove_file(&scratch).ok();
    formatted
}

/// The sibling temp file [`real_formatter_drift`] stages must never survive the call -- a stray
/// `.alef-verify-drift-*` file left behind in a consumer's working tree would itself show up as
/// an untracked file on the next `git status`, which is precisely the kind of side effect a
/// read-only `alef verify` must not have.
#[test]
fn leaves_no_temp_file_behind_after_comparing() {
    let Some(_poly) = crate::test_support::tool_available_with_stable_path("poly") else {
        return;
    };
    let dir = tempfile::tempdir().expect("tempdir");
    let real_path = dir.path().join("pyproject.toml");
    std::fs::write(&real_path, "[project]\nname = \"old\"\n").unwrap();
    let candidates = vec![candidate(
        &real_path,
        "[project]\nname = \"old\"\n",
        "[project]\nname=\"new\"\n",
    )];

    let _ = real_formatter_drift(candidates, dir.path());

    let leftovers: Vec<_> = std::fs::read_dir(dir.path())
        .unwrap()
        .filter_map(Result::ok)
        .map(|entry| entry.file_name())
        .filter(|name| name != "pyproject.toml")
        .collect();
    assert!(
        leftovers.is_empty(),
        "no temp file may survive a comparison call, found: {leftovers:?}"
    );
}

/// [`render_predicts_final_bytes`]'s contract, which is deliberately ASYMMETRIC between the two
/// extensions -- see the module doc for the measured alef#478 evidence.
///
/// `.rs` is cleared only when poly is absent. `normalize_content` runs a REAL `rustfmt`
/// (`format_rust_content`), not an imitation of one, and alef#465 removed the ordering bug that
/// used to make that no-poly prediction wrong on a first run --
/// [`rust_binding_bytes_on_disk_match_a_fresh_render_with_no_poly`] measures that end to end
/// against a real `alef all` with `poly` off `PATH`.
///
/// `.md` is cleared ONLY when poly is absent. alef models exactly one rumdl rule, a blank-line
/// cap matched to MD012 -- and the poly config alef itself generates DISABLES MD012 while
/// leaving the rules that actually reshape alef's markdown enabled. Measured in a consumer: a
/// cold `alef readme` and `alef docs` left 29 pages differing from committed, every one of them
/// reconciled exactly by a real `poly fmt --fix`. Predicting them in memory reported all 29 as
/// drifted against a tree the writer was a correct fixed point for. With poly absent nothing
/// reformats the page after alef writes it, so the prediction is exact again and the fast path
/// is kept for that case only.
///
/// alef#458 originally gated both extensions TOGETHER on implementation symmetry rather than on
/// a measured cause, and got both halves wrong in opposite directions. Keep them reasoned about
/// separately. ~keep
///
/// Pure and host-independent (no subprocess, no real `poly` binary), so every case is provable
/// on any machine regardless of what it has installed. ~keep
#[test]
fn render_predicts_final_bytes_clears_rust_and_markdown_only_without_poly() {
    let cases = [
        ("lib.rs", false, true),
        ("reference.md", false, true),
        ("pyproject.toml", false, false),
        ("bindings.go", false, false),
        ("noextension", false, false),
    ];
    for (name, with_poly, without_poly) in cases {
        assert_eq!(
            render_predicts_final_bytes(std::path::Path::new(name), true),
            with_poly,
            "render_predicts_final_bytes({name:?}) with poly present must be {with_poly}"
        );
        assert_eq!(
            render_predicts_final_bytes(std::path::Path::new(name), false),
            without_poly,
            "render_predicts_final_bytes({name:?}) with poly absent must be {without_poly}"
        );
    }
}

#[test]
fn managed_toml_drift_preview_preserves_the_existing_provenance_header() {
    let dir = tempfile::tempdir().expect("tempdir");
    let existing = "# This file is auto-generated by alef — DO NOT EDIT.\n\
# alef:hash:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\
# To regenerate: alef generate\n\
# To verify freshness: alef verify --exit-code\n\n\
[discovery]\nexclude = [\"generated/**\", \"consumer/**\"]\n";
    let file = crate::core::backend::GeneratedFile {
        path: std::path::PathBuf::from("poly.toml"),
        content: "[discovery]\nexclude = [\"generated/**\"]\n".to_string(),
        generated_header: true,
    };

    let output = managed_output_for_drift(&file, existing, dir.path())
        .into_iter()
        .next()
        .expect("managed output");

    assert!(
        output
            .content
            .contains("# To verify freshness: alef verify --exit-code")
    );
    assert!(output.content.contains("\"consumer/**\""));
    assert!(
        crate::cli::pipeline::matches_alef_output(&dir.path().join("poly.toml"), existing, &output.content),
        "verification must predict the merge writer's fixed point, including its preserved header"
    );
}

/// `alef all` leaves poly.toml in poly's canonical form (the writer unstamps, runs `poly fmt
/// --fix`, then restamps), but the generator spells `[[hooks.sources]].hooks` as a multi-line
/// array and the merge replaces the consumer's array-of-tables with that spelling verbatim. The
/// preserved on-disk hash line used to make poly skip the staged copy, so verify compared the
/// raw multi-line merge against the canonical file and reported drift no `alef all` could clear. ~keep
#[test]
fn managed_poly_toml_drift_is_predicted_through_the_formatter_not_the_raw_merge() {
    let Some(_poly) = crate::test_support::tool_available_with_stable_path("poly") else {
        return;
    };
    let dir = tempfile::tempdir().expect("tempdir");
    let generated = "[discovery]\nexclude = [\"generated/**\"]\n\n[[hooks.sources]]\nid = \"ai-rulez\"\ngit = \"https://example.invalid/ai-rulez.git\"\nrevision = \"v1\"\nhooks = [\n  \"ai-rulez-validate\",\n]\n";
    let canonical = "[discovery]\nexclude = [\"generated/**\"]\n\n[[hooks.sources]]\nid = \"ai-rulez\"\ngit = \"https://example.invalid/ai-rulez.git\"\nrevision = \"v1\"\nhooks = [\"ai-rulez-validate\"]\n";
    let path = dir.path().join("poly.toml");
    let header = crate::cli::pipeline::ensure_generated_header(&path, canonical);
    let hash = crate::core::hash::compute_file_hash(&header);
    std::fs::write(&path, crate::core::hash::inject_hash_line(&header, &hash)).unwrap();
    let file = crate::core::backend::GeneratedFile {
        path: std::path::PathBuf::from("poly.toml"),
        content: generated.to_string(),
        generated_header: true,
    };

    let probe_dir = dir.path().join("probe");
    std::fs::create_dir_all(&probe_dir).unwrap();
    let probe = probe_dir.join("poly.toml");
    std::fs::write(&probe, generated).unwrap();
    crate::cli::pipeline::poly_format_strict(std::slice::from_ref(&probe), &probe_dir)
        .expect("poly must format the negative-control render");
    assert_eq!(
        std::fs::read_to_string(&probe).unwrap(),
        canonical,
        "negative control: poly's canonical spelling of the generated array is the compact one"
    );

    let (drifted, stats) =
        drifted_managed_paths_with(std::slice::from_ref(&file), dir.path(), &drift_test_config(), &|tool| {
            tool == "poly"
        });

    assert!(
        drifted.is_empty(),
        "poly.toml already at poly's fixed point must not be reported as drift: {drifted:?}"
    );
    assert_eq!(stats.compared, 1, "the formatter pass must actually have run");
}

#[test]
fn ordinary_generated_toml_uses_the_fresh_render_without_merge_semantics() {
    let dir = tempfile::tempdir().expect("tempdir");
    let existing = "# This file is auto-generated by alef — DO NOT EDIT.\n\
# alef:hash:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\
# To regenerate: alef generate\n\
# To verify freshness: alef verify\n\n\
[build]\ntarget-dir = \"consumer-target\"\n";
    let file = crate::core::backend::GeneratedFile {
        path: std::path::PathBuf::from(".cargo/config.toml"),
        content: "[build]\ntarget-dir = \"generated-target\"\n".to_string(),
        generated_header: true,
    };

    let output = managed_output_for_drift(&file, existing, dir.path())
        .into_iter()
        .next()
        .expect("managed output");

    assert!(output.content.contains("generated-target"));
    assert!(!output.content.contains("consumer-target"));
}

/// A create-once E2E manifest can have `generated_header = false` in the current render while
/// the existing file still carries the marker an earlier alef wrote. The real scaffold writer
/// preserves that on-disk marker before comparing or writing, so verification must predict the
/// same header-preserving bytes instead of comparing the marked file to a raw render forever. ~keep
#[test]
fn drift_preview_preserves_an_existing_marker_for_an_unheadered_render() {
    let dir = tempfile::tempdir().expect("tempdir");
    let cases = [
        ("test_apps/csharp/Xberg.E2eTests.csproj", "<Project />\n"),
        (
            "test_apps/java/pom.xml",
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project />\n",
        ),
        ("test_apps/zig/build.zig.zon", ".{ .name = .e2e }\n"),
    ];

    for (relative, raw) in cases {
        let path = dir.path().join(relative);
        let marked = crate::cli::pipeline::ensure_generated_header(&path, raw);
        let file_hash = crate::core::hash::compute_file_hash(&marked);
        let existing = crate::core::hash::inject_hash_line(&marked, &file_hash);
        let file = crate::core::backend::GeneratedFile {
            path: std::path::PathBuf::from(relative),
            content: raw.to_owned(),
            generated_header: false,
        };

        let output = managed_output_for_drift(&file, &existing, dir.path())
            .into_iter()
            .next()
            .expect("managed output");

        assert!(
            crate::cli::pipeline::matches_alef_output(&path, &existing, &output.content),
            "{relative}: verify must mirror the writer's disk-aware header preservation"
        );
    }
}

/// alef#465 END TO END, against [`drifted_managed_paths_with`]'s own injectable seam: with poly
/// unavailable, an `.rs` candidate must still be COMPARED on the fast path, in both directions
/// -- silent when it matches a fresh render, reported when it does not -- never routed into the
/// counted-skip bucket. This is the repin of the alef#458 contract that asserted the exact
/// opposite; the gate it pinned was suppressing this coverage on the one CI leg with no poly
/// installed rather than avoiding a false positive, once alef#465 made the first write already
/// rustfmt-formatted (measured by
/// [`rust_binding_bytes_on_disk_match_a_fresh_render_with_no_poly`]).
///
/// `FormatDriftStats` stays at its default in both halves on purpose: it counts only the
/// real-formatter tier, and a fast-path file never reaches that tier. Drives `&|_| false`
/// directly, so this is provable on a host that does, in fact, have `poly` installed. ~keep
#[test]
fn drifted_managed_paths_compares_an_rs_candidate_on_the_fast_path_when_poly_is_unavailable() {
    let dir = tempfile::tempdir().expect("tempdir");
    let file = crate::core::backend::GeneratedFile {
        path: std::path::PathBuf::from("lib.rs"),
        content: "pub fn greet() -> &'static str { \"old\" }\n".to_string(),
        generated_header: true,
    };
    let rendered = crate::cli::commands::adopt::managed_outputs(std::slice::from_ref(&file), dir.path());
    std::fs::write(dir.path().join("lib.rs"), &rendered[0].content).unwrap();

    let (drifted, stats) = drifted_managed_paths_with(
        std::slice::from_ref(&file),
        dir.path(),
        &drift_test_config(),
        &|_tool| false,
    );

    assert!(
        drifted.is_empty(),
        "an up-to-date .rs file must be compared and found clean without poly, not reported: {drifted:?}"
    );
    assert_eq!(
        stats,
        FormatDriftStats {
            matched_render_exactly: 1,
            content_verified_paths: HashSet::from([dir.path().join("lib.rs")]),
            ..FormatDriftStats::default()
        },
        "a fast-path file must be counted as settled against the render, never as a real-formatter \
         skip just because poly is absent"
    );

    let changed = vec![crate::core::backend::GeneratedFile {
        path: std::path::PathBuf::from("lib.rs"),
        content: "pub fn greet() -> &'static str { \"new\" }\n".to_string(),
        generated_header: true,
    }];

    let (drifted, stats) = drifted_managed_paths_with(&changed, dir.path(), &drift_test_config(), &|_tool| false);

    assert_eq!(
        drifted,
        vec![dir.path().join("lib.rs").display().to_string()],
        "a genuinely stale .rs file must be REPORTED with poly absent -- this is the finding the \
         alef#458 gate suppressed on the no-poly CI leg"
    );
    assert_eq!(
        stats,
        FormatDriftStats {
            content_verified_paths: HashSet::from([dir.path().join("lib.rs")]),
            ..FormatDriftStats::default()
        }
    );
}

/// THE MEASUREMENT that licensed dropping the `poly_available` gate from
/// [`render_predicts_final_bytes`]'s `.rs` arm (alef#465 vs alef#458), and the regression test
/// that keeps that licence valid.
///
/// The gate existed because `alef all` wrote Rust bindings BEFORE the scaffold stage emitted
/// `rustfmt.toml`, so on a first run the bindings landed unformatted while an in-memory
/// re-render -- which resolves `rustfmt.toml` fresh -- predicted formatted bytes. With poly
/// absent nothing repaired the disk copy, so the prediction was wrong and the fast path
/// manufactured a false drift finding.
///
/// This drives a real, from-scratch first `alef all` (no committed `rustfmt.toml`) with `poly`
/// made to look absent for the run's duration -- without that guard `alef all`'s own whole-tree
/// `poly fmt --fix` pass would repair the bytes regardless of the write-time ordering, and this
/// test would pass for the wrong reason -- and then asserts byte equality between every marked
/// `.rs` file on disk and a fresh [`crate::cli::pipeline::normalize_content`] render of those
/// same bytes. That render is the exact half of the fast-path prediction the gate distrusted,
/// so equality is what makes the ungated `.rs` arm honest; should this ever go red, the gate
/// has to come back rather than the assertion being relaxed.
///
/// `compared > 0` is asserted separately and deliberately: a run that generated no marked `.rs`
/// file at all would satisfy every byte comparison vacuously and render identically to a real
/// pass (the `prove-the-check-fired` rule). ~keep
#[test]
fn rust_binding_bytes_on_disk_match_a_fresh_render_with_no_poly() {
    if !crate::cli::pipeline::is_tool_available("rustfmt") {
        return;
    }

    let temp = tempfile::tempdir().expect("tempdir");
    let root = temp.path().canonicalize().unwrap_or_else(|_| temp.path().to_path_buf());
    write_first_run_fixture(&root);
    assert!(
        !root.join("rustfmt.toml").exists(),
        "fixture setup: this run must start with no committed rustfmt.toml, or it is not \
         exercising a project's first `alef all` run at all"
    );

    let _cargo_guard = crate::test_support::RealCargoGuard::acquire();
    let _no_poly = crate::test_support::PathWithoutToolGuard::exclude("poly");
    let _cwd = crate::test_support::CwdGuard::enter(&root);

    let context = crate::bin_cli::dispatch::DispatchContext {
        config_path: root.join("alef.toml"),
        crate_filter: Vec::new(),
    };
    crate::bin_cli::all_commands::handle(first_run_all_command(), &context)
        .expect("alef all must succeed against a plain python fixture");

    let mut compared = 0usize;
    let mut mismatches = Vec::new();
    for entry in walkdir::WalkDir::new(&root).into_iter().filter_map(Result::ok) {
        let path = entry.path();
        if !path.is_file() || path.extension().and_then(|extension| extension.to_str()) != Some("rs") {
            continue;
        }
        let Ok(disk) = std::fs::read_to_string(path) else {
            continue;
        };
        if !crate::core::hash::content_has_alef_marker(&disk) {
            continue;
        }
        compared += 1;
        let rerendered = crate::cli::pipeline::normalize_content(&root, path, &disk);
        if rerendered != disk {
            mismatches.push(format!(
                "{}\n--- on disk ---\n{}\n--- fresh render ---\n{}",
                path.display(),
                first_differing_lines(&disk, &rerendered),
                first_differing_lines(&rerendered, &disk)
            ));
        }
    }

    assert!(
        compared > 0,
        "no marked .rs file was produced by this run, so every byte comparison above was \
         vacuous -- this check examined nothing"
    );
    assert!(
        mismatches.is_empty(),
        "{compared} marked .rs file(s) compared; {} differ from a fresh in-memory render on a \
         first run with no poly, so the .rs fast-path prediction is still unsound:\n{}",
        mismatches.len(),
        mismatches.join("\n\n")
    );
}

/// First few lines of `left` from the point it stops matching `right`, for the diff excerpt the
/// assertion above prints. Whole-file dumps of generated bindings are unreadable in test output.
fn first_differing_lines(left: &str, right: &str) -> String {
    let start = left
        .lines()
        .zip(right.lines())
        .position(|(l, r)| l != r)
        .unwrap_or_else(|| left.lines().count().min(right.lines().count()));
    left.lines().skip(start).take(6).collect::<Vec<_>>().join("\n")
}

const FIRST_RUN_FIXTURE_SOURCE: &str = "pub fn compute_widget_totals(\n    \
    alpha: String,\n    bravo: String,\n    charlie: String,\n    delta: String,\n    echo: String,\n    \
    foxtrot: String,\n    golf: String,\n    hotel: String,\n    india: String,\n    juliett: String,\n\
) -> String {\n    \
    format!(\"{alpha}{bravo}{charlie}{delta}{echo}{foxtrot}{golf}{hotel}{india}{juliett}\")\n\
}\n";

const FIRST_RUN_FIXTURE_CARGO_TOML: &str = "[package]\nname = \"test-lib\"\nversion = \"0.1.0\"\nedition = \"2024\"\n";

const FIRST_RUN_FIXTURE_ALEF_TOML: &str = r#"
[workspace]
languages = ["python"]

[[crates]]
name = "test-lib"
sources = ["src/lib.rs"]
version_from = "Cargo.toml"

[crates.python]
module_name = "test_lib"

[crates.python.stubs]
output = "packages/python/test_lib"
"#;

fn write_first_run_fixture(root: &std::path::Path) {
    std::fs::create_dir_all(root.join("src")).expect("create fixture src directory");
    std::fs::write(root.join("src/lib.rs"), FIRST_RUN_FIXTURE_SOURCE).expect("write fixture source");
    std::fs::write(root.join("Cargo.toml"), FIRST_RUN_FIXTURE_CARGO_TOML).expect("write fixture Cargo.toml");
    std::fs::write(root.join("alef.toml"), FIRST_RUN_FIXTURE_ALEF_TOML).expect("write fixture alef.toml");
}

fn first_run_all_command() -> crate::bin_cli::args::Commands {
    crate::bin_cli::args::Commands::All {
        clean: false,
        clobber_create_once_seeds: false,
        strict: false,
        skip_frb: false,
        skip_snippet_validation: false,
        skip_compile: true,
    }
}