amont-agent 2.41.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
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
//! The record of what the guard saw.
//!
//! Modelled on amont's `bypass` store, including its central rule: **this
//! module only counts. Nothing in it may participate in a decision.** The
//! stance gates a command; the journal informs a human. A wrong read here
//! miscounts, and it must never be able to do worse than that.
//!
//! ## Not in `.git/`
//!
//! `bypass` lives in the common git dir because "how often does this repository
//! dodge its gate" is a question about a repository. This hook fires wherever
//! Claude Code is working, including outside any repository at all, and the
//! question it answers — "does this rule misfire?" — is about the *rule*. So
//! one file per machine, next to the settings that installed it.
//!
//! ## One write per record
//!
//! Several sessions and their subagents run at once. Each record is built
//! whole and written with a single `write_all` to an append-mode handle, and
//! capped so that write stays small enough to interleave atomically in
//! practice. A torn line is dropped on read, exactly as `bypass::event` does —
//! the failure mode is a lost record, never a corrupt count.
//!
//! ## Commands carry secrets
//!
//! Measured across the real corpus: 283 `TOKEN|SECRET|KEY=` assignments, 17
//! `https://user:pass@` URLs, and literal `ghp_`/`--password` values. This file
//! persists command text, so redaction is not optional, and the byte cap is a
//! second line of defence for the shapes nobody anticipated.
//!
//! Never pushed, never transmitted. The project's no-telemetry promise applies
//! in full.

use std::fs;
use std::io::Write;
use std::path::PathBuf;

use crate::ui;

/// First line of the journal. A future format bumps this, and an older reader
/// sees an empty journal rather than misreading one.
pub const FORMAT: &str = "amont-agent-v1";

/// A record must fit in one small write. The excerpt is what gives, because
/// commands do not fit anyway: measured p50 240 bytes, p95 1,777, max 13 KB.
const MAX_RECORD: usize = 512;
const MAX_EXCERPT: usize = 200;

/// Rotate past this. Roughly the same budget `bypass` uses.
const MAX_BYTES: u64 = 256 * 1024;

/// How many rotated generations are kept (`journal.log.1` … `.10`).
const GENERATIONS: u32 = 10;

pub fn dir() -> Option<PathBuf> {
    Some(crate::settings::config_dir()?.join("amont-agent"))
}

/// Open an existing journal file for appending; never creates one. Creating
/// it is [`create_with_header`]'s job, so a writer that raced a rotation finds
/// no file and goes back through the header path instead of creating one
/// without a header. [`private`] is what widens nothing and narrows an old
/// journal in place.
fn open_private(path: &std::path::Path) -> Option<fs::File> {
    let f = fs::OpenOptions::new().append(true).open(path).ok()?;
    // An older amont-agent created this file at 0644 under the default
    // umask, and it is still holding the command text it wrote then. Narrow
    // it once, here, rather than leaving the upgrade to a release note
    // nobody reads.
    private(path, 0o600);
    Some(f)
}

/// Narrow `path` to `mode` when it is wider than that. Never widens, and
/// never complains: a journal that could not be chmod'ed is still a journal,
/// and this module may not fail the hook.
#[cfg(unix)]
pub(crate) fn private(path: &std::path::Path, mode: u32) {
    use std::os::unix::fs::PermissionsExt;
    let Ok(meta) = fs::metadata(path) else { return };
    let now = meta.permissions().mode() & 0o777;
    if now & !mode != 0 {
        let _ = fs::set_permissions(path, fs::Permissions::from_mode(now & mode));
    }
}

/// Windows has no mode bits to narrow; the file inherits the ACL of
/// `%USERPROFILE%\.claude`, which is where its settings already live.
#[cfg(not(unix))]
pub(crate) fn private(_path: &std::path::Path, _mode: u32) {}

pub fn path() -> Option<PathBuf> {
    Some(dir()?.join("journal.log"))
}

/// `journal.log.N` next to `base`.
fn generation(base: &std::path::Path, n: u32) -> PathBuf {
    let mut s = base.as_os_str().to_os_string();
    s.push(format!(".{n}"));
    PathBuf::from(s)
}

/// The generations that exist for `base`, oldest first: `.10` … `.1`, then
/// the live file.
fn paths_of(base: &std::path::Path) -> Vec<PathBuf> {
    (1..=GENERATIONS)
        .rev()
        .map(|n| generation(base, n))
        .chain(std::iter::once(base.to_path_buf()))
        .filter(|p| p.exists())
        .collect()
}

/// Every journal file that exists, oldest first.
pub fn paths() -> Vec<PathBuf> {
    path().map(|p| paths_of(&p)).unwrap_or_default()
}

/// Timestamp of the oldest record in the journal, if any.
pub fn oldest_record() -> Option<u64> {
    paths().iter().find_map(|p| {
        fs::read_to_string(p).ok()?.lines().find_map(|l| {
            let mut f = l.strip_prefix("F ")?.split_whitespace();
            f.next()?.parse::<u64>().ok()
        })
    })
}

/// What one rule has seen, read back out of the journal.
///
/// This is the other half of the loop the crate is built around. A rule ships
/// `observe`, and the question that decides whether it may advise is not how
/// often its `examine` fires — the backtester answers that — but how often its
/// `confirm` agreed. The backtester cannot answer that: it replays commands
/// against a world that has moved, so it never runs `confirm`. The journal is
/// the only record of what `confirm` actually said, and until this reader
/// existed the only way to ask was `awk` on the file.
///
/// Still under the module rule: this counts, and nothing reads it to decide.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Seen {
    pub denied: u32,
    pub advised: u32,
    pub watched: u32,
    /// `examine` fired and `confirm` said no. For an assertion, the claim
    /// could not be checked.
    pub unconfirmed: u32,
    /// Why `confirm` said no, by reason, so the leading one can be shown. A
    /// reason is one whitespace-free token as [`field`] wrote it.
    pub reasons: std::collections::BTreeMap<String, u32>,
}

impl Seen {
    pub fn total(&self) -> u32 {
        self.denied + self.advised + self.watched + self.unconfirmed
    }

    /// The most frequent reason `confirm` declined, if any.
    pub fn top_reason(&self) -> Option<(&str, u32)> {
        self.reasons
            .iter()
            .max_by_key(|(_, n)| **n)
            .map(|(r, n)| (r.as_str(), *n))
    }
}

/// Every rule's [`Seen`] for records no older than `since` seconds.
pub fn tally(since: u64) -> std::collections::BTreeMap<String, Seen> {
    let mut out = Default::default();
    let now = now();
    for p in paths() {
        tally_into(&mut out, &p, since, now);
    }
    out
}

/// [`tally`] against a named file and a fixed clock, so it can be tested
/// without touching the machine's journal.
///
/// Reads one generation: only `F ` lines, and a line that does not
/// carry its fixed fields is a torn write and is dropped, never counted
/// wrong. The eight fixed fields are exactly what [`line_for`] emits; the
/// excerpt after them is free text and is not parsed.
#[cfg(test)]
pub fn tally_at(
    path: &std::path::Path,
    since: u64,
    now: u64,
) -> std::collections::BTreeMap<String, Seen> {
    let mut out: std::collections::BTreeMap<String, Seen> = Default::default();
    tally_into(&mut out, path, since, now);
    out
}

fn tally_into(
    out: &mut std::collections::BTreeMap<String, Seen>,
    path: &std::path::Path,
    since: u64,
    now: u64,
) {
    let Ok(text) = fs::read_to_string(path) else {
        return;
    };
    let floor = now.saturating_sub(since);
    for line in text.lines() {
        if !line.starts_with("F ") {
            continue;
        }
        let mut f = line.split_whitespace();
        let (Some(_), Some(ts), Some(rule), Some(stance), Some(outcome)) =
            (f.next(), f.next(), f.next(), f.next(), f.next())
        else {
            continue;
        };
        let Ok(ts) = ts.parse::<u64>() else {
            continue;
        };
        if ts < floor {
            continue;
        }
        let seen = out.entry(rule.to_string()).or_default();
        match (stance, outcome) {
            // A `confirm` that declined, or an assertion that could not check
            // its claim. The outcome field carries the reason; older records
            // wrote the literal `skipped` there, which counts as a reason
            // nobody stated.
            ("unconfirmed" | "unverified", why) => {
                seen.unconfirmed += 1;
                *seen.reasons.entry(why.to_string()).or_default() += 1;
            }
            (_, "denied") => seen.denied += 1,
            (_, "advised") => seen.advised += 1,
            (_, "watched") => seen.watched += 1,
            // An outcome this reader does not know. Counted as seen, because
            // it was, but not as any of the four it can name.
            _ => {}
        }
    }
}

/// One thing that happened.
pub struct Entry<'a> {
    pub rule: &'a str,
    pub stance: &'a str,
    /// What actually happened to the command: `denied`, `advised`, `watched`.
    pub outcome: &'a str,
    pub session: &'a str,
    pub repo: &'a str,
    /// The permission mode the call arrived in. Recorded, never acted on —
    /// it is how you would notice if a rule ever stopped applying in one.
    pub mode: &'a str,
    pub excerpt: &'a str,
}

/// Append one record. Every failure is swallowed: the journal must never be
/// able to fail the hook, and `the_journal_never_fails_the_hook` pins that.
/// Set by `doctor`'s own probe on the child it spawns. See [`record`].
pub const ENV_PROBE: &str = "AMONT_AGENT_PROBE";

pub fn record(entry: &Entry) {
    // `doctor` proves the guard works by feeding the real binary a command it
    // must refuse. That firing is synthetic — nobody typed it, and no model
    // was going to run it — so recording it would put a `pipe-to-tail` denial
    // in the journal every time somebody asks whether the guard is healthy.
    //
    // That matters beyond tidiness. The journal is the measurement: `status`
    // counts it, and the per-1000 evidence that gates `graduate` comes from
    // the same data. A health check that inflates a rule's firing rate makes
    // the rule look more necessary the more often you check on it — the
    // observer changing what it observes, which is the exact distinction
    // `observe` and `advise` exist to keep clean.
    if std::env::var_os(ENV_PROBE).is_some() {
        return;
    }
    let _ = try_record(entry);
}

fn try_record(entry: &Entry) -> Option<()> {
    let path = path()?;
    let dir = path.parent()?;
    fs::create_dir_all(dir).ok()?;
    private(dir, 0o700);
    append(&path, MAX_BYTES, &line_for(entry))
}

/// Rotate if needed, then append one record. Split from [`try_record`] so a
/// test can use a scratch path and a small threshold.
fn append(path: &std::path::Path, max: u64, line: &str) -> Option<()> {
    // Rotation happens BEFORE the write, so `journal.log` always exists
    // afterwards and doctor's liveness mtime stays correct.
    let mut stuck = None;
    if fs::metadata(path).map(|m| m.len() > max).unwrap_or(false) {
        stuck = rotate(path, max).err();
    }
    // The file appears with its header already in it: of several writers
    // that find no file, exactly one creates it, and nobody can append to an
    // empty file the header would then overwrite.
    // A rotation can move the file between the two steps; then the open finds
    // nothing, and the header path runs again.
    let mut f = (0..3).find_map(|_| {
        create_with_header(path)?;
        open_private(path)
    })?;
    if let Some(why) = stuck {
        // The journal kept growing past its cap: said once per write, in the
        // journal itself, where `doctor` and a reader of the file see it.
        let _ = f.write_all(format!("F {} - - rotate-failed - - - {why}\n", now()).as_bytes());
    }
    f.write_all(line.as_bytes()).ok()?;
    Some(())
}

/// Create `path` holding just the header, if it does not exist. The header is
/// written to a file of this process's own, then hard-linked into place: a
/// link fails when the name exists, so the creation is atomic and carries its
/// content. (A `create_new` then `write_all` was not: another writer appended
/// a record to the empty file, and the header overwrote it at offset 0.)
///
/// `None` only when the header could not be written at all: the record is
/// then dropped rather than left in a file without one.
///
/// The mode, 0600 rather than 0644, is set AT CREATION, not afterwards: a
/// file that exists world-readable for the instant between `open` and
/// `set_permissions` is a file somebody's backup agent can have read, and the
/// link carries the staged file's mode. An existing journal keeps whatever
/// mode it has — the same rule `atomic::carry_mode` follows for
/// `settings.json`, and for the same reason: our writes never change who can
/// read a file that already existed.
fn create_with_header(path: &std::path::Path) -> Option<()> {
    if path.exists() {
        return Some(());
    }
    let staged = {
        let mut s = path.as_os_str().to_os_string();
        // Per call, not per process: two threads must not share it.
        static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let n = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        s.push(format!(".new.{}.{n}", std::process::id()));
        PathBuf::from(s)
    };
    let mut opts = fs::OpenOptions::new();
    opts.write(true).create(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let wrote = opts
        .open(&staged)
        .and_then(|mut f| f.write_all(format!("{FORMAT}\n").as_bytes()));
    // AlreadyExists is another writer's header: ours is not needed.
    let linked = wrote.and_then(|()| match fs::hard_link(&staged, path) {
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
        // A file system without hard links: an append-mode `create_new`.
        // A racing record may then come before the header, never under it.
        Err(_) => {
            let mut opts = fs::OpenOptions::new();
            opts.append(true).create_new(true);
            #[cfg(unix)]
            {
                use std::os::unix::fs::OpenOptionsExt;
                opts.mode(0o600);
            }
            match opts.open(path) {
                Ok(mut f) => f.write_all(format!("{FORMAT}\n").as_bytes()),
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
                Err(e) => Err(e),
            }
        }
        Ok(()) => Ok(()),
    });
    let _ = fs::remove_file(&staged);
    linked.ok()
}

/// Shift the generations by renames only; nothing is read or rewritten. A
/// short-lived lock file makes one writer do it: the others append to the
/// file as it is. A stale lock (a crashed writer) is ignored after a minute.
/// `Err` only when the live file could not be moved: older generations that
/// fail to shift cost history, never the cap.
fn rotate(path: &std::path::Path, max: u64) -> Result<(), String> {
    let lock = generation(path, 0);
    let mut opts = fs::OpenOptions::new();
    opts.write(true).create_new(true);
    if opts.open(&lock).is_err() {
        let stale = fs::metadata(&lock)
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.elapsed().ok())
            .is_some_and(|age| age.as_secs() > 60);
        if !stale || fs::remove_file(&lock).is_err() || opts.open(&lock).is_err() {
            return Ok(());
        }
    }
    let mut moved = Ok(());
    // Re-check under the lock: another writer may have rotated already.
    if fs::metadata(path).map(|m| m.len() > max).unwrap_or(false) {
        let _ = fs::remove_file(generation(path, GENERATIONS));
        for n in (1..GENERATIONS).rev() {
            let _ = fs::rename(generation(path, n), generation(path, n + 1));
        }
        moved = fs::rename(path, generation(path, 1)).map_err(|e| e.kind().to_string());
    }
    let _ = fs::remove_file(&lock);
    moved
        .map(|_| ())
        .map_err(|why| why.replace(char::is_whitespace, "-"))
}

/// Build the whole record as one line. Separated from the write so it can be
/// tested without a filesystem, and so `a_record_is_one_write` can assert the
/// shape rather than race on it.
pub fn line_for(entry: &Entry) -> String {
    let excerpt = redact_and_trim(entry.excerpt);
    let mut line = format!(
        "F {} {} {} {} {} {} {} {}\n",
        now(),
        field(entry.rule),
        field(entry.stance),
        field(entry.outcome),
        field(&entry.session.chars().take(8).collect::<String>()),
        field(entry.repo),
        field(entry.mode),
        excerpt
    );
    if line.len() > MAX_RECORD {
        let keep = MAX_RECORD - 2;
        let cut = (0..=keep)
            .rev()
            .find(|i| line.is_char_boundary(*i))
            .unwrap_or(0);
        line.truncate(cut);
        line.push('\n');
    }
    line
}

/// A single space-free token. Everything in a record but the excerpt is one,
/// which is what lets the reader split on whitespace.
fn field(s: &str) -> String {
    let cleaned: String = ui::sanitize(s)
        .chars()
        .map(|c| if c.is_whitespace() { '_' } else { c })
        .collect();
    if cleaned.is_empty() {
        "-".to_string()
    } else {
        cleaned
    }
}

/// Secrets out, control bytes out, newlines out, then a hard length cap.
pub fn redact_and_trim(text: &str) -> String {
    let mut s = redact(text);
    s = ui::sanitize(&s);
    s = s.split_whitespace().collect::<Vec<_>>().join(" ");
    if s.chars().count() > MAX_EXCERPT {
        s = s.chars().take(MAX_EXCERPT).collect::<String>() + "…";
    }
    s
}

/// The shapes that actually appear in the corpus, plus the obvious token
/// prefixes. Deliberately blunt: this is a redactor, not a parser, and a
/// false redaction costs a less readable sample while a missed one costs a
/// secret on disk.
pub fn redact(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    // Whether the PREVIOUS word said that this one is a credential.
    // `--password=x` is one word and `redact_word` handles it alone;
    // `--password x` and `Authorization: Bearer <jwt>` are two, and a
    // word-at-a-time redactor could not see the second half of either.
    let mut announced = false;
    for word in text.split_inclusive(char::is_whitespace) {
        let trimmed = word.trim_end();
        if announced && !trimmed.is_empty() && !trimmed.starts_with('-') {
            // Keep whatever CLOSES the word — a quote, a comma — attached
            // rather than swallowed, exactly as `redact_query` does. A
            // redactor that turns `-H "Authorization: Bearer x"` into
            // unbalanced quotes makes its own output unreadable, which is
            // the bug the corpus already caught once.
            let closing: String = trimmed
                .chars()
                .rev()
                .take_while(|c| !c.is_alphanumeric() && !matches!(c, '-' | '_' | '.'))
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .collect();
            out.push_str("***");
            out.push_str(&closing);
            out.push_str(&word[trimmed.len()..]);
            announced = false;
            continue;
        }
        announced = announces_a_secret(trimmed);
        out.push_str(&redact_word(word));
    }
    out
}

/// Does this word say "the NEXT one is a credential"?
///
/// A flag whose name reads like a secret and carries no `=` of its own, or
/// an HTTP authentication scheme. Blunt in the same direction as the rest of
/// this module: `--api-key-file config.json` loses the filename, which costs
/// a less readable sample, and the alternative costs a token on disk.
///
/// `-p` is deliberately absent. It is `--password` to mysql and `--patch` to
/// git, and `git add -p .` is far commoner here than the other one.
fn announces_a_secret(word: &str) -> bool {
    if word.eq_ignore_ascii_case("bearer") || word.eq_ignore_ascii_case("basic") {
        return true;
    }
    let Some(name) = word.strip_prefix('-') else {
        return false;
    };
    if word.contains('=') {
        return false; // `--password=x` — one word, already handled
    }
    let name = name.strip_prefix('-').unwrap_or(name);
    !name.is_empty() && secret_named(name)
}

fn redact_word(word: &str) -> String {
    let trimmed = word.trim_end();
    let tail = &word[trimmed.len()..];

    // A URL is handled as a URL, because the `NAME=value` rule below cannot see
    // the difference between an assignment and a query string. It used to try,
    // with `API` among its needles — so `/api/v1/repos/…?limit=5"` matched,
    // everything after the `=` was replaced including the closing quote, and a
    // perfectly ordinary curl became unparseable shell. The corpus caught it.
    if let Some(scheme) = trimmed.find("://") {
        let mut out = String::from(&trimmed[..scheme + 3]);
        let rest = &trimmed[scheme + 3..];
        // `https://user:pass@host`
        let rest = match rest.find('@') {
            Some(at) if !rest[..at].contains('/') => {
                out.push_str("***:***");
                &rest[at..]
            }
            _ => rest,
        };
        out.push_str(&redact_query(rest));
        return out + tail;
    }
    // `--password=x`, `GITHUB_TOKEN=x`. Only where the name reads like a flag
    // or an identifier: a name carrying a path separator is not an assignment.
    if let Some(eq) = trimmed.find('=') {
        let (name, _) = trimmed.split_at(eq);
        if !name.contains('/') && !name.contains(':') && secret_named(name) {
            return format!("{name}=***") + tail;
        }
    }
    // Bare credential shapes.
    for prefix in [
        "ghp_",
        "gho_",
        "ghu_",
        "ghs_",
        "ghr_",
        "github_pat_",
        "sk-",
        "AKIA",
    ] {
        if trimmed.starts_with(prefix) && trimmed.len() > prefix.len() + 8 {
            return format!("{prefix}***{tail}");
        }
    }
    word.to_string()
}

/// Does this name say "the thing after the `=` is a credential"?
///
/// `API` is deliberately absent: on its own it matches every `/api/` in every
/// URL. `API_KEY` and `APIKEY` are still caught, by `KEY`.
fn secret_named(name: &str) -> bool {
    let upper = name.to_ascii_uppercase();
    ["TOKEN", "SECRET", "PASSWORD", "PASSWD", "KEY", "CREDENTIAL"]
        .iter()
        .any(|needle| upper.contains(needle))
}

/// Redact only the values of secret-named query parameters, leaving the rest of
/// the URL — and, critically, any trailing quote — intact.
///
/// The user's own standing rule is that a secret riding in a URL is still a
/// secret, so `?token=…` must go; `?limit=5` must not.
fn redact_query(rest: &str) -> String {
    let Some(q) = rest.find('?') else {
        return rest.to_string();
    };
    let (base, query) = rest.split_at(q + 1);
    let mut out = String::from(base);
    // Keep whatever closes the word (a quote, a comma) attached to the last
    // parameter rather than swallowed by it.
    for (i, param) in query.split('&').enumerate() {
        if i > 0 {
            out.push('&');
        }
        match param.split_once('=') {
            Some((name, value)) if secret_named(name) => {
                let keep: String = value
                    .chars()
                    .rev()
                    .take_while(|c| !c.is_alphanumeric() && *c != '-' && *c != '_')
                    .collect::<Vec<_>>()
                    .into_iter()
                    .rev()
                    .collect();
                out.push_str(name);
                out.push_str("=***");
                out.push_str(&keep);
            }
            _ => out.push_str(param),
        }
    }
    out
}

fn now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry<'a>(excerpt: &'a str) -> Entry<'a> {
        Entry {
            rule: "pipe-to-tail",
            stance: "deny",
            outcome: "denied",
            session: "0123456789abcdef",
            repo: "amont",
            mode: "default",
            excerpt,
        }
    }

    /// The reader counts what the writer wrote, drops what it cannot read,
    /// and never invents a reason for a record that stated none.
    #[test]
    fn the_tally_reads_what_was_written_and_nothing_else() {
        let dir = std::env::temp_dir().join(format!("amont-agent-tally-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).expect("scratch dir");
        let path = dir.join("journal.log");
        let now = 2_000_000u64;
        let text = format!(
            "{FORMAT}\n\
             F {} pipe-to-tail deny denied sess repo default git push | tail -1\n\
             F {} stale-base advise advised sess repo default git checkout -b x\n\
             F {} stale-base unconfirmed the_start_point_is_not_behind_origin sess repo default git checkout -b y\n\
             F {} stale-base unconfirmed the_start_point_is_not_behind_origin sess repo default git checkout -b z\n\
             F {} stale-base unconfirmed skipped sess repo default git checkout -b w\n\
             F {} branch-force-delete observe watched sess repo default git branch -D q\n\
             F {} branch-force-delete observe watched sess repo default git branch -D old\n\
             F {} pipe-to-tail deny denied\n\
             F notatime pipe-to-tail deny denied sess repo default x\n\
             this line is torn and has no F\n",
            now - 10,
            now - 20,
            now - 30,
            now - 40,
            now - 50,
            now - 60,
            now - 400_000, // outside a 100_000-second window
            now - 5,       // fixed fields present, no excerpt: still a record
        );
        fs::write(&path, text).expect("write journal");

        let seen = tally_at(&path, 100_000, now);

        let pipe = &seen["pipe-to-tail"];
        assert_eq!((pipe.denied, pipe.total()), (2, 2), "{pipe:?}");

        let stale = &seen["stale-base"];
        assert_eq!(stale.advised, 1);
        assert_eq!(stale.unconfirmed, 3);
        assert_eq!(
            stale.top_reason(),
            Some(("the_start_point_is_not_behind_origin", 2)),
            "the leading reason, not the legacy `skipped`"
        );

        let bfd = &seen["branch-force-delete"];
        assert_eq!(bfd.watched, 1, "the old record is outside the window");

        let _ = fs::remove_dir_all(&dir);
    }

    /// The implementation review's lines count under the buckets the soak
    /// reads: declined pushes by reason, spoken ones by stance.
    #[test]
    fn the_tally_keeps_the_implementation_reviews_reasons_apart() {
        let dir = std::env::temp_dir().join(format!("amont-agent-tally-ir-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).expect("scratch dir");
        let path = dir.join("journal.log");
        let now = 2_000_000u64;
        let t = now - 10;
        let text = format!(
            "{FORMAT}\n\
             F {t} implementation-review unconfirmed reviewed s1 app default git push -u origin feat/x\n\
             F {t} implementation-review unconfirmed reviewed s1 app default git push -u origin feat/x\n\
             F {t} implementation-review unconfirmed no-plan s1 app default git push -u origin chore/b\n\
             F {t} implementation-review unconfirmed overruled s1 app default git push -u origin feat/x\n\
             F {t} implementation-review advise advised s1 app default tree=5085edae1d66 review=missing verdict=-\n\
             F {t} implementation-review advise advised s1 app default tree=5085edae1d66 review=stale verdict=-\n\
             F {t} implementation-review deny denied s1 app default tree=5085edae1d66 review=missing verdict=-\n\
             F {t} implementation-review observe watched s1 app default tree=5085edae1d66 review=missing verdict=-\n\
             F {t} implementation-review - overruled s1 app - tree=5085edae1d66 review=overruled verdict=rework\n"
        );
        fs::write(&path, text).expect("write journal");
        let seen = tally_at(&path, 100_000, now);
        let ir = &seen["implementation-review"];
        assert_eq!((ir.advised, ir.denied, ir.watched), (2, 1, 1), "{ir:?}");
        assert_eq!(ir.unconfirmed, 4);
        assert_eq!(ir.reasons.get("reviewed"), Some(&2));
        assert_eq!(ir.reasons.get("no-plan"), Some(&1));
        assert_eq!(ir.reasons.get("overruled"), Some(&1));
        let _ = fs::remove_dir_all(&dir);
    }

    /// Interleaving is only safe if a record is one line with no interior
    /// newline. Cheaper and far less flaky to assert on the builder than to
    /// race real processes.
    #[test]
    fn a_record_is_exactly_one_line() {
        let line = line_for(&entry("git push \n\n origin main | tail -1"));
        assert_eq!(line.matches('\n').count(), 1);
        assert!(line.ends_with('\n'));
        assert!(line.len() <= MAX_RECORD);
    }

    /// A 13 KB command must not produce a 13 KB write.
    #[test]
    fn an_enormous_command_still_fits_one_write() {
        let line = line_for(&entry(&"x".repeat(20_000)));
        assert!(line.len() <= MAX_RECORD, "{} bytes", line.len());
        assert_eq!(line.matches('\n').count(), 1);
    }

    /// This file persists command text, and command text carries credentials.
    #[test]
    fn a_credential_never_reaches_the_journal() {
        for (raw, must_not_contain) in [
            ("git push https://fred:hunter2@github.com/x", "hunter2"),
            (
                "GITHUB_TOKEN=ghp_abcdefghijklmnop1234 git push",
                "ghp_abcdefghijklmnop1234",
            ),
            ("curl -H x --password=s3cr3t https://x", "s3cr3t"),
            (
                "gh auth login --with-token ghp_zzzzzzzzzzzzzzzzzzzz",
                "ghp_zzzzzzzzzzzzzzzzzzzz",
            ),
        ] {
            let got = redact_and_trim(raw);
            assert!(
                !got.contains(must_not_contain),
                "leaked {must_not_contain:?} from {raw:?} → {got}"
            );
        }

        // The AWS shape is assembled at run time rather than written out.
        // amont's own `pre-commit-secrets` refused this file when the literal
        // was here — correctly, because it matches on shape and cannot know
        // that this particular one is Amazon's published example. A test fixture
        // is not worth teaching a secret scanner to make exceptions.
        let key = format!("AKIA{}", "IOSFODNN7EXAMPLE");
        let got = redact_and_trim(&format!("aws --key {key} s3 ls"));
        assert!(!got.contains(&key), "leaked an access key id → {got}");
    }

    /// Redaction must not eat the part a reviewer needs.
    #[test]
    fn redaction_leaves_the_command_readable() {
        let got = redact_and_trim("GITHUB_TOKEN=ghp_abcdefghijklmnop1234 git push | tail -1");
        assert!(got.contains("git push"), "{got}");
        assert!(got.contains("tail"), "{got}");
    }

    /// A control byte in a command must not reach a file a terminal will later
    /// print — the same reason `ui::sanitize` exists for the trust prompt.
    #[test]
    fn control_bytes_are_escaped_not_stored_raw() {
        let got = redact_and_trim("git push \u{1b}[8m hidden");
        assert!(!got.contains('\u{1b}'), "{got}");
    }

    /// The bug the corpus found. `API` was a secret-name needle, so `/api/v1/`
    /// in any URL matched, everything after the first `=` was replaced — the
    /// closing quote included — and an ordinary curl became unparseable shell.
    /// A redactor that mangles benign commands makes its own output useless.
    #[test]
    fn an_api_path_is_not_a_secret_assignment() {
        let raw = r#"curl -sS "http://localhost:3000/api/v1/repos/x/actions/tasks?limit=5" | jq"#;
        assert_eq!(redact(raw), raw, "a benign URL was rewritten");
    }

    /// But a secret riding in a URL is still a secret.
    #[test]
    fn a_secret_query_parameter_is_still_redacted() {
        let got = redact("curl \"https://hooks.example.com/x?token=abc123def456&limit=5\"");
        assert!(!got.contains("abc123def456"), "{got}");
        assert!(
            got.contains("limit=5"),
            "the benign parameter survived: {got}"
        );
        assert!(got.ends_with('"'), "the closing quote survived: {got}");
    }

    /// Redaction must not turn a readable command into one the lexer refuses,
    /// or every redacted sample becomes useless for review.
    #[test]
    fn redaction_leaves_a_command_the_lexer_can_still_read() {
        for raw in [
            r#"curl -sS "http://x/api/v1/tasks?limit=5" | jq '.total'"#,
            r#"GITHUB_TOKEN=ghp_aaaaaaaaaaaaaaaaaaaa git push origin main"#,
            r#"git commit -m "msg" --no-verify && git push"#,
        ] {
            let redacted = redact(raw);
            assert!(
                !matches!(
                    crate::shell::lex(&redacted),
                    crate::shell::Parsed::Opaque(_)
                ),
                "redaction made this unreadable: {redacted}"
            );
        }
    }

    #[test]
    fn a_field_never_contains_a_space() {
        assert!(!field("two words").contains(' '));
        assert_eq!(field(""), "-");
    }

    /// The half a word-at-a-time redactor could not see: the credential is
    /// the NEXT word, not the one carrying the `=`.
    #[test]
    fn a_credential_in_the_following_word_is_redacted_too() {
        for (raw, secret) in [
            ("curl --password s3cr3t https://x", "s3cr3t"),
            (
                "gh auth login --with-token gitlab-abcdefghij",
                "gitlab-abcdefghij",
            ),
            (
                r#"curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.body.sig" https://x"#,
                "eyJhbGciOiJIUzI1NiJ9.body.sig",
            ),
            (
                "vault write secret/x api_key=zzz --token hvs.CAESIJx",
                "hvs.CAESIJx",
            ),
        ] {
            let got = redact(raw);
            assert!(
                !got.contains(secret),
                "leaked {secret:?} from {raw:?} → {got}"
            );
        }
    }

    /// …and it must not eat the quote that closes the word, or the sample
    /// stops being a command anybody can read. Same rule `redact_query`
    /// already follows for a secret query parameter.
    #[test]
    fn the_following_word_keeps_what_closes_it() {
        let got = redact(r#"curl -H "Authorization: Bearer abcdefghij" https://x"#);
        assert!(
            got.contains(r#"***""#),
            "the closing quote was swallowed: {got}"
        );
        assert!(
            !matches!(crate::shell::lex(&got), crate::shell::Parsed::Opaque(_)),
            "redaction made this unreadable: {got}"
        );
    }

    /// A flag is not a value. `--token --verbose` must not redact the second
    /// flag and then let the real value through unredacted behind it.
    #[test]
    fn a_flag_after_an_announcement_is_not_the_value() {
        let got = redact("curl --token --verbose https://x");
        assert!(got.contains("--verbose"), "{got}");
    }

    /// The file holds command text. It is created 0600, not 0644 — and an
    /// older one, written before this was true, is narrowed in place.
    #[cfg(unix)]
    #[test]
    fn the_journal_is_not_world_readable() {
        use std::os::unix::fs::PermissionsExt;
        let dir = std::env::temp_dir().join(format!("amont-agent-mode-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        let fresh = dir.join("journal.log");
        create_with_header(&fresh).expect("create");
        open_private(&fresh).expect("open");
        let mode = fs::metadata(&fresh).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "a journal we create is ours alone");

        let old = dir.join("legacy.log");
        fs::write(&old, "F 1 x\n").unwrap();
        fs::set_permissions(&old, fs::Permissions::from_mode(0o644)).unwrap();
        open_private(&old).expect("open");
        let mode = fs::metadata(&old).unwrap().permissions().mode() & 0o777;
        assert_eq!(
            mode, 0o600,
            "an existing 0644 journal is narrowed, not left"
        );

        // …but never WIDENED: 0400 is stricter than we ask for and stays.
        let strict = dir.join("strict.log");
        fs::write(&strict, "F 1 x\n").unwrap();
        fs::set_permissions(&strict, fs::Permissions::from_mode(0o400)).unwrap();
        private(&strict, 0o600);
        let mode = fs::metadata(&strict).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o400, "narrowing must never widen");

        let _ = fs::remove_dir_all(&dir);
    }

    fn scratch(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("amont-agent-{tag}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).expect("scratch dir");
        dir
    }

    fn rec(ts: u64, tag: &str) -> String {
        format!("F {ts} r deny denied sess repo default {tag}\n")
    }

    #[test]
    fn rotation_keeps_ten_generations_and_every_file_has_a_header() {
        let dir = scratch("rotate");
        let path = dir.join("journal.log");
        let big = "x".repeat(300);
        // ~350 bytes a record, threshold 1000: about 3 records a generation.
        for i in 0..60 {
            append(&path, 1000, &rec(1, &format!("late{i} {big}"))).expect("append");
        }
        let all = paths_of(&path);
        assert_eq!(all.len(), 11, "journal.log + .1..=.10: {all:?}");
        assert!(!generation(&path, 11).exists(), "the oldest was dropped");
        for p in &all {
            let text = fs::read_to_string(p).unwrap();
            assert_eq!(text.lines().next(), Some(FORMAT), "{p:?}");
        }
        // Oldest first: the last path is the live file.
        assert_eq!(all.last(), Some(&path));
        assert!(all[0].ends_with("journal.log.10"));
        let _ = fs::remove_dir_all(&dir);
    }

    /// A live file that cannot be moved keeps growing: the journal says so
    /// rather than keeping quiet about a broken cap.
    #[test]
    fn a_rotation_that_cannot_move_the_live_file_is_journalled() {
        let dir = scratch("stuck");
        let path = dir.join("journal.log");
        append(&path, 100, &rec(1, &"z".repeat(200))).expect("first");
        // Every generation is a non-empty directory: no rename can land, so
        // the live file stays where it is, past its cap.
        for n in 1..=GENERATIONS {
            fs::create_dir(generation(&path, n)).unwrap();
            fs::write(generation(&path, n).join("x"), "x").unwrap();
        }
        append(&path, 100, &rec(2, "late")).expect("still appends");
        let text = fs::read_to_string(&path).unwrap();
        assert!(text.contains(" rotate-failed "), "{text}");
        assert!(text.contains(" late"), "{text}");
        assert!(!generation(&path, 0).exists(), "the lock is released");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn the_tally_reads_every_generation_with_the_floor() {
        let dir = scratch("gens");
        let path = dir.join("journal.log");
        let now = 2_000_000u64;
        let w = |p: &std::path::Path, ts: u64, rule: &str| {
            fs::write(
                p,
                format!("{FORMAT}\nF {ts} {rule} deny denied s r default x\n"),
            )
            .unwrap();
        };
        w(&generation(&path, 3), now - 100, "in-three");
        w(&generation(&path, 9), now - 500_000, "old-nine");
        w(&path, now - 5, "live");
        let mut seen = std::collections::BTreeMap::new();
        for p in paths_of(&path) {
            tally_into(&mut seen, &p, 100_000, now);
        }
        assert_eq!(seen["in-three"].denied, 1);
        assert_eq!(seen["live"].denied, 1);
        assert!(!seen.contains_key("old-nine"), "outside the window");
        let _ = fs::remove_dir_all(&dir);
    }

    /// Entry point for the child processes of the test below; a no-op unless
    /// the parent set the environment.
    #[test]
    #[ignore = "a helper: spawned by eight_processes_lose_no_record_and_tear_no_line"]
    fn child_writer() {
        let (Some(p), Some(id)) = (
            std::env::var_os("AMONT_JOURNAL_TEST_PATH"),
            std::env::var("AMONT_JOURNAL_TEST_ID").ok(),
        ) else {
            return;
        };
        for i in 0..120 {
            append(
                std::path::Path::new(&p),
                20_000,
                &rec(1, &format!("w{id}-{i} {}", "y".repeat(100))),
            );
        }
    }

    #[test]
    fn eight_processes_lose_no_record_and_tear_no_line() {
        let dir = scratch("procs");
        let path = dir.join("journal.log");
        let exe = std::env::current_exe().unwrap();
        let kids: Vec<_> = (0..8)
            .map(|id| {
                std::process::Command::new(&exe)
                    .args([
                        "--exact",
                        "--ignored",
                        "journal::tests::child_writer",
                        "--test-threads=1",
                    ])
                    .env("AMONT_JOURNAL_TEST_PATH", &path)
                    .env("AMONT_JOURNAL_TEST_ID", id.to_string())
                    .stdout(std::process::Stdio::null())
                    .spawn()
                    .expect("spawn")
            })
            .collect();
        for mut k in kids {
            assert!(k.wait().unwrap().success());
        }
        let mut found = std::collections::BTreeSet::new();
        for p in paths_of(&path) {
            let text = fs::read_to_string(&p).unwrap();
            // Concurrent too: a file appears with its header already in it.
            assert_eq!(text.lines().next(), Some(FORMAT), "{p:?}");
            for line in text.lines() {
                if line.starts_with("F ") {
                    let f: Vec<&str> = line.split_whitespace().collect();
                    assert!(f.len() >= 9, "torn line {line:?} in {p:?}");
                    found.insert(f[8].to_string());
                }
            }
        }
        assert!(
            paths_of(&path).len() > 2,
            "the threshold was crossed several times"
        );
        for id in 0..8 {
            for i in 0..120 {
                assert!(found.contains(&format!("w{id}-{i}")), "lost w{id}-{i}");
            }
        }
        let _ = fs::remove_dir_all(&dir);
    }
}