Skip to main content

amont_runtime/
gate_stamp.rs

1//! The record that turns "a declaration exists" into "the check ran".
2//!
3//! Moving a gate entry to commit time (`docs/checks.md`, "Moving a gate entry
4//! earlier") makes the push gate skip a script because a `pre-commit`
5//! declaration covers it. A declaration is a promise on paper: a commit made
6//! with `--no-verify`, from a libgit2 client that runs no hooks, or on a
7//! machine without amont was never judged by it — and until this module
8//! existed, push time had no way to tell those commits from checked ones.
9//!
10//! Three hooks share one record:
11//!
12//! 1. **pre-commit** ([`record`]) writes a one-shot marker into `$GIT_DIR`
13//!    naming the gate scripts that actually ran, bound to the tree the commit
14//!    is about to write (`git write-tree` — during pre-commit the index IS
15//!    the commit's content; `staged_only` parks only the working tree).
16//! 2. **post-commit** ([`bind_to_head`]) consumes the marker and, when the
17//!    marker's tree matches `HEAD^{tree}`, stamps the commit in a notes ref.
18//!    `--no-verify` skips pre-commit but NOT post-commit, so an unchecked
19//!    commit arrives here with no marker and gets no stamp — which is the
20//!    entire point. The tree comparison makes an aborted commit's leftover
21//!    marker harmless, and a retried commit of the SAME tree correctly
22//!    stamped: the check really did run on exactly that content.
23//! 3. **pre-push** ([`stamps_for`]) reads the stamps back and suppresses a
24//!    gate script only for pushes whose relevant commits all carry it.
25//!
26//! Every failure mode points the same direction: no marker, a mismatched
27//! tree, a missing note, a rewritten hash — all mean "no stamp", and no stamp
28//! means the push gate RUNS. Nothing here can let an unchecked commit
29//! through; it can only cost a redundant gate run.
30//!
31//! Why a notes ref and not config: notes are keyed by commit, garbage-collect
32//! with unreachable commits (an `amont.checked.<hash>` config key would
33//! outlive every rebase forever), stay local (notes refs are not pushed by
34//! default), and stay out of `git log` (only `refs/notes/commits` displays by
35//! default). `amont uninstall` deletes the ref; see `uninstall_repo_hooks`.
36
37use std::collections::{HashMap, HashSet};
38use std::path::PathBuf;
39
40/// First token of the marker file and of every note body. Versioned like
41/// `staged_only::FORMAT`: a future amont that changes the shape bumps this,
42/// and an old record is ignored rather than misread.
43pub const FORMAT: &str = "amont-gate-v1";
44
45/// The notes ref, spelled the way `git notes --ref` wants it.
46pub const NOTES_REF: &str = "amont-gate";
47
48/// The same ref, fully qualified — what `git update-ref -d` needs.
49pub const NOTES_FULL_REF: &str = "refs/notes/amont-gate";
50
51/// The marker's filename inside `$GIT_DIR`.
52const MARKER: &str = "amont-gate";
53
54/// `$GIT_DIR/amont-gate` — the worktree-PRIVATE gitdir, deliberately: the
55/// commit this marker waits for happens in this worktree. The stamps the
56/// marker becomes live in the common dir (a notes ref) and are shared.
57fn marker_path() -> Option<PathBuf> {
58    let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
59    Some(std::path::Path::new(&dir).join(MARKER))
60}
61
62/// pre-commit: record that `scripts` ran clean against the tree the commit
63/// will carry.
64///
65/// Called on EVERY pre-commit verdict, with an empty list when nothing
66/// qualifying ran (or the commit is about to be blocked) — an aborted or
67/// unchecked attempt must not inherit a previous attempt's marker.
68///
69/// Best-effort throughout: a failure to record costs one redundant gate run
70/// at push time, which is the safe direction, and a pre-commit that failed a
71/// COMMIT over bookkeeping would be the tail wagging the dog.
72pub fn record(scripts: &[&str]) {
73    let Some(path) = marker_path() else { return };
74    if scripts.is_empty() {
75        let _ = std::fs::remove_file(&path);
76        return;
77    }
78    // The index, as the object id `git commit` is about to seal. Inherits
79    // `GIT_INDEX_FILE`, so `git commit -a`'s temporary index answers here
80    // too. Pure read of the index: writes objects, touches no ref.
81    let Some(tree) = crate::git::stdout(&["write-tree"]) else {
82        let _ = std::fs::remove_file(&path);
83        return;
84    };
85    let mut body = format!("{FORMAT}\n{tree}\n");
86    for s in scripts {
87        body.push_str(s);
88        body.push('\n');
89    }
90    let _ = std::fs::write(&path, body);
91}
92
93/// post-commit: consume the marker; stamp HEAD when the tree still matches.
94///
95/// One-shot by construction — the marker is deleted before anything is
96/// judged, so no path through here can leave it to vouch for a later commit.
97///
98/// Returns the scripts it actually stamped (empty on every no-stamp path,
99/// including a note git refused). The caller subtracts this from what the
100/// manifest declares to learn what the commit dodged — [`crate::bypass`]
101/// keeps that count. Two records, two questions: the stamp gates a check,
102/// the ledger only counts.
103pub fn bind_to_head() -> Vec<String> {
104    let Some(path) = marker_path() else {
105        return Vec::new();
106    };
107    let Ok(body) = std::fs::read_to_string(&path) else {
108        return Vec::new(); // no marker: nothing ran at pre-commit, nothing to stamp
109    };
110    let _ = std::fs::remove_file(&path);
111    let mut lines = body.lines();
112    if lines.next() != Some(FORMAT) {
113        return Vec::new();
114    }
115    let Some(tree) = lines.next() else {
116        return Vec::new();
117    };
118    let scripts: Vec<&str> = lines.filter(|l| !l.trim().is_empty()).collect();
119    if scripts.is_empty() {
120        return Vec::new();
121    }
122    let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
123        return Vec::new();
124    };
125    // A different tree means this commit is not the one pre-commit judged —
126    // the marker is a dead letter from an aborted attempt.
127    if head_tree != tree {
128        return Vec::new();
129    }
130    let note = format!("{FORMAT} {}", scripts.join(" "));
131    if !crate::git::succeeds(&[
132        "notes", "--ref", NOTES_REF, "add", "-f", "-m", &note, "HEAD",
133    ]) {
134        return Vec::new(); // a note git refused is not a stamp
135    }
136    scripts.iter().map(|s| s.to_string()).collect()
137}
138
139/// pre-push: which of `commits` carry a stamp, and for which scripts.
140///
141/// One `notes list` narrows the reads to commits that have a note at all;
142/// absent ref, unparseable note, wrong format version — all read as "no
143/// stamp", which re-runs the gate.
144pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
145    let mut out = HashMap::new();
146    if commits.is_empty() {
147        return out;
148    }
149    let Some(list) = crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]) else {
150        return out; // no ref yet: nothing is stamped
151    };
152    let noted: HashSet<&str> = list
153        .lines()
154        .filter_map(|l| l.split_whitespace().nth(1))
155        .collect();
156    for commit in commits {
157        if !noted.contains(commit.as_str()) {
158            continue;
159        }
160        let Some(body) = crate::git::stdout(&["notes", "--ref", NOTES_REF, "show", commit]) else {
161            continue;
162        };
163        let Some(first) = body.lines().next() else {
164            continue;
165        };
166        let mut tokens = first.split_whitespace();
167        if tokens.next() != Some(FORMAT) {
168            continue;
169        }
170        out.insert(commit.clone(), tokens.map(str::to_string).collect());
171    }
172    out
173}
174
175/// uninstall: forget everything this module ever wrote here.
176///
177/// The stamps are OUR bookkeeping — unlike `hook.skip` and `amont.severity`,
178/// which are the user's statements and are never touched.
179pub fn forget() {
180    if let Some(path) = marker_path() {
181        let _ = std::fs::remove_file(&path);
182    }
183    let _ = crate::git::succeeds(&["update-ref", "-d", NOTES_FULL_REF]);
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189    use std::path::Path;
190
191    /// A real repository, because every function here is a conversation with
192    /// git — hand-rolled fixtures would test the conversation we imagined.
193    fn repo(name: &str) -> PathBuf {
194        let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
195        let _ = std::fs::remove_dir_all(&dir);
196        std::fs::create_dir_all(&dir).unwrap();
197        git(&dir, &["init", "-q", "--template=", "."]);
198        git(&dir, &["config", "user.email", "t@t.test"]);
199        git(&dir, &["config", "user.name", "t"]);
200        dir
201    }
202
203    fn git(dir: &Path, args: &[&str]) -> String {
204        let out = std::process::Command::new("git")
205            .arg("-C")
206            .arg(dir)
207            .args(args)
208            .output()
209            .expect("git");
210        String::from_utf8_lossy(&out.stdout).trim().to_string()
211    }
212
213    /// The module talks to the repo at the process cwd; these tests each set
214    /// it. Serialised because cwd is process-global.
215    static CWD: std::sync::Mutex<()> = std::sync::Mutex::new(());
216
217    fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
218        let _guard = CWD.lock().unwrap_or_else(|p| p.into_inner());
219        let prev = std::env::current_dir().unwrap();
220        std::env::set_current_dir(dir).unwrap();
221        let r = f();
222        std::env::set_current_dir(prev).unwrap();
223        r
224    }
225
226    #[test]
227    fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
228        let dir = repo("roundtrip");
229        std::fs::write(dir.join("a.ts"), "x").unwrap();
230        git(&dir, &["add", "a.ts"]);
231        in_repo(&dir, || {
232            record(&["typecheck", "test"]);
233            git(&dir, &["commit", "-qm", "chore: a"]);
234            let stamped = bind_to_head();
235            assert_eq!(
236                stamped,
237                vec!["typecheck".to_string(), "test".to_string()],
238                "bind_to_head reports the scripts it stamped"
239            );
240            let head = git(&dir, &["rev-parse", "HEAD"]);
241            let stamps = stamps_for(std::slice::from_ref(&head));
242            assert_eq!(
243                stamps.get(&head).map(Vec::as_slice),
244                Some(&["typecheck".to_string(), "test".to_string()][..])
245            );
246            // One-shot: the marker is gone.
247            // One-shot: the marker is gone. The fixture's own path, not
248            // `marker_path()` — that helper spawns git, and a transient
249            // spawn failure on a loaded runner reads as `None` here while
250            // production code correctly treats it as "no marker". Seen once,
251            // on Windows, as an unwrap panic in a sibling test.
252            assert!(!dir.join(".git").join(MARKER).exists());
253        });
254        let _ = std::fs::remove_dir_all(&dir);
255    }
256
257    #[test]
258    fn a_marker_for_a_different_tree_stamps_nothing() {
259        let dir = repo("stale");
260        std::fs::write(dir.join("a.ts"), "x").unwrap();
261        git(&dir, &["add", "a.ts"]);
262        in_repo(&dir, || {
263            record(&["typecheck"]);
264            // The commit that actually lands carries DIFFERENT content — the
265            // aborted-attempt-then-different-retry shape.
266            std::fs::write(dir.join("a.ts"), "y").unwrap();
267            git(&dir, &["add", "a.ts"]);
268            git(&dir, &["commit", "-qm", "chore: different"]);
269            assert!(
270                bind_to_head().is_empty(),
271                "bind_to_head reports nothing when the tree moved"
272            );
273            let head = git(&dir, &["rev-parse", "HEAD"]);
274            assert!(
275                stamps_for(&[head]).is_empty(),
276                "a stale marker must not vouch"
277            );
278            assert!(
279                !dir.join(".git").join(MARKER).exists(),
280                "consumed either way"
281            );
282        });
283        let _ = std::fs::remove_dir_all(&dir);
284    }
285
286    #[test]
287    fn an_empty_record_clears_a_previous_marker() {
288        let dir = repo("clears");
289        std::fs::write(dir.join("a.ts"), "x").unwrap();
290        git(&dir, &["add", "a.ts"]);
291        in_repo(&dir, || {
292            record(&["typecheck"]);
293            assert!(dir.join(".git").join(MARKER).exists());
294            record(&[]);
295            assert!(!dir.join(".git").join(MARKER).exists());
296        });
297        let _ = std::fs::remove_dir_all(&dir);
298    }
299
300    /// The version guard's REJECT branch, fed a hand-written marker: an old
301    /// (or future) format is ignored rather than misread — the doc's claim,
302    /// now pinned. Every other test's markers come from record() itself and
303    /// so always carry the current FORMAT.
304    #[test]
305    fn a_marker_in_an_unknown_format_stamps_nothing() {
306        let dir = repo("wrongformat");
307        std::fs::write(dir.join("a.ts"), "x").unwrap();
308        git(&dir, &["add", "a.ts"]);
309        in_repo(&dir, || {
310            let tree = git(&dir, &["write-tree"]);
311            let marker = dir.join(".git").join(MARKER);
312            std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
313            git(&dir, &["commit", "-qm", "chore: a"]);
314            bind_to_head();
315            let head = git(&dir, &["rev-parse", "HEAD"]);
316            assert!(
317                stamps_for(std::slice::from_ref(&head)).is_empty(),
318                "an unknown format was trusted"
319            );
320            assert!(!marker.exists(), "consumed either way");
321        });
322        let _ = std::fs::remove_dir_all(&dir);
323    }
324
325    /// A note somebody else wrote into OUR ref is not a stamp. Absent this,
326    /// `git notes --ref=amont-gate add` would be a one-line way to vouch for
327    /// an unchecked commit — the parsing trust boundary of the whole chain.
328    #[test]
329    fn a_foreign_note_is_not_a_stamp() {
330        let dir = repo("foreignnote");
331        std::fs::write(dir.join("a.ts"), "x").unwrap();
332        git(&dir, &["add", "a.ts"]);
333        in_repo(&dir, || {
334            git(&dir, &["commit", "-qm", "chore: a"]);
335            git(
336                &dir,
337                &[
338                    "notes",
339                    "--ref",
340                    NOTES_REF,
341                    "add",
342                    "-m",
343                    "typecheck test",
344                    "HEAD",
345                ],
346            );
347            let head = git(&dir, &["rev-parse", "HEAD"]);
348            assert!(
349                stamps_for(std::slice::from_ref(&head)).is_empty(),
350                "a note without the format token was trusted"
351            );
352        });
353        let _ = std::fs::remove_dir_all(&dir);
354    }
355
356    #[test]
357    fn forget_removes_the_stamps() {
358        let dir = repo("forget");
359        std::fs::write(dir.join("a.ts"), "x").unwrap();
360        git(&dir, &["add", "a.ts"]);
361        in_repo(&dir, || {
362            record(&["typecheck"]);
363            git(&dir, &["commit", "-qm", "chore: a"]);
364            bind_to_head();
365            let head = git(&dir, &["rev-parse", "HEAD"]);
366            assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
367            forget();
368            assert!(stamps_for(&[head]).is_empty());
369        });
370        let _ = std::fs::remove_dir_all(&dir);
371    }
372}