amont_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/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::registry::{all_stage_checks, Ctx, Overrides};
34use crate::ui::{highlight, valid_sign, warning_sign};
35
36/// The checks for a stage, minus anything `hook.skip` filters out. Resolution
37/// goes through `names_check`, the one rule this and the severity lookup share:
38/// `git config hook.skip ruff` skips `pre-commit-ruff` by short name.
39fn selected<'a>(
40 settings: &crate::config::Settings,
41 stage: Stage,
42 manifest: &'a crate::manifest::Manifest,
43) -> Vec<&'a dyn Check> {
44 selected_during(settings, stage, &[], manifest)
45}
46
47/// Do this repository's hooks apply the CONVENTIONS, or only the safety net?
48///
49/// `git config amont.conventions declared` (usually `--global`, set by
50/// `amont enroll`) scopes the house rules to repositories that commit an
51/// `amont.conf` — the standing grant of `init.templateDir` then becomes safe
52/// to hand a whole team: a clone of somebody else's project gets conflict,
53/// secret, size and debug-leftover protection, and none of this team's
54/// opinions about commit subjects or branch names. The default,
55/// `everywhere`, keeps today's behaviour exactly.
56///
57/// Presence of the manifest is the declaration; its CONTENT stays
58/// trust-gated. Reading presence executes nothing, so no consent is needed.
59pub fn conventions_apply(
60 settings: &crate::config::Settings,
61 manifest: &crate::manifest::Manifest,
62) -> bool {
63 manifest.declared || !declared_mode(settings)
64}
65
66/// One config read per process — this sits on the hook path of every commit.
67fn declared_mode(settings: &crate::config::Settings) -> bool {
68 *settings.declared_mode.get_or_init(|| {
69 crate::config::enumerated_or(
70 settings,
71 "amont.conventions",
72 &["everywhere", "declared"],
73 "everywhere",
74 ) == "declared"
75 })
76}
77
78/// The checks for a stage, minus `hook.skip` and minus anything that declares
79/// it does not run during an operation currently in progress.
80fn selected_during<'a>(
81 settings: &crate::config::Settings,
82 stage: Stage,
83 in_progress: &[crate::check::GitState],
84 manifest: &'a crate::manifest::Manifest,
85) -> Vec<&'a dyn Check> {
86 let skips = configured_skips(settings);
87 // Externals are included here, so `hook.skip` and the severity override
88 // govern a declared command exactly as they govern a built-in. A repository
89 // that can add a check it cannot disable would be a worse deal than not
90 // being able to add one.
91 let (kept, dropped): (Vec<_>, Vec<_>) = all_stage_checks(stage, manifest)
92 .into_iter()
93 .partition(|c| !skips.iter().any(|s| crate::skip_suppresses(c.name(), s)));
94 let names: Vec<&str> = dropped.iter().map(|c| c.name()).collect();
95 announce_skips(settings, &names);
96
97 // Announced separately from `hook.skip`, and with the operation named: "not
98 // during a rebase" is a property of the moment and will be true again in a
99 // minute, which is a different thing to tell a reader than "you disabled
100 // this".
101 let (kept, paused): (Vec<_>, Vec<_>) = kept.into_iter().partition(|check| {
102 !check
103 .scope()
104 .not_during
105 .iter()
106 .any(|state| in_progress.contains(state))
107 });
108 if !paused.is_empty() {
109 let what = in_progress
110 .iter()
111 .map(|s| s.as_str())
112 .collect::<Vec<_>>()
113 .join(" and ");
114 println!(
115 "{} {} check(s) paused during {what}: {}",
116 warning_sign(),
117 paused.len(),
118 paused
119 .iter()
120 .map(|c| c.name())
121 .collect::<Vec<_>>()
122 .join(", ")
123 );
124 }
125
126 // The conventions split, last: a held-back check was neither skipped (a
127 // choice about THIS repository) nor paused (a property of the moment) —
128 // this repository simply never subscribed. One line, count not names:
129 // in the clone-of-somebody-else's-project case this prints on every
130 // commit, and fifteen names every time is how a safety message becomes
131 // scroll-past noise.
132 if conventions_apply(settings, manifest) {
133 return kept;
134 }
135 let (kept, held): (Vec<_>, Vec<_>) = kept
136 .into_iter()
137 .partition(|check| check.reach() == crate::check::Reach::Safety);
138 if !held.is_empty() {
139 println!(
140 "{} {} convention check(s) held back — no amont.conf here and \
141 amont.conventions is `declared`; the safety net still runs",
142 warning_sign(),
143 held.len(),
144 );
145 }
146 kept
147}
148
149/// The key that turns evidence ordering on. `declared` — the registry's
150/// order, the one this file's header argues for — is the default and nothing
151/// about it changes.
152const ORDER: &str = "amont.order";
153
154/// How far back [`crate::gate_evidence::order_by_evidence`] looks. Not a
155/// config key: it is an input to an ordering that changes nothing about what
156/// runs, and a knob nobody can predict the effect of is a knob that invites
157/// cargo-culting. Ninety days is the same window the report defaults to, so
158/// the ordering a push takes is the ordering `amont-fleet gates` explains.
159const ORDER_WINDOW_DAYS: u64 = 90;
160
161/// Does this repository want its push gates ordered by what the record says?
162fn evidence_ordering(settings: &crate::config::Settings) -> bool {
163 crate::config::enumerated_or(settings, ORDER, &["declared", "evidence"], "declared")
164 == "evidence"
165}
166
167/// Reorder the SCOPED push gates — the suites and audits — by the local
168/// record, leaving everything else exactly where the registry put it.
169///
170/// Two halves, and the split is the safety property. The unscoped pre-push
171/// checks ask about the PUSH — is this branch protected, is the name legal,
172/// is the branch behind, is there a secret in it — and the registry orders
173/// them "cheapest and most decisive first" for a reason: discovering a
174/// protected branch after twenty minutes of tests is precisely the waste this
175/// feature exists to remove, and promoting a suite above them would
176/// reintroduce it. So they keep their positions absolutely.
177///
178/// The scoped gates are permuted among the positions they already occupy.
179/// Nothing is added, removed or skipped — [`crate::gate_evidence`] argues
180/// that at length — and with no history the permutation is the identity.
181fn ordered_by_evidence<'a>(
182 settings: &crate::config::Settings,
183 checks: Vec<&'a dyn Check>,
184) -> Vec<&'a dyn Check> {
185 if !evidence_ordering(settings) || checks.len() < 2 {
186 return checks;
187 }
188 let slots: Vec<usize> = checks
189 .iter()
190 .enumerate()
191 .filter(|(_, c)| !c.scope().is_unscoped())
192 .map(|(i, _)| i)
193 .collect();
194 if slots.len() < 2 {
195 return checks;
196 }
197 let names: Vec<String> = slots
198 .iter()
199 .map(|&i| checks[i].name().to_string())
200 .collect();
201 let history = crate::gate_evidence::history_in(std::path::Path::new("."));
202 if history.is_empty() {
203 return checks;
204 }
205 let order = crate::gate_evidence::order_by_evidence(
206 &names,
207 &history,
208 crate::gate_evidence::now(),
209 ORDER_WINDOW_DAYS,
210 );
211 let mut out = checks.clone();
212 for (slot, &pick) in slots.iter().zip(&order) {
213 out[*slot] = checks[slots[pick]];
214 }
215 if out
216 .iter()
217 .map(|c| c.name())
218 .ne(checks.iter().map(|c| c.name()))
219 {
220 crate::say!(
221 "{} gate order from this repository's own record: {}",
222 valid_sign(),
223 slots
224 .iter()
225 .map(|&i| out[i].name())
226 .collect::<Vec<_>>()
227 .join(", ")
228 );
229 }
230 out
231}
232
233/// Say out loud which checks did not run.
234///
235/// A skip is otherwise invisible at exactly the moment it matters. With
236/// `hook.skip = merge-conflict` set, a commit printed six green ticks and no
237/// hint that a seventh check had been disabled — the developer sees a clean run
238/// and concludes they are covered.
239///
240/// It is worse than it sounds, because one value can silence a whole stage:
241/// `hook.skip = pre-commit` suppresses all fifteen. That is now something
242/// somebody meant rather than the accident it once was — `e` used to cost
243/// twenty by substring reach — but a commit under it still looks exactly like a
244/// commit that had nothing to report.
245///
246/// One line, only when something was actually skipped, so a normal commit is
247/// unchanged. This reaches every skip however it was created — hand-edited
248/// config included — which no dashboard can claim.
249fn announce_skips(settings: &crate::config::Settings, dropped: &[&str]) {
250 if dropped.is_empty() {
251 return;
252 }
253 // Two lines, not one: "you decided this" (hook.skip on this machine)
254 // and "your team decided this" (a skip line in the committed
255 // amont.conf) are different things to be told — the same reason paused
256 // and held-back get their own sentences. A name both sources suppress
257 // is announced as the machine's: the local decision is the nearer one.
258 let (machine, _policy) = crate::skips_by_source(settings);
259 let (yours, theirs): (Vec<&&str>, Vec<&&str>) = dropped
260 .iter()
261 .partition(|name| machine.iter().any(|s| crate::skip_suppresses(name, s)));
262 let say = |names: &[&&str], via: &str| {
263 if names.is_empty() {
264 return;
265 }
266 let plural = if names.len() == 1 { "check" } else { "checks" };
267 println!(
268 "{} {} {plural} skipped by {}: {}",
269 warning_sign(),
270 names.len(),
271 highlight(via),
272 names.iter().map(|n| **n).collect::<Vec<_>>().join(", ")
273 );
274 };
275 say(&yours, "hook.skip");
276 say(&theirs, "amont.conf");
277}
278
279/// Say, once per stage, what the manifest's policy could not do — withheld
280/// behind trust, or aiming at names that exist nowhere. Policy that silently
281/// does not apply is a silent behaviour change, which is the one kind this
282/// codebase does not allow itself.
283fn announce_policy_state(settings: &crate::config::Settings, manifest: &crate::manifest::Manifest) {
284 if let Some(why) = manifest.policy_withheld {
285 println!(
286 "{} {} policy not applied: {why}",
287 warning_sign(),
288 highlight(crate::manifest::MANIFEST),
289 );
290 }
291 for note in &manifest.policy_notes {
292 println!("{} {}", warning_sign(), note);
293 }
294 // The version floor rides the same two call sites: once per stage,
295 // beside the other "this repository expects something you lack" lines.
296 crate::skew::announce_minimum(settings);
297}
298
299/// Run every item concurrently and collect `(name, code)` in the INPUT order.
300///
301/// Extracted so the concurrency itself can be tested with a rendezvous instead
302/// of a stopwatch — an earlier wall-clock test was flaky the moment the machine
303/// was busy, and a threshold that trips under load teaches you to ignore it.
304fn run_concurrently<T, R, F>(items: &[T], run: F, if_thread_died: R) -> Vec<R>
305where
306 T: Sync,
307 R: Send + Sync + Clone,
308 F: Fn(&T) -> R + Sync,
309{
310 let slots: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
311 std::thread::scope(|scope| {
312 for (item, slot) in items.iter().zip(&slots) {
313 let run = &run;
314 let died = &if_thread_died;
315 scope.spawn(move || {
316 // CAUGHT, not propagated. `thread::scope` re-raises a child
317 // panic in the parent, which would abort the whole hook with a
318 // backtrace and throw away the other nineteen checks' results —
319 // and would make `if_thread_died` unreachable, which is what it
320 // was until this test existed to notice.
321 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(item)))
322 .unwrap_or_else(|_| died.clone());
323 *slot.lock().expect("poisoned") = Some(outcome);
324 });
325 }
326 });
327 slots
328 .into_iter()
329 .map(|s| {
330 s.into_inner()
331 .expect("poisoned")
332 .unwrap_or_else(|| if_thread_died.clone())
333 })
334 .collect()
335}
336
337/// Take the index-fidelity hold, or say why the caller must stop.
338///
339/// Extracted from `pre_commit` so that `amont run` — which its own doc
340/// comment calls "a rehearsal of the hook" — can take exactly the same hold
341/// rather than judging the working tree while a real commit judges the index.
342///
343/// Around the WHOLE fan-out, not per check: twenty checks run concurrently and
344/// would fight over one working tree.
345fn hold_unstaged() -> Result<crate::staged_only::StagedOnly, Verdict> {
346 // BEFORE `enter()`, not after: `enter()` is what checks out the tree and
347 // parks the unstaged half, and a signal landing in the gap between that
348 // and the handler being armed would hit the default disposition — dead
349 // process, tree left checked out, nothing restored. The handler no-ops
350 // harmlessly on a signal that arrives before there is anything held.
351 crate::staged_only::install_signal_handler();
352 match crate::staged_only::StagedOnly::enter() {
353 Ok(guard) => Ok(guard),
354 Err(e) => {
355 // Refusing to check the wrong content is the safe direction; a
356 // check that read the tree would be answering about a commit
357 // nobody is making.
358 eprintln!("{e}");
359 Err(Verdict::Block)
360 }
361 }
362}
363
364pub fn pre_commit(ctx: &Ctx) -> Verdict {
365 let settings = ctx.settings;
366 // Before anything runs: a pinned tool at the wrong version makes every
367 // verdict below it suspect, and the warning costs one --version per pin.
368 crate::manifest::verify_tool_pins(&ctx.manifest.pins);
369 announce_policy_state(ctx.settings, ctx.manifest);
370 let in_progress = crate::git_states_in_progress();
371 let checks = selected_during(ctx.settings, Stage::PreCommit, &in_progress, ctx.manifest);
372
373 // Tree gates (ADR-0024): judged BEFORE the hold, which is the only moment
374 // unstaged edits are visible; started AFTER it, so they lint the commit's
375 // tree. They never decide the commit.
376 let tree_gates = if ctx.manifest.tree.is_empty() || !crate::tree_lint::enabled(settings) {
377 None
378 } else {
379 match crate::tree_lint::guard(settings) {
380 Some(why) => {
381 crate::hooks::common::say(" tree lint not proven — CI will lint:");
382 crate::hooks::common::say(&crate::tree_lint::fit_line(" ", &why, ""));
383 crate::tree_lint::note_withheld(&ctx.manifest.tree);
384 None
385 }
386 None => Some(&ctx.manifest.tree),
387 }
388 };
389
390 let held = match hold_unstaged() {
391 Ok(guard) => guard,
392 Err(verdict) => return verdict,
393 };
394
395 let root = crate::hooks::common::repo_root();
396 // How long this commit's own declared checks are expected to run — the
397 // cover a tree gate can hide behind — from their last measured runs.
398 let decls =
399 crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals);
400 // Only declarations whose scope this commit touches RUN; the others
401 // return at once, and their duration says nothing about cover.
402 let staged = if ctx.manifest.tree.is_empty() {
403 Vec::new()
404 } else {
405 crate::hooks::common::staged_files(&[])
406 };
407 // A declaration in scope that was never measured is UNKNOWN cover, and
408 // unknown means run: the run teaches both numbers, exactly as an unknown
409 // gate time does. Guessing 0 would skip the one commit that could learn.
410 let cover_ms = if tree_gates.is_some() {
411 decls
412 .iter()
413 .filter(|d| d.scope.touches(&staged))
414 .map(|d| crate::tree_cache::duration_of(&d.id).unwrap_or(u64::MAX))
415 .max()
416 .unwrap_or(0)
417 } else {
418 0
419 };
420 let side_car = tree_gates.and_then(|g| {
421 crate::tree_lint::start(
422 settings,
423 std::path::Path::new(&root),
424 g,
425 &ctx.manifest.pins,
426 cover_ms,
427 )
428 });
429
430 let severities = Overrides::read(settings);
431 let (verdict, outcomes, durations) = run_stage_traced(settings, &checks, ctx, &severities);
432 // Remember how long the declared checks that judged something took, for
433 // the next commit's cover estimate.
434 if !ctx.manifest.tree.is_empty() {
435 let measured: Vec<(String, u64)> = checks
436 .iter()
437 .zip(outcomes.iter().zip(&durations))
438 .filter(|(c, (o, _))| {
439 matches!(o, Outcome::Passed | Outcome::Failed)
440 && decls
441 .iter()
442 .any(|d| d.id == c.name() && d.scope.touches(&staged))
443 })
444 .map(|(c, (_, ms))| (c.name().to_string(), *ms))
445 .collect();
446 crate::tree_cache::record_durations(&measured);
447 }
448
449 // The shadow-mode ledger. Silent, best-effort, and never consulted by any
450 // verdict — see `crate::downgrade`.
451 crate::downgrade::note(
452 settings,
453 &downgraded_events(&checks, &outcomes, &severities),
454 );
455
456 // What post-commit will bind to the commit: the gate-declared checks
457 // that RAN clean, recorded while the index still is the commit's tree.
458 // Called on every verdict — an empty record clears any leftover marker,
459 // so a blocked attempt (or a repo with nothing declared) cannot leave an
460 // earlier attempt's marker to vouch for the next commit. `Unavailable`
461 // deliberately does not qualify: a check whose tool is missing judged
462 // nothing, and stamping it would be the paper promise this exists to
463 // replace.
464 // EVERY blocking declaration, not only the npm GATE names: a custom
465 // `pre-commit check … block …` earns its stamp the same way, and a
466 // same-named pre-push declaration defers to it (see `pair_verdict`).
467 let ran: Vec<String> = if matches!(verdict, Verdict::Block) {
468 Vec::new()
469 } else {
470 crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals)
471 .into_iter()
472 .filter(|d| {
473 checks
474 .iter()
475 .zip(&outcomes)
476 .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Passed | Outcome::Fixed))
477 })
478 .map(|d| d.script)
479 .collect()
480 };
481 // A rewrite means the tree the gates linted is not the one committed.
482 let stampable =
483 !matches!(verdict, Verdict::Block) && !outcomes.iter().any(|o| matches!(o, Outcome::Fixed));
484 let mut ran = ran;
485 if let Some(car) = side_car {
486 ran.extend(crate::tree_lint::finish(settings, car, stampable));
487 }
488 let ran: Vec<&str> = ran.iter().map(String::as_str).collect();
489 crate::gate_stamp::record(&ran);
490 // Under the hold, the index IS the commit's tree: its evidence goes there.
491 if !ctx.manifest.tree.is_empty() {
492 if let Some(tree) = crate::git::stdout(&["write-tree"]) {
493 crate::tree_lint::flush_evidence(&tree);
494 }
495 }
496
497 drop(held);
498 verdict
499}
500
501/// The checks that FAILED without blocking, each with why — the shadow-mode
502/// signal [`crate::downgrade`] keeps.
503///
504/// Derived at the hook entry points and deliberately NOT inside
505/// [`run_stage_traced`], which is where `classify` already computes the same
506/// set. `run_all` reaches that function too, so recording there would let
507/// every `amont run` rehearsal inflate a ledger a lead is going to read as a
508/// count of real commits — and `run --all-files` over a dirty tree would add
509/// dozens of events for content nobody is committing.
510///
511/// A check that DECLARES `warn` is counted but is not evidence about a
512/// rollout: it was never going to block, so calling it "would have blocked"
513/// would inflate the one number the whole feature exists to produce. Only an
514/// override of a blocking check earns that.
515fn downgraded_events(
516 checks: &[&dyn Check],
517 outcomes: &[Outcome],
518 severities: &Overrides,
519) -> Vec<(String, crate::downgrade::Origin)> {
520 checks
521 .iter()
522 .zip(outcomes)
523 .filter(|(_, o)| matches!(o, Outcome::Failed))
524 .filter(|(c, _)| matches!(severities.of(**c), Severity::Warn))
525 .map(|(c, _)| (c.name().to_string(), downgrade_origin(*c, severities)))
526 .collect()
527}
528
529/// Why this check did not block. Shared, because `pre_push` fail-fasts and
530/// never builds an outcomes vector to hand to [`downgraded_events`].
531fn downgrade_origin(check: &dyn Check, severities: &Overrides) -> crate::downgrade::Origin {
532 use crate::downgrade::Origin;
533 use crate::registry::Source;
534 if matches!(check.severity(), Severity::Warn) {
535 return Origin::Declared;
536 }
537 match severities.applied_with_source(check.name()) {
538 Some((_, _, Source::Config)) => Origin::Config,
539 Some((_, _, Source::Policy)) => Origin::Policy,
540 // Declared `block`, resolved `warn`, and nothing claims to have
541 // overridden it: a contradiction. Count it, but not as evidence — the
542 // conservative direction for a number whose only failure mode is
543 // being too alarming.
544 None => Origin::Declared,
545 }
546}
547
548/// The pre-commit body, over the checks it is GIVEN.
549///
550/// A seam, so a test can hand it a check that panics. Without it the value
551/// standing in for a dead check was a literal at one call site that no test
552/// could reach — the rule was asserted on the runner and merely hoped for here.
553fn run_stage(checks: &[&dyn Check], ctx: &Ctx, severities: &Overrides) -> Verdict {
554 let settings = ctx.settings;
555 run_stage_traced(settings, checks, ctx, severities).0
556}
557
558/// [`run_stage`], keeping the per-check outcomes — index-aligned with
559/// `checks` — alive past the verdict. `pre_commit` needs them to know which
560/// gate-declared checks actually ran (`gate_stamp`); `Report` cannot answer
561/// that, because `classify` deliberately drops the names of `Passed`.
562fn run_stage_traced(
563 settings: &crate::config::Settings,
564 checks: &[&dyn Check],
565 ctx: &Ctx,
566 severities: &Overrides,
567) -> (Verdict, Vec<Outcome>, Vec<u64>) {
568 if checks.is_empty() {
569 return (Verdict::Proceed, Vec::new(), Vec::new());
570 }
571 // One slot per check: everything a check says lands in its own buffer
572 // and reaches stdout as ONE block when it finishes — see `live`. Off
573 // (`amont.progress false`), no sink is ever installed and every print
574 // streams exactly as it always did.
575 let stage = crate::live::enabled(settings).then(|| {
576 let names: Vec<&str> = checks.iter().map(|c| c.name()).collect();
577 crate::live::Stage::begin(settings, &names)
578 });
579 let items: Vec<(usize, &&dyn Check)> = checks.iter().enumerate().collect();
580 let timed = run_concurrently(
581 &items,
582 |(idx, check)| {
583 let started = std::time::Instant::now();
584 let _sink = stage.as_ref().map(|s| s.enter(*idx));
585 // The block is emitted however the check leaves — a panicking
586 // check's partial output still reaches the reader, above the
587 // dead-check verdict `run_concurrently` fills in.
588 let _flush = stage
589 .as_ref()
590 .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, *idx));
591 let sub = Ctx {
592 name: check.name(),
593 args: ctx.args,
594 hooks_dir: ctx.hooks_dir,
595 push: ctx.push,
596 manifest: ctx.manifest,
597 settings: ctx.settings,
598 };
599 let outcome = check.run(&sub);
600 let ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
601 (outcome, ms)
602 },
603 // A check whose thread died has not passed. Stated here, where the slot
604 // is filled, rather than hidden in a `Default` impl that every future
605 // `#[derive(Default)]` would silently inherit.
606 (Outcome::Failed, 0),
607 );
608 let (outcomes, durations): (Vec<Outcome>, Vec<u64>) = timed.into_iter().unzip();
609
610 let report = classify(checks, &outcomes, severities);
611 announce(settings, &report);
612 (report.verdict(), outcomes, durations)
613}
614
615/// What a stage concluded, before anything is printed or exited.
616///
617/// A VALUE, so the classification can be asserted directly. While this was one
618/// function that classified, printed and returned an exit code, its tests could
619/// only check the code — whether the right thing was SAID went untested.
620#[derive(Debug, Default, PartialEq, Eq)]
621struct Report<'a> {
622 /// Repaired. The commit proceeds, but the author's files changed under
623 /// them and that must be said out loud.
624 fixed: Vec<&'a str>,
625 /// Failed, and the severity that applies blocks.
626 blocked: Vec<&'a str>,
627 /// Failed, but configured to warn. The check printed an error and meant it,
628 /// so somebody has to say it did not block.
629 downgraded: Vec<&'a str>,
630 /// Could not run. Distinct from "passed", which is the whole point.
631 unavailable: Vec<&'a str>,
632 /// How many passed outright. Only read when `amont.quiet` swallowed their
633 /// individual lines — a run that says nothing at all is indistinguishable
634 /// from a gate that never ran, and that is the one thing this crate will
635 /// not let a reader believe.
636 passed: usize,
637}
638
639impl Report<'_> {
640 fn verdict(&self) -> Verdict {
641 Verdict::blocking(!self.blocked.is_empty())
642 }
643}
644
645/// Pure: outcomes and severities in, a verdict out. No IO.
646fn classify<'a>(
647 checks: &[&'a dyn Check],
648 outcomes: &[Outcome],
649 severities: &Overrides,
650) -> Report<'a> {
651 let mut report = Report::default();
652 for (check, outcome) in checks.iter().zip(outcomes) {
653 match outcome {
654 Outcome::Passed => report.passed += 1,
655 // `Warned` needs nothing: a check that chose to warn has already
656 // said what it wanted to, and a roll-up would only repeat it.
657 Outcome::Warned => {}
658 Outcome::Fixed => report.fixed.push(check.name()),
659 Outcome::Unavailable => report.unavailable.push(check.name()),
660 // Judged nothing, said nothing: not a pass to count, not a gap
661 // to announce.
662 Outcome::Inert => {}
663 Outcome::Failed => match severities.of(*check) {
664 Severity::Block => report.blocked.push(check.name()),
665 Severity::Warn => report.downgraded.push(check.name()),
666 },
667 }
668 }
669 report
670}
671
672/// Says what happened. Prints; decides nothing.
673fn announce(settings: &crate::config::Settings, report: &Report) {
674 if crate::live::quiet(settings) && report.passed > 0 {
675 println!("{} {} check(s) passed", valid_sign(), report.passed);
676 }
677 if !report.fixed.is_empty() {
678 // Louder than a pass, because files on disk are not what the author
679 // left them: they asked for the repair, but they did not watch it.
680 println!(
681 "{} {} check(s) fixed and re-staged: {}",
682 valid_sign(),
683 report.fixed.len(),
684 report.fixed.join(", ")
685 );
686 }
687 if !report.unavailable.is_empty() {
688 // Distinct from "passed". Silence here is how a repo looks verified
689 // when nothing actually ran — the trailing count is the one line
690 // guaranteed to be read, whatever the twenty blocks above said.
691 println!(
692 "{} {} check(s) could not run: {}",
693 warning_sign(),
694 report.unavailable.len(),
695 report.unavailable.join(", ")
696 );
697 }
698 if !report.downgraded.is_empty() {
699 println!(
700 "{} {} check(s) reported a problem but are set to warn: {}",
701 warning_sign(),
702 report.downgraded.len(),
703 report.downgraded.join(", ")
704 );
705 }
706 if report.blocked.is_empty() {
707 return;
708 }
709 println!("\n🚨 Error raised by:");
710 for name in &report.blocked {
711 println!(" - {}", highlight(name));
712 }
713}
714
715/// Point every check at `git ls-files` instead of the index.
716///
717/// THE definition, called from both entry points. There used to be two: this
718/// one, and a copy in `main.rs` built from a RAW `ls-files` — no `-z` — whose
719/// output git QUOTES for any unusual byte, so `é.json` arrived as the nine-byte
720/// literal `"\303\251.json"` and was handed to prettier and eslint as a path
721/// that does not exist. And because `override_file_set` writes a `OnceLock`,
722/// main's quoted list WON: whichever ran first was the one that counted, and
723/// main's ran first. `git.rs` documents this exact failure.
724pub fn enter_all_files_mode() {
725 crate::hooks::common::override_file_set(
726 crate::git::stdout_paths(&["ls-files"]).unwrap_or_default(),
727 );
728}
729
730/// `amont run` — every applicable check, on demand.
731///
732/// Two questions, and the mode says which it answers:
733///
734/// - **staged** (default) is "would my commit pass" — the same set a commit
735/// would check, so it is a rehearsal of the hook, and it takes the same
736/// index-fidelity hold the hook takes.
737/// - **`--all-files`** is "does my working tree pass". Deliberately NOT the same
738/// question: on a dirty tree it reports on content that is not committed and
739/// may never be. That is right for adopting a check into an existing
740/// repository, where `git add .` is not an acceptable way to measure the mess,
741/// and it is why `--all-files` takes no stash — there is no staged/unstaged
742/// distinction to protect when the answer is "all of it".
743pub fn run_all(ctx: &Ctx, all_files: bool) -> Verdict {
744 let settings = ctx.settings;
745 // ORDER: the override goes in FIRST. It is what tells `fixing_enabled` and
746 // `restage` that the file set is not the index, and both are consulted
747 // from inside the checks below.
748 if all_files {
749 enter_all_files_mode();
750 if crate::hooks::common::fixing_requested(settings) {
751 println!(
752 "{} {} is set, but fixing is off for {}: the input set is the \
753 working tree, not the index",
754 warning_sign(),
755 highlight("amont.fix"),
756 highlight("--all-files")
757 );
758 }
759 // Stash-free, per decision 1 of docs/index-fidelity-and-run-modes.md:
760 // there is no staged/unstaged distinction to protect when the input
761 // set is `git ls-files`, so a hold would be surprising extra mutation
762 // with no correctness upside.
763 return run_stage(
764 &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
765 ctx,
766 &Overrides::read(settings),
767 );
768 }
769
770 // Staged mode IS a rehearsal of the commit, so it takes the same hold the
771 // commit does. Without it, `amont run` failed on garbage in the tree
772 // that `git commit` — which holds the unstaged half aside — passed, and
773 // vice versa: the two modes disagreed about the same repository, which is
774 // exactly what this mode exists not to do.
775 let held = match hold_unstaged() {
776 Ok(guard) => guard,
777 Err(verdict) => return verdict,
778 };
779 let verdict = run_stage(
780 &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
781 ctx,
782 &Overrides::read(settings),
783 );
784 // AFTER the report has been printed: dropping earlier would put the
785 // unstaged content back under a check that is still reading files.
786 drop(held);
787 verdict
788}
789
790/// `amont run <check>` — one check by name. `None` when there is no such
791/// check, which the caller turns into a usage error.
792///
793/// Lives here rather than in `main.rs` so `registry::lookup` stays inside the
794/// runtime, and so the hold decision is made once: a named check takes the
795/// index-fidelity hold only when it is a `Stage::PreCommit` check running in
796/// staged mode. A pre-push or commit-msg check invoked by name must never
797/// touch the working tree — nothing about a push is a staging operation.
798/// Resolve what `amont run <name>` means, exactly as `hook.skip` resolves a
799/// name — the rest of the tool taught `ban-terms`; making `run` demand the
800/// full id was a pointless second vocabulary. Ambiguity is an answer, not a
801/// guess: the two `branch-pattern` checks are different code at different
802/// stages.
803///
804/// Public because the CALLER needs the answer before anything else happens:
805/// main decides whether to synthesize push refs from the resolved name, and
806/// an ambiguous name must say so rather than fail on a missing upstream it
807/// was never going to use.
808pub fn resolve_check_name(name: &str, manifest: &crate::manifest::Manifest) -> Named2 {
809 if crate::registry::lookup(name, manifest).is_some() {
810 return Named2::Resolved(name.to_string());
811 }
812 let mut matches: Vec<String> = crate::registry::CHECKS
813 .iter()
814 .map(|c| c.name.to_string())
815 .chain(manifest.externals.iter().map(|e| e.id.clone()))
816 .filter(|id| crate::skip_suppresses(id, name))
817 .collect();
818 matches.dedup();
819 match matches.len() {
820 0 => Named2::Unknown,
821 1 => Named2::Resolved(matches.remove(0)),
822 _ => Named2::Ambiguous(matches),
823 }
824}
825
826/// How a run name resolved.
827pub enum Named2 {
828 Resolved(String),
829 Unknown,
830 Ambiguous(Vec<String>),
831}
832
833pub fn run_named(ctx: &Ctx, name: &str, all_files: bool) -> Named {
834 let full: String = match resolve_check_name(name, ctx.manifest) {
835 Named2::Resolved(id) => id,
836 Named2::Unknown => return Named::Unknown,
837 Named2::Ambiguous(ids) => return Named::Ambiguous(ids),
838 };
839 let name = full.as_str();
840 let Some(run_check) = crate::registry::lookup(name, ctx.manifest) else {
841 return Named::Unknown;
842 };
843 // The Ctx must carry the RESOLVED id: lookup's closure re-resolves
844 // through `ctx.name`, and handing it the short name back would panic on
845 // the very ambiguity this function just settled.
846 let ctx = &Ctx {
847 name,
848 args: ctx.args,
849 hooks_dir: ctx.hooks_dir,
850 push: ctx.push,
851 manifest: ctx.manifest,
852 settings: ctx.settings,
853 };
854 if all_files {
855 enter_all_files_mode();
856 return Named::Ran(run_check(ctx));
857 }
858 let is_pre_commit_check = crate::registry::one_named(name, ctx.manifest)
859 .is_some_and(|c| c.stage() == Stage::PreCommit);
860 if !is_pre_commit_check {
861 return Named::Ran(run_check(ctx));
862 }
863 let held = match hold_unstaged() {
864 Ok(guard) => guard,
865 Err(verdict) => return Named::Ran(verdict),
866 };
867 let verdict = run_check(ctx);
868 drop(held);
869 Named::Ran(verdict)
870}
871
872/// What `run_named` resolved a name to.
873pub enum Named {
874 Ran(Verdict),
875 /// Nothing matches — full id, short name, or entrypoint.
876 Unknown,
877 /// A short name that reaches more than one check; the caller lists them
878 /// so the user can pick a full id.
879 Ambiguous(Vec<String>),
880}
881
882pub fn pre_push(ctx: &Ctx) -> Verdict {
883 let settings = ctx.settings;
884 // `amont.treeLintWait` counts from HERE, so no earlier wait (a test
885 // rehearsal's `amont.rehearsalWait`) can extend it.
886 let push_started = std::time::Instant::now();
887 // The notes push `attest` makes re-enters this hook; its ref list is only
888 // ever the attest ref, so there is nothing to prove — and proving it
889 // would recurse.
890 if crate::attest::push_guard_active() {
891 return Verdict::Proceed;
892 }
893 crate::manifest::verify_tool_pins(&ctx.manifest.pins);
894 announce_policy_state(ctx.settings, ctx.manifest);
895 // NB: no CHERRY_PICK_HEAD check here — the zsh pre-push had none either.
896 let severities = Overrides::read(settings);
897 // pre-push had NO state guard at all, with a comment admitting it existed
898 // only because the zsh version had none. Now it asks the same question
899 // pre-commit does and each check answers for itself.
900 let in_progress = crate::git_states_in_progress();
901 // Declared order unless this repository asked for the other one. The
902 // permutation is decided BEFORE the live stage is begun, because the
903 // stage draws the list in the order it is given.
904 let pre_push_checks = ordered_by_evidence(
905 settings,
906 selected_during(ctx.settings, Stage::PrePush, &in_progress, ctx.manifest),
907 );
908 let stage = crate::live::enabled(settings).then(|| {
909 let names: Vec<&str> = pre_push_checks.iter().map(|c| c.name()).collect();
910 crate::live::Stage::begin(settings, &names)
911 });
912 // What actually PASSED, for the attestation at the bottom. `Warned` and
913 // `Unavailable` stay out — "could not run" is not "passed" — and a
914 // commit-time-gated pair counts, because its stamps say the check ran on
915 // every pushed tree.
916 let mut passed: Vec<String> = Vec::new();
917 // Accumulated rather than written per check: one append at the end costs a
918 // single file open, and the loop below can leave early.
919 let mut downgraded: Vec<(String, crate::downgrade::Origin)> = Vec::new();
920 // PUSH STAMPS. The tips being pushed, and what earlier runs of THIS gate
921 // recorded against their trees — an `amont run pre-push` rehearsal, or a
922 // push whose gate passed and whose transport then died. A scoped gate
923 // (a test suite: its verdict is a function of the tree alone) whose
924 // stamp sits on every tip is not run again; the unscoped ones
925 // (branch-protect, secrets — questions about the push, not the content)
926 // always run. `amont.pushStamps false` turns the reuse off.
927 //
928 // Reading `ctx.push` here may consume stdin, exactly as `attest` does
929 // below; every pre-push check reads it anyway.
930 let tips: Vec<String> = {
931 let mut t: Vec<String> = ctx
932 .push
933 .get()
934 .iter()
935 .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
936 .map(|r| r.local_oid.clone())
937 .collect();
938 t.dedup();
939 t
940 };
941 let reuse_stamps = crate::gate_stamp::push_stamps_enabled(settings);
942 // The working tree AS THE SUITE WILL BE HANDED IT, captured before any
943 // gate has run.
944 //
945 // Timing is the point. Asking afterwards means a gate that modifies a
946 // tracked file — a formatter, a suite that updates a snapshot fixture —
947 // disqualifies its OWN stamp. What a stamp needs to know is what the
948 // suite could READ, which is the state it was handed; a change the suite
949 // itself made was never an input to it.
950 //
951 // Tracked modifications only. `stamp_tips` argues that gap, which is a
952 // deliberate one.
953 let tree_at_start = if reuse_stamps {
954 crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"]).unwrap_or_default()
955 } else {
956 String::new()
957 };
958 // A background rehearsal of one of these tips may be mid-suite right
959 // now. Waiting for it is strictly less work than starting over, and
960 // its stamp — read AFTER the wait, below — is the hand-off.
961 // Only when this push has test gates for the rehearsal to vouch for: a
962 // rehearsal that is only proving tree lint is waited for by the tree
963 // verdict alone, under its own `amont.treeLintWait` (ADR-0024), never
964 // under `amont.rehearsalWait`.
965 if reuse_stamps && !tips.is_empty() {
966 let changed = crate::pushrefs::changed_files(ctx.push.get());
967 if !scoped_push_gates(settings, ctx.manifest, &changed).is_empty() {
968 crate::rehearsal::await_for(settings, &tips);
969 }
970 }
971 let push_stamps = if reuse_stamps && !tips.is_empty() {
972 crate::gate_stamp::stamps_for(&tips)
973 } else {
974 Default::default()
975 };
976 // Inside a rehearsal snapshot only the content gates make sense: the
977 // unscoped checks ask about a PUSH — its branch name, its target, its
978 // secrets — and no push is happening. Said once, not per check.
979 let rehearsing = crate::rehearsal::in_snapshot();
980 if rehearsing {
981 crate::say!(
982 "rehearsal: running the test gates only — the push-shaped checks run at push time"
983 );
984 }
985 let stamped_on_every_tip = |name: &str| -> bool {
986 !tips.is_empty()
987 && tips.iter().all(|t| {
988 push_stamps
989 .get(t)
990 .is_some_and(|s| s.iter().any(|g| g == name))
991 })
992 };
993 // What actually RAN and passed here (as opposed to being vouched for by
994 // a stamp) — the set this run may stamp in turn.
995 let mut ran_and_passed: Vec<String> = Vec::new();
996 // What each gate COST and how it ENDED, for the record `gate_evidence`
997 // reads. Every outcome, failures included: the stamp deliberately has no
998 // opinion about a gate that failed, and a dataset that kept only the
999 // passes could never say a gate is flaky.
1000 let mut evidence: Vec<crate::gate_stamp::Run> = Vec::new();
1001 // The question `amont list` answers with "inert here — needs go.sum":
1002 // does this repository carry the marker that turns the check on? Asked
1003 // of the index, once, and answered the same way here — a check the
1004 // registry calls inert used to run anyway, find its tool or lockfile
1005 // missing, and warn that it "could not run" on every push of a
1006 // repository it was never meant to touch.
1007 let tracked = crate::tracked_paths();
1008 for (idx, check) in pre_push_checks.iter().enumerate() {
1009 if !check.scope().opted_in(&tracked) {
1010 continue;
1011 }
1012 let _sink = stage.as_ref().map(|s| s.enter(idx));
1013 let _flush = stage
1014 .as_ref()
1015 .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, idx));
1016 // A declared pre-push external whose NAME is also declared at
1017 // pre-commit (blocking) is a gate pair: the commit-time side earned
1018 // per-commit stamps, and this side runs only for pushes carrying
1019 // commits with no record of it — the same contract the npm gate has
1020 // always had, for vocabularies npm never heard of (`cargo test`,
1021 // `pytest`, anything). Messages mirror the npm gate's exactly;
1022 // docs/checks.md quotes them.
1023 // The push side of a pair is `(name, scope)`, from whichever of the
1024 // two kinds of check this is. A declared pre-push external supplies
1025 // its own; anything else is a BUILT-IN, and `pairing_name` plus the
1026 // registry's scope say the same two things about it.
1027 //
1028 // The external is tried FIRST and its inputs are unchanged, so the
1029 // declared path behaves exactly as before — that is what the
1030 // untouched declared-pair tests prove.
1031 if rehearsing && check.scope().is_unscoped() {
1032 continue;
1033 }
1034 if !check.scope().is_unscoped() && stamped_on_every_tip(check.name()) {
1035 crate::say!(
1036 "{} {} passed on this exact tree earlier — not repeating it here",
1037 valid_sign(),
1038 highlight(check.name()),
1039 );
1040 passed.push(check.name().to_string());
1041 continue;
1042 }
1043 let declared = ctx
1044 .manifest
1045 .externals
1046 .iter()
1047 .find(|e| e.stage == Stage::PrePush && e.id == check.name());
1048 let builtin_scope = check.scope();
1049 let pairing: Option<(&str, &crate::check::Scope)> = match declared {
1050 Some(ext) => match &ext.kind {
1051 crate::manifest::Kind::Runnable { scope, .. } => {
1052 Some((ext.short_name.as_str(), scope))
1053 }
1054 // A declared pre-push entry that runs nothing has no scope to
1055 // judge with, and is not a built-in either. Nothing to pair.
1056 _ => None,
1057 },
1058 None => Some((check.pairing_name(), &builtin_scope)),
1059 };
1060 if let Some((name, push_scope)) = pairing {
1061 match crate::hooks::run_tests::pair_verdict(
1062 ctx.settings,
1063 name,
1064 push_scope,
1065 ctx.manifest,
1066 ctx.push,
1067 ) {
1068 crate::hooks::run_tests::PairVerdict::Gated => {
1069 crate::say!(
1070 "{} {} gated at commit instead — not repeating it here",
1071 valid_sign(),
1072 highlight(name),
1073 );
1074 passed.push(check.name().to_string());
1075 continue;
1076 }
1077 crate::hooks::run_tests::PairVerdict::Unstamped(n) => {
1078 // `amont.unstampedPush refuse`: never run a suite with
1079 // the remote's connection held open — say how to earn
1080 // the stamp instead. Not inside a rehearsal snapshot:
1081 // running there is how the stamp is earned.
1082 if !rehearsing && crate::rehearsal::refuse_unstamped(ctx.settings) {
1083 crate::say!(
1084 "{} {} is declared at commit time, but {n} pushed \
1085 commit{} carr{} no record of it (rewritten by a \
1086 rebase or amend, or made without the hooks) — \
1087 refusing the push",
1088 warning_sign(),
1089 name,
1090 if n == 1 { "" } else { "s" },
1091 if n == 1 { "ies" } else { "y" },
1092 );
1093 crate::say!(
1094 " Test this tree first, with no push waiting on it: {} — then push again",
1095 highlight("amont rehearse --wait"),
1096 );
1097 crate::downgrade::note(settings, &downgraded);
1098 record_evidence(&tips, &evidence);
1099 println!("\n🚨 Error raised by hook {}", highlight(check.name()));
1100 return Verdict::Block;
1101 }
1102 crate::say!(
1103 "{} {} is declared at commit time, but {n} pushed \
1104 commit{} carr{} no record of it — running it here",
1105 warning_sign(),
1106 name,
1107 if n == 1 { "" } else { "s" },
1108 if n == 1 { "ies" } else { "y" },
1109 );
1110 }
1111 crate::hooks::run_tests::PairVerdict::NotPaired => {}
1112 }
1113 }
1114 let sub = Ctx {
1115 name: check.name(),
1116 args: ctx.args,
1117 hooks_dir: ctx.hooks_dir,
1118 push: ctx.push,
1119 manifest: ctx.manifest,
1120 settings: ctx.settings,
1121 };
1122 // Wall clock around the check itself, not around the hook: the number
1123 // that catches a suite which stopped finding tests is how long THAT
1124 // gate took, and everything outside this call is bookkeeping.
1125 let started = std::time::Instant::now();
1126 let outcome = check.run(&sub);
1127 evidence.push(crate::gate_stamp::Run {
1128 at: crate::gate_evidence::now(),
1129 gate: check.name().to_string(),
1130 outcome: run_outcome(outcome),
1131 ms: started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
1132 });
1133 match outcome {
1134 Outcome::Passed => {
1135 passed.push(check.name().to_string());
1136 if !check.scope().is_unscoped() {
1137 ran_and_passed.push(check.name().to_string());
1138 }
1139 }
1140 // Announced, never fatal: a check that could not run has not
1141 // invalidated anything, and neither has a warning.
1142 Outcome::Unavailable => {
1143 println!(
1144 "{} {} could not run",
1145 warning_sign(),
1146 highlight(check.name())
1147 )
1148 }
1149 Outcome::Warned => {}
1150 // Nothing to judge: not passed (nothing to stamp or attest), not
1151 // a gap (nothing is missing). The dispatcher asked the registry's
1152 // opt-in question above; this is a check answering it for itself.
1153 Outcome::Inert => {}
1154 // Cannot occur: `Fix::Rewrite` is refused on a pre-push
1155 // declaration, so nothing here can repair anything.
1156 Outcome::Fixed => {}
1157 Outcome::Failed => match severities.of(*check) {
1158 Severity::Warn => {
1159 downgraded.push((
1160 check.name().to_string(),
1161 downgrade_origin(*check, &severities),
1162 ));
1163 println!(
1164 "{} {} reported a problem (severity warn)",
1165 warning_sign(),
1166 highlight(check.name())
1167 );
1168 }
1169 // Fail-fast applies ONLY to Block: the later steps are
1170 // expensive and their preconditions are gone.
1171 Severity::Block => {
1172 // Record what already warned before leaving. Those checks
1173 // ran and reported; a later check blocking does not unmake
1174 // them, and dropping them here would make the ledger quietly
1175 // under-count every push that ended badly.
1176 crate::downgrade::note(settings, &downgraded);
1177 // The same argument for the evidence, and it matters more
1178 // here: this is the path a FAILURE leaves by, and a record
1179 // written only on the way out of a successful push would
1180 // be a dataset of passes calling itself a dataset of runs.
1181 record_evidence(&tips, &evidence);
1182 println!("\n🚨 Error raised by hook {}", highlight(check.name()));
1183 return Verdict::Block;
1184 }
1185 },
1186 }
1187 }
1188 // Every block gate passed — stamp the tips with the scoped gates that
1189 // RAN here, so the next push of this content (a retry after a dropped
1190 // connection, or the real push after an `amont run pre-push` rehearsal)
1191 // skips them. Only when what ran is what is being pushed: with
1192 // `amont.testPushedTree` the suite ran on the tip itself — unless the
1193 // snapshot could not be made, which `stamp_tips` asks about rather than
1194 // assuming; otherwise it ran on the working tree, which vouches for the
1195 // tip only when the two are the same content — HEAD, with nothing
1196 // modified and nothing untracked.
1197 // The same proxy `attestable` uses, for the same reason: a scoped gate
1198 // whose files the push never touched returns `Passed` having run
1199 // nothing, and a stamp for THAT would let a later push that does touch
1200 // them skip a suite nobody ran.
1201 if reuse_stamps && !ran_and_passed.is_empty() {
1202 let changed = crate::pushrefs::changed_files(ctx.push.get());
1203 let really_ran: Vec<String> = pre_push_checks
1204 .iter()
1205 .filter(|c| ran_and_passed.iter().any(|p| p == c.name()))
1206 .filter(|c| c.scope().touches(&changed))
1207 .map(|c| c.name().to_string())
1208 .collect();
1209 stamp_tips(&tips, &really_ran, &tree_at_start);
1210 }
1211 // …and say so to CI, if this repository opted in.
1212 // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
1213 // `ctx.push` may consume stdin, and a disabled repo should leave stdin
1214 // exactly as it found it.
1215 // Tree gates (ADR-0024) are not push checks: nothing runs here. Each is
1216 // attested only when the TREE of every pushed tip carries its commit-time
1217 // proof; a whole-tree proof needs no changed-files scope. Fail-closed:
1218 // anything else is simply not attested, and CI lints.
1219 let (tree_proven, tree_unproven) =
1220 if !ctx.manifest.tree.is_empty() && crate::attest::enabled(settings) {
1221 crate::tree_lint::await_verdict(settings, &ctx.manifest.tree, &tips, push_started)
1222 } else {
1223 (Vec::new(), Vec::new())
1224 };
1225 if !tree_unproven.is_empty() {
1226 crate::hooks::common::say(&crate::tree_lint::fit_line(
1227 " lint not attested (cold or changed tree): ",
1228 &tree_unproven.join(" "),
1229 " — CI will lint",
1230 ));
1231 }
1232 if (!passed.is_empty() || !tree_proven.is_empty()) && crate::attest::enabled(settings) {
1233 let remote = ctx
1234 .args
1235 .first()
1236 .map(|a| a.to_string_lossy().into_owned())
1237 .unwrap_or_default();
1238 let changed = crate::pushrefs::changed_files(ctx.push.get());
1239 let mut vouched = attestable(&pre_push_checks, &passed, &changed);
1240 vouched.extend(tree_proven);
1241 crate::attest::attest_push(ctx.settings, &remote, ctx.push.get(), &vouched);
1242 }
1243 crate::downgrade::note(settings, &downgraded);
1244 record_evidence(&tips, &evidence);
1245 Verdict::Proceed
1246}
1247
1248/// What one check's outcome is called in the record.
1249fn run_outcome(outcome: Outcome) -> crate::gate_stamp::RunOutcome {
1250 use crate::gate_stamp::RunOutcome as R;
1251 match outcome {
1252 Outcome::Passed => R::Passed,
1253 Outcome::Failed => R::Failed,
1254 Outcome::Warned => R::Warned,
1255 Outcome::Fixed => R::Fixed,
1256 Outcome::Unavailable => R::Unavailable,
1257 Outcome::Inert => R::Inert,
1258 }
1259}
1260
1261/// File this push's runs under the content they judged.
1262///
1263/// ONE key, not one per tip: a push of two branches ran each gate once, and
1264/// writing the same run onto both trees would make a report count it twice.
1265/// The first tip's tree is that key, falling back to `HEAD` — and to nothing
1266/// at all when git will not name either, which costs a row in a report and
1267/// never a verdict.
1268fn record_evidence(tips: &[String], runs: &[crate::gate_stamp::Run]) {
1269 if runs.is_empty() {
1270 return;
1271 }
1272 let tree = tips
1273 .first()
1274 .and_then(|tip| crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]))
1275 .or_else(|| crate::git::stdout(&["rev-parse", "HEAD^{tree}"]));
1276 if let Some(tree) = tree {
1277 crate::gate_stamp::record_runs(&tree, runs);
1278 }
1279}
1280
1281/// The scoped pre-push gates — test suites — that have work to do for a
1282/// push that changed `changed`: what a rehearsal would run, and therefore
1283/// what its stamp would have to name before a push may skip anything.
1284///
1285/// The same two filters `pre_push` applies before stamping (selected here,
1286/// and `scope().touches` the change), so the rehearsal's idea of "nothing to
1287/// do" is the push's idea of "nothing to stamp".
1288pub fn scoped_push_gates(
1289 settings: &crate::config::Settings,
1290 manifest: &crate::manifest::Manifest,
1291 changed: &[String],
1292) -> Vec<String> {
1293 let in_progress = crate::git_states_in_progress();
1294 let tracked = crate::tracked_paths();
1295 selected_during(settings, Stage::PrePush, &in_progress, manifest)
1296 .into_iter()
1297 .filter(|c| !c.scope().is_unscoped() && c.scope().touches(changed))
1298 // The same opt-in gate `pre_push` applies: a suite the repository
1299 // never turned on is not work a rehearsal owes a stamp for.
1300 .filter(|c| c.scope().opted_in(&tracked))
1301 .map(|c| c.name().to_string())
1302 .collect()
1303}
1304
1305/// Push-stamp every tip whose content is what the gates actually tested.
1306///
1307/// See the comment at the call site for the two cases. Silent when nothing
1308/// qualifies — a dirty working tree is the ordinary state of a machine
1309/// mid-work, and a note on every push would teach people to ignore it.
1310fn stamp_tips(tips: &[String], gates: &[String], tree_at_start: &str) {
1311 let head = crate::git::stdout(&["rev-parse", "HEAD"]);
1312 // TRACKED modifications only — a KNOWN gap, kept deliberately, and
1313 // spelled out because the comment that used to sit here argued it
1314 // backwards ("untracked files are not in any tree the suite could have
1315 // been asked about"). That is not the reason. The danger is not that the
1316 // tree lacks them, it is that the RUN had them: a new test file, a
1317 // fixture, a local `.env`, present while the suite ran and absent from
1318 // the tree the stamp vouches for.
1319 //
1320 // Counting them was tried, and is worse than the gap. Gates leave
1321 // artefacts — a log, a coverage directory, whatever a declared
1322 // `amont.conf` command writes — and nothing cleans them up, so a
1323 // repository using declared gates would stop earning stamps permanently
1324 // after its first commit. That does not merely lose an optimisation: it
1325 // puts the suite back INSIDE the push, which is the failure the whole
1326 // stamping mechanism exists to prevent. amont's own
1327 // `a_push_stamp_merges_with_a_commit_time_stamp` fixture is exactly that
1328 // shape, and CI is where it surfaced — a `*.log` line in one developer's
1329 // global gitignore had hidden it on the machine that wrote the change.
1330 //
1331 // `amont.testPushedTree true` closes the gap properly for anyone who
1332 // wants it closed: it runs the suite in a checkout of the commit, where
1333 // no untracked file exists to be read.
1334 //
1335 // `tree_at_start` — not a fresh `git status`. The gates have run by now
1336 // and may have written into the tree; what a stamp needs to know is what
1337 // the suite could READ, which is the state it was handed. See the
1338 // capture in `pre_push`.
1339 let worktree_clean = tree_at_start.trim().is_empty();
1340 let in_snapshot = crate::rehearsal::in_snapshot();
1341 let mut stamped: Vec<String> = Vec::new();
1342 for tip in tips {
1343 // Inside a rehearsal the working tree IS a checkout git made of this
1344 // commit, so it is the tip's content by construction — and whatever
1345 // `amont.snapshotPrepare` had to add to make it runnable (a
1346 // `node_modules`, a virtualenv) is not a reason to distrust it. That
1347 // is the same argument a pushed-tree snapshot makes.
1348 let is_head = head.as_deref() == Some(tip.as_str());
1349 let tree_is_tip = is_head && (in_snapshot || worktree_clean);
1350 // PER GATE, from what each one actually did — not from the config.
1351 // `amont.testPushedTree` is a request; `pushed_tree::ran_on_tip` is
1352 // the record of which gates were handed a checkout of this tip. A
1353 // gate that ran somewhere else (a snapshot that could not be made,
1354 // or a check that ran in the working tree) may vouch for the tip
1355 // only when the working tree WAS the tip. Deciding from the flag
1356 // stamped every passing gate onto a tip that one of them had never
1357 // seen.
1358 let vouched: Vec<String> = gates
1359 .iter()
1360 .filter(|g| tree_is_tip || crate::pushed_tree::ran_on_tip(g, tip))
1361 .cloned()
1362 .collect();
1363 if vouched.is_empty() {
1364 continue;
1365 }
1366 let spec = format!("{tip}^{{tree}}");
1367 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
1368 continue;
1369 };
1370 if crate::gate_stamp::stamp_push(tip, &tree, &vouched) {
1371 for g in vouched {
1372 if !stamped.contains(&g) {
1373 stamped.push(g);
1374 }
1375 }
1376 }
1377 }
1378 if !stamped.is_empty() {
1379 crate::say!(
1380 "{} stamped {} for this tree — the next push of it skips them ({})",
1381 valid_sign(),
1382 highlight(&stamped.join(" ")),
1383 crate::gate_stamp::NOTES_REF,
1384 );
1385 }
1386}
1387
1388/// Of the checks that passed, the ones an attestation may actually VOUCH for.
1389///
1390/// A language gate whose scope the push never touched returns `Passed` having
1391/// run nothing — `cargo_test` walks its refs, finds no crate root, and falls
1392/// out of the loop green. That is right for a push gate (there was nothing to
1393/// object to) and wrong for an attestation: a JS-only push was minting
1394/// `gates … pre-push-cargo-test pre-push-go-test pre-push-pytest`, and in a
1395/// MIXED repository CI would then skip a suite that nobody ran on that tree.
1396///
1397/// The declared `scope` is the honest filter, and the same data `amont list`
1398/// already reports. Unscoped checks (`Scope::ALWAYS` — branch-protect,
1399/// secrets) match everything and are vouched for, which is accurate: they
1400/// really did run. An empty `changed` vouches for nothing scoped, which is
1401/// the safe direction — CI runs the suite.
1402///
1403/// [`Scope::touches`], NOT `Scope::matches`. `matches` also asks whether the
1404/// repository has opted in — whether a `Cargo.toml` exists — and asking that
1405/// of a push DIFF can only answer no unless the push happened to touch the
1406/// marker. So `pre-push-cargo-test` was vouched for by a push that edited
1407/// `Cargo.toml` and never by one that edited only `.rs` files, which is the
1408/// ordinary case and the one worth skipping CI for. The feature attested
1409/// almost nothing, silently, and looked like it worked.
1410///
1411/// WHAT THIS IS STILL A PROXY FOR, stated plainly because the trust path
1412/// deserves it: the honest question is "did this gate actually run", and no
1413/// gate reports that. `rust_tools::test` returns `Passed` whether it ran a
1414/// suite or found no crate root and fell out of its loop — the very thing
1415/// the first paragraph describes. Scope is the closest available stand-in.
1416/// It is now a good one: a gate is vouched for only if the push changed a
1417/// file its extensions cover.
1418///
1419/// The gap that remains is narrow and one-directional: a `.rs` file outside
1420/// every crate would be covered here while `cargo test` had nothing to say
1421/// about it. Closing it properly means an outcome that distinguishes "ran
1422/// and passed" from "found nothing to do", which is a change to every gate
1423/// and to `Outcome` itself — worth doing, not worth smuggling into this.
1424fn attestable(checks: &[&dyn Check], passed: &[String], changed: &[String]) -> Vec<String> {
1425 checks
1426 .iter()
1427 .filter(|c| passed.iter().any(|p| p == c.name()))
1428 .filter(|c| c.scope().touches(changed))
1429 .map(|c| c.name().to_string())
1430 .collect()
1431}
1432
1433#[cfg(test)]
1434mod tests {
1435 use super::*;
1436 use crate::check::{Builtin, Scope};
1437 use std::sync::atomic::{AtomicUsize, Ordering};
1438
1439 /// A check whose only job is to carry a name and a severity into `report`.
1440 /// Its `run` is never called — `report` is fed outcomes directly, which is
1441 /// what makes `Unavailable` testable at all: the real thing needs a missing
1442 /// binary, and a test that uninstalls the developer's toolchain is worse
1443 /// than no test.
1444 const fn stub(name: &'static str, severity: Severity) -> Builtin {
1445 Builtin {
1446 name,
1447 stage: Stage::PreCommit,
1448 scope: Scope::ALWAYS,
1449 severity,
1450 run: |_| Outcome::Passed,
1451 fix: crate::check::Fix::None,
1452 reach: crate::check::Reach::Convention,
1453 }
1454 }
1455
1456 /// A pre-push gate with an OPT-IN file, as the real Rust and Python
1457 /// gates have: `.rs` files, but only where a `Cargo.toml` exists.
1458 const fn opt_in(
1459 name: &'static str,
1460 exts: &'static [&'static str],
1461 names: &'static [&'static str],
1462 ) -> Builtin {
1463 Builtin {
1464 name,
1465 stage: Stage::PrePush,
1466 scope: Scope::new(exts, names),
1467 severity: Severity::Block,
1468 run: |_| Outcome::Passed,
1469 fix: crate::check::Fix::None,
1470 reach: crate::check::Reach::Convention,
1471 }
1472 }
1473
1474 /// A pre-push gate scoped to one language's files.
1475 const fn scoped(name: &'static str, exts: &'static [&'static str]) -> Builtin {
1476 Builtin {
1477 name,
1478 stage: Stage::PrePush,
1479 scope: Scope::new(exts, &[]),
1480 severity: Severity::Block,
1481 run: |_| Outcome::Passed,
1482 fix: crate::check::Fix::None,
1483 reach: crate::check::Reach::Convention,
1484 }
1485 }
1486
1487 /// The over-claim this filter exists to stop, caught in the wild: a
1488 /// JS-only push minted `gates … pre-push-cargo-test pre-push-go-test
1489 /// pre-push-pytest`, because each of those gates finds nothing of its
1490 /// language to do and returns `Passed` having run NOTHING. Harmless in a
1491 /// single-language repo, unsound in a mixed one — CI would skip a suite
1492 /// nobody ran on that tree.
1493 #[test]
1494 fn a_gate_whose_language_the_push_never_touched_is_not_vouched_for() {
1495 let js = scoped("pre-push-run-tests-js", &[".ts", ".js"]);
1496 let rust = scoped("pre-push-cargo-test", &[".rs"]);
1497 let py = scoped("pre-push-pytest", &[".py"]);
1498 let always = stub("pre-push-secrets", Severity::Block);
1499 let checks: Vec<&dyn Check> = vec![&js, &rust, &py, &always];
1500 let passed: Vec<String> = checks.iter().map(|c| c.name().to_string()).collect();
1501
1502 let changed = vec!["app/routes/home.ts".to_string()];
1503 let vouched = attestable(&checks, &passed, &changed);
1504 assert_eq!(
1505 vouched,
1506 vec![
1507 "pre-push-run-tests-js".to_string(),
1508 "pre-push-secrets".to_string()
1509 ],
1510 "only the gate that had work, plus the unscoped one that always runs"
1511 );
1512
1513 // Nothing computed about the push vouches for nothing scoped — the
1514 // safe direction, since CI then runs the suite.
1515 assert_eq!(
1516 attestable(&checks, &passed, &[]),
1517 vec!["pre-push-secrets".to_string()]
1518 );
1519
1520 // A check that did NOT pass is never vouched for, whatever its scope.
1521 let only_rust_passed = vec!["pre-push-cargo-test".to_string()];
1522 assert!(attestable(&checks, &only_rust_passed, &changed).is_empty());
1523 }
1524
1525 /// No overrides configured. `report` takes them as a VALUE now, so its
1526 /// tests need no repository and no git at all.
1527 fn none() -> Overrides {
1528 Overrides::default()
1529 }
1530
1531 static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
1532 static WARNER: Builtin = stub("stub-warner", Severity::Warn);
1533
1534 /// The unit tests hold `&dyn Check` for the same reason the dispatcher
1535 /// does: `report` must not be able to tell a built-in from an external.
1536 const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
1537 [cs[0], cs[1], cs[2]]
1538 }
1539
1540 /// The classification itself, which used to be unreachable: while one
1541 /// function classified AND printed AND returned a code, a test could assert
1542 /// the code and nothing else.
1543 #[test]
1544 fn every_outcome_lands_in_the_right_bucket() {
1545 let checks: [&dyn Check; 5] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER, &BLOCKER];
1546 let got = classify(
1547 &checks,
1548 &[
1549 Outcome::Passed,
1550 Outcome::Unavailable,
1551 Outcome::Failed,
1552 Outcome::Failed,
1553 Outcome::Inert,
1554 ],
1555 &none(),
1556 );
1557 assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
1558 assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
1559 assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
1560 assert_eq!(got.passed, 1, "inert is not a pass: {got:?}");
1561 }
1562
1563 /// A clean stage concludes nothing at all — not an empty message, no
1564 /// message. Twenty checks that passed should print no roll-ups.
1565 ///
1566 /// `passed` is a tally, not a roll-up. It exists so that `amont.quiet` can
1567 /// say how many lines it swallowed, and it must never be the reason this
1568 /// report looks like it has something to announce.
1569 #[test]
1570 fn a_clean_stage_has_nothing_to_report() {
1571 let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
1572 let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
1573 assert!(
1574 got.fixed.is_empty()
1575 && got.blocked.is_empty()
1576 && got.downgraded.is_empty()
1577 && got.unavailable.is_empty(),
1578 "a clean stage found something to announce: {got:?}"
1579 );
1580 assert_eq!(got.passed, 1, "the pass was not tallied: {got:?}");
1581 assert_eq!(got.verdict(), Verdict::Proceed);
1582 }
1583
1584 #[test]
1585 fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
1586 let b: &dyn Check = &BLOCKER;
1587 let w: &dyn Check = &WARNER;
1588 assert_eq!(
1589 classify(&[b], &[Outcome::Failed], &none()).verdict(),
1590 Verdict::Block
1591 );
1592 assert_eq!(
1593 classify(&[b], &[Outcome::Passed], &none()).verdict(),
1594 Verdict::Proceed
1595 );
1596 // Every non-blocking shape, one at a time, so a regression cannot hide
1597 // behind a passing sibling.
1598 assert_eq!(
1599 classify(&[b], &[Outcome::Warned], &none()).verdict(),
1600 Verdict::Proceed
1601 );
1602 assert_eq!(
1603 classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
1604 Verdict::Proceed
1605 );
1606 assert_eq!(
1607 classify(&[w], &[Outcome::Failed], &none()).verdict(),
1608 Verdict::Proceed
1609 );
1610 }
1611
1612 #[test]
1613 fn one_blocking_failure_among_many_still_fails() {
1614 let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
1615 assert_eq!(
1616 classify(
1617 &checks,
1618 &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
1619 &none()
1620 )
1621 .verdict(),
1622 Verdict::Block
1623 );
1624 // Same shape, with the only *blocking* failure removed.
1625 assert_eq!(
1626 classify(
1627 &checks,
1628 &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
1629 &none()
1630 )
1631 .verdict(),
1632 Verdict::Proceed
1633 );
1634 }
1635
1636 /// The slot of a check whose thread died. Reading that as a pass is how a
1637 /// crash becomes a green commit.
1638 ///
1639 /// Asserted through the RUNNER, not through a `Default` impl: the rule
1640 /// belongs to this call site, and a test on `Outcome::default()` proved
1641 /// only that a trait impl existed, not that the runner used it.
1642 /// A check that PANICS must fail the commit, not pass it — and must not
1643 /// take the other checks down with it.
1644 ///
1645 /// Driven through the stage body rather than the runner, because the value
1646 /// that stands in for a dead check is chosen at the call site and the
1647 /// runner's own test cannot see that choice.
1648 #[test]
1649 fn a_panicking_check_blocks_the_commit() {
1650 static DIES: Builtin = Builtin {
1651 name: "stub-dies",
1652 stage: Stage::PreCommit,
1653 scope: Scope::ALWAYS,
1654 severity: Severity::Block,
1655 run: |_| panic!("this check died"),
1656 fix: crate::check::Fix::None,
1657 reach: crate::check::Reach::Convention,
1658 };
1659 let hook = std::panic::take_hook();
1660 std::panic::set_hook(Box::new(|_| {}));
1661 let push = crate::pushrefs::PushRefs::default();
1662 let manifest = crate::manifest::Manifest::default();
1663 let settings = crate::config::Settings::default();
1664 let ctx = Ctx {
1665 name: "pre-commit",
1666 args: &[],
1667 hooks_dir: std::path::Path::new("."),
1668 push: &push,
1669 manifest: &manifest,
1670 settings: &settings,
1671 };
1672 let verdict = run_stage(&[&DIES], &ctx, &none());
1673 std::panic::set_hook(hook);
1674 assert_eq!(
1675 verdict,
1676 Verdict::Block,
1677 "a check that died must not let the commit through"
1678 );
1679 }
1680
1681 #[test]
1682 fn a_thread_that_dies_leaves_a_failure_behind() {
1683 // The default hook would print a backtrace for the deliberate panic and
1684 // make a passing run look broken.
1685 let hook = std::panic::take_hook();
1686 std::panic::set_hook(Box::new(|_| {}));
1687 let items = ["a", "b", "c"];
1688 let out = run_concurrently(
1689 &items,
1690 |n: &&str| {
1691 if *n == "b" {
1692 panic!("this check died");
1693 }
1694 Outcome::Passed
1695 },
1696 Outcome::Failed,
1697 );
1698 std::panic::set_hook(hook);
1699 assert_eq!(
1700 out,
1701 vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
1702 "a dead check must not read as one that passed, \
1703 and must not take the other checks down with it"
1704 );
1705 }
1706 use std::time::{Duration, Instant};
1707
1708 /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
1709 /// observe all the others arrive. Were the runner serial, the first task
1710 /// would wait alone, time out, and return non-zero — a failure, not a hang.
1711 #[test]
1712 fn run_concurrently_actually_overlaps() {
1713 static ARRIVED: AtomicUsize = AtomicUsize::new(0);
1714 ARRIVED.store(0, Ordering::SeqCst);
1715 let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
1716 let n = names.len();
1717
1718 let out = run_concurrently(
1719 &names,
1720 move |_: &&str| {
1721 ARRIVED.fetch_add(1, Ordering::SeqCst);
1722 let deadline = Instant::now() + Duration::from_secs(10);
1723 while ARRIVED.load(Ordering::SeqCst) < n {
1724 if Instant::now() > deadline {
1725 return 1; // never met the others — execution was serial
1726 }
1727 std::thread::yield_now();
1728 }
1729 0
1730 },
1731 1,
1732 );
1733 assert!(
1734 out.iter().all(|c| *c == 0),
1735 "tasks did not overlap: {out:?}"
1736 );
1737 }
1738
1739 #[test]
1740 fn results_come_back_in_input_order() {
1741 let names: Vec<&'static str> = vec!["first", "second", "third"];
1742 let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
1743 assert_eq!(out, vec![0, 7, 0], "results keep the input order");
1744 }
1745
1746 /// The filter calls the shared resolver rather than restating it. This test
1747 /// used to inline `n.contains(s)` — its own copy of the rule — and so went
1748 /// on passing after the rule changed underneath it.
1749 #[test]
1750 fn skips_are_filtered_by_the_shared_resolver() {
1751 let all = ["pre-commit-ruff", "pre-commit-prettier"];
1752 let skips = ["ruff".to_string()];
1753 let kept: Vec<_> = all
1754 .iter()
1755 .copied()
1756 .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
1757 .collect();
1758 assert_eq!(kept, vec!["pre-commit-prettier"]);
1759 }
1760
1761 /// The ordinary Rust push: source changed, `Cargo.toml` untouched.
1762 ///
1763 /// This test used to assert the OPPOSITE, and said so — it pinned
1764 /// `attestable` filtering on `Scope::matches`, which also asks whether
1765 /// the repository has opted in. Asking that of a push diff meant a
1766 /// `.rs`-only push, in a repository with a `Cargo.toml` sitting right
1767 /// there, attested nothing. Since that is what nearly every Rust push
1768 /// looks like, the feature was attesting almost nothing at all — quietly,
1769 /// while appearing to work.
1770 #[test]
1771 fn an_ordinary_source_push_is_vouched_for() {
1772 let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
1773 let checks: Vec<&dyn Check> = vec![&rust];
1774 let passed = vec!["pre-push-cargo-test".to_string()];
1775
1776 let changed = vec!["crates/amont/src/main.rs".to_string()];
1777 assert_eq!(
1778 attestable(&checks, &passed, &changed),
1779 vec!["pre-push-cargo-test".to_string()],
1780 "a push that changed Rust must vouch for the Rust gate"
1781 );
1782
1783 // And still when the marker IS in the diff — the opt-in file is not
1784 // required, but it is not disqualifying either.
1785 let changed = vec![
1786 "crates/amont/src/main.rs".to_string(),
1787 "Cargo.toml".to_string(),
1788 ];
1789 assert_eq!(
1790 attestable(&checks, &passed, &changed),
1791 vec!["pre-push-cargo-test".to_string()]
1792 );
1793 }
1794
1795 /// The over-claim the filter exists to stop, with an opt-in gate: a
1796 /// JS-only push must not vouch for the Rust suite, whatever files the
1797 /// repository contains.
1798 ///
1799 /// This is the half of the contract the fix above must not have broken,
1800 /// and it is the reason `touches` asks about EXTENSIONS rather than
1801 /// dropping the scope test altogether.
1802 #[test]
1803 fn an_opt_in_gate_is_not_vouched_for_by_a_push_in_another_language() {
1804 let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
1805 let checks: Vec<&dyn Check> = vec![&rust];
1806 let passed = vec!["pre-push-cargo-test".to_string()];
1807
1808 for changed in [
1809 vec!["app/routes/home.ts".to_string()],
1810 // Even the marker alone: editing Cargo.toml changes no Rust
1811 // source, so the suite has nothing new to have verified.
1812 vec!["Cargo.toml".to_string()],
1813 vec![],
1814 ] {
1815 assert!(
1816 attestable(&checks, &passed, &changed).is_empty(),
1817 "must not vouch for the Rust gate on {changed:?}"
1818 );
1819 }
1820 }
1821}