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 // Not "nothing ran": git could not name the tree, so nothing may be
83 // vouched for. Dropping the marker is the fail-safe half (the gate
84 // re-runs at push); saying so is the half that was missing.
85 crate::hooks::common::warn(
86 "git would not name the staged tree — this commit records no gate stamp",
87 );
88 let _ = std::fs::remove_file(&path);
89 return;
90 };
91 let mut body = format!("{FORMAT}\n{tree}\n");
92 for s in scripts {
93 body.push_str(s);
94 body.push('\n');
95 }
96 let _ = std::fs::write(&path, body);
97}
98
99/// post-commit: consume the marker; stamp HEAD when the tree still matches.
100///
101/// One-shot by construction — the marker is deleted before anything is
102/// judged, so no path through here can leave it to vouch for a later commit.
103///
104/// Returns the scripts it actually stamped (empty on every no-stamp path,
105/// including a note git refused). The caller subtracts this from what the
106/// manifest declares to learn what the commit dodged — [`crate::bypass`]
107/// keeps that count. Two records, two questions: the stamp gates a check,
108/// the ledger only counts.
109pub fn bind_to_head() -> Vec<String> {
110 let Some(path) = marker_path() else {
111 return Vec::new();
112 };
113 let Ok(body) = std::fs::read_to_string(&path) else {
114 return Vec::new(); // no marker: nothing ran at pre-commit, nothing to stamp
115 };
116 let _ = std::fs::remove_file(&path);
117 let mut lines = body.lines();
118 if lines.next() != Some(FORMAT) {
119 return Vec::new();
120 }
121 let Some(tree) = lines.next() else {
122 return Vec::new();
123 };
124 let scripts: Vec<&str> = lines.filter(|l| !l.trim().is_empty()).collect();
125 if scripts.is_empty() {
126 return Vec::new();
127 }
128 let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
129 crate::hooks::common::warn(
130 "git would not name this commit's tree — no gate stamp was written",
131 );
132 return Vec::new();
133 };
134 // A different tree means this commit is not the one pre-commit judged —
135 // the marker is a dead letter from an aborted attempt.
136 if head_tree != tree {
137 return Vec::new();
138 }
139 let note = format!("{FORMAT} {}", scripts.join(" "));
140 if !crate::git::succeeds(&[
141 "notes", "--ref", NOTES_REF, "add", "-f", "-m", ¬e, "HEAD",
142 ]) {
143 // A note git refused is not a stamp — and the push will re-run these
144 // checks, which is right but looks arbitrary unless it is said.
145 crate::hooks::common::warn(
146 "git refused to write the gate stamp — these checks will run again at push",
147 );
148 return Vec::new();
149 }
150 scripts.iter().map(|s| s.to_string()).collect()
151}
152
153/// pre-push: which of `commits` carry a stamp, and for which scripts.
154///
155/// One `notes list` narrows the reads to commits that have a note at all;
156/// absent ref, unparseable note, wrong format version — all read as "no
157/// stamp", which re-runs the gate.
158pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
159 let mut out = HashMap::new();
160 if commits.is_empty() {
161 return out;
162 }
163 let Some(list) = crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]) else {
164 // NOT the absent-ref case, whatever an older comment here claimed:
165 // `notes list` exits 0 with empty output when the ref does not exist,
166 // so that arrives as `Some("")` and falls through as "nothing is
167 // stamped" — correctly. Reaching HERE means git could not answer at
168 // all. Same verdict (the gates re-run: never skip work on a question
169 // we could not ask), different sentence, because a transient git
170 // failure that reads as "nothing is stamped" is indistinguishable
171 // from the real thing — which is exactly how one flaky spawn cost a
172 // day of not-diagnosing.
173 crate::hooks::common::warn(
174 "git would not list the gate stamps — every gated check will run again",
175 );
176 return out;
177 };
178 let noted: HashSet<&str> = list
179 .lines()
180 .filter_map(|l| l.split_whitespace().nth(1))
181 .collect();
182 for commit in commits {
183 if !noted.contains(commit.as_str()) {
184 continue;
185 }
186 let Some(body) = crate::git::stdout(&["notes", "--ref", NOTES_REF, "show", commit]) else {
187 continue;
188 };
189 let Some(first) = body.lines().next() else {
190 continue;
191 };
192 let mut tokens = first.split_whitespace();
193 if tokens.next() != Some(FORMAT) {
194 continue;
195 }
196 out.insert(commit.clone(), tokens.map(str::to_string).collect());
197 }
198 out
199}
200
201/// uninstall: forget everything this module ever wrote here.
202///
203/// The stamps are OUR bookkeeping — unlike `hook.skip` and `amont.severity`,
204/// which are the user's statements and are never touched.
205pub fn forget() -> bool {
206 let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
207 let notes = crate::git::succeeds(&["update-ref", "-d", NOTES_FULL_REF]);
208 marker || notes
209}
210
211/// The same, for a repository this process is not standing in.
212pub fn forget_in(repo: &std::path::Path) -> bool {
213 let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
214 .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
215 let notes = crate::git::succeeds_in(repo, &["update-ref", "-d", NOTES_FULL_REF]);
216 marker || notes
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use std::path::Path;
223
224 /// A real repository, because every function here is a conversation with
225 /// git — hand-rolled fixtures would test the conversation we imagined.
226 fn repo(name: &str) -> PathBuf {
227 let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
228 let _ = std::fs::remove_dir_all(&dir);
229 std::fs::create_dir_all(&dir).unwrap();
230 git(&dir, &["init", "-q", "--template=", "."]);
231 git(&dir, &["config", "user.email", "t@t.test"]);
232 git(&dir, &["config", "user.name", "t"]);
233 dir
234 }
235
236 fn git(dir: &Path, args: &[&str]) -> String {
237 let out = std::process::Command::new("git")
238 .arg("-C")
239 .arg(dir)
240 .args(args)
241 .output()
242 .expect("git");
243 String::from_utf8_lossy(&out.stdout).trim().to_string()
244 }
245
246 /// The module talks to the repo at the process cwd; these tests each set
247 /// it. Serialised via the crate-wide lock, because cwd is process-global
248 /// and `attest`'s tests move it too.
249 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
250 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
251 let prev = std::env::current_dir().unwrap();
252 std::env::set_current_dir(dir).unwrap();
253 let r = f();
254 std::env::set_current_dir(prev).unwrap();
255 r
256 }
257
258 #[test]
259 fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
260 let dir = repo("roundtrip");
261 std::fs::write(dir.join("a.ts"), "x").unwrap();
262 git(&dir, &["add", "a.ts"]);
263 in_repo(&dir, || {
264 record(&["typecheck", "test"]);
265 git(&dir, &["commit", "-qm", "chore: a"]);
266 let stamped = bind_to_head();
267 assert_eq!(
268 stamped,
269 vec!["typecheck".to_string(), "test".to_string()],
270 "bind_to_head reports the scripts it stamped"
271 );
272 let head = git(&dir, &["rev-parse", "HEAD"]);
273 let stamps = stamps_for(std::slice::from_ref(&head));
274 assert_eq!(
275 stamps.get(&head).map(Vec::as_slice),
276 Some(&["typecheck".to_string(), "test".to_string()][..])
277 );
278 // One-shot: the marker is gone.
279 // One-shot: the marker is gone. The fixture's own path, not
280 // `marker_path()` — that helper spawns git, and a transient
281 // spawn failure on a loaded runner reads as `None` here while
282 // production code correctly treats it as "no marker". Seen once,
283 // on Windows, as an unwrap panic in a sibling test.
284 assert!(!dir.join(".git").join(MARKER).exists());
285 });
286 let _ = std::fs::remove_dir_all(&dir);
287 }
288
289 #[test]
290 fn a_marker_for_a_different_tree_stamps_nothing() {
291 let dir = repo("stale");
292 std::fs::write(dir.join("a.ts"), "x").unwrap();
293 git(&dir, &["add", "a.ts"]);
294 in_repo(&dir, || {
295 record(&["typecheck"]);
296 // The commit that actually lands carries DIFFERENT content — the
297 // aborted-attempt-then-different-retry shape.
298 std::fs::write(dir.join("a.ts"), "y").unwrap();
299 git(&dir, &["add", "a.ts"]);
300 git(&dir, &["commit", "-qm", "chore: different"]);
301 assert!(
302 bind_to_head().is_empty(),
303 "bind_to_head reports nothing when the tree moved"
304 );
305 let head = git(&dir, &["rev-parse", "HEAD"]);
306 assert!(
307 stamps_for(&[head]).is_empty(),
308 "a stale marker must not vouch"
309 );
310 assert!(
311 !dir.join(".git").join(MARKER).exists(),
312 "consumed either way"
313 );
314 });
315 let _ = std::fs::remove_dir_all(&dir);
316 }
317
318 #[test]
319 fn an_empty_record_clears_a_previous_marker() {
320 let dir = repo("clears");
321 std::fs::write(dir.join("a.ts"), "x").unwrap();
322 git(&dir, &["add", "a.ts"]);
323 in_repo(&dir, || {
324 record(&["typecheck"]);
325 assert!(dir.join(".git").join(MARKER).exists());
326 record(&[]);
327 assert!(!dir.join(".git").join(MARKER).exists());
328 });
329 let _ = std::fs::remove_dir_all(&dir);
330 }
331
332 /// The version guard's REJECT branch, fed a hand-written marker: an old
333 /// (or future) format is ignored rather than misread — the doc's claim,
334 /// now pinned. Every other test's markers come from record() itself and
335 /// so always carry the current FORMAT.
336 #[test]
337 fn a_marker_in_an_unknown_format_stamps_nothing() {
338 let dir = repo("wrongformat");
339 std::fs::write(dir.join("a.ts"), "x").unwrap();
340 git(&dir, &["add", "a.ts"]);
341 in_repo(&dir, || {
342 let tree = git(&dir, &["write-tree"]);
343 let marker = dir.join(".git").join(MARKER);
344 std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
345 git(&dir, &["commit", "-qm", "chore: a"]);
346 bind_to_head();
347 let head = git(&dir, &["rev-parse", "HEAD"]);
348 assert!(
349 stamps_for(std::slice::from_ref(&head)).is_empty(),
350 "an unknown format was trusted"
351 );
352 assert!(!marker.exists(), "consumed either way");
353 });
354 let _ = std::fs::remove_dir_all(&dir);
355 }
356
357 /// A note somebody else wrote into OUR ref is not a stamp. Absent this,
358 /// `git notes --ref=amont-gate add` would be a one-line way to vouch for
359 /// an unchecked commit — the parsing trust boundary of the whole chain.
360 #[test]
361 fn a_foreign_note_is_not_a_stamp() {
362 let dir = repo("foreignnote");
363 std::fs::write(dir.join("a.ts"), "x").unwrap();
364 git(&dir, &["add", "a.ts"]);
365 in_repo(&dir, || {
366 git(&dir, &["commit", "-qm", "chore: a"]);
367 git(
368 &dir,
369 &[
370 "notes",
371 "--ref",
372 NOTES_REF,
373 "add",
374 "-m",
375 "typecheck test",
376 "HEAD",
377 ],
378 );
379 let head = git(&dir, &["rev-parse", "HEAD"]);
380 assert!(
381 stamps_for(std::slice::from_ref(&head)).is_empty(),
382 "a note without the format token was trusted"
383 );
384 });
385 let _ = std::fs::remove_dir_all(&dir);
386 }
387
388 /// An absent notes ref is `Some("")`, not `None` — the distinction the
389 /// warning on that branch depends on. If git ever starts failing here
390 /// instead, this test fails and the warning stops being a lie.
391 #[test]
392 fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
393 let dir = repo("no-stamps");
394 std::fs::write(dir.join("a.ts"), "x").unwrap();
395 git(&dir, &["add", "a.ts"]);
396 git(&dir, &["commit", "-qm", "chore: a"]);
397 in_repo(&dir, || {
398 assert_eq!(
399 crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
400 Some(""),
401 "an absent notes ref must be an ANSWER, not a failure — the \
402 no-stamps path and the git-is-broken path are told apart by it"
403 );
404 let head = git(&dir, &["rev-parse", "HEAD"]);
405 assert!(stamps_for(&[head]).is_empty());
406 });
407 let _ = std::fs::remove_dir_all(&dir);
408 }
409
410 #[test]
411 fn forget_removes_the_stamps() {
412 let dir = repo("forget");
413 std::fs::write(dir.join("a.ts"), "x").unwrap();
414 git(&dir, &["add", "a.ts"]);
415 in_repo(&dir, || {
416 record(&["typecheck"]);
417 git(&dir, &["commit", "-qm", "chore: a"]);
418 bind_to_head();
419 let head = git(&dir, &["rev-parse", "HEAD"]);
420 assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
421 forget();
422 assert!(stamps_for(&[head]).is_empty());
423 });
424 let _ = std::fs::remove_dir_all(&dir);
425 }
426}