Skip to main content

testing_conventions/
e2e.rs

1//! `e2e attest` / `e2e verify` (#17) — the e2e attestation nudge.
2//!
3//! `attest` runs the e2e suite locally and records that it ran against the
4//! current commit; `verify` (a later slice, #68) confirms in CI that the latest
5//! code commit is attested. The point is to *nudge* agents to run e2e locally —
6//! CI never runs e2e, it only checks the committed attestation.
7//!
8//! This module implements both `attest` (#67) and `verify` (#68).
9
10use std::path::{Path, PathBuf};
11use std::process::Command;
12use std::time::{SystemTime, UNIX_EPOCH};
13
14use anyhow::{bail, Context, Result};
15use serde::{Deserialize, Serialize};
16
17/// Where the committed attestation lives, relative to the repo root.
18pub const ATTESTATION_PATH: &str = "e2e-attestation.json";
19
20/// A record of one local e2e run — written to disk and committed by [`attest`].
21///
22/// `commit` is the SHA of the code commit the run was made against (HEAD at
23/// attest time); [`verify`](crate::e2e) (#68) checks it against the latest code
24/// commit. The rest is information for humans — nothing is gated on it.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Attestation {
27    /// The command that was run (e.g. `pnpm run e2e`).
28    pub command: String,
29    /// When it ran, as a Unix timestamp (seconds).
30    pub ran_at: u64,
31    /// The command's exit code — recorded, never gated on.
32    pub exit_code: i32,
33    /// The commit the run was made against (HEAD at attest time).
34    pub commit: String,
35}
36
37/// Run `command` in `repo`, write an [`Attestation`] naming the current HEAD to
38/// `repo`/[`ATTESTATION_PATH`], and commit it on top. Returns the attestation.
39///
40/// Writes regardless of the command's exit code — this forces a *run*, not a
41/// *pass*.
42pub fn attest(repo: &Path, command: &str) -> Result<Attestation> {
43    let commit = git_capture(repo, &["rev-parse", "HEAD"])
44        .context("resolving HEAD — `e2e attest` must run inside a git repo with a commit")?;
45
46    // Run the e2e command via the shell, streaming its output through.
47    let status = Command::new("sh")
48        .arg("-c")
49        .arg(command)
50        .current_dir(repo)
51        .status()
52        .with_context(|| format!("running e2e command `{command}`"))?;
53    let exit_code = status.code().unwrap_or(-1);
54
55    let ran_at = SystemTime::now()
56        .duration_since(UNIX_EPOCH)
57        .map(|d| d.as_secs())
58        .unwrap_or(0);
59
60    let attestation = Attestation {
61        command: command.to_string(),
62        ran_at,
63        exit_code,
64        commit: commit.clone(),
65    };
66
67    // Write the attestation, then commit just that file on top — it names the
68    // code commit it was run against (a commit can't name its own SHA).
69    let path = repo.join(ATTESTATION_PATH);
70    let json = serde_json::to_string_pretty(&attestation).context("serializing the attestation")?;
71    std::fs::write(&path, format!("{json}\n"))
72        .with_context(|| format!("writing {}", path.display()))?;
73
74    git_run(repo, &["add", ATTESTATION_PATH])?;
75    let short = &commit[..commit.len().min(7)];
76    let message = format!("e2e attestation for {short}");
77    // A plain commit that inherits the repo's signing policy: a repo requiring
78    // verified signatures gets a signed (mergeable) attestation, instead of the
79    // unsigned commit a forced `commit.gpgsign=false` would leave behind (#128).
80    git_run(repo, &["commit", "-q", "-m", message.as_str()])?;
81
82    Ok(attestation)
83}
84
85/// The outcome of [`verify`] — whether the committed attestation names the latest
86/// code commit, and if not, why.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum Verification {
89    /// The attestation names the latest code commit — the gate passes.
90    Fresh,
91    /// No attestation file is present — the gate fails.
92    Missing,
93    /// An attestation is present but names an older commit than the latest code
94    /// commit (code changed since it was attested) — the gate fails.
95    Stale {
96        /// The commit the attestation names.
97        attested: String,
98        /// The latest code commit (newest one touching a non-attestation path).
99        latest: String,
100    },
101}
102
103/// Verify that the committed attestation names the latest code commit (#68) — the
104/// CI side of the nudge. Reads only the committed attestation: never runs e2e,
105/// never inspects the recorded exit code or output.
106///
107/// Equivalent to [`verify_scoped`] with `scope` set to `repo` — the freshness
108/// walk covers everything under `repo`, same as before #294.
109pub fn verify(repo: &Path) -> Result<Verification> {
110    verify_scoped(repo, repo)
111}
112
113/// Verify the committed attestation at `repo`, scoping the "latest code commit"
114/// walk to `scope` instead of all of `repo` (#294).
115///
116/// `repo` and `scope` serve different roles: `repo` is where
117/// `e2e-attestation.json` lives (the package root — a manifest's own natural
118/// home), while `scope` is what counts as "code" for freshness (the directory a
119/// `path`-scoped call actually named, which can be narrower — a package root
120/// commonly also holds `tests/`, docs, and config files that aren't the
121/// attestable source). `scope` must be `repo` or a descendant of it.
122///
123/// Equivalent to [`verify_since`] with `base` set to `None` — the walk covers
124/// all reachable history, same as before #319.
125pub fn verify_scoped(repo: &Path, scope: &Path) -> Result<Verification> {
126    verify_since(repo, scope, None)
127}
128
129/// Equivalent to [`verify_extra_scoped`] with no extra roots and no excludes —
130/// the freshness walk covers only `scope`, same as before #333.
131pub fn verify_since(repo: &Path, scope: &Path, base: Option<&str>) -> Result<Verification> {
132    verify_extra_scoped(repo, scope, base, &[], &[])
133}
134
135/// Verify the committed attestation at `repo`, joining **extra freshness roots**
136/// outside `scope` into the "latest code commit" walk (#333).
137///
138/// `extra_scopes` are **repo-root-relative** directories — a shared source tree
139/// that is a sibling of the package (a native core bound into several language
140/// bindings), which no `scope` at-or-below the attestation directory can reach.
141/// Their commits count as code just like commits under `scope`, so a change to
142/// the shared tree stales an attestation whose own subtree it doesn't touch.
143/// `excludes` are repo-root-relative directories carved back out of that union —
144/// a feature-gated subtree (a core `cli/` compiled out of the bindings) whose
145/// changes must not stale them. Because the roots may lie outside the package
146/// subtree — that's the point — the descendant constraint stays on `scope` only.
147///
148/// The freshness rule is unchanged: the attestation must name the newest in-range
149/// commit touching the **union** of `scope` and `extra_scopes`, minus `excludes`.
150/// `base` diff-scopes the walk exactly as in [`verify_since`]. Empty
151/// `extra_scopes` and `excludes` are byte-identical to [`verify_since`].
152pub fn verify_extra_scoped(
153    repo: &Path,
154    scope: &Path,
155    base: Option<&str>,
156    extra_scopes: &[PathBuf],
157    excludes: &[PathBuf],
158) -> Result<Verification> {
159    let path = repo.join(ATTESTATION_PATH);
160    let Ok(contents) = std::fs::read_to_string(&path) else {
161        return Ok(Verification::Missing);
162    };
163    let attestation: Attestation =
164        serde_json::from_str(&contents).context("parsing the attestation")?;
165
166    match latest_code_commit(repo, scope, base, extra_scopes, excludes)? {
167        // With `--base`, an empty walk means this branch introduced no scoped
168        // code commit — there is nothing to re-attest, so it's fresh by
169        // construction (mirrors the changed-line coverage/mutation gates, which
170        // pass on an empty diff). This is what keeps the gate squash-safe: a
171        // stale-on-base attestation never reds a PR that didn't touch the source.
172        // Without `--base` the walk covers all history and only comes back empty
173        // for a scope with no commits at all, where an equality check against the
174        // attested SHA (below) is the right answer — same as before this flag.
175        None if base.is_some() => Ok(Verification::Fresh),
176        latest => {
177            let latest = latest.unwrap_or_default();
178            if attestation.commit == latest {
179                Ok(Verification::Fresh)
180            } else {
181                Ok(Verification::Stale {
182                    attested: attestation.commit,
183                    latest,
184                })
185            }
186        }
187    }
188}
189
190/// The newest commit that changed any path other than the attestation file,
191/// under the union of `scope` and `extra_scopes` minus `excludes` — the "latest
192/// code commit" the attestation must name to be fresh. Uses an `:(exclude)`
193/// pathspec so the attestation's own commit never counts as code. `extra_scopes`
194/// and `excludes` are repo-root-relative (`:(top)` pathspec magic), so they match
195/// from the top of the tree regardless of `repo` being a subdirectory cwd — that
196/// is how a sibling tree outside `scope` joins the walk (#333). When `base` is
197/// `Some`, the walk is restricted to the commits this branch introduced
198/// (`<base>..HEAD`); `None` when that range holds no such commit. Without `base`
199/// the walk covers all reachable history.
200fn latest_code_commit(
201    repo: &Path,
202    scope: &Path,
203    base: Option<&str>,
204    extra_scopes: &[PathBuf],
205    excludes: &[PathBuf],
206) -> Result<Option<String>> {
207    let pathspec = relative_pathspec(repo, scope);
208    let mut args: Vec<String> = vec!["log".into(), "-1".into(), "--format=%H".into()];
209    // `<base>..HEAD` — commits reachable from HEAD but not `base`, i.e. the ones
210    // this branch introduced. A commit that also landed on `base` (a squash of an
211    // earlier PR) is reachable from `base`, so it's excluded here — that's the
212    // whole point.
213    if let Some(base) = base {
214        args.push(format!("{base}..HEAD"));
215    }
216    args.push("--".into());
217    // Positive pathspecs: the package's own `scope`, plus each extra root as a
218    // repo-root-relative `:(top)` pathspec so it matches from the tree top rather
219    // than relative to `repo` (the package cwd git runs in).
220    args.push(pathspec);
221    for extra in extra_scopes {
222        args.push(format!(":(top){}", extra.display()));
223    }
224    // Negative pathspecs: the attestation itself never counts as code, and each
225    // excluded (feature-gated) subtree of an extra root is carved back out.
226    args.push(format!(":(exclude){ATTESTATION_PATH}"));
227    for exclude in excludes {
228        args.push(format!(":(top,exclude){}", exclude.display()));
229    }
230    let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
231    let out = git_capture(repo, &arg_refs)?;
232    Ok((!out.is_empty()).then_some(out))
233}
234
235/// `scope` as a pathspec relative to `repo` (git resolves pathspecs relative to
236/// the invocation's cwd, which is always `repo` here). `.` when `scope` is
237/// `repo` itself — byte-identical to the pre-#294 pathspec.
238fn relative_pathspec(repo: &Path, scope: &Path) -> String {
239    if scope == repo {
240        return ".".to_string();
241    }
242    match scope.strip_prefix(repo) {
243        Ok(rel) if !rel.as_os_str().is_empty() => rel.to_string_lossy().into_owned(),
244        _ => scope.to_string_lossy().into_owned(),
245    }
246}
247
248/// Run `git` with `args` in `repo`, returning trimmed stdout; errors if git fails.
249fn git_capture(repo: &Path, args: &[&str]) -> Result<String> {
250    let out = Command::new("git")
251        .args(args)
252        .current_dir(repo)
253        .output()
254        .with_context(|| format!("running `git {}`", args.join(" ")))?;
255    if !out.status.success() {
256        bail!(
257            "`git {}` failed: {}",
258            args.join(" "),
259            String::from_utf8_lossy(&out.stderr).trim()
260        );
261    }
262    Ok(String::from_utf8(out.stdout)?.trim().to_string())
263}
264
265/// Run `git` with `args` in `repo` for its side effect; errors if git fails.
266fn git_run(repo: &Path, args: &[&str]) -> Result<()> {
267    let status = Command::new("git")
268        .args(args)
269        .current_dir(repo)
270        .status()
271        .with_context(|| format!("running `git {}`", args.join(" ")))?;
272    if !status.success() {
273        bail!("`git {}` failed", args.join(" "));
274    }
275    Ok(())
276}