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 via the crate-wide lock, because cwd is process-global
215    /// and `attest`'s tests move it too.
216    fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
217        let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
218        let prev = std::env::current_dir().unwrap();
219        std::env::set_current_dir(dir).unwrap();
220        let r = f();
221        std::env::set_current_dir(prev).unwrap();
222        r
223    }
224
225    #[test]
226    fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
227        let dir = repo("roundtrip");
228        std::fs::write(dir.join("a.ts"), "x").unwrap();
229        git(&dir, &["add", "a.ts"]);
230        in_repo(&dir, || {
231            record(&["typecheck", "test"]);
232            git(&dir, &["commit", "-qm", "chore: a"]);
233            let stamped = bind_to_head();
234            assert_eq!(
235                stamped,
236                vec!["typecheck".to_string(), "test".to_string()],
237                "bind_to_head reports the scripts it stamped"
238            );
239            let head = git(&dir, &["rev-parse", "HEAD"]);
240            let stamps = stamps_for(std::slice::from_ref(&head));
241            assert_eq!(
242                stamps.get(&head).map(Vec::as_slice),
243                Some(&["typecheck".to_string(), "test".to_string()][..])
244            );
245            // One-shot: the marker is gone.
246            // One-shot: the marker is gone. The fixture's own path, not
247            // `marker_path()` — that helper spawns git, and a transient
248            // spawn failure on a loaded runner reads as `None` here while
249            // production code correctly treats it as "no marker". Seen once,
250            // on Windows, as an unwrap panic in a sibling test.
251            assert!(!dir.join(".git").join(MARKER).exists());
252        });
253        let _ = std::fs::remove_dir_all(&dir);
254    }
255
256    #[test]
257    fn a_marker_for_a_different_tree_stamps_nothing() {
258        let dir = repo("stale");
259        std::fs::write(dir.join("a.ts"), "x").unwrap();
260        git(&dir, &["add", "a.ts"]);
261        in_repo(&dir, || {
262            record(&["typecheck"]);
263            // The commit that actually lands carries DIFFERENT content — the
264            // aborted-attempt-then-different-retry shape.
265            std::fs::write(dir.join("a.ts"), "y").unwrap();
266            git(&dir, &["add", "a.ts"]);
267            git(&dir, &["commit", "-qm", "chore: different"]);
268            assert!(
269                bind_to_head().is_empty(),
270                "bind_to_head reports nothing when the tree moved"
271            );
272            let head = git(&dir, &["rev-parse", "HEAD"]);
273            assert!(
274                stamps_for(&[head]).is_empty(),
275                "a stale marker must not vouch"
276            );
277            assert!(
278                !dir.join(".git").join(MARKER).exists(),
279                "consumed either way"
280            );
281        });
282        let _ = std::fs::remove_dir_all(&dir);
283    }
284
285    #[test]
286    fn an_empty_record_clears_a_previous_marker() {
287        let dir = repo("clears");
288        std::fs::write(dir.join("a.ts"), "x").unwrap();
289        git(&dir, &["add", "a.ts"]);
290        in_repo(&dir, || {
291            record(&["typecheck"]);
292            assert!(dir.join(".git").join(MARKER).exists());
293            record(&[]);
294            assert!(!dir.join(".git").join(MARKER).exists());
295        });
296        let _ = std::fs::remove_dir_all(&dir);
297    }
298
299    /// The version guard's REJECT branch, fed a hand-written marker: an old
300    /// (or future) format is ignored rather than misread — the doc's claim,
301    /// now pinned. Every other test's markers come from record() itself and
302    /// so always carry the current FORMAT.
303    #[test]
304    fn a_marker_in_an_unknown_format_stamps_nothing() {
305        let dir = repo("wrongformat");
306        std::fs::write(dir.join("a.ts"), "x").unwrap();
307        git(&dir, &["add", "a.ts"]);
308        in_repo(&dir, || {
309            let tree = git(&dir, &["write-tree"]);
310            let marker = dir.join(".git").join(MARKER);
311            std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
312            git(&dir, &["commit", "-qm", "chore: a"]);
313            bind_to_head();
314            let head = git(&dir, &["rev-parse", "HEAD"]);
315            assert!(
316                stamps_for(std::slice::from_ref(&head)).is_empty(),
317                "an unknown format was trusted"
318            );
319            assert!(!marker.exists(), "consumed either way");
320        });
321        let _ = std::fs::remove_dir_all(&dir);
322    }
323
324    /// A note somebody else wrote into OUR ref is not a stamp. Absent this,
325    /// `git notes --ref=amont-gate add` would be a one-line way to vouch for
326    /// an unchecked commit — the parsing trust boundary of the whole chain.
327    #[test]
328    fn a_foreign_note_is_not_a_stamp() {
329        let dir = repo("foreignnote");
330        std::fs::write(dir.join("a.ts"), "x").unwrap();
331        git(&dir, &["add", "a.ts"]);
332        in_repo(&dir, || {
333            git(&dir, &["commit", "-qm", "chore: a"]);
334            git(
335                &dir,
336                &[
337                    "notes",
338                    "--ref",
339                    NOTES_REF,
340                    "add",
341                    "-m",
342                    "typecheck test",
343                    "HEAD",
344                ],
345            );
346            let head = git(&dir, &["rev-parse", "HEAD"]);
347            assert!(
348                stamps_for(std::slice::from_ref(&head)).is_empty(),
349                "a note without the format token was trusted"
350            );
351        });
352        let _ = std::fs::remove_dir_all(&dir);
353    }
354
355    #[test]
356    fn forget_removes_the_stamps() {
357        let dir = repo("forget");
358        std::fs::write(dir.join("a.ts"), "x").unwrap();
359        git(&dir, &["add", "a.ts"]);
360        in_repo(&dir, || {
361            record(&["typecheck"]);
362            git(&dir, &["commit", "-qm", "chore: a"]);
363            bind_to_head();
364            let head = git(&dir, &["rev-parse", "HEAD"]);
365            assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
366            forget();
367            assert!(stamps_for(&[head]).is_empty());
368        });
369        let _ = std::fs::remove_dir_all(&dir);
370    }
371}