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