Skip to main content

lean_ctx_cloud/tasks/
gate.rs

1// SPDX-License-Identifier: Apache-2.0
2//! G6 in the Instance (process v1 §5): the locked-path check on submit and
3//! before verify, and the gate's own rerun of the declared command at the
4//! judged commit. Both run here, in the Instance's process, never through
5//! an agent's shell.
6//!
7//! **What the agent's repository cannot change.** Every git call runs with
8//! an empty environment, no global or system config, no replace objects,
9//! no attributes file, and hooks, fsmonitor, external diff and textconv
10//! off. The judged commit and `spec_commit` are fetched into a **private
11//! bare repository** in the gate's own directory (over git's transport, so
12//! every object is hashed again on the way in; no refs/replace, no
13//! alternates, no filters, no config of the agent's repository). The
14//! commit-to-commit check and the rerun tree come only from that copy; the
15//! tree is written blob by blob, with no checkout, so no smudge filter or
16//! attribute applies.
17//!
18//! **The locked-path check** judges the commit and the handed-in worktree:
19//! the commit against `spec_commit` in the private copy (what the rerun
20//! runs), and the worktree with `git diff <spec_commit>` and `git ls-files
21//! --others --exclude-standard` (§5). Every path under a locked path
22//! ([`under_locked`], the matcher Cloud's contract tests use) is kept, each
23//! once with its strongest kind; any type change of a locked path (file ↔
24//! symlink ↔ directory) is `type_changed`, and a path that was a symlink
25//! at `spec_commit` and now resolves outside the repository is
26//! `outside_repo`. A locked path that itself lies outside the repository
27//! is refused.
28//!
29//! **The rerun** (`run`) runs its tree outside `$HOME` (cargo reads every
30//! parent's `.cargo/config.toml`; a run under one is refused), with an
31//! empty environment plus a fixed allowlist (a fixed `PATH`, the gate's own
32//! `CARGO_HOME`, `CARGO_TARGET_DIR` and `TMPDIR` under the Instance's data
33//! dir), and the locked paths laid over from `spec_commit` (files the
34//! judged commit added under a locked path are not in the tree), read-only
35//! during the run and compared with `spec_commit` after every command (a
36//! build script that rewrote a locked test fails `locked_paths_changed`).
37//! A judged commit that changes, against `spec_commit`, cargo's
38//! configuration or toolchain file, any build script, or the build-script
39//! and test-target keys of any manifest (`manifest`) is refused: those
40//! choose what runs the tests.
41//!
42//! **The compiler's list** (`list`): before the rerun, for an M/H task
43//! whose command runs cargo, the same command runs at `spec_commit` in a
44//! tree, target directory and log of its own, with a target runner that
45//! lists each test binary's tests instead of running them. The locked
46//! tests it lists must pass in the rerun, besides those the parser names.
47//!
48//! **Known gap:** the code of the judged commit (its library, proc-macros,
49//! path and registry dependencies with their build scripts) runs at build
50//! time, as the same Unix user as the agent and the Instance. It can still
51//! change `~/.rustup`, `~/.local/bin`, `~/.cargo/bin`, the toolchain or this
52//! Instance's files, or act on the run in ways no file check sees. The code
53//! under test runs inside the test binary and can end it with exit 0: the
54//! harness report (`gate_report.rs`) catches that unless the code also forges a
55//! complete, consistent report. The
56//! locked files' content, inode, mode and change time are checked after
57//! every command, so a rewrite shows even when the bytes were put back.
58//! Only a sandboxed run on pounce under the gate, with the locked paths
59//! bind mounted read-only and no write access outside the run (§5),
60//! closes the rest.
61
62use std::collections::{BTreeMap, BTreeSet};
63use std::path::{Component, Path, PathBuf};
64use std::process::{Command, Stdio};
65use std::time::{Duration, Instant};
66
67use lean_ctx_protocol::cloud::gate::{
68    ChangedPathV1, FeatureResultV1, G6RecordV1, GATE_RECORD_SCHEMA, GateResult, LockedChange,
69    LockedPathsV1, MISSING_CI_PIPELINE, PROCESS_VERSION, RULE_LOCKED_PATHS_CHANGED, RerunReportV1,
70    RerunV1, TaskProcessGateV1, TaskProcessV1, TaskRisk, TestStatusV1, under_locked,
71    validate_repo_path,
72};
73use lean_ctx_time::{SecondsFormat, UtcDateTime};
74use sha2::{Digest as _, Sha256};
75
76#[path = "gate_list.rs"]
77mod list;
78#[path = "gate_manifest.rs"]
79mod manifest;
80#[path = "gate_report.rs"]
81mod report;
82#[path = "gate_run.rs"]
83mod run;
84#[path = "gate_tree.rs"]
85mod tree;
86pub use run::GateDirs;
87use run::{
88    CARGO_CONFIGS, LockedFiles, MoveWatch, Unlock, cargo_run_dir, make_private_dir, private_dir,
89    run_command, run_env,
90};
91use tree::{export_tree, private_copy};
92
93/// Why the gate could not judge: never a pass.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum GateError {
96    /// A locked path names a place outside the repository.
97    LockedPathOutsideRepo(String),
98    /// git or the command could not run, or answered something unexpected.
99    Check(String),
100}
101
102impl std::fmt::Display for GateError {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        match self {
105            Self::LockedPathOutsideRepo(path) => write!(
106                f,
107                "locked path {path:?} lies outside the repository; the gate refuses it"
108            ),
109            Self::Check(why) => write!(f, "the G6 check could not run: {why}"),
110        }
111    }
112}
113
114/// What G6 runs for one task: its risk, the commit its locked paths are
115/// pinned to, those paths, and the declared command.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct GateInputs {
118    pub risk: TaskRisk,
119    /// M/H: the feature list's `spec_commit`; S: the claim's start commit.
120    pub spec_commit: String,
121    /// M/H: the feature list's `locked_paths` at `spec_commit`; S: none.
122    pub locked_paths: Vec<String>,
123    /// M/H: the feature list's `test_command`; S: the repo's declared one.
124    pub command: String,
125    pub e2e_command: Option<String>,
126    /// Feature ids whose `passes` the run sets (M/H).
127    pub features: Vec<String>,
128    /// The longest the rerun may take.
129    pub timeout: Duration,
130}
131
132/// The longest the gate's own run may take.
133pub const RERUN_TIMEOUT: Duration = Duration::from_mins(45);
134
135/// What G6 needs and the task view does not carry.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum Missing {
138    /// Cloud serves it for process tasks, but this Cloud did not.
139    Cloud(&'static str),
140    /// This Instance has no record of it.
141    Local(&'static str),
142}
143
144/// The inputs of G6 for a process task: from Cloud's process fields and
145/// what it serves beside them (`gate`; M/H: the feature list; S: the
146/// repo's declared command) and, for S, the commit this Instance's claim
147/// started from.
148pub fn inputs_for(
149    process: &TaskProcessV1,
150    gate: Option<&TaskProcessGateV1>,
151    start_commit: Option<&str>,
152) -> Result<GateInputs, Missing> {
153    fn given(v: Option<&String>) -> Option<&str> {
154        v.map(String::as_str)
155            .map(str::trim)
156            .filter(|v| !v.is_empty())
157    }
158    let none = TaskProcessGateV1::default();
159    let gate = gate.unwrap_or(&none);
160    if process.risk.has_spec() {
161        let spec = given(process.spec_commit.as_ref())
162            .ok_or(Missing::Cloud("the feature list's spec_commit"))?;
163        if gate.locked_paths.is_empty() {
164            return Err(Missing::Cloud("the feature list's locked_paths"));
165        }
166        let command = given(gate.test_command.as_ref())
167            .ok_or(Missing::Cloud("the feature list's test_command"))?;
168        Ok(GateInputs {
169            risk: process.risk,
170            spec_commit: spec.to_owned(),
171            locked_paths: gate.locked_paths.clone(),
172            command: command.to_owned(),
173            e2e_command: given(gate.e2e_command.as_ref()).map(str::to_owned),
174            features: gate.features.clone(),
175            timeout: RERUN_TIMEOUT,
176        })
177    } else {
178        let command = given(gate.repo_test_command.as_ref())
179            .ok_or(Missing::Cloud("the repo's declared test_command (repo-ci)"))?;
180        let start = start_commit
181            .map(str::trim)
182            .filter(|s| !s.is_empty())
183            .ok_or(Missing::Local("the commit this task's claim started from"))?;
184        Ok(GateInputs {
185            risk: process.risk,
186            spec_commit: start.to_owned(),
187            locked_paths: Vec::new(),
188            command: command.to_owned(),
189            e2e_command: None,
190            features: Vec::new(),
191            timeout: RERUN_TIMEOUT,
192        })
193    }
194}
195
196/// The config every gate git call runs with: nothing a repository or the
197/// environment can configure to run code or to show other content.
198const GIT_SAFE_CONFIG: [&str; 18] = [
199    "-c",
200    "core.fsmonitor=false",
201    "-c",
202    "core.hooksPath=/dev/null",
203    "-c",
204    "core.quotePath=false",
205    "-c",
206    "core.attributesFile=/dev/null",
207    "-c",
208    "diff.external=",
209    "-c",
210    "diff.ignoreSubmodules=none",
211    "-c",
212    "core.untrackedCache=false",
213    "-c",
214    "protocol.file.allow=always",
215    "-c",
216    "uploadpack.allowAnySHA1InWant=true",
217];
218
219/// git with an empty environment: no global or system config, no replace
220/// objects, nothing a repository can configure to run code. Its `PATH` is
221/// the system directories only ([`run::system_dirs`]).
222fn git(repo: &Path) -> Command {
223    let mut cmd = Command::new("git");
224    cmd.env_clear()
225        .env("PATH", run::system_path())
226        .env("LANG", "C")
227        .env("GIT_CONFIG_NOSYSTEM", "1")
228        .env("GIT_CONFIG_GLOBAL", "/dev/null")
229        .env("GIT_NO_REPLACE_OBJECTS", "1")
230        .env("GIT_TERMINAL_PROMPT", "0")
231        .arg("--no-replace-objects")
232        .arg("-C")
233        .arg(repo)
234        .args(GIT_SAFE_CONFIG)
235        .stdin(Stdio::null());
236    cmd
237}
238
239fn run_git(mut cmd: Command, what: &str) -> Result<Vec<u8>, GateError> {
240    let out = cmd
241        .output()
242        .map_err(|e| GateError::Check(format!("git {what}: {e}")))?;
243    if !out.status.success() {
244        return Err(GateError::Check(format!(
245            "git {what} failed: {}",
246            String::from_utf8_lossy(&out.stderr).trim()
247        )));
248    }
249    Ok(out.stdout)
250}
251
252/// The full commit id `rev` names in `repo`.
253pub fn resolve_commit(repo: &Path, rev: &str) -> Result<String, GateError> {
254    if rev.starts_with('-') {
255        return Err(GateError::Check(format!("{rev:?} is not a commit")));
256    }
257    let mut cmd = git(repo);
258    cmd.args(["rev-parse", "--verify", "--quiet", "--end-of-options"])
259        .arg(format!("{rev}^{{commit}}"));
260    let out = run_git(cmd, "rev-parse")?;
261    let sha = String::from_utf8_lossy(&out).trim().to_owned();
262    if sha.len() == 40 && sha.bytes().all(|b| b.is_ascii_hexdigit()) {
263        Ok(sha.to_ascii_lowercase())
264    } else {
265        Err(GateError::Check(format!("{rev:?} is not a commit")))
266    }
267}
268
269/// `HEAD` of the worktree `repo`.
270pub fn head_commit(repo: &Path) -> Result<String, GateError> {
271    resolve_commit(repo, "HEAD")
272}
273
274fn nul_fields(bytes: &[u8]) -> impl Iterator<Item = String> + '_ {
275    bytes
276        .split(|b| *b == 0)
277        .filter(|f| !f.is_empty())
278        .map(|f| String::from_utf8_lossy(f).into_owned())
279}
280
281/// What a path is.
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283enum Kind {
284    File,
285    Symlink,
286    Dir,
287}
288
289/// Every entry of `commit` (trees included) with its kind.
290fn tree_entries(repo: &Path, commit: &str) -> Result<Vec<(String, Kind)>, GateError> {
291    let mut cmd = git(repo);
292    cmd.args(["ls-tree", "-r", "-t", "-z", "--full-tree", commit]);
293    let out = run_git(cmd, "ls-tree")?;
294    let mut entries = Vec::new();
295    for field in nul_fields(&out) {
296        // `<mode> SP <type> SP <object> TAB <path>`
297        let Some((meta, path)) = field.split_once('\t') else {
298            continue;
299        };
300        let kind = match meta.split(' ').next() {
301            Some("040000" | "160000") => Kind::Dir,
302            Some("120000") => Kind::Symlink,
303            _ => Kind::File,
304        };
305        entries.push((path.to_owned(), kind));
306    }
307    Ok(entries)
308}
309
310/// What `path` is in the worktree now (a parent symlink is followed; the
311/// last component is not).
312fn worktree_kind(root: &Path, path: &str) -> Option<Kind> {
313    let meta = std::fs::symlink_metadata(root.join(path)).ok()?;
314    let ft = meta.file_type();
315    Some(if ft.is_symlink() {
316        Kind::Symlink
317    } else if ft.is_dir() {
318        Kind::Dir
319    } else {
320        Kind::File
321    })
322}
323
324/// `path` without `.`, with `..` applied (no file system access).
325fn lexical(path: &Path) -> PathBuf {
326    let mut out = PathBuf::new();
327    for component in path.components() {
328        match component {
329            Component::ParentDir => {
330                out.pop();
331            }
332            Component::CurDir => {}
333            other => out.push(other),
334        }
335    }
336    out
337}
338
339/// Whether the symlink at `root/path` resolves outside `root`: by its link
340/// text, and by where it resolves when it does.
341fn resolves_outside(root: &Path, canonical_root: &Path, path: &str) -> bool {
342    let link = root.join(path);
343    let Ok(target) = std::fs::read_link(&link) else {
344        return false;
345    };
346    let parent = link.parent().unwrap_or(root);
347    let joined = lexical(&parent.join(&target));
348    if !joined.starts_with(lexical(root)) && !joined.starts_with(canonical_root) {
349        return true;
350    }
351    match std::fs::canonicalize(&link) {
352        Ok(resolved) => !resolved.starts_with(canonical_root),
353        Err(_) => false,
354    }
355}
356
357/// Rank when one path differs in more than one way: the stronger kind is
358/// the one recorded (each path once).
359fn rank(change: LockedChange) -> u8 {
360    match change {
361        LockedChange::OutsideRepo => 3,
362        LockedChange::TypeChanged => 2,
363        _ => 1,
364    }
365}
366
367/// The locked-path check of the handed-in worktree `root` against
368/// `spec_commit` (§5): every path under `checked` byte-identical, nothing
369/// new, deleted, untracked or of another type, no locked symlink resolving
370/// outside. It runs in the agent's repository (the worktree is there) with
371/// the hardened `git`; [`g6_record`] adds the commit-to-commit check
372/// from a private copy, which no config of that repository reaches.
373pub fn check_locked_paths(
374    root: &Path,
375    spec_commit: &str,
376    checked: &[String],
377) -> Result<LockedPathsV1, GateError> {
378    for path in checked {
379        validate_repo_path(path).map_err(|_| GateError::LockedPathOutsideRepo(path.clone()))?;
380    }
381    let spec = resolve_commit(root, spec_commit)?;
382    let mut changed: BTreeMap<String, LockedChange> = BTreeMap::new();
383    if !checked.is_empty() {
384        let locked = |path: &str| checked.iter().any(|c| under_locked(path, c));
385
386        // Content, mode, added, deleted, file ↔ symlink (worktree vs spec,
387        // committed and uncommitted alike).
388        let mut cmd = git(root);
389        cmd.args([
390            "diff",
391            "--no-ext-diff",
392            "--no-textconv",
393            "--no-renames",
394            "--ignore-submodules=none",
395            "--name-status",
396            "-z",
397            &spec,
398            "--",
399        ]);
400        let out = run_git(cmd, "diff")?;
401        let fields: Vec<String> = nul_fields(&out).collect();
402        for pair in fields.chunks(2) {
403            let [status, path] = pair else { continue };
404            if locked(path) {
405                note(&mut changed, path.clone(), status_change(status));
406            }
407        }
408
409        // New files git does not track.
410        let mut cmd = git(root);
411        cmd.args(["ls-files", "--others", "--exclude-standard", "-z", "--"]);
412        for path in nul_fields(&run_git(cmd, "ls-files")?) {
413            if locked(&path) {
414                note(&mut changed, path, LockedChange::Untracked);
415            }
416        }
417
418        // Any type change, directories included, and locked symlinks that
419        // now resolve outside the repository.
420        let canonical_root = std::fs::canonicalize(root)
421            .map_err(|e| GateError::Check(format!("the worktree: {e}")))?;
422        for (path, was) in tree_entries(root, &spec)? {
423            if !locked(&path) {
424                continue;
425            }
426            let now = worktree_kind(root, &path);
427            if let Some(now) = now
428                && now != was
429            {
430                note(&mut changed, path.clone(), LockedChange::TypeChanged);
431            }
432            if was == Kind::Symlink
433                && now == Some(Kind::Symlink)
434                && resolves_outside(root, &canonical_root, &path)
435            {
436                note(&mut changed, path, LockedChange::OutsideRepo);
437            }
438        }
439    }
440    Ok(into_check(spec, checked, changed))
441}
442
443/// The reason of a locked-path failure: every differing path with its kind.
444pub fn changed_reason(check: &LockedPathsV1) -> String {
445    let list = check
446        .changed
447        .iter()
448        .map(|c| format!("{} {}", c.path, c.change.as_str()))
449        .collect::<Vec<_>>()
450        .join(", ");
451    let mut reason = format!(
452        "locked paths differ from spec_commit {}: {list}",
453        &check.spec_commit[..8.min(check.spec_commit.len())]
454    );
455    if reason.chars().count() > 2000 {
456        reason = reason.chars().take(1997).collect::<String>() + "...";
457    }
458    reason
459}
460
461fn now_rfc3339() -> String {
462    UtcDateTime::now().to_rfc3339_opts(SecondsFormat::Secs, true)
463}
464
465fn host_name() -> String {
466    std::fs::read_to_string("/etc/hostname")
467        .ok()
468        .map(|h| h.trim().to_owned())
469        .filter(|h| !h.is_empty() && h.len() <= 128)
470        .or_else(|| std::env::var("HOSTNAME").ok().filter(|h| !h.is_empty()))
471        .unwrap_or_else(|| "localhost".to_owned())
472}
473
474/// The commit-to-commit check in the private repository `git_dir`: the
475/// judged commit `artifact` against `spec`, every path under `checked`.
476/// The same kinds as the worktree check, except `untracked` (only a
477/// worktree has it) and `outside_repo`: a locked symlink whose link text
478/// changed is `modified` here, whatever it points to.
479fn commit_check(
480    git_dir: &Path,
481    artifact: &str,
482    spec: &str,
483    checked: &[String],
484) -> Result<BTreeMap<String, LockedChange>, GateError> {
485    let locked = |path: &str| checked.iter().any(|c| under_locked(path, c));
486    let mut changed: BTreeMap<String, LockedChange> = BTreeMap::new();
487    if checked.is_empty() {
488        return Ok(changed);
489    }
490    let mut cmd = git(git_dir);
491    cmd.args([
492        "diff",
493        "--no-ext-diff",
494        "--no-textconv",
495        "--no-renames",
496        "--ignore-submodules=none",
497        "--name-status",
498        "-z",
499        spec,
500        artifact,
501        "--",
502    ]);
503    let fields: Vec<String> = nul_fields(&run_git(cmd, "diff")?).collect();
504    for pair in fields.chunks(2) {
505        let [status, path] = pair else { continue };
506        if locked(path) {
507            note(&mut changed, path.clone(), status_change(status));
508        }
509    }
510    let then: BTreeMap<String, Kind> = tree_entries(git_dir, spec)?.into_iter().collect();
511    for (path, kind) in tree_entries(git_dir, artifact)? {
512        if locked(&path)
513            && let Some(was) = then.get(&path)
514            && *was != kind
515        {
516            note(&mut changed, path, LockedChange::TypeChanged);
517        }
518    }
519    Ok(changed)
520}
521
522fn status_change(status: &str) -> LockedChange {
523    match status.chars().next() {
524        Some('A') => LockedChange::Added,
525        Some('D') => LockedChange::Deleted,
526        Some('T') => LockedChange::TypeChanged,
527        _ => LockedChange::Modified,
528    }
529}
530
531/// Record `change` for `path`, keeping the stronger kind (each path once).
532fn note(changed: &mut BTreeMap<String, LockedChange>, path: String, change: LockedChange) {
533    let entry = changed.entry(path).or_insert(change);
534    if rank(change) > rank(*entry) {
535        *entry = change;
536    }
537}
538
539fn into_check(
540    spec: String,
541    checked: &[String],
542    changed: BTreeMap<String, LockedChange>,
543) -> LockedPathsV1 {
544    let changed: Vec<ChangedPathV1> = changed
545        .into_iter()
546        .map(|(path, change)| ChangedPathV1 { path, change })
547        .collect();
548    LockedPathsV1 {
549        spec_commit: spec,
550        checked: checked.to_vec(),
551        ok: changed.is_empty(),
552        changed,
553    }
554}
555
556/// Files that choose what runs the tests: cargo's configuration and the
557/// toolchain file.
558fn chooses_the_runner(path: &str) -> bool {
559    let name = path.rsplit('/').next().unwrap_or(path);
560    matches!(name, "rust-toolchain" | "rust-toolchain.toml")
561        || CARGO_CONFIGS
562            .iter()
563            .any(|c| path == *c || path.ends_with(&format!("/{c}")))
564}
565
566/// Refused: the judged commit changes cargo's configuration or toolchain
567/// file against `spec` (a `runner = "true"` turns any red run green).
568fn refuse_runner_changes(git_dir: &Path, spec: &str, artifact: &str) -> Result<(), GateError> {
569    let mut cmd = git(git_dir);
570    cmd.args([
571        "diff",
572        "--no-ext-diff",
573        "--no-textconv",
574        "--no-renames",
575        "--name-only",
576        "-z",
577        spec,
578        artifact,
579        "--",
580    ]);
581    let changed: Vec<String> = nul_fields(&run_git(cmd, "diff")?)
582        .filter(|p| chooses_the_runner(p))
583        .collect();
584    if changed.is_empty() {
585        return Ok(());
586    }
587    Err(GateError::Check(format!(
588        "the judged commit changes {} against spec_commit; cargo's configuration and toolchain choose what runs the tests, so the gate does not run them (a person judges that change)",
589        changed.join(", ")
590    )))
591}
592
593/// What the gate's run turned out to be, beyond its exit code.
594enum RunVerdict {
595    /// Nothing the gate forbids happened: the exit code is the evidence.
596    Clean,
597    /// Locked paths changed during the run (a build script or test rewrote
598    /// them), each with its kind.
599    LockedChanged(BTreeMap<String, LockedChange>),
600    /// The harness did not report, a locked test was not built or not run,
601    /// or a build script compiled a changed source: fail with this reason.
602    Failed(String),
603}
604
605/// The gate's own run (§5): the tree of `commit` from the private copy
606/// `git_dir`, without its locked paths, written into `run` (outside
607/// `$HOME`), the locked paths laid over from `spec_commit` (so a file the
608/// commit added under a locked path is not there) and made read-only; the
609/// declared command (and the e2e command, if any) run there, with target
610/// and temp files in `scratch`. `rerun.commit` is `commit`.
611///
612/// After the commands the gate judges the run (§5): the locked files of the
613/// tree (content, inode, mode, change time, and the tree's own container)
614/// must be unchanged, and — for an M/H task or a cargo command — the harness must have
615/// reported, every locked test must have been built and reported passed,
616/// and no build script may have compiled a changed source. `listed` is the
617/// compiler's list at `spec_commit` ([`list`]); its note opens the log.
618#[allow(clippy::too_many_arguments)]
619fn rerun_in(
620    git_dir: &Path,
621    run: &Path,
622    scratch: &Path,
623    work: &Path,
624    commit: &str,
625    spec: &str,
626    inputs: &GateInputs,
627    listed: Option<&list::SpecList>,
628) -> Result<(RerunV1, RunVerdict), GateError> {
629    let tree = run.join("tree");
630    make_private_dir(&tree)?;
631    // Opens the per-run directory (locked with the tree) and the tree again.
632    let _unlock = Unlock(run.to_path_buf());
633    let has_spec = inputs.risk.has_spec();
634    let locked_paths: &[String] = if has_spec { &inputs.locked_paths } else { &[] };
635    let locked = |path: &str| locked_paths.iter().any(|c| under_locked(path, c));
636    export_tree(git_dir, commit, &tree, &|path| !locked(path))?;
637    if has_spec {
638        export_tree(git_dir, spec, &tree, &locked)?;
639    }
640    LockedFiles::read(&tree, locked_paths)?.lock(&tree)?;
641    // Pinned after the lock: the chmod moved every change time.
642    let pinned = LockedFiles::read(&tree, locked_paths)?;
643    // A rename of the per-run directory or any directory above it during
644    // the run, even one put back (R5-1).
645    let watch = MoveWatch::new(run)?;
646    let env = run_env(scratch, work)?;
647    let target = scratch.join("target");
648
649    let log_path = scratch.join("run.log");
650    let mut log = std::fs::File::create(&log_path)
651        .map_err(|e| GateError::Check(format!("the run log: {e}")))?;
652    if let Some(listed) = listed {
653        use std::io::Write as _;
654        writeln!(log, "{}", listed.note)
655            .map_err(|e| GateError::Check(format!("the run log: {e}")))?;
656    }
657    let started_at = now_rfc3339();
658    let deadline = Instant::now() + inputs.timeout;
659    let mut exit_code = run_command(&tree, &inputs.command, &env, &mut log, deadline)?;
660    let mut tampered = pinned.changes(
661        &tree,
662        &LockedFiles::read(&tree, locked_paths)?,
663        watch.moved(),
664    );
665    if exit_code == 0
666        && tampered.is_empty()
667        && let Some(e2e) = &inputs.e2e_command
668    {
669        exit_code = run_command(&tree, e2e, &env, &mut log, deadline)?;
670        tampered = pinned.changes(
671            &tree,
672            &LockedFiles::read(&tree, locked_paths)?,
673            watch.moved(),
674        );
675    }
676    let finished_at = now_rfc3339();
677    drop(log);
678    let bytes =
679        std::fs::read(&log_path).map_err(|e| GateError::Check(format!("the run log: {e}")))?;
680    let log_sha256 = hex::encode(Sha256::digest(&bytes));
681    let log_text = String::from_utf8_lossy(&bytes);
682
683    // Judge the run. A changed locked path comes first (it stops the rest);
684    // then, for an M/H task or a cargo command, the harness report and
685    // dep-info: required by the task inputs, not by what the run left in
686    // `target/` (R5-3).
687    let (verdict, report) = if !tampered.is_empty() {
688        (RunVerdict::LockedChanged(tampered), None)
689    } else if exit_code == 0 && (has_spec || runs_cargo(inputs)) {
690        judge_cargo_run(
691            git_dir,
692            spec,
693            commit,
694            &tree,
695            &target,
696            locked_paths,
697            listed.map(|l| &l.tests),
698            &log_text,
699            &log_sha256,
700        )?
701    } else {
702        (RunVerdict::Clean, None)
703    };
704    let features = if has_spec {
705        let green = exit_code == 0 && matches!(verdict, RunVerdict::Clean);
706        inputs
707            .features
708            .iter()
709            .map(|id| FeatureResultV1 {
710                id: id.clone(),
711                passes: green,
712            })
713            .collect()
714    } else {
715        Vec::new()
716    };
717    let rerun = RerunV1 {
718        command: inputs.command.clone(),
719        e2e_command: inputs.e2e_command.clone(),
720        host: host_name(),
721        commit: commit.to_owned(),
722        spec_commit: spec.to_owned(),
723        exit_code,
724        log_sha256,
725        started_at,
726        finished_at,
727        features,
728        report,
729    };
730    Ok((rerun, verdict))
731}
732
733/// Whether the declared command (or the e2e command) runs cargo: a word
734/// `cargo` in it, or a path ending in `/cargo`.
735fn runs_cargo(inputs: &GateInputs) -> bool {
736    std::iter::once(&inputs.command)
737        .chain(inputs.e2e_command.as_ref())
738        .any(|c| {
739            c.split(|ch: char| !(ch.is_alphanumeric() || ch == '_' || ch == '-'))
740                .any(|w| w == "cargo")
741        })
742}
743
744/// The harness-report and dep-info checks for a run that must report
745/// (§5, leanctx-cloud bb1a533e): no build script compiled a changed source,
746/// the harness reported consistently and ran tests, and every locked test
747/// was built and reported `passed`. The report goes into the record on a
748/// fail too, with each locked test's status.
749#[allow(clippy::too_many_arguments)]
750fn judge_cargo_run(
751    git_dir: &Path,
752    spec: &str,
753    commit: &str,
754    tree: &Path,
755    target: &Path,
756    locked_paths: &[String],
757    listed: Option<&BTreeMap<String, BTreeSet<String>>>,
758    log_text: &str,
759    log_sha256: &str,
760) -> Result<(RunVerdict, Option<RerunReportV1>), GateError> {
761    // The in-tree sources every build script compiled (its `#[path]`
762    // modules and `include!`s): refused when changed against spec_commit.
763    let build_sources = report::in_tree_build_sources(tree, target);
764    if let Err(e) = manifest::refuse_changed_sources(git_dir, spec, commit, &build_sources) {
765        return Ok((RunVerdict::Failed(e.to_string()), None));
766    }
767    let rep = report::parse_report(log_text);
768    if !rep.found {
769        return Ok((
770            RunVerdict::Failed(
771                "rerun_report_missing: the test harness produced no result report (the run ended before the tests ran)".into(),
772            ),
773            None,
774        ));
775    }
776    // First the compiler's list at spec_commit (r8 alternative C): each
777    // locked test libtest listed there must pass here, in a binary built
778    // from its file, whatever the parser below can name. Its paths are
779    // relative to the file's mount at spec_commit; here they get the
780    // file's mount in this tree, the one the parser binds to.
781    let mut listed_tests: BTreeMap<String, Vec<String>> = BTreeMap::new();
782    let mut listed_checked = Vec::new();
783    let mut not_listed_passed = Vec::new();
784    for (file, rels) in listed.into_iter().flatten() {
785        let prefix = match report::module_prefix(tree, file) {
786            Ok(prefix) => prefix,
787            Err(e) => {
788                not_listed_passed.push(format!("{file}: {} tests, but {e}", rels.len()));
789                continue;
790            }
791        };
792        let one = BTreeMap::from([(
793            file.clone(),
794            rels.iter()
795                .map(|r| format!("{prefix}{r}"))
796                .collect::<Vec<_>>(),
797        )]);
798        let checked = report::locked_statuses(tree, target, &one, &rep);
799        let failed: Vec<String> = checked
800            .iter()
801            .filter(|t| t.status != report::PASSED)
802            .map(|t| format!("{} ({})", t.test, t.status))
803            .collect();
804        if !failed.is_empty() {
805            not_listed_passed.push(format!("{file}: {}", failed.join(", ")));
806        }
807        listed_checked.extend(checked);
808        listed_tests.extend(one);
809    }
810    if !not_listed_passed.is_empty() {
811        return Ok((
812            RunVerdict::Failed(format!(
813                "locked_test_not_run: listed by the compiler at spec_commit: {}",
814                not_listed_passed.join("; ")
815            )),
816            Some(report::record(&rep, log_sha256, listed_checked)),
817        ));
818    }
819    // Every locked `*.rs`, with the tests it declares (R6-1): one the gate
820    // cannot read is never dropped, the run fails.
821    let mut tests = match report::locked_tests(tree, locked_paths) {
822        Ok(tests) => tests,
823        Err(e) => {
824            return Ok((
825                RunVerdict::Failed(format!("locked_test_not_run: {e}")),
826                Some(report::record(&rep, log_sha256, listed_checked)),
827            ));
828        }
829    };
830    // Union: the parser's names and the compiler's.
831    for (file, names) in listed_tests {
832        let all = tests.entry(file).or_default();
833        all.extend(names);
834        all.sort();
835        all.dedup();
836    }
837    let names_checked: Vec<TestStatusV1> = report::locked_statuses(tree, target, &tests, &rep);
838    let record = report::record(&rep, log_sha256, names_checked.clone());
839    let fail = |reason: String| Ok((RunVerdict::Failed(reason), Some(record.clone())));
840
841    if rep.named_passed > rep.passed {
842        return fail(format!(
843            "rerun_report_inconsistent: the harness named {} tests passed but its summaries count {}",
844            rep.named_passed, rep.passed
845        ));
846    }
847    let nameless: Vec<&str> = tests
848        .iter()
849        .filter(|(file, names)| names.is_empty() && report::is_test_root(tree, file))
850        .map(|(file, _)| file.as_str())
851        .collect();
852    if !nameless.is_empty() {
853        return fail(format!(
854            "locked_test_not_run: {} declares no test the gate can name",
855            nameless.join(", ")
856        ));
857    }
858    let unbuilt = report::unbuilt(tree, target, &tests);
859    if !unbuilt.is_empty() {
860        return fail(format!(
861            "locked_test_not_run: no test binary of the run was built from {}",
862            unbuilt.join(", ")
863        ));
864    }
865    // R9-1: a test binary that compiled a locked file with tests must mount
866    // it from its own root by a plain chain; else the locked body may sit
867    // where libtest collects nothing while a hollow test takes its path.
868    let unmounted = report::unmounted(tree, target, &tests, &rep);
869    if !unmounted.is_empty() {
870        return fail(format!(
871            "locked_test_not_run: the test binary of {} compiled it without mounting it by a plain `mod` chain from its root",
872            unmounted.join(", ")
873        ));
874    }
875    // Independent of names: a binary built from a locked file that ended
876    // before its summary ran nothing the gate can trust.
877    let unfinished = report::unfinished(tree, target, &tests, &rep);
878    if !unfinished.is_empty() {
879        return fail(format!(
880            "locked_test_not_run: the test binary of {} ended before its summary",
881            unfinished.join(", ")
882        ));
883    }
884    let not_passed: Vec<String> = names_checked
885        .iter()
886        .filter(|t| t.status != report::PASSED)
887        .map(|t| format!("{} ({})", t.test, t.status))
888        .collect();
889    if !not_passed.is_empty() {
890        return fail(format!("locked_test_not_run: {}", not_passed.join(", ")));
891    }
892    // Last, so a task with locked tests names them: zero tests of any kind
893    // (an S task's declared command) is no evidence either.
894    if rep.passed + rep.failed + rep.ignored == 0 {
895        return fail("rerun_no_tests: the harness reported no test at all".into());
896    }
897    Ok((RunVerdict::Clean, Some(record)))
898}
899
900/// The reason of the Instance's record when everything it checks holds.
901fn awaiting_ci_reason(artifact: &str) -> String {
902    format!(
903        "locked paths unchanged and the gate's rerun green at {}; the Instance does not read CI, so the Cloud completes this record with ci (§5.1)",
904        &artifact[..12]
905    )
906}
907
908/// The G6 record of the worktree `root` at the judged commit `artifact`,
909/// worked out in the gate's directories `dirs`: the locked-path check of
910/// the commit and of the worktree first (a failure stops there, `rule:
911/// locked_paths_changed`), then the gate's rerun of `artifact`, whose
912/// locked files are checked again after every command (a change there is
913/// the same failure). The worktree must be at `artifact`; otherwise the
914/// check would judge something else, and the gate refuses.
915///
916/// Everything the Instance checks holding is `blocked` with `missing:
917/// [ci_pipeline]`, never `pass`: the Instance does not read CI.
918pub fn g6_record(
919    root: &Path,
920    dirs: &GateDirs,
921    artifact: &str,
922    inputs: &GateInputs,
923) -> Result<G6RecordV1, GateError> {
924    let artifact = resolve_commit(root, artifact)?;
925    let head = head_commit(root)?;
926    if head != artifact {
927        return Err(GateError::Check(format!(
928            "the worktree is at {}, not at the judged commit {}",
929            &head[..12],
930            &artifact[..12]
931        )));
932    }
933    let checked: &[String] = if inputs.risk.has_spec() {
934        &inputs.locked_paths
935    } else {
936        &[]
937    };
938    if inputs.risk.has_spec() && checked.is_empty() {
939        return Err(GateError::Check(
940            "an M or H task has locked paths; none were given".into(),
941        ));
942    }
943    let worktree = check_locked_paths(root, &inputs.spec_commit, checked)?;
944    let spec = worktree.spec_commit.clone();
945    let scratch = private_dir(&dirs.work)?;
946    let git_dir = private_copy(root, scratch.path(), &[&artifact, &spec])?;
947    let mut changed = commit_check(&git_dir, &artifact, &spec, checked)?;
948    for item in worktree.changed {
949        note(&mut changed, item.path, item.change);
950    }
951    let base = |result, missing: Vec<String>, locked_paths, rerun, rule: Option<&str>, reason| {
952        G6RecordV1 {
953            schema: GATE_RECORD_SCHEMA.into(),
954            process: PROCESS_VERSION.into(),
955            gate: "G6".into(),
956            risk: inputs.risk,
957            artifact_commit: artifact.clone(),
958            result,
959            missing,
960            locked_paths,
961            rerun,
962            rule: rule.map(str::to_owned),
963            reason,
964        }
965    };
966    let locked_paths = into_check(spec.clone(), checked, changed);
967    let checked_record = |record: G6RecordV1| {
968        record
969            .validate()
970            .map_err(|e| GateError::Check(format!("the record breaks the contract: {e}")))?;
971        Ok(record)
972    };
973    if !locked_paths.ok {
974        let reason = changed_reason(&locked_paths);
975        return checked_record(base(
976            GateResult::Fail,
977            Vec::new(),
978            locked_paths,
979            None,
980            Some(RULE_LOCKED_PATHS_CHANGED),
981            Some(reason),
982        ));
983    }
984    let record = {
985        refuse_runner_changes(&git_dir, &spec, &artifact)?;
986        manifest::refuse_build_changes(&git_dir, &spec, &artifact)?;
987        // Before the rerun, so nothing the judged commit builds has run yet.
988        let listed = if inputs.risk.has_spec() && runs_cargo(inputs) {
989            Some(list::spec_list(
990                &git_dir,
991                &spec,
992                &dirs.runs,
993                scratch.path(),
994                &dirs.work,
995                &inputs.command,
996                checked,
997                inputs.timeout,
998            )?)
999        } else {
1000            None
1001        };
1002        let run_dir = cargo_run_dir(&dirs.runs)?;
1003        let (run, verdict) = rerun_in(
1004            &git_dir,
1005            run_dir.path(),
1006            scratch.path(),
1007            &dirs.work,
1008            &artifact,
1009            &spec,
1010            inputs,
1011            listed.as_ref(),
1012        )?;
1013        match verdict {
1014            RunVerdict::LockedChanged(tampered) => {
1015                let after = into_check(spec.clone(), checked, tampered);
1016                let reason = format!(
1017                    "the gate's run changed locked paths (a build script or test rewrote them): {}",
1018                    changed_reason(&after)
1019                );
1020                base(
1021                    GateResult::Fail,
1022                    Vec::new(),
1023                    after,
1024                    Some(run),
1025                    Some(RULE_LOCKED_PATHS_CHANGED),
1026                    Some(reason.chars().take(2000).collect()),
1027                )
1028            }
1029            RunVerdict::Failed(reason) => base(
1030                GateResult::Fail,
1031                Vec::new(),
1032                locked_paths,
1033                Some(run),
1034                None,
1035                Some(reason.chars().take(2000).collect()),
1036            ),
1037            RunVerdict::Clean if run.exit_code == 0 => base(
1038                GateResult::Blocked,
1039                vec![MISSING_CI_PIPELINE.to_owned()],
1040                locked_paths,
1041                Some(run),
1042                None,
1043                Some(awaiting_ci_reason(&artifact)),
1044            ),
1045            RunVerdict::Clean => {
1046                let reason = format!(
1047                    "the gate's run of {:?} at {} exited {}",
1048                    run.command,
1049                    &artifact[..12],
1050                    run.exit_code
1051                );
1052                base(
1053                    GateResult::Fail,
1054                    Vec::new(),
1055                    locked_paths,
1056                    Some(run),
1057                    None,
1058                    Some(reason),
1059                )
1060            }
1061        }
1062    };
1063    checked_record(record)
1064}
1065
1066/// The check before verify (E48): the judged commit `artifact` against
1067/// `spec_commit`, commit to commit (the verifier has no handed-in
1068/// worktree), in a private copy fetched from `repo` into the Instance's G6
1069/// directory `work`, so `repo`'s config, replace refs and attributes
1070/// cannot hide a change. Nothing runs here, so no cargo config matters.
1071/// The same kinds as on submit, except `untracked` (only a worktree has
1072/// it) and `outside_repo` (a changed link text is `modified`).
1073pub fn recheck_commit(
1074    repo: &Path,
1075    work: &Path,
1076    artifact: &str,
1077    spec_commit: &str,
1078    checked: &[String],
1079) -> Result<LockedPathsV1, GateError> {
1080    for path in checked {
1081        validate_repo_path(path).map_err(|_| GateError::LockedPathOutsideRepo(path.clone()))?;
1082    }
1083    let artifact = resolve_commit(repo, artifact)?;
1084    let spec = resolve_commit(repo, spec_commit)?;
1085    let scratch = private_dir(work)?;
1086    let git_dir = private_copy(repo, scratch.path(), &[&artifact, &spec])?;
1087    let changed = commit_check(&git_dir, &artifact, &spec, checked)?;
1088    Ok(into_check(spec, checked, changed))
1089}
1090
1091#[cfg(test)]
1092#[path = "gate_tests.rs"]
1093pub(super) mod tests;