amont-agent 2.30.2

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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
//! 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> {
        let json = self.json()?;
        // A `Stop` decision is top-level; every other event nests it.
        if let Some(d) = json.get("decision").and_then(|d| d.as_str()) {
            return Some(d.to_string());
        }
        Some(
            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")
        // Nor steered by it: a developer's `amont.agent.<rule>.stance` in
        // their global git config (implementation-review at deny, say)
        // would otherwise decide what these tests observe.
        .env("GIT_CONFIG_GLOBAL", home().join("no-global-gitconfig"))
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .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);
    }
}

/// A `Stop` outside any repository is answered with nothing.
#[test]
fn a_stop_event_is_silent() {
    let r = send(
        r#"{"hook_event_name":"Stop","session_id":"sess1234","cwd":"/tmp",
            "permission_mode":"default","last_assistant_message":"done",
            "background_tasks":[],"stop_hook_active":false}"#,
    );
    assert_eq!(r.stdout, "");
    assert_eq!(r.decision(), None);
    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}"
    );
}

/// A scratch file worth reading, and the two halves of a Read on it: the
/// `PreToolUse` that asks whether the session already has the file, and the
/// `PostToolUse` that says the read happened.
struct ReadFixture {
    dir: PathBuf,
    file: PathBuf,
}

impl ReadFixture {
    fn new(name: &str) -> ReadFixture {
        ReadFixture::with_size(name, 6000)
    }

    /// A file of `bytes` bytes (a multiple of 100), in lines of 100.
    fn with_size(name: &str, bytes: usize) -> ReadFixture {
        let dir = home().join(name);
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("scratch dir");
        let file = dir.join("big.rs");
        let line = format!("{}\n", "x".repeat(99));
        std::fs::write(&file, line.repeat(bytes / 100)).expect("a file worth reading");
        ReadFixture { dir, file }
    }

    /// A scratch file named `file_name` holding `text`, for the write tools:
    /// the rule rebuilds the file from disk, so the file has to say something.
    fn with_content(name: &str, file_name: &str, text: &str) -> ReadFixture {
        let dir = home().join(name);
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("scratch dir");
        let file = dir.join(file_name);
        std::fs::write(&file, text).expect("a file worth editing");
        ReadFixture { dir, file }
    }

    /// As [`ReadFixture::file_event`], with the stance config pinned to `cfg`.
    fn file_event_with_global(
        &self,
        event: &str,
        tool: &str,
        session: &str,
        input: &str,
        cfg: &str,
    ) -> Reply {
        let cwd = serde_json::Value::String(self.dir.display().to_string());
        let path = serde_json::Value::String(self.file.display().to_string());
        send_with_global(
            &format!(
                r#"{{"hook_event_name":"{event}","tool_name":"{tool}","cwd":{cwd},
                 "session_id":"{session}","permission_mode":"default",
                 "tool_input":{{"file_path":{path}{input}}}}}"#
            ),
            cfg,
        )
    }

    fn file_event(&self, event: &str, tool: &str, session: &str, input: &str) -> Reply {
        let cwd = serde_json::Value::String(self.dir.display().to_string());
        let path = serde_json::Value::String(self.file.display().to_string());
        send(&format!(
            r#"{{"hook_event_name":"{event}","tool_name":"{tool}","cwd":{cwd},
                 "session_id":"{session}","permission_mode":"default",
                 "tool_input":{{"file_path":{path}{input}}}}}"#
        ))
    }

    /// About to Read.
    fn read(&self, session: &str) -> Reply {
        self.file_event("PreToolUse", "Read", session, "")
    }

    /// Read, and it worked.
    fn read_done(&self, session: &str) -> Reply {
        let done = self.file_event("PostToolUse", "Read", session, "");
        assert_eq!(done.stdout, "", "a finished read is remembered silently");
        done
    }

    fn bash_event(&self, event: &str, session: &str, command: &str) -> Reply {
        let cwd = serde_json::Value::String(self.dir.display().to_string());
        send(&format!(
            r#"{{"hook_event_name":"{event}","tool_name":"Bash","cwd":{cwd},
                 "session_id":"{session}","permission_mode":"default",
                 "tool_input":{{"command":"{command}"}}}}"#
        ))
    }
}

/// 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 f = ReadFixture::new("reread-repo");
    let read = |session: &str| f.read(session);

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

    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 = f.file_event(
        "PreToolUse",
        "Edit",
        "rr-1",
        r#","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");
    f.read_done("rr-1");

    // From the shell: a dump of the file the session just read.
    let cat = f.bash_event("PreToolUse", "rr-1", "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 first Read of a large file with no window is advised, never refused.
#[test]
fn a_large_whole_read_is_advised() {
    let f = ReadFixture::with_size("unbounded-large", 20_000);
    let first = f.read("ul-1");
    assert_eq!(first.code, 0);
    assert!(
        first.reason().contains("read-unbounded-large"),
        "{}",
        first.stdout
    );
    assert_eq!(first.decision(), None, "advise, not deny: {}", first.stdout);
}

/// A window, or a deliberate whole read spelled `offset: 1` plus a `limit`,
/// is the way through.
#[test]
fn a_windowed_or_deliberate_whole_read_is_silent() {
    let f = ReadFixture::with_size("unbounded-window", 20_000);
    let windowed = f.file_event("PreToolUse", "Read", "uw-1", r#","limit":200"#);
    assert!(
        !windowed.stdout.contains("read-unbounded-large"),
        "{}",
        windowed.stdout
    );
    let whole = f.file_event("PreToolUse", "Read", "uw-2", r#","offset":1,"limit":200"#);
    assert!(
        !whole.stdout.contains("read-unbounded-large"),
        "{}",
        whole.stdout
    );
}

/// Under the threshold the advice costs more than the read.
#[test]
fn a_small_first_read_stays_silent() {
    let f = ReadFixture::new("unbounded-small");
    assert_eq!(f.read("us-1").stdout, "");
}

/// A second whole Read is `file-reread`'s to answer, and only its.
#[test]
fn a_reread_says_file_reread_only() {
    let f = ReadFixture::with_size("unbounded-reread", 20_000);
    assert!(f.read("ur-1").reason().contains("read-unbounded-large"));
    f.read_done("ur-1");
    let second = f.read("ur-1");
    let said = second.reason();
    assert!(said.contains("file-reread"), "{}", second.stdout);
    assert!(!said.contains("read-unbounded-large"), "{}", second.stdout);
}

/// With `file-reread` observing, a re-read still keeps this rule quiet: it
/// yields to whether the file was seen, not to whether a message came back.
#[test]
fn an_observed_reread_still_suppresses() {
    let f = ReadFixture::with_size("unbounded-observed", 20_000);
    let cfg = "[amont \"agent.file-reread\"]\n\tstance = observe";
    let session = "obsrd-01";
    // The first read is only remembered, so the journal below holds what the
    // second one did and nothing else.
    f.file_event_with_global("PostToolUse", "Read", session, "", cfg);
    let second = f.file_event_with_global("PreToolUse", "Read", session, "", cfg);
    assert_eq!(second.stdout, "", "neither rule speaks: {}", second.stdout);

    let journal = std::fs::read_to_string(home().join("amont-agent").join("journal.log"))
        .expect("the hook wrote a journal");
    let rows: Vec<&str> = journal.lines().filter(|l| l.contains(session)).collect();
    let rereads = rows
        .iter()
        .filter(|l| l.contains("file-reread") && l.contains("watched"))
        .count();
    let large = rows
        .iter()
        .filter(|l| l.contains("read-unbounded-large"))
        .count();
    assert_eq!(rereads, 1, "{rows:?}");
    assert_eq!(large, 0, "{rows:?}");
}

/// A Read is remembered once it has HAPPENED. One that was refused, or that
/// failed on a path that is not there, put nothing in context — and a retry
/// told "its contents are already in context" is a retry that never learns
/// what the file says. The same for a `cat`: only the `PostToolUse` that
/// reports it ran is the read.
#[test]
fn a_read_that_never_completed_is_not_remembered() {
    let f = ReadFixture::new("reread-incomplete");

    assert_eq!(
        f.read("ri-1").stdout,
        "",
        "a first read is not commented on"
    );
    assert_eq!(
        f.read("ri-1").stdout,
        "",
        "no PostToolUse came back, so the first Read is not on record"
    );

    let cat = f.bash_event("PreToolUse", "ri-2", "cat big.rs");
    assert!(
        !cat.reason().contains("file-reread"),
        "nothing read yet: {}",
        cat.stdout
    );
    let again = f.bash_event("PreToolUse", "ri-2", "cat big.rs");
    assert!(
        !again.reason().contains("file-reread"),
        "the first cat never ran, so it is not a read: {}",
        again.stdout
    );
    assert_eq!(
        f.bash_event("PostToolUse", "ri-2", "cat big.rs").stdout,
        "",
        "a finished cat is remembered silently"
    );
    let third = f.bash_event("PreToolUse", "ri-2", "cat big.rs");
    assert!(
        third.reason().contains("file-reread"),
        "now it has run once: {}",
        third.stdout
    );
}

/// The Edit tool is not the only thing that writes a file: `sed -i`, a
/// formatter, `git checkout`, another session in the same checkout. A file
/// that changed on disk since it was read is read again without comment —
/// the record is checked against the file, not trusted on its own.
#[test]
fn a_file_changed_behind_the_sessions_back_is_read_again_without_comment() {
    let f = ReadFixture::new("reread-changed");
    assert_eq!(f.read("rc-1").stdout, "");
    f.read_done("rc-1");
    assert!(
        f.read("rc-1").reason().contains("file-reread"),
        "unchanged, so the second read is advised against"
    );

    std::fs::write(&f.file, "y".repeat(6001)).expect("rewrite the file");
    assert_eq!(
        f.read("rc-1").stdout,
        "",
        "the file is not what the session read any more"
    );
    f.read_done("rc-1");
    assert!(
        f.read("rc-1").reason().contains("file-reread"),
        "read again and unchanged since: advised again"
    );

    std::fs::remove_file(&f.file).expect("remove the file");
    assert_eq!(
        f.read("rc-1").stdout,
        "",
        "a file that is gone is not in context"
    );
}

/// The shape that was advised live on 2026-09-14: a background task's output
/// file, Read while still EMPTY, then read again once the task had written
/// to it. Nothing in the session wrote it, so the record alone says
/// "unchanged"; the file says otherwise, and the file wins. An empty read is
/// also the one case where "what it says is already in context" is exactly
/// nothing — worth pinning on its own, apart from the rewrite above.
#[test]
fn a_file_read_while_empty_and_filled_by_a_background_task_is_read_again() {
    let f = ReadFixture::new("reread-empty-then-written");
    std::fs::write(&f.file, "").expect("an empty output file");
    assert_eq!(f.read("bg-1").stdout, "");
    f.read_done("bg-1");
    assert!(
        f.read("bg-1").reason().contains("file-reread"),
        "still empty, still what the session saw: advised against"
    );

    // Nothing the hook sees writes it — a background process appends.
    let mut out = std::fs::OpenOptions::new()
        .append(true)
        .open(&f.file)
        .expect("append to the output file");
    std::io::Write::write_all(&mut out, b"21:07:41 state=success\n").expect("append");
    drop(out);
    assert_eq!(
        f.read("bg-1").stdout,
        "",
        "the task wrote to it since: read again without comment"
    );
}

/// 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"
    );
}

/// A pipeline we cannot read costs us that pipeline, not the line.
///
/// The `xargs` run is unreadable; the `git commit … | tail -1` beside it is
/// not, and it is the shape the only blocking rule exists for. Before
/// per-pipeline opacity the whole command was silence.
#[test]
fn a_hidden_pipeline_does_not_silence_the_rest_of_the_line() {
    let dir = home();
    let cwd = serde_json::Value::String(dir.display().to_string());
    let cmd = serde_json::Value::String(
        "git status -s | xargs git add && git commit -q -m x 2>&1 | tail -1".to_string(),
    );
    let reply = send(&format!(
        r#"{{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":{cwd},
             "session_id":"partial-1","permission_mode":"default",
             "tool_input":{{"command":{cmd}}}}}"#
    ));
    assert_eq!(reply.code, 0);
    let said = reply.reason();
    assert!(
        said.contains("pipe-to-tail"),
        "the readable pipeline was not judged: {}",
        reply.stdout
    );
    // Capped: a command we only partly read may advise, never refuse.
    assert_eq!(
        reply.decision(),
        None,
        "a half-read command produced a refusal: {}",
        reply.stdout
    );
}

/// Nothing readable survived, so the guard stays as silent as it always was.
#[test]
fn a_wholly_unreadable_command_is_still_not_judged() {
    let cwd = serde_json::Value::String(home().display().to_string());
    for command in [
        "git status --short | xargs git add",
        "source ./setup.sh && git push origin main 2>&1 | tail -1",
    ] {
        let cmd = serde_json::Value::String(command.to_string());
        let reply = send(&format!(
            r#"{{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":{cwd},
                 "session_id":"partial-2","permission_mode":"default",
                 "tool_input":{{"command":{cmd}}}}}"#
        ));
        assert_eq!(reply.stdout, "", "{command} was judged: {}", reply.stdout);
    }
}

/// The hook, with its stance config pinned to `global` so the developer's own
/// `~/.gitconfig` cannot decide what the test sees.
fn send_with_global(payload: &str, global: &str) -> Reply {
    let dir = home();
    let cfg = dir.join("fanout.gitconfig");
    std::fs::write(&cfg, global).expect("global config");
    let mut child = Command::new(env!("CARGO_BIN_EXE_amont-agent"))
        .arg("hook")
        .env("CLAUDE_CONFIG_DIR", &dir)
        .env("GIT_CONFIG_GLOBAL", &cfg)
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .env("SHELL", "/bin/zsh")
        .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(),
    }
}

const FANOUT: &str = r#"i=0; while [ $i -lt 400 ]; do curl -s "https://ghcr.io/v2/o/r/tags/list?page=$i"; i=$((i+1)); done"#;
const ADVISE_FANOUT: &str = "[amont \"agent.request-fanout\"]\n\tstance = advise\n";

/// `request-fanout` ships observing: it measures and says nothing.
#[test]
fn a_fanout_is_silent_while_the_rule_observes() {
    let r = send_with_global(&bash(FANOUT), "");
    assert_eq!(r.stdout, "");
    assert_eq!(r.code, 0);
}

/// Promoted to `advise`, it speaks — with the count, the host and the
/// reason the count is bounded — and never refuses.
#[test]
fn a_fanout_is_advised_once_promoted() {
    let r = send_with_global(&bash(FANOUT), ADVISE_FANOUT);
    assert_ne!(r.decision().as_deref(), Some("deny"));
    let reason = r.reason();
    assert!(reason.contains("400"), "{reason}");
    assert!(reason.contains("ghcr.io"), "{reason}");
    assert!(reason.contains("egress IP"), "{reason}");
}

/// A command the legacy lexer cannot read (an `xargs` elsewhere on the line)
/// is still analysed: the analysis carries its own account of what it could
/// not follow.
#[test]
fn a_fanout_beside_an_unreadable_clause_is_still_advised() {
    let cmd = format!("{FANOUT}; ls | xargs -n1 echo");
    let r = send_with_global(&bash(&cmd), ADVISE_FANOUT);
    let reason = r.reason();
    assert!(reason.contains("ghcr.io"), "{reason}");
    assert!(reason.contains("could not follow"), "{reason}");
}

/// Even `deny`, set for this rule by name, only advises.
#[test]
fn a_fanout_is_never_refused() {
    let r = send_with_global(
        &bash(FANOUT),
        "[amont \"agent.request-fanout\"]\n\tstance = deny\n",
    );
    assert_ne!(r.decision().as_deref(), Some("deny"));
    assert!(r.reason().contains("ghcr.io"));
}

fn journal_rows(session: &str) -> Vec<String> {
    std::fs::read_to_string(home().join("amont-agent").join("journal.log"))
        .expect("the hook wrote a journal")
        .lines()
        .filter(|l| l.contains(session))
        .map(str::to_string)
        .collect()
}

const ADD_IGNORE: &str =
    r#","old_string":"return g(a)","new_string":"return g(a)  # type: ignore""#;

/// An Edit that adds a suppression is advised, never refused, and the advice
/// names the line it is on.
#[test]
fn lint_suppression_an_edit_adding_a_type_ignore_is_advised() {
    let f = ReadFixture::with_content("lsa-add", "x.py", "def f(a):\n    return g(a)\n");
    let said = f.file_event("PreToolUse", "Edit", "lsa-add1", ADD_IGNORE);
    assert_eq!(said.code, 0);
    assert!(
        said.reason().contains("lint-suppression-added"),
        "{}",
        said.stdout
    );
    assert!(
        said.reason().contains("line 2: # type: ignore"),
        "{}",
        said.stdout
    );
    assert_eq!(said.decision(), None, "advise, not deny: {}", said.stdout);
    let rows = journal_rows("lsa-add1");
    assert!(
        rows.iter().any(|r| r.contains("lint-suppression-added")
            && r.contains(" advised ")
            && r.contains("x.py:2 type: ignore[] (+1) exact")),
        "{rows:?}"
    );
}

/// Changing code on a line that keeps its suppression is not adding one.
#[test]
fn lint_suppression_an_edit_on_an_already_suppressed_line_is_silent() {
    let f = ReadFixture::with_content("lsa-kept", "x.py", "x = f(a)  # type: ignore\n");
    let said = f.file_event(
        "PreToolUse",
        "Edit",
        "lsa-kept1",
        r#","old_string":"f(a)","new_string":"f(b)""#,
    );
    assert_eq!(said.stdout, "", "{}", said.stdout);
}

/// A Write has no file to read for a new path, and a config is looked at
/// too: loosening `strict` is advised.
#[test]
fn lint_suppression_a_new_tsconfig_with_strict_off_is_advised() {
    let f = ReadFixture::with_content("lsa-ts", "tsconfig.json", "");
    std::fs::remove_file(&f.file).expect("a new file");
    let said = f.file_event(
        "PreToolUse",
        "Write",
        "lsa-ts-1",
        r#","content":"{\"compilerOptions\": {\"strict\": false}}""#,
    );
    assert!(
        said.reason().contains("lint-suppression-added"),
        "{}",
        said.stdout
    );
    assert!(
        said.reason()
            .contains("loosens tsconfig.json strict = false"),
        "{}",
        said.stdout
    );
    assert_eq!(said.decision(), None, "advise, not deny: {}", said.stdout);
}

/// `observe` through the git config: nothing said, and the journal shows the
/// rule watched.
#[test]
fn lint_suppression_observed_is_silent_and_journalled_as_watched() {
    let f = ReadFixture::with_content("lsa-obs", "x.py", "def f(a):\n    return g(a)\n");
    let cfg = "[amont \"agent.lint-suppression-added\"]\n\tstance = observe";
    let session = "lsaobs-1";
    let said = f.file_event_with_global("PreToolUse", "Edit", session, ADD_IGNORE, cfg);
    assert_eq!(said.stdout, "", "{}", said.stdout);
    let rows = journal_rows(session);
    assert!(
        rows.iter()
            .any(|r| r.contains("lint-suppression-added") && r.contains(" watched ")),
        "{rows:?}"
    );
}

/// The implementation-review guard comes first and still refuses, whatever the
/// content says.
#[test]
fn lint_suppression_leaves_the_pass_file_guard_denying() {
    let f = ReadFixture::with_content("lsa-guard", "x.py", "");
    let target = home()
        .join("amont-agent")
        .join("implementation-review")
        .join("by-tree")
        .join("app")
        .join("z.py");
    let cwd = serde_json::Value::String(f.dir.display().to_string());
    let path = serde_json::Value::String(target.display().to_string());
    let said = send(&format!(
        r#"{{"hook_event_name":"PreToolUse","tool_name":"Write","cwd":{cwd},
             "session_id":"lsa-gd-1","permission_mode":"default",
             "tool_input":{{"file_path":{path},"content":"x = 1  # noqa\n"}}}}"#
    ));
    assert_eq!(said.decision().as_deref(), Some("deny"), "{}", said.stdout);
    assert!(
        said.reason().contains("implementation-review"),
        "{}",
        said.stdout
    );
    assert!(
        !said.reason().contains("lint-suppression-added"),
        "{}",
        said.stdout
    );
}

/// The write is recorded before any advice is built, so an advised Edit still
/// resets what the session knows of the file, and `file-reread` sees it.
#[test]
fn lint_suppression_an_advised_edit_is_a_write_for_file_reread() {
    let f = ReadFixture::with_content("lsa-reread", "x.py", "def f(a):\n    return g(a)\n");
    let session = "lsarr-01";
    f.read_done(session);
    let again = f.read(session);
    assert!(
        again.reason().contains("file-reread"),
        "control: {}",
        again.stdout
    );

    let edit = f.file_event("PreToolUse", "Edit", session, ADD_IGNORE);
    assert!(
        edit.reason().contains("lint-suppression-added"),
        "{}",
        edit.stdout
    );
    assert_eq!(
        f.read(session).stdout,
        "",
        "a read after the edit is a different read"
    );
}