Skip to main content

amont_runtime/
bypass.rs

1//! The ledger of unverified commits — the bypass signal, kept instead of
2//! discarded.
3//!
4//! [`crate::gate_stamp`] already detects the interesting event: a commit
5//! that a commit-time gate declaration covered, created without that gate
6//! having run — `--no-verify` is the commonest cause, a blocked attempt
7//! retried with it the second, a gate whose tool was missing the third.
8//! Until this module existed the detection was followed by a bare `return`:
9//! the first symptom of a slow or flaky check (people routing around it) was
10//! thrown away at the exact moment it was in hand.
11//!
12//! This module only counts. The stamp gates a check (a wrong read there
13//! weakens the push gate); the ledger informs a dashboard (a wrong read here
14//! miscounts). That difference in stakes is why this is not part of
15//! `gate_stamp` — nothing in this file participates in any suppression
16//! decision, and nothing ever may.
17//!
18//! The ledger is a local file, never a ref, never pushed, never sent
19//! anywhere — the project's no-telemetry promise applies in full. It lives
20//! in the COMMON git dir (unlike the deliberately worktree-private marker)
21//! because "how often does this repository dodge its gate" is a question
22//! about the repository, not about one worktree. `amont uninstall` deletes
23//! it; so does `amont.recordBypasses false`, prospectively.
24//!
25//! Format, versioned like its siblings (`amont-gate-v1`, `amont-held-v1`):
26//!
27//! ```text
28//! amont-bypass-v1
29//! <unix-epoch> <commit-oid> <script>
30//! ```
31//!
32//! One line per uncovered script. No paths ever appear in the file, which is
33//! why newline/space delimiting is safe here where `staged_only` needed NUL.
34
35use std::io::Write;
36use std::path::{Path, PathBuf};
37
38/// First line of the ledger. A future amont that changes the shape bumps
39/// this, and an old ledger reads as empty rather than being misread.
40pub const FORMAT: &str = "amont-bypass-v1";
41
42/// The ledger's filename inside the common git dir.
43const LEDGER: &str = "amont-bypasses";
44
45/// Compact past this — roughly 1,100 events. A ledger that long has long
46/// since saturated the signal it exists to carry.
47const MAX_BYTES: u64 = 64 * 1024;
48
49/// Events kept by a compaction, newest first. After a compaction the total
50/// is a FLOOR, not an exact count — the recent shape survives, which is the
51/// part that means anything.
52const KEEP: usize = 500;
53
54/// What the ledger says, aggregated. Everything a reader displays comes
55/// through here; nobody re-parses the file.
56#[derive(Debug, Default, Clone, PartialEq, Eq)]
57pub struct Ledger {
58    /// Events on record (a floor after compaction).
59    pub total: usize,
60    /// The newest event's epoch, if any.
61    pub last: Option<u64>,
62    /// Count descending, then script ascending — a stable order a golden
63    /// render can pin.
64    pub by_script: Vec<ScriptCount>,
65}
66
67/// One script's slice of the ledger.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ScriptCount {
70    pub script: String,
71    pub count: usize,
72    /// The newest event for THIS script.
73    pub last: u64,
74}
75
76/// One valid event line, or nothing. The shared trust boundary: `parse` and
77/// compaction both refuse a line through this, so a hand-edited ledger can
78/// neither skew the counts with garbage nor smuggle a control byte into a
79/// terminal — script names must be short printable ASCII, oids hex.
80fn event(line: &str) -> Option<(u64, &str, &str)> {
81    let mut fields = line.split_whitespace();
82    let (Some(epoch), Some(oid), Some(script), None) =
83        (fields.next(), fields.next(), fields.next(), fields.next())
84    else {
85        return None;
86    };
87    let epoch = epoch.parse::<u64>().ok()?;
88    if !(7..=64).contains(&oid.len()) || !oid.bytes().all(|b| b.is_ascii_hexdigit()) {
89        return None;
90    }
91    if !(1..=32).contains(&script.len()) || !script.bytes().all(|b| b.is_ascii_graphic()) {
92        return None;
93    }
94    Some((epoch, oid, script))
95}
96
97/// Aggregate a ledger's text. Pure; a malformed line is skipped, never
98/// guessed at, and a missing or foreign header reads as an empty ledger.
99pub fn parse(text: &str) -> Ledger {
100    let mut lines = text.lines().filter(|l| !l.trim().is_empty());
101    if lines.next() != Some(FORMAT) {
102        return Ledger::default();
103    }
104    let mut out = Ledger::default();
105    for line in lines {
106        let Some((epoch, _oid, script)) = event(line) else {
107            continue;
108        };
109        out.total += 1;
110        out.last = Some(out.last.map_or(epoch, |l| l.max(epoch)));
111        match out.by_script.iter_mut().find(|s| s.script == script) {
112            Some(s) => {
113                s.count += 1;
114                s.last = s.last.max(epoch);
115            }
116            None => out.by_script.push(ScriptCount {
117                script: script.to_string(),
118                count: 1,
119                last: epoch,
120            }),
121        }
122    }
123    out.by_script
124        .sort_by(|a, b| b.count.cmp(&a.count).then(a.script.cmp(&b.script)));
125    out
126}
127
128/// The fleet's door: read the ledger under an already-resolved common dir.
129/// Absent file, unreadable file, foreign format — all read as empty.
130pub fn read_at(common_dir: &Path) -> Ledger {
131    read_file(&common_dir.join(LEDGER))
132}
133
134/// The in-repo door: resolves the common dir itself (process cwd). Empty on
135/// any failure — `amont list` in a broken repo still prints.
136pub fn read() -> Ledger {
137    ledger_path().map(|p| read_file(&p)).unwrap_or_default()
138}
139
140fn read_file(path: &Path) -> Ledger {
141    std::fs::read_to_string(path)
142        .map(|t| parse(&t))
143        .unwrap_or_default()
144}
145
146/// A relative age in the largest unit that fits — integer arithmetic only,
147/// no calendar. A timestamp from the future (clock skew between worktree
148/// hosts) clamps to "just now" rather than underflowing.
149pub fn age(now: u64, then: u64) -> String {
150    let d = now.saturating_sub(then);
151    if d < 60 {
152        "just now".to_string()
153    } else if d < 3600 {
154        format!("{}m ago", d / 60)
155    } else if d < 86_400 {
156        format!("{}h ago", d / 3600)
157    } else if d < 7 * 86_400 {
158        format!("{}d ago", d / 86_400)
159    } else if d < 365 * 86_400 {
160        format!("{}w ago", d / (7 * 86_400))
161    } else {
162        format!("{}y ago", d / (365 * 86_400))
163    }
164}
165
166/// post-commit: record every gate-declared script this commit's files were
167/// covered by that is NOT in `stamped` (what [`crate::gate_stamp`] just
168/// wrote a note for). Completely silent, like the hook it runs in — the
169/// number's whole value is that it is collected without a lecture.
170///
171/// The ordering below is the design: a repository that declares no gate
172/// pays ZERO extra git spawns, and a gated repository whose commit was
173/// properly stamped pays zero too. Only a commit already known to be
174/// unverified spends processes.
175pub(crate) fn note_unverified(manifest: &crate::manifest::Manifest, stamped: &[String]) {
176    let names = crate::hooks::run_tests::gate_names_declared(&manifest.externals);
177    if names.is_empty() {
178        return;
179    }
180    if names.iter().all(|n| stamped.iter().any(|s| s == n)) {
181        return;
182    }
183    // Skips and severity overrides can retire a declaration from the gate;
184    // an entry the push gate would not trust cannot be "bypassed". EVERY
185    // blocking declaration counts, whatever its name — the ledger is about
186    // dodged checks, not about npm's vocabulary.
187    let declared = crate::hooks::run_tests::blocking_commit_decls(&manifest.externals);
188    let missing: Vec<_> = declared
189        .iter()
190        .filter(|d| !stamped.contains(&d.script))
191        .collect();
192    if missing.is_empty() {
193        return;
194    }
195    if !crate::config::boolean_or("amont.recordBypasses", true) {
196        return;
197    }
198    let files = head_files();
199    if files.is_empty() {
200        return; // git could not tell → do not guess
201    }
202    let scripts: Vec<&str> = missing
203        .iter()
204        .filter(|d| d.scope.matches(&files))
205        .map(|d| d.script.as_str())
206        .collect();
207    if scripts.is_empty() {
208        return;
209    }
210    let Some(oid) = crate::git::stdout(&["rev-parse", "HEAD"]) else {
211        return;
212    };
213    let Some(path) = ledger_path() else { return };
214    append(&path, &oid, &scripts);
215}
216
217/// HEAD's own files. `--root` because a parentless commit prints NOTHING
218/// without it, and the initial commit is exactly the one somebody makes with
219/// `--no-verify`. `-m` because a conflict-resolution commit DOES run
220/// post-commit and shows nothing without it. `stdout_paths` inserts `-z`.
221fn head_files() -> Vec<String> {
222    crate::git::stdout_paths(&[
223        "diff-tree",
224        "--no-commit-id",
225        "--name-only",
226        "-r",
227        "-m",
228        "--root",
229        "HEAD",
230    ])
231    .unwrap_or_default()
232}
233
234/// `<common-dir>/amont-bypasses` — shared by every worktree of the repo.
235fn ledger_path() -> Option<PathBuf> {
236    let dir = crate::git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
237    Some(Path::new(&dir).join(LEDGER))
238}
239
240/// Append one event line per script, creating the header first if the file
241/// is new. Best-effort throughout: a bookkeeping failure must never disturb
242/// a commit that already exists.
243fn append(path: &Path, commit: &str, scripts: &[&str]) {
244    // `create_new` means exactly one writer ever wins the header, whatever
245    // the worktree count.
246    let _ = std::fs::OpenOptions::new()
247        .write(true)
248        .create_new(true)
249        .open(path)
250        .and_then(|mut f| f.write_all(format!("{FORMAT}\n").as_bytes()));
251    compact_if_large(path);
252    let now = now_epoch();
253    let mut body = String::new();
254    for script in scripts {
255        body.push_str(&format!("{now} {commit} {script}\n"));
256    }
257    // One O_APPEND write of a few short lines: atomic enough in practice,
258    // and a torn line is dropped by `parse` rather than misread.
259    let _ = std::fs::OpenOptions::new()
260        .create(true)
261        .append(true)
262        .open(path)
263        .and_then(|mut f| f.write_all(body.as_bytes()));
264}
265
266/// Keep the file bounded: past [`MAX_BYTES`], rewrite it as the header plus
267/// the newest [`KEEP`] valid events. A concurrent appender can lose a few
268/// events to the rename — acceptable for a counter, unlike for a gate.
269fn compact_if_large(path: &Path) {
270    let Ok(meta) = std::fs::metadata(path) else {
271        return;
272    };
273    if meta.len() <= MAX_BYTES {
274        return;
275    }
276    let Ok(text) = std::fs::read_to_string(path) else {
277        return;
278    };
279    let events: Vec<&str> = text.lines().filter(|l| event(l).is_some()).collect();
280    let keep = &events[events.len().saturating_sub(KEEP)..];
281    let mut body = String::with_capacity(keep.len() * 64 + FORMAT.len() + 1);
282    body.push_str(FORMAT);
283    body.push('\n');
284    for line in keep {
285        body.push_str(line);
286        body.push('\n');
287    }
288    let tmp = path.with_file_name(format!("{LEDGER}.tmp-{}", std::process::id()));
289    if std::fs::write(&tmp, body).is_ok() {
290        let _ = std::fs::rename(&tmp, path);
291    }
292}
293
294fn now_epoch() -> u64 {
295    std::time::SystemTime::now()
296        .duration_since(std::time::UNIX_EPOCH)
297        .map(|d| d.as_secs())
298        .unwrap_or_default()
299}
300
301/// uninstall: the ledger is OUR bookkeeping, gone with the hooks.
302pub fn forget() {
303    if let Some(path) = ledger_path() {
304        let _ = std::fs::remove_file(&path);
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    fn ledger(events: &[&str]) -> String {
313        let mut s = format!("{FORMAT}\n");
314        for e in events {
315            s.push_str(e);
316            s.push('\n');
317        }
318        s
319    }
320
321    /// No header, no ledger — a truncated or foreign file reads as empty.
322    #[test]
323    fn a_ledger_without_the_header_is_ignored() {
324        assert_eq!(parse("100 abcdef0 typecheck\n"), Ledger::default());
325        assert_eq!(parse(""), Ledger::default());
326    }
327
328    /// A future format version reads as empty rather than being misread.
329    #[test]
330    fn a_ledger_in_an_unknown_format_version_reads_as_empty() {
331        assert_eq!(
332            parse("amont-bypass-v2\n100 abcdef0 typecheck\n"),
333            Ledger::default()
334        );
335    }
336
337    /// A torn or hand-mangled line is skipped; its neighbours still count.
338    #[test]
339    fn malformed_lines_are_skipped_and_the_rest_still_counted() {
340        let text = ledger(&[
341            "100 abcdef0 typecheck",
342            "not an event line",
343            "101 abcdef0",            // two fields
344            "102 abcdef0 test extra", // four fields
345            "103 nothexg typecheck",  // oid not hex
346            "104 abc typecheck",      // oid too short
347            "105 abcdef0 test",
348        ]);
349        let l = parse(&text);
350        assert_eq!(l.total, 2);
351        assert_eq!(l.last, Some(105));
352    }
353
354    /// The trust boundary: a script name carrying a control byte never
355    /// reaches a display — the line is refused wholesale.
356    #[test]
357    fn a_script_name_with_a_control_byte_is_rejected() {
358        let text = ledger(&["100 abcdef0 type\u{1b}check"]);
359        assert_eq!(parse(&text).total, 0);
360    }
361
362    /// Counts group by script; each group keeps its own newest timestamp,
363    /// and the order is count desc then name asc — stable for a render.
364    #[test]
365    fn counts_group_by_script_and_keep_the_latest_timestamp() {
366        let text = ledger(&[
367            "100 aaaaaaa typecheck",
368            "200 bbbbbbb test",
369            "300 ccccccc typecheck",
370        ]);
371        let l = parse(&text);
372        assert_eq!(l.total, 3);
373        assert_eq!(l.last, Some(300));
374        assert_eq!(l.by_script.len(), 2);
375        assert_eq!(l.by_script[0].script, "typecheck");
376        assert_eq!(l.by_script[0].count, 2);
377        assert_eq!(l.by_script[0].last, 300);
378        assert_eq!(l.by_script[1].script, "test");
379        assert_eq!(l.by_script[1].last, 200);
380    }
381
382    /// A repo that never bypassed anything has no file, and that reads as
383    /// zero — not as an error.
384    #[test]
385    fn an_absent_ledger_reads_as_empty() {
386        let dir = std::env::temp_dir().join(format!("amont-bypass-none-{}", std::process::id()));
387        let _ = std::fs::create_dir_all(&dir);
388        assert_eq!(read_at(&dir), Ledger::default());
389        let _ = std::fs::remove_dir_all(&dir);
390    }
391
392    /// Compaction keeps the header and the NEWEST events; the file shrinks
393    /// and still parses.
394    #[test]
395    fn compaction_keeps_the_header_and_the_newest_events() {
396        let dir = std::env::temp_dir().join(format!("amont-bypass-compact-{}", std::process::id()));
397        let _ = std::fs::create_dir_all(&dir);
398        let path = dir.join(LEDGER);
399        let mut body = format!("{FORMAT}\n");
400        // Well past MAX_BYTES: ~2,600 events of ~40 bytes.
401        for i in 0..2_600u64 {
402            body.push_str(&format!("{i} abcdef0123456789 typecheck\n"));
403        }
404        std::fs::write(&path, body).unwrap();
405        compact_if_large(&path);
406        let text = std::fs::read_to_string(&path).unwrap();
407        assert!(text.starts_with(FORMAT));
408        let l = parse(&text);
409        assert_eq!(l.total, KEEP);
410        assert_eq!(l.last, Some(2_599), "the newest events survive");
411        let _ = std::fs::remove_dir_all(&dir);
412    }
413
414    /// Appending to a fresh path writes the header once; appending again
415    /// does not duplicate it.
416    #[test]
417    fn appending_twice_writes_exactly_one_header() {
418        let dir = std::env::temp_dir().join(format!("amont-bypass-append-{}", std::process::id()));
419        let _ = std::fs::create_dir_all(&dir);
420        let path = dir.join(LEDGER);
421        append(&path, "abcdef0123456789", &["typecheck"]);
422        append(&path, "abcdef0123456789", &["test"]);
423        let text = std::fs::read_to_string(&path).unwrap();
424        assert_eq!(text.matches(FORMAT).count(), 1, "{text:?}");
425        assert_eq!(parse(&text).total, 2);
426        let _ = std::fs::remove_dir_all(&dir);
427    }
428
429    /// The largest unit that fits, and clean boundaries.
430    #[test]
431    fn age_reads_in_the_largest_unit_that_fits() {
432        assert_eq!(age(1000, 990), "just now");
433        assert_eq!(age(1000 + 120, 1000), "2m ago");
434        assert_eq!(age(1000 + 2 * 3600, 1000), "2h ago");
435        assert_eq!(age(1000 + 3 * 86_400, 1000), "3d ago");
436        assert_eq!(age(1000 + 20 * 86_400, 1000), "2w ago");
437        assert_eq!(age(1000 + 800 * 86_400, 1000), "2y ago");
438    }
439
440    /// Clock skew across machines can put an event in the future; that
441    /// clamps to "just now" instead of underflowing to eternity.
442    #[test]
443    fn a_timestamp_from_the_future_does_not_underflow() {
444        assert_eq!(age(100, 200), "just now");
445    }
446}