haz-cli 0.1.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
//! End-to-end tests for `haz cache clean` against per-scenario
//! fixtures under `tests/fixtures/cache_clean/`. Each fixture is
//! a minimal workspace; cache state under `.haz/cache/` is built
//! at runtime (via `Cache::store` for valid entries plus
//! hand-rolled scaffolding for the stale shapes) so the entries
//! remain valid as `CHAPTER_REVISION` evolves.
//!
//! The tests exercise the four AUX-022..AUX-027 branches the CLI
//! must surface:
//!
//! - AUX-022 rejection when no mode is supplied (neither CLI nor
//!   workspace) and the success-path under each individual mode.
//! - AUX-024 dry-run reporting + on-disk preservation.
//! - AUX-025 workspace-default fallback when the CLI is silent.
//! - The CFG-034 / CFG-035 grammar rejection at the CLI parser
//!   layer.

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::process::Command;

use haz_cache::cache::Cache;
use haz_cache::key::CacheKey;
use haz_cache::key::prefix::CHAPTER_REVISION;
use haz_cache::layout;
use haz_cache::manifest::{HashFunctionLabel, Manifest};
use haz_cache::store::{StoreInputs, StoredOutput};
use haz_cli::EXIT_INTERNAL_OR_CONFIG_ERROR;
use haz_domain::settings::cache::HashAlgo;
use haz_vfs::StdFilesystem;
use tempfile::TempDir;

const HAZ_BIN: &str = env!("CARGO_BIN_EXE_haz");
const HASH_ALGO: HashAlgo = HashAlgo::Blake3;

fn fixture_tempdir(name: &str) -> TempDir {
    let src = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/cache_clean")
        .join(name);
    let dst = TempDir::new().expect("tempdir creation failed");
    copy_dir_recursive(&src, dst.path());
    dst
}

fn copy_dir_recursive(src: &Path, dst: &Path) {
    fs::create_dir_all(dst).unwrap();
    for entry in fs::read_dir(src).unwrap() {
        let entry = entry.unwrap();
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());
        if entry.file_type().unwrap().is_dir() {
            copy_dir_recursive(&src_path, &dst_path);
        } else {
            fs::copy(&src_path, &dst_path).unwrap();
        }
    }
}

/// Run `haz cache clean <args>` against `workspace_root`. Returns
/// the captured `(stdout, stderr, exit_code)` tuple.
fn haz_cache_clean(workspace_root: &Path, args: &[&str]) -> (String, String, Option<i32>) {
    let mut cmd = Command::new(HAZ_BIN);
    cmd.args(["cache", "clean"]);
    cmd.args(args);
    cmd.current_dir(workspace_root);
    let output = cmd.output().expect("failed to spawn haz");
    (
        String::from_utf8(output.stdout).expect("haz stdout was not utf-8"),
        String::from_utf8(output.stderr).expect("haz stderr was not utf-8"),
        output.status.code(),
    )
}

fn build_cache(workspace_root: &Path) -> Cache<StdFilesystem> {
    Cache::new(StdFilesystem::new(), workspace_root, HASH_ALGO)
}

fn key_with_first_byte(first: u8) -> CacheKey {
    let mut bytes = [0u8; 32];
    bytes[0] = first;
    CacheKey::from_bytes(bytes)
}

/// Store a valid entry whose manifest carries `created_at_unix`.
/// Tests that exercise `--max-age` rely on `created_at = 0` so
/// the wall-clock `now` is guaranteed to lie past any reasonable
/// cutoff, evicting the entry under every `--max-age` value.
fn store_valid_entry_at(
    cache: &Cache<StdFilesystem>,
    key: &CacheKey,
    rel: &str,
    bytes: &[u8],
    created_at_unix: u64,
) {
    let workspace_root = cache.workspace_root().to_path_buf();
    let target = workspace_root.join(rel);
    let anchored = format!("/{rel}");
    fs::create_dir_all(target.parent().unwrap()).unwrap();
    fs::write(&target, bytes).unwrap();
    let outs = [StoredOutput {
        workspace_absolute_path: &anchored,
        on_disk_path: &target,
        mode: 0o644,
    }];
    cache
        .store(
            key,
            &StoreInputs {
                outputs: &outs,
                stdout: b"",
                stderr: b"",
                created_at_unix,
            },
        )
        .expect("store should succeed for a fresh key");
}

/// Hand-write a manifest whose `chapter_revision` does NOT match
/// the current value. The resulting entry is "objectively stale"
/// per CACHE-022 and counts under `--soft` only.
fn write_schema_stale_entry(cache: &Cache<StdFilesystem>, key: &CacheKey) {
    let entry_dir = layout::entry_dir(cache.cache_root(), key);
    fs::create_dir_all(&entry_dir).unwrap();
    let manifest = Manifest {
        chapter_revision: CHAPTER_REVISION.saturating_add(1),
        hash_function: HashFunctionLabel::Blake3,
        key: *key,
        outputs: vec![],
        stdout_len: 0,
        stderr_len: 0,
        stdout_hash: [0u8; 32],
        stderr_hash: [0u8; 32],
        exit_status: 0,
        created_at_unix: 0,
    };
    fs::write(
        layout::manifest_path(cache.cache_root(), key),
        manifest.to_json_bytes(),
    )
    .unwrap();
}

/// Create an orphan `<shard>/.tmp-<key>-<random>` directory (the
/// incomplete two-phase-store shape from CACHE-017).
fn write_orphan_tmp_dir(cache: &Cache<StdFilesystem>, key: &CacheKey, random: &str) {
    let tmp = layout::tmp_entry_dir(cache.cache_root(), key, random);
    fs::create_dir_all(&tmp).unwrap();
    fs::write(tmp.join("partial.bin"), b"scratch").unwrap();
}

/// Create an orphan `<cache_root>/.restore-<key>-<random>`
/// staging directory (the interrupted-restore shape).
fn write_orphan_restore_dir(cache: &Cache<StdFilesystem>, key: &CacheKey, random: &str) {
    let staging = layout::restore_staging_dir(cache.cache_root(), key, random);
    fs::create_dir_all(&staging).unwrap();
    fs::write(staging.join("leftover.bin"), b"scratch").unwrap();
}

/// Pre-populate `<workspace_root>/.haz/cache/` with:
///
/// - 2 well-formed entries at `created_at_unix = 0`.
/// - 1 schema-mismatched entry.
/// - 1 orphan `.tmp-` directory.
/// - 1 orphan `.restore-` directory.
fn populate_mixed_cache(workspace_root: &Path) {
    let cache = build_cache(workspace_root);
    let key_a = key_with_first_byte(0xAA);
    store_valid_entry_at(&cache, &key_a, "lib/out_a", b"hello", 0);
    let key_b = key_with_first_byte(0xBB);
    store_valid_entry_at(&cache, &key_b, "lib/out_b", b"world!", 0);
    let key_c = key_with_first_byte(0xCC);
    write_schema_stale_entry(&cache, &key_c);
    let key_d = key_with_first_byte(0xDD);
    write_orphan_tmp_dir(&cache, &key_d, "tmpsuffix");
    let key_e = key_with_first_byte(0xEE);
    write_orphan_restore_dir(&cache, &key_e, "rsfxsuffix");
}

/// Recursively snapshot every regular file under `root`,
/// returning a `BTreeMap<relative_path, bytes>`. Symlinks and
/// other non-file kinds are skipped.
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);
        }
    }
}

// --- AUX-022: no-mode rejection ---

#[test]
fn aux_022_no_mode_rejects_with_diagnostic() {
    // Bare `haz cache clean` against a workspace lacking
    // `cache.clean.*` defaults MUST be rejected per AUX-022.
    let tmp = fixture_tempdir("fresh_workspace");
    let (_, stderr, code) = haz_cache_clean(tmp.path(), &[]);
    assert_ne!(
        code,
        Some(0),
        "no-mode invocation must exit non-zero; stderr: {stderr}",
    );
    assert!(
        stderr.contains("at least one mode"),
        "AUX-022 diagnostic must surface the requirement: {stderr}",
    );
}

// --- AUX-024: --soft happy path on a populated cache ---

#[test]
fn clean_soft_reports_aux_024_categories_on_populated_cache() {
    let tmp = fixture_tempdir("populated_with_mixed_entries");
    populate_mixed_cache(tmp.path());

    let (stdout, stderr, code) = haz_cache_clean(tmp.path(), &["--soft"]);
    assert_eq!(code, Some(0), "expected exit 0; stderr: {stderr}");
    // Fixture contributes: 1 schema-stale entry, 1 orphan tmp,
    // 1 orphan restore. The two well-formed entries survive.
    assert!(
        stdout.contains("entries inspected: 3"),
        "expected inspected=3 (2 well-formed + 1 corrupt): {stdout}",
    );
    assert!(
        stdout.contains("evicted --soft: 1"),
        "expected one soft-evicted entry (the schema-stale one): {stdout}",
    );
    assert!(
        stdout.contains("evicted --max-age: 0"),
        "max-age inactive must read zero: {stdout}",
    );
    assert!(
        stdout.contains("evicted --max-size: 0"),
        "max-size inactive must read zero: {stdout}",
    );
    assert!(
        stdout.contains("orphan tmp directories removed: 1"),
        "expected one orphan tmp removed: {stdout}",
    );
    assert!(
        stdout.contains("orphan restore directories removed: 1"),
        "expected one orphan restore removed: {stdout}",
    );

    // The well-formed entries survive on disk.
    let cache_root = tmp.path().join(".haz/cache");
    let key_a = key_with_first_byte(0xAA);
    assert!(layout::entry_dir(&cache_root, &key_a).exists());
}

// --- AUX-022: --max-age happy path with created_at=0 ---

#[test]
fn clean_max_age_evicts_well_formed_entries_strictly_older_than_cutoff() {
    let tmp = fixture_tempdir("populated_with_mixed_entries");
    populate_mixed_cache(tmp.path());

    // 1s cutoff; every well-formed entry has created_at=0 and is
    // well past `now - 1s`, so both get evicted.
    let (stdout, stderr, code) = haz_cache_clean(tmp.path(), &["--max-age", "1s"]);
    assert_eq!(code, Some(0), "expected exit 0; stderr: {stderr}");
    assert!(
        stdout.contains("evicted --max-age: 2"),
        "expected both well-formed entries evicted by max-age: {stdout}",
    );
    // Corrupt entry stays (AUX-023: --max-age ignores corrupt entries).
    let cache_root = tmp.path().join(".haz/cache");
    let key_c = key_with_first_byte(0xCC);
    assert!(
        layout::entry_dir(&cache_root, &key_c).exists(),
        "schema-stale entry must NOT be evicted by --max-age alone",
    );
    // Orphan tmp / restore dirs stay (only --soft reclaims them).
    let key_d = key_with_first_byte(0xDD);
    let key_e = key_with_first_byte(0xEE);
    assert!(layout::tmp_entry_dir(&cache_root, &key_d, "tmpsuffix").exists());
    assert!(layout::restore_staging_dir(&cache_root, &key_e, "rsfxsuffix").exists());
}

// --- AUX-024: dry-run preserves disk state and prints a plan ---

#[test]
fn aux_024_dry_run_does_not_modify_disk_and_emits_plan() {
    let tmp = fixture_tempdir("populated_with_mixed_entries");
    populate_mixed_cache(tmp.path());

    let cache_root = tmp.path().join(".haz/cache");
    let before = snapshot_dir(&cache_root);

    let (stdout, stderr, code) =
        haz_cache_clean(tmp.path(), &["--soft", "--max-age", "1s", "--dry-run"]);
    assert_eq!(code, Some(0), "expected exit 0; stderr: {stderr}");
    assert!(
        stdout.contains("dry-run: AUX-024 plan only"),
        "dry-run banner missing: {stdout}",
    );
    assert!(
        stdout.contains("would evict --soft:"),
        "dry-run mode labels: {stdout}",
    );
    assert!(
        stdout.contains("bytes projected:"),
        "dry-run bytes label: {stdout}",
    );
    assert!(
        stdout.contains("dry-run plan:"),
        "per-entry plan header: {stdout}",
    );
    // The per-entry plan must list each evicted entry's mode.
    assert!(
        stdout.contains("mode=--soft"),
        "dry-run plan must include soft mode entries: {stdout}",
    );
    assert!(
        stdout.contains("mode=--max-age"),
        "dry-run plan must include max-age mode entries: {stdout}",
    );

    let after = snapshot_dir(&cache_root);
    assert_eq!(
        before, after,
        "dry-run must leave the cache root byte-identical",
    );
}

// --- AUX-025: workspace default satisfies AUX-022 ---

#[test]
fn aux_025_workspace_default_max_age_satisfies_aux_022() {
    // The fixture's `.haz/workspace.yml` carries
    // `cache.clean.max_age: 1s`. A bare `haz cache clean`
    // succeeds because AUX-025 lets the workspace default
    // supply the mode AUX-022 requires.
    let tmp = fixture_tempdir("with_workspace_max_age_default");
    let cache = build_cache(tmp.path());
    let key = key_with_first_byte(0xAA);
    store_valid_entry_at(&cache, &key, "lib/out", b"x", 0);

    let (stdout, stderr, code) = haz_cache_clean(tmp.path(), &[]);
    assert_eq!(code, Some(0), "expected exit 0; stderr: {stderr}");
    assert!(
        stdout.contains("evicted --max-age: 1"),
        "expected the entry to be evicted under the workspace default: {stdout}",
    );
    // The entry is gone from disk.
    let cache_root = tmp.path().join(".haz/cache");
    assert!(!layout::entry_dir(&cache_root, &key).exists());
}

// --- CFG-034: malformed CLI duration rejected at parse time ---

#[test]
fn cfg_034_bare_integer_max_age_rejected_at_cli_parse_time() {
    let tmp = fixture_tempdir("fresh_workspace");
    let (_, stderr, code) = haz_cache_clean(tmp.path(), &["--max-age", "90"]);
    // CFG-034 / AUX-027: malformed-duration rejection MUST land in
    // the EXEC-021 internal / configuration-error class. The
    // task-failure class (`1`) MUST NOT be returned.
    assert_eq!(
        code,
        Some(EXIT_INTERNAL_OR_CONFIG_ERROR),
        "malformed --max-age must use the config-error class; stderr: {stderr}",
    );
    // The parser does not run the workspace load before failing;
    // the diagnostic is bpaf's, anchored at the flag value.
    assert!(
        !stderr.is_empty(),
        "missing diagnostic for malformed duration: {stderr}",
    );
}

// --- AUX-027: cache clean exit-code class mapping ---

#[test]
fn aux_027_success_exits_zero_and_does_not_use_task_failure_class() {
    // AUX-027: `haz cache clean` MUST exit 0 on a successful run,
    // including when the eviction set is empty. The task-failure
    // class (1) MUST NOT be returned.
    const EXIT_TASK_FAILURE: i32 = 1;

    let tmp = fixture_tempdir("fresh_workspace");
    let (_, stderr, code) = haz_cache_clean(tmp.path(), &["--soft"]);
    assert_eq!(
        code,
        Some(0),
        "AUX-027: --soft on a fresh workspace exits 0; stderr: {stderr}",
    );
    assert_ne!(code, Some(EXIT_TASK_FAILURE));
}

#[test]
fn aux_027_no_mode_rejection_uses_config_error_class() {
    // AUX-027: a bare `haz cache clean` (no mode flag, no
    // workspace default) MUST be rejected per AUX-022. The exit
    // code MUST be in the EXEC-021 internal / configuration-error
    // class.
    let tmp = fixture_tempdir("fresh_workspace");
    let (_, stderr, code) = haz_cache_clean(tmp.path(), &[]);
    assert_eq!(
        code,
        Some(EXIT_INTERNAL_OR_CONFIG_ERROR),
        "AUX-027: no-mode rejection MUST use the config-error class; stderr: {stderr}",
    );
}

#[test]
fn aux_027_malformed_duration_uses_config_error_class() {
    // AUX-027 / CFG-034: a malformed `--max-age` value MUST be
    // rejected with a typed CLI error and the exit code MUST land
    // in the EXEC-021 internal / configuration-error class. This
    // is the test that originally surfaced the bpaf-induced
    // mis-mapping (parse failures exited with `1`, the
    // task-failure class); regression-locks the
    // `apps/haz-cli/src/main.rs` `ParseFailure` mapping.
    let tmp = fixture_tempdir("fresh_workspace");
    let (_, stderr, code) = haz_cache_clean(tmp.path(), &["--max-age", "90"]);
    assert_eq!(
        code,
        Some(EXIT_INTERNAL_OR_CONFIG_ERROR),
        "AUX-027: malformed duration MUST use the config-error class; stderr: {stderr}",
    );
}