greengate_runtime/dispatch.rs
1//! The two dispatchers.
2//!
3//! They are NOT the same shape, and both shapes are load-bearing:
4//!
5//! - `pre-commit` runs its checks CONCURRENTLY and reports EVERY failure.
6//! Serial would be a visible slowdown on each commit; stopping at the first
7//! failure would hide the rest, so you'd fix one lint error, commit, and
8//! immediately meet the next.
9//! - `pre-push` runs them SERIALLY and stops at the FIRST failure, naming just
10//! that check. The steps are ordered and expensive (protected branch, then
11//! branch name, then rebase, then the whole test suite) and there is no point
12//! running tests after a rebase conflict.
13//!
14//! Resist the tempting shared `run_all` helper — collapsing these is the
15//! obvious way to silently lose the distinction. `tests/it/dispatchers.rs` pins
16//! both.
17//!
18//! Checks are FUNCTIONS in this binary, called directly. They used to be files:
19//! `.git/hooks/pre-commit-*`, each an identical `sh` shim whose only job was to
20//! re-exec this same binary and tell it its own name. One commit therefore cost
21//! 27 processes — a shim, the binary, then 13 more shims and 13 more binaries —
22//! to do work the binary already had in a table.
23//!
24//! Deleting that removed the filename glob (order was lexicographic, so a
25//! rename could silently reorder a gate), the shebang emulation Windows needed
26//! because it cannot execute a `#!` script, and the spawn plumbing under both.
27//! Order is now a declared list in `registry`.
28
29use std::sync::Mutex;
30
31use crate::check::{Check, Outcome, Severity, Stage, Verdict};
32use crate::configured_skips;
33use crate::names::BIN;
34use crate::registry::{all_stage_checks, Ctx, Overrides};
35use crate::ui::{highlight, valid_sign, warning_sign};
36
37/// The checks for a stage, minus anything `hook.skip` filters out. Resolution
38/// goes through `names_check`, the one rule this and the severity lookup share:
39/// `git config hook.skip ruff` skips `pre-commit-ruff` by short name.
40fn selected<'a>(
41 settings: &crate::config::Settings,
42 stage: Stage,
43 manifest: &'a crate::manifest::Manifest,
44) -> Vec<&'a dyn Check> {
45 selected_during(settings, stage, &[], manifest)
46}
47
48/// Do this repository's hooks apply the CONVENTIONS, or only the safety net?
49///
50/// `git config greengate.conventions declared` (usually `--global`, set by
51/// `amont enroll`) scopes the house rules to repositories that commit an
52/// `amont.conf` — the standing grant of `init.templateDir` then becomes safe
53/// to hand a whole team: a clone of somebody else's project gets conflict,
54/// secret, size and debug-leftover protection, and none of this team's
55/// opinions about commit subjects or branch names. The default,
56/// `everywhere`, keeps today's behaviour exactly.
57///
58/// Presence of the manifest is the declaration; its CONTENT stays
59/// trust-gated. Reading presence executes nothing, so no consent is needed.
60pub fn conventions_apply(
61 settings: &crate::config::Settings,
62 manifest: &crate::manifest::Manifest,
63) -> bool {
64 manifest.declared || !declared_mode(settings)
65}
66
67/// One config read per process — this sits on the hook path of every commit.
68fn declared_mode(settings: &crate::config::Settings) -> bool {
69 *settings.declared_mode.get_or_init(|| {
70 crate::config::enumerated_or(
71 settings,
72 "greengate.conventions",
73 &["everywhere", "declared"],
74 "everywhere",
75 ) == "declared"
76 })
77}
78
79/// The checks for a stage, minus `hook.skip` and minus anything that declares
80/// it does not run during an operation currently in progress.
81fn selected_during<'a>(
82 settings: &crate::config::Settings,
83 stage: Stage,
84 in_progress: &[crate::check::GitState],
85 manifest: &'a crate::manifest::Manifest,
86) -> Vec<&'a dyn Check> {
87 let skips = configured_skips(settings);
88 // Externals are included here, so `hook.skip` and the severity override
89 // govern a declared command exactly as they govern a built-in. A repository
90 // that can add a check it cannot disable would be a worse deal than not
91 // being able to add one.
92 let (kept, dropped): (Vec<_>, Vec<_>) = all_stage_checks(stage, manifest)
93 .into_iter()
94 .partition(|c| !skips.iter().any(|s| crate::skip_suppresses(c.name(), s)));
95 let names: Vec<&str> = dropped.iter().map(|c| c.name()).collect();
96 announce_skips(settings, manifest.file_name(), &names);
97
98 // Announced separately from `hook.skip`, and with the operation named: "not
99 // during a rebase" is a property of the moment and will be true again in a
100 // minute, which is a different thing to tell a reader than "you disabled
101 // this".
102 let (kept, paused): (Vec<_>, Vec<_>) = kept.into_iter().partition(|check| {
103 !check
104 .scope()
105 .not_during
106 .iter()
107 .any(|state| in_progress.contains(state))
108 });
109 if !paused.is_empty() {
110 let what = in_progress
111 .iter()
112 .map(|s| s.as_str())
113 .collect::<Vec<_>>()
114 .join(" and ");
115 println!(
116 "{} {} check(s) paused during {what}: {}",
117 warning_sign(),
118 paused.len(),
119 paused
120 .iter()
121 .map(|c| c.name())
122 .collect::<Vec<_>>()
123 .join(", ")
124 );
125 }
126
127 // The conventions split, last: a held-back check was neither skipped (a
128 // choice about THIS repository) nor paused (a property of the moment) —
129 // this repository simply never subscribed. One line, count not names:
130 // in the clone-of-somebody-else's-project case this prints on every
131 // commit, and fifteen names every time is how a safety message becomes
132 // scroll-past noise.
133 if conventions_apply(settings, manifest) {
134 return kept;
135 }
136 let (kept, held): (Vec<_>, Vec<_>) = kept
137 .into_iter()
138 .partition(|check| check.reach() == crate::check::Reach::Safety);
139 if !held.is_empty() {
140 println!(
141 "{} {} convention check(s) held back — no {} here and \
142 greengate.conventions is `declared`; the safety net still runs",
143 warning_sign(),
144 held.len(),
145 manifest.file_name(),
146 );
147 }
148 kept
149}
150
151/// The key that turns evidence ordering on. `declared` — the registry's
152/// order, the one this file's header argues for — is the default and nothing
153/// about it changes.
154const ORDER: &str = "greengate.order";
155
156/// How far back [`crate::gate_evidence::order_by_evidence`] looks. Not a
157/// config key: it is an input to an ordering that changes nothing about what
158/// runs, and a knob nobody can predict the effect of is a knob that invites
159/// cargo-culting. Ninety days is the same window the report defaults to, so
160/// the ordering a push takes is the ordering `amont-fleet gates` explains.
161const ORDER_WINDOW_DAYS: u64 = 90;
162
163/// Does this repository want its push gates ordered by what the record says?
164fn evidence_ordering(settings: &crate::config::Settings) -> bool {
165 crate::config::enumerated_or(settings, ORDER, &["declared", "evidence"], "declared")
166 == "evidence"
167}
168
169/// Reorder the SCOPED push gates — the suites and audits — by the local
170/// record, leaving everything else exactly where the registry put it.
171///
172/// Two halves, and the split is the safety property. The unscoped pre-push
173/// checks ask about the PUSH — is this branch protected, is the name legal,
174/// is the branch behind, is there a secret in it — and the registry orders
175/// them "cheapest and most decisive first" for a reason: discovering a
176/// protected branch after twenty minutes of tests is precisely the waste this
177/// feature exists to remove, and promoting a suite above them would
178/// reintroduce it. So they keep their positions absolutely.
179///
180/// The scoped gates are permuted among the positions they already occupy.
181/// Nothing is added, removed or skipped — [`crate::gate_evidence`] argues
182/// that at length — and with no history the permutation is the identity.
183fn ordered_by_evidence<'a>(
184 settings: &crate::config::Settings,
185 checks: Vec<&'a dyn Check>,
186) -> Vec<&'a dyn Check> {
187 if !evidence_ordering(settings) || checks.len() < 2 {
188 return checks;
189 }
190 let slots: Vec<usize> = checks
191 .iter()
192 .enumerate()
193 .filter(|(_, c)| !c.scope().is_unscoped())
194 .map(|(i, _)| i)
195 .collect();
196 if slots.len() < 2 {
197 return checks;
198 }
199 let names: Vec<String> = slots
200 .iter()
201 .map(|&i| checks[i].name().to_string())
202 .collect();
203 let history = crate::gate_evidence::history_in(std::path::Path::new("."));
204 if history.is_empty() {
205 return checks;
206 }
207 let order = crate::gate_evidence::order_by_evidence(
208 &names,
209 &history,
210 crate::gate_evidence::now(),
211 ORDER_WINDOW_DAYS,
212 );
213 let mut out = checks.clone();
214 for (slot, &pick) in slots.iter().zip(&order) {
215 out[*slot] = checks[slots[pick]];
216 }
217 if out
218 .iter()
219 .map(|c| c.name())
220 .ne(checks.iter().map(|c| c.name()))
221 {
222 crate::say!(
223 "{} gate order from this repository's own record: {}",
224 valid_sign(),
225 slots
226 .iter()
227 .map(|&i| out[i].name())
228 .collect::<Vec<_>>()
229 .join(", ")
230 );
231 }
232 out
233}
234
235/// Say out loud which checks did not run.
236///
237/// A skip is otherwise invisible at exactly the moment it matters. With
238/// `hook.skip = merge-conflict` set, a commit printed six green ticks and no
239/// hint that a seventh check had been disabled — the developer sees a clean run
240/// and concludes they are covered.
241///
242/// It is worse than it sounds, because one value can silence a whole stage:
243/// `hook.skip = pre-commit` suppresses all fifteen. That is now something
244/// somebody meant rather than the accident it once was — `e` used to cost
245/// twenty by substring reach — but a commit under it still looks exactly like a
246/// commit that had nothing to report.
247///
248/// One line, only when something was actually skipped, so a normal commit is
249/// unchanged. This reaches every skip however it was created — hand-edited
250/// config included — which no dashboard can claim.
251fn announce_skips(settings: &crate::config::Settings, manifest_file: &str, dropped: &[&str]) {
252 if dropped.is_empty() {
253 return;
254 }
255 // Two lines, not one: "you decided this" (hook.skip on this machine)
256 // and "your team decided this" (a skip line in the committed
257 // greengate.conf) are different things to be told — the same reason paused
258 // and held-back get their own sentences. A name both sources suppress
259 // is announced as the machine's: the local decision is the nearer one.
260 let (machine, _policy) = crate::skips_by_source(settings);
261 let (yours, theirs): (Vec<&&str>, Vec<&&str>) = dropped
262 .iter()
263 .partition(|name| machine.iter().any(|s| crate::skip_suppresses(name, s)));
264 let say = |names: &[&&str], via: &str| {
265 if names.is_empty() {
266 return;
267 }
268 let plural = if names.len() == 1 { "check" } else { "checks" };
269 println!(
270 "{} {} {plural} skipped by {}: {}",
271 warning_sign(),
272 names.len(),
273 highlight(via),
274 names.iter().map(|n| **n).collect::<Vec<_>>().join(", ")
275 );
276 };
277 say(&yours, "hook.skip");
278 say(&theirs, manifest_file);
279}
280
281/// Say, once per stage, what the manifest's policy could not do — withheld
282/// behind trust, or aiming at names that exist nowhere. Policy that silently
283/// does not apply is a silent behaviour change, which is the one kind this
284/// codebase does not allow itself.
285fn announce_policy_state(settings: &crate::config::Settings, manifest: &crate::manifest::Manifest) {
286 if let Some(why) = manifest.policy_withheld {
287 println!(
288 "{} {} policy not applied: {why}",
289 warning_sign(),
290 highlight(manifest.file_name()),
291 );
292 }
293 for note in &manifest.policy_notes {
294 println!("{} {}", warning_sign(), note);
295 }
296 // The version floor rides the same two call sites: once per stage,
297 // beside the other "this repository expects something you lack" lines.
298 crate::skew::announce_minimum(settings);
299}
300
301/// Run every item concurrently and collect `(name, code)` in the INPUT order.
302///
303/// Extracted so the concurrency itself can be tested with a rendezvous instead
304/// of a stopwatch — an earlier wall-clock test was flaky the moment the machine
305/// was busy, and a threshold that trips under load teaches you to ignore it.
306fn run_concurrently<T, R, F>(items: &[T], run: F, if_thread_died: R) -> Vec<R>
307where
308 T: Sync,
309 R: Send + Sync + Clone,
310 F: Fn(&T) -> R + Sync,
311{
312 let slots: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
313 std::thread::scope(|scope| {
314 for (item, slot) in items.iter().zip(&slots) {
315 let run = &run;
316 let died = &if_thread_died;
317 scope.spawn(move || {
318 // CAUGHT, not propagated. `thread::scope` re-raises a child
319 // panic in the parent, which would abort the whole hook with a
320 // backtrace and throw away the other nineteen checks' results —
321 // and would make `if_thread_died` unreachable, which is what it
322 // was until this test existed to notice.
323 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(item)))
324 .unwrap_or_else(|_| died.clone());
325 *slot.lock().expect("poisoned") = Some(outcome);
326 });
327 }
328 });
329 slots
330 .into_iter()
331 .map(|s| {
332 s.into_inner()
333 .expect("poisoned")
334 .unwrap_or_else(|| if_thread_died.clone())
335 })
336 .collect()
337}
338
339/// Take the index-fidelity hold, or say why the caller must stop.
340///
341/// Extracted from `pre_commit` so that `amont run` — which its own doc
342/// comment calls "a rehearsal of the hook" — can take exactly the same hold
343/// rather than judging the working tree while a real commit judges the index.
344///
345/// Around the WHOLE fan-out, not per check: twenty checks run concurrently and
346/// would fight over one working tree.
347fn hold_unstaged() -> Result<crate::staged_only::StagedOnly, Verdict> {
348 // BEFORE `enter()`, not after: `enter()` is what checks out the tree and
349 // parks the unstaged half, and a signal landing in the gap between that
350 // and the handler being armed would hit the default disposition — dead
351 // process, tree left checked out, nothing restored. The handler no-ops
352 // harmlessly on a signal that arrives before there is anything held.
353 crate::staged_only::install_signal_handler();
354 match crate::staged_only::StagedOnly::enter() {
355 Ok(guard) => Ok(guard),
356 Err(e) => {
357 // Refusing to check the wrong content is the safe direction; a
358 // check that read the tree would be answering about a commit
359 // nobody is making.
360 eprintln!("{e}");
361 Err(Verdict::Block)
362 }
363 }
364}
365
366pub fn pre_commit(ctx: &Ctx) -> Verdict {
367 let settings = ctx.settings;
368 // A detached rehearsal's passes become cluster tokens before any gate
369 // asks for one (ADR-0017). Costs one `stat` when nothing is pending, and
370 // nothing in a repository that declares no `platform=any` gate.
371 crate::cluster::collect_if_declared(ctx.manifest);
372 // Before anything runs: a pinned tool at the wrong version makes every
373 // verdict below it suspect, and the warning costs one --version per pin.
374 crate::manifest::verify_tool_pins(&ctx.manifest.pins, ctx.manifest.file_name());
375 announce_policy_state(ctx.settings, ctx.manifest);
376 let in_progress = crate::git_states_in_progress();
377 let checks = selected_during(ctx.settings, Stage::PreCommit, &in_progress, ctx.manifest);
378
379 // Tree gates (ADR-0024): judged BEFORE the hold, which is the only moment
380 // unstaged edits are visible; started AFTER it, so they lint the commit's
381 // tree. They never decide the commit.
382 let tree_gates = if ctx.manifest.tree.is_empty() || !crate::tree_lint::enabled(settings) {
383 None
384 } else {
385 match crate::tree_lint::guard(settings) {
386 Some(why) => {
387 crate::hooks::common::say(" tree lint not proven — CI will lint:");
388 crate::hooks::common::say(&crate::tree_lint::fit_line(" ", &why, ""));
389 crate::tree_lint::note_withheld(&ctx.manifest.tree);
390 None
391 }
392 None => Some(&ctx.manifest.tree),
393 }
394 };
395
396 let held = match hold_unstaged() {
397 Ok(guard) => guard,
398 Err(verdict) => return verdict,
399 };
400
401 let root = crate::hooks::common::repo_root();
402 // How long this commit's own declared checks are expected to run — the
403 // cover a tree gate can hide behind — from their last measured runs.
404 let decls =
405 crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals);
406 // Only declarations whose scope this commit touches RUN; the others
407 // return at once, and their duration says nothing about cover.
408 let staged = if ctx.manifest.tree.is_empty() {
409 Vec::new()
410 } else {
411 crate::hooks::common::staged_files(&[])
412 };
413 // A declaration in scope that was never measured is UNKNOWN cover, and
414 // unknown means run: the run teaches both numbers, exactly as an unknown
415 // gate time does. Guessing 0 would skip the one commit that could learn.
416 let cover_ms = if tree_gates.is_some() {
417 decls
418 .iter()
419 .filter(|d| d.scope.touches(&staged))
420 .map(|d| crate::tree_cache::duration_of(&d.id).unwrap_or(u64::MAX))
421 .max()
422 .unwrap_or(0)
423 } else {
424 0
425 };
426 let side_car = tree_gates.and_then(|g| {
427 crate::tree_lint::start(
428 settings,
429 std::path::Path::new(&root),
430 g,
431 &ctx.manifest.pins,
432 cover_ms,
433 )
434 });
435
436 let severities = Overrides::read(settings);
437 // Resolved once and handed down (ADR-0020): the stage and the wave
438 // ledger below ask the same question, and each read of a git setting is
439 // a spawn the commit's budget counts (`spawn_budget.rs`).
440 let waves = Waves::resolve(settings);
441 let (verdict, outcomes, durations) =
442 run_stage_traced(settings, &checks, ctx, &severities, waves);
443 // Remember how long the declared checks that judged something took, for
444 // the next commit's cover estimate.
445 if !ctx.manifest.tree.is_empty() {
446 let measured: Vec<(String, u64)> = checks
447 .iter()
448 .zip(outcomes.iter().zip(&durations))
449 .filter(|(c, (o, _))| {
450 matches!(o, Outcome::Passed | Outcome::Failed)
451 && decls
452 .iter()
453 .any(|d| d.id == c.name() && d.scope.touches(&staged))
454 })
455 .map(|(c, (_, ms))| (c.name().to_string(), *ms))
456 .collect();
457 crate::tree_cache::record_durations(&measured);
458 }
459
460 // The wave ledger (ADR-0020): how long the Light wave held the Heavy one
461 // back, and what a blocking Light failure skipped. Hook only, never
462 // `amont run`, like the downgrade ledger below.
463 if waves == Waves::LightThenHeavy {
464 let light_ms = checks
465 .iter()
466 .zip(&durations)
467 .filter(|(c, _)| !is_heavy(**c))
468 .map(|(_, ms)| *ms)
469 .max()
470 .unwrap_or(0);
471 let skipped: Vec<&str> = checks
472 .iter()
473 .zip(&outcomes)
474 .filter(|(_, o)| **o == Outcome::Skipped)
475 .map(|(c, _)| c.name())
476 .collect();
477 // Heavy checks this change reached that judged something, or would
478 // have: clippy on a `.txt`-only commit returns `Passed` having judged
479 // nothing, and one that came back `Inert`, `Unavailable` or `Deferred`
480 // waited for nothing either. A commit with none writes no line, and
481 // spends no git spawn on the ledger's path (`spawn_budget.rs`). The
482 // staged list is the stage's own, cached; the tracked list is read
483 // only for a Heavy check this change touched (`would_judge` asks it
484 // only then), so an ordinary commit pays nothing here.
485 let staged = crate::hooks::common::staged_files(&[]);
486 let heavy_checks = checks
487 .iter()
488 .zip(&outcomes)
489 .filter(|(c, o)| is_heavy(**c) && o.judged_or_skipped())
490 .filter(|(c, _)| c.scope().touches(&staged))
491 .filter(|(c, _)| {
492 c.would_judge(&staged, crate::hooks::common::tracked_files().as_deref())
493 })
494 .count();
495 crate::waves::note(light_ms, heavy_checks, &skipped);
496 }
497
498 // The shadow-mode ledger. Silent, best-effort, and never consulted by any
499 // verdict — see `crate::downgrade`.
500 crate::downgrade::note(
501 settings,
502 &downgraded_events(&checks, &outcomes, &severities),
503 );
504
505 // What post-commit will bind to the commit: the gate-declared checks
506 // that RAN clean, recorded while the index still is the commit's tree.
507 // Called on every verdict — an empty record clears any leftover marker,
508 // so a blocked attempt (or a repo with nothing declared) cannot leave an
509 // earlier attempt's marker to vouch for the next commit. `Unavailable`
510 // deliberately does not qualify: a check whose tool is missing judged
511 // nothing, and stamping it would be the paper promise this exists to
512 // replace.
513 // EVERY blocking declaration, not only the npm GATE names: a custom
514 // `pre-commit check … block …` earns its stamp the same way, and a
515 // same-named pre-push declaration defers to it (see `pair_verdict`).
516 let ran: Vec<String> = if matches!(verdict, Verdict::Block) {
517 Vec::new()
518 } else {
519 crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals)
520 .into_iter()
521 .filter(|d| {
522 checks
523 .iter()
524 .zip(&outcomes)
525 .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Passed | Outcome::Fixed))
526 })
527 // A pass the cluster proved is recorded in its own ref and never
528 // becomes a local token (ADR-0016).
529 .filter(|d| !crate::cluster::proved_on_index(&d.id))
530 // The token, not the bare script: a skip is honoured only for the
531 // same command run by the same program (`gate_identity`). A
532 // declaration whose program cannot be identified earns no stamp.
533 .filter_map(|d| {
534 ctx.manifest
535 .externals
536 .iter()
537 .find(|e| e.id == d.id)
538 .and_then(|e| crate::gate_identity::external_token(e, &d.script))
539 })
540 .collect()
541 };
542 // A rewrite means the tree the gates linted is not the one committed.
543 let stampable =
544 !matches!(verdict, Verdict::Block) && !outcomes.iter().any(|o| matches!(o, Outcome::Fixed));
545 let mut ran = ran;
546 if let Some(car) = side_car {
547 ran.extend(crate::tree_lint::finish(settings, car, stampable));
548 }
549 let ran: Vec<&str> = ran.iter().map(String::as_str).collect();
550 crate::gate_stamp::record(&ran);
551 // The blocking declarations the busy policy deferred, by script name, on
552 // the staged tree (the commit's, under the hold): pre-push reads them to
553 // defer the push twin too (ADR-0013). Never a token: nothing is stamped.
554 let deferred: Vec<String> =
555 crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals)
556 .into_iter()
557 .filter(|d| {
558 checks
559 .iter()
560 .zip(&outcomes)
561 .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Deferred))
562 })
563 .map(|d| d.script)
564 .collect();
565 if !deferred.is_empty() {
566 if let Some(tree) = crate::git::stdout(&["write-tree"]) {
567 crate::gate_stamp::record_deferred(&tree, &deferred);
568 }
569 }
570 // Under the hold, the index IS the commit's tree: its evidence goes there.
571 if !ctx.manifest.tree.is_empty() {
572 if let Some(tree) = crate::git::stdout(&["write-tree"]) {
573 crate::tree_lint::flush_evidence(&tree);
574 }
575 }
576
577 drop(held);
578 verdict
579}
580
581/// The checks that FAILED without blocking, each with why — the shadow-mode
582/// signal [`crate::downgrade`] keeps.
583///
584/// Derived at the hook entry points and deliberately NOT inside
585/// [`run_stage_traced`], which is where `classify` already computes the same
586/// set. `run_all` reaches that function too, so recording there would let
587/// every `amont run` rehearsal inflate a ledger a lead is going to read as a
588/// count of real commits — and `run --all-files` over a dirty tree would add
589/// dozens of events for content nobody is committing.
590///
591/// A check that DECLARES `warn` is counted but is not evidence about a
592/// rollout: it was never going to block, so calling it "would have blocked"
593/// would inflate the one number the whole feature exists to produce. Only an
594/// override of a blocking check earns that.
595fn downgraded_events(
596 checks: &[&dyn Check],
597 outcomes: &[Outcome],
598 severities: &Overrides,
599) -> Vec<(String, crate::downgrade::Origin)> {
600 checks
601 .iter()
602 .zip(outcomes)
603 .filter(|(_, o)| matches!(o, Outcome::Failed))
604 .filter(|(c, _)| matches!(severities.of(**c), Severity::Warn))
605 .map(|(c, _)| (c.name().to_string(), downgrade_origin(*c, severities)))
606 .collect()
607}
608
609/// Why this check did not block. Shared, because `pre_push` fail-fasts and
610/// never builds an outcomes vector to hand to [`downgraded_events`].
611fn downgrade_origin(check: &dyn Check, severities: &Overrides) -> crate::downgrade::Origin {
612 use crate::downgrade::Origin;
613 use crate::registry::Source;
614 if matches!(check.severity(), Severity::Warn) {
615 return Origin::Declared;
616 }
617 match severities.applied_with_source(check.name()) {
618 Some((_, _, Source::Config)) => Origin::Config,
619 Some((_, _, Source::Policy)) => Origin::Policy,
620 // Declared `block`, resolved `warn`, and nothing claims to have
621 // overridden it: a contradiction. Count it, but not as evidence — the
622 // conservative direction for a number whose only failure mode is
623 // being too alarming.
624 None => Origin::Declared,
625 }
626}
627
628/// The pre-commit body, over the checks it is GIVEN.
629///
630/// A seam, so a test can hand it a check that panics. Without it the value
631/// standing in for a dead check was a literal at one call site that no test
632/// could reach — the rule was asserted on the runner and merely hoped for here.
633fn run_stage(checks: &[&dyn Check], ctx: &Ctx, severities: &Overrides) -> Verdict {
634 let settings = ctx.settings;
635 run_stage_traced(settings, checks, ctx, severities, Waves::resolve(settings)).0
636}
637
638/// [`run_stage`], keeping the per-check outcomes — index-aligned with
639/// `checks` — alive past the verdict. `pre_commit` needs them to know which
640/// gate-declared checks actually ran (`gate_stamp`); `Report` cannot answer
641/// that, because `classify` deliberately drops the names of `Passed`.
642fn run_stage_traced(
643 settings: &crate::config::Settings,
644 checks: &[&dyn Check],
645 ctx: &Ctx,
646 severities: &Overrides,
647 waves: Waves,
648) -> (Verdict, Vec<Outcome>, Vec<u64>) {
649 if checks.is_empty() {
650 return (Verdict::Proceed, Vec::new(), Vec::new());
651 }
652 // One slot per check: everything a check says lands in its own buffer
653 // and reaches stdout as ONE block when it finishes — see `live`. Off
654 // (`greengate.progress false`), no sink is ever installed and every print
655 // streams exactly as it always did.
656 let stage = crate::live::enabled(settings).then(|| {
657 let names: Vec<&str> = checks.iter().map(|c| c.name()).collect();
658 crate::live::Stage::begin(settings, &names)
659 });
660 let items: Vec<(usize, &&dyn Check)> = checks.iter().enumerate().collect();
661 let run_one = |(idx, check): &(usize, &&dyn Check)| -> (Outcome, u64) {
662 let started = std::time::Instant::now();
663 let _sink = stage.as_ref().map(|s| s.enter(*idx));
664 // The block is emitted however the check leaves — a panicking
665 // check's partial output still reaches the reader, above the
666 // dead-check verdict `run_concurrently` fills in.
667 let flush = stage
668 .as_ref()
669 .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, *idx));
670 let sub = Ctx {
671 name: check.name(),
672 args: ctx.args,
673 hooks_dir: ctx.hooks_dir,
674 push: ctx.push,
675 manifest: ctx.manifest,
676 settings: ctx.settings,
677 handed_to_cluster: ctx.handed_to_cluster,
678 land: ctx.land,
679 audits: ctx.audits,
680 source_worktree: ctx.source_worktree,
681 };
682 let slot = enter(**check, || severities.of(**check));
683 let outcome = deferred_or(&slot, check.run(&sub));
684 if let Some(f) = &flush {
685 f.outcome(outcome);
686 }
687 // The record measures the check, not its wait for a host slot.
688 let ran = started.elapsed().saturating_sub(slot.queued());
689 let ms = u64::try_from(ran.as_millis()).unwrap_or(u64::MAX);
690 (outcome, ms)
691 };
692 // A check whose thread died has not passed. Stated here, where the slot
693 // is filled, rather than hidden in a `Default` impl that every future
694 // `#[derive(Default)]` would silently inherit.
695 let died = (Outcome::Failed, 0);
696 let timed = match waves {
697 Waves::LightThenHeavy => in_waves(&items, &run_one, died, severities),
698 Waves::One => run_concurrently(&items, run_one, died),
699 };
700 let (outcomes, durations): (Vec<Outcome>, Vec<u64>) = timed.into_iter().unzip();
701
702 let report = classify(checks, &outcomes, severities);
703 announce(settings, &report);
704 (report.verdict(), outcomes, durations)
705}
706
707/// How a pre-commit stage runs its checks (ADR-0020).
708#[derive(Debug, Clone, Copy, PartialEq, Eq)]
709enum Waves {
710 /// Every check at once, as before 2.1 (`greengate.failFast false`).
711 One,
712 /// The Light checks, then the Heavy ones only if none blocked.
713 LightThenHeavy,
714}
715
716impl Waves {
717 /// `GREENGATE_FAIL_FAST` for one run, then `greengate.failFast` (git config, then
718 /// a trusted `set failFast` in `amont.conf`), then on. Read once by the
719 /// caller and handed down, never cached behind the settings it takes.
720 fn resolve(settings: &crate::config::Settings) -> Waves {
721 if resolve_fail_fast(std::env::var(FAIL_FAST_ENV).ok().as_deref(), settings) {
722 Waves::LightThenHeavy
723 } else {
724 Waves::One
725 }
726 }
727}
728
729/// Heavy checks take a host slot and run in the second wave (ADR-0009,
730/// ADR-0020); everything else is Light.
731fn is_heavy(check: &dyn Check) -> bool {
732 check.weight() == crate::host_slots::Weight::Heavy
733}
734
735const FAIL_FAST_ENV: &str = "GREENGATE_FAIL_FAST";
736
737/// [`Waves::resolve`] with the environment value handed in: the testable seam,
738/// because setting a variable in a threaded test binary races its siblings.
739fn resolve_fail_fast(from_env: Option<&str>, settings: &crate::config::Settings) -> bool {
740 match from_env
741 .filter(|v| !v.is_empty())
742 .map(str::to_ascii_lowercase)
743 .as_deref()
744 {
745 Some("true" | "1" | "yes" | "on") => true,
746 Some("false" | "0" | "no" | "off") => false,
747 Some(other) => {
748 crate::config::complain(
749 FAIL_FAST_ENV,
750 &format!("{other:?} is not true or false"),
751 "greengate.failFast",
752 );
753 crate::config::boolean_or(settings, "greengate.failFast", true)
754 }
755 None => crate::config::boolean_or(settings, "greengate.failFast", true),
756 }
757}
758
759/// The stage in two waves (ADR-0020): every Light check at once, then — only
760/// if none of them FAILED at a blocking severity — every Heavy check at once.
761/// A Heavy check the first wave condemned never starts: it takes no host
762/// slot, earns no stamp, and comes back `Skipped`. Results stay index-aligned
763/// with `items`, as `run_concurrently`'s do.
764///
765/// Waves, not cancellation: the check runner kills only a tool's direct child
766/// (`wait_within`), so stopping a running `cargo test` would orphan its test
767/// binaries. A wave that never starts needs no kill.
768fn in_waves<'a, F>(
769 items: &[(usize, &&'a dyn Check)],
770 run: &F,
771 died: (Outcome, u64),
772 severities: &Overrides,
773) -> Vec<(Outcome, u64)>
774where
775 F: Fn(&(usize, &&'a dyn Check)) -> (Outcome, u64) + Sync,
776{
777 let (light, heavies): (Vec<_>, Vec<_>) =
778 items.iter().copied().partition(|(_, c)| !is_heavy(**c));
779 let mut out = vec![died; items.len()];
780 let light_out = if light.is_empty() {
781 Vec::new()
782 } else {
783 run_concurrently(&light, run, died)
784 };
785 // A dead Light thread reads `Failed` and so condemns the Heavy wave: a
786 // check that died has not passed.
787 let blocked = light
788 .iter()
789 .zip(&light_out)
790 .any(|((_, c), (o, _))| *o == Outcome::Failed && severities.of(**c) == Severity::Block);
791 for ((idx, _), r) in light.iter().zip(light_out) {
792 out[*idx] = r;
793 }
794 if heavies.is_empty() {
795 return out;
796 }
797 if blocked {
798 // Only a check that would have judged something is SKIPPED; the rest
799 // would have come back `Inert` (clippy in a repository with no Rust),
800 // and naming them would list checks that never apply here. The check
801 // answers for itself (`Check::would_judge`).
802 let staged = crate::hooks::common::staged_files(&[]);
803 let tracked = crate::hooks::common::tracked_files();
804 for (idx, c) in &heavies {
805 out[*idx] = if c.would_judge(&staged, tracked.as_deref()) {
806 (Outcome::Skipped, 0)
807 } else {
808 (Outcome::Inert, 0)
809 };
810 }
811 return out;
812 }
813 for ((idx, _), r) in heavies.iter().zip(run_concurrently(&heavies, run, died)) {
814 out[*idx] = r;
815 }
816 out
817}
818
819/// What a stage concluded, before anything is printed or exited.
820///
821/// A VALUE, so the classification can be asserted directly. While this was one
822/// function that classified, printed and returned an exit code, its tests could
823/// only check the code — whether the right thing was SAID went untested.
824#[derive(Debug, Default, PartialEq, Eq)]
825struct Report<'a> {
826 /// Repaired. The commit proceeds, but the author's files changed under
827 /// them and that must be said out loud.
828 fixed: Vec<&'a str>,
829 /// Failed, and the severity that applies blocks.
830 blocked: Vec<&'a str>,
831 /// Failed, but configured to warn. The check printed an error and meant it,
832 /// so somebody has to say it did not block.
833 downgraded: Vec<&'a str>,
834 /// Could not run. Distinct from "passed", which is the whole point.
835 unavailable: Vec<&'a str>,
836 /// Deferred to CI by the busy policy (ADR-0013). Not passed, not a gap
837 /// on this machine's part either: said so, with what to do about it.
838 deferred: Vec<(&'a str, Severity)>,
839 /// Heavy checks that never started because a Light one blocked first
840 /// (ADR-0020). Said in quiet mode too: a refused commit whose suite did
841 /// not run must never read as one whose suite passed.
842 skipped: Vec<&'a str>,
843 /// How many passed outright. Only read when `greengate.quiet` swallowed their
844 /// individual lines — a run that says nothing at all is indistinguishable
845 /// from a gate that never ran, and that is the one thing this crate will
846 /// not let a reader believe.
847 passed: usize,
848}
849
850impl Report<'_> {
851 fn verdict(&self) -> Verdict {
852 Verdict::blocking(!self.blocked.is_empty())
853 }
854}
855
856/// Pure: outcomes and severities in, a verdict out. No IO.
857fn classify<'a>(
858 checks: &[&'a dyn Check],
859 outcomes: &[Outcome],
860 severities: &Overrides,
861) -> Report<'a> {
862 let mut report = Report::default();
863 for (check, outcome) in checks.iter().zip(outcomes) {
864 match outcome {
865 Outcome::Passed => report.passed += 1,
866 // `Warned` needs nothing: a check that chose to warn has already
867 // said what it wanted to, and a roll-up would only repeat it.
868 Outcome::Warned => {}
869 Outcome::Fixed => report.fixed.push(check.name()),
870 Outcome::Unavailable => report.unavailable.push(check.name()),
871 // Judged nothing, said nothing: not a pass to count, not a gap
872 // to announce.
873 Outcome::Inert => {}
874 Outcome::Deferred => report.deferred.push((check.name(), severities.of(*check))),
875 Outcome::Skipped => report.skipped.push(check.name()),
876 Outcome::Failed => match severities.of(*check) {
877 Severity::Block => report.blocked.push(check.name()),
878 Severity::Warn => report.downgraded.push(check.name()),
879 },
880 }
881 }
882 report
883}
884
885/// Says what happened. Prints; decides nothing.
886fn announce(settings: &crate::config::Settings, report: &Report) {
887 if crate::live::quiet(settings) && report.passed > 0 {
888 println!("{} {} check(s) passed", valid_sign(), report.passed);
889 }
890 if !report.fixed.is_empty() {
891 // Louder than a pass, because files on disk are not what the author
892 // left them: they asked for the repair, but they did not watch it.
893 println!(
894 "{} {} check(s) fixed and re-staged: {}",
895 valid_sign(),
896 report.fixed.len(),
897 report.fixed.join(", ")
898 );
899 }
900 if !report.unavailable.is_empty() {
901 // Distinct from "passed". Silence here is how a repo looks verified
902 // when nothing actually ran — the trailing count is the one line
903 // guaranteed to be read, whatever the twenty blocks above said.
904 println!(
905 "{} {} check(s) could not run: {}",
906 warning_sign(),
907 report.unavailable.len(),
908 report.unavailable.join(", ")
909 );
910 }
911 if !report.deferred.is_empty() {
912 announce_deferred(&report.deferred);
913 }
914 if !report.downgraded.is_empty() {
915 println!(
916 "{} {} check(s) reported a problem but are set to warn: {}",
917 warning_sign(),
918 report.downgraded.len(),
919 report.downgraded.join(", ")
920 );
921 }
922 if !report.skipped.is_empty() {
923 announce_skipped(&report.skipped, &report.blocked);
924 }
925 if report.blocked.is_empty() {
926 return;
927 }
928 println!("\n🚨 Error raised by:");
929 for name in &report.blocked {
930 println!(" - {}", highlight(name));
931 }
932}
933
934/// Point every check at `git ls-files` instead of the index.
935///
936/// THE definition, called from both entry points. There used to be two: this
937/// one, and a copy in `main.rs` built from a RAW `ls-files` — no `-z` — whose
938/// output git QUOTES for any unusual byte, so `é.json` arrived as the nine-byte
939/// literal `"\303\251.json"` and was handed to prettier and eslint as a path
940/// that does not exist. And because `override_file_set` writes a `OnceLock`,
941/// main's quoted list WON: whichever ran first was the one that counted, and
942/// main's ran first. `git.rs` documents this exact failure.
943pub fn enter_all_files_mode() {
944 crate::hooks::common::override_file_set(
945 crate::git::stdout_paths(&["ls-files"]).unwrap_or_default(),
946 );
947}
948
949/// `amont run` — every applicable check, on demand.
950///
951/// Two questions, and the mode says which it answers:
952///
953/// - **staged** (default) is "would my commit pass" — the same set a commit
954/// would check, so it is a rehearsal of the hook, and it takes the same
955/// index-fidelity hold the hook takes.
956/// - **`--all-files`** is "does my working tree pass". Deliberately NOT the same
957/// question: on a dirty tree it reports on content that is not committed and
958/// may never be. That is right for adopting a check into an existing
959/// repository, where `git add .` is not an acceptable way to measure the mess,
960/// and it is why `--all-files` takes no stash — there is no staged/unstaged
961/// distinction to protect when the answer is "all of it".
962pub fn run_all(ctx: &Ctx, all_files: bool) -> Verdict {
963 let settings = ctx.settings;
964 // ORDER: the override goes in FIRST. It is what tells `fixing_enabled` and
965 // `restage` that the file set is not the index, and both are consulted
966 // from inside the checks below.
967 if all_files {
968 enter_all_files_mode();
969 if crate::hooks::common::fixing_requested(settings) {
970 println!(
971 "{} {} is set, but fixing is off for {}: the input set is the \
972 working tree, not the index",
973 warning_sign(),
974 highlight("greengate.fix"),
975 highlight("--all-files")
976 );
977 }
978 // Stash-free, per decision 1 of docs/index-fidelity-and-run-modes.md:
979 // there is no staged/unstaged distinction to protect when the input
980 // set is `git ls-files`, so a hold would be surprising extra mutation
981 // with no correctness upside.
982 return run_stage(
983 &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
984 ctx,
985 &Overrides::read(settings),
986 );
987 }
988
989 // Staged mode IS a rehearsal of the commit, so it takes the same hold the
990 // commit does. Without it, `amont run` failed on garbage in the tree
991 // that `git commit` — which holds the unstaged half aside — passed, and
992 // vice versa: the two modes disagreed about the same repository, which is
993 // exactly what this mode exists not to do.
994 let held = match hold_unstaged() {
995 Ok(guard) => guard,
996 Err(verdict) => return verdict,
997 };
998 let verdict = run_stage(
999 &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
1000 ctx,
1001 &Overrides::read(settings),
1002 );
1003 // AFTER the report has been printed: dropping earlier would put the
1004 // unstaged content back under a check that is still reading files.
1005 drop(held);
1006 verdict
1007}
1008
1009/// `amont run <check>` — one check by name. `None` when there is no such
1010/// check, which the caller turns into a usage error.
1011///
1012/// Lives here rather than in `main.rs` so `registry::lookup` stays inside the
1013/// runtime, and so the hold decision is made once: a named check takes the
1014/// index-fidelity hold only when it is a `Stage::PreCommit` check running in
1015/// staged mode. A pre-push or commit-msg check invoked by name must never
1016/// touch the working tree — nothing about a push is a staging operation.
1017/// Resolve what `amont run <name>` means, exactly as `hook.skip` resolves a
1018/// name — the rest of the tool taught `ban-terms`; making `run` demand the
1019/// full id was a pointless second vocabulary. Ambiguity is an answer, not a
1020/// guess: the two `branch-pattern` checks are different code at different
1021/// stages.
1022///
1023/// Public because the CALLER needs the answer before anything else happens:
1024/// main decides whether to synthesize push refs from the resolved name, and
1025/// an ambiguous name must say so rather than fail on a missing upstream it
1026/// was never going to use.
1027pub fn resolve_check_name(name: &str, manifest: &crate::manifest::Manifest) -> Named2 {
1028 if crate::registry::lookup(name, manifest).is_some() {
1029 return Named2::Resolved(name.to_string());
1030 }
1031 let mut matches: Vec<String> = crate::registry::CHECKS
1032 .iter()
1033 .map(|c| c.name.to_string())
1034 .chain(manifest.externals.iter().map(|e| e.id.clone()))
1035 .filter(|id| crate::skip_suppresses(id, name))
1036 .collect();
1037 matches.dedup();
1038 match matches.len() {
1039 0 => Named2::Unknown,
1040 1 => Named2::Resolved(matches.remove(0)),
1041 _ => Named2::Ambiguous(matches),
1042 }
1043}
1044
1045/// How a run name resolved.
1046pub enum Named2 {
1047 Resolved(String),
1048 Unknown,
1049 Ambiguous(Vec<String>),
1050}
1051
1052pub fn run_named(ctx: &Ctx, name: &str, all_files: bool) -> Named {
1053 let full: String = match resolve_check_name(name, ctx.manifest) {
1054 Named2::Resolved(id) => id,
1055 Named2::Unknown => return Named::Unknown,
1056 Named2::Ambiguous(ids) => return Named::Ambiguous(ids),
1057 };
1058 let name = full.as_str();
1059 let Some(run_check) = crate::registry::lookup(name, ctx.manifest) else {
1060 return Named::Unknown;
1061 };
1062 // The Ctx must carry the RESOLVED id: lookup's closure re-resolves
1063 // through `ctx.name`, and handing it the short name back would panic on
1064 // the very ambiguity this function just settled.
1065 let ctx = &Ctx {
1066 name,
1067 args: ctx.args,
1068 hooks_dir: ctx.hooks_dir,
1069 push: ctx.push,
1070 manifest: ctx.manifest,
1071 settings: ctx.settings,
1072 handed_to_cluster: ctx.handed_to_cluster,
1073 land: ctx.land,
1074 audits: ctx.audits,
1075 source_worktree: ctx.source_worktree,
1076 };
1077 // Under quiet, a check run by name is captured like one inside its stage
1078 // — one slot, its tool's output to a log, one line on a pass — whatever
1079 // `greengate.progress` says: the person who asked for quiet asked for this.
1080 let check = crate::registry::one_named(name, ctx.manifest);
1081 let run = |ctx: &Ctx| match check.filter(|_| crate::live::quiet(ctx.settings)) {
1082 Some(check) => run_quiet(ctx, check),
1083 None => run_check(ctx),
1084 };
1085 if all_files {
1086 enter_all_files_mode();
1087 return Named::Ran(run(ctx));
1088 }
1089 let is_pre_commit_check = check.is_some_and(|c| c.stage() == Stage::PreCommit);
1090 if !is_pre_commit_check {
1091 return Named::Ran(run(ctx));
1092 }
1093 let held = match hold_unstaged() {
1094 Ok(guard) => guard,
1095 Err(verdict) => return Named::Ran(verdict),
1096 };
1097 let verdict = run(ctx);
1098 drop(held);
1099 Named::Ran(verdict)
1100}
1101
1102/// One check by name, in a one-slot stage. The verdict is the one
1103/// `registry::lookup` gives a check: blocking only a failed `block` check.
1104/// Enter `check` for the host-slot bookkeeping: a heavy check whose severity
1105/// is `warn` never waits for a slot (`host_slots::never_waits`), except inside
1106/// a rehearsal snapshot, where no push connection is open, no commit waits,
1107/// and land's pre-stage needs the check's evidence: there it follows the
1108/// busy policy the rehearsal sets, except in land's pre-stage, where a `warn`
1109/// check waits at most `greengate.warnSlotWait` and then runs unqueued
1110/// (`host_slots::wait_bounded_for_warn`). Only a heavy check can wait, so only it
1111/// asks `severity`, which the caller answers from its stage's severity fold
1112/// when it has one: a git-config read per check broke the commit's git-spawn
1113/// budget.
1114fn enter(check: &dyn Check, severity: impl FnOnce() -> Severity) -> crate::host_slots::CheckGuard {
1115 let guard = crate::host_slots::enter_check(check.name(), check.weight());
1116 if check.weight() == crate::host_slots::Weight::Heavy {
1117 if !crate::rehearsal::in_snapshot() {
1118 if matches!(severity(), Severity::Warn) {
1119 crate::host_slots::never_waits();
1120 }
1121 } else if crate::rehearsal::in_prestage() && matches!(severity(), Severity::Warn) {
1122 crate::host_slots::wait_bounded_for_warn();
1123 }
1124 }
1125 guard
1126}
1127
1128fn run_quiet(ctx: &Ctx, check: &dyn Check) -> Verdict {
1129 let stage = crate::live::Stage::begin(ctx.settings, &[check.name()]);
1130 stage.named();
1131 let _sink = stage.enter(0);
1132 let flush = crate::live::FinishOnDrop::new(ctx.settings, &stage, 0);
1133 let outcome = {
1134 let slot = enter(check, || crate::registry::severity_of(ctx.settings, check));
1135 deferred_or(&slot, check.run(ctx))
1136 };
1137 flush.outcome(outcome);
1138 // The block prints here, before anything the caller says after it.
1139 drop(flush);
1140 // The same rule `registry::lookup` applies, with every variant named.
1141 let blocks = match outcome {
1142 Outcome::Failed => match crate::registry::severity_of(ctx.settings, check) {
1143 Severity::Block => true,
1144 Severity::Warn => false,
1145 },
1146 Outcome::Passed
1147 | Outcome::Warned
1148 | Outcome::Fixed
1149 | Outcome::Unavailable
1150 | Outcome::Inert
1151 | Outcome::Deferred
1152 | Outcome::Skipped => false,
1153 };
1154 Verdict::blocking(blocks)
1155}
1156
1157/// What `run_named` resolved a name to.
1158pub enum Named {
1159 Ran(Verdict),
1160 /// Nothing matches — full id, short name, or entrypoint.
1161 Unknown,
1162 /// A short name that reaches more than one check; the caller lists them
1163 /// so the user can pick a full id.
1164 Ambiguous(Vec<String>),
1165}
1166
1167/// Why a pre-push gate need not run in this push (ADR-0018: the refusal and
1168/// the loop ask the same question, through `pre_push`'s `decide`).
1169enum Skip {
1170 /// The rehearsal that made this snapshot gave it to the cluster.
1171 HandedToCluster,
1172 /// Its stamp, or its cluster token, is on every pushed tip.
1173 Stamped,
1174 /// It completed without passing on every pushed tip's tree, in a
1175 /// rehearsal or land's pre-stage (ADR-0018). Never a pass: it is not
1176 /// attested, and only a push that would otherwise refuse honours it.
1177 CompletedEarlier,
1178 /// Its commit-time twin was proved on the cluster for every tip.
1179 TwinOnCluster(String),
1180 /// Its commit-time pair covered the push; `coverage` says whether by every
1181 /// pushed commit's stamp or by the tips' own stamp keys (ADR-0019).
1182 GatedAtCommit {
1183 name: String,
1184 coverage: crate::hooks::run_tests::Coverage,
1185 },
1186 /// Its commit-time pair was deferred to CI on this many pushed commits.
1187 DeferredAtCommit(String, usize),
1188}
1189
1190/// What `decide` says about one gate: skip it, for a reason, or run it —
1191/// noting the commit-time pair that left this many pushed commits unstamped.
1192enum Decision {
1193 Skip(Skip),
1194 Run {
1195 unstamped_pair: Option<(String, usize)>,
1196 /// A same-named commit-time declaration that did not vouch, and why:
1197 /// the push says so before it runs the gate.
1198 unpaired: Option<(String, crate::hooks::run_tests::WhyNot)>,
1199 },
1200}
1201
1202/// `greengate.pushStamps`, as the refusal needs it: whether anything run before
1203/// the push can let it skip its gates.
1204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1205pub(crate) enum StampReuse {
1206 On,
1207 Off,
1208}
1209
1210/// The tag a push carries, if it pushes one: its refusal names
1211/// `amont land --tag`, since `amont land` alone pushes the branch.
1212fn pushed_tag(refs: &[crate::pushrefs::PushRef]) -> Option<&str> {
1213 refs.iter()
1214 .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
1215 .find_map(|r| r.remote_ref.strip_prefix("refs/tags/"))
1216}
1217
1218/// The bare push's refusal (ADR-0018), one command per line, each line at most
1219/// 80 columns, so each copies cleanly. With stamp reuse off, nothing amont can
1220/// run beforehand lets this push skip its gates, so `rehearse` is not
1221/// offered. A tag push is offered `amont land --tag`, never the branch
1222/// remedies, whose records do not answer for a release.
1223pub(crate) fn push_refusal(
1224 short: &str,
1225 missing: &[&str],
1226 reuse: StampReuse,
1227 tag: Option<&str>,
1228) -> Vec<String> {
1229 let mut out = vec![format!(
1230 "{BIN}: push refused: {} push gate{} {} not run on {short}:",
1231 missing.len(),
1232 if missing.len() == 1 { "" } else { "s" },
1233 if missing.len() == 1 { "has" } else { "have" },
1234 )];
1235 out.extend(wrap_names(missing));
1236 let land = match tag {
1237 Some(tag) => format!("{BIN} land --tag {tag}"),
1238 None => format!("{BIN} land"),
1239 };
1240 if reuse == StampReuse::Off {
1241 out.push(" stamp reuse is off (greengate.pushStamps false); turn it on:".to_string());
1242 out.push(" git config greengate.pushStamps true".to_string());
1243 out.push(" then run the gates before git connects, and push:".to_string());
1244 out.push(format!(" {land}"));
1245 } else {
1246 out.push(" run them before git connects, then push:".to_string());
1247 out.push(format!(" {land}"));
1248 if tag.is_none() {
1249 out.push(" or stamp this tree first:".to_string());
1250 out.push(format!(" {BIN} rehearse --wait"));
1251 }
1252 }
1253 out.push(" or run them in this push:".to_string());
1254 out.push(" git config greengate.pushGates inline".to_string());
1255 out
1256}
1257
1258/// The refusal inside `amont land`'s own push, led by the sentinel `land`
1259/// matches. `land` is what land's pre-stage saw: a pushed range whose remote
1260/// side differs is the remote moving under land; anything else is evidence
1261/// the pre-stage should have left and did not.
1262pub(crate) fn land_refusal(
1263 land: &crate::rehearsal::LandLine,
1264 refs: &[crate::pushrefs::PushRef],
1265 missing: &[&str],
1266) -> Vec<String> {
1267 let moved = refs
1268 .iter()
1269 .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
1270 .any(|r| r.remote_oid != land.remote_tip);
1271 let mut out = Vec::new();
1272 if moved {
1273 out.push(crate::land::LAND_REMOTE_MOVED.to_string());
1274 out.push(format!(
1275 "{BIN}: the remote moved during land; run {BIN} land again"
1276 ));
1277 } else {
1278 out.push(crate::land::LAND_EVIDENCE_MISSING.to_string());
1279 out.push(format!("{BIN}: land's pre-stage left no evidence for:"));
1280 }
1281 out.extend(wrap_names(missing));
1282 out
1283}
1284
1285/// Gate names as indented lines of at most 80 columns.
1286pub(crate) fn wrap_names(names: &[&str]) -> Vec<String> {
1287 let mut lines = Vec::new();
1288 let mut line = String::from(" ");
1289 for name in names {
1290 if line.len() + 1 + name.len() > 80 && !line.trim().is_empty() {
1291 lines.push(std::mem::replace(&mut line, String::from(" ")));
1292 }
1293 line.push(' ');
1294 line.push_str(name);
1295 }
1296 if !line.trim().is_empty() {
1297 lines.push(line);
1298 }
1299 lines
1300}
1301
1302pub fn pre_push(ctx: &Ctx) -> Verdict {
1303 let settings = ctx.settings;
1304 // `greengate.treeLintWait` counts from HERE, so no earlier wait (a test
1305 // rehearsal's `greengate.rehearsalWait`) can extend it.
1306 let push_started = std::time::Instant::now();
1307 // The notes push `attest` makes re-enters this hook; its ref list is only
1308 // ever the attest ref, so there is nothing to prove — and proving it
1309 // would recurse.
1310 if crate::attest::push_guard_active() {
1311 return Verdict::Proceed;
1312 }
1313 // Before the stamps are read: what a detached rehearsal finished while the
1314 // laptop was away counts at this push (ADR-0017). Not inside a rehearsal's
1315 // own snapshot, which stands in for a push that is not happening.
1316 if !crate::rehearsal::in_snapshot() {
1317 crate::cluster::collect_if_declared(ctx.manifest);
1318 }
1319 crate::manifest::verify_tool_pins(&ctx.manifest.pins, ctx.manifest.file_name());
1320 announce_policy_state(ctx.settings, ctx.manifest);
1321 // NB: no CHERRY_PICK_HEAD check here — the zsh pre-push had none either.
1322 let severities = Overrides::read(settings);
1323 // pre-push had NO state guard at all, with a comment admitting it existed
1324 // only because the zsh version had none. Now it asks the same question
1325 // pre-commit does and each check answers for itself.
1326 let in_progress = crate::git_states_in_progress();
1327 // Declared order unless this repository asked for the other one. The
1328 // permutation is decided BEFORE the live stage is begun, because the
1329 // stage draws the list in the order it is given.
1330 let pre_push_checks = ordered_by_evidence(
1331 settings,
1332 selected_during(ctx.settings, Stage::PrePush, &in_progress, ctx.manifest),
1333 );
1334 let stage = crate::live::enabled(settings).then(|| {
1335 let names: Vec<&str> = pre_push_checks.iter().map(|c| c.name()).collect();
1336 crate::live::Stage::begin(settings, &names)
1337 });
1338 // What actually PASSED, for the attestation at the bottom. `Warned` and
1339 // `Unavailable` stay out — "could not run" is not "passed" — and a
1340 // commit-time-gated pair counts, because its stamps say the check ran on
1341 // every pushed tree.
1342 let mut passed: Vec<String> = Vec::new();
1343 // Accumulated rather than written per check: one append at the end costs a
1344 // single file open, and the loop below can leave early.
1345 let mut downgraded: Vec<(String, crate::downgrade::Origin)> = Vec::new();
1346 // PUSH STAMPS. The tips being pushed, and what earlier runs of THIS gate
1347 // recorded against their trees — an `amont run pre-push` rehearsal, or a
1348 // push whose gate passed and whose transport then died. A scoped gate
1349 // (a test suite: its verdict is a function of the tree alone) whose
1350 // stamp sits on every tip is not run again; the unscoped ones
1351 // (branch-protect, secrets — questions about the push, not the content)
1352 // always run. `greengate.pushStamps false` turns the reuse off.
1353 //
1354 // Reading `ctx.push` here may consume stdin, exactly as `attest` does
1355 // below; every pre-push check reads it anyway.
1356 let tips: Vec<String> = {
1357 let mut t: Vec<String> = ctx
1358 .push
1359 .get()
1360 .iter()
1361 .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
1362 // An annotated tag pushes its tag object; what was tested, stamped
1363 // and recorded is the commit it points at (ADR-0018).
1364 .map(|r| {
1365 crate::git::stdout(&[
1366 "rev-parse",
1367 "--verify",
1368 "-q",
1369 &format!("{}^{{commit}}", r.local_oid),
1370 ])
1371 .unwrap_or_else(|| r.local_oid.clone())
1372 })
1373 .collect();
1374 t.sort_unstable();
1375 t.dedup();
1376 t
1377 };
1378 let reuse_stamps = crate::gate_stamp::push_stamps_enabled(settings);
1379 // The working tree AS THE SUITE WILL BE HANDED IT, captured before any
1380 // gate has run.
1381 //
1382 // Timing is the point. Asking afterwards means a gate that modifies a
1383 // tracked file — a formatter, a suite that updates a snapshot fixture —
1384 // disqualifies its OWN stamp. What a stamp needs to know is what the
1385 // suite could READ, which is the state it was handed; a change the suite
1386 // itself made was never an input to it.
1387 //
1388 // Tracked modifications only. `stamp_tips` argues that gap, which is a
1389 // deliberate one.
1390 //
1391 // Read whatever `reuse_stamps` says: the attestation asks it too (#289),
1392 // and an empty string here would read as a clean tree.
1393 let tree_at_start =
1394 crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"]).unwrap_or_default();
1395 // Inside a rehearsal snapshot only the content gates make sense: the
1396 // unscoped checks ask about a PUSH — its branch name, its target, its
1397 // secrets — and no push is happening. Said once, not per check.
1398 let rehearsing = crate::rehearsal::in_snapshot();
1399 let handed_to_cluster = ctx.handed_to_cluster;
1400 // The push `amont land` makes after its pre-stage ran the gates
1401 // (ADR-0018), as `<sha> <remote tip>`.
1402 let land = match ctx.land {
1403 crate::rehearsal::LandEnv::Absent => None,
1404 crate::rehearsal::LandEnv::Valid(line) => Some(line),
1405 crate::rehearsal::LandEnv::Malformed(raw) => {
1406 eprintln!(
1407 "{BIN}: push refused: {} is not `<sha> <remote tip>` ({raw:?})",
1408 crate::rehearsal::LAND_ENV
1409 );
1410 eprintln!(
1411 " unset it, then push again: unset {}",
1412 crate::rehearsal::LAND_ENV
1413 );
1414 return Verdict::Block;
1415 }
1416 };
1417 // ADR-0018: a heavy gate never runs while git holds the remote's
1418 // connection open, unless this machine asked for that
1419 // (`greengate.pushGates inline`). Land's own push expects its pre-stage's
1420 // evidence; a bare push under `refuse` (the default) refuses at once.
1421 // Neither waits for a background rehearsal: that wait would itself hold
1422 // the connection.
1423 let gate_before_push =
1424 !rehearsing && (land.is_some() || crate::rehearsal::refuse_push_gates(settings));
1425 // A background rehearsal of one of these tips may be mid-suite right
1426 // now. Waiting for it is strictly less work than starting over, and
1427 // its stamp — read AFTER the wait, below — is the hand-off.
1428 // Only when this push has test gates for the rehearsal to vouch for: a
1429 // rehearsal that is only proving tree lint is waited for by the tree
1430 // verdict alone, under its own `greengate.treeLintWait` (ADR-0024), never
1431 // under `greengate.rehearsalWait`.
1432 if reuse_stamps && !tips.is_empty() && !gate_before_push {
1433 let changed = crate::pushrefs::changed_files(ctx.push.get());
1434 if !scoped_push_gates(settings, ctx.manifest, &changed).is_empty() {
1435 crate::rehearsal::await_for(settings, &tips);
1436 }
1437 }
1438 let push_stamps = if reuse_stamps && !tips.is_empty() {
1439 crate::gate_stamp::stamps_for(&tips)
1440 } else {
1441 Default::default()
1442 };
1443 if rehearsing {
1444 crate::say!(
1445 "rehearsal: running the test gates only — the push-shaped checks run at push time"
1446 );
1447 }
1448 let stamped_on_every_tip = |name: &str| -> bool {
1449 // The complete token, or nothing: a gate whose identity cannot be
1450 // worked out is never skipped on a stamp.
1451 let Some(token) = crate::gate_identity::token(&ctx.manifest.externals, name) else {
1452 return false;
1453 };
1454 !tips.is_empty()
1455 && tips
1456 .iter()
1457 .all(|t| push_stamps.get(t).is_some_and(|s| s.contains(&token)))
1458 };
1459 // A trusted `platform=any` gate is also vouched for by its cluster token
1460 // on every tip's tree (ADR-0016). Asked only for such a gate, so a
1461 // repository with none pays no spawn.
1462 let cluster_stamped = |name: &str| -> bool {
1463 reuse_stamps
1464 && ctx
1465 .manifest
1466 .externals
1467 .iter()
1468 .find(|e| e.id == name)
1469 .is_some_and(|e| crate::cluster::vouched_on_every(settings, e, &tips))
1470 };
1471 // Why a gate need not run in this push, or that it must. ONE function,
1472 // asked by the loop below and by the refusal before it, so a gate the
1473 // loop would skip is never refused, and one it would run never passes
1474 // the refusal (ADR-0018).
1475 let decide = |check: &dyn Check| -> Decision {
1476 // Handed to the cluster by the rehearsal that made this snapshot: not
1477 // repeated here, its pass comes back as a cluster token.
1478 if rehearsing && handed_to_cluster.iter().any(|gate| gate == check.name()) {
1479 return Decision::Skip(Skip::HandedToCluster);
1480 }
1481 // A dependency audit is never skipped: its verdict depends on the
1482 // day's advisories and the push's stakes, so it replays a fresh
1483 // record instead, inside the check (ADR-0018).
1484 if crate::hooks::audit::is_audit(check.name()) {
1485 return Decision::Run {
1486 unstamped_pair: None,
1487 unpaired: None,
1488 };
1489 }
1490 if stamped_push_gate(check)
1491 && (stamped_on_every_tip(check.name()) || cluster_stamped(check.name()))
1492 {
1493 return Decision::Skip(Skip::Stamped);
1494 }
1495 if gate_before_push && reuse_stamps && stamped_push_gate(check) {
1496 let done = crate::gate_identity::token(&ctx.manifest.externals, check.name())
1497 .is_some_and(|token| {
1498 crate::gate_stamp::done_on_every(&tips, &token, severities.of(check))
1499 });
1500 if done {
1501 return Decision::Skip(Skip::CompletedEarlier);
1502 }
1503 }
1504 let declared = ctx
1505 .manifest
1506 .externals
1507 .iter()
1508 .find(|e| e.stage == Stage::PrePush && e.id == check.name());
1509 // A `platform=any` push gate whose commit twin declares the same suite
1510 // and was proved on the cluster on every tip's tree is gated at commit
1511 // too, and counts as a cluster pass under its own id (ADR-0016).
1512 if let Some(push_gate) = declared.filter(|_| reuse_stamps) {
1513 let claimed_from_twin = ctx
1514 .manifest
1515 .externals
1516 .iter()
1517 .filter(|e| e.stage == Stage::PreCommit && e.short_name == push_gate.short_name)
1518 .any(|twin| {
1519 crate::cluster::claim_twin_cluster_pass(settings, push_gate, twin, &tips)
1520 });
1521 if claimed_from_twin {
1522 return Decision::Skip(Skip::TwinOnCluster(push_gate.short_name.clone()));
1523 }
1524 }
1525 // The push side of a pair is `(name, scope)`, from whichever of the
1526 // two kinds of check this is. A declared pre-push external supplies
1527 // its own; anything else is a BUILT-IN, and `pairing_name` plus the
1528 // registry's scope say the same two things about it.
1529 let builtin_scope = check.scope();
1530 let pairing: Option<(&str, &crate::check::Scope)> = match declared {
1531 Some(ext) => match &ext.kind {
1532 crate::manifest::Kind::Runnable { scope, .. } => {
1533 Some((ext.short_name.as_str(), scope))
1534 }
1535 // A declared pre-push entry that runs nothing has no scope to
1536 // judge with, and is not a built-in either. Nothing to pair.
1537 _ => None,
1538 },
1539 None => Some((check.pairing_name(), &builtin_scope)),
1540 };
1541 let Some((name, push_scope)) = pairing else {
1542 return Decision::Run {
1543 unstamped_pair: None,
1544 unpaired: None,
1545 };
1546 };
1547 match crate::hooks::run_tests::pair_verdict(
1548 ctx.settings,
1549 name,
1550 push_scope,
1551 ctx.manifest,
1552 ctx.push,
1553 ) {
1554 crate::hooks::run_tests::PairVerdict::Gated(coverage) => {
1555 Decision::Skip(Skip::GatedAtCommit {
1556 name: name.to_string(),
1557 coverage,
1558 })
1559 }
1560 crate::hooks::run_tests::PairVerdict::Deferred(n) => {
1561 Decision::Skip(Skip::DeferredAtCommit(name.to_string(), n))
1562 }
1563 crate::hooks::run_tests::PairVerdict::Unstamped(n) => Decision::Run {
1564 unstamped_pair: Some((name.to_string(), n)),
1565 unpaired: None,
1566 },
1567 crate::hooks::run_tests::PairVerdict::NotPaired(why) => Decision::Run {
1568 unstamped_pair: None,
1569 unpaired: why.map(|why| (name.to_string(), why)),
1570 },
1571 }
1572 };
1573 // The question `amont list` answers with "inert here — needs go.sum",
1574 // asked of the index once (see the loop below).
1575 let tracked = crate::tracked_paths();
1576 // ADR-0018: refuse before any heavy gate starts. The gates this push
1577 // owes are the scoped ones its range touches (`scoped_push_gates`, the
1578 // same set a rehearsal stamps); each is asked `decide`, and any it would
1579 // have to RUN means the push refuses.
1580 if gate_before_push && !tips.is_empty() {
1581 let changed = crate::pushrefs::changed_files(ctx.push.get());
1582 let owed = scoped_push_gates(settings, ctx.manifest, &changed);
1583 // Why each owed gate would run, kept from the one `decide` that found
1584 // it missing: the reasons are printed ahead of the refusal without
1585 // asking the gate a second time.
1586 let reasons: std::cell::RefCell<Vec<(String, crate::hooks::run_tests::WhyNot)>> =
1587 std::cell::RefCell::new(Vec::new());
1588 let missing: Vec<&str> = pre_push_checks
1589 .iter()
1590 .filter(|c| {
1591 if crate::hooks::audit::is_audit(c.name()) {
1592 // Owed on every push it is opted into, whatever the
1593 // range touches, unless a fresh record answers for it.
1594 c.scope().opted_in(&tracked)
1595 && crate::hooks::audit::owed(settings, ctx.audits, c.name(), ctx.push.get())
1596 } else {
1597 // A declared command whose program is not installed can
1598 // never be stamped or recorded, so no pre-stage could
1599 // answer for it: owing it would refuse every push for
1600 // good. It runs below instead, fails to start, and warns,
1601 // as before 2.0. Only that: a gate whose token failed for
1602 // another reason stays owed.
1603 owed.iter().any(|o| o == c.name())
1604 && !crate::gate_identity::program_missing(&ctx.manifest.externals, c.name())
1605 && match decide(**c) {
1606 Decision::Run { unpaired, .. } => {
1607 reasons.borrow_mut().extend(unpaired);
1608 true
1609 }
1610 Decision::Skip(_) => false,
1611 }
1612 }
1613 })
1614 .map(|c| c.name())
1615 .collect();
1616 if !missing.is_empty() {
1617 let short: String = tips
1618 .first()
1619 .map(|t| t.chars().take(8).collect())
1620 .unwrap_or_default();
1621 // Why a pair did not vouch comes BEFORE the refusal: refusing is the
1622 // default for a bare push, so a refused push is where a silent
1623 // "it would have run the suite again" went unexplained.
1624 for (name, why) in reasons.borrow().iter() {
1625 crate::hooks::run_tests::say_why_not(name, why);
1626 }
1627 let lines = match land {
1628 Some(line) => land_refusal(line, ctx.push.get(), &missing),
1629 None => push_refusal(
1630 &short,
1631 &missing,
1632 if reuse_stamps {
1633 StampReuse::On
1634 } else {
1635 StampReuse::Off
1636 },
1637 pushed_tag(ctx.push.get()),
1638 ),
1639 };
1640 for line in lines {
1641 eprintln!("{line}");
1642 }
1643 return Verdict::Block;
1644 }
1645 }
1646 // What actually RAN and passed here (as opposed to being vouched for by
1647 // a stamp) — the set this run may stamp in turn.
1648 let mut ran_and_passed: Vec<String> = Vec::new();
1649 // Scoped gates that RAN here and completed without passing — a warning,
1650 // or a tool that was missing (ADR-0018): recorded beside the stamps, never
1651 // as one, so a refusing push does not ask for them again.
1652 let mut completed_otherwise: Vec<(String, crate::gate_stamp::Completion)> = Vec::new();
1653 // What each gate COST and how it ENDED, for the record `gate_evidence`
1654 // reads. Every outcome, failures included: the stamp deliberately has no
1655 // opinion about a gate that failed, and a dataset that kept only the
1656 // passes could never say a gate is flaky.
1657 let mut evidence: Vec<crate::gate_stamp::Run> = Vec::new();
1658 // The question `amont list` answers with "inert here — needs go.sum":
1659 // does this repository carry the marker that turns the check on? Asked
1660 // of the index, once, and answered the same way here — a check the
1661 // registry calls inert used to run anyway, find its tool or lockfile
1662 // missing, and warn that it "could not run" on every push of a
1663 // repository it was never meant to touch.
1664 // Inside a rehearsal a heavy gate hands its slot to the next one; the
1665 // scope releases what is parked on every way out of this function.
1666 let park = crate::host_slots::ParkScope::begin();
1667 for (idx, check) in pre_push_checks.iter().enumerate() {
1668 if !check.scope().opted_in(&tracked) {
1669 continue;
1670 }
1671 let _sink = stage.as_ref().map(|s| s.enter(idx));
1672 let flush = stage
1673 .as_ref()
1674 .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, idx));
1675 // A declared pre-push external whose NAME is also declared at
1676 // pre-commit (blocking) is a gate pair: the commit-time side earned
1677 // per-commit stamps, and this side runs only for pushes carrying
1678 // commits with no record of it — the same contract the npm gate has
1679 // always had, for vocabularies npm never heard of (`cargo test`,
1680 // `pytest`, anything). Messages mirror the npm gate's exactly;
1681 // docs/checks.md quotes them. `decide` holds the reasoning, shared
1682 // with the refusal above.
1683 // The dependency audits are unscoped too (opted in by a lockfile,
1684 // with no file scope), but a rehearsal is exactly where their record
1685 // is earned (ADR-0018), so they run here.
1686 if rehearsing && !stamped_push_gate(*check) && !crate::hooks::audit::is_audit(check.name())
1687 {
1688 continue;
1689 }
1690 // A push of deletions only (or of no ref at all: git ran the hook
1691 // with nothing to push) has no commit for an audit to answer for, and
1692 // running one would hold the connection open for nothing (ADR-0018).
1693 if gate_before_push && tips.is_empty() && crate::hooks::audit::is_audit(check.name()) {
1694 continue;
1695 }
1696 match decide(*check) {
1697 Decision::Skip(Skip::HandedToCluster) => {
1698 crate::say!(
1699 "{} {} runs on the cluster — the next commit or push collects it",
1700 valid_sign(),
1701 highlight(check.name()),
1702 );
1703 continue;
1704 }
1705 Decision::Skip(Skip::Stamped) => {
1706 crate::say!(
1707 "{} {} passed on this exact tree earlier — not repeating it here",
1708 valid_sign(),
1709 highlight(check.name()),
1710 );
1711 passed.push(check.name().to_string());
1712 continue;
1713 }
1714 Decision::Skip(Skip::CompletedEarlier) => {
1715 crate::say!(
1716 "{} {} ran on this tree earlier and did not pass cleanly (it warned or \
1717 could not run) — not repeating it here",
1718 warning_sign(),
1719 highlight(check.name()),
1720 );
1721 continue;
1722 }
1723 Decision::Skip(Skip::TwinOnCluster(short)) => {
1724 crate::say!(
1725 "{} {} gated at commit on the cluster instead — not repeating it here",
1726 valid_sign(),
1727 highlight(&short),
1728 );
1729 passed.push(check.name().to_string());
1730 continue;
1731 }
1732 Decision::Skip(Skip::GatedAtCommit { name, coverage }) => {
1733 crate::say!(
1734 "{} {} gated at commit instead — not repeating it here",
1735 valid_sign(),
1736 highlight(&name),
1737 );
1738 // A second line only when a TIP vouched alone: the plain line
1739 // has always meant "every pushed commit carries its stamp",
1740 // and a reader who pushed an unstamped commit deserves to see
1741 // what the skip rests on. Its own line, so the first stays
1742 // within 80 columns; "the code at", because a plans-only tip
1743 // never ran the gate itself — its canonical tree did.
1744 if let crate::hooks::run_tests::Coverage::Tips(tips) = coverage {
1745 crate::say!(" the code at tip {} passed at commit", tips.join(", "));
1746 }
1747 passed.push(check.name().to_string());
1748 continue;
1749 }
1750 Decision::Skip(Skip::DeferredAtCommit(name, n)) => {
1751 crate::say!(
1752 "{} {} was deferred to CI at commit on {n} pushed commit{} \
1753 — deferring it here too",
1754 warning_sign(),
1755 highlight(&name),
1756 if n == 1 { "" } else { "s" },
1757 );
1758 evidence.push(crate::gate_stamp::Run {
1759 at: crate::gate_evidence::now(),
1760 gate: check.name().to_string(),
1761 outcome: crate::gate_stamp::RunOutcome::Deferred,
1762 ms: 0,
1763 });
1764 continue;
1765 }
1766 Decision::Run {
1767 unstamped_pair: Some((name, n)),
1768 ..
1769 } => {
1770 // `greengate.unstampedPush refuse`: never run a suite with
1771 // the remote's connection held open — say how to earn
1772 // the stamp instead. Not inside a rehearsal snapshot:
1773 // running there is how the stamp is earned.
1774 if !rehearsing && crate::rehearsal::refuse_unstamped(ctx.settings) {
1775 crate::say!(
1776 "{} {} is declared at commit time, but {n} pushed \
1777 commit{} carr{} no record of it (rewritten by a \
1778 rebase or amend, or made without the hooks) — \
1779 refusing the push",
1780 warning_sign(),
1781 name,
1782 if n == 1 { "" } else { "s" },
1783 if n == 1 { "ies" } else { "y" },
1784 );
1785 crate::say!(
1786 " Test this tree first, with no push waiting on it: {} — then push again",
1787 highlight(&format!("{BIN} rehearse --wait")),
1788 );
1789 crate::downgrade::note(settings, &downgraded);
1790 record_evidence(&tips, &evidence);
1791 println!("\n🚨 Error raised by hook {}", highlight(check.name()));
1792 return Verdict::Block;
1793 }
1794 crate::say!(
1795 "{} {} is declared at commit time, but {n} pushed \
1796 commit{} carr{} no record of it — running it here",
1797 warning_sign(),
1798 name,
1799 if n == 1 { "" } else { "s" },
1800 if n == 1 { "ies" } else { "y" },
1801 );
1802 }
1803 Decision::Run {
1804 unstamped_pair: None,
1805 unpaired,
1806 } => {
1807 if let Some((name, why)) = unpaired {
1808 crate::hooks::run_tests::say_why_not(&name, &why);
1809 }
1810 }
1811 }
1812 let sub = Ctx {
1813 name: check.name(),
1814 args: ctx.args,
1815 hooks_dir: ctx.hooks_dir,
1816 push: ctx.push,
1817 manifest: ctx.manifest,
1818 settings: ctx.settings,
1819 handed_to_cluster: ctx.handed_to_cluster,
1820 land: ctx.land,
1821 audits: ctx.audits,
1822 source_worktree: ctx.source_worktree,
1823 };
1824 // Wall clock around the check itself, not around the hook: the number
1825 // that catches a suite which stopped finding tests is how long THAT
1826 // gate took, and everything outside this call is bookkeeping.
1827 let started = std::time::Instant::now();
1828 let mut severity_read: Option<Severity> = None;
1829 let slot = enter(*check, || {
1830 let severity = crate::registry::severity_of(ctx.settings, *check);
1831 severity_read = Some(severity);
1832 severity
1833 });
1834 let outcome = deferred_or(&slot, check.run(&sub));
1835 if let Some(f) = &flush {
1836 f.outcome(outcome);
1837 }
1838 let ran = started.elapsed().saturating_sub(slot.queued());
1839 drop(slot);
1840 evidence.push(crate::gate_stamp::Run {
1841 at: crate::gate_evidence::now(),
1842 gate: check.name().to_string(),
1843 outcome: run_outcome(outcome),
1844 ms: ran.as_millis().min(u128::from(u64::MAX)) as u64,
1845 });
1846 match outcome {
1847 Outcome::Passed => {
1848 passed.push(check.name().to_string());
1849 // An audit's pass is a record of its report, never a stamp.
1850 if stamped_push_gate(*check) {
1851 ran_and_passed.push(check.name().to_string());
1852 }
1853 }
1854 // Announced, never fatal: a check that could not run has not
1855 // invalidated anything, and neither has a warning.
1856 Outcome::Unavailable => {
1857 if stamped_push_gate(*check) {
1858 completed_otherwise.push((
1859 check.name().to_string(),
1860 crate::gate_stamp::Completion::Unavailable,
1861 ));
1862 }
1863 println!(
1864 "{} {} could not run",
1865 warning_sign(),
1866 highlight(check.name())
1867 )
1868 }
1869 Outcome::Warned => {
1870 if stamped_push_gate(*check) {
1871 completed_otherwise.push((
1872 check.name().to_string(),
1873 crate::gate_stamp::Completion::Warned,
1874 ));
1875 }
1876 }
1877 // Not run, never fatal, never passed: CI runs it (ADR-0013).
1878 Outcome::Deferred => announce_deferred(&[(
1879 check.name(),
1880 severity_read.unwrap_or_else(|| crate::registry::severity_of(ctx.settings, *check)),
1881 )]),
1882 // Nothing to judge: not passed (nothing to stamp or attest), not
1883 // a gap (nothing is missing). The dispatcher asked the registry's
1884 // opt-in question above; this is a check answering it for itself.
1885 Outcome::Inert => {}
1886 // Cannot occur: `Fix::Rewrite` is refused on a pre-push
1887 // declaration, so nothing here can repair anything.
1888 Outcome::Fixed => {}
1889 // Cannot occur: pre-push is serial and stops at the first failure
1890 // on its own; only pre-commit's waves skip (ADR-0020).
1891 Outcome::Skipped => {}
1892 Outcome::Failed => match severities.of(*check) {
1893 Severity::Warn => {
1894 if stamped_push_gate(*check) {
1895 completed_otherwise.push((
1896 check.name().to_string(),
1897 crate::gate_stamp::Completion::FailedUnderWarn,
1898 ));
1899 }
1900 downgraded.push((
1901 check.name().to_string(),
1902 downgrade_origin(*check, &severities),
1903 ));
1904 println!(
1905 "{} {} reported a problem (severity warn)",
1906 warning_sign(),
1907 highlight(check.name())
1908 );
1909 }
1910 // Fail-fast applies ONLY to Block: the later steps are
1911 // expensive and their preconditions are gone.
1912 Severity::Block => {
1913 // Record what already warned before leaving. Those checks
1914 // ran and reported; a later check blocking does not unmake
1915 // them, and dropping them here would make the ledger quietly
1916 // under-count every push that ended badly.
1917 crate::downgrade::note(settings, &downgraded);
1918 // The same argument for the evidence, and it matters more
1919 // here: this is the path a FAILURE leaves by, and a record
1920 // written only on the way out of a successful push would
1921 // be a dataset of passes calling itself a dataset of runs.
1922 record_evidence(&tips, &evidence);
1923 println!("\n🚨 Error raised by hook {}", highlight(check.name()));
1924 return Verdict::Block;
1925 }
1926 },
1927 }
1928 }
1929 drop(park);
1930 // Every block gate passed — stamp the tips with the scoped gates that
1931 // RAN here, so the next push of this content (a retry after a dropped
1932 // connection, or the real push after an `amont run pre-push` rehearsal)
1933 // skips them. Only when what ran is what is being pushed: with
1934 // `greengate.testPushedTree` the suite ran on the tip itself — unless the
1935 // snapshot could not be made, which `stamp_tips` asks about rather than
1936 // assuming; otherwise it ran on the working tree, which vouches for the
1937 // tip only when the two are the same content — HEAD, with nothing
1938 // modified and nothing untracked.
1939 // The same proxy `attestable` uses, for the same reason: a scoped gate
1940 // whose files the push never touched returns `Passed` having run
1941 // nothing, and a stamp for THAT would let a later push that does touch
1942 // them skip a suite nobody ran.
1943 if reuse_stamps && !ran_and_passed.is_empty() {
1944 let changed = crate::pushrefs::changed_files(ctx.push.get());
1945 let really_ran: Vec<String> = pre_push_checks
1946 .iter()
1947 .filter(|c| ran_and_passed.iter().any(|p| p == c.name()))
1948 .filter(|c| c.scope().touches(&changed))
1949 .map(|c| c.name().to_string())
1950 .collect();
1951 stamp_tips(&ctx.manifest.externals, &tips, &really_ran, &tree_at_start);
1952 }
1953 record_audits(ctx.audits, &tree_at_start);
1954 if reuse_stamps && !completed_otherwise.is_empty() {
1955 let changed = crate::pushrefs::changed_files(ctx.push.get());
1956 let really_ran: Vec<(String, crate::gate_stamp::Completion)> = completed_otherwise
1957 .into_iter()
1958 .filter(|(name, _)| {
1959 pre_push_checks
1960 .iter()
1961 .any(|c| c.name() == name && c.scope().touches(&changed))
1962 })
1963 .collect();
1964 record_completions(&ctx.manifest.externals, &tips, &really_ran, &tree_at_start);
1965 }
1966 // …and say so to CI, if this repository opted in.
1967 // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
1968 // `ctx.push` may consume stdin, and a disabled repo should leave stdin
1969 // exactly as it found it.
1970 // Tree gates (ADR-0024) are not push checks: nothing runs here. Each is
1971 // attested only when the TREE of every pushed tip carries its commit-time
1972 // proof; a whole-tree proof needs no changed-files scope. Fail-closed:
1973 // anything else is simply not attested, and CI lints.
1974 let (tree_proven, tree_unproven) =
1975 if !ctx.manifest.tree.is_empty() && crate::attest::enabled(settings) {
1976 crate::tree_lint::await_verdict(settings, &ctx.manifest.tree, &tips, push_started)
1977 } else {
1978 (Vec::new(), Vec::new())
1979 };
1980 if !tree_unproven.is_empty() {
1981 crate::hooks::common::say(&crate::tree_lint::fit_line(
1982 " lint not attested (cold or changed tree): ",
1983 &tree_unproven.join(" "),
1984 " — CI will lint",
1985 ));
1986 }
1987 if (!passed.is_empty() || !tree_proven.is_empty()) && crate::attest::enabled(settings) {
1988 let remote = ctx
1989 .args
1990 .first()
1991 .map(|a| a.to_string_lossy().into_owned())
1992 .unwrap_or_default();
1993 let changed = crate::pushrefs::changed_files(ctx.push.get());
1994 // Only local passes enter the laptop's attestation (ADR-0016); the
1995 // cluster's go to the linux block, which `attest_push` narrows per tip
1996 // to the trees the cluster actually judged.
1997 let (cluster_passed, local): (Vec<String>, Vec<String>) = passed
1998 .iter()
1999 .cloned()
2000 .partition(|p| crate::cluster::proved_anywhere(p));
2001 let vouched = attestable(&pre_push_checks, &local, &changed);
2002 let cluster_vouched = attestable(&pre_push_checks, &cluster_passed, &changed);
2003 // Per tip, the gates whose run saw that tip's content: the working
2004 // tree was the tip when they started, or they ran in a checkout of it
2005 // (#289; the rule `stamp_tips` applies). A tree gate's proof is the
2006 // tree's own commit-time record, so it needs no witness.
2007 let witness = TipWitness::new(&tree_at_start);
2008 let gates_for = |tip: &str| -> Vec<String> {
2009 vouched
2010 .iter()
2011 .filter(|g| witness.vouches(g, tip))
2012 .chain(tree_proven.iter())
2013 .cloned()
2014 .collect()
2015 };
2016 crate::attest::attest_push_per_tip(
2017 ctx.settings,
2018 &remote,
2019 ctx.push.get(),
2020 &gates_for,
2021 &cluster_vouched,
2022 );
2023 }
2024 // Outside the `passed` branch above on purpose: a push that changes only
2025 // documentation or its plan still carries a plan and a review to record.
2026 // holds-until: a dispatch-level test drives a push where no gate passed;
2027 // until one exists, moving this call inside that branch fails no test.
2028 if crate::attest::enabled(settings) {
2029 let remote = ctx
2030 .args
2031 .first()
2032 .map(|a| a.to_string_lossy().into_owned())
2033 .unwrap_or_default();
2034 crate::attest::provenance_push(ctx.settings, &remote, ctx.push.get());
2035 }
2036 crate::downgrade::note(settings, &downgraded);
2037 record_evidence(&tips, &evidence);
2038 Verdict::Proceed
2039}
2040
2041/// What one check's outcome is called in the record.
2042fn run_outcome(outcome: Outcome) -> crate::gate_stamp::RunOutcome {
2043 use crate::gate_stamp::RunOutcome as R;
2044 match outcome {
2045 Outcome::Passed => R::Passed,
2046 Outcome::Failed => R::Failed,
2047 Outcome::Warned => R::Warned,
2048 Outcome::Fixed => R::Fixed,
2049 Outcome::Unavailable => R::Unavailable,
2050 Outcome::Inert => R::Inert,
2051 Outcome::Deferred => R::Deferred,
2052 // Never produced at pre-push (ADR-0020); were it, it judged nothing.
2053 Outcome::Skipped => R::Inert,
2054 }
2055}
2056
2057/// The check's outcome, unless the busy policy deferred it: then Deferred,
2058/// whatever the check made of its refused spawn (ADR-0013).
2059fn deferred_or(slot: &crate::host_slots::CheckGuard, outcome: Outcome) -> Outcome {
2060 if slot.deferred().is_some() {
2061 Outcome::Deferred
2062 } else {
2063 outcome
2064 }
2065}
2066
2067/// The Heavy checks a blocking Light failure kept from starting (ADR-0020),
2068/// what blocked, and how to run each one now: `amont run` takes one name, so
2069/// one line per check, each short enough for an 80-column terminal.
2070fn announce_skipped(names: &[&str], blocked_by: &[&str]) {
2071 let names_list = names
2072 .iter()
2073 .map(|n| highlight(n))
2074 .collect::<Vec<_>>()
2075 .join(", ");
2076 match blocked_by {
2077 [one] => println!(
2078 "{} {} check(s) skipped because {} failed: {names_list}",
2079 crate::ui::skipped_sign(),
2080 names.len(),
2081 highlight(one),
2082 ),
2083 _ => println!(
2084 "{} {} check(s) skipped, a blocking check failed: {names_list}",
2085 crate::ui::skipped_sign(),
2086 names.len(),
2087 ),
2088 }
2089 println!(" fix the failures above and commit again; to run one now:");
2090 for n in names {
2091 println!(" {}", highlight(&format!("{BIN} run {n}")));
2092 }
2093}
2094
2095/// The deferral roll-up: which checks, then how to run each now and how to
2096/// stop deferring. Printed in quiet mode too, like `could not run`: a gate
2097/// skipped without a word looks exactly like a pass. Each deferred check is
2098/// advised the command that waits for its slot; the `onBusy wait` hint is
2099/// offered only for `block` checks, since a `warn` check never waits on a
2100/// commit or a push and the hint cannot stop it deferring there.
2101fn announce_deferred(deferred: &[(&str, Severity)]) {
2102 for line in deferral_advice(deferred) {
2103 println!("{line}");
2104 }
2105}
2106
2107/// The lines [`announce_deferred`] prints: the roll-up, then one `run now:`
2108/// command per deferred check (`amont run` takes one check by name, and a
2109/// `--raw` run waits for its slot under `GREENGATE_ON_BUSY=wait`, warn or block),
2110/// then the `onBusy wait` hint only when a `block` check is in the list,
2111/// since only a `block` check stops deferring under it.
2112fn deferral_advice(deferred: &[(&str, Severity)]) -> Vec<String> {
2113 let names: Vec<&str> = deferred.iter().map(|(name, _)| *name).collect();
2114 let mut lines = vec![format!(
2115 "{} {} check(s) deferred to CI, no host slot freed: {}",
2116 warning_sign(),
2117 names.len(),
2118 names.join(", ")
2119 )];
2120 let mut any_block = false;
2121 for (name, severity) in deferred {
2122 match severity {
2123 Severity::Block => any_block = true,
2124 Severity::Warn => {}
2125 }
2126 lines.push(format!(
2127 " run now: {}",
2128 highlight(&format!("GREENGATE_ON_BUSY=wait {BIN} run --raw {name}"))
2129 ));
2130 }
2131 if any_block {
2132 lines.push(format!(
2133 " stop deferring the block checks: {}",
2134 highlight("set onBusy wait")
2135 ));
2136 }
2137 lines
2138}
2139
2140/// File this push's runs under the content they judged.
2141///
2142/// ONE key, not one per tip: a push of two branches ran each gate once, and
2143/// writing the same run onto both trees would make a report count it twice.
2144/// The first tip's tree is that key, falling back to `HEAD` — and to nothing
2145/// at all when git will not name either, which costs a row in a report and
2146/// never a verdict.
2147fn record_evidence(tips: &[String], runs: &[crate::gate_stamp::Run]) {
2148 if runs.is_empty() {
2149 return;
2150 }
2151 let tree = tips
2152 .first()
2153 .and_then(|tip| crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]))
2154 .or_else(|| crate::git::stdout(&["rev-parse", "HEAD^{tree}"]));
2155 if let Some(tree) = tree {
2156 crate::gate_stamp::record_runs(&tree, runs);
2157 }
2158}
2159
2160/// Is `check` a push gate that runs before git connects, and is stamped for
2161/// it (ADR-0018)? A scoped one, or a declared `heavy` one whatever its scope:
2162/// a `*` declaration can be any command, and one that runs for a minute on
2163/// the open connection is the failure ADR-0018 exists to stop (#414). The
2164/// built-in unscoped checks (branch-protect, secrets) are light and need the
2165/// push's own refs, so they stay in the hook; the dependency audits answer
2166/// through their own record.
2167pub fn stamped_push_gate(check: &dyn Check) -> bool {
2168 !crate::hooks::audit::is_audit(check.name())
2169 && (!check.scope().is_unscoped() || check.weight() == crate::host_slots::Weight::Heavy)
2170}
2171
2172/// The stamped pre-push gates ([`stamped_push_gate`]) — test suites, and
2173/// declared heavy gates — that have work to do for a push that changed
2174/// `changed`: what a rehearsal would run, and therefore what its stamp would
2175/// have to name before a push may skip anything.
2176///
2177/// The same two filters `pre_push` applies before stamping (selected here,
2178/// and `scope().touches` the change), so the rehearsal's idea of "nothing to
2179/// do" is the push's idea of "nothing to stamp".
2180pub fn scoped_push_gates(
2181 settings: &crate::config::Settings,
2182 manifest: &crate::manifest::Manifest,
2183 changed: &[String],
2184) -> Vec<String> {
2185 let in_progress = crate::git_states_in_progress();
2186 let tracked = crate::tracked_paths();
2187 selected_during(settings, Stage::PrePush, &in_progress, manifest)
2188 .into_iter()
2189 .filter(|c| stamped_push_gate(*c) && c.scope().touches(changed))
2190 // The same opt-in gate `pre_push` applies: a suite the repository
2191 // never turned on is not work a rehearsal owes a stamp for.
2192 .filter(|c| c.scope().opted_in(&tracked))
2193 .map(|c| c.name().to_string())
2194 .collect()
2195}
2196
2197/// The dependency audits a push of `refs` owes (ADR-0018): opted in, and
2198/// with no fresh record for the pushed commits in the push's mode. Owed
2199/// whatever the range touches, unlike `scoped_push_gates`.
2200pub fn owed_audits(
2201 settings: &crate::config::Settings,
2202 manifest: &crate::manifest::Manifest,
2203 ledger: &crate::hooks::audit::Ledger,
2204 refs: &[crate::pushrefs::PushRef],
2205) -> Vec<String> {
2206 let in_progress = crate::git_states_in_progress();
2207 let tracked = crate::tracked_paths();
2208 selected_during(settings, Stage::PrePush, &in_progress, manifest)
2209 .into_iter()
2210 .filter(|c| crate::hooks::audit::is_audit(c.name()))
2211 .filter(|c| c.scope().opted_in(&tracked))
2212 .filter(|c| crate::hooks::audit::owed(settings, ledger, c.name(), refs))
2213 .map(|c| c.name().to_string())
2214 .collect()
2215}
2216
2217/// Push-stamp every tip whose content is what the gates actually tested.
2218///
2219/// See the comment at the call site for the two cases. Silent when nothing
2220/// qualifies — a dirty working tree is the ordinary state of a machine
2221/// mid-work, and a note on every push would teach people to ignore it.
2222fn stamp_tips(
2223 externals: &[crate::manifest::External],
2224 tips: &[String],
2225 gates: &[String],
2226 tree_at_start: &str,
2227) {
2228 let witness = TipWitness::new(tree_at_start);
2229 // TRACKED modifications only — a KNOWN gap, kept deliberately, and
2230 // spelled out because the comment that used to sit here argued it
2231 // backwards ("untracked files are not in any tree the suite could have
2232 // been asked about"). That is not the reason. The danger is not that the
2233 // tree lacks them, it is that the RUN had them: a new test file, a
2234 // fixture, a local `.env`, present while the suite ran and absent from
2235 // the tree the stamp vouches for.
2236 //
2237 // Counting them was tried, and is worse than the gap. Gates leave
2238 // artefacts — a log, a coverage directory, whatever a declared
2239 // `amont.conf` command writes — and nothing cleans them up, so a
2240 // repository using declared gates would stop earning stamps permanently
2241 // after its first commit. That does not merely lose an optimisation: it
2242 // puts the suite back INSIDE the push, which is the failure the whole
2243 // stamping mechanism exists to prevent. amont's own push flow
2244 // (`flows/push.rs`, steps `first push` and `retry`) is exactly that
2245 // shape, and CI is where it surfaced — a `*.log` line in one developer's
2246 // global gitignore had hidden it on the machine that wrote the change.
2247 //
2248 // `greengate.testPushedTree true` closes the gap properly for anyone who
2249 // wants it closed: it runs the suite in a checkout of the commit, where
2250 // no untracked file exists to be read.
2251 //
2252 // `tree_at_start` — not a fresh `git status`. The gates have run by now
2253 // and may have written into the tree; what a stamp needs to know is what
2254 // the suite could READ, which is the state it was handed. See the
2255 // capture in `pre_push`.
2256 let mut stamped: Vec<String> = Vec::new();
2257 for tip in tips {
2258 // PER GATE, from what each one actually did — not from the config.
2259 // `greengate.testPushedTree` is a request; `pushed_tree::ran_on_tip` is
2260 // the record of which gates were handed a checkout of this tip. A
2261 // gate that ran somewhere else (a snapshot that could not be made,
2262 // or a check that ran in the working tree) may vouch for the tip
2263 // only when the working tree WAS the tip. Deciding from the flag
2264 // stamped every passing gate onto a tip that one of them had never
2265 // seen.
2266 let vouched: Vec<String> = gates
2267 .iter()
2268 .filter(|g| witness.vouches(g, tip))
2269 .cloned()
2270 .collect();
2271 if vouched.is_empty() {
2272 continue;
2273 }
2274 let spec = format!("{tip}^{{tree}}");
2275 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
2276 continue;
2277 };
2278 // A gate the cluster proved on this tree is already recorded in its
2279 // own ref: a local push stamp would let the laptop vouch for it.
2280 let vouched: Vec<String> = vouched
2281 .into_iter()
2282 .filter(|g| !crate::cluster::proved(g, &tree))
2283 .collect();
2284 // Tokens, not names; a gate with no identity is not stamped.
2285 let tokens: Vec<String> = vouched
2286 .iter()
2287 .filter_map(|g| crate::gate_identity::token(externals, g))
2288 .collect();
2289 if crate::gate_stamp::stamp_push(tip, &tree, &tokens) {
2290 for g in vouched {
2291 if !stamped.contains(&g) {
2292 stamped.push(g);
2293 }
2294 }
2295 }
2296 }
2297 if !stamped.is_empty() {
2298 crate::say!(
2299 "{} stamped {} for this tree — the next push of it skips them ({})",
2300 valid_sign(),
2301 highlight(&stamped.join(" ")),
2302 crate::gate_stamp::NOTES_REF,
2303 );
2304 }
2305}
2306
2307/// Write the audit records this push produced (ADR-0018), only for a commit
2308/// the working tree IS: HEAD, inside a rehearsal snapshot or with a clean
2309/// worktree — the tools read the working tree, not the commit.
2310fn record_audits(ledger: &crate::hooks::audit::Ledger, tree_at_start: &str) {
2311 let pending = ledger.take_pending();
2312 if pending.is_empty() {
2313 return;
2314 }
2315 let witness = TipWitness::new(tree_at_start);
2316 for record in pending {
2317 if !witness.tree_is_tip(&record.tip) {
2318 continue;
2319 }
2320 if let Err(why) = crate::hooks::audit::write_pending(&record) {
2321 crate::hooks::common::warn(&format!(
2322 "{why} — the next push of this tree owes the audit again"
2323 ));
2324 }
2325 }
2326}
2327
2328/// Record the gates that completed without passing (ADR-0018), on exactly the
2329/// tips `stamp_tips` would stamp: a tip whose content is what the gates ran
2330/// on — HEAD, inside a rehearsal snapshot or with a clean worktree. One note
2331/// write per tree and kind of completion.
2332fn record_completions(
2333 externals: &[crate::manifest::External],
2334 tips: &[String],
2335 gates: &[(String, crate::gate_stamp::Completion)],
2336 tree_at_start: &str,
2337) {
2338 if gates.is_empty() {
2339 return;
2340 }
2341 let witness = TipWitness::new(tree_at_start);
2342 let mut by_kind: Vec<(crate::gate_stamp::Completion, Vec<String>)> = Vec::new();
2343 for (gate, how) in gates {
2344 let Some(token) = crate::gate_identity::token(externals, gate) else {
2345 continue;
2346 };
2347 match by_kind.iter_mut().find(|(kind, _)| kind == how) {
2348 Some((_, tokens)) => tokens.push(token),
2349 None => by_kind.push((*how, vec![token])),
2350 }
2351 }
2352 for tip in tips {
2353 if !witness.tree_is_tip(tip) {
2354 continue;
2355 }
2356 let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]) else {
2357 continue;
2358 };
2359 for (how, tokens) in &by_kind {
2360 if let Err(why) = crate::gate_stamp::record_done(&tree, tokens, *how) {
2361 crate::hooks::common::warn(&format!(
2362 "{why} — the next push of this tree owes those gates again"
2363 ));
2364 }
2365 }
2366 }
2367}
2368
2369/// Of the checks that passed, the ones an attestation may actually VOUCH for.
2370///
2371/// A language gate whose scope the push never touched returns `Passed` having
2372/// run nothing — `cargo_test` walks its refs, finds no crate root, and falls
2373/// out of the loop green. That is right for a push gate (there was nothing to
2374/// object to) and wrong for an attestation: a JS-only push was minting
2375/// `gates … pre-push-cargo-test pre-push-go-test pre-push-pytest`, and in a
2376/// MIXED repository CI would then skip a suite that nobody ran on that tree.
2377///
2378/// The declared `scope` is the honest filter, and the same data `amont list`
2379/// already reports. Unscoped checks (`Scope::ALWAYS` — branch-protect,
2380/// secrets) match everything and are vouched for, which is accurate: they
2381/// really did run. An empty `changed` vouches for nothing scoped, which is
2382/// the safe direction — CI runs the suite.
2383///
2384/// [`Scope::touches`], NOT `Scope::matches`. `matches` also asks whether the
2385/// repository has opted in — whether a `Cargo.toml` exists — and asking that
2386/// of a push DIFF can only answer no unless the push happened to touch the
2387/// marker. So `pre-push-cargo-test` was vouched for by a push that edited
2388/// `Cargo.toml` and never by one that edited only `.rs` files, which is the
2389/// ordinary case and the one worth skipping CI for. The feature attested
2390/// almost nothing, silently, and looked like it worked.
2391///
2392/// WHAT THIS IS STILL A PROXY FOR, stated plainly because the trust path
2393/// deserves it: the honest question is "did this gate actually run", and no
2394/// gate reports that. `rust_tools::test` returns `Passed` whether it ran a
2395/// suite or found no crate root and fell out of its loop — the very thing
2396/// the first paragraph describes. Scope is the closest available stand-in.
2397/// It is now a good one: a gate is vouched for only if the push changed a
2398/// file its extensions cover.
2399///
2400/// The gap that remains is narrow and one-directional: a `.rs` file outside
2401/// every crate would be covered here while `cargo test` had nothing to say
2402/// about it. Closing it properly means an outcome that distinguishes "ran
2403/// and passed" from "found nothing to do", which is a change to every gate
2404/// and to `Outcome` itself — worth doing, not worth smuggling into this.
2405/// Which pushed tips a gate's run in this process saw (#289): the working
2406/// tree was the tip when the gates started, or the gate ran in a checkout of
2407/// it (`pushed_tree::ran_on_tip`). Shared by the push stamps and the
2408/// attestation, so the two never disagree about what was tested.
2409struct TipWitness {
2410 head: Option<String>,
2411 /// The working tree held HEAD's content when the gates started: clean
2412 /// of tracked changes, or a rehearsal snapshot. A snapshot is a checkout
2413 /// git made of the commit, and whatever `greengate.snapshotPrepare` added to
2414 /// make it runnable (a `node_modules`, a virtualenv) is not a reason to
2415 /// distrust it.
2416 tree_is_head: bool,
2417}
2418
2419impl TipWitness {
2420 fn new(tree_at_start: &str) -> Self {
2421 Self::from_parts(
2422 crate::git::stdout(&["rev-parse", "HEAD"]),
2423 crate::rehearsal::in_snapshot(),
2424 tree_at_start,
2425 )
2426 }
2427
2428 fn from_parts(head: Option<String>, in_snapshot: bool, tree_at_start: &str) -> Self {
2429 TipWitness {
2430 head,
2431 tree_is_head: in_snapshot || tree_at_start.trim().is_empty(),
2432 }
2433 }
2434
2435 /// The working tree was `tip` when the gates started.
2436 fn tree_is_tip(&self, tip: &str) -> bool {
2437 self.tree_is_head && self.head.as_deref() == Some(tip)
2438 }
2439
2440 fn vouches(&self, gate: &str, tip: &str) -> bool {
2441 self.tree_is_tip(tip) || crate::pushed_tree::ran_on_tip(gate, tip)
2442 }
2443}
2444
2445fn attestable(checks: &[&dyn Check], passed: &[String], changed: &[String]) -> Vec<String> {
2446 checks
2447 .iter()
2448 .filter(|c| passed.iter().any(|p| p == c.name()))
2449 .filter(|c| c.scope().touches(changed))
2450 .map(|c| c.name().to_string())
2451 .collect()
2452}
2453
2454#[cfg(test)]
2455mod tests {
2456 use super::*;
2457 use crate::check::{Builtin, Scope};
2458 use std::sync::atomic::{AtomicUsize, Ordering};
2459
2460 /// #289: a dirty working tree witnesses no tip, even HEAD; a clean one,
2461 /// or a snapshot, witnesses HEAD only.
2462 #[test]
2463 fn only_a_clean_head_or_a_snapshot_witnesses_a_tip() {
2464 let head = Some("a".repeat(40));
2465 let tip = "a".repeat(40);
2466 let other = "b".repeat(40);
2467 let dirty = TipWitness::from_parts(head.clone(), false, " M src/lib.rs\n");
2468 assert!(!dirty.tree_is_tip(&tip));
2469 let clean = TipWitness::from_parts(head.clone(), false, "");
2470 assert!(clean.tree_is_tip(&tip));
2471 assert!(!clean.tree_is_tip(&other));
2472 let snapshot = TipWitness::from_parts(head, true, " M node_modules/x\n");
2473 assert!(snapshot.tree_is_tip(&tip));
2474 }
2475
2476 /// ADR-0018: the refusals fit 80 columns, put each command on its own
2477 /// line, and name only amont's own commands (every Green Harness part is
2478 /// optional: amont runs without relais, the skills or amont-agent).
2479 #[test]
2480 fn the_push_refusals_fit_and_name_only_amont() {
2481 let many: Vec<String> = (0..12)
2482 .map(|i| format!("pre-push-gate-number-{i}"))
2483 .collect();
2484 let names: Vec<&str> = many.iter().map(String::as_str).collect();
2485 let refs = vec![crate::pushrefs::PushRef {
2486 local_ref: "refs/heads/x".into(),
2487 local_oid: "a".repeat(40),
2488 remote_ref: "refs/heads/x".into(),
2489 remote_oid: "b".repeat(40),
2490 }];
2491 let sets = [
2492 push_refusal("abcdef12", &names, StampReuse::On, None),
2493 push_refusal("abcdef12", &names, StampReuse::Off, None),
2494 land_refusal(
2495 &crate::rehearsal::LandLine {
2496 sha: "a".repeat(40),
2497 remote_tip: "b".repeat(40),
2498 },
2499 &refs,
2500 &names,
2501 ),
2502 land_refusal(
2503 &crate::rehearsal::LandLine {
2504 sha: "a".repeat(40),
2505 remote_tip: "c".repeat(40),
2506 },
2507 &refs,
2508 &names,
2509 ),
2510 push_refusal(
2511 "abcdef12",
2512 &names,
2513 StampReuse::On,
2514 Some("v12.345.6789-rc.1+build.2026-11-05"),
2515 ),
2516 ];
2517 for lines in &sets {
2518 for line in lines {
2519 assert!(line.chars().count() <= 80, "{line:?}");
2520 for foreign in ["relais", "skill", "amont-agent"] {
2521 assert!(!line.contains(foreign), "{line:?}");
2522 }
2523 }
2524 let joined = lines.join("\n");
2525 for name in &names {
2526 assert!(joined.contains(name), "every gate is named: {joined}");
2527 }
2528 }
2529 assert!(sets[0].iter().any(|l| l.ends_with(&format!("{BIN} land"))));
2530 assert!(sets[0]
2531 .iter()
2532 .any(|l| l.ends_with(&format!("{BIN} rehearse --wait"))));
2533 assert!(
2534 !sets[1].iter().any(|l| l.contains("rehearse")),
2535 "{:?}",
2536 sets[1]
2537 );
2538 assert!(sets[1]
2539 .iter()
2540 .any(|l| l.contains("greengate.pushStamps true")));
2541 assert!(sets[1].iter().any(|l| l.ends_with(&format!("{BIN} land"))));
2542 assert_eq!(sets[2][0], crate::land::LAND_EVIDENCE_MISSING);
2543 assert_eq!(sets[3][0], crate::land::LAND_REMOTE_MOVED);
2544 assert!(sets[0][0].starts_with(&format!("{BIN}: push refused:")));
2545 // A tag push is offered the tag's own land, never the branch remedies.
2546 assert!(
2547 sets[4].iter().any(|l| l.ends_with(&format!(
2548 "{BIN} land --tag v12.345.6789-rc.1+build.2026-11-05"
2549 ))),
2550 "{:?}",
2551 sets[4]
2552 );
2553 assert!(
2554 !sets[4].iter().any(|l| l.contains("rehearse")),
2555 "{:?}",
2556 sets[4]
2557 );
2558 }
2559
2560 /// A check whose only job is to carry a name and a severity into `report`.
2561 /// Its `run` is never called — `report` is fed outcomes directly, which is
2562 /// what makes `Unavailable` testable at all: the real thing needs a missing
2563 /// binary, and a test that uninstalls the developer's toolchain is worse
2564 /// than no test.
2565 const fn stub(name: &'static str, severity: Severity) -> Builtin {
2566 Builtin {
2567 name,
2568 stage: Stage::PreCommit,
2569 scope: Scope::ALWAYS,
2570 severity,
2571 run: |_| Outcome::Passed,
2572 fix: crate::check::Fix::None,
2573 reach: crate::check::Reach::Convention,
2574 }
2575 }
2576
2577 /// A pre-push gate with an OPT-IN file, as the real Rust and Python
2578 /// gates have: `.rs` files, but only where a `Cargo.toml` exists.
2579 const fn opt_in(
2580 name: &'static str,
2581 exts: &'static [&'static str],
2582 names: &'static [&'static str],
2583 ) -> Builtin {
2584 Builtin {
2585 name,
2586 stage: Stage::PrePush,
2587 scope: Scope::new(exts, names),
2588 severity: Severity::Block,
2589 run: |_| Outcome::Passed,
2590 fix: crate::check::Fix::None,
2591 reach: crate::check::Reach::Convention,
2592 }
2593 }
2594
2595 /// A pre-push gate scoped to one language's files.
2596 const fn scoped(name: &'static str, exts: &'static [&'static str]) -> Builtin {
2597 Builtin {
2598 name,
2599 stage: Stage::PrePush,
2600 scope: Scope::new(exts, &[]),
2601 severity: Severity::Block,
2602 run: |_| Outcome::Passed,
2603 fix: crate::check::Fix::None,
2604 reach: crate::check::Reach::Convention,
2605 }
2606 }
2607
2608 /// The over-claim this filter exists to stop, caught in the wild: a
2609 /// JS-only push minted `gates … pre-push-cargo-test pre-push-go-test
2610 /// pre-push-pytest`, because each of those gates finds nothing of its
2611 /// language to do and returns `Passed` having run NOTHING. Harmless in a
2612 /// single-language repo, unsound in a mixed one — CI would skip a suite
2613 /// nobody ran on that tree.
2614 #[test]
2615 fn a_gate_whose_language_the_push_never_touched_is_not_vouched_for() {
2616 let js = scoped("pre-push-run-tests-js", &[".ts", ".js"]);
2617 let rust = scoped("pre-push-cargo-test", &[".rs"]);
2618 let py = scoped("pre-push-pytest", &[".py"]);
2619 let always = stub("pre-push-secrets", Severity::Block);
2620 let checks: Vec<&dyn Check> = vec![&js, &rust, &py, &always];
2621 let passed: Vec<String> = checks.iter().map(|c| c.name().to_string()).collect();
2622
2623 let changed = vec!["app/routes/home.ts".to_string()];
2624 let vouched = attestable(&checks, &passed, &changed);
2625 assert_eq!(
2626 vouched,
2627 vec![
2628 "pre-push-run-tests-js".to_string(),
2629 "pre-push-secrets".to_string()
2630 ],
2631 "only the gate that had work, plus the unscoped one that always runs"
2632 );
2633
2634 // Nothing computed about the push vouches for nothing scoped — the
2635 // safe direction, since CI then runs the suite.
2636 assert_eq!(
2637 attestable(&checks, &passed, &[]),
2638 vec!["pre-push-secrets".to_string()]
2639 );
2640
2641 // A check that did NOT pass is never vouched for, whatever its scope.
2642 let only_rust_passed = vec!["pre-push-cargo-test".to_string()];
2643 assert!(attestable(&checks, &only_rust_passed, &changed).is_empty());
2644 }
2645
2646 /// No overrides configured. `report` takes them as a VALUE now, so its
2647 /// tests need no repository and no git at all.
2648 fn none() -> Overrides {
2649 Overrides::default()
2650 }
2651
2652 static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
2653 static WARNER: Builtin = stub("stub-warner", Severity::Warn);
2654
2655 /// The unit tests hold `&dyn Check` for the same reason the dispatcher
2656 /// does: `report` must not be able to tell a built-in from an external.
2657 const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
2658 [cs[0], cs[1], cs[2]]
2659 }
2660
2661 /// The classification itself, which used to be unreachable: while one
2662 /// function classified AND printed AND returned a code, a test could assert
2663 /// the code and nothing else.
2664 #[test]
2665 fn every_outcome_lands_in_the_right_bucket() {
2666 let checks: [&dyn Check; 5] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER, &BLOCKER];
2667 let got = classify(
2668 &checks,
2669 &[
2670 Outcome::Passed,
2671 Outcome::Unavailable,
2672 Outcome::Failed,
2673 Outcome::Failed,
2674 Outcome::Inert,
2675 ],
2676 &none(),
2677 );
2678 assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
2679 assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
2680 assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
2681 assert_eq!(got.passed, 1, "inert is not a pass: {got:?}");
2682 }
2683
2684 /// A clean stage concludes nothing at all — not an empty message, no
2685 /// message. Twenty checks that passed should print no roll-ups.
2686 ///
2687 /// `passed` is a tally, not a roll-up. It exists so that `greengate.quiet` can
2688 /// say how many lines it swallowed, and it must never be the reason this
2689 /// report looks like it has something to announce.
2690 #[test]
2691 fn a_clean_stage_has_nothing_to_report() {
2692 let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
2693 let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
2694 assert!(
2695 got.fixed.is_empty()
2696 && got.blocked.is_empty()
2697 && got.downgraded.is_empty()
2698 && got.unavailable.is_empty(),
2699 "a clean stage found something to announce: {got:?}"
2700 );
2701 assert_eq!(got.passed, 1, "the pass was not tallied: {got:?}");
2702 assert_eq!(got.verdict(), Verdict::Proceed);
2703 }
2704
2705 #[test]
2706 fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
2707 let b: &dyn Check = &BLOCKER;
2708 let w: &dyn Check = &WARNER;
2709 assert_eq!(
2710 classify(&[b], &[Outcome::Failed], &none()).verdict(),
2711 Verdict::Block
2712 );
2713 assert_eq!(
2714 classify(&[b], &[Outcome::Passed], &none()).verdict(),
2715 Verdict::Proceed
2716 );
2717 // Every non-blocking shape, one at a time, so a regression cannot hide
2718 // behind a passing sibling.
2719 assert_eq!(
2720 classify(&[b], &[Outcome::Warned], &none()).verdict(),
2721 Verdict::Proceed
2722 );
2723 assert_eq!(
2724 classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
2725 Verdict::Proceed
2726 );
2727 assert_eq!(
2728 classify(&[w], &[Outcome::Failed], &none()).verdict(),
2729 Verdict::Proceed
2730 );
2731 // A skipped Heavy check never blocks by itself: the Light failure
2732 // that skipped it does (ADR-0020). It is listed, never counted passed.
2733 let skipped = classify(&[b], &[Outcome::Skipped], &none());
2734 assert_eq!(skipped.verdict(), Verdict::Proceed);
2735 assert_eq!(skipped.skipped, vec![b.name()]);
2736 assert_eq!(skipped.passed, 0);
2737 }
2738
2739 #[test]
2740 fn the_environment_word_on_fail_fast_wins_and_a_bad_one_falls_back() {
2741 let settings = crate::config::Settings::default();
2742 assert!(!resolve_fail_fast(Some("false"), &settings));
2743 assert!(!resolve_fail_fast(Some("0"), &settings));
2744 assert!(resolve_fail_fast(Some("TRUE"), &settings));
2745 // Unset or unreadable: the configured value, here the default.
2746 assert!(resolve_fail_fast(None, &settings));
2747 assert!(resolve_fail_fast(Some(""), &settings));
2748 assert!(resolve_fail_fast(Some("sometimes"), &settings));
2749 }
2750
2751 #[test]
2752 fn one_blocking_failure_among_many_still_fails() {
2753 let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
2754 assert_eq!(
2755 classify(
2756 &checks,
2757 &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
2758 &none()
2759 )
2760 .verdict(),
2761 Verdict::Block
2762 );
2763 // Same shape, with the only *blocking* failure removed.
2764 assert_eq!(
2765 classify(
2766 &checks,
2767 &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
2768 &none()
2769 )
2770 .verdict(),
2771 Verdict::Proceed
2772 );
2773 }
2774
2775 /// The slot of a check whose thread died. Reading that as a pass is how a
2776 /// crash becomes a green commit.
2777 ///
2778 /// Asserted through the RUNNER, not through a `Default` impl: the rule
2779 /// belongs to this call site, and a test on `Outcome::default()` proved
2780 /// only that a trait impl existed, not that the runner used it.
2781 /// A check that PANICS must fail the commit, not pass it — and must not
2782 /// take the other checks down with it.
2783 ///
2784 /// Driven through the stage body rather than the runner, because the value
2785 /// that stands in for a dead check is chosen at the call site and the
2786 /// runner's own test cannot see that choice.
2787 #[test]
2788 fn a_panicking_check_blocks_the_commit() {
2789 static DIES: Builtin = Builtin {
2790 name: "stub-dies",
2791 stage: Stage::PreCommit,
2792 scope: Scope::ALWAYS,
2793 severity: Severity::Block,
2794 run: |_| panic!("this check died"),
2795 fix: crate::check::Fix::None,
2796 reach: crate::check::Reach::Convention,
2797 };
2798 let hook = std::panic::take_hook();
2799 std::panic::set_hook(Box::new(|_| {}));
2800 let push = crate::pushrefs::PushRefs::default();
2801 let manifest = crate::manifest::Manifest::default();
2802 let settings = crate::config::Settings::default();
2803 let ctx = Ctx {
2804 name: "pre-commit",
2805 args: &[],
2806 hooks_dir: std::path::Path::new("."),
2807 push: &push,
2808 manifest: &manifest,
2809 settings: &settings,
2810 handed_to_cluster: &[],
2811 land: &crate::rehearsal::LandEnv::Absent,
2812 audits: &Default::default(),
2813 source_worktree: None,
2814 };
2815 let verdict = run_stage(&[&DIES], &ctx, &none());
2816 std::panic::set_hook(hook);
2817 assert_eq!(
2818 verdict,
2819 Verdict::Block,
2820 "a check that died must not let the commit through"
2821 );
2822 }
2823
2824 #[test]
2825 fn a_thread_that_dies_leaves_a_failure_behind() {
2826 // The default hook would print a backtrace for the deliberate panic and
2827 // make a passing run look broken.
2828 let hook = std::panic::take_hook();
2829 std::panic::set_hook(Box::new(|_| {}));
2830 let items = ["a", "b", "c"];
2831 let out = run_concurrently(
2832 &items,
2833 |n: &&str| {
2834 if *n == "b" {
2835 panic!("this check died");
2836 }
2837 Outcome::Passed
2838 },
2839 Outcome::Failed,
2840 );
2841 std::panic::set_hook(hook);
2842 assert_eq!(
2843 out,
2844 vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
2845 "a dead check must not read as one that passed, \
2846 and must not take the other checks down with it"
2847 );
2848 }
2849 use std::time::{Duration, Instant};
2850
2851 /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
2852 /// observe all the others arrive. Were the runner serial, the first task
2853 /// would wait alone, time out, and return non-zero — a failure, not a hang.
2854 #[test]
2855 fn run_concurrently_actually_overlaps() {
2856 static ARRIVED: AtomicUsize = AtomicUsize::new(0);
2857 ARRIVED.store(0, Ordering::SeqCst);
2858 let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
2859 let n = names.len();
2860
2861 let out = run_concurrently(
2862 &names,
2863 move |_: &&str| {
2864 ARRIVED.fetch_add(1, Ordering::SeqCst);
2865 let deadline = Instant::now() + Duration::from_secs(10);
2866 while ARRIVED.load(Ordering::SeqCst) < n {
2867 if Instant::now() > deadline {
2868 return 1; // never met the others — execution was serial
2869 }
2870 std::thread::yield_now();
2871 }
2872 0
2873 },
2874 1,
2875 );
2876 assert!(
2877 out.iter().all(|c| *c == 0),
2878 "tasks did not overlap: {out:?}"
2879 );
2880 }
2881
2882 #[test]
2883 fn results_come_back_in_input_order() {
2884 let names: Vec<&'static str> = vec!["first", "second", "third"];
2885 let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
2886 assert_eq!(out, vec![0, 7, 0], "results keep the input order");
2887 }
2888
2889 /// The filter calls the shared resolver rather than restating it. This test
2890 /// used to inline `n.contains(s)` — its own copy of the rule — and so went
2891 /// on passing after the rule changed underneath it.
2892 #[test]
2893 fn skips_are_filtered_by_the_shared_resolver() {
2894 let all = ["pre-commit-ruff", "pre-commit-prettier"];
2895 let skips = ["ruff".to_string()];
2896 let kept: Vec<_> = all
2897 .iter()
2898 .copied()
2899 .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
2900 .collect();
2901 assert_eq!(kept, vec!["pre-commit-prettier"]);
2902 }
2903
2904 /// The ordinary Rust push: source changed, `Cargo.toml` untouched.
2905 ///
2906 /// This test used to assert the OPPOSITE, and said so — it pinned
2907 /// `attestable` filtering on `Scope::matches`, which also asks whether
2908 /// the repository has opted in. Asking that of a push diff meant a
2909 /// `.rs`-only push, in a repository with a `Cargo.toml` sitting right
2910 /// there, attested nothing. Since that is what nearly every Rust push
2911 /// looks like, the feature was attesting almost nothing at all — quietly,
2912 /// while appearing to work.
2913 #[test]
2914 fn an_ordinary_source_push_is_vouched_for() {
2915 let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
2916 let checks: Vec<&dyn Check> = vec![&rust];
2917 let passed = vec!["pre-push-cargo-test".to_string()];
2918
2919 let changed = vec!["crates/greengate/src/main.rs".to_string()];
2920 assert_eq!(
2921 attestable(&checks, &passed, &changed),
2922 vec!["pre-push-cargo-test".to_string()],
2923 "a push that changed Rust must vouch for the Rust gate"
2924 );
2925
2926 // And still when the marker IS in the diff — the opt-in file is not
2927 // required, but it is not disqualifying either.
2928 let changed = vec![
2929 "crates/greengate/src/main.rs".to_string(),
2930 "Cargo.toml".to_string(),
2931 ];
2932 assert_eq!(
2933 attestable(&checks, &passed, &changed),
2934 vec!["pre-push-cargo-test".to_string()]
2935 );
2936 }
2937
2938 /// The over-claim the filter exists to stop, with an opt-in gate: a
2939 /// JS-only push must not vouch for the Rust suite, whatever files the
2940 /// repository contains.
2941 ///
2942 /// This is the half of the contract the fix above must not have broken,
2943 /// and it is the reason `touches` asks about EXTENSIONS rather than
2944 /// dropping the scope test altogether.
2945 #[test]
2946 fn an_opt_in_gate_is_not_vouched_for_by_a_push_in_another_language() {
2947 let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
2948 let checks: Vec<&dyn Check> = vec![&rust];
2949 let passed = vec!["pre-push-cargo-test".to_string()];
2950
2951 for changed in [
2952 vec!["app/routes/home.ts".to_string()],
2953 // Even the marker alone: editing Cargo.toml changes no Rust
2954 // source, so the suite has nothing new to have verified.
2955 vec!["Cargo.toml".to_string()],
2956 vec![],
2957 ] {
2958 assert!(
2959 attestable(&checks, &passed, &changed).is_empty(),
2960 "must not vouch for the Rust gate on {changed:?}"
2961 );
2962 }
2963 }
2964
2965 /// amont #431: `onBusy wait` cannot stop a `warn` gate deferring, so a
2966 /// list of warn gates is advised only the command that waits, once per
2967 /// gate, and the hint is never offered.
2968 #[test]
2969 fn deferred_warn_gates_are_each_advised_the_command_that_waits() {
2970 let lines = deferral_advice(&[
2971 ("pre-push-probe", Severity::Warn),
2972 ("pre-push-lint", Severity::Warn),
2973 ]);
2974 let said = lines.join("\n");
2975 assert!(said.contains("2 check(s) deferred to CI"), "{said}");
2976 for gate in ["pre-push-probe", "pre-push-lint"] {
2977 assert!(
2978 said.contains(&format!("GREENGATE_ON_BUSY=wait {BIN} run --raw {gate}")),
2979 "{said}"
2980 );
2981 }
2982 assert!(!said.contains("set onBusy wait"), "{said}");
2983 }
2984
2985 /// A list mixing a `block` and a `warn` gate: both get their command,
2986 /// and the `onBusy wait` hint says it stops only the block checks.
2987 #[test]
2988 fn a_mixed_deferral_names_every_gate_and_scopes_the_hint() {
2989 let lines = deferral_advice(&[
2990 ("pre-push-probe", Severity::Warn),
2991 ("pre-push-cargo-test", Severity::Block),
2992 ]);
2993 let said = lines.join("\n");
2994 for gate in ["pre-push-probe", "pre-push-cargo-test"] {
2995 assert!(
2996 said.contains(&format!("GREENGATE_ON_BUSY=wait {BIN} run --raw {gate}")),
2997 "{said}"
2998 );
2999 }
3000 let hint = lines
3001 .iter()
3002 .find(|l| l.contains("set onBusy wait"))
3003 .expect("the hint, for the block gate");
3004 assert!(hint.contains("block checks"), "{hint}");
3005 assert_eq!(lines.len(), 4, "roll-up, two commands, one hint: {said}");
3006 }
3007}