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