1use 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#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum GateError {
96 LockedPathOutsideRepo(String),
98 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#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct GateInputs {
118 pub risk: TaskRisk,
119 pub spec_commit: String,
121 pub locked_paths: Vec<String>,
123 pub command: String,
125 pub e2e_command: Option<String>,
126 pub features: Vec<String>,
128 pub timeout: Duration,
130}
131
132pub const RERUN_TIMEOUT: Duration = Duration::from_mins(45);
134
135#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum Missing {
138 Cloud(&'static str),
140 Local(&'static str),
142}
143
144pub 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
196const 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
219fn 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
252pub 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
269pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283enum Kind {
284 File,
285 Symlink,
286 Dir,
287}
288
289fn 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 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
310fn 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
324fn 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
339fn 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
357fn rank(change: LockedChange) -> u8 {
360 match change {
361 LockedChange::OutsideRepo => 3,
362 LockedChange::TypeChanged => 2,
363 _ => 1,
364 }
365}
366
367pub 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 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 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 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
443pub 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
474fn 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
531fn 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
556fn 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
566fn 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
593enum RunVerdict {
595 Clean,
597 LockedChanged(BTreeMap<String, LockedChange>),
600 Failed(String),
603}
604
605#[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 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 let pinned = LockedFiles::read(&tree, locked_paths)?;
643 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 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
733fn 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#[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 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 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 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 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 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 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 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
900fn 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 LeanCTX Cloud completes this record with ci (§5.1)",
904 &artifact[..12]
905 )
906}
907
908pub 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 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
1066pub 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;