amont-agent 2.10.0

A guard that inspects a shell command before Claude Code runs it
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
//! The wire contract, driven through the real binary.
//!
//! Claude Code parses this hook's stdout as JSON when it starts with `{`, and
//! silently ignores it otherwise. "Silently" is the important word: a hook that
//! prints one stray line produces no error anywhere the author will look, and
//! the guard is simply gone. So these tests assert on the exact bytes, not on
//! "something sensible happened".

use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};

struct Reply {
    code: i32,
    stdout: String,
}

impl Reply {
    fn json(&self) -> Option<serde_json::Value> {
        serde_json::from_str(&self.stdout).ok()
    }
    fn decision(&self) -> Option<String> {
        Some(
            self.json()?
                .get("hookSpecificOutput")?
                .get("permissionDecision")?
                .as_str()?
                .to_string(),
        )
    }
    fn reason(&self) -> String {
        self.json()
            .and_then(|v| {
                let o = v.get("hookSpecificOutput")?.clone();
                Some(
                    o.get("permissionDecisionReason")
                        .or_else(|| o.get("additionalContext"))?
                        .as_str()?
                        .to_string(),
                )
            })
            .unwrap_or_default()
    }
}

/// A scratch config dir per test, so nothing here writes to the real journal.
fn home() -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "amont-agent-hook-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    std::fs::create_dir_all(&dir).expect("scratch dir");
    dir
}

fn send(payload: &str) -> Reply {
    send_with_path(payload, None)
}

/// As [`send`], with `PATH` replaced entirely by `bin_dir`.
fn send_with_path_only(payload: &str, bin_dir: &std::path::Path) -> Reply {
    send_inner(payload, bin_dir.display().to_string())
}

/// As [`send`], with `bin_dir` prepended to `PATH`.
///
/// The guidance check shells out to whatever `amont` resolves to, so a test
/// about its answer must supply that `amont` rather than depend on the
/// developer's machine having one — and on which version it is.
fn send_with_path(payload: &str, bin_dir: Option<&std::path::Path>) -> Reply {
    let path = match bin_dir {
        Some(d) => {
            let rest = std::env::var("PATH").unwrap_or_default();
            format!("{}:{rest}", d.display())
        }
        None => std::env::var("PATH").unwrap_or_default(),
    };
    send_inner(payload, path)
}

fn send_inner(payload: &str, path: String) -> Reply {
    let mut child = Command::new(env!("CARGO_BIN_EXE_amont-agent"))
        .arg("hook")
        .env("CLAUDE_CONFIG_DIR", home())
        .env("PATH", path)
        // The guard must not be silenced by the developer's own environment
        // while its own tests are running.
        .env_remove("AMONT_AGENT_OFF")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("the binary runs");
    child
        .stdin
        .take()
        .expect("stdin")
        .write_all(payload.as_bytes())
        .expect("write the payload");
    let out = child.wait_with_output().expect("the hook exits");
    Reply {
        code: out.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
    }
}

fn bash(command: &str) -> String {
    format!(
        r#"{{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"/tmp",
             "session_id":"sess1234","tool_use_id":"t1","permission_mode":"default",
             "tool_input":{{"command":{}}}}}"#,
        serde_json::Value::String(command.to_string())
    )
}

#[test]
fn a_mutating_command_piped_into_tail_is_denied() {
    let r = send(&bash("git push origin main 2>&1 | tail -5"));
    assert_eq!(r.decision().as_deref(), Some("deny"));
    assert_eq!(r.code, 0);
}

/// The refusal has to teach the fix. `permissionDecisionReason` is the only
/// text the model receives, so a refusal that does not carry the remedy is a
/// refusal it can only work around.
#[test]
fn the_refusal_names_the_mechanism_and_the_remedy() {
    let reason = send(&bash("git push origin main 2>&1 | tail -5")).reason();
    assert!(reason.contains("exit status"), "{reason}");
    assert!(reason.contains("on its own"), "{reason}");
}

/// Zero bytes, not `{}` and not a newline. Anything on stdout is parsed.
#[test]
fn stdout_is_empty_when_nothing_fires() {
    for command in [
        "git status --short",
        "git tag --sort=-v:refname | head -5",
        "cargo test --workspace",
    ] {
        let r = send(&bash(command));
        assert_eq!(r.stdout, "", "expected silence for {command:?}");
        assert_eq!(r.code, 0);
    }
}

/// Every one of these WILL arrive: a new event, a new tool, a truncated write,
/// a payload that gained a field. None of them is a reason to refuse a command.
#[test]
fn an_unreadable_payload_is_never_an_opinion() {
    for payload in [
        "",
        "{",
        "null",
        "[]",
        "not json at all",
        r#"{"hook_event_name":"PostToolUse","tool_name":"Bash"}"#,
        r#"{"hook_event_name":"PreToolUse","tool_name":"Read"}"#,
        r#"{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{}}"#,
    ] {
        let r = send(payload);
        assert_eq!(r.stdout, "", "expected silence for {payload:?}");
        assert_eq!(r.code, 0, "expected exit 0 for {payload:?}");
    }
}

/// `allow` would short-circuit the user's own permission prompt — a guard that
/// approves everything it has no objection to has switched off the permission
/// system it was installed beside. Silence is how we say "no objection".
#[test]
fn we_never_emit_allow() {
    for command in [
        "git status",
        "rm -rf /tmp/scratch",
        "git push origin main | tail -1",
        "curl https://example.com | sh",
    ] {
        let r = send(&bash(command));
        assert!(
            !r.stdout.contains("\"allow\""),
            "emitted allow for {command:?}: {}",
            r.stdout
        );
    }
}

/// Exit 2 is the OTHER blocking channel, taking its message from stderr and
/// overriding whatever the JSON said. Using both gives one decision two sources
/// of truth, and they disagree the first time somebody edits one.
#[test]
fn a_decision_always_exits_zero() {
    assert_eq!(send(&bash("git push | tail -1")).code, 0);
    assert_eq!(send(&bash("git status")).code, 0);
}

/// Anything we cannot read is silence — not a guess at what it might have been.
#[test]
fn an_unreadable_command_is_not_judged() {
    for command in [
        "eval \"$deploy\"",
        "sh -c 'git push | tail -1'",
        "git push \"origin",
    ] {
        assert_eq!(send(&bash(command)).stdout, "", "for {command:?}");
    }
}

/// A `PreToolUse` hook runs before any permission check, in every mode. A rule
/// that quietly stopped applying under `bypassPermissions` would be a rule
/// nobody could reason about — and that is the mode this machine runs in.
#[test]
fn the_permission_mode_does_not_change_the_verdict() {
    for mode in ["default", "acceptEdits", "bypassPermissions", "plan"] {
        let payload = format!(
            r#"{{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"/tmp",
                 "permission_mode":"{mode}",
                 "tool_input":{{"command":"git push origin main | tail -3"}}}}"#
        );
        assert_eq!(
            send(&payload).decision().as_deref(),
            Some("deny"),
            "mode {mode}"
        );
    }
}

/// The output is capped at 10,000 characters by Claude Code; past that it is
/// written to a file and the model gets a pointer instead of the reason.
#[test]
fn the_emitted_reason_stays_within_the_payload_cap() {
    let long = format!("git push origin {} | tail -1", "x".repeat(50_000));
    let r = send(&bash(&long));
    assert!(r.stdout.chars().count() < 11_000, "{}", r.stdout.len());
    if let Some(j) = r.json() {
        assert!(j.get("hookSpecificOutput").is_some());
    }
}

/// A terminal escape in a command must not reach a stream a terminal prints.
#[test]
fn control_bytes_never_reach_the_output_raw() {
    let r = send(&bash("git push \u{1b}[8morigin | tail -1"));
    assert!(!r.stdout.contains('\u{1b}'), "{}", r.stdout);
}

/// One writer to stdout, enforced by reading this crate's own sources — no
/// compiler can ask this question, and the failure it prevents is silent.
#[test]
fn only_the_emitter_writes_to_stdout() {
    let src = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src");
    let mut offenders = Vec::new();
    // Exempt: the emitter itself, and the modules that only ever run under a
    // CLI verb a person typed. What makes those safe is that nothing reachable
    // from `hook` calls them — `decide` dispatches to the rules, the journal and
    // the emitter, and to nothing here.
    const NOT_THE_HOOK_PATH: &[&str] = &["decision.rs", "main.rs", "doctor.rs", "backtest.rs"];
    walk(&src, &mut |path, text| {
        if NOT_THE_HOOK_PATH.iter().any(|name| path.ends_with(name)) {
            return;
        }
        for (n, line) in text.lines().enumerate() {
            let code = line.split("//").next().unwrap_or("");
            // `eprintln!` CONTAINS `println!`. Blank the stderr macros before
            // looking, or every diagnostic in the crate reads as a violation —
            // which is the same unbounded-substring mistake this crate exists
            // to stop making about shell commands.
            let code = code.replace("eprintln!", "").replace("eprint!", "");
            if code.contains("println!") || code.contains("print!") {
                offenders.push(format!("{}:{}", path.display(), n + 1));
            }
        }
    });
    assert!(
        offenders.is_empty(),
        "stdout is written outside decision.rs:\n{}",
        offenders.join("\n")
    );
}

fn walk(dir: &std::path::Path, f: &mut impl FnMut(&std::path::Path, &str)) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for e in entries.flatten() {
        let p = e.path();
        if p.is_dir() {
            walk(&p, f);
        } else if p.extension().is_some_and(|x| x == "rs") {
            if let Ok(text) = std::fs::read_to_string(&p) {
                f(&p, &text);
            }
        }
    }
}

/// A clone whose origin has moved on. Two commits on the bare origin, the
/// clone taken after the first, so `HEAD` is exactly one behind.
fn a_stale_clone() -> (PathBuf, PathBuf) {
    let root = home().join("stale");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).expect("scratch root");
    let origin = root.join("origin.git");
    let work = root.join("work");
    let clone = root.join("clone");
    let git = |dir: &std::path::Path, args: &[&str]| {
        let out = Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .output()
            .expect("git runs");
        assert!(
            out.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    };
    git(
        &root,
        &[
            "init",
            "-q",
            "--bare",
            "--initial-branch=main",
            "origin.git",
        ],
    );
    git(&root, &["clone", "-q", origin.to_str().unwrap(), "work"]);
    git(&work, &["config", "user.email", "t@t.test"]);
    git(&work, &["config", "user.name", "t"]);
    git(&work, &["commit", "-q", "--allow-empty", "-m", "first"]);
    git(&work, &["push", "-q", "origin", "HEAD:main"]);
    git(&root, &["clone", "-q", origin.to_str().unwrap(), "clone"]);
    git(
        &work,
        &[
            "commit",
            "-q",
            "--allow-empty",
            "-m",
            "feat: the thing that already exists",
        ],
    );
    git(&work, &["push", "-q", "origin", "HEAD:main"]);
    (clone, work)
}

fn session_start(cwd: &std::path::Path) -> String {
    format!(
        r#"{{"hook_event_name":"SessionStart","source":"startup","session_id":"sess1234","cwd":{}}}"#,
        serde_json::Value::String(cwd.to_string_lossy().into_owned())
    )
}

/// The whole point: a session opening in a checkout the remote has moved past
/// is told so, with the count and the newest commit it is missing — and the
/// remote ref was refreshed to find out, without touching the working tree.
#[test]
fn a_session_opening_in_a_stale_checkout_is_told_how_far_behind_it_is() {
    let (clone, _) = a_stale_clone();
    let r = send(&session_start(&clone));
    assert_eq!(r.code, 0);
    let doc = r.json().expect("a decision document");
    let out = &doc["hookSpecificOutput"];
    assert_eq!(out["hookEventName"], "SessionStart", "{doc}");
    let text = out["additionalContext"].as_str().unwrap_or_default();
    assert!(text.contains("1 commit behind origin/main"), "{text}");
    assert!(text.contains("the thing that already exists"), "{text}");
    assert!(text.starts_with("amont-agent/stale-base:"), "{text}");
    // Informed, not moved: HEAD is where it was.
    let head = Command::new("git")
        .args(["-C", clone.to_str().unwrap(), "log", "-1", "--format=%s"])
        .output()
        .unwrap();
    assert_eq!(String::from_utf8_lossy(&head.stdout).trim(), "first");
}

/// Up to date is silence — zero bytes, like every other no-opinion.
#[test]
fn a_session_opening_in_a_current_checkout_says_nothing() {
    let (_, work) = a_stale_clone();
    let r = send(&session_start(&work));
    assert_eq!(r.stdout, "");
    assert_eq!(r.code, 0);
}

/// Not a repository, or a `cwd` that is gone: nothing to measure, nothing said.
#[test]
fn a_session_opening_outside_a_repository_says_nothing() {
    for cwd in [std::env::temp_dir(), PathBuf::from("/nonexistent/for/sure")] {
        let r = send(&session_start(&cwd));
        assert_eq!(r.stdout, "", "expected silence for {}", cwd.display());
        assert_eq!(r.code, 0);
    }
}

/// The branch-creation rule, end to end: a branch about to be started from a
/// stale HEAD is advised — and one started from `origin/main` is not.
#[test]
fn a_branch_started_from_a_stale_head_is_advised() {
    let (clone, _) = a_stale_clone();
    let payload = |command: &str| {
        format!(
            r#"{{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":{},
                 "session_id":"sess1234","tool_use_id":"t1","permission_mode":"default",
                 "tool_input":{{"command":{}}}}}"#,
            serde_json::Value::String(clone.to_string_lossy().into_owned()),
            serde_json::Value::String(command.to_string())
        )
    };
    let r = send(&payload("git worktree add ../clone-wt-x -b feat/x"));
    let doc = r.json().expect("a decision document");
    let text = doc["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .unwrap_or_default();
    assert!(text.starts_with("amont-agent/stale-base:"), "{doc}");
    assert!(
        doc["hookSpecificOutput"]["permissionDecision"].is_null(),
        "advice refuses nothing: {doc}"
    );

    let r = send(&payload(
        "git worktree add ../clone-wt-x -b feat/x origin/main",
    ));
    assert_eq!(r.stdout, "", "the remedy must not trip the rule");
}

/// The guidance block is checked when the session opens — before an agent
/// has read and believed it.
///
/// This drives the shell-out, so it supplies its own `amont`: a stub whose
/// stderr and exit code are the contract this crate reads. Three cases,
/// because the middle one is the whole reason the decision is made on
/// stderr rather than on the exit code.
///
/// UNIX ONLY, and the reason is Windows' process creation rather than
/// anything about this crate. `CreateProcessW` appends `.exe` and nothing
/// else when the name it is given has no extension, so neither a `#!/bin/sh`
/// stub nor an `amont.bat` is reachable through `Command::new("amont")`
/// there — the stub would have to be a real compiled executable, which is
/// more machinery than this assertion is worth.
///
/// What is NOT lost on Windows: `guidance`'s own unit tests cover the stderr
/// parsing and every not-drift case on every platform, and
/// `a_marked_block_with_no_amont_installed_says_nothing` below covers the
/// no-amont path there too.
#[cfg(unix)]
#[test]
fn a_session_opening_on_a_stale_guidance_block_is_told() {
    let (_, work) = a_stale_clone(); // `work` is up to date with origin
                                     // The marker is what makes this crate bother to spawn anything at all.
    std::fs::write(
        work.join("AGENTS.md"),
        "# Project\n\n<!-- amont:start -->\nSTALE\n<!-- amont:end -->\n",
    )
    .unwrap();

    let bin = home().join("stub-bin");
    std::fs::create_dir_all(&bin).unwrap();
    let stub = bin.join("amont");
    let write_stub = |body: &str| {
        use std::os::unix::fs::PermissionsExt;
        std::fs::write(&stub, body).unwrap();
        std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
    };

    // Drifted: amont exits 1 and says so on stderr.
    write_stub(
        "#!/bin/sh\necho \"$PWD/AGENTS.md: drifted from the generated block \
         — run \\`amont agents-md\\`\" >&2\nexit 1\n",
    );
    let r = send_with_path(&session_start(&work), Some(&bin));
    let doc = r.json().expect("a decision document");
    let text = doc["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .unwrap_or_default();
    assert!(text.contains("amont-agent/agents-md: AGENTS.md"), "{text}");
    assert!(text.contains("amont agents-md"), "{text}");

    // Exit 1 WITHOUT a drift line — amont could not read the file. Same
    // exit code, and it must not be reported as staleness.
    write_stub("#!/bin/sh\necho \"$PWD/AGENTS.md: Permission denied\" >&2\nexit 1\n");
    let r = send_with_path(&session_start(&work), Some(&bin));
    assert_eq!(
        r.stdout, "",
        "exit 1 alone is not drift — amont uses it for unreadable files too"
    );

    // Up to date: nothing on stderr, exit 0.
    write_stub("#!/bin/sh\necho \"$PWD/AGENTS.md: up to date\"\nexit 0\n");
    let r = send_with_path(&session_start(&work), Some(&bin));
    assert_eq!(r.stdout, "", "a current block is not news");
}

/// Somebody who does not use amont has no `amont` on PATH, and the whole
/// feature must then be invisible rather than an error.
#[test]
fn a_marked_block_with_no_amont_installed_says_nothing() {
    let (_, work) = a_stale_clone();
    std::fs::write(
        work.join("AGENTS.md"),
        "# Project\n\n<!-- amont:start -->\nSTALE\n<!-- amont:end -->\n",
    )
    .unwrap();
    let empty = home().join("no-amont-here");
    std::fs::create_dir_all(&empty).unwrap();
    // An empty PATH: nothing resolves, `amont` least of all.
    let r = send_with_path_only(&session_start(&work), &empty);
    assert_eq!(r.stdout, "", "no amont, no opinion");
}

/// `push-preflight`, end to end: a push from an amont-guarded checkout whose
/// tree is not yet stamped is advised to rehearse; the same push once the
/// tree carries a push stamp is not. Drives the shell-out to `amont list`,
/// so it supplies its own `amont` stub (unix only, for the same reason as
/// the guidance test above).
#[cfg(unix)]
#[test]
fn a_push_from_an_unrehearsed_tree_is_advised_and_a_stamped_one_is_not() {
    let (_, work) = a_stale_clone(); // any real repo with a HEAD will do
                                     // amont's shim, by its one-word signature.
    let hooks = work.join(".git").join("hooks");
    std::fs::create_dir_all(&hooks).unwrap();
    std::fs::write(
        hooks.join("pre-push"),
        "#!/bin/sh\nexec amont --hooks-dir . pre-push \"$@\"\n",
    )
    .unwrap();
    // An `amont` whose `list --json --stage pre-push` says a JS suite runs.
    let bin = home().join("stub-bin-push");
    std::fs::create_dir_all(&bin).unwrap();
    {
        use std::os::unix::fs::PermissionsExt;
        let stub = bin.join("amont");
        std::fs::write(
            &stub,
            "#!/bin/sh\necho '{\"checks\":[{\"id\":\"pre-push-run-tests-js\",\"stage\":\"pre-push\",\"source\":\"builtin\",\"status\":\"runs\"}]}'\n",
        )
        .unwrap();
        std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    let payload = format!(
        r#"{{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":{},
             "session_id":"sess1234","tool_use_id":"t1","permission_mode":"default",
             "tool_input":{{"command":"git push -u origin feat/x"}}}}"#,
        serde_json::Value::String(work.to_string_lossy().into_owned()),
    );
    let r = send_with_path(&payload, Some(&bin));
    let doc = r.json().expect("a decision document");
    let text = doc["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .unwrap_or_default();
    assert!(text.starts_with("amont-agent/push-preflight:"), "{doc}");
    assert!(text.contains("amont rehearse --wait"), "{text}");
    assert!(
        doc["hookSpecificOutput"]["permissionDecision"].is_null(),
        "advice refuses nothing: {doc}"
    );

    // Rehearsed: a push stamp on HEAD's tree, as amont ≥ 1.27 writes it.
    let out = Command::new("git")
        .args([
            "-C",
            work.to_str().unwrap(),
            "notes",
            "--ref",
            "amont-gate",
            "add",
            "-f",
            "-m",
            "amont-gate-v1 pre-push-run-tests-js",
            "HEAD^{tree}",
        ])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let r = send_with_path(&payload, Some(&bin));
    assert_eq!(r.stdout, "", "a rehearsed tree is not nagged: {}", r.stdout);
}

/// A `confirm` that declines writes WHY, in the rule's words, and `status`
/// reads it back. This is the loop the crate runs on: a rule ships `observe`,
/// and the number that decides whether it may advise is how often `confirm`
/// agreed — a number the backtester cannot produce, because it never runs
/// `confirm`. Until this, the only reader of that number was `awk`.
#[test]
fn a_declined_confirm_records_why_and_status_reads_it_back() {
    // A primary checkout with no linked worktrees: `worktree-isolation`'s
    // `examine` fires on the shape and its `confirm` declines, naming why.
    let repo = home().join("solo-repo");
    let _ = std::fs::remove_dir_all(&repo);
    std::fs::create_dir_all(&repo).expect("scratch repo");
    let init = Command::new("git")
        .args(["init", "-q", "--initial-branch=main", "."])
        .current_dir(&repo)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .output()
        .expect("git runs");
    assert!(init.status.success());

    let payload = format!(
        r#"{{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":{},
             "session_id":"seen1234","tool_use_id":"t1","permission_mode":"default",
             "tool_input":{{"command":"git checkout -b feat/why"}}}}"#,
        serde_json::Value::String(repo.display().to_string())
    );
    let reply = send(&payload);
    assert_eq!(reply.code, 0);

    let journal = std::fs::read_to_string(home().join("amont-agent").join("journal.log"))
        .expect("the hook wrote a journal");
    let line = journal
        .lines()
        .find(|l| l.contains("worktree-isolation unconfirmed"))
        .unwrap_or_else(|| panic!("no unconfirmed record in:\n{journal}"));
    assert!(
        line.contains("nothing_else_is_checked_out_from_this_repository"),
        "the reason, in the rule's own words: {line}"
    );
    assert!(
        !line.contains(" skipped "),
        "`skipped` is not a reason: {line}"
    );

    let status = Command::new(env!("CARGO_BIN_EXE_amont-agent"))
        .arg("status")
        .env("CLAUDE_CONFIG_DIR", home())
        .env_remove("AMONT_AGENT_OFF")
        .output()
        .expect("the binary runs");
    let text = String::from_utf8_lossy(&status.stdout);
    let row = text
        .lines()
        .find(|l| l.starts_with("worktree-isolation"))
        .unwrap_or_else(|| panic!("no status row in:\n{text}"));
    assert!(
        row.contains("1 unconfirmed (nothing else is checked out from this repository \u{d7}1)"),
        "status reads the journal back, reason and all: {row}"
    );
}

/// The file tier. A Read is remembered; a second Read of the same path with
/// nothing written to it since is advised against; an Edit in between makes
/// the next Read silent again; and a `cat` of the same file is the same
/// question asked from the shell.
#[test]
fn a_file_read_twice_is_advised_and_an_edit_between_resets_it() {
    let dir = home().join("reread-repo");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("scratch dir");
    let file = dir.join("big.rs");
    std::fs::write(&file, "x".repeat(6000)).expect("a file worth reading");
    let cwd = serde_json::Value::String(dir.display().to_string());
    let path = serde_json::Value::String(file.display().to_string());
    let read = |session: &str| {
        send(&format!(
            r#"{{"hook_event_name":"PreToolUse","tool_name":"Read","cwd":{cwd},
                 "session_id":"{session}","permission_mode":"default",
                 "tool_input":{{"file_path":{path}}}}}"#
        ))
    };

    let first = read("rr-1");
    assert_eq!(first.code, 0);
    assert_eq!(first.stdout, "", "a first read is not commented on");

    let second = read("rr-1");
    assert!(
        second.reason().contains("file-reread") && second.reason().contains("already read"),
        "second read: {}",
        second.stdout
    );
    assert_eq!(
        second.decision(),
        None,
        "advise, not deny: {}",
        second.stdout
    );

    // Another session has its own record.
    assert_eq!(read("rr-2").stdout, "");

    let edit = send(&format!(
        r#"{{"hook_event_name":"PreToolUse","tool_name":"Edit","cwd":{cwd},
             "session_id":"rr-1","permission_mode":"default",
             "tool_input":{{"file_path":{path},"old_string":"x","new_string":"y"}}}}"#
    ));
    assert_eq!(edit.stdout, "", "a write is remembered silently");
    assert_eq!(read("rr-1").stdout, "", "a read after an edit is right");

    // From the shell: a dump of the file the session just read.
    let cat = send(&format!(
        r#"{{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":{cwd},
             "session_id":"rr-1","permission_mode":"default",
             "tool_input":{{"command":"cat big.rs"}}}}"#
    ));
    let said = cat.reason();
    assert!(
        said.contains("file-reread"),
        "cat after Read: {}",
        cat.stdout
    );
    assert!(
        said.contains("whole-file-dump"),
        "a 6 KB cat is a dump too: {}",
        cat.stdout
    );
}

/// A poll whose budget fits the call's timeout is left alone; one that can
/// outlast it is what the rule is about.
#[test]
fn a_poll_is_judged_against_the_calls_timeout() {
    // A directory that exists on every platform: `confirm` declines in one
    // that does not, and `/tmp` is not one on Windows.
    let cwd = serde_json::Value::String(home().display().to_string());
    let payload = |timeout: &str, cmd: &str| {
        send(&format!(
            r#"{{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":{cwd},
                 "session_id":"poll-1","permission_mode":"default",
                 "tool_input":{{"command":"{cmd}"{timeout}}}}}"#
        ))
    };
    let loop_ =
        "for i in $(seq 1 36); do gh pr checks 1 | grep -q pending || break; sleep 15; done";
    assert!(
        payload("", loop_).reason().contains("foreground-poll"),
        "nine minutes against a two-minute default"
    );
    assert_eq!(
        payload(r#","timeout":600000"#, loop_).stdout,
        "",
        "nine minutes inside an explicit ten"
    );
    assert!(
        payload(r#","timeout":600000"#, "while true; do sleep 5; done")
            .reason()
            .contains("foreground-poll"),
        "unbounded is over any clock"
    );
}