Skip to main content

greengate_runtime/
run_stamp.rs

1//! `amont run --stamp` and `amont stamps` (ADR-0015): a runner other than the
2//! commit hook earns amont's verdict for a tree, and anyone can ask which
3//! gates a tree carries a verdict for.
4//!
5//! The commit hook stamps the tree it is about to seal and the push hook the
6//! tips it pushes. A tool that verifies a tree of its own (relais, in a clean
7//! candidate worktree) had no way to leave the same record, so the person's
8//! later commit and push of that exact tree ran the suite again. `run --stamp`
9//! runs the named gates on HEAD of a clean worktree and writes the same tokens
10//! the hooks write, through the same writers:
11//!
12//! - a commit-time declaration that blocks is stamped on the TREE note, under
13//!   its script name ([`crate::gate_stamp::stamp_tree`]), which is what the
14//!   pre-commit hook ([`crate::gate_stamp::vouched_for_staged_tree`]) and the
15//!   push twin's pairing read. Not the one-shot marker: that lives in the
16//!   worktree-private gitdir and dies with a throwaway worktree;
17//! - a push gate is stamped on the tree and the commit
18//!   ([`crate::gate_stamp::stamp_push`]), as a rehearsal does;
19//! - a built-in pre-commit check gets its built-in token on the tree note. The
20//!   commit hook reruns built-ins whatever the note says (they read the index);
21//!   the token is evidence for `amont stamps` and the tools that read it.
22//!
23//! Nothing here signs. Signing stays at push time, with the key the pre-push
24//! hook already uses, over the stamps it finds (decisions programme "one
25//! verdict per tree", t02).
26//!
27//! Every failure points the usual way: a gate that did not pass, was deferred,
28//! could not run or had nothing to judge writes no token, and no token means
29//! the hooks run it.
30
31use crate::check::{Check, Outcome, Severity, Stage};
32use crate::manifest::Manifest;
33use crate::names::BIN;
34use crate::pushrefs::PushRefs;
35use crate::registry::Ctx;
36use crate::ui::{highlight, valid_sign, warning_sign};
37
38/// Exit codes of `amont run --stamp`.
39pub const EXIT_STAMPED: i32 = 0;
40pub const EXIT_FAILED: i32 = 1;
41pub const EXIT_REFUSED: i32 = 2;
42/// A gate was deferred, could not run, or had nothing to judge: no token was
43/// written for it, and nothing failed.
44pub const EXIT_UNSTAMPED: i32 = 4;
45
46/// What became of one gate in a `run --stamp`.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum Ended {
49    Stamped,
50    /// A push gate whose commit-time twin passed in this run: its pairing at
51    /// push time reads the twin's tree token, so it is not run twice.
52    CoveredBy(String),
53    Failed,
54    /// Deferred by the busy policy (ADR-0013): never a token.
55    Deferred,
56    /// Could not run, warned, repaired files, not opted in, or judged nothing.
57    NotStamped(&'static str),
58}
59
60/// How `amont stamps` prints its answer.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum Output {
63    Json,
64    Text,
65}
66
67/// One gate's state on a tree, as `amont stamps` reports it.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum State {
70    Stamped,
71    Attested,
72    Deferred,
73    Absent,
74}
75
76impl State {
77    pub fn as_str(self) -> &'static str {
78        match self {
79            State::Stamped => "stamped",
80            State::Attested => "attested",
81            State::Deferred => "deferred",
82            State::Absent => "absent",
83        }
84    }
85}
86
87/// Resolve `names` to check ids. A short name that reaches more than one
88/// check (`cargo-test`: the commit-time declaration and the push built-in)
89/// selects all of them: the push one is then covered by its twin, not run
90/// twice. Empty `names`: the default set.
91fn resolve(
92    settings: &crate::config::Settings,
93    manifest: &Manifest,
94    names: &[String],
95) -> Result<Vec<String>, String> {
96    if names.is_empty() {
97        return Ok(default_gates(settings, manifest));
98    }
99    let mut out: Vec<String> = Vec::new();
100    for n in names {
101        let ids = match crate::dispatch::resolve_check_name(n, manifest) {
102            crate::dispatch::Named2::Resolved(id) => vec![id],
103            crate::dispatch::Named2::Ambiguous(ids) => ids,
104            crate::dispatch::Named2::Unknown => {
105                return Err(format!("unknown gate {n:?} — try `{BIN} list`"))
106            }
107        };
108        for id in ids {
109            if crate::registry::one_named(&id, manifest).is_none() {
110                return Err(format!("{n:?} is not a check `--stamp` can run"));
111            }
112            if !out.contains(&id) {
113                out.push(id);
114            }
115        }
116    }
117    Ok(out)
118}
119
120/// Every gate the hooks honour a stamp for: the blocking commit-time
121/// declarations, and the scoped push gates this repository opted into.
122/// `hook.skip` removes a gate here as it does from a stage.
123pub fn default_gates(settings: &crate::config::Settings, manifest: &Manifest) -> Vec<String> {
124    let skips = crate::configured_skips(settings);
125    let skipped = |id: &str| skips.iter().any(|s| crate::skip_suppresses(id, s));
126    let tracked = crate::tracked_paths();
127    let mut out: Vec<String> =
128        crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
129            .into_iter()
130            .map(|d| d.id)
131            .filter(|id| !skipped(id))
132            .collect();
133    for c in crate::registry::all_stage_checks(Stage::PrePush, manifest) {
134        let scope = c.scope();
135        if crate::dispatch::stamped_push_gate(c) && scope.opted_in(&tracked) && !skipped(c.name()) {
136            let id = c.name().to_string();
137            if !out.contains(&id) {
138                out.push(id);
139            }
140        }
141    }
142    out
143}
144
145/// The token a gate's verdict is stamped under, and whether it is a
146/// commit-time one (tree note) or a push one (tree and commit).
147fn token_for(
148    settings: &crate::config::Settings,
149    manifest: &Manifest,
150    check: &dyn Check,
151) -> Option<String> {
152    if check.stage() == Stage::PreCommit {
153        if let Some(d) =
154            crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
155                .into_iter()
156                .find(|d| d.id == check.name())
157        {
158            return manifest
159                .externals
160                .iter()
161                .find(|e| e.id == d.id)
162                .and_then(|e| crate::gate_identity::external_token(e, &d.script));
163        }
164    }
165    crate::gate_identity::token(&manifest.externals, check.name())
166}
167
168/// The commit-time declaration a push gate pairs with, if any.
169fn twin_of(
170    settings: &crate::config::Settings,
171    manifest: &Manifest,
172    check: &dyn Check,
173) -> Option<String> {
174    if check.stage() != Stage::PrePush {
175        return None;
176    }
177    let short = check.pairing_name();
178    crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
179        .into_iter()
180        .find(|d| d.script == short)
181        .map(|d| d.id)
182}
183
184/// Run one check by itself, keeping its outcome (a deferral wins, as in a
185/// stage).
186fn run_one(ctx: &Ctx, check: &dyn Check) -> Outcome {
187    let slot = crate::host_slots::enter_check(check.name(), check.weight());
188    let outcome = check.run(ctx);
189    if slot.deferred().is_some() {
190        Outcome::Deferred
191    } else {
192        outcome
193    }
194}
195
196/// `amont run --stamp [<gate>…]`.
197pub fn stamp(settings: &crate::config::Settings, manifest: &Manifest, names: &[String]) -> i32 {
198    // Captured before anything runs: what the gates are handed is what the
199    // stamp vouches for. Tracked changes only, as `stamp_tips` argues; the
200    // untracked artefacts a gate leaves behind do not count.
201    let dirty = crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"]);
202    match dirty.as_deref() {
203        None => {
204            eprintln!("{BIN}: git would not say whether the worktree is clean — nothing stamped");
205            return EXIT_REFUSED;
206        }
207        Some(s) if !s.trim().is_empty() => {
208            eprintln!(
209                "{BIN}: run --stamp needs a clean worktree: tracked files differ from HEAD, so \
210                 the gates would judge content no tree holds — commit or stash them first"
211            );
212            return EXIT_REFUSED;
213        }
214        Some(_) => {}
215    }
216    let (Some(head), Some(tree)) = (
217        crate::git::stdout(&["rev-parse", "HEAD"]),
218        crate::git::stdout(&["rev-parse", "HEAD^{tree}"]),
219    ) else {
220        eprintln!("{BIN}: run --stamp needs a commit at HEAD to stamp");
221        return EXIT_REFUSED;
222    };
223    let ids = match resolve(settings, manifest, names) {
224        Ok(ids) => ids,
225        Err(e) => {
226            eprintln!("{BIN}: {e}");
227            return EXIT_REFUSED;
228        }
229    };
230    if ids.is_empty() {
231        println!("{} no gate to stamp here", warning_sign());
232        return EXIT_STAMPED;
233    }
234    let checks: Vec<&dyn Check> = ids
235        .iter()
236        .filter_map(|id| crate::registry::one_named(id, manifest))
237        .collect();
238    let tracked = crate::tracked_paths();
239    // Commit-time gates judge the whole tree, not an index nobody staged.
240    if checks.iter().any(|c| c.stage() == Stage::PreCommit) {
241        crate::dispatch::enter_all_files_mode();
242    }
243    let hooks_dir = std::path::PathBuf::from(".git/hooks");
244    let empty = PushRefs::preloaded(Vec::new());
245    let audits = crate::hooks::audit::Ledger::default();
246    // A push gate judges a push; standalone there is none, so the one ref a
247    // rehearsal would push is synthesised, as `amont run pre-push` does —
248    // only when a push gate actually has to run (one covered by its twin
249    // needs no ref, and a repository with no remote then says nothing).
250    let push: std::cell::OnceCell<Option<(PushRefs, Vec<String>)>> = std::cell::OnceCell::new();
251    let push_for = || {
252        push.get_or_init(|| match crate::pushrefs::synthetic_from_upstream() {
253            Ok(r) => {
254                let refs = PushRefs::preloaded(vec![r]);
255                let changed = crate::pushrefs::changed_files(refs.get());
256                Some((refs, changed))
257            }
258            Err(e) => {
259                eprintln!("{BIN}: push gates cannot run here: {e}");
260                None
261            }
262        })
263        .as_ref()
264    };
265    let mut ended: Vec<(String, Ended)> = Vec::new();
266    // Commit-time first, so a push gate can be covered by its twin.
267    let mut ordered = checks.clone();
268    ordered.sort_by_key(|c| u8::from(c.stage() != Stage::PreCommit));
269    for check in ordered {
270        let name = check.name().to_string();
271        let scope = check.scope();
272        if !scope.opted_in(&tracked) {
273            ended.push((name, Ended::NotStamped("not opted in here")));
274            continue;
275        }
276        let end = match check.stage() {
277            Stage::PreCommit => {
278                if !scope.is_unscoped() && !scope.touches(&tracked) {
279                    Ended::NotStamped("no tracked file in its scope")
280                } else {
281                    let ctx = Ctx {
282                        name: check.name(),
283                        args: &[],
284                        hooks_dir: &hooks_dir,
285                        push: &empty,
286                        manifest,
287                        settings,
288                        handed_to_cluster: &[],
289                        land: &crate::rehearsal::LandEnv::Absent,
290                        audits: &audits,
291                        source_worktree: None,
292                    };
293                    finish(
294                        settings,
295                        manifest,
296                        check,
297                        &tree,
298                        run_one(&ctx, check),
299                        |tok| crate::gate_stamp::stamp_tree(&tree, &[tok]),
300                    )
301                }
302            }
303            Stage::PrePush => {
304                let twin = twin_of(settings, manifest, check);
305                if let Some(t) =
306                    twin.filter(|t| ended.iter().any(|(n, e)| n == t && *e == Ended::Stamped))
307                {
308                    Ended::CoveredBy(t)
309                } else {
310                    match push_for() {
311                        None => Ended::NotStamped("no push ref to judge"),
312                        Some((_, changed)) if !scope.is_unscoped() && !scope.touches(changed) => {
313                            Ended::NotStamped("nothing it judges changed since the base")
314                        }
315                        Some((refs, _)) => {
316                            let ctx = Ctx {
317                                name: check.name(),
318                                args: &[],
319                                hooks_dir: &hooks_dir,
320                                push: refs,
321                                manifest,
322                                settings,
323                                handed_to_cluster: &[],
324                                land: &crate::rehearsal::LandEnv::Absent,
325                                audits: &audits,
326                                source_worktree: None,
327                            };
328                            finish(
329                                settings,
330                                manifest,
331                                check,
332                                &tree,
333                                run_one(&ctx, check),
334                                |tok| crate::gate_stamp::stamp_push(&head, &tree, &[tok]),
335                            )
336                        }
337                    }
338                }
339            }
340        };
341        ended.push((name, end));
342    }
343    report(&tree, &ended)
344}
345
346/// Turn one outcome into what is recorded, writing the token on a pass.
347fn finish(
348    settings: &crate::config::Settings,
349    manifest: &Manifest,
350    check: &dyn Check,
351    tree: &str,
352    outcome: Outcome,
353    write: impl FnOnce(String) -> bool,
354) -> Ended {
355    match outcome {
356        // The cluster recorded it in its own ref (ADR-0016); a local token
357        // here would claim a run this machine never made.
358        Outcome::Passed if crate::cluster::proved(check.name(), tree) => Ended::Stamped,
359        Outcome::Passed => match token_for(settings, manifest, check) {
360            Some(tok) => {
361                if write(tok) {
362                    Ended::Stamped
363                } else {
364                    Ended::NotStamped("git refused the note")
365                }
366            }
367            None => Ended::NotStamped("its identity cannot be worked out"),
368        },
369        Outcome::Failed => match crate::registry::severity_of(settings, check) {
370            Severity::Block => Ended::Failed,
371            Severity::Warn => Ended::NotStamped("failed, set to warn"),
372        },
373        Outcome::Deferred => Ended::Deferred,
374        Outcome::Fixed => Ended::NotStamped("repaired files"),
375        Outcome::Warned => Ended::NotStamped("warned"),
376        Outcome::Unavailable => Ended::NotStamped("could not run"),
377        Outcome::Inert => Ended::NotStamped("judged nothing"),
378        Outcome::Skipped => Ended::NotStamped("skipped, an earlier gate failed"),
379    }
380}
381
382fn report(tree: &str, ended: &[(String, Ended)]) -> i32 {
383    let short = tree.get(..12).unwrap_or(tree);
384    let mut code = EXIT_STAMPED;
385    for (name, end) in ended {
386        match end {
387            Ended::Stamped => println!(
388                "{} stamped {} on tree {short}",
389                valid_sign(),
390                highlight(name)
391            ),
392            Ended::CoveredBy(t) => println!(
393                "{} {} covered by its commit-time twin {}",
394                valid_sign(),
395                highlight(name),
396                highlight(t)
397            ),
398            Ended::Failed => {
399                println!(
400                    "{} {} failed — not stamped",
401                    warning_sign(),
402                    highlight(name)
403                );
404                code = EXIT_FAILED;
405            }
406            Ended::Deferred => {
407                println!(
408                    "{} {} deferred, no host slot freed — not stamped",
409                    warning_sign(),
410                    highlight(name)
411                );
412                if code == EXIT_STAMPED {
413                    code = EXIT_UNSTAMPED;
414                }
415            }
416            Ended::NotStamped(why) => {
417                println!("{} {} not stamped: {why}", warning_sign(), highlight(name));
418                if code == EXIT_STAMPED {
419                    code = EXIT_UNSTAMPED;
420                }
421            }
422        }
423    }
424    code
425}
426
427/// The ids that carry a gate's verdict: itself, and its twin at the other
428/// stage. A commit-time declaration and the push gate it pairs with run the
429/// same command on the same tree, so a token or a signed attestation for
430/// either is the verdict of both (the push hook skips on the first, CI on
431/// the second).
432fn verdict_ids(
433    settings: &crate::config::Settings,
434    manifest: &Manifest,
435    check: &dyn Check,
436) -> Vec<String> {
437    let mut ids = vec![check.name().to_string()];
438    match check.stage() {
439        Stage::PrePush => ids.extend(twin_of(settings, manifest, check)),
440        Stage::PreCommit => {
441            let declared =
442                crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
443                    .into_iter()
444                    .any(|d| d.id == check.name());
445            if declared {
446                ids.extend(
447                    crate::registry::all_stage_checks(Stage::PrePush, manifest)
448                        .into_iter()
449                        .filter(|c| c.pairing_name() == check.pairing_name())
450                        .map(|c| c.name().to_string()),
451                );
452            }
453        }
454    }
455    ids
456}
457
458/// A detached checkout of a commit with no files, removed on drop: the
459/// verifier judges the tree checked out where it is pointed.
460struct Detached {
461    dir: std::path::PathBuf,
462}
463
464impl Detached {
465    fn at(commit: &str) -> Option<Detached> {
466        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
467        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
468        let dir = std::env::temp_dir().join(format!("greengate-stamps-{}-{n}", std::process::id()));
469        let path = dir.to_str()?;
470        crate::git::succeeds(&[
471            "worktree",
472            "add",
473            "--detach",
474            "--no-checkout",
475            "-q",
476            path,
477            commit,
478        ])
479        .then_some(Detached { dir })
480    }
481}
482
483impl Drop for Detached {
484    fn drop(&mut self) {
485        if let Some(path) = self.dir.to_str() {
486            let remove = ["worktree", "remove", "--force", path];
487            let _ = crate::git::succeeds(&remove); // best-effort: scratch, swept below
488        }
489        let _ = std::fs::remove_dir_all(&self.dir); // best-effort: scratch left by a failed remove
490    }
491}
492
493/// A commit holding `tree`, for a caller that was given a bare tree id. Fixed
494/// identity and date, so the same tree is the same commit; nothing refers to
495/// it and gc takes it.
496fn commit_of_tree(tree: &str) -> Option<String> {
497    let out = std::process::Command::new("git")
498        .args(["commit-tree", tree, "-m", "amont stamps"])
499        .env("GIT_AUTHOR_NAME", "amont")
500        .env("GIT_AUTHOR_EMAIL", "amont@localhost")
501        .env("GIT_COMMITTER_NAME", "amont")
502        .env("GIT_COMMITTER_EMAIL", "amont@localhost")
503        .env("GIT_AUTHOR_DATE", "@0 +0000")
504        .env("GIT_COMMITTER_DATE", "@0 +0000")
505        .output()
506        .ok()?;
507    out.status
508        .success()
509        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
510        .filter(|c| !c.is_empty())
511}
512
513/// The gate ids a signed attestation covers for `tree` on this platform.
514///
515/// The verifier syncs the notes from origin before it judges (up to 15 s, 45
516/// if origin is dead), so [`states`] asks only when some gate is not already
517/// stamped. For a tree other than the one checked out, a throwaway checkout of
518/// `commit` (or of a commit made for the tree) is what it is pointed at.
519///
520/// `anywhere` are the trusted `platform=any` gate ids: a linux block the
521/// cluster's pass earned covers them on this platform too.
522fn attested_for(tree: &str, commit: Option<&str>, anywhere: &[String]) -> Vec<String> {
523    let Some(signers) = crate::attest::default_signers() else {
524        return Vec::new();
525    };
526    let platform = crate::attest::platform();
527    let checked_out = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
528    let gates = if checked_out.as_deref() == Some(tree) {
529        crate::attest::covered(&signers, None, Some(&platform), anywhere)
530    } else {
531        let Some(commit) = commit.map(str::to_string).or_else(|| commit_of_tree(tree)) else {
532            return Vec::new();
533        };
534        let Some(checkout) = Detached::at(&commit) else {
535            return Vec::new();
536        };
537        crate::attest::covered_in(&checkout.dir, &signers, None, Some(&platform), anywhere)
538    };
539    gates
540        .map(|g| g.split_whitespace().map(str::to_string).collect())
541        .unwrap_or_default()
542}
543
544/// Each gate's state on `tree`: a valid local token (its own or its twin's),
545/// else a signed attestation for it on this platform, else a recorded
546/// deferral, else nothing. `commit` is the commit `tree` was asked for by, if
547/// it was asked for by one.
548pub fn states(
549    settings: &crate::config::Settings,
550    manifest: &Manifest,
551    tree: &str,
552    commit: Option<&str>,
553    ids: &[String],
554) -> Vec<(String, State)> {
555    let tokens = crate::gate_stamp::tree_tokens(tree);
556    let deferred = crate::gate_stamp::deferred_on(tree);
557    let attested: std::cell::OnceCell<Vec<String>> = std::cell::OnceCell::new();
558    let anywhere = crate::cluster::platform_any_ids(manifest);
559    ids.iter()
560        .filter_map(|id| crate::registry::one_named(id, manifest).map(|c| (id, c)))
561        .map(|(id, check)| {
562            let verdict = verdict_ids(settings, manifest, check);
563            let stamped = verdict
564                .iter()
565                .filter_map(|v| crate::registry::one_named(v, manifest))
566                .filter_map(|c| token_for(settings, manifest, c))
567                .any(|t| tokens.contains(&t))
568                || crate::cluster::stamped_on_tree(settings, &manifest.externals, &verdict, tree);
569            let state = if stamped {
570                State::Stamped
571            } else if attested
572                .get_or_init(|| attested_for(tree, commit, &anywhere))
573                .iter()
574                .any(|g| verdict.contains(g))
575            {
576                State::Attested
577            } else if deferred
578                .iter()
579                .any(|d| *d == crate::short_name(id) || *d == check.pairing_name())
580            {
581                State::Deferred
582            } else {
583                State::Absent
584            };
585            (id.clone(), state)
586        })
587        .collect()
588}
589
590/// `amont stamps [--json] [--tree <rev>] [<gate>…]`. Exit 0 with an answer,
591/// 2 on usage (an unknown gate, a rev that names no tree).
592pub fn stamps_command(
593    settings: &crate::config::Settings,
594    manifest: &Manifest,
595    output: Output,
596    tree: Option<&str>,
597    names: &[String],
598) -> i32 {
599    // A detached rehearsal's passes are tokens before the question is asked
600    // (ADR-0017).
601    crate::cluster::collect_if_declared(manifest);
602    let rev = tree.unwrap_or("HEAD");
603    let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{rev}^{{tree}}")]) else {
604        eprintln!("{BIN}: {rev:?} names no tree here");
605        return EXIT_REFUSED;
606    };
607    // The commit the tree was asked for by, when it was asked for by one.
608    let commit = crate::git::stdout(&[
609        "rev-parse",
610        "--verify",
611        "--quiet",
612        &format!("{rev}^{{commit}}"),
613    ]);
614    let ids = match resolve(settings, manifest, names) {
615        Ok(ids) => ids,
616        Err(e) => {
617            eprintln!("{BIN}: {e}");
618            return EXIT_REFUSED;
619        }
620    };
621    let states = states(settings, manifest, &tree, commit.as_deref(), &ids);
622    if output == Output::Json {
623        let gates: Vec<String> = states
624            .iter()
625            .map(|(id, s)| crate::json::string_field(id, s.as_str()))
626            .collect();
627        println!(
628            "{}",
629            crate::json::object(&[
630                crate::json::string_field("tree", &tree),
631                crate::json::string_field("platform", &crate::attest::platform()),
632                format!("\"gates\":{}", crate::json::object(&gates)),
633            ])
634        );
635    } else {
636        println!("tree {tree} ({})", crate::attest::platform());
637        for (id, s) in &states {
638            println!("  {:<9} {id}", s.as_str());
639        }
640    }
641    0
642}