alef 0.78.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
use anyhow::Result;
use std::path::PathBuf;
use std::process;

use crate::cli::{cache, dispatch, pipeline};

use super::args::*;
use super::dispatch::DispatchContext;
use super::helpers::*;
use super::verify_orphans;

mod docs;
mod generate;
mod verify;
mod verify_flags;

use verify_flags::refuse_unimplemented_verify_flags;

pub(crate) fn handle(command: Commands, context: &DispatchContext) -> Result<Option<Commands>> {
    let config_path = &context.config_path;
    match command {
        Commands::Extract { output } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            for resolved_cfg in &crates_to_process {
                let effective_output = if multi {
                    output
                        .parent()
                        .unwrap_or(std::path::Path::new("."))
                        .join(format!("{}.ir.json", resolved_cfg.name))
                } else {
                    output.clone()
                };
                let api = pipeline::extract(resolved_cfg, config_path, false)?;
                if let Some(parent) = effective_output.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                std::fs::write(&effective_output, serde_json::to_string_pretty(&api)?)?;
                if multi {
                    tracing::info!("[{}] Wrote IR to {}", resolved_cfg.name, effective_output.display());
                } else {
                    tracing::info!("Wrote IR to {}", effective_output.display());
                }
            }
            Ok(None)
        }
        Commands::Generate {
            lang,
            clean,
            skip_frb,
            strict,
            skip_compile,
        } => generate::handle_generate(lang, clean, skip_frb, strict, skip_compile, config_path, context),
        Commands::Stubs { lang } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            let base_dir = std::env::current_dir()?;
            let mut grand_total: usize = 0;
            for resolved_cfg in &crates_to_process {
                let languages = resolve_languages(resolved_cfg, lang.as_deref())?;
                if multi {
                    tracing::info!(
                        "[{}] Generating type stubs for: {}",
                        resolved_cfg.name,
                        format_languages(&languages)
                    );
                } else {
                    tracing::info!("Generating type stubs for: {}", format_languages(&languages));
                }
                let api = pipeline::extract(resolved_cfg, config_path, false)?;
                let files = pipeline::generate_stubs(&api, resolved_cfg, &languages)?;
                let sources_hash = cache::sources_hash(&resolved_cfg.sources)?;

                let hashes: Vec<(String, String)> = files
                    .iter()
                    .flat_map(|(_, fs)| {
                        fs.iter().map(|f| {
                            (
                                base_dir.join(&f.path).display().to_string(),
                                cache::hash_content(&f.content),
                            )
                        })
                    })
                    .collect();

                let cache_key = format!("{}.stubs", resolved_cfg.name);
                let stored = cache::read_generation_hashes(&cache_key).unwrap_or_default();
                let all_match = !hashes.is_empty() && hashes.iter().all(|(p, h)| stored.get(p) == Some(h));

                if all_match {
                    if multi {
                        tracing::info!("[{}] Stubs up to date (skipping)", resolved_cfg.name);
                    } else {
                        tracing::info!("Stubs up to date (skipping)");
                    }
                    continue;
                }

                let count = pipeline::write_files(&files, &base_dir)?;
                let _ = cache::write_generation_hashes(&cache_key, &hashes);

                // `alef stubs` exposes no `--strict` flag, so it always takes the lenient
                // default -- but it goes through the same reporting entry point as every other
                // surface, so a skipped formatter is named in the run output instead of being
                // dropped into a warning nothing collects. ~keep
                pipeline::format_generated_reporting(resolved_cfg, &base_dir, None, false)?;

                let stub_paths: std::collections::HashSet<PathBuf> = files
                    .iter()
                    .flat_map(|(_, fs)| pipeline::stampable_output_paths(fs, &base_dir))
                    .collect();
                let alef_toml_bytes = cache::read_alef_toml_bytes(config_path);
                pipeline::finalize_hashes_after_tree_format(&stub_paths, &base_dir, &sources_hash, &alef_toml_bytes)?;
                grand_total += count;
            }
            tracing::info!("Generated {grand_total} stub files");
            Ok(None)
        }
        Commands::Scaffold { lang } => {
            let (workspace, resolved) = load_config(config_path)?;
            crate::bin_cli::version_pin_sync::sync_alef_version_pin(
                &workspace,
                config_path,
                crate::bin_cli::build_info::running_build_is_clean(),
            )?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            let base_dir = std::env::current_dir()?;

            let config_toml = std::fs::read_to_string(config_path)?;
            let mut grand_total: usize = 0;
            for resolved_cfg in &crates_to_process {
                let languages = resolve_languages(resolved_cfg, lang.as_deref())?;
                let api = pipeline::extract(resolved_cfg, config_path, false)?;
                // Runs regardless of the stage-cache check below: a manifest a prior scaffold run
                // could not prove ownership of (see `scaffold::repair`'s doc) stays broken forever
                // on a cache hit otherwise, since the cache records this run as complete even
                // though that one write was refused. ~keep
                crate::scaffold::repair_missing_cfg_binding_features(&api, resolved_cfg, &languages);
                let ir_json = serde_json::to_string(&api)?;
                let stage_hash = cache::compute_stage_hash(&ir_json, "scaffold", &config_toml, &[]);
                let sources_hash = cache::sources_hash(&resolved_cfg.sources)?;
                let alef_toml_bytes = cache::read_alef_toml_bytes(config_path);
                if cache::is_stage_cached(&resolved_cfg.name, "scaffold", &stage_hash) {
                    if multi {
                        tracing::info!("[{}] Scaffold up to date (cached)", resolved_cfg.name);
                    } else {
                        tracing::info!("Scaffold up to date (cached)");
                    }
                    continue;
                }
                if multi {
                    tracing::info!(
                        "[{}] Generating scaffolding for: {}",
                        resolved_cfg.name,
                        format_languages(&languages)
                    );
                } else {
                    tracing::info!("Generating scaffolding for: {}", format_languages(&languages));
                }
                let files = pipeline::scaffold(&api, resolved_cfg, &languages, config_path)?;
                let count = pipeline::write_scaffold_files(&files, &base_dir)?;
                let scaffold_paths = pipeline::stampable_output_paths(&files, &base_dir);
                pipeline::finalize_hashes(&scaffold_paths, &sources_hash, &alef_toml_bytes)?;
                // The stage manifest passed to `write_stage_hash` is deliberately every path
                // `pipeline::scaffold` returned, not `scaffold_paths`'s marker-filtered subset.
                // `is_stage_cached`'s disk-presence check (`cache::outputs_exist`) only ever
                // inspects paths recorded in that manifest, so a create-once seed file --
                // `generated_header: false`, unmarked by design so a hand-grown suite is never
                // clobbered on a later run -- was invisible to it. Deleting one left the "scaffold"
                // stage hash unchanged (source, config, and fixtures were untouched) and the cache
                // read as a hit, so `pipeline::scaffold`'s own create-if-absent logic never ran
                // again to replace it: the alef #C incident. Presence is a weaker claim than
                // ownership -- it only says "a path this stage is responsible for still exists",
                // which is exactly what a create-once file's absence should invalidate, independent
                // of whether alef may ever overwrite its content. ~keep
                let all_output_paths: Vec<PathBuf> = files.iter().map(|file| base_dir.join(&file.path)).collect();
                cache::write_stage_hash(&resolved_cfg.name, "scaffold", stage_hash.as_str(), &all_output_paths)?;
                grand_total += count;
            }

            pipeline::install_poly_hooks(&base_dir);

            // downstream crates can use `#[cfg_attr(alef, alef(skip))]` and
            // `#[cfg_attr(feature = "alef-meta", alef(since = "..."))]`
            match pipeline::ensure_workspace_alef_meta_check_cfg() {
                Ok(true) => tracing::info!(
                    "Patched Cargo.toml: added [workspace.lints.rust] unexpected_cfgs allowlist for alef and alef-meta"
                ),
                Ok(false) => {}
                Err(e) => tracing::warn!("could not patch workspace lints for alef/alef-meta: {e}"),
            }

            tracing::info!("Generated {grand_total} scaffold files");
            Ok(None)
        }
        Commands::Readme { lang } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            let base_dir = std::env::current_dir()?;
            let config_toml = std::fs::read_to_string(config_path)?;
            let mut grand_total: usize = 0;
            for resolved_cfg in &crates_to_process {
                let languages = crate::readme::expand_configured_readme_languages(
                    resolved_cfg,
                    &resolve_readme_languages(resolved_cfg, lang.as_deref())?,
                );
                let api = pipeline::extract(resolved_cfg, config_path, false)?;
                let ir_json = serde_json::to_string(&api)?;
                let stage_hash = cache::compute_stage_hash(&ir_json, "readme", &config_toml, &[]);
                let sources_hash = cache::sources_hash(&resolved_cfg.sources)?;
                let alef_toml_bytes = cache::read_alef_toml_bytes(config_path);
                if cache::is_stage_cached(&resolved_cfg.name, "readme", &stage_hash) {
                    if multi {
                        tracing::info!("[{}] READMEs up to date (cached)", resolved_cfg.name);
                    } else {
                        tracing::info!("READMEs up to date (cached)");
                    }
                    continue;
                }
                if multi {
                    tracing::info!(
                        "[{}] Generating READMEs for: {}",
                        resolved_cfg.name,
                        format_languages(&languages)
                    );
                } else {
                    tracing::info!("Generating READMEs for: {}", format_languages(&languages));
                }
                let files = pipeline::readme(&api, resolved_cfg, &languages)?;
                let count = pipeline::write_scaffold_files_with_overwrite(&files, &base_dir, true)?;
                let output_paths: Vec<PathBuf> = files
                    .iter()
                    .filter(|file| file.carries_alef_marker())
                    .map(|file| base_dir.join(&file.path))
                    .collect();
                let readme_paths = pipeline::stampable_output_paths(&files, &base_dir);
                pipeline::finalize_hashes(&readme_paths, &sources_hash, &alef_toml_bytes)?;
                cache::write_stage_hash(&resolved_cfg.name, "readme", stage_hash.as_str(), &output_paths)?;
                grand_total += count;
            }
            tracing::info!("Generated {grand_total} README files");
            Ok(None)
        }
        Commands::Docs {
            lang,
            output,
            skip_snippet_validation,
        } => docs::handle(config_path, context, lang, output, skip_snippet_validation),
        Commands::SyncVersions {
            bump,
            set,
            regen,
            skip_swift_checksum,
            release_date,
        } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            for resolved_cfg in &crates_to_process {
                if let Some(version) = &set {
                    if multi {
                        tracing::info!("[{}] Setting version to {version}", resolved_cfg.name);
                    } else {
                        tracing::info!("Setting version to {version}");
                    }
                    pipeline::set_version(resolved_cfg, version)?;
                }
                if multi {
                    tracing::info!("[{}] Syncing versions from Cargo.toml", resolved_cfg.name);
                } else {
                    tracing::info!("Syncing versions from Cargo.toml");
                }
                pipeline::sync_versions(
                    resolved_cfg,
                    config_path,
                    bump.as_deref(),
                    !regen,
                    skip_swift_checksum,
                    release_date.as_deref(),
                )?;
            }
            tracing::info!("Version sync complete");
            Ok(None)
        }
        Commands::Build { lang, release, strict } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            for resolved_cfg in &crates_to_process {
                let languages = resolve_languages(resolved_cfg, lang.as_deref())?;
                let profile = if release { "release" } else { "dev" };
                if multi {
                    tracing::info!(
                        "[{}] Building bindings ({profile}) for: {}",
                        resolved_cfg.name,
                        format_languages(&languages)
                    );
                } else {
                    tracing::info!("Building bindings ({profile}) for: {}", format_languages(&languages));
                }
                pipeline::build(resolved_cfg, &languages, release, strict)?;
            }
            tracing::info!("Build complete");
            Ok(None)
        }
        Commands::Fmt { lang: _ } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            let base_dir = std::env::current_dir()?;
            for resolved_cfg in &crates_to_process {
                if multi {
                    tracing::info!("[{}] Formatting generated output...", resolved_cfg.name);
                } else {
                    tracing::info!("Formatting generated output...");
                }
                pipeline::fmt(resolved_cfg, &base_dir)?;
            }
            tracing::info!("Format complete");
            Ok(None)
        }
        Commands::Lint { lang: _ } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            let base_dir = std::env::current_dir()?;
            for resolved_cfg in &crates_to_process {
                if multi {
                    tracing::info!("[{}] Linting generated output...", resolved_cfg.name);
                } else {
                    tracing::info!("Linting generated output...");
                }
                pipeline::lint(resolved_cfg, &base_dir)?;
            }
            tracing::info!("Lint complete");
            Ok(None)
        }
        Commands::Test { lang, e2e, coverage } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            for resolved_cfg in &crates_to_process {
                let languages = resolve_test_languages(resolved_cfg, lang.as_deref(), e2e)?;
                if multi {
                    tracing::info!(
                        "[{}] Running tests for: {}",
                        resolved_cfg.name,
                        format_languages(&languages)
                    );
                } else {
                    tracing::info!("Running tests for: {}", format_languages(&languages));
                }
                if e2e {
                    tracing::info!("  (with e2e tests)");
                }
                if coverage {
                    tracing::info!("  (with coverage)");
                }
                pipeline::test(resolved_cfg, &languages, e2e, coverage)?;
            }
            tracing::info!("Tests complete");
            Ok(None)
        }
        Commands::Setup { lang, timeout } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            for resolved_cfg in &crates_to_process {
                let languages = resolve_languages(resolved_cfg, lang.as_deref())?;
                if multi {
                    tracing::info!(
                        "[{}] Setting up dependencies for: {}",
                        resolved_cfg.name,
                        format_languages(&languages)
                    );
                } else {
                    tracing::info!("Setting up dependencies for: {}", format_languages(&languages));
                }
                pipeline::setup(resolved_cfg, &languages, timeout)?;
            }
            tracing::info!("Setup complete");
            Ok(None)
        }
        Commands::Clean { lang } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            for resolved_cfg in &crates_to_process {
                let languages = resolve_languages(resolved_cfg, lang.as_deref())?;
                if multi {
                    tracing::info!(
                        "[{}] Cleaning build artifacts for: {}",
                        resolved_cfg.name,
                        format_languages(&languages)
                    );
                } else {
                    tracing::info!("Cleaning build artifacts for: {}", format_languages(&languages));
                }
                pipeline::clean(resolved_cfg, &languages)?;
            }
            tracing::info!("Clean complete");
            Ok(None)
        }
        Commands::Update { lang, latest } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            let multi = dispatch::is_multi_crate(&crates_to_process);
            for resolved_cfg in &crates_to_process {
                let languages = resolve_languages(resolved_cfg, lang.as_deref())?;
                let mode = if latest { "latest" } else { "compatible" };
                if multi {
                    tracing::info!(
                        "[{}] Updating dependencies ({mode}) for: {}",
                        resolved_cfg.name,
                        format_languages(&languages)
                    );
                } else {
                    tracing::info!("Updating dependencies ({mode}) for: {}", format_languages(&languages));
                }
                pipeline::update(resolved_cfg, &languages, latest)?;
            }
            tracing::info!("Update complete");
            Ok(None)
        }
        Commands::Verify {
            exit_code: _,
            report_only,
            compile,
            lint,
            lang,
        } => {
            // ~keep `exit_code` is deliberately ignored: it is `hide = true` and documented as a
            // deprecated no-op because verification fails by default now. These three are not.
            // They are visible, documented as doing extra work ("Also run compilation check"),
            // and were destructured away — so `alef verify --compile` exited 0 having compiled
            // nothing, which is indistinguishable from a passing compile check. Refuse instead:
            // a flag that cannot be honored must not report success.
            refuse_unimplemented_verify_flags(compile, lint, lang.as_deref())?;
            verify::run(context, report_only)
        }
        Commands::Diff { exit_code } => {
            let (_workspace, resolved) = load_config(config_path)?;
            let crates_to_process = dispatch::select_crates(&resolved, &context.crate_filter)?;
            tracing::info!("Computing diff of generated bindings...");
            let base_dir = std::env::current_dir()?;
            let mut all_diffs: Vec<String> = Vec::new();
            // Unioned across every crate before the orphan diff runs below, exactly like
            // `Commands::Verify` above -- see that arm's `all_managed_paths` for why a file
            // legitimately owned by crate B must never look orphaned merely because crate A's
            // own managed surface doesn't mention it. ~keep
            let mut all_managed_paths: std::collections::HashSet<std::path::PathBuf> = std::collections::HashSet::new();
            for resolved_cfg in &crates_to_process {
                let languages = resolve_languages(resolved_cfg, None)?;
                let api = pipeline::extract(resolved_cfg, config_path, false)?;
                // `write_cache: false` -- `alef diff` is documented as "without writing" (see its
                // clap doc comment) and must stay read-only the same way `alef verify` does. Passing
                // `true` here regenerated bindings in memory only to preview a diff, yet still ran
                // `pipeline::generate`'s internal `write_lang_hash`, which unconditionally overwrites
                // `<lang>.manifest` with just this call's own file list -- discarding whatever fuller
                // manifest `alef generate`/`alef all` had folded in from later phases (public_api,
                // stubs, service API) via `write_lang_manifest`. For a backend whose core bindings
                // step emits only its Rust glue crate (python/node/ruby/elixir/php/wasm), every `alef
                // diff` run silently regressed `<lang>.manifest` back down to that one file. ~keep
                let bindings = pipeline::generate(&api, resolved_cfg, &languages, true, config_path, false)?;
                let stubs = pipeline::generate_stubs(&api, resolved_cfg, &languages)?;
                let scaffold = pipeline::scaffold(&api, resolved_cfg, &languages, config_path)?;
                all_diffs.extend(pipeline::diff_files(&bindings, &base_dir)?);
                all_diffs.extend(pipeline::diff_files(&stubs, &base_dir)?);
                all_diffs.extend(pipeline::diff_files(
                    &[(crate::core::config::Language::Rust, scaffold)],
                    &base_dir,
                )?);
                // `alef diff` is documented as a preview of what `alef generate` would do, and a
                // real generate also sweeps orphans (`pipeline::generate_sweep_roots`,
                // `src/cli/pipeline/generate/orphans.rs`) -- a file the current run's backends
                // would no longer produce. Before this, `alef diff` had no way to preview that
                // impending removal at all: it only ever unioned `pipeline::diff_files` over
                // bindings/stubs/scaffold, never the orphan sweep `alef verify` already runs. This
                // reuses `find_missing_and_frozen_generated_files` purely for its `managed_paths`
                // side effect -- the same full-surface regeneration `Commands::Verify` above pays
                // for the identical reason -- and reports through
                // `verify_orphans::find_orphaned_generated_files`, never a second orphan-finding
                // implementation. ~keep
                let found =
                    find_missing_and_frozen_generated_files(&languages, &api, resolved_cfg, config_path, &base_dir)?;
                all_managed_paths.extend(found.managed_paths);
            }
            let orphan_generated_files = verify_orphans::find_orphaned_generated_files(&base_dir, &all_managed_paths);

            if all_diffs.is_empty() && orphan_generated_files.is_empty() {
                crate::bin_cli::output::line("No changes detected.");
            } else {
                if !all_diffs.is_empty() {
                    crate::bin_cli::output::line("Files that would change:");
                    for diff in &all_diffs {
                        crate::bin_cli::output::line(format_args!("  {diff}"));
                    }
                }
                if !orphan_generated_files.is_empty() {
                    crate::bin_cli::output::line(
                        "Files that would be removed (orphaned generated files a regeneration would sweep -- \
                         alef never deletes automatically; review each and delete by hand if genuinely stale):",
                    );
                    for path in &orphan_generated_files {
                        crate::bin_cli::output::line(format_args!("  {path}"));
                    }
                }
                if exit_code {
                    process::exit(1);
                }
            }
            Ok(None)
        }
        other => Ok(Some(other)),
    }
}

/// Fail `alef verify` when a record alef requires to be committed exists on disk but git
/// does not track it.
///
/// Kept separate from [`super::verify_outcome::ensure_success`] because the remedy is
/// different in kind: nothing is stale, nothing regenerates it, a human has to `git add`
/// the file -- so folding it into "generated bindings, versions, or snippet coverage are
/// out of date" would name the wrong fix. The message therefore lists every offending
/// record and the exact command, because the notice this replaces was ignored precisely
/// for being unspecific and unactionable.
///
/// `report_only` short-circuits after the caller has already printed the records, matching
/// how every other verify failure downgrades to a report. ~keep
pub(super) fn ensure_required_records_tracked(untracked: &[&'static str], report_only: bool) -> Result<()> {
    if report_only || untracked.is_empty() {
        return Ok(());
    }
    anyhow::bail!(
        "required alef records exist but git does not track them: {names}. Fix with `git add {names_spaced}` \
         and commit them -- until then this verification passes only on the machine holding the uncommitted \
         files, and a fresh clone or CI has neither the scaffold protection nor a correct orphan picture",
        names = untracked.join(", "),
        names_spaced = untracked.join(" "),
    )
}

/// Fail `alef verify` when a crate's last generation run started but never finished --
/// `cache::generation_record::mark_generation_in_progress` is written before the first
/// mutation of a run and only cleared on success, so a marker still present here means the
/// process that wrote it died mid-flight (alef#268). Kept as a distinct gate, with its own
/// message, for the same reason [`ensure_required_records_tracked`] is: this is not staleness
/// and `alef generate` is not automatically the fix a reader would infer from "out of date" --
/// rerunning is correct, but the diagnosis has to say why, or it reads exactly like the
/// missing-file staleness report this gate exists to distinguish from. `report_only`
/// downgrades to a report, matching every other verify failure. ~keep
pub(super) fn ensure_generation_completed(incomplete_crates: &[String], report_only: bool) -> Result<()> {
    if report_only || incomplete_crates.is_empty() {
        return Ok(());
    }
    anyhow::bail!(
        "the last generation run did not complete for: {names} -- it was interrupted before \
         finishing. Rerun `alef all`/`alef generate` for the affected crate(s); this is not \
         ordinary staleness, and any missing/frozen findings already reported for these crates \
         may be an artifact of the unfinished run rather than drift",
        names = incomplete_crates.join(", "),
    )
}

#[cfg(test)]
mod format_scope_tests;
#[cfg(test)]
mod post_build_failure_stamp_tests;
#[cfg(test)]
mod post_build_format_order_tests;
#[cfg(test)]
mod strict_formatting_tests;
#[cfg(test)]
mod tests;