haz-cli 0.2.0

Command-line task runner: tracks task DAGs across a workspace of projects, executes them with caching.
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
//! `haz cache` subcommands per `CACHE-021` / `CACHE-022` /
//! `AUX-017`..`AUX-027`.
//!
//! - [`clear`] backs `haz cache clear`: an unconditional reset of
//!   `<workspace_root>/.haz/cache`. Subsequent lookups against
//!   the same workspace are misses until new entries are stored.
//! - [`clean`] backs `haz cache clean [--soft] [--max-age <D>]
//!   [--max-size <B>] [--dry-run]`: composable reclamation of
//!   objectively-stale entries plus age- / size-bounded
//!   eviction (`CACHE-022`, `AUX-022`..`AUX-027`). The executor
//!   merges CLI flags with workspace `cache.clean.*` defaults
//!   (`AUX-025`) and enforces the "at least one mode" rule
//!   (`AUX-022`).
//! - [`info`] backs `haz cache info`: a read-only walk that
//!   classifies entries and reports counts, total bytes, and
//!   schema-prefix breakdown without mutating the cache root.
//!
//! All three subcommands first load the workspace via
//! `crate::workspace_load::load_workspace` to locate the
//! workspace root. The cache subcommand surface is independent of
//! the bearing-project concept (`EXEC-022`) and ignores cwd
//! beyond using it as the discovery starting point. A future
//! revision MAY expose a discovery-only fast path so the cache
//! commands succeed against a workspace with broken `haz.yml`
//! files; for v1, a parseable workspace is required.

use std::io::{self, Write};
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

use haz_cache::clean::{CleanOptions, CleanReport, EvictionMode};
use haz_cache::info::CacheInfoReport;
use haz_cache::manifest::HashFunctionLabel;
use haz_domain::settings::cache_clean::CacheCleanSettings;
use miette::{IntoDiagnostic, Result, WrapErr, miette};

use crate::cli::CacheCleanArgs;
use crate::context::Context;

/// Execute `haz cache clear` against `cwd`.
///
/// Returns 0 on success. Errors propagate as miette diagnostics
/// (workspace-load failure, filesystem failure during the
/// recursive removal).
///
/// # Errors
///
/// Returns a [`miette::Report`] for workspace-load or
/// invalidation failures.
pub fn clear(ctx: &Context) -> Result<i32> {
    let cache = ctx.cache_writer();
    cache
        .clear()
        .into_diagnostic()
        .wrap_err("cache clear failed")?;
    let mut out = io::stdout().lock();
    writeln!(out, "cache cleared.")
        .into_diagnostic()
        .wrap_err("failed to write confirmation")?;
    Ok(0)
}

/// Execute `haz cache clean` against `cwd` with the supplied CLI
/// args.
///
/// Resolves the effective mode set by combining `args` with
/// workspace `cache.clean.*` defaults per `AUX-025` (CLI overrides
/// workspace), enforces the `AUX-022` "at least one mode" rule,
/// runs the unified `CacheWriter::clean`, and emits the `AUX-024`
/// report.
///
/// # Errors
///
/// Returns a [`miette::Report`] on workspace-load failure, on a
/// no-effective-mode invocation, or when the cache root itself
/// cannot be read (the only fatal `clean` filesystem error per
/// `AUX-028`). Best-effort per-item failures are NOT returned as a
/// report: they are printed to stderr and yield the
/// [`EXIT_INTERNAL_OR_CONFIG_ERROR`](crate::EXIT_INTERNAL_OR_CONFIG_ERROR)
/// exit class per `AUX-027`, after the `AUX-024` report is emitted.
pub fn clean(ctx: &Context, args: &CacheCleanArgs) -> Result<i32> {
    let opts = resolve_clean_options(
        args,
        &ctx.workspace().settings.cache.clean,
        system_now_unix(),
    )?;
    let cache = ctx.cache_writer();
    let outcome = cache
        .clean(&opts)
        .into_diagnostic()
        .wrap_err("cache clean failed")?;
    let mut out = io::stdout().lock();
    print_clean_report(&opts, &outcome.report, &mut out)
        .into_diagnostic()
        .wrap_err("failed to write clean report")?;
    drop(out);

    if outcome.failures.is_empty() {
        return Ok(0);
    }

    // `AUX-028`: the report above already described what was
    // reclaimed; the per-item failures go to stderr and the run
    // exits in the `EXEC-021` config-error class per `AUX-027`.
    let mut err = io::stderr().lock();
    for failure in &outcome.failures {
        writeln!(err, "cache clean: {failure}")
            .into_diagnostic()
            .wrap_err("failed to write clean failure")?;
    }
    Ok(crate::EXIT_INTERNAL_OR_CONFIG_ERROR)
}

/// Merge CLI flags with workspace defaults per `AUX-025` and
/// enforce the `AUX-022` "at least one mode" rule.
fn resolve_clean_options(
    args: &CacheCleanArgs,
    defaults: &CacheCleanSettings,
    now_unix: u64,
) -> Result<CleanOptions> {
    let max_age = args.max_age.or(defaults.max_age);
    let max_size = args.max_size.or(defaults.max_size);
    if !args.soft && max_age.is_none() && max_size.is_none() {
        return Err(miette!(
            "haz cache clean requires at least one mode: --soft, --max-age <DURATION>, or --max-size <BYTES> (AUX-022; workspace cache.clean.max_age / max_size MAY supply a default per AUX-025)"
        ));
    }
    Ok(CleanOptions {
        soft: args.soft,
        max_age,
        max_size,
        dry_run: args.dry_run,
        now_unix,
    })
}

fn system_now_unix() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

/// Render an `AUX-024` clean report to `out`.
///
/// The format is implementation-defined within the `AUX-024`
/// requirements: every required category appears as its own
/// labelled line, and the per-entry dry-run plan is emitted only
/// when [`CleanOptions::dry_run`] is set and the eviction set is
/// non-empty (so the section header never dangles).
fn print_clean_report(
    opts: &CleanOptions,
    report: &CleanReport,
    out: &mut impl Write,
) -> io::Result<()> {
    if opts.dry_run {
        writeln!(out, "dry-run: AUX-024 plan only, no entries removed.")?;
    }
    writeln!(out, "entries inspected: {}", report.inspected)?;
    let (soft_label, age_label, size_label) = if opts.dry_run {
        (
            "would evict --soft",
            "would evict --max-age",
            "would evict --max-size",
        )
    } else {
        ("evicted --soft", "evicted --max-age", "evicted --max-size")
    };
    writeln!(out, "{}: {}", soft_label, report.evicted_by_soft)?;
    writeln!(out, "{}: {}", age_label, report.evicted_by_max_age)?;
    writeln!(out, "{}: {}", size_label, report.evicted_by_max_size)?;
    let tmp_verb = if opts.dry_run { "noted" } else { "removed" };
    writeln!(
        out,
        "orphan tmp directories {tmp_verb}: {}",
        report.removed_tmp_dirs,
    )?;
    writeln!(
        out,
        "orphan restore directories {tmp_verb}: {}",
        report.removed_restore_dirs,
    )?;
    let bytes_label = if opts.dry_run {
        "bytes projected"
    } else {
        "bytes reclaimed"
    };
    writeln!(out, "{bytes_label}: {}", report.bytes_reclaimed)?;
    if opts.dry_run && !report.evicted_entries.is_empty() {
        writeln!(out, "dry-run plan:")?;
        for e in &report.evicted_entries {
            writeln!(
                out,
                "  {} created_at={} footprint={} mode={}",
                e.key_hex_prefix,
                e.created_at_unix,
                e.footprint,
                mode_label_name(e.matched_mode),
            )?;
        }
    }
    Ok(())
}

fn mode_label_name(m: EvictionMode) -> &'static str {
    match m {
        EvictionMode::Soft => "--soft",
        EvictionMode::MaxAge => "--max-age",
        EvictionMode::MaxSize => "--max-size",
    }
}

/// Execute `haz cache info` against `cwd`.
///
/// Loads the workspace to locate the cache root, walks the cache
/// in read-only mode via `CacheReader::info`, and prints the
/// classification per `AUX-019`. Returns 0 on success.
///
/// # Errors
///
/// Returns a [`miette::Report`] for workspace-load or filesystem
/// read failures during the cache walk.
pub fn info(ctx: &Context) -> Result<i32> {
    let cache = ctx.cache_reader();
    let report = cache
        .info()
        .into_diagnostic()
        .wrap_err("cache info walk failed")?;
    let mut out = io::stdout().lock();
    print_info_report(cache.cache_root(), &report, &mut out)
        .into_diagnostic()
        .wrap_err("failed to write cache info report")?;
    Ok(0)
}

/// Render an [`AUX-019`] info report to `out`.
///
/// The format is implementation-defined; this v1 lists each
/// category on its own line. The `by schema` section is omitted
/// entirely when there are no well-formed entries to break down.
fn print_info_report(
    cache_root: &Path,
    report: &CacheInfoReport,
    out: &mut impl Write,
) -> io::Result<()> {
    writeln!(out, "cache root: {}", cache_root.display())?;
    writeln!(out, "well-formed entries: {}", report.well_formed_entries)?;
    writeln!(out, "corrupt entries: {}", report.corrupt_entries)?;
    writeln!(out, "orphan tmp directories: {}", report.orphan_tmp_dirs)?;
    writeln!(
        out,
        "orphan restore directories: {}",
        report.orphan_restore_dirs,
    )?;
    writeln!(out, "total bytes: {}", report.total_bytes)?;
    if !report.by_schema.is_empty() {
        writeln!(out, "by schema:")?;
        for ((rev, hash), count) in &report.by_schema {
            writeln!(
                out,
                "  (revision={rev}, hash={}): {count}",
                hash_label_name(*hash),
            )?;
        }
    }
    Ok(())
}

/// Map a [`HashFunctionLabel`] to the spec's canonical lowercase
/// string (`CACHE-002` registry).
fn hash_label_name(label: HashFunctionLabel) -> &'static str {
    match label {
        HashFunctionLabel::Blake3 => "blake3",
        HashFunctionLabel::Sha256 => "sha256",
    }
}

#[cfg(test)]
mod tests {
    use super::{
        clean, clear, hash_label_name, info, mode_label_name, print_clean_report,
        print_info_report, resolve_clean_options,
    };
    use crate::cli::CacheCleanArgs;
    use crate::context::Context;
    use haz_cache::clean::{CleanOptions, CleanReport, EvictedEntry, EvictionMode};
    use haz_cache::info::CacheInfoReport;
    use haz_cache::manifest::HashFunctionLabel;
    use haz_domain::settings::cache_clean::CacheCleanSettings;
    use haz_domain::settings::cache_clean::max_age::MaxAge;
    use haz_domain::settings::cache_clean::max_size::MaxSize;
    use miette::Result;
    use std::collections::BTreeMap;
    use std::fs;
    use std::path::{Path, PathBuf};

    fn run_clear(cwd: &Path) -> Result<i32> {
        clear(&Context::open(cwd)?)
    }

    fn run_clean(cwd: &Path, args: &CacheCleanArgs) -> Result<i32> {
        clean(&Context::open(cwd)?, args)
    }

    fn run_info(cwd: &Path) -> Result<i32> {
        info(&Context::open(cwd)?)
    }

    fn write_file(path: &Path, contents: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, contents).unwrap();
    }

    /// Build an explicit-mode workspace `load_workspace` accepts.
    ///
    /// Explicit mode (`.haz/workspace.yml`) rather than implicit
    /// mode (`.git` marker), because cache tests pre-populate
    /// `.haz/cache/...`; with implicit mode, discovery sees the
    /// `.haz/` directory and tries to read a `workspace.yml` that
    /// isn't there. Explicit mode keeps `.haz/` legitimately used
    /// by the workspace, so a sibling `.haz/cache/` subtree does
    /// not confuse discovery.
    fn write_workspace(root: &Path) {
        write_file(&root.join(".haz/workspace.yml"), "projects:\n  - /lib\n");
        write_file(
            &root.join("lib/haz.yml"),
            "name: lib\ntasks:\n  default:\n    command: [\"true\"]\n",
        );
    }

    #[test]
    fn clear_on_fresh_workspace_is_noop_and_exits_zero() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_workspace(root);
        let code = run_clear(root).unwrap();
        assert_eq!(code, 0);
        // Cache root was never created; idempotent no-op behaviour
        // of `Cache::clear` is what makes this OK.
        assert!(!root.join(".haz/cache").exists());
    }

    #[test]
    fn clear_removes_an_existing_cache_root() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_workspace(root);
        // Pre-populate the cache root with a sentinel file; clear
        // MUST take the whole subtree out.
        let sentinel = root.join(".haz/cache/ab/sentinel");
        write_file(&sentinel, "anything");
        assert!(sentinel.exists());
        let code = run_clear(root).unwrap();
        assert_eq!(code, 0);
        assert!(!root.join(".haz/cache").exists());
    }

    #[test]
    fn clear_does_not_touch_files_outside_cache_root() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_workspace(root);
        write_file(&root.join("docs/keep.md"), "important");
        write_file(&root.join(".haz/cache/ab/c"), "stale");
        let code = run_clear(root).unwrap();
        assert_eq!(code, 0);
        assert!(!root.join(".haz/cache").exists());
        assert_eq!(
            fs::read_to_string(root.join("docs/keep.md")).unwrap(),
            "important"
        );
    }

    fn soft_only_args() -> CacheCleanArgs {
        CacheCleanArgs {
            soft: true,
            ..CacheCleanArgs::default()
        }
    }

    #[test]
    fn clean_soft_on_fresh_workspace_reports_all_zero() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_workspace(root);
        let code = run_clean(root, &soft_only_args()).unwrap();
        assert_eq!(code, 0);
    }

    #[test]
    fn clean_soft_reclaims_a_restore_staging_directory() {
        // A `.restore-<key>-<rand>` directory under the cache root
        // is the simplest "objectively stale" artefact for a
        // black-box test: it doesn't require constructing a valid
        // manifest, only creating the staging directory shape.
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_workspace(root);
        let staging = root.join(".haz/cache/.restore-abcdef-1234");
        write_file(&staging.join("leftover.bin"), "scratch");
        assert!(staging.exists());
        let code = run_clean(root, &soft_only_args()).unwrap();
        assert_eq!(code, 0);
        assert!(!staging.exists());
    }

    #[test]
    fn clean_rejects_invocation_with_no_effective_mode() {
        // AUX-022: a bare `haz cache clean` against a workspace
        // with no `cache.clean.*` defaults MUST be rejected with
        // a typed CLI error.
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_workspace(root);
        let err = run_clean(root, &CacheCleanArgs::default()).unwrap_err();
        let rendered = format!("{err}");
        assert!(
            rendered.contains("at least one mode"),
            "AUX-022 rejection diagnostic must surface the requirement: {rendered}",
        );
    }

    #[test]
    fn clean_dry_run_under_soft_leaves_restore_staging_in_place() {
        // AUX-024: `--dry-run` MUST compute the eviction set but
        // make no on-disk changes. Soft pass would normally
        // reclaim the staging directory; under dry-run it stays.
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_workspace(root);
        let staging = root.join(".haz/cache/.restore-abcdef-1234");
        write_file(&staging.join("leftover.bin"), "scratch");

        let args = CacheCleanArgs {
            soft: true,
            dry_run: true,
            ..CacheCleanArgs::default()
        };
        let code = run_clean(root, &args).unwrap();
        assert_eq!(code, 0);
        assert!(
            staging.exists(),
            "dry-run must not remove the restore staging directory",
        );
    }

    #[test]
    fn clean_uses_workspace_default_max_age_when_cli_silent() {
        // AUX-025: workspace `cache.clean.max_age` MAY supply the
        // mode that satisfies AUX-022 when the CLI is silent.
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_file(
            &root.join(".haz/workspace.yml"),
            "projects:\n  - /lib\ncache:\n  clean:\n    max_age: 30d\n",
        );
        write_file(
            &root.join("lib/haz.yml"),
            "name: lib\ntasks:\n  default:\n    command: [\"true\"]\n",
        );
        // No CLI mode flags set; the workspace default supplies it.
        let code = run_clean(root, &CacheCleanArgs::default()).unwrap();
        assert_eq!(code, 0);
    }

    // ---- resolve_clean_options ----

    fn defaults_with(max_age: Option<&str>, max_size: Option<&str>) -> CacheCleanSettings {
        CacheCleanSettings {
            max_age: max_age.map(|s| MaxAge::parse(s).unwrap()),
            max_size: max_size.map(|s| MaxSize::parse(s).unwrap()),
        }
    }

    #[test]
    fn resolve_clean_options_rejects_no_effective_mode() {
        let err = resolve_clean_options(
            &CacheCleanArgs::default(),
            &CacheCleanSettings::default(),
            0,
        )
        .unwrap_err();
        let rendered = format!("{err}");
        assert!(
            rendered.contains("at least one mode"),
            "AUX-022 rejection diagnostic must surface the requirement: {rendered}",
        );
    }

    #[test]
    fn resolve_clean_options_falls_back_to_workspace_when_cli_silent() {
        let defaults = defaults_with(Some("30d"), Some("1GB"));
        let opts = resolve_clean_options(&CacheCleanArgs::default(), &defaults, 12345).unwrap();
        assert_eq!(opts.max_age, defaults.max_age);
        assert_eq!(opts.max_size, defaults.max_size);
        assert!(!opts.soft);
        assert!(!opts.dry_run);
        assert_eq!(opts.now_unix, 12345);
    }

    #[test]
    fn resolve_clean_options_cli_overrides_workspace_defaults() {
        // AUX-025: an explicit CLI flag overrides the workspace
        // default for that mode (the OTHER mode still inherits
        // its default when CLI is silent for it).
        let defaults = defaults_with(Some("30d"), Some("1GB"));
        let cli_age = MaxAge::parse("7d").unwrap();
        let args = CacheCleanArgs {
            max_age: Some(cli_age),
            ..CacheCleanArgs::default()
        };
        let opts = resolve_clean_options(&args, &defaults, 0).unwrap();
        assert_eq!(opts.max_age, Some(cli_age));
        assert_eq!(opts.max_size, defaults.max_size);
    }

    #[test]
    fn resolve_clean_options_soft_alone_satisfies_aux_022() {
        let opts =
            resolve_clean_options(&soft_only_args(), &CacheCleanSettings::default(), 0).unwrap();
        assert!(opts.soft);
        assert!(opts.max_age.is_none());
        assert!(opts.max_size.is_none());
    }

    // ---- print_clean_report ----

    fn sample_report() -> CleanReport {
        CleanReport {
            inspected: 7,
            evicted_by_soft: 2,
            evicted_by_max_age: 3,
            evicted_by_max_size: 1,
            removed_tmp_dirs: 1,
            removed_restore_dirs: 2,
            bytes_reclaimed: 4096,
            evicted_entries: vec![
                EvictedEntry {
                    key_hex_prefix: "deadbeef".to_owned(),
                    created_at_unix: 100,
                    footprint: 512,
                    matched_mode: EvictionMode::Soft,
                },
                EvictedEntry {
                    key_hex_prefix: "cafef00d".to_owned(),
                    created_at_unix: 200,
                    footprint: 1024,
                    matched_mode: EvictionMode::MaxAge,
                },
            ],
        }
    }

    fn render(opts: &CleanOptions, report: &CleanReport) -> String {
        let mut out = Vec::<u8>::new();
        print_clean_report(opts, report, &mut out).unwrap();
        String::from_utf8(out).unwrap()
    }

    #[test]
    fn print_clean_report_renders_required_aux_024_categories() {
        let opts = CleanOptions {
            soft: true,
            ..CleanOptions::default()
        };
        let rendered = render(&opts, &sample_report());
        assert!(
            rendered.contains("entries inspected: 7"),
            "missing inspected line: {rendered}",
        );
        assert!(
            rendered.contains("evicted --soft: 2"),
            "missing soft line: {rendered}",
        );
        assert!(
            rendered.contains("evicted --max-age: 3"),
            "missing max-age line: {rendered}",
        );
        assert!(
            rendered.contains("evicted --max-size: 1"),
            "missing max-size line: {rendered}",
        );
        assert!(
            rendered.contains("orphan tmp directories removed: 1"),
            "missing tmp line: {rendered}",
        );
        assert!(
            rendered.contains("orphan restore directories removed: 2"),
            "missing restore line: {rendered}",
        );
        assert!(
            rendered.contains("bytes reclaimed: 4096"),
            "missing bytes line: {rendered}",
        );
        assert!(
            !rendered.contains("dry-run"),
            "non-dry-run output must not mention dry-run: {rendered}",
        );
    }

    #[test]
    fn print_clean_report_lists_per_entry_detail_under_dry_run() {
        let opts = CleanOptions {
            soft: true,
            dry_run: true,
            ..CleanOptions::default()
        };
        let rendered = render(&opts, &sample_report());
        assert!(
            rendered.contains("would evict --soft: 2"),
            "dry-run soft label: {rendered}",
        );
        assert!(
            rendered.contains("would evict --max-age: 3"),
            "dry-run max-age label: {rendered}",
        );
        assert!(
            rendered.contains("bytes projected: 4096"),
            "dry-run bytes label: {rendered}",
        );
        assert!(
            rendered.contains("dry-run plan:"),
            "dry-run plan header: {rendered}",
        );
        assert!(
            rendered.contains("deadbeef created_at=100 footprint=512 mode=--soft"),
            "dry-run plan soft entry: {rendered}",
        );
        assert!(
            rendered.contains("cafef00d created_at=200 footprint=1024 mode=--max-age"),
            "dry-run plan max-age entry: {rendered}",
        );
    }

    #[test]
    fn print_clean_report_omits_dry_run_plan_when_evicted_entries_empty() {
        // The "dry-run plan:" header MUST NOT appear when there
        // is nothing to list; otherwise it would dangle.
        let opts = CleanOptions {
            soft: true,
            dry_run: true,
            ..CleanOptions::default()
        };
        let empty = CleanReport::default();
        let rendered = render(&opts, &empty);
        assert!(
            !rendered.contains("dry-run plan:"),
            "empty dry-run plan must omit the header: {rendered}",
        );
    }

    #[test]
    fn mode_label_name_maps_each_variant() {
        assert_eq!(mode_label_name(EvictionMode::Soft), "--soft");
        assert_eq!(mode_label_name(EvictionMode::MaxAge), "--max-age");
        assert_eq!(mode_label_name(EvictionMode::MaxSize), "--max-size");
    }

    // ---- info ----

    #[test]
    fn aux_021_info_on_fresh_workspace_exits_zero() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_workspace(root);
        let code = run_info(root).unwrap();
        assert_eq!(code, 0);
        // No cache root was created during info; AUX-018 read-only.
        assert!(!root.join(".haz/cache").exists());
    }

    #[test]
    fn aux_018_info_does_not_mutate_an_existing_cache_root() {
        // Pre-populate a mix of cache shapes (an orphan restore
        // dir + a corrupt entry without a manifest). Snapshot the
        // (path, bytes) state of `.haz/cache/` before and after
        // info; the two snapshots MUST be byte-identical.
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        write_workspace(root);
        write_file(
            &root.join(".haz/cache/.restore-abcdef-1234/leftover.bin"),
            "scratch",
        );
        // Corrupt entry: shard dir + entry dir, no manifest.
        fs::create_dir_all(root.join(".haz/cache/ab/0000")).unwrap();
        write_file(&root.join(".haz/cache/ab/0000/stdout"), "");
        let before = snapshot_dir(&root.join(".haz/cache"));
        let code = run_info(root).unwrap();
        assert_eq!(code, 0);
        let after = snapshot_dir(&root.join(".haz/cache"));
        assert_eq!(
            before, after,
            "cache root state must not change under info()",
        );
    }

    #[test]
    fn aux_019_info_output_lists_every_required_category() {
        // The format is implementation-defined; this test pins it
        // by checking that every AUX-019 category appears as its
        // own labelled line. Constructing a CacheInfoReport
        // directly bypasses the FS walk so the test is purely a
        // format check.
        let report = CacheInfoReport {
            well_formed_entries: 5,
            corrupt_entries: 2,
            orphan_tmp_dirs: 1,
            orphan_restore_dirs: 3,
            total_bytes: 12345,
            by_schema: {
                let mut m: BTreeMap<(u8, HashFunctionLabel), u64> = BTreeMap::new();
                m.insert((0, HashFunctionLabel::Blake3), 5);
                m
            },
        };
        let mut out = Vec::<u8>::new();
        let cache_root = PathBuf::from("/some/workspace/.haz/cache");
        print_info_report(&cache_root, &report, &mut out).unwrap();
        let rendered = String::from_utf8(out).unwrap();
        assert!(
            rendered.contains("cache root: /some/workspace/.haz/cache"),
            "missing cache root line: {rendered}",
        );
        assert!(
            rendered.contains("well-formed entries: 5"),
            "missing well-formed line: {rendered}",
        );
        assert!(
            rendered.contains("corrupt entries: 2"),
            "missing corrupt line: {rendered}",
        );
        assert!(
            rendered.contains("orphan tmp directories: 1"),
            "missing orphan tmp line: {rendered}",
        );
        assert!(
            rendered.contains("orphan restore directories: 3"),
            "missing orphan restore line: {rendered}",
        );
        assert!(
            rendered.contains("total bytes: 12345"),
            "missing total bytes line: {rendered}",
        );
        assert!(
            rendered.contains("by schema:"),
            "missing schema breakdown header: {rendered}",
        );
        assert!(
            rendered.contains("(revision=0, hash=blake3): 5"),
            "missing schema breakdown entry: {rendered}",
        );
    }

    #[test]
    fn aux_019_info_output_omits_schema_section_when_no_well_formed_entries() {
        // The `by schema:` section MUST NOT appear when there are
        // no well-formed entries to enumerate; otherwise the
        // output would carry a dangling header.
        let report = CacheInfoReport {
            well_formed_entries: 0,
            corrupt_entries: 2,
            orphan_tmp_dirs: 0,
            orphan_restore_dirs: 0,
            total_bytes: 0,
            by_schema: BTreeMap::new(),
        };
        let mut out = Vec::<u8>::new();
        print_info_report(Path::new("/ws/.haz/cache"), &report, &mut out).unwrap();
        let rendered = String::from_utf8(out).unwrap();
        assert!(
            !rendered.contains("by schema:"),
            "schema section should be omitted: {rendered}",
        );
    }

    #[test]
    fn hash_label_name_maps_spec_canonical_strings() {
        // CACHE-002 registry: the canonical labels are `blake3`
        // and `sha256` (lowercase).
        assert_eq!(hash_label_name(HashFunctionLabel::Blake3), "blake3");
        assert_eq!(hash_label_name(HashFunctionLabel::Sha256), "sha256");
    }

    /// Recursively snapshot every regular file under `root`,
    /// returning a `BTreeMap<relative_path, bytes>`. Symlinks and
    /// other non-file kinds are skipped; nested directories
    /// recurse.
    fn snapshot_dir(root: &Path) -> BTreeMap<String, Vec<u8>> {
        let mut out = BTreeMap::new();
        snapshot_into(root, root, &mut out);
        out
    }

    fn snapshot_into(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
        let Ok(entries) = fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let Ok(ft) = entry.file_type() else { continue };
            if ft.is_file() {
                let rel = path
                    .strip_prefix(base)
                    .map_or_else(|_| path.display().to_string(), |p| p.display().to_string());
                let bytes = fs::read(&path).unwrap_or_default();
                out.insert(rel, bytes);
            } else if ft.is_dir() {
                snapshot_into(base, &path, out);
            }
        }
    }
}