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(settings, &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 // A stamp or a cluster proof is by tree, so it answers only for a gate
1491 // that blocks: a `warn` gate's verdict may read more than the tree
1492 // (f129), and a stamp written before it was `warn`, or by an older
1493 // greengate, must not skip it.
1494 if stamped_push_gate(check)
1495 && severities.of(check) == Severity::Block
1496 && (stamped_on_every_tip(check.name()) || cluster_stamped(check.name()))
1497 {
1498 return Decision::Skip(Skip::Stamped);
1499 }
1500 if gate_before_push && reuse_stamps && stamped_push_gate(check) {
1501 let done = crate::gate_identity::token(&ctx.manifest.externals, check.name())
1502 .is_some_and(|token| {
1503 crate::gate_stamp::done_on_every(&tips, &token, severities.of(check))
1504 });
1505 if done {
1506 return Decision::Skip(Skip::CompletedEarlier);
1507 }
1508 }
1509 let declared = ctx
1510 .manifest
1511 .externals
1512 .iter()
1513 .find(|e| e.stage == Stage::PrePush && e.id == check.name());
1514 // A `platform=any` push gate whose commit twin declares the same suite
1515 // and was proved on the cluster on every tip's tree is gated at commit
1516 // too, and counts as a cluster pass under its own id (ADR-0016).
1517 if let Some(push_gate) = declared.filter(|_| reuse_stamps) {
1518 let claimed_from_twin = ctx
1519 .manifest
1520 .externals
1521 .iter()
1522 .filter(|e| e.stage == Stage::PreCommit && e.short_name == push_gate.short_name)
1523 .any(|twin| {
1524 crate::cluster::claim_twin_cluster_pass(settings, push_gate, twin, &tips)
1525 });
1526 if claimed_from_twin {
1527 return Decision::Skip(Skip::TwinOnCluster(push_gate.short_name.clone()));
1528 }
1529 }
1530 // The push side of a pair is `(name, scope)`, from whichever of the
1531 // two kinds of check this is. A declared pre-push external supplies
1532 // its own; anything else is a BUILT-IN, and `pairing_name` plus the
1533 // registry's scope say the same two things about it.
1534 let builtin_scope = check.scope();
1535 let pairing: Option<(&str, &crate::check::Scope)> = match declared {
1536 Some(ext) => match &ext.kind {
1537 crate::manifest::Kind::Runnable { scope, .. } => {
1538 Some((ext.short_name.as_str(), scope))
1539 }
1540 // A declared pre-push entry that runs nothing has no scope to
1541 // judge with, and is not a built-in either. Nothing to pair.
1542 _ => None,
1543 },
1544 None => Some((check.pairing_name(), &builtin_scope)),
1545 };
1546 let Some((name, push_scope)) = pairing else {
1547 return Decision::Run {
1548 unstamped_pair: None,
1549 unpaired: None,
1550 };
1551 };
1552 match crate::hooks::run_tests::pair_verdict(
1553 ctx.settings,
1554 name,
1555 push_scope,
1556 ctx.manifest,
1557 ctx.push,
1558 ) {
1559 crate::hooks::run_tests::PairVerdict::Gated(coverage) => {
1560 Decision::Skip(Skip::GatedAtCommit {
1561 name: name.to_string(),
1562 coverage,
1563 })
1564 }
1565 crate::hooks::run_tests::PairVerdict::Deferred(n) => {
1566 Decision::Skip(Skip::DeferredAtCommit(name.to_string(), n))
1567 }
1568 crate::hooks::run_tests::PairVerdict::Unstamped(n) => Decision::Run {
1569 unstamped_pair: Some((name.to_string(), n)),
1570 unpaired: None,
1571 },
1572 crate::hooks::run_tests::PairVerdict::NotPaired(why) => Decision::Run {
1573 unstamped_pair: None,
1574 unpaired: why.map(|why| (name.to_string(), why)),
1575 },
1576 }
1577 };
1578 // The question `amont list` answers with "inert here — needs go.sum",
1579 // asked of the index once (see the loop below).
1580 let tracked = crate::tracked_paths();
1581 // ADR-0018: refuse before any heavy gate starts. The gates this push
1582 // owes are the scoped ones its range touches (`scoped_push_gates`, the
1583 // same set a rehearsal stamps); each is asked `decide`, and any it would
1584 // have to RUN means the push refuses.
1585 if gate_before_push && !tips.is_empty() {
1586 let changed = crate::pushrefs::changed_files(ctx.push.get());
1587 let owed = scoped_push_gates(settings, ctx.manifest, &changed);
1588 // Why each owed gate would run, kept from the one `decide` that found
1589 // it missing: the reasons are printed ahead of the refusal without
1590 // asking the gate a second time.
1591 let reasons: std::cell::RefCell<Vec<(String, crate::hooks::run_tests::WhyNot)>> =
1592 std::cell::RefCell::new(Vec::new());
1593 let missing: Vec<&str> = pre_push_checks
1594 .iter()
1595 .filter(|c| {
1596 if crate::hooks::audit::is_audit(c.name()) {
1597 // Owed on every push it is opted into, whatever the
1598 // range touches, unless a fresh record answers for it.
1599 c.scope().opted_in(&tracked)
1600 && crate::hooks::audit::owed(settings, ctx.audits, c.name(), ctx.push.get())
1601 } else {
1602 // A declared command whose program is not installed can
1603 // never be stamped or recorded, so no pre-stage could
1604 // answer for it: owing it would refuse every push for
1605 // good. It runs below instead, fails to start, and warns,
1606 // as before 2.0. Only that: a gate whose token failed for
1607 // another reason stays owed.
1608 owed.iter().any(|o| o == c.name())
1609 && !crate::gate_identity::program_missing(&ctx.manifest.externals, c.name())
1610 && match decide(**c) {
1611 Decision::Run { unpaired, .. } => {
1612 reasons.borrow_mut().extend(unpaired);
1613 true
1614 }
1615 Decision::Skip(_) => false,
1616 }
1617 }
1618 })
1619 .map(|c| c.name())
1620 .collect();
1621 if !missing.is_empty() {
1622 let short: String = tips
1623 .first()
1624 .map(|t| t.chars().take(8).collect())
1625 .unwrap_or_default();
1626 // Why a pair did not vouch comes BEFORE the refusal: refusing is the
1627 // default for a bare push, so a refused push is where a silent
1628 // "it would have run the suite again" went unexplained.
1629 for (name, why) in reasons.borrow().iter() {
1630 crate::hooks::run_tests::say_why_not(name, why);
1631 }
1632 let lines = match land {
1633 Some(line) => land_refusal(line, ctx.push.get(), &missing),
1634 None => push_refusal(
1635 &short,
1636 &missing,
1637 if reuse_stamps {
1638 StampReuse::On
1639 } else {
1640 StampReuse::Off
1641 },
1642 pushed_tag(ctx.push.get()),
1643 ),
1644 };
1645 for line in lines {
1646 eprintln!("{line}");
1647 }
1648 return Verdict::Block;
1649 }
1650 }
1651 // What actually RAN and passed here (as opposed to being vouched for by
1652 // a stamp) — the set this run may stamp in turn.
1653 let mut ran_and_passed: Vec<String> = Vec::new();
1654 // Scoped gates that RAN here and completed without passing — a warning,
1655 // or a tool that was missing (ADR-0018): recorded beside the stamps, never
1656 // as one, so a refusing push does not ask for them again.
1657 let mut completed_otherwise: Vec<(String, crate::gate_stamp::Completion)> = Vec::new();
1658 // What each gate COST and how it ENDED, for the record `gate_evidence`
1659 // reads. Every outcome, failures included: the stamp deliberately has no
1660 // opinion about a gate that failed, and a dataset that kept only the
1661 // passes could never say a gate is flaky.
1662 let mut evidence: Vec<crate::gate_stamp::Run> = Vec::new();
1663 // The question `amont list` answers with "inert here — needs go.sum":
1664 // does this repository carry the marker that turns the check on? Asked
1665 // of the index, once, and answered the same way here — a check the
1666 // registry calls inert used to run anyway, find its tool or lockfile
1667 // missing, and warn that it "could not run" on every push of a
1668 // repository it was never meant to touch.
1669 // Inside a rehearsal a heavy gate hands its slot to the next one; the
1670 // scope releases what is parked on every way out of this function.
1671 let park = crate::host_slots::ParkScope::begin();
1672 for (idx, check) in pre_push_checks.iter().enumerate() {
1673 if !check.scope().opted_in(&tracked) {
1674 continue;
1675 }
1676 let _sink = stage.as_ref().map(|s| s.enter(idx));
1677 let flush = stage
1678 .as_ref()
1679 .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, idx));
1680 // A declared pre-push external whose NAME is also declared at
1681 // pre-commit (blocking) is a gate pair: the commit-time side earned
1682 // per-commit stamps, and this side runs only for pushes carrying
1683 // commits with no record of it — the same contract the npm gate has
1684 // always had, for vocabularies npm never heard of (`cargo test`,
1685 // `pytest`, anything). Messages mirror the npm gate's exactly;
1686 // docs/checks.md quotes them. `decide` holds the reasoning, shared
1687 // with the refusal above.
1688 // The dependency audits are unscoped too (opted in by a lockfile,
1689 // with no file scope), but a rehearsal is exactly where their record
1690 // is earned (ADR-0018), so they run here.
1691 if rehearsing && !stamped_push_gate(*check) && !crate::hooks::audit::is_audit(check.name())
1692 {
1693 continue;
1694 }
1695 // A push of deletions only (or of no ref at all: git ran the hook
1696 // with nothing to push) has no commit for an audit to answer for, and
1697 // running one would hold the connection open for nothing (ADR-0018).
1698 if gate_before_push && tips.is_empty() && crate::hooks::audit::is_audit(check.name()) {
1699 continue;
1700 }
1701 match decide(*check) {
1702 Decision::Skip(Skip::HandedToCluster) => {
1703 crate::say!(
1704 "{} {} runs on the cluster — the next commit or push collects it",
1705 valid_sign(),
1706 highlight(check.name()),
1707 );
1708 continue;
1709 }
1710 Decision::Skip(Skip::Stamped) => {
1711 crate::say!(
1712 "{} {} passed on this exact tree earlier — not repeating it here",
1713 valid_sign(),
1714 highlight(check.name()),
1715 );
1716 passed.push(check.name().to_string());
1717 continue;
1718 }
1719 Decision::Skip(Skip::CompletedEarlier) => {
1720 crate::say!(
1721 "{} {} ended on this tree earlier without passing (it warned, could not \
1722 run, or was deferred to CI on a busy host) — not repeating it here",
1723 warning_sign(),
1724 highlight(check.name()),
1725 );
1726 continue;
1727 }
1728 Decision::Skip(Skip::TwinOnCluster(short)) => {
1729 crate::say!(
1730 "{} {} gated at commit on the cluster instead — not repeating it here",
1731 valid_sign(),
1732 highlight(&short),
1733 );
1734 passed.push(check.name().to_string());
1735 continue;
1736 }
1737 Decision::Skip(Skip::GatedAtCommit { name, coverage }) => {
1738 crate::say!(
1739 "{} {} gated at commit instead — not repeating it here",
1740 valid_sign(),
1741 highlight(&name),
1742 );
1743 // A second line only when a TIP vouched alone: the plain line
1744 // has always meant "every pushed commit carries its stamp",
1745 // and a reader who pushed an unstamped commit deserves to see
1746 // what the skip rests on. Its own line, so the first stays
1747 // within 80 columns; "the code at", because a plans-only tip
1748 // never ran the gate itself — its canonical tree did.
1749 if let crate::hooks::run_tests::Coverage::Tips(tips) = coverage {
1750 crate::say!(" the code at tip {} passed at commit", tips.join(", "));
1751 }
1752 passed.push(check.name().to_string());
1753 continue;
1754 }
1755 Decision::Skip(Skip::DeferredAtCommit(name, n)) => {
1756 crate::say!(
1757 "{} {} was deferred to CI at commit on {n} pushed commit{} \
1758 — deferring it here too",
1759 warning_sign(),
1760 highlight(&name),
1761 if n == 1 { "" } else { "s" },
1762 );
1763 evidence.push(crate::gate_stamp::Run {
1764 at: crate::gate_evidence::now(),
1765 gate: check.name().to_string(),
1766 outcome: crate::gate_stamp::RunOutcome::Deferred,
1767 ms: 0,
1768 });
1769 continue;
1770 }
1771 Decision::Run {
1772 unstamped_pair: Some((name, n)),
1773 ..
1774 } => {
1775 // `greengate.unstampedPush refuse`: never run a suite with
1776 // the remote's connection held open — say how to earn
1777 // the stamp instead. Not inside a rehearsal snapshot:
1778 // running there is how the stamp is earned.
1779 if !rehearsing && crate::rehearsal::refuse_unstamped(ctx.settings) {
1780 crate::say!(
1781 "{} {} is declared at commit time, but {n} pushed \
1782 commit{} carr{} no record of it (rewritten by a \
1783 rebase or amend, or made without the hooks) — \
1784 refusing the push",
1785 warning_sign(),
1786 name,
1787 if n == 1 { "" } else { "s" },
1788 if n == 1 { "ies" } else { "y" },
1789 );
1790 crate::say!(
1791 " Test this tree first, with no push waiting on it: {} — then push again",
1792 highlight(&format!("{BIN} rehearse --wait")),
1793 );
1794 crate::downgrade::note(settings, &downgraded);
1795 record_evidence(&tips, &evidence);
1796 println!("\n🚨 Error raised by hook {}", highlight(check.name()));
1797 return Verdict::Block;
1798 }
1799 crate::say!(
1800 "{} {} is declared at commit time, but {n} pushed \
1801 commit{} carr{} no record of it — running it here",
1802 warning_sign(),
1803 name,
1804 if n == 1 { "" } else { "s" },
1805 if n == 1 { "ies" } else { "y" },
1806 );
1807 }
1808 Decision::Run {
1809 unstamped_pair: None,
1810 unpaired,
1811 } => {
1812 if let Some((name, why)) = unpaired {
1813 crate::hooks::run_tests::say_why_not(&name, &why);
1814 }
1815 }
1816 }
1817 let sub = Ctx {
1818 name: check.name(),
1819 args: ctx.args,
1820 hooks_dir: ctx.hooks_dir,
1821 push: ctx.push,
1822 manifest: ctx.manifest,
1823 settings: ctx.settings,
1824 handed_to_cluster: ctx.handed_to_cluster,
1825 land: ctx.land,
1826 audits: ctx.audits,
1827 source_worktree: ctx.source_worktree,
1828 };
1829 // Wall clock around the check itself, not around the hook: the number
1830 // that catches a suite which stopped finding tests is how long THAT
1831 // gate took, and everything outside this call is bookkeeping.
1832 let started = std::time::Instant::now();
1833 let mut severity_read: Option<Severity> = None;
1834 let slot = enter(*check, || {
1835 let severity = crate::registry::severity_of(ctx.settings, *check);
1836 severity_read = Some(severity);
1837 severity
1838 });
1839 let outcome = deferred_or(&slot, check.run(&sub));
1840 if let Some(f) = &flush {
1841 f.outcome(outcome);
1842 }
1843 let ran = started.elapsed().saturating_sub(slot.queued());
1844 drop(slot);
1845 evidence.push(crate::gate_stamp::Run {
1846 at: crate::gate_evidence::now(),
1847 gate: check.name().to_string(),
1848 outcome: run_outcome(outcome),
1849 ms: ran.as_millis().min(u128::from(u64::MAX)) as u64,
1850 });
1851 match outcome {
1852 Outcome::Passed => {
1853 passed.push(check.name().to_string());
1854 // An audit's pass is a record of its report, never a stamp.
1855 if stamped_push_gate(*check) {
1856 // A pass under `warn` is not stamped (f129): a stamp is
1857 // keyed by tree, and an advisory gate may read more than
1858 // the tree. It is an hour-long completion instead.
1859 if severities.of(*check) == Severity::Warn {
1860 println!(
1861 "{} {} passed under warn: not stamped, a land within the hour skips it",
1862 warning_sign(),
1863 highlight(check.name())
1864 );
1865 completed_otherwise.push((
1866 check.name().to_string(),
1867 crate::gate_stamp::Completion::PassedUnderWarn,
1868 ));
1869 } else {
1870 ran_and_passed.push(check.name().to_string());
1871 }
1872 }
1873 }
1874 // Announced, never fatal: a check that could not run has not
1875 // invalidated anything, and neither has a warning.
1876 Outcome::Unavailable => {
1877 if stamped_push_gate(*check) {
1878 completed_otherwise.push((
1879 check.name().to_string(),
1880 crate::gate_stamp::Completion::Unavailable,
1881 ));
1882 }
1883 println!(
1884 "{} {} could not run",
1885 warning_sign(),
1886 highlight(check.name())
1887 )
1888 }
1889 Outcome::Warned => {
1890 if stamped_push_gate(*check) {
1891 completed_otherwise.push((
1892 check.name().to_string(),
1893 crate::gate_stamp::Completion::Warned,
1894 ));
1895 }
1896 }
1897 // Not run, never fatal, never passed: CI runs it (ADR-0013).
1898 // Recorded as a completion for an hour (ADR-0022), so land's push
1899 // after a pre-stage deferral does not refuse it as missing.
1900 Outcome::Deferred => {
1901 // Only where a deferral leaves land's push nothing to show:
1902 // a rehearsal or land's pre-stage (ADR-0022). A plain push's
1903 // `slotWait` deferral writes none, so a later land on a freed
1904 // host runs the gate rather than skip it for an hour.
1905 if stamped_push_gate(*check)
1906 && (crate::rehearsal::in_prestage() || crate::rehearsal::in_snapshot())
1907 {
1908 completed_otherwise.push((
1909 check.name().to_string(),
1910 crate::gate_stamp::Completion::Deferred,
1911 ));
1912 }
1913 announce_deferred(
1914 ctx.settings,
1915 &[(
1916 check.name(),
1917 severity_read
1918 .unwrap_or_else(|| crate::registry::severity_of(ctx.settings, *check)),
1919 )],
1920 )
1921 }
1922 // Nothing to judge: not passed (nothing to stamp or attest), not
1923 // a gap (nothing is missing). The dispatcher asked the registry's
1924 // opt-in question above; this is a check answering it for itself.
1925 Outcome::Inert => {}
1926 // Cannot occur: `Fix::Rewrite` is refused on a pre-push
1927 // declaration, so nothing here can repair anything.
1928 Outcome::Fixed => {}
1929 // Cannot occur: pre-push is serial and stops at the first failure
1930 // on its own; only pre-commit's waves skip (ADR-0020).
1931 Outcome::Skipped => {}
1932 Outcome::Failed => match severities.of(*check) {
1933 Severity::Warn => {
1934 if stamped_push_gate(*check) {
1935 completed_otherwise.push((
1936 check.name().to_string(),
1937 crate::gate_stamp::Completion::FailedUnderWarn,
1938 ));
1939 }
1940 downgraded.push((
1941 check.name().to_string(),
1942 downgrade_origin(*check, &severities),
1943 ));
1944 println!(
1945 "{} {} reported a problem (severity warn)",
1946 warning_sign(),
1947 highlight(check.name())
1948 );
1949 }
1950 // Fail-fast applies ONLY to Block: the later steps are
1951 // expensive and their preconditions are gone.
1952 Severity::Block => {
1953 // Record what already warned before leaving. Those checks
1954 // ran and reported; a later check blocking does not unmake
1955 // them, and dropping them here would make the ledger quietly
1956 // under-count every push that ended badly.
1957 crate::downgrade::note(settings, &downgraded);
1958 // The same argument for the evidence, and it matters more
1959 // here: this is the path a FAILURE leaves by, and a record
1960 // written only on the way out of a successful push would
1961 // be a dataset of passes calling itself a dataset of runs.
1962 record_evidence(&tips, &evidence);
1963 println!("\n🚨 Error raised by hook {}", highlight(check.name()));
1964 return Verdict::Block;
1965 }
1966 },
1967 }
1968 }
1969 drop(park);
1970 // Every block gate passed — stamp the tips with the scoped gates that
1971 // RAN here, so the next push of this content (a retry after a dropped
1972 // connection, or the real push after an `amont run pre-push` rehearsal)
1973 // skips them. Only when what ran is what is being pushed: with
1974 // `greengate.testPushedTree` the suite ran on the tip itself — unless the
1975 // snapshot could not be made, which `stamp_tips` asks about rather than
1976 // assuming; otherwise it ran on the working tree, which vouches for the
1977 // tip only when the two are the same content — HEAD, with nothing
1978 // modified and nothing untracked.
1979 // The same proxy `attestable` uses, for the same reason: a scoped gate
1980 // whose files the push never touched returns `Passed` having run
1981 // nothing, and a stamp for THAT would let a later push that does touch
1982 // them skip a suite nobody ran.
1983 if reuse_stamps && !ran_and_passed.is_empty() {
1984 let changed = crate::pushrefs::changed_files(ctx.push.get());
1985 let really_ran: Vec<String> = pre_push_checks
1986 .iter()
1987 .filter(|c| ran_and_passed.iter().any(|p| p == c.name()))
1988 .filter(|c| c.scope().touches(&changed))
1989 .map(|c| c.name().to_string())
1990 .collect();
1991 stamp_tips(&ctx.manifest.externals, &tips, &really_ran, &tree_at_start);
1992 }
1993 record_audits(ctx.audits, &tree_at_start);
1994 if reuse_stamps && !completed_otherwise.is_empty() {
1995 let changed = crate::pushrefs::changed_files(ctx.push.get());
1996 let really_ran: Vec<(String, crate::gate_stamp::Completion)> = completed_otherwise
1997 .into_iter()
1998 .filter(|(name, _)| {
1999 pre_push_checks
2000 .iter()
2001 .any(|c| c.name() == name && c.scope().touches(&changed))
2002 })
2003 .collect();
2004 record_completions(&ctx.manifest.externals, &tips, &really_ran, &tree_at_start);
2005 }
2006 // …and say so to CI, if this repository opted in.
2007 // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
2008 // `ctx.push` may consume stdin, and a disabled repo should leave stdin
2009 // exactly as it found it.
2010 // Tree gates (ADR-0024) are not push checks: nothing runs here. Each is
2011 // attested only when the TREE of every pushed tip carries its commit-time
2012 // proof; a whole-tree proof needs no changed-files scope. Fail-closed:
2013 // anything else is simply not attested, and CI lints.
2014 let (tree_proven, tree_unproven) =
2015 if !ctx.manifest.tree.is_empty() && crate::attest::enabled(settings) {
2016 crate::tree_lint::await_verdict(settings, &ctx.manifest.tree, &tips, push_started)
2017 } else {
2018 (Vec::new(), Vec::new())
2019 };
2020 if !tree_unproven.is_empty() {
2021 crate::hooks::common::say(&crate::tree_lint::fit_line(
2022 " lint not attested (cold or changed tree): ",
2023 &tree_unproven.join(" "),
2024 " — CI will lint",
2025 ));
2026 }
2027 if (!passed.is_empty() || !tree_proven.is_empty()) && crate::attest::enabled(settings) {
2028 let remote = ctx
2029 .args
2030 .first()
2031 .map(|a| a.to_string_lossy().into_owned())
2032 .unwrap_or_default();
2033 let changed = crate::pushrefs::changed_files(ctx.push.get());
2034 // Only local passes enter the laptop's attestation (ADR-0016); the
2035 // cluster's go to the linux block, which `attest_push` narrows per tip
2036 // to the trees the cluster actually judged.
2037 let (cluster_passed, local): (Vec<String>, Vec<String>) = passed
2038 .iter()
2039 .cloned()
2040 .partition(|p| crate::cluster::proved_anywhere(p));
2041 let vouched = attestable(&pre_push_checks, &local, &changed);
2042 let cluster_vouched = attestable(&pre_push_checks, &cluster_passed, &changed);
2043 // Per tip, the gates whose run saw that tip's content: the working
2044 // tree was the tip when they started, or they ran in a checkout of it
2045 // (#289; the rule `stamp_tips` applies). A tree gate's proof is the
2046 // tree's own commit-time record, so it needs no witness.
2047 let witness = TipWitness::new(&tree_at_start);
2048 let gates_for = |tip: &str| -> Vec<String> {
2049 vouched
2050 .iter()
2051 .filter(|g| witness.vouches(g, tip))
2052 .chain(tree_proven.iter())
2053 .cloned()
2054 .collect()
2055 };
2056 crate::attest::attest_push_per_tip(
2057 ctx.settings,
2058 &remote,
2059 ctx.push.get(),
2060 &gates_for,
2061 &cluster_vouched,
2062 );
2063 }
2064 // Outside the `passed` branch above on purpose: a push that changes only
2065 // documentation or its plan still carries a plan and a review to record.
2066 // holds-until: a dispatch-level test drives a push where no gate passed;
2067 // until one exists, moving this call inside that branch fails no test.
2068 if crate::attest::enabled(settings) {
2069 let remote = ctx
2070 .args
2071 .first()
2072 .map(|a| a.to_string_lossy().into_owned())
2073 .unwrap_or_default();
2074 crate::attest::provenance_push(ctx.settings, &remote, ctx.push.get());
2075 }
2076 crate::downgrade::note(settings, &downgraded);
2077 record_evidence(&tips, &evidence);
2078 Verdict::Proceed
2079}
2080
2081/// What one check's outcome is called in the record.
2082fn run_outcome(outcome: Outcome) -> crate::gate_stamp::RunOutcome {
2083 use crate::gate_stamp::RunOutcome as R;
2084 match outcome {
2085 Outcome::Passed => R::Passed,
2086 Outcome::Failed => R::Failed,
2087 Outcome::Warned => R::Warned,
2088 Outcome::Fixed => R::Fixed,
2089 Outcome::Unavailable => R::Unavailable,
2090 Outcome::Inert => R::Inert,
2091 Outcome::Deferred => R::Deferred,
2092 // Never produced at pre-push (ADR-0020); were it, it judged nothing.
2093 Outcome::Skipped => R::Inert,
2094 }
2095}
2096
2097/// The check's outcome, unless the busy policy deferred it: then Deferred,
2098/// whatever the check made of its refused spawn (ADR-0013).
2099fn deferred_or(slot: &crate::host_slots::CheckGuard, outcome: Outcome) -> Outcome {
2100 if slot.deferred().is_some() {
2101 Outcome::Deferred
2102 } else {
2103 outcome
2104 }
2105}
2106
2107/// The Heavy checks a blocking Light failure kept from starting (ADR-0020),
2108/// what blocked, and how to run each one now: `amont run` takes one name, so
2109/// one line per check, each short enough for an 80-column terminal.
2110fn announce_skipped(names: &[&str], blocked_by: &[&str]) {
2111 let names_list = names
2112 .iter()
2113 .map(|n| highlight(n))
2114 .collect::<Vec<_>>()
2115 .join(", ");
2116 match blocked_by {
2117 [one] => println!(
2118 "{} {} check(s) skipped because {} failed: {names_list}",
2119 crate::ui::skipped_sign(),
2120 names.len(),
2121 highlight(one),
2122 ),
2123 _ => println!(
2124 "{} {} check(s) skipped, a blocking check failed: {names_list}",
2125 crate::ui::skipped_sign(),
2126 names.len(),
2127 ),
2128 }
2129 println!(" fix the failures above and commit again; to run one now:");
2130 for n in names {
2131 println!(" {}", highlight(&format!("{BIN} run {n}")));
2132 }
2133}
2134
2135/// The deferral roll-up: which checks, then how to run each now and how to
2136/// stop deferring. Printed in quiet mode too, like `could not run`: a gate
2137/// skipped without a word looks exactly like a pass. Each deferred check is
2138/// advised the command that waits for its slot; the `onBusy wait` hint is
2139/// offered only for `block` checks, since a `warn` check never waits on a
2140/// commit or a push and the hint cannot stop it deferring there.
2141fn announce_deferred(settings: &crate::config::Settings, deferred: &[(&str, Severity)]) {
2142 let ceiling =
2143 crate::host_slots::wait_ceiling_secs(crate::hooks::common::check_timeout(settings));
2144 for line in deferral_advice(deferred, crate::host_slots::deferred_by(), ceiling) {
2145 println!("{line}");
2146 }
2147}
2148
2149/// The lines [`announce_deferred`] prints: the roll-up, then one `wait for a slot` label
2150/// and command per deferred check (`amont run` takes one check by name, and a
2151/// `--raw` run waits for its slot under `GREENGATE_ON_BUSY=wait`, warn or block),
2152/// then the `onBusy wait` hint only when a `block` check is in the list,
2153/// since only a `block` check stops deferring under it.
2154fn deferral_advice(
2155 deferred: &[(&str, Severity)],
2156 deferred_by: crate::host_slots::DeferredBy,
2157 ceiling: u64,
2158) -> Vec<String> {
2159 let names: Vec<&str> = deferred.iter().map(|(name, _)| *name).collect();
2160 let mut lines = vec![format!(
2161 "{} {} check(s) deferred to CI, the host was busy: {}",
2162 warning_sign(),
2163 names.len(),
2164 names.join(", ")
2165 )];
2166 let mut any_block = false;
2167 if !deferred.is_empty() {
2168 lines.push(format!(
2169 " wait for a slot, up to {} (greengate.timeout):",
2170 crate::hooks::common::human_secs(ceiling)
2171 ));
2172 }
2173 for (name, severity) in deferred {
2174 match severity {
2175 Severity::Block => any_block = true,
2176 Severity::Warn => {}
2177 }
2178 lines.push(format!(
2179 " {}",
2180 highlight(&format!("GREENGATE_ON_BUSY=wait {BIN} run --raw {name}"))
2181 ));
2182 }
2183 // Skipping the queue is the person's choice, offered second (ADR-0022).
2184 if let Some((name, _)) = deferred.first() {
2185 lines.push(" skip the queue (the host is busy):".to_string());
2186 lines.push(format!(
2187 " {}",
2188 highlight(&format!("GREENGATE_ON_BUSY=now {BIN} run --raw {name}"))
2189 ));
2190 }
2191 // `set onBusy wait` stops only a `slotWait` deferral: a ceiling under
2192 // `onBusy wait` defers under either policy.
2193 if any_block && deferred_by == crate::host_slots::DeferredBy::SlotWait {
2194 lines.push(format!(
2195 " stop deferring the block checks: {}",
2196 highlight("set onBusy wait")
2197 ));
2198 }
2199 lines
2200}
2201
2202/// File this push's runs under the content they judged.
2203///
2204/// ONE key, not one per tip: a push of two branches ran each gate once, and
2205/// writing the same run onto both trees would make a report count it twice.
2206/// The first tip's tree is that key, falling back to `HEAD` — and to nothing
2207/// at all when git will not name either, which costs a row in a report and
2208/// never a verdict.
2209fn record_evidence(tips: &[String], runs: &[crate::gate_stamp::Run]) {
2210 if runs.is_empty() {
2211 return;
2212 }
2213 let tree = tips
2214 .first()
2215 .and_then(|tip| crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]))
2216 .or_else(|| crate::git::stdout(&["rev-parse", "HEAD^{tree}"]));
2217 if let Some(tree) = tree {
2218 crate::gate_stamp::record_runs(&tree, runs);
2219 }
2220}
2221
2222/// Is `check` a push gate that runs before git connects, and is stamped for
2223/// it (ADR-0018)? A scoped one, or a declared `heavy` one whatever its scope:
2224/// a `*` declaration can be any command, and one that runs for a minute on
2225/// the open connection is the failure ADR-0018 exists to stop (#414). The
2226/// built-in unscoped checks (branch-protect, secrets) are light and need the
2227/// push's own refs, so they stay in the hook; the dependency audits answer
2228/// through their own record.
2229pub fn stamped_push_gate(check: &dyn Check) -> bool {
2230 !crate::hooks::audit::is_audit(check.name())
2231 && (!check.scope().is_unscoped() || check.weight() == crate::host_slots::Weight::Heavy)
2232}
2233
2234/// The stamped pre-push gates ([`stamped_push_gate`]) — test suites, and
2235/// declared heavy gates — that have work to do for a push that changed
2236/// `changed`: what a rehearsal would run, and therefore what its stamp would
2237/// have to name before a push may skip anything.
2238///
2239/// The same two filters `pre_push` applies before stamping (selected here,
2240/// and `scope().touches` the change), so the rehearsal's idea of "nothing to
2241/// do" is the push's idea of "nothing to stamp".
2242pub fn scoped_push_gates(
2243 settings: &crate::config::Settings,
2244 manifest: &crate::manifest::Manifest,
2245 changed: &[String],
2246) -> Vec<String> {
2247 let in_progress = crate::git_states_in_progress();
2248 let tracked = crate::tracked_paths();
2249 selected_during(settings, Stage::PrePush, &in_progress, manifest)
2250 .into_iter()
2251 .filter(|c| stamped_push_gate(*c) && c.scope().touches(changed))
2252 // The same opt-in gate `pre_push` applies: a suite the repository
2253 // never turned on is not work a rehearsal owes a stamp for.
2254 .filter(|c| c.scope().opted_in(&tracked))
2255 .map(|c| c.name().to_string())
2256 .collect()
2257}
2258
2259/// The dependency audits a push of `refs` owes (ADR-0018): opted in, and
2260/// with no fresh record for the pushed commits in the push's mode. Owed
2261/// whatever the range touches, unlike `scoped_push_gates`.
2262pub fn owed_audits(
2263 settings: &crate::config::Settings,
2264 manifest: &crate::manifest::Manifest,
2265 ledger: &crate::hooks::audit::Ledger,
2266 refs: &[crate::pushrefs::PushRef],
2267) -> Vec<String> {
2268 let in_progress = crate::git_states_in_progress();
2269 let tracked = crate::tracked_paths();
2270 selected_during(settings, Stage::PrePush, &in_progress, manifest)
2271 .into_iter()
2272 .filter(|c| crate::hooks::audit::is_audit(c.name()))
2273 .filter(|c| c.scope().opted_in(&tracked))
2274 .filter(|c| crate::hooks::audit::owed(settings, ledger, c.name(), refs))
2275 .map(|c| c.name().to_string())
2276 .collect()
2277}
2278
2279/// Push-stamp every tip whose content is what the gates actually tested.
2280///
2281/// See the comment at the call site for the two cases. Silent when nothing
2282/// qualifies — a dirty working tree is the ordinary state of a machine
2283/// mid-work, and a note on every push would teach people to ignore it.
2284fn stamp_tips(
2285 externals: &[crate::manifest::External],
2286 tips: &[String],
2287 gates: &[String],
2288 tree_at_start: &str,
2289) {
2290 let witness = TipWitness::new(tree_at_start);
2291 // TRACKED modifications only — a KNOWN gap, kept deliberately, and
2292 // spelled out because the comment that used to sit here argued it
2293 // backwards ("untracked files are not in any tree the suite could have
2294 // been asked about"). That is not the reason. The danger is not that the
2295 // tree lacks them, it is that the RUN had them: a new test file, a
2296 // fixture, a local `.env`, present while the suite ran and absent from
2297 // the tree the stamp vouches for.
2298 //
2299 // Counting them was tried, and is worse than the gap. Gates leave
2300 // artefacts — a log, a coverage directory, whatever a declared
2301 // `amont.conf` command writes — and nothing cleans them up, so a
2302 // repository using declared gates would stop earning stamps permanently
2303 // after its first commit. That does not merely lose an optimisation: it
2304 // puts the suite back INSIDE the push, which is the failure the whole
2305 // stamping mechanism exists to prevent. amont's own push flow
2306 // (`flows/push.rs`, steps `first push` and `retry`) is exactly that
2307 // shape, and CI is where it surfaced — a `*.log` line in one developer's
2308 // global gitignore had hidden it on the machine that wrote the change.
2309 //
2310 // `greengate.testPushedTree true` closes the gap properly for anyone who
2311 // wants it closed: it runs the suite in a checkout of the commit, where
2312 // no untracked file exists to be read.
2313 //
2314 // `tree_at_start` — not a fresh `git status`. The gates have run by now
2315 // and may have written into the tree; what a stamp needs to know is what
2316 // the suite could READ, which is the state it was handed. See the
2317 // capture in `pre_push`.
2318 let mut stamped: Vec<String> = Vec::new();
2319 for tip in tips {
2320 // PER GATE, from what each one actually did — not from the config.
2321 // `greengate.testPushedTree` is a request; `pushed_tree::ran_on_tip` is
2322 // the record of which gates were handed a checkout of this tip. A
2323 // gate that ran somewhere else (a snapshot that could not be made,
2324 // or a check that ran in the working tree) may vouch for the tip
2325 // only when the working tree WAS the tip. Deciding from the flag
2326 // stamped every passing gate onto a tip that one of them had never
2327 // seen.
2328 let vouched: Vec<String> = gates
2329 .iter()
2330 .filter(|g| witness.vouches(g, tip))
2331 .cloned()
2332 .collect();
2333 if vouched.is_empty() {
2334 continue;
2335 }
2336 let spec = format!("{tip}^{{tree}}");
2337 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
2338 continue;
2339 };
2340 // A gate the cluster proved on this tree is already recorded in its
2341 // own ref: a local push stamp would let the laptop vouch for it.
2342 let vouched: Vec<String> = vouched
2343 .into_iter()
2344 .filter(|g| !crate::cluster::proved(g, &tree))
2345 .collect();
2346 // Tokens, not names; a gate with no identity is not stamped.
2347 let tokens: Vec<String> = vouched
2348 .iter()
2349 .filter_map(|g| crate::gate_identity::token(externals, g))
2350 .collect();
2351 if crate::gate_stamp::stamp_push(tip, &tree, &tokens) {
2352 for g in vouched {
2353 if !stamped.contains(&g) {
2354 stamped.push(g);
2355 }
2356 }
2357 }
2358 }
2359 if !stamped.is_empty() {
2360 crate::say!(
2361 "{} stamped {} for this tree — the next push of it skips them ({})",
2362 valid_sign(),
2363 highlight(&stamped.join(" ")),
2364 crate::gate_stamp::NOTES_REF,
2365 );
2366 }
2367}
2368
2369/// Write the audit records this push produced (ADR-0018), only for a commit
2370/// the working tree IS: HEAD, inside a rehearsal snapshot or with a clean
2371/// worktree — the tools read the working tree, not the commit.
2372fn record_audits(ledger: &crate::hooks::audit::Ledger, tree_at_start: &str) {
2373 let pending = ledger.take_pending();
2374 if pending.is_empty() {
2375 return;
2376 }
2377 let witness = TipWitness::new(tree_at_start);
2378 for record in pending {
2379 if !witness.tree_is_tip(&record.tip) {
2380 continue;
2381 }
2382 if let Err(why) = crate::hooks::audit::write_pending(&record) {
2383 crate::hooks::common::warn(&format!(
2384 "{why} — the next push of this tree owes the audit again"
2385 ));
2386 }
2387 }
2388}
2389
2390/// Record the gates that completed without passing (ADR-0018), on exactly the
2391/// tips `stamp_tips` would stamp: a tip whose content is what the gates ran
2392/// on — HEAD, inside a rehearsal snapshot or with a clean worktree. One note
2393/// write per tree and kind of completion.
2394fn record_completions(
2395 externals: &[crate::manifest::External],
2396 tips: &[String],
2397 gates: &[(String, crate::gate_stamp::Completion)],
2398 tree_at_start: &str,
2399) {
2400 if gates.is_empty() {
2401 return;
2402 }
2403 let witness = TipWitness::new(tree_at_start);
2404 let mut by_kind: Vec<(crate::gate_stamp::Completion, Vec<String>)> = Vec::new();
2405 for (gate, how) in gates {
2406 let Some(token) = crate::gate_identity::token(externals, gate) else {
2407 continue;
2408 };
2409 match by_kind.iter_mut().find(|(kind, _)| kind == how) {
2410 Some((_, tokens)) => tokens.push(token),
2411 None => by_kind.push((*how, vec![token])),
2412 }
2413 }
2414 for tip in tips {
2415 if !witness.tree_is_tip(tip) {
2416 continue;
2417 }
2418 let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]) else {
2419 continue;
2420 };
2421 for (how, tokens) in &by_kind {
2422 if let Err(why) = crate::gate_stamp::record_done(&tree, tokens, *how) {
2423 crate::hooks::common::warn(&format!(
2424 "{why} — the next push of this tree owes those gates again"
2425 ));
2426 }
2427 }
2428 }
2429}
2430
2431/// Of the checks that passed, the ones an attestation may actually VOUCH for.
2432///
2433/// A language gate whose scope the push never touched returns `Passed` having
2434/// run nothing — `cargo_test` walks its refs, finds no crate root, and falls
2435/// out of the loop green. That is right for a push gate (there was nothing to
2436/// object to) and wrong for an attestation: a JS-only push was minting
2437/// `gates … pre-push-cargo-test pre-push-go-test pre-push-pytest`, and in a
2438/// MIXED repository CI would then skip a suite that nobody ran on that tree.
2439///
2440/// The declared `scope` is the honest filter, and the same data `amont list`
2441/// already reports. Unscoped checks (`Scope::ALWAYS` — branch-protect,
2442/// secrets) match everything and are vouched for, which is accurate: they
2443/// really did run. An empty `changed` vouches for nothing scoped, which is
2444/// the safe direction — CI runs the suite.
2445///
2446/// [`Scope::touches`], NOT `Scope::matches`. `matches` also asks whether the
2447/// repository has opted in — whether a `Cargo.toml` exists — and asking that
2448/// of a push DIFF can only answer no unless the push happened to touch the
2449/// marker. So `pre-push-cargo-test` was vouched for by a push that edited
2450/// `Cargo.toml` and never by one that edited only `.rs` files, which is the
2451/// ordinary case and the one worth skipping CI for. The feature attested
2452/// almost nothing, silently, and looked like it worked.
2453///
2454/// WHAT THIS IS STILL A PROXY FOR, stated plainly because the trust path
2455/// deserves it: the honest question is "did this gate actually run", and no
2456/// gate reports that. `rust_tools::test` returns `Passed` whether it ran a
2457/// suite or found no crate root and fell out of its loop — the very thing
2458/// the first paragraph describes. Scope is the closest available stand-in.
2459/// It is now a good one: a gate is vouched for only if the push changed a
2460/// file its extensions cover.
2461///
2462/// The gap that remains is narrow and one-directional: a `.rs` file outside
2463/// every crate would be covered here while `cargo test` had nothing to say
2464/// about it. Closing it properly means an outcome that distinguishes "ran
2465/// and passed" from "found nothing to do", which is a change to every gate
2466/// and to `Outcome` itself — worth doing, not worth smuggling into this.
2467/// Which pushed tips a gate's run in this process saw (#289): the working
2468/// tree was the tip when the gates started, or the gate ran in a checkout of
2469/// it (`pushed_tree::ran_on_tip`). Shared by the push stamps and the
2470/// attestation, so the two never disagree about what was tested.
2471struct TipWitness {
2472 head: Option<String>,
2473 /// The working tree held HEAD's content when the gates started: clean
2474 /// of tracked changes, or a rehearsal snapshot. A snapshot is a checkout
2475 /// git made of the commit, and whatever `greengate.snapshotPrepare` added to
2476 /// make it runnable (a `node_modules`, a virtualenv) is not a reason to
2477 /// distrust it.
2478 tree_is_head: bool,
2479}
2480
2481impl TipWitness {
2482 fn new(tree_at_start: &str) -> Self {
2483 Self::from_parts(
2484 crate::git::stdout(&["rev-parse", "HEAD"]),
2485 crate::rehearsal::in_snapshot(),
2486 tree_at_start,
2487 )
2488 }
2489
2490 fn from_parts(head: Option<String>, in_snapshot: bool, tree_at_start: &str) -> Self {
2491 TipWitness {
2492 head,
2493 tree_is_head: in_snapshot || tree_at_start.trim().is_empty(),
2494 }
2495 }
2496
2497 /// The working tree was `tip` when the gates started.
2498 fn tree_is_tip(&self, tip: &str) -> bool {
2499 self.tree_is_head && self.head.as_deref() == Some(tip)
2500 }
2501
2502 fn vouches(&self, gate: &str, tip: &str) -> bool {
2503 self.tree_is_tip(tip) || crate::pushed_tree::ran_on_tip(gate, tip)
2504 }
2505}
2506
2507fn attestable(checks: &[&dyn Check], passed: &[String], changed: &[String]) -> Vec<String> {
2508 checks
2509 .iter()
2510 .filter(|c| passed.iter().any(|p| p == c.name()))
2511 .filter(|c| c.scope().touches(changed))
2512 .map(|c| c.name().to_string())
2513 .collect()
2514}
2515
2516#[cfg(test)]
2517mod tests {
2518 use super::*;
2519 use crate::check::{Builtin, Scope};
2520 use std::sync::atomic::{AtomicUsize, Ordering};
2521
2522 /// #289: a dirty working tree witnesses no tip, even HEAD; a clean one,
2523 /// or a snapshot, witnesses HEAD only.
2524 #[test]
2525 fn only_a_clean_head_or_a_snapshot_witnesses_a_tip() {
2526 let head = Some("a".repeat(40));
2527 let tip = "a".repeat(40);
2528 let other = "b".repeat(40);
2529 let dirty = TipWitness::from_parts(head.clone(), false, " M src/lib.rs\n");
2530 assert!(!dirty.tree_is_tip(&tip));
2531 let clean = TipWitness::from_parts(head.clone(), false, "");
2532 assert!(clean.tree_is_tip(&tip));
2533 assert!(!clean.tree_is_tip(&other));
2534 let snapshot = TipWitness::from_parts(head, true, " M node_modules/x\n");
2535 assert!(snapshot.tree_is_tip(&tip));
2536 }
2537
2538 /// ADR-0018: the refusals fit 80 columns, put each command on its own
2539 /// line, and name only amont's own commands (every Green Harness part is
2540 /// optional: amont runs without relais, the skills or amont-agent).
2541 #[test]
2542 fn the_push_refusals_fit_and_name_only_amont() {
2543 let many: Vec<String> = (0..12)
2544 .map(|i| format!("pre-push-gate-number-{i}"))
2545 .collect();
2546 let names: Vec<&str> = many.iter().map(String::as_str).collect();
2547 let refs = vec![crate::pushrefs::PushRef {
2548 local_ref: "refs/heads/x".into(),
2549 local_oid: "a".repeat(40),
2550 remote_ref: "refs/heads/x".into(),
2551 remote_oid: "b".repeat(40),
2552 }];
2553 let sets = [
2554 push_refusal("abcdef12", &names, StampReuse::On, None),
2555 push_refusal("abcdef12", &names, StampReuse::Off, None),
2556 land_refusal(
2557 &crate::rehearsal::LandLine {
2558 sha: "a".repeat(40),
2559 remote_tip: "b".repeat(40),
2560 },
2561 &refs,
2562 &names,
2563 ),
2564 land_refusal(
2565 &crate::rehearsal::LandLine {
2566 sha: "a".repeat(40),
2567 remote_tip: "c".repeat(40),
2568 },
2569 &refs,
2570 &names,
2571 ),
2572 push_refusal(
2573 "abcdef12",
2574 &names,
2575 StampReuse::On,
2576 Some("v12.345.6789-rc.1+build.2026-11-05"),
2577 ),
2578 ];
2579 for lines in &sets {
2580 for line in lines {
2581 assert!(line.chars().count() <= 80, "{line:?}");
2582 for foreign in ["relais", "skill", "amont-agent"] {
2583 assert!(!line.contains(foreign), "{line:?}");
2584 }
2585 }
2586 let joined = lines.join("\n");
2587 for name in &names {
2588 assert!(joined.contains(name), "every gate is named: {joined}");
2589 }
2590 }
2591 assert!(sets[0].iter().any(|l| l.ends_with(&format!("{BIN} land"))));
2592 assert!(sets[0]
2593 .iter()
2594 .any(|l| l.ends_with(&format!("{BIN} rehearse --wait"))));
2595 assert!(
2596 !sets[1].iter().any(|l| l.contains("rehearse")),
2597 "{:?}",
2598 sets[1]
2599 );
2600 assert!(sets[1]
2601 .iter()
2602 .any(|l| l.contains("greengate.pushStamps true")));
2603 assert!(sets[1].iter().any(|l| l.ends_with(&format!("{BIN} land"))));
2604 assert_eq!(sets[2][0], crate::land::LAND_EVIDENCE_MISSING);
2605 assert_eq!(sets[3][0], crate::land::LAND_REMOTE_MOVED);
2606 assert!(sets[0][0].starts_with(&format!("{BIN}: push refused:")));
2607 // A tag push is offered the tag's own land, never the branch remedies.
2608 assert!(
2609 sets[4].iter().any(|l| l.ends_with(&format!(
2610 "{BIN} land --tag v12.345.6789-rc.1+build.2026-11-05"
2611 ))),
2612 "{:?}",
2613 sets[4]
2614 );
2615 assert!(
2616 !sets[4].iter().any(|l| l.contains("rehearse")),
2617 "{:?}",
2618 sets[4]
2619 );
2620 }
2621
2622 /// A check whose only job is to carry a name and a severity into `report`.
2623 /// Its `run` is never called — `report` is fed outcomes directly, which is
2624 /// what makes `Unavailable` testable at all: the real thing needs a missing
2625 /// binary, and a test that uninstalls the developer's toolchain is worse
2626 /// than no test.
2627 const fn stub(name: &'static str, severity: Severity) -> Builtin {
2628 Builtin {
2629 name,
2630 stage: Stage::PreCommit,
2631 scope: Scope::ALWAYS,
2632 severity,
2633 run: |_| Outcome::Passed,
2634 fix: crate::check::Fix::None,
2635 reach: crate::check::Reach::Convention,
2636 }
2637 }
2638
2639 /// A pre-push gate with an OPT-IN file, as the real Rust and Python
2640 /// gates have: `.rs` files, but only where a `Cargo.toml` exists.
2641 const fn opt_in(
2642 name: &'static str,
2643 exts: &'static [&'static str],
2644 names: &'static [&'static str],
2645 ) -> Builtin {
2646 Builtin {
2647 name,
2648 stage: Stage::PrePush,
2649 scope: Scope::new(exts, names),
2650 severity: Severity::Block,
2651 run: |_| Outcome::Passed,
2652 fix: crate::check::Fix::None,
2653 reach: crate::check::Reach::Convention,
2654 }
2655 }
2656
2657 /// A pre-push gate scoped to one language's files.
2658 const fn scoped(name: &'static str, exts: &'static [&'static str]) -> Builtin {
2659 Builtin {
2660 name,
2661 stage: Stage::PrePush,
2662 scope: Scope::new(exts, &[]),
2663 severity: Severity::Block,
2664 run: |_| Outcome::Passed,
2665 fix: crate::check::Fix::None,
2666 reach: crate::check::Reach::Convention,
2667 }
2668 }
2669
2670 /// The over-claim this filter exists to stop, caught in the wild: a
2671 /// JS-only push minted `gates … pre-push-cargo-test pre-push-go-test
2672 /// pre-push-pytest`, because each of those gates finds nothing of its
2673 /// language to do and returns `Passed` having run NOTHING. Harmless in a
2674 /// single-language repo, unsound in a mixed one — CI would skip a suite
2675 /// nobody ran on that tree.
2676 #[test]
2677 fn a_gate_whose_language_the_push_never_touched_is_not_vouched_for() {
2678 let js = scoped("pre-push-run-tests-js", &[".ts", ".js"]);
2679 let rust = scoped("pre-push-cargo-test", &[".rs"]);
2680 let py = scoped("pre-push-pytest", &[".py"]);
2681 let always = stub("pre-push-secrets", Severity::Block);
2682 let checks: Vec<&dyn Check> = vec![&js, &rust, &py, &always];
2683 let passed: Vec<String> = checks.iter().map(|c| c.name().to_string()).collect();
2684
2685 let changed = vec!["app/routes/home.ts".to_string()];
2686 let vouched = attestable(&checks, &passed, &changed);
2687 assert_eq!(
2688 vouched,
2689 vec![
2690 "pre-push-run-tests-js".to_string(),
2691 "pre-push-secrets".to_string()
2692 ],
2693 "only the gate that had work, plus the unscoped one that always runs"
2694 );
2695
2696 // Nothing computed about the push vouches for nothing scoped — the
2697 // safe direction, since CI then runs the suite.
2698 assert_eq!(
2699 attestable(&checks, &passed, &[]),
2700 vec!["pre-push-secrets".to_string()]
2701 );
2702
2703 // A check that did NOT pass is never vouched for, whatever its scope.
2704 let only_rust_passed = vec!["pre-push-cargo-test".to_string()];
2705 assert!(attestable(&checks, &only_rust_passed, &changed).is_empty());
2706 }
2707
2708 /// No overrides configured. `report` takes them as a VALUE now, so its
2709 /// tests need no repository and no git at all.
2710 fn none() -> Overrides {
2711 Overrides::default()
2712 }
2713
2714 static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
2715 static WARNER: Builtin = stub("stub-warner", Severity::Warn);
2716
2717 /// The unit tests hold `&dyn Check` for the same reason the dispatcher
2718 /// does: `report` must not be able to tell a built-in from an external.
2719 const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
2720 [cs[0], cs[1], cs[2]]
2721 }
2722
2723 /// The classification itself, which used to be unreachable: while one
2724 /// function classified AND printed AND returned a code, a test could assert
2725 /// the code and nothing else.
2726 #[test]
2727 fn every_outcome_lands_in_the_right_bucket() {
2728 let checks: [&dyn Check; 5] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER, &BLOCKER];
2729 let got = classify(
2730 &checks,
2731 &[
2732 Outcome::Passed,
2733 Outcome::Unavailable,
2734 Outcome::Failed,
2735 Outcome::Failed,
2736 Outcome::Inert,
2737 ],
2738 &none(),
2739 );
2740 assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
2741 assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
2742 assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
2743 assert_eq!(got.passed, 1, "inert is not a pass: {got:?}");
2744 }
2745
2746 /// A clean stage concludes nothing at all — not an empty message, no
2747 /// message. Twenty checks that passed should print no roll-ups.
2748 ///
2749 /// `passed` is a tally, not a roll-up. It exists so that `greengate.quiet` can
2750 /// say how many lines it swallowed, and it must never be the reason this
2751 /// report looks like it has something to announce.
2752 #[test]
2753 fn a_clean_stage_has_nothing_to_report() {
2754 let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
2755 let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
2756 assert!(
2757 got.fixed.is_empty()
2758 && got.blocked.is_empty()
2759 && got.downgraded.is_empty()
2760 && got.unavailable.is_empty(),
2761 "a clean stage found something to announce: {got:?}"
2762 );
2763 assert_eq!(got.passed, 1, "the pass was not tallied: {got:?}");
2764 assert_eq!(got.verdict(), Verdict::Proceed);
2765 }
2766
2767 #[test]
2768 fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
2769 let b: &dyn Check = &BLOCKER;
2770 let w: &dyn Check = &WARNER;
2771 assert_eq!(
2772 classify(&[b], &[Outcome::Failed], &none()).verdict(),
2773 Verdict::Block
2774 );
2775 assert_eq!(
2776 classify(&[b], &[Outcome::Passed], &none()).verdict(),
2777 Verdict::Proceed
2778 );
2779 // Every non-blocking shape, one at a time, so a regression cannot hide
2780 // behind a passing sibling.
2781 assert_eq!(
2782 classify(&[b], &[Outcome::Warned], &none()).verdict(),
2783 Verdict::Proceed
2784 );
2785 assert_eq!(
2786 classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
2787 Verdict::Proceed
2788 );
2789 assert_eq!(
2790 classify(&[w], &[Outcome::Failed], &none()).verdict(),
2791 Verdict::Proceed
2792 );
2793 // A skipped Heavy check never blocks by itself: the Light failure
2794 // that skipped it does (ADR-0020). It is listed, never counted passed.
2795 let skipped = classify(&[b], &[Outcome::Skipped], &none());
2796 assert_eq!(skipped.verdict(), Verdict::Proceed);
2797 assert_eq!(skipped.skipped, vec![b.name()]);
2798 assert_eq!(skipped.passed, 0);
2799 }
2800
2801 #[test]
2802 fn the_environment_word_on_fail_fast_wins_and_a_bad_one_falls_back() {
2803 let settings = crate::config::Settings::default();
2804 assert!(!resolve_fail_fast(Some("false"), &settings));
2805 assert!(!resolve_fail_fast(Some("0"), &settings));
2806 assert!(resolve_fail_fast(Some("TRUE"), &settings));
2807 // Unset or unreadable: the configured value, here the default.
2808 assert!(resolve_fail_fast(None, &settings));
2809 assert!(resolve_fail_fast(Some(""), &settings));
2810 assert!(resolve_fail_fast(Some("sometimes"), &settings));
2811 }
2812
2813 #[test]
2814 fn one_blocking_failure_among_many_still_fails() {
2815 let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
2816 assert_eq!(
2817 classify(
2818 &checks,
2819 &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
2820 &none()
2821 )
2822 .verdict(),
2823 Verdict::Block
2824 );
2825 // Same shape, with the only *blocking* failure removed.
2826 assert_eq!(
2827 classify(
2828 &checks,
2829 &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
2830 &none()
2831 )
2832 .verdict(),
2833 Verdict::Proceed
2834 );
2835 }
2836
2837 /// The slot of a check whose thread died. Reading that as a pass is how a
2838 /// crash becomes a green commit.
2839 ///
2840 /// Asserted through the RUNNER, not through a `Default` impl: the rule
2841 /// belongs to this call site, and a test on `Outcome::default()` proved
2842 /// only that a trait impl existed, not that the runner used it.
2843 /// A check that PANICS must fail the commit, not pass it — and must not
2844 /// take the other checks down with it.
2845 ///
2846 /// Driven through the stage body rather than the runner, because the value
2847 /// that stands in for a dead check is chosen at the call site and the
2848 /// runner's own test cannot see that choice.
2849 #[test]
2850 fn a_panicking_check_blocks_the_commit() {
2851 static DIES: Builtin = Builtin {
2852 name: "stub-dies",
2853 stage: Stage::PreCommit,
2854 scope: Scope::ALWAYS,
2855 severity: Severity::Block,
2856 run: |_| panic!("this check died"),
2857 fix: crate::check::Fix::None,
2858 reach: crate::check::Reach::Convention,
2859 };
2860 let hook = std::panic::take_hook();
2861 std::panic::set_hook(Box::new(|_| {}));
2862 let push = crate::pushrefs::PushRefs::default();
2863 let manifest = crate::manifest::Manifest::default();
2864 let settings = crate::config::Settings::default();
2865 let ctx = Ctx {
2866 name: "pre-commit",
2867 args: &[],
2868 hooks_dir: std::path::Path::new("."),
2869 push: &push,
2870 manifest: &manifest,
2871 settings: &settings,
2872 handed_to_cluster: &[],
2873 land: &crate::rehearsal::LandEnv::Absent,
2874 audits: &Default::default(),
2875 source_worktree: None,
2876 };
2877 let verdict = run_stage(&[&DIES], &ctx, &none());
2878 std::panic::set_hook(hook);
2879 assert_eq!(
2880 verdict,
2881 Verdict::Block,
2882 "a check that died must not let the commit through"
2883 );
2884 }
2885
2886 #[test]
2887 fn a_thread_that_dies_leaves_a_failure_behind() {
2888 // The default hook would print a backtrace for the deliberate panic and
2889 // make a passing run look broken.
2890 let hook = std::panic::take_hook();
2891 std::panic::set_hook(Box::new(|_| {}));
2892 let items = ["a", "b", "c"];
2893 let out = run_concurrently(
2894 &items,
2895 |n: &&str| {
2896 if *n == "b" {
2897 panic!("this check died");
2898 }
2899 Outcome::Passed
2900 },
2901 Outcome::Failed,
2902 );
2903 std::panic::set_hook(hook);
2904 assert_eq!(
2905 out,
2906 vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
2907 "a dead check must not read as one that passed, \
2908 and must not take the other checks down with it"
2909 );
2910 }
2911 use std::time::{Duration, Instant};
2912
2913 /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
2914 /// observe all the others arrive. Were the runner serial, the first task
2915 /// would wait alone, time out, and return non-zero — a failure, not a hang.
2916 #[test]
2917 fn run_concurrently_actually_overlaps() {
2918 static ARRIVED: AtomicUsize = AtomicUsize::new(0);
2919 ARRIVED.store(0, Ordering::SeqCst);
2920 let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
2921 let n = names.len();
2922
2923 let out = run_concurrently(
2924 &names,
2925 move |_: &&str| {
2926 ARRIVED.fetch_add(1, Ordering::SeqCst);
2927 let deadline = Instant::now() + Duration::from_secs(10);
2928 while ARRIVED.load(Ordering::SeqCst) < n {
2929 if Instant::now() > deadline {
2930 return 1; // never met the others — execution was serial
2931 }
2932 std::thread::yield_now();
2933 }
2934 0
2935 },
2936 1,
2937 );
2938 assert!(
2939 out.iter().all(|c| *c == 0),
2940 "tasks did not overlap: {out:?}"
2941 );
2942 }
2943
2944 #[test]
2945 fn results_come_back_in_input_order() {
2946 let names: Vec<&'static str> = vec!["first", "second", "third"];
2947 let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
2948 assert_eq!(out, vec![0, 7, 0], "results keep the input order");
2949 }
2950
2951 /// The filter calls the shared resolver rather than restating it. This test
2952 /// used to inline `n.contains(s)` — its own copy of the rule — and so went
2953 /// on passing after the rule changed underneath it.
2954 #[test]
2955 fn skips_are_filtered_by_the_shared_resolver() {
2956 let all = ["pre-commit-ruff", "pre-commit-prettier"];
2957 let skips = ["ruff".to_string()];
2958 let kept: Vec<_> = all
2959 .iter()
2960 .copied()
2961 .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
2962 .collect();
2963 assert_eq!(kept, vec!["pre-commit-prettier"]);
2964 }
2965
2966 /// The ordinary Rust push: source changed, `Cargo.toml` untouched.
2967 ///
2968 /// This test used to assert the OPPOSITE, and said so — it pinned
2969 /// `attestable` filtering on `Scope::matches`, which also asks whether
2970 /// the repository has opted in. Asking that of a push diff meant a
2971 /// `.rs`-only push, in a repository with a `Cargo.toml` sitting right
2972 /// there, attested nothing. Since that is what nearly every Rust push
2973 /// looks like, the feature was attesting almost nothing at all — quietly,
2974 /// while appearing to work.
2975 #[test]
2976 fn an_ordinary_source_push_is_vouched_for() {
2977 let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
2978 let checks: Vec<&dyn Check> = vec![&rust];
2979 let passed = vec!["pre-push-cargo-test".to_string()];
2980
2981 let changed = vec!["crates/greengate/src/main.rs".to_string()];
2982 assert_eq!(
2983 attestable(&checks, &passed, &changed),
2984 vec!["pre-push-cargo-test".to_string()],
2985 "a push that changed Rust must vouch for the Rust gate"
2986 );
2987
2988 // And still when the marker IS in the diff — the opt-in file is not
2989 // required, but it is not disqualifying either.
2990 let changed = vec![
2991 "crates/greengate/src/main.rs".to_string(),
2992 "Cargo.toml".to_string(),
2993 ];
2994 assert_eq!(
2995 attestable(&checks, &passed, &changed),
2996 vec!["pre-push-cargo-test".to_string()]
2997 );
2998 }
2999
3000 /// The over-claim the filter exists to stop, with an opt-in gate: a
3001 /// JS-only push must not vouch for the Rust suite, whatever files the
3002 /// repository contains.
3003 ///
3004 /// This is the half of the contract the fix above must not have broken,
3005 /// and it is the reason `touches` asks about EXTENSIONS rather than
3006 /// dropping the scope test altogether.
3007 #[test]
3008 fn an_opt_in_gate_is_not_vouched_for_by_a_push_in_another_language() {
3009 let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
3010 let checks: Vec<&dyn Check> = vec![&rust];
3011 let passed = vec!["pre-push-cargo-test".to_string()];
3012
3013 for changed in [
3014 vec!["app/routes/home.ts".to_string()],
3015 // Even the marker alone: editing Cargo.toml changes no Rust
3016 // source, so the suite has nothing new to have verified.
3017 vec!["Cargo.toml".to_string()],
3018 vec![],
3019 ] {
3020 assert!(
3021 attestable(&checks, &passed, &changed).is_empty(),
3022 "must not vouch for the Rust gate on {changed:?}"
3023 );
3024 }
3025 }
3026
3027 /// amont #431: `onBusy wait` cannot stop a `warn` gate deferring, so a
3028 /// list of warn gates is advised only the command that waits, once per
3029 /// gate, and the hint is never offered.
3030 #[test]
3031 fn deferred_warn_gates_are_each_advised_the_command_that_waits() {
3032 let lines = deferral_advice(
3033 &[
3034 ("pre-push-probe", Severity::Warn),
3035 ("pre-push-lint", Severity::Warn),
3036 ],
3037 crate::host_slots::DeferredBy::SlotWait,
3038 3600,
3039 );
3040 let said = lines.join("\n");
3041 assert!(said.contains("2 check(s) deferred to CI"), "{said}");
3042 for gate in ["pre-push-probe", "pre-push-lint"] {
3043 assert!(
3044 said.contains(&format!("GREENGATE_ON_BUSY=wait {BIN} run --raw {gate}")),
3045 "{said}"
3046 );
3047 }
3048 assert!(!said.contains("set onBusy wait"), "{said}");
3049 }
3050
3051 /// A list mixing a `block` and a `warn` gate: both get their command,
3052 /// and the `onBusy wait` hint says it stops only the block checks.
3053 #[test]
3054 fn a_mixed_deferral_names_every_gate_and_scopes_the_hint() {
3055 let lines = deferral_advice(
3056 &[
3057 ("pre-push-probe", Severity::Warn),
3058 ("pre-push-cargo-test", Severity::Block),
3059 ],
3060 crate::host_slots::DeferredBy::SlotWait,
3061 3600,
3062 );
3063 let said = lines.join("\n");
3064 for gate in ["pre-push-probe", "pre-push-cargo-test"] {
3065 assert!(
3066 said.contains(&format!("GREENGATE_ON_BUSY=wait {BIN} run --raw {gate}")),
3067 "{said}"
3068 );
3069 }
3070 let hint = lines
3071 .iter()
3072 .find(|l| l.contains("set onBusy wait"))
3073 .expect("the hint, for the block gate");
3074 assert!(hint.contains("block checks"), "{hint}");
3075 assert_eq!(
3076 lines.len(),
3077 7,
3078 "roll-up, the wait label, two commands, the skip label and command, one hint: {said}"
3079 );
3080 }
3081
3082 /// ADR-0022: a line that ended defers under `onBusy wait` too, so the
3083 /// `onBusy wait` hint would stop nothing and is left out; skipping the
3084 /// queue is offered second, after the command that waits. Each command
3085 /// stands alone under its label, so it copies whole and fits 80 columns.
3086 #[test]
3087 fn a_line_end_deferral_offers_the_wait_then_the_skip_and_no_hint() {
3088 let lines = deferral_advice(
3089 &[("pre-push-cargo-test", Severity::Block)],
3090 crate::host_slots::DeferredBy::LineEnded,
3091 3600,
3092 );
3093 let said = lines.join("\n");
3094 assert!(!said.contains("set onBusy wait"), "{said}");
3095 assert_eq!(
3096 lines[1], " wait for a slot, up to 1h00m (greengate.timeout):",
3097 "{said}"
3098 );
3099 // A disabled `greengate.timeout` waits to the queue's own 3600 s.
3100 let off = deferral_advice(
3101 &[("pre-push-cargo-test", Severity::Block)],
3102 crate::host_slots::DeferredBy::LineEnded,
3103 crate::host_slots::wait_ceiling_secs(0),
3104 );
3105 assert_eq!(off[1], lines[1], "{off:?}");
3106 assert!(lines.iter().all(|l| l.chars().count() <= 80), "{said}");
3107 assert!(lines[2].contains("GREENGATE_ON_BUSY=wait"), "{said}");
3108 assert!(lines[3].contains("skip the queue"), "{said}");
3109 assert!(lines[4].contains("GREENGATE_ON_BUSY=now"), "{said}");
3110 assert_eq!(lines.len(), 5, "{said}");
3111 }
3112}