rust-fs-core 0.3.11

Pure-Rust block-device framework — BlockRead/BlockDevice traits + FileDevice + CallbackDevice + LRU cache. Foundation crate for the rust-fs-* drivers and rust-img-* containers.
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
//! The family's shared scripts, run the way every other repository runs them.
//!
//! `scripts/test-floor.sh` and `scripts/semver-check.sh` lived as a separate
//! copy in each repository -- twelve of the first and thirteen of the second
//! -- and the copies drifted: one bug (a floor that exited silently on a tier
//! that ran nothing) had to be fixed seven times, and a counting rule one
//! repository added reached no other. They are now rust-fs-core's alone,
//! exactly as `scripts/output-budget.sh` already was: a repository carries one
//! byte-identical bootstrap, `scripts/core.sh`, which finds this crate and runs
//! the script named against the calling repository.
//!
//! So everything here runs the scripts from a CALLER tree -- a repository that
//! is not this one -- because that is the only way they are used. Each caller
//! tree is built under this repository's `tmp/`, never the OS temporary
//! directory, and removed afterwards.
//!
//! THE SCRIPTS RUN IN PLACE (#212). A caller used to carry a byte-identical
//! bootstrap, `scripts/core.sh`, and fourteen of them a `scripts/tier.sh`, each
//! there only to find this crate; the copies had to be recopied on every bump,
//! and the tier wrappers drifted fourteen ways. Now a caller runs
//! `bash ../rust-fs-core/scripts/NAME.sh` from its own checkout, the script
//! works on the repository it is run from, and family-check refuses a copy of
//! either file.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU64, Ordering};

fn repo() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}

fn bash() -> PathBuf {
    if cfg!(windows) {
        for candidate in [
            r"C:\Program Files\Git\bin\bash.exe",
            r"C:\Program Files\Git\usr\bin\bash.exe",
        ] {
            let path = PathBuf::from(candidate);
            if path.is_file() {
                return path;
            }
        }
    }
    PathBuf::from("bash")
}

fn printed(output: &Output) -> String {
    format!(
        "status {:?}\nstdout:\n{}\nstderr:\n{}",
        output.status.code(),
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    )
}

/// A throwaway repository under this one's `tmp/`, removed on drop: a git
/// repository of its own, so a script run from it treats it as the caller,
/// with a log directory and no copy of anything of this crate's.
struct Caller {
    root: PathBuf,
}

impl Caller {
    fn new(tag: &str) -> Self {
        static NEXT: AtomicU64 = AtomicU64::new(0);
        let root = repo().join("tmp").join(format!(
            "family-caller-{tag}-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = fs::remove_dir_all(&root);
        // The guard exists before anything that can panic, so a failed setup
        // still removes the tree: a panic before `Caller` was built would
        // skip its Drop and leave the directory behind.
        let caller = Caller { root };
        fs::create_dir_all(caller.root.join("scripts")).unwrap();
        fs::create_dir_all(caller.root.join("tmp").join("logs")).unwrap();
        fs::write(
            caller.root.join("Cargo.toml"),
            "[package]\nname = \"am-example\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        let out = Command::new("git")
            .current_dir(&caller.root)
            .args(["init", "-q"])
            .output()
            .expect("git is needed to build a caller repository");
        assert!(out.status.success(), "git init: {}", printed(&out));
        caller
    }

    fn log(&self, tier: &str, text: &str) {
        fs::write(
            self.root
                .join("tmp")
                .join("logs")
                .join(format!("{tier}.log")),
            text,
        )
        .unwrap();
    }

    /// `bash <this crate>/scripts/NAME.sh ARGS...` from the caller's own
    /// directory, with nothing set to say which repository it is: the script
    /// finds that from where it is run, as a consumer's CI runs it.
    fn core(&self, args: &[&str], env: &[(&str, &str)]) -> Output {
        let (name, rest) = args.split_first().expect("a script name");
        let mut command = Command::new(bash());
        command
            .current_dir(&self.root)
            .arg(repo().join("scripts").join(format!("{name}.sh")))
            .args(rest)
            .env_remove("FS_CORE_CALLER")
            .env_remove("FS_CORE_ROOT");
        for (key, value) in env {
            command.env(key, value);
        }
        command.output().unwrap()
    }
}

impl Drop for Caller {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.root);
    }
}

fn version_of(script: &str) -> String {
    let out = Command::new(bash())
        .arg(repo().join("scripts").join(script))
        .arg("--version")
        .output()
        .unwrap();
    String::from_utf8_lossy(&out.stdout).trim().to_string()
}

#[test]
fn each_family_script_states_its_contract() {
    assert_eq!(version_of("test-floor.sh"), "rust-fs-core-test-floor 1");
    assert_eq!(version_of("semver-check.sh"), "rust-fs-core-semver-check 1");
    assert_eq!(
        version_of("guest-rust-toolchain.sh"),
        "rust-fs-core-guest-rust-toolchain 1"
    );
    assert_eq!(
        version_of("stage-siblings.sh"),
        "rust-fs-core-stage-siblings 1"
    );
    assert_eq!(
        version_of("guest-rust-run.sh"),
        "rust-fs-core-guest-rust-run 1"
    );
    assert_eq!(version_of("ci-gate.sh"), "rust-fs-core-ci-gate 1");
    assert_eq!(version_of("package-cli.sh"), "rust-fs-core-package-cli 1");
}

/// `ci-gate` runs in place like the others. Its behaviour against
/// a caller's `ci.yml` and `.github-guard` is `tests/scripts/test-ci-gate.sh`,
/// which needs python3's yaml module and so runs where CI provides one.
#[test]
fn ci_gate_runs_in_place() {
    let caller = Caller::new("ci-gate");
    let out = caller.core(&["ci-gate", "--version"], &[]);
    assert!(out.status.success(), "{}", printed(&out));
    assert_eq!(
        String::from_utf8_lossy(&out.stdout).trim(),
        "rust-fs-core-ci-gate 1",
        "{}",
        printed(&out)
    );
}

#[test]
fn the_floor_reads_the_callers_log_not_this_repositorys() {
    let caller = Caller::new("floor");
    caller.log(
        "unit",
        "test result: ok. 3 passed; 0 failed\ntest result: ok. 4 passed; 0 failed\n",
    );
    let pass = caller.core(&["test-floor", "unit", "7"], &[]);
    assert!(pass.status.success(), "{}", printed(&pass));
    assert!(
        String::from_utf8_lossy(&pass.stdout).contains("unit: 7 tests executed (floor 7)"),
        "{}",
        printed(&pass)
    );

    let fail = caller.core(&["test-floor", "unit", "8"], &[]);
    assert_eq!(fail.status.code(), Some(1), "{}", printed(&fail));
    assert!(
        String::from_utf8_lossy(&fail.stdout)
            .contains("only 7 tests executed in the unit tier, floor is 8"),
        "{}",
        printed(&fail)
    );
}

#[test]
fn the_floor_names_a_tier_that_ran_nothing_and_one_that_never_ran() {
    let caller = Caller::new("empty");
    caller.log("empty", "compiled; no test binary\n");
    let empty = caller.core(&["test-floor", "empty", "1"], &[]);
    assert_eq!(empty.status.code(), Some(1), "{}", printed(&empty));
    assert!(
        String::from_utf8_lossy(&empty.stdout)
            .contains("only 0 tests executed in the empty tier, floor is 1"),
        "{}",
        printed(&empty)
    );

    let absent = caller.core(&["test-floor", "never-ran", "1"], &[]);
    assert_eq!(absent.status.code(), Some(1), "{}", printed(&absent));
    assert!(
        String::from_utf8_lossy(&absent.stderr).contains("did not run"),
        "{}",
        printed(&absent)
    );
}

#[test]
fn the_floor_counts_a_semver_runs_lints_coloured_or_not() {
    let caller = Caller::new("semver-lints");
    caller.log(
        "semver",
        "semver-check: am-example 0.1.0\n\u{1b}[1m\u{1b}[32m     Checked\u{1b}[0m [   0.013s] 196 checks: 196 pass, 58 skip\n",
    );
    let out = caller.core(&["test-floor", "semver", "196"], &[]);
    assert!(out.status.success(), "{}", printed(&out));
    let short = caller.core(&["test-floor", "semver", "197"], &[]);
    assert_eq!(short.status.code(), Some(1), "{}", printed(&short));
}

#[test]
fn refusing_ignored_tests_is_asked_for_and_then_enforced() {
    let caller = Caller::new("ignored");
    caller.log(
        "unit",
        "test result: ok. 5 passed; 0 failed; 2 ignored; 0 measured\n",
    );
    let allowed = caller.core(&["test-floor", "unit", "5"], &[]);
    assert!(allowed.status.success(), "{}", printed(&allowed));
    let refused = caller.core(&["test-floor", "--refuse-ignored", "unit", "5"], &[]);
    assert_eq!(refused.status.code(), Some(1), "{}", printed(&refused));
    assert!(
        String::from_utf8_lossy(&refused.stdout).contains("2 tests ignored in the unit tier"),
        "{}",
        printed(&refused)
    );
}

#[test]
fn semver_check_checks_the_callers_package() {
    let caller = Caller::new("semver");
    let out = caller.core(&["semver-check"], &[("SEMVER_CHECK_DRY_RUN", "1")]);
    assert!(out.status.success(), "{}", printed(&out));
    let said = String::from_utf8_lossy(&out.stdout);
    assert!(
        said.contains("cargo semver-checks check-release --package am-example"),
        "{}",
        printed(&out)
    );
    assert!(
        // The package flag, not the bare name: the checkout's own path is
        // `.../rust-fs-core/...`, so the name alone is in every line.
        !said.contains("--package rust-fs-core") && !said.contains("--package am-fs-core"),
        "it checked this crate, not the caller's: {}",
        printed(&out)
    );
}

#[test]
fn semver_check_names_the_former_name_a_renamed_crate_is_compared_with() {
    let caller = Caller::new("semver-former");
    fs::write(
        caller.root.join("Cargo.toml"),
        "[package]\nname = \"rust-example\"\nversion = \"0.2.0\"\n\n\
         [package.metadata.semver]\nformer-name = \"am-example\"\n",
    )
    .unwrap();
    let out = caller.core(&["semver-check"], &[("SEMVER_CHECK_DRY_RUN", "1")]);
    assert!(out.status.success(), "{}", printed(&out));
    let said = String::from_utf8_lossy(&out.stdout);
    assert!(
        said.contains("--package rust-example"),
        "it did not check the crate under its new name: {}",
        printed(&out)
    );
    assert!(
        said.contains("against am-example's newest release"),
        "it did not say the former name is the baseline: {}",
        printed(&out)
    );
}

/// A script run in place works on the repository it is run from, and a
/// script run from somewhere that is no repository at all says so rather
/// than reading this crate's own files as if they were the caller's.
#[test]
fn a_script_run_in_place_works_on_the_repository_it_is_run_from() {
    let caller = Caller::new("in-place");
    caller.log("unit", "test result: ok. 2 passed; 0 failed\n");
    let out = caller.core(&["test-floor", "unit", "2"], &[]);
    assert!(out.status.success(), "{}", printed(&out));

    // A subdirectory of the caller is still the caller.
    let nested = caller.root.join("src");
    fs::create_dir_all(&nested).unwrap();
    let out = Command::new(bash())
        .current_dir(&nested)
        .arg(repo().join("scripts").join("test-floor.sh"))
        .args(["unit", "2"])
        .env_remove("FS_CORE_CALLER")
        .output()
        .unwrap();
    assert!(out.status.success(), "{}", printed(&out));

    // FS_CORE_CALLER still names the caller outright, wherever it is run.
    let elsewhere = Command::new(bash())
        .current_dir(repo())
        .arg(repo().join("scripts").join("test-floor.sh"))
        .args(["unit", "2"])
        .env("FS_CORE_CALLER", &caller.root)
        .output()
        .unwrap();
    assert!(elsewhere.status.success(), "{}", printed(&elsewhere));
}

#[test]
fn this_repository_runs_its_own_scripts_in_place_too() {
    let out = Command::new(bash())
        .current_dir(repo())
        .arg(repo().join("scripts").join("test-floor.sh"))
        .arg("--version")
        .env_remove("FS_CORE_ROOT")
        .output()
        .unwrap();
    assert!(out.status.success(), "{}", printed(&out));
    assert_eq!(
        String::from_utf8_lossy(&out.stdout).trim(),
        "rust-fs-core-test-floor 1"
    );
}

/// The published crate is how a consumer with no checkout gets these, so the
/// package must carry all three.
#[test]
fn the_package_ships_every_family_script() {
    let manifest = fs::read_to_string(repo().join("Cargo.toml")).unwrap();
    for line in manifest.lines() {
        let line = line.trim();
        assert!(
            !(line.starts_with("include")
                || (line.starts_with("exclude") && line.contains("scripts"))),
            "Cargo.toml narrows the package in a way that could drop scripts/: {line}"
        );
    }
    for script in [
        "core.sh",
        "output-budget.sh",
        "test-floor.sh",
        "semver-check.sh",
        "family-check.sh",
        "guest-rust-toolchain.sh",
        "ci-gate.sh",
        "package-cli.sh",
        "stage-siblings.sh",
        "guest-rust-run.sh",
        "tier.sh",
    ] {
        assert!(
            Path::new(&repo().join("scripts").join(script)).is_file(),
            "scripts/{script}"
        );
    }
}

#[test]
fn family_check_passes_a_clean_caller_and_refuses_each_kind_of_copy() {
    // Clean: the scripts are run in place from the rust-fs-core checkout.
    let clean = Caller::new("family-clean");
    fs::write(
        clean.root.join("chores.yml"),
        "tasks:\n  t:\n    cmds:\n      - 'bash ../rust-fs-core/scripts/test-floor.sh debug 1'\n",
    )
    .unwrap();
    let ok = clean.core(&["family-check"], &[]);
    assert!(ok.status.success(), "{}", printed(&ok));
    assert!(
        String::from_utf8_lossy(&ok.stdout).contains("PASS  family-check"),
        "{}",
        printed(&ok)
    );

    // A committed copy of a family script.
    let copy = Caller::new("family-copy");
    fs::write(copy.root.join("scripts/test-floor.sh"), "echo mine\n").unwrap();
    let out = copy.core(&["family-check"], &[]);
    assert_eq!(out.status.code(), Some(1), "{}", printed(&out));
    assert!(
        String::from_utf8_lossy(&out.stdout).contains(
            "scripts/test-floor.sh is a copy of rust-fs-core's; delete it and run ../rust-fs-core/scripts/test-floor.sh in place"
        ),
        "{}",
        printed(&out)
    );

    // The bootstrap and the tier wrapper are copies too: each existed only to
    // find this crate, and both drifted (#212).
    for wrapper in ["core.sh", "tier.sh"] {
        let kept = Caller::new("family-wrapper");
        fs::write(kept.root.join("scripts").join(wrapper), "echo mine\n").unwrap();
        let out = kept.core(&["family-check"], &[]);
        assert_eq!(out.status.code(), Some(1), "{wrapper}: {}", printed(&out));
        assert!(
            String::from_utf8_lossy(&out.stdout)
                .contains(&format!("scripts/{wrapper} is a copy of rust-fs-core's")),
            "{wrapper}: {}",
            printed(&out)
        );
    }

    // A call through a copy, or through the old bootstrap or tier wrapper,
    // is refused; a comment naming one is fine.
    let calls = Caller::new("family-calls");
    fs::create_dir_all(calls.root.join(".github/workflows")).unwrap();
    fs::write(
        calls.root.join(".github/workflows/ci.yml"),
        "jobs:\n  t:\n    steps:\n      # see scripts/semver-check.sh\n      - run: bash scripts/test-floor.sh debug 1\n      - run: bash scripts/core.sh test-floor debug 1\n      - run: scripts/tier.sh unit unit 10 100 -- cargo test\n",
    )
    .unwrap();
    let out = calls.core(&["family-check"], &[]);
    assert_eq!(out.status.code(), Some(1), "{}", printed(&out));
    let said = String::from_utf8_lossy(&out.stdout);
    for expected in [
        "bash scripts/test-floor.sh debug 1",
        "bash scripts/core.sh test-floor debug 1",
        "scripts/tier.sh unit unit 10 100",
    ] {
        assert!(said.contains(expected), "{expected}: {}", printed(&out));
    }
    assert!(
        !said.contains("see scripts/semver-check.sh"),
        "a comment was counted as a call: {}",
        printed(&out)
    );

    // A driver's own guest command is its scripts/guest-suite.sh, and the
    // family script it runs is run in place from the staged sibling.
    let driver = Caller::new("family-guest-suite-is-the-drivers");
    fs::write(
        driver.root.join("scripts/guest-suite.sh"),
        "exec bash /share/siblings/rust-fs-core/scripts/guest-rust-run.sh fs-x /share rust-fs-core -- scripts/test.sh\n",
    )
    .unwrap();
    fs::write(
        driver.root.join("chores.yml"),
        "tasks:\n  test:vm:\n    cmds:\n      - 'bash ../rust-fs-core/scripts/stage-siblings.sh /share rust-fs-core -- true'\n",
    )
    .unwrap();
    let out = driver.core(&["family-check"], &[]);
    assert!(out.status.success(), "{}", printed(&out));
}

/// The bootstrap is refused whatever its mode: it used to be required, and
/// executable (rust-fs-core#200); it is now a copy like any other (#212).
#[test]
fn family_check_refuses_a_committed_bootstrap_however_it_is_kept() {
    let git = |caller: &Caller, args: &[&str]| {
        let out = Command::new("git")
            .current_dir(&caller.root)
            .args(args)
            .output()
            .expect("git is needed to build a caller repository");
        assert!(out.status.success(), "git {args:?}: {}", printed(&out));
    };
    let caller = Caller::new("family-bootstrap-committed");
    fs::copy(
        repo().join("scripts").join("core.sh"),
        caller.root.join("scripts").join("core.sh"),
    )
    .unwrap();
    git(&caller, &["add", "scripts/core.sh"]);
    git(&caller, &["update-index", "--chmod=+x", "scripts/core.sh"]);
    let out = caller.core(&["family-check"], &[]);
    assert_eq!(out.status.code(), Some(1), "{}", printed(&out));
    assert!(
        String::from_utf8_lossy(&out.stdout)
            .contains("scripts/core.sh is a copy of rust-fs-core's"),
        "{}",
        printed(&out)
    );
}

/// One tier runner for the family (#212): run in place, it writes the log
/// under the caller's `tmp/logs/`, not this crate's.
#[test]
fn the_tier_runner_runs_in_place_and_logs_in_the_caller() {
    let caller = Caller::new("tier");
    let out = caller.core(
        &[
            "tier",
            "unit",
            "unit",
            "50",
            "5000",
            "--",
            "echo",
            "hello from the caller",
        ],
        &[],
    );
    assert!(out.status.success(), "{}", printed(&out));
    let log = fs::read_to_string(caller.root.join("tmp/logs/unit.log"))
        .expect("the tier's log is in the caller's tmp/logs");
    assert!(log.contains("hello from the caller"), "{log}");
}

/// The check three repositories carried in their own tier wrappers, shared:
/// a run that printed SKIP lines counted them as passes, and a skipped test
/// reads exactly like a passing one (#212).
#[test]
fn the_tier_runner_refuses_a_skip_when_asked() {
    let caller = Caller::new("tier-skips");
    let refused = caller.core(
        &[
            "tier",
            "--refuse-skips",
            "unit",
            "unit",
            "50",
            "5000",
            "--",
            "echo",
            "SKIP: no fixture",
        ],
        &[],
    );
    assert_eq!(refused.status.code(), Some(66), "{}", printed(&refused));
    assert!(
        String::from_utf8_lossy(&refused.stderr).contains("SKIP"),
        "the refusal does not name the skip: {}",
        printed(&refused)
    );

    let allowed = caller.core(
        &[
            "tier",
            "unit",
            "unit",
            "50",
            "5000",
            "--",
            "echo",
            "SKIP: no fixture",
        ],
        &[],
    );
    assert!(
        allowed.status.success(),
        "a skip is only refused when asked: {}",
        printed(&allowed)
    );
}

#[test]
fn per_target_floors_catch_a_suite_that_emptied_inside_a_healthy_total() {
    let caller = Caller::new("targets");
    fs::create_dir_all(caller.root.join(".github")).unwrap();
    fs::write(
        caller.root.join(".github/test-floors.txt"),
        "# target floor\nlib 2\nreads 3\nwrites 1\n",
    )
    .unwrap();
    // Coloured `Running` lines, as CI's CARGO_TERM_COLOR=always prints them.
    let run = |writes: u32| {
        format!(
            "\u{1b}[1m\u{1b}[32m     Running\u{1b}[0m unittests src/lib.rs (x)\ntest result: ok. 2 passed\n\
             \u{1b}[1m\u{1b}[32m     Running\u{1b}[0m tests/reads.rs (x)\ntest result: ok. 9 passed\n\
             \u{1b}[1m\u{1b}[32m     Running\u{1b}[0m tests/writes.rs (x)\ntest result: ok. {writes} passed\n"
        )
    };
    caller.log("suite", &run(1));
    let ok = caller.core(
        &[
            "test-floor",
            "--targets",
            ".github/test-floors.txt",
            "suite",
        ],
        &[],
    );
    assert!(ok.status.success(), "{}", printed(&ok));
    assert!(
        String::from_utf8_lossy(&ok.stdout).contains("3 target(s) met their floors"),
        "{}",
        printed(&ok)
    );

    // A target the log never mentions -- a suite that stopped being BUILT --
    // counts as zero, not as absent and therefore fine.
    fs::write(
        caller.root.join(".github/test-floors.txt"),
        "reads 3\nnever_built 1\n",
    )
    .unwrap();
    caller.log("suite", &run(1));
    let unbuilt = caller.core(
        &[
            "test-floor",
            "--targets",
            ".github/test-floors.txt",
            "suite",
        ],
        &[],
    );
    assert_eq!(unbuilt.status.code(), Some(1), "{}", printed(&unbuilt));
    assert!(
        String::from_utf8_lossy(&unbuilt.stdout)
            .contains("never_built executed 0 tests, floor is 1"),
        "{}",
        printed(&unbuilt)
    );
    fs::write(
        caller.root.join(".github/test-floors.txt"),
        "# target floor\nlib 2\nreads 3\nwrites 1\n",
    )
    .unwrap();

    caller.log("suite", &run(0));
    let emptied = caller.core(
        &[
            "test-floor",
            "--targets",
            ".github/test-floors.txt",
            "suite",
        ],
        &[],
    );
    assert_eq!(emptied.status.code(), Some(1), "{}", printed(&emptied));
    assert!(
        String::from_utf8_lossy(&emptied.stdout).contains("writes executed 0 tests, floor is 1"),
        "{}",
        printed(&emptied)
    );
}

/// The agent-core check reads the AGENTS.md of the repository it is run
/// from. Run in place, a check that read this crate's own AGENTS.md would
/// pass every caller, whatever its guide said.
#[test]
fn the_agent_core_check_reads_the_callers_guide_not_this_repositorys() {
    let caller = Caller::new("agents-core");
    fs::write(
        caller.root.join("AGENTS.md"),
        "# A guide with no shared block\n",
    )
    .unwrap();
    let out = caller.core(&["agents-core-check"], &[]);
    assert_eq!(out.status.code(), Some(1), "{}", printed(&out));
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("BEGIN marker"),
        "the refusal does not name the missing marker: {}",
        printed(&out)
    );

    // The caller's guide with the block intact passes.
    fs::copy(repo().join("AGENTS.md"), caller.root.join("AGENTS.md")).unwrap();
    let out = caller.core(&["agents-core-check"], &[]);
    assert!(out.status.success(), "{}", printed(&out));
}

/// `tier` with its flags, running `bash -c SCRIPT` as the tier's command.
fn tier_running(caller: &Caller, flags: &[&str], script: &str) -> Output {
    let mut args = vec!["tier"];
    args.extend_from_slice(flags);
    args.extend_from_slice(&["unit", "unit", "50", "5000", "--", "bash", "-c", script]);
    caller.core(&args, &[])
}

/// `--refuse-ignored`: libtest's own `N ignored` fails a tier that otherwise
/// passed. `cargo test` prints its ignored count and exits 0, so a tier that
/// stopped running half of itself is a green line unless this reads it.
#[test]
fn the_tier_runner_refuses_an_ignored_test_when_asked() {
    let caller = Caller::new("tier-ignored");
    let ok = "echo 'test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out'";
    let two = "echo 'test result: ok. 5 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out'";

    let out = tier_running(&caller, &["--refuse-ignored"], ok);
    assert!(out.status.success(), "nothing ignored: {}", printed(&out));

    let out = tier_running(&caller, &["--refuse-ignored"], two);
    assert_eq!(out.status.code(), Some(66), "{}", printed(&out));
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("2 test(s) ignored"),
        "the refusal does not count the ignored tests: {}",
        printed(&out)
    );

    // Summed across test binaries: an ignore in the second is caught too.
    let out = tier_running(&caller, &["--refuse-ignored"], &format!("{ok}; {two}"));
    assert_eq!(out.status.code(), Some(66), "{}", printed(&out));

    // Only a verdict at the start of a line counts; a quoted summary is not one.
    let out = tier_running(
        &caller,
        &["--refuse-ignored"],
        "echo '  the oracle said: test result: ok. 1 passed; 0 failed; 9 ignored'",
    );
    assert!(
        out.status.success(),
        "a quoted summary was read: {}",
        printed(&out)
    );

    // Not asked, not refused.
    let out = tier_running(&caller, &[], two);
    assert!(out.status.success(), "refused unasked: {}", printed(&out));

    // Both gates at once, in either order.
    let out = tier_running(
        &caller,
        &["--refuse-ignored", "--refuse-skips"],
        "echo 'SKIP: x'",
    );
    assert_eq!(out.status.code(), Some(66), "{}", printed(&out));
    let out = tier_running(&caller, &["--refuse-skips", "--refuse-ignored"], two);
    assert_eq!(out.status.code(), Some(66), "{}", printed(&out));
}

/// A command that failed keeps its own status: its story is better than a
/// skip or ignored count, so the gates only refuse a pass.
#[test]
fn a_failing_tier_keeps_its_own_status_through_both_gates() {
    let caller = Caller::new("tier-gates-fail");
    let out = tier_running(
        &caller,
        &["--refuse-skips", "--refuse-ignored"],
        "echo 'SKIP: x'; echo 'test result: FAILED. 1 passed; 1 failed; 2 ignored; 0 measured; 0 filtered out'; exit 3",
    );
    assert_eq!(out.status.code(), Some(3), "{}", printed(&out));
}

/// `tier.sh TIER -- COMMAND`: the budget is a row of the caller's own
/// `scripts/tier-budgets.txt`, so a repository keeps one measured table as
/// data while the runner stays here. A tier with no row is refused rather
/// than run unbudgeted.
#[test]
fn the_tier_runner_reads_a_budget_from_the_callers_table() {
    let caller = Caller::new("tier-table");
    fs::write(
        caller.root.join("scripts").join("tier-budgets.txt"),
        "# tier  lines  bytes   measured 2026-10-06\nunit    2      200\n\nloud    1      100  # a comment after the row\n",
    )
    .unwrap();

    let out = caller.core(&["tier", "unit", "--", "echo", "hello"], &[]);
    assert!(out.status.success(), "{}", printed(&out));
    assert!(
        caller.root.join("tmp/logs/unit.log").is_file(),
        "the log is not named for the tier: {}",
        printed(&out)
    );

    let out = caller.core(
        &[
            "tier",
            "loud",
            "--",
            "bash",
            "-c",
            "echo one; echo two; echo three",
        ],
        &[],
    );
    assert_eq!(
        out.status.code(),
        Some(65),
        "the row's budget was not applied: {}",
        printed(&out)
    );

    let out = caller.core(&["tier", "absent", "--", "echo", "hi"], &[]);
    assert_eq!(out.status.code(), Some(2), "{}", printed(&out));
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("tier-budgets.txt"),
        "the refusal does not name the table: {}",
        printed(&out)
    );

    // The gates apply to the table form too.
    let out = caller.core(
        &["tier", "--refuse-skips", "unit", "--", "echo", "SKIP: x"],
        &[],
    );
    assert_eq!(out.status.code(), Some(66), "{}", printed(&out));
}

/// No table at all is refused, naming the file that would provide one.
#[test]
fn the_tier_runner_refuses_the_table_form_without_a_table() {
    let caller = Caller::new("tier-no-table");
    let out = caller.core(&["tier", "unit", "--", "echo", "hi"], &[]);
    assert_eq!(out.status.code(), Some(2), "{}", printed(&out));
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("scripts/tier-budgets.txt"),
        "{}",
        printed(&out)
    );
}