amont 1.63.0

Opinionated git hooks that judge what you are committing, not what is on disk
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
//! The checks whose assertions are about ELAPSED TIME.
//!
//! `amont` runs a check under two clocks: a silence budget (`amont.idleTimeout`
//! — a tool that has printed nothing for N seconds is presumed stuck) and a
//! total ceiling (`amont.timeout`). The tests below prove the wiring by
//! actually spending the seconds, which makes them the only tests in this
//! suite that can fail because of what ELSE was running.
//!
//! # Why they are their own binary
//!
//! They used to live in `external.rs`. `a_chatty_check_outlives_the_idle_budget`
//! ticks every 0.2s for fifteen seconds against a ten-second budget, and its
//! neighbours there held `sleep 300` — so it competed for a scheduler slot with
//! twenty-odd tests each spawning `amont`, `git` and shell subprocesses. It
//! failed roughly two runs in three, and adding just two unrelated tests to
//! that file took it to three failures in three.
//!
//! `cargo` runs test BINARIES sequentially, so a file of their own hands them
//! the machine. The `SEQUENTIAL` lock then keeps them from competing with each
//! other, which matters because two of them park a `sleep 300` while a third is
//! trying to be scheduled every 200ms.
//!
//! Neither half is a retry and neither weakens an assertion: the budgets, the
//! tick rate and every expectation are exactly as they were. What changed is
//! only how much else is happening on the machine while the clock is read.
//!
//! # Which run where
//!
//! A commit runs the ones it can afford, each a few seconds: the ceiling
//! kill, the idle kill, contiguous output, the lock-wait and marker rules.
//! The CPU-load and lock-wait scenarios, 4 to 26 s each and 91 s together,
//! and the 15 s proof that output resets the idle clock (pinned without
//! sleeping by `common::tests::the_clocks_judge_silence_and_ceiling_
//! separately`) are `#[ignore]`d and run in CI's hooks job
//! (`make test-load`), ADR-0009's "skipping the check by name and leaning on
//! CI" (decisions plan 2026-10-17-amont-tests-follow-user-flows).
//!
//! The *decisions* these tests exercise are pinned to the second, without any
//! sleeping, by `common::tests::the_clocks_judge_silence_and_ceiling_separately`
//! in the runtime. These prove the wiring end to end.

mod common;

use common::Repo;
use std::process::Command;
use std::sync::{Mutex, MutexGuard};

/// One timing test at a time.
///
/// `PoisonError` is unwrapped through deliberately: a panicking test poisons
/// the lock, and turning every subsequent test into a second failure would
/// bury the first one — which is the report that actually says what broke.
static SEQUENTIAL: Mutex<()> = Mutex::new(());

fn alone() -> MutexGuard<'static, ()> {
    SEQUENTIAL.lock().unwrap_or_else(|e| e.into_inner())
}

/// Trust is a separate decision, so every test about what a declared check
/// does has to make it first — otherwise they would all be testing the trust
/// gate instead.
fn manifest(r: &Repo, body: &str) {
    r.stage("amont.conf", body);
    let out = Command::new(env!("CARGO_BIN_EXE_amont"))
        .arg("trust")
        .current_dir(r.path(""))
        .output()
        .expect("amont trust");
    assert!(out.status.success(), "could not trust the manifest");
}

/// One hung tool must not hold the commit — and the parked unstaged work —
/// hostage. The budget kills it and the check FAILS, loudly, with the config
/// key that raises the budget named.
#[cfg(unix)]
#[test]
fn a_check_that_outlives_the_budget_is_killed_and_fails() {
    let _alone = alone();
    let r = Repo::new();
    // `exec`, so the sleep IS the spawned process rather than a grandchild:
    // the kill only reaches the direct child, and a grandchild inheriting the
    // harness's output pipe would hold this TEST hostage the way no real git
    // invocation can (git lends hooks its own stdio, it does not read a pipe).
    let body = "#!/bin/sh\nexec sleep 300\n";
    staged_exec(&r, "slow.sh", body);
    manifest(&r, "pre-commit  slowpoke  *  block  ./slow.sh\n");
    r.git(&["config", "amont.timeout", "1"]);

    let started = std::time::Instant::now();
    let run = r.hook("pre-commit", &[]);
    assert!(
        started.elapsed() < std::time::Duration::from_secs(60),
        "the deadline never fired"
    );
    assert!(!run.passed(), "a killed check must fail:\n{}", run.output());
    assert!(
        run.says("timed out") && run.says("amont.timeout"),
        "must say what happened and how to change the budget:\n{}",
        run.output()
    );
}

/// The other clock. A tool that goes quiet is stuck; the silence budget
/// kills it, the check fails, and the message names the silence — not the
/// wall clock, which is off here and must not be blamed.
#[cfg(unix)]
#[test]
fn a_silent_check_is_killed_by_the_idle_budget() {
    let _alone = alone();
    let r = Repo::new();
    let body = "#!/bin/sh\nexec sleep 300\n";
    staged_exec(&r, "quiet.sh", body);
    manifest(&r, "pre-commit  quiet  *  block  ./quiet.sh\n");
    r.git(&["config", "amont.timeout", "0"]);
    r.git(&["config", "amont.idleTimeout", "1"]);

    let started = std::time::Instant::now();
    let run = r.hook("pre-commit", &[]);
    assert!(
        started.elapsed() < std::time::Duration::from_secs(60),
        "the silence budget never fired"
    );
    assert!(!run.passed(), "a killed check must fail:\n{}", run.output());
    assert!(
        run.says("printed nothing") && run.says("amont.idleTimeout"),
        "must blame the silence and name its key:\n{}",
        run.output()
    );
    assert!(
        !run.says("amont.timeout <secs>"),
        "the ceiling was off and must not be blamed:\n{}",
        run.output()
    );
}

/// The point of the second clock: a tool that keeps talking is slow, not
/// stuck, and outlives a silence budget shorter than its total run.
#[cfg(unix)]
#[test]
#[ignore = "real-clock load scenario: CI runs it (`make test-load`), not every commit (ADR-0009)"]
fn a_chatty_check_outlives_the_idle_budget() {
    let _alone = alone();
    let r = Repo::new();
    let body =
        "#!/bin/sh\ni=0\nwhile [ $i -lt 75 ]; do i=$((i+1)); echo tick $i; sleep 0.2; done\n";
    staged_exec(&r, "chatty.sh", body);
    manifest(&r, "pre-commit  chatty  *  block  ./chatty.sh\n");
    // Fifteen seconds of ticks every 0.2s against a ten-second budget. The
    // 50x margin is for a machine running the whole suite at once, where a
    // `sleep 0.2` has been seen to take 25 times that — never for the tool
    // itself, which is the thing being measured. The decision itself is
    // pinned to the second by `common::tests::the_clocks_judge_silence_and_
    // ceiling_separately`; this test only proves the wiring end to end.
    r.git(&["config", "amont.idleTimeout", "10"]);

    let run = r.hook("pre-commit", &[]);
    assert!(
        run.passed(),
        "fifteen seconds of steady output must not trip a ten-second silence budget:\n{}",
        run.output()
    );
    assert!(!run.says("killed"), "{}", run.output());
}

/// THE interleave regression: two concurrent checks, each printing around a
/// deliberate pause, must come out as two CONTIGUOUS blocks. Against the
/// pre-capture code this fails almost every run — both probes are mid-sleep
/// together and their second lines land across each other's.
#[cfg(unix)]
#[test]
fn concurrent_checks_emit_contiguous_blocks() {
    let _alone = alone();
    let r = Repo::new();
    for name in ["alpha", "beta"] {
        staged_exec(
            &r,
            &format!("{name}.sh"),
            &format!("#!/bin/sh\necho {name}-first\nsleep 1\necho {name}-second\nexit 0\n"),
        );
    }
    manifest(
        &r,
        "pre-commit  alpha  *  warn  ./alpha.sh\n\
         pre-commit  beta  *  warn  ./beta.sh\n",
    );

    let run = r.hook("pre-commit", &[]);
    assert!(run.passed(), "{}", run.output());
    let out = run.output();
    for (name, other) in [("alpha", "beta"), ("beta", "alpha")] {
        let first = out
            .find(&format!("{name}-first"))
            .unwrap_or_else(|| panic!("{name}-first missing:\n{out}"));
        let second = out
            .find(&format!("{name}-second"))
            .unwrap_or_else(|| panic!("{name}-second missing:\n{out}"));
        assert!(first < second, "{name}'s lines arrived reversed:\n{out}");
        assert!(
            !out[first..second].contains(other),
            "{name}'s block was interleaved with {other}'s:\n{out}"
        );
    }
}

// --- Busy is not stuck (ADR-0008, `hooks.liveness`) --------------------------
//
// A silent check whose process tree is measurably working is not killed by
// the silence budget; it answers to the ceiling. Every fixture below is built
// so that NOTHING depends on amont returning: the root stays alive for the
// whole run (it is what amont waits on), every worker stops itself within
// twenty seconds, the scripts kill their own group on exit, and the harness
// runs amont in a process group of its own under a watchdog that SIGKILLs
// all of it and fails the test at sixty seconds.
//
// Budgets: idle 4 s, ceiling 12 s. A check the silence budget wrongly kills
// dies at ~4 s; one kept alive by its CPU dies at the ceiling, ~12 s. Four
// seconds, not two: in a full workspace run a fork can stall for a second or
// more on a loaded machine, and a process blocked in exec burns no CPU — the
// tree then legitimately looks idle, and a two-second budget has no slack.
// The fixtures run as `sh ./x.sh`, not `./x.sh`: macOS can hold a freshly
// written executable in execve for seconds while it is assessed, most of all
// right after a test run has created hundreds of new files. Such a process
// has done no work — idle, correctly — so exec'ing the script directly made
// these tests fail intermittently with the check killed before its first
// line (the sampler saw one root, under 1 ms of CPU, no children). Running
// the system `sh` and reading the script as data takes the fresh file out of
// the exec path.
// Each busy fixture also prints one line once its burn is running, so its
// own start-up is not counted as silence, and runs under AMONT_CPU_TRACE so
// a failure shows what the sampler saw.

#[cfg(any(target_os = "linux", target_os = "macos"))]
const WATCHDOG: std::time::Duration = std::time::Duration::from_secs(60);

/// A busy loop in `sh` that stops itself after `secs`: a burst of pure
/// arithmetic between clock checks, so it spends its time on CPU rather
/// than spawning. It says `burning` once, when the loop is about to start.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn burn(secs: u32) -> String {
    format!(
        "end=$(( $(date +%s) + {secs} ))\n\
         echo burning\n\
         while :; do i=0; while [ $i -lt 20000 ]; do i=$((i+1)); done; \
         [ \"$(date +%s)\" -ge \"$end\" ] && break; done\n"
    )
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn script(r: &Repo, name: &str, body: &str) {
    staged_exec(r, name, &format!("#!/bin/sh\ntrap 'kill 0' EXIT\n{body}"));
}

/// Write `name` as a fixture executable, primed (see
/// [`common::fixture_exec`]: the first exec of a fresh file is not timed),
/// and stage it.
#[cfg(unix)]
fn staged_exec(r: &Repo, name: &str, body: &str) {
    common::fixture_exec(&r.path(name), body);
    r.git(&["add", name]);
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn busy_budgets(r: &Repo) {
    r.git(&["config", "amont.idleTimeout", "4"]);
    r.git(&["config", "amont.timeout", "12"]);
}

/// A fresh trace file for one test.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn trace_file(tag: &str) -> std::path::PathBuf {
    let p = std::env::temp_dir().join(format!("amont-cpu-trace-{}-{tag}", std::process::id()));
    let _ = std::fs::remove_file(&p);
    p
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn killed_at_the_ceiling(
    run: &common::HookRun,
    took: std::time::Duration,
    trace: &std::path::Path,
) {
    let seen = std::fs::read_to_string(trace).unwrap_or_default();
    let _ = std::fs::remove_file(trace);
    assert!(!run.passed(), "a killed check must fail:\n{}", run.output());
    assert!(
        took >= std::time::Duration::from_secs(11),
        "killed after {took:?}: the silence budget fired on a busy check:\n{}\n\
         what the sampler saw (pid start ppid cpu_ns):\n{seen}",
        run.output()
    );
    assert!(
        run.says("timed out") && run.says("kept its CPU busy"),
        "must be the ceiling, naming the busy tree:\n{}\nsampler:\n{seen}",
        run.output()
    );
}

/// The case this exists for: silent, and working in the root itself.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
#[ignore = "real-clock load scenario: CI runs it (`make test-load`), not every commit (ADR-0009)"]
fn a_silent_busy_check_answers_to_the_ceiling_not_the_silence_budget() {
    let _alone = alone();
    let r = Repo::new();
    script(&r, "busy.sh", &burn(24));
    manifest(&r, "pre-commit  busy  *  block  sh ./busy.sh\n");
    busy_budgets(&r);
    let trace = trace_file("busy");
    let (run, took) = r.hook_watched(
        "pre-commit",
        &[("AMONT_CPU_TRACE", trace.as_os_str())],
        WATCHDOG,
    );
    killed_at_the_ceiling(&run, took, &trace);
}

/// Work done in short-lived children the root forks and reaps one after
/// another — a test runner's worker per file. A sum over LIVE processes
/// misses all of it; the parent's reaped-children time does not.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
#[ignore = "real-clock load scenario: CI runs it (`make test-load`), not every commit (ADR-0009)"]
fn fork_per_file_work_keeps_a_silent_check_alive() {
    let _alone = alone();
    let r = Repo::new();
    let body = "end=$(( $(date +%s) + 24 ))\n\
                echo burning\n\
                while [ \"$(date +%s)\" -lt \"$end\" ]; do \
                sh -c 'i=0; while [ $i -lt 3000 ]; do i=$((i+1)); done'; done\n";
    script(&r, "churn.sh", body);
    manifest(&r, "pre-commit  churn  *  block  sh ./churn.sh\n");
    busy_budgets(&r);
    let trace = trace_file("churn");
    let (run, took) = r.hook_watched(
        "pre-commit",
        &[("AMONT_CPU_TRACE", trace.as_os_str())],
        WATCHDOG,
    );
    killed_at_the_ceiling(&run, took, &trace);
}

/// A worker whose parent exits is reparented away from the tree. Once the
/// sampler has SEEN it, it keeps counting. The intermediate waits until the
/// worker's pid appears in `AMONT_CPU_TRACE` before it exits, so the test
/// never depends on winning the discovery race — which the guarantee does
/// not cover (a worker orphaned before it was ever seen is invisible). The
/// root then idles in `sleep`, so the only CPU left is the orphan's.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
#[ignore = "real-clock load scenario: CI runs it (`make test-load`), not every commit (ADR-0009)"]
fn a_seen_worker_keeps_counting_after_its_parent_exits() {
    let _alone = alone();
    let r = Repo::new();
    let trace = trace_file("orphan");
    let worker = burn(24).trim_end().replace('\n', "; ");
    let body = format!(
        "sh -c '({worker}) & w=$!; n=0; \
         while [ $n -lt 200 ]; do grep -q \"^$w \" \"$AMONT_CPU_TRACE\" 2>/dev/null && break; \
         n=$((n+1)); sleep 0.05; done'\n\
         sleep 24\n"
    );
    script(&r, "orphan.sh", &body);
    manifest(&r, "pre-commit  orphan  *  block  sh ./orphan.sh\n");
    busy_budgets(&r);
    let (run, took) = r.hook_watched(
        "pre-commit",
        &[("AMONT_CPU_TRACE", trace.as_os_str())],
        WATCHDOG,
    );
    killed_at_the_ceiling(&run, took, &trace);
}

/// A tool blocked on nothing — the hang the silence budget exists for —
/// still dies at the budget, and the message now says the CPU was measured
/// idle, naming the span the claim rests on.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn an_idle_silent_check_still_dies_at_the_budget_and_says_it_was_measured() {
    let _alone = alone();
    let r = Repo::new();
    // `exec`: sleep IS the root. A child sleep would outlive the kill and hold
    // amont's output pipe until it ended — the grandchild limitation this
    // change does not address.
    script(&r, "idle.sh", "exec sleep 30\n");
    manifest(&r, "pre-commit  idle  *  block  ./idle.sh\n");
    r.git(&["config", "amont.idleTimeout", "3"]);
    r.git(&["config", "amont.timeout", "0"]);
    let (run, took) = r.hook_watched("pre-commit", &[], WATCHDOG);
    assert!(!run.passed(), "{}", run.output());
    assert!(
        took < std::time::Duration::from_secs(10),
        "took {took:?}:\n{}",
        run.output()
    );
    assert!(
        run.says("printed nothing") && run.says("did no measurable CPU work"),
        "must say it was silent AND measured idle:\n{}",
        run.output()
    );
}

/// `amont.idleCpuCredit false` restores the silence-only rule: the same busy
/// check dies at the budget, and the message makes no CPU claim.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
#[ignore = "real-clock load scenario: CI runs it (`make test-load`), not every commit (ADR-0009)"]
fn with_cpu_credit_off_a_busy_silent_check_dies_at_the_budget() {
    let _alone = alone();
    let r = Repo::new();
    script(&r, "busy.sh", &burn(20));
    manifest(&r, "pre-commit  busy  *  block  sh ./busy.sh\n");
    busy_budgets(&r);
    r.git(&["config", "amont.idleCpuCredit", "false"]);
    let (run, took) = r.hook_watched("pre-commit", &[], WATCHDOG);
    assert!(!run.passed(), "{}", run.output());
    assert!(
        took < std::time::Duration::from_secs(7),
        "took {took:?}:\n{}",
        run.output()
    );
    assert!(
        run.says("printed nothing for 4s and was killed"),
        "{}",
        run.output()
    );
    assert!(
        !run.says("CPU"),
        "no CPU claim when CPU is not sampled:\n{}",
        run.output()
    );
}

// --- Waiting is not stuck (ADR-0009) ----------------------------------------

/// The exact line cargo prints while another cargo holds its lock.
#[cfg(any(target_os = "linux", target_os = "macos"))]
const CARGO_WAIT: &str = "    Blocking waiting for file lock on build directory";

/// A tool that says it is waiting on a lock, then goes silent for three
/// times the silence budget, is not killed: the clock does not run during a
/// declared wait. It passes, and says what it waited for.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
#[ignore = "real-clock load scenario: CI runs it (`make test-load`), not every commit (ADR-0009)"]
fn a_declared_lock_wait_outlives_the_silence_budget() {
    let _alone = alone();
    let r = Repo::new();
    // Not `script()`: its `trap 'kill 0' EXIT` is for fixtures that are
    // killed, and a script that exits on its own would take amont's whole
    // process group down with it.
    {
        use std::os::unix::fs::PermissionsExt;
        r.stage(
            "wait.sh",
            &format!(
                "#!/bin/sh\necho '{CARGO_WAIT}' >&2\nsleep 6\necho '    Checking x v0.1.0' >&2\n"
            ),
        );
        std::fs::set_permissions(r.path("wait.sh"), std::fs::Permissions::from_mode(0o755))
            .expect("chmod");
        r.git(&["add", "wait.sh"]);
    }
    manifest(&r, "pre-commit  locked  *  block  sh ./wait.sh\n");
    r.git(&["config", "amont.idleTimeout", "2"]);
    r.git(&["config", "amont.timeout", "12"]);
    let (run, took) = r.hook_watched("pre-commit", &[], WATCHDOG);
    assert!(
        run.passed(),
        "a declared wait is not a hang:\n{}",
        run.output()
    );
    assert!(took < std::time::Duration::from_secs(11), "took {took:?}");
    assert!(
        run.says("waited") && run.says("the cargo lock on the build directory"),
        "a passing check says what it waited for:\n{}",
        run.output()
    );
}

/// A declared wait answers to `amont.lockWait`, and the message names the
/// lock, its likely holders and the key.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn a_lock_wait_past_its_budget_is_killed_and_named() {
    let _alone = alone();
    let r = Repo::new();
    script(
        &r,
        "stuck.sh",
        &format!("echo '{CARGO_WAIT}' >&2\nexec sleep 30\n"),
    );
    manifest(&r, "pre-commit  locked  *  block  sh ./stuck.sh\n");
    r.git(&["config", "amont.idleTimeout", "60"]);
    r.git(&["config", "amont.lockWait", "2"]);
    r.git(&["config", "amont.timeout", "12"]);
    let (run, took) = r.hook_watched("pre-commit", &[], WATCHDOG);
    assert!(!run.passed(), "{}", run.output());
    assert!(took < std::time::Duration::from_secs(8), "took {took:?}");
    assert!(
        run.says("waited 2s for the cargo lock on the build directory")
            && run.says("amont.lockWait"),
        "must name the wait, the lock and the key:\n{}",
        run.output()
    );
}

/// Only stderr is read for markers: the same words on stdout are output
/// like any other, and the silence budget still applies after them.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn a_marker_on_stdout_does_not_pause_the_clock() {
    let _alone = alone();
    let r = Repo::new();
    script(
        &r,
        "out.sh",
        &format!("echo '{CARGO_WAIT}'\nexec sleep 30\n"),
    );
    manifest(&r, "pre-commit  locked  *  block  sh ./out.sh\n");
    r.git(&["config", "amont.idleTimeout", "2"]);
    r.git(&["config", "amont.timeout", "0"]);
    let (run, took) = r.hook_watched("pre-commit", &[], WATCHDOG);
    assert!(!run.passed(), "{}", run.output());
    assert!(took < std::time::Duration::from_secs(10), "took {took:?}");
    assert!(run.says("printed nothing"), "{}", run.output());
}

/// While the CPU cannot be measured, the silence budget is the extended
/// one, `idleTimeout × idleLoadScale`: not killed at 2 s, killed near 8 s,
/// even with the ceiling off.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
#[ignore = "real-clock load scenario: CI runs it (`make test-load`), not every commit (ADR-0009)"]
fn an_unmeasured_check_answers_to_the_extended_budget() {
    let _alone = alone();
    let r = Repo::new();
    // A child, so the walk has more than the root to count and the cap of
    // zero below makes every snapshot partial. Its output goes nowhere:
    // amont kills only the root, and a child holding the pipe would keep
    // amont reading until it exits.
    script(&r, "idle.sh", "sleep 30 >/dev/null 2>&1 &\nwait\n");
    manifest(&r, "pre-commit  idle  *  block  ./idle.sh\n");
    r.git(&["config", "amont.idleTimeout", "2"]);
    r.git(&["config", "amont.timeout", "0"]);
    let zero = std::ffi::OsString::from("0");
    let four = std::ffi::OsString::from("4");
    let held = std::ffi::OsString::from("held");
    let (run, took) = r.hook_watched_unpinned(
        "pre-commit",
        &[
            ("AMONT_CPU_MAX_PROCS", zero.as_os_str()),
            ("AMONT_IDLE_LOAD_SCALE", four.as_os_str()),
            ("AMONT_HOST_SLOT", held.as_os_str()),
        ],
        WATCHDOG,
    );
    assert!(!run.passed(), "{}", run.output());
    assert!(
        took >= std::time::Duration::from_secs(7) && took < std::time::Duration::from_secs(30),
        "took {took:?}: the extended budget is 8 s\n{}",
        run.output()
    );
    assert!(
        run.says("CPU could not be measured") && run.says("amont.idleLoadScale"),
        "must say why the budget is not the configured one:\n{}",
        run.output()
    );
}

/// A Rust repository whose `cargo` is a shim that sleeps through clippy,
/// for the host-slot fixtures.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn slow_clippy_repo() -> Repo {
    let r = Repo::new();
    r.stage(
        "Cargo.toml",
        "[package]\nname = \"x\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    );
    r.stage("src/lib.rs", "pub fn x() {}\n");
    let dir = r.path(".git/toolshims");
    std::fs::create_dir_all(&dir).expect("mkdir");
    common::fixture_exec(
        &dir.join("cargo"),
        "#!/bin/sh\ncase \"$1\" in\n  --version) echo 'cargo 1.0.0 (fake)';;\n  \
         clippy) [ \"$2\" = --version ] && { echo clippy; exit 0; }; sleep 5;;\nesac\nexit 0\n",
    );
    r
}

/// Two repositories commit at once with one host slot: their clippys run
/// one after the other, not together. Five-second clippys, so a loaded
/// machine cannot blur "one after the other" (≥ 10 s) into "together"
/// (≈ 5 s). With a slot directory another user
/// could have made (mode 0755), queueing is off, both run at once, and each
/// says why.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
#[ignore = "real-clock load scenario: CI runs it (`make test-load`), not every commit (ADR-0009)"]
fn heavy_checks_queue_for_a_host_slot() {
    let _alone = alone();
    let slots = std::env::temp_dir().join(format!("amont-slots-fixture-{}", std::process::id()));
    let run_pair = |slots: &std::path::Path| -> (std::time::Duration, Vec<String>) {
        // Both repositories exist, their shims primed, before the clock
        // starts: the span measured is the two hooks and nothing else.
        let repos = [slow_clippy_repo(), slow_clippy_repo()];
        let started = std::time::Instant::now();
        let outputs: Vec<String> = std::thread::scope(|s| {
            let handles: Vec<_> = repos
                .iter()
                .map(|r| {
                    s.spawn(move || {
                        let path = std::ffi::OsString::from(format!(
                            "{}:{}",
                            r.path(".git/toolshims").display(),
                            std::env::var("PATH").unwrap_or_default()
                        ));
                        let one = std::ffi::OsString::from("1");
                        let (run, _) = r.hook_watched_unpinned(
                            "pre-commit-clippy",
                            &[
                                ("PATH", path.as_os_str()),
                                ("AMONT_SLOT_DIR", slots.as_os_str()),
                                ("AMONT_HOST_SLOTS", one.as_os_str()),
                            ],
                            WATCHDOG,
                        );
                        assert!(run.passed(), "{}", run.output());
                        run.output()
                    })
                })
                .collect();
            handles
                .into_iter()
                .map(|h| h.join().expect("join"))
                .collect()
        });
        (started.elapsed(), outputs)
    };

    let _ = std::fs::remove_dir_all(&slots);
    let (took, outputs) = run_pair(&slots);
    assert!(
        took >= std::time::Duration::from_secs(10),
        "two 5 s clippys with one slot took {took:?}: they ran together"
    );
    assert_eq!(
        outputs
            .iter()
            .filter(|o| o.contains("for a host slot"))
            .count(),
        1,
        "exactly one of the two waited, and said so:\n{outputs:#?}"
    );

    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::remove_dir_all(&slots);
    std::fs::create_dir_all(&slots).expect("mkdir");
    std::fs::set_permissions(&slots, std::fs::Permissions::from_mode(0o755)).expect("chmod");
    let (took, outputs) = run_pair(&slots);
    assert!(
        took < std::time::Duration::from_millis(8500),
        "an unsafe slot directory must not queue: took {took:?}"
    );
    for out in outputs {
        assert!(out.contains("host slots are off"), "{out}");
    }
    let _ = std::fs::remove_dir_all(&slots);
}

/// A Rust repository whose `cargo` prints a look-alike wait line and hangs
/// on its first clippy, then passes; `always` makes it hang every time.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn waiting_clippy_repo(always: bool) -> Repo {
    let r = Repo::new();
    r.stage(
        "Cargo.toml",
        "[package]\nname = \"x\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    );
    r.stage("src/lib.rs", "pub fn x() {}\n");
    let dir = r.path(".git/toolshims");
    std::fs::create_dir_all(&dir).expect("mkdir");
    let seen = dir.join("seen");
    let guard = if always {
        String::new()
    } else {
        format!("[ -f '{0}' ] && exit 0; touch '{0}'; ", seen.display())
    };
    common::fixture_exec(
        &dir.join("cargo"),
        &format!(
            "#!/bin/sh\ncase \"$1\" in\n  --version) echo 'cargo 1.0.0 (fake)';;\n  \
             clippy) [ \"$2\" = --version ] && {{ echo clippy; exit 0; }}; {guard}\
             echo 'waiting for lock on x' >&2; exec sleep 30;;\nesac\nexit 0\n"
        ),
    );
    r.git(&["config", "amont.idleTimeout", "2"]);
    r.git(&["config", "amont.timeout", "12"]);
    r
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn with_shims(r: &Repo) -> std::ffi::OsString {
    std::ffi::OsString::from(format!(
        "{}:{}",
        r.path(".git/toolshims").display(),
        std::env::var("PATH").unwrap_or_default()
    ))
}

/// Run as the `pre-commit` STAGE, which is how git runs it: a check run on
/// its own by name inherits the terminal, where nobody reads its lines and
/// only the ceiling applies.
///
/// A built-in killed while its last line read like a wait is retried once,
/// says so, and passes when the retry does — with no failure text. A
/// second kill is final, and both attempts fit in one ceiling.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
#[ignore = "real-clock load scenario: CI runs it (`make test-load`), not every commit (ADR-0009)"]
fn a_wait_like_kill_is_retried_once() {
    let _alone = alone();
    let r = waiting_clippy_repo(false);
    let path = with_shims(&r);
    let (run, took) = r.hook_watched("pre-commit", &[("PATH", path.as_os_str())], WATCHDOG);
    assert!(run.passed(), "the retry passed:\n{}", run.output());
    assert!(took < std::time::Duration::from_secs(8), "took {took:?}");
    assert!(
        run.says("clippy") && run.says("was killed while it looked like it was waiting"),
        "names the check, not the program:\n{}",
        run.output()
    );
    assert_eq!(
        run.output().matches("retrying once").count(),
        1,
        "{}",
        run.output()
    );
    assert!(
        !run.says("printed nothing"),
        "no failure text:\n{}",
        run.output()
    );

    let r = waiting_clippy_repo(true);
    let path = with_shims(&r);
    let (run, took) = r.hook_watched("pre-commit", &[("PATH", path.as_os_str())], WATCHDOG);
    assert!(!run.passed(), "{}", run.output());
    assert!(
        took < std::time::Duration::from_secs(12),
        "one ceiling: took {took:?}"
    );
    assert_eq!(
        run.output().matches("retrying once").count(),
        1,
        "{}",
        run.output()
    );
    assert!(run.says("printed nothing"), "{}", run.output());
}

/// A declared external is never retried: a user's command may not be safe
/// to run twice.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn a_declared_check_is_never_retried() {
    let _alone = alone();
    let r = Repo::new();
    script(
        &r,
        "look.sh",
        "echo 'waiting for lock on x' >&2\nexec sleep 30\n",
    );
    manifest(&r, "pre-commit  look  *  block  ./look.sh\n");
    r.git(&["config", "amont.idleTimeout", "2"]);
    r.git(&["config", "amont.timeout", "12"]);
    let (run, _) = r.hook_watched("pre-commit", &[], WATCHDOG);
    assert!(!run.passed(), "{}", run.output());
    assert!(!run.says("retrying once"), "{}", run.output());
}