greengate-runtime 3.0.1

The amont hook logic: registry, dispatchers, checks and the trust model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
//! pre-commit-tree-parity — a CI step skipped on `tree-<name>` must run exactly
//! that gate's command (ADR-0024, `ci.skip-needs-the-same-command`).
//!
//! An attestation names a gate, and a gate is worth only the command behind
//! it. If a workflow's gated `run:` drifts from the `tree` line in
//! `amont.conf`, CI keeps skipping a step whose command nobody proved. This
//! check compares the two on every commit that touches either, and CI runs it
//! too (`amont tree-parity`, never skipped), so a `--no-verify` drift still
//! fails.
//!
//! amont has no dependencies, so this is not a YAML parser. It reads the one
//! shape workflow files take — `jobs:` → a job → `steps:` → `- ` items — line
//! by line, and **fails closed**: anything it cannot read with certainty on a
//! gated step is a problem, never a guess. That covers:
//!
//! - a block scalar;
//! - an anchor or alias;
//! - a quoted form with escapes;
//! - `${{ }}` interpolation;
//! - a step-level `env:` or `shell:`, or a `working-directory:` the gate does
//!   not declare as `cwd=`;
//! - any `env:` or `defaults:` a gated step would inherit from its job or its
//!   workflow — with one exception: an inherited `defaults: run: shell: bash`
//!   is accepted when the gated command has no pipe, list, redirection or
//!   substitution, because bash's `-e` and `pipefail` cannot change the verdict
//!   of a simple command (a decision of the person, 2026-09-30: the fleet sets
//!   it workflow-wide on purpose).
//!
//! A gate that needs one of these does not attest.

use std::path::Path;

use crate::check::Outcome;
use crate::hooks::common::{fail, hl, ok, repo_root, warn};
use crate::manifest::{normalize_command, tree_gates, TreeGate, MANIFEST};

/// Where workflows live, per forge.
pub const WORKFLOW_DIRS: &[&str] = &[".github/workflows", ".forgejo/workflows"];

/// One thing wrong, where it is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Problem {
    pub file: String,
    pub line: usize,
    pub what: String,
}

impl std::fmt::Display for Problem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.line == 0 {
            write!(f, "{}: {}", self.file, self.what)
        } else {
            write!(f, "{}:{}: {}", self.file, self.line, self.what)
        }
    }
}

/// A step, as far as parity needs to see one.
#[derive(Debug, Default)]
struct Step {
    line: usize,
    /// `(key, raw value after the colon, line)` for keys at the step's own
    /// indentation — never nested ones.
    keys: Vec<(String, String, usize)>,
    /// Every line of the step, for finding `tree-` references wherever the
    /// `if:` puts them (a block scalar included).
    text: String,
}

/// What a job or a workflow hands down to its steps.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Inherited {
    /// `defaults:` holding exactly `run:` → `shell: bash`.
    ShellBash,
    /// Any `env:`, or any other `defaults:`.
    Other,
}

#[derive(Debug, Default)]
struct Job {
    /// `env:` or `defaults:` at the job's own level, with their lines.
    inherits: Vec<(usize, Inherited)>,
    steps: Vec<Step>,
}

#[derive(Debug, Default)]
struct Workflow {
    /// `env:` or `defaults:` at the top level.
    inherits: Vec<(usize, Inherited)>,
    jobs: Vec<Job>,
    /// `tree-` references on lines that belong to no step.
    stray: Vec<usize>,
}

fn indent_of(line: &str) -> usize {
    line.len() - line.trim_start_matches(' ').len()
}

/// `key: value` → `(key, value)`; `None` when the line is not a mapping key.
fn key_of(s: &str) -> Option<(&str, &str)> {
    let (k, v) = s.split_once(':')?;
    let ok = !k.is_empty()
        && k.chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
    (ok && (v.is_empty() || v.starts_with(' '))).then(|| (k, v.trim()))
}

fn mentions_tree(line: &str) -> bool {
    line.contains("'tree-") || line.contains("\"tree-")
}

/// What the `env:`/`defaults:` key on line `idx` (0-based) hands down.
/// `defaults:` whose body is exactly `run:` → `shell: bash` is the one shape
/// that may be accepted; everything else is `Other`.
fn classify(lines: &[&str], idx: usize) -> Inherited {
    let key_line = lines[idx];
    if key_of(key_line.trim()).map(|(k, _)| k) != Some("defaults") {
        return Inherited::Other;
    }
    let level = indent_of(key_line);
    let body: Vec<&str> = lines[idx + 1..]
        .iter()
        .map(|l| (indent_of(l), l.trim()))
        .filter(|(_, t)| !t.is_empty() && !t.starts_with('#'))
        .take_while(|(ind, _)| *ind > level)
        .map(|(_, t)| t)
        .collect();
    let bash = ["shell: bash", "shell: 'bash'", "shell: \"bash\""];
    match body.as_slice() {
        ["run:", shell] if bash.contains(shell) => Inherited::ShellBash,
        _ => Inherited::Other,
    }
}

/// Whether bash's `-e`/`pipefail` could change this command's verdict: a
/// pipe, a list, a redirection, a substitution or a subshell.
fn is_simple(command: &str) -> bool {
    !command.contains(['|', ';', '&', '>', '<', '`', '(', ')']) && !command.contains("$(")
}

fn read_workflow(text: &str) -> Workflow {
    let all: Vec<&str> = text.lines().collect();
    let mut wf = Workflow::default();
    let mut in_jobs = false;
    let mut job_indent: Option<usize> = None;
    let mut job_key_indent: Option<usize> = None;
    let mut steps_indent: Option<usize> = None;
    let mut dash_indent: Option<usize> = None;
    for (i, raw) in text.lines().enumerate() {
        let lineno = i + 1;
        let trimmed = raw.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let ind = indent_of(raw);
        if ind == 0 {
            in_jobs = false;
            job_indent = None;
            job_key_indent = None;
            steps_indent = None;
            dash_indent = None;
            if let Some((k, _)) = key_of(trimmed) {
                if k == "jobs" {
                    in_jobs = true;
                } else if k == "env" || k == "defaults" {
                    wf.inherits.push((lineno, classify(&all, i)));
                }
            }
            if mentions_tree(raw) {
                wf.stray.push(lineno);
            }
            continue;
        }
        if !in_jobs {
            if mentions_tree(raw) {
                wf.stray.push(lineno);
            }
            continue;
        }
        let ji = *job_indent.get_or_insert(ind);
        if ind <= ji {
            // A new job header (or something at the jobs level).
            job_key_indent = None;
            steps_indent = None;
            dash_indent = None;
            wf.jobs.push(Job::default());
            if mentions_tree(raw) {
                wf.stray.push(lineno);
            }
            continue;
        }
        let Some(job) = wf.jobs.last_mut() else {
            if mentions_tree(raw) {
                wf.stray.push(lineno);
            }
            continue;
        };
        let jki = *job_key_indent.get_or_insert(ind);
        if ind <= jki {
            // A job-level key ends any steps list.
            steps_indent = None;
            dash_indent = None;
            if let Some((k, _)) = key_of(trimmed) {
                if k == "steps" {
                    steps_indent = Some(ind);
                } else if k == "env" || k == "defaults" {
                    job.inherits.push((lineno, classify(&all, i)));
                }
            }
            if mentions_tree(raw) {
                wf.stray.push(lineno);
            }
            continue;
        }
        if steps_indent.is_none() {
            if mentions_tree(raw) {
                wf.stray.push(lineno);
            }
            continue;
        }
        if let Some(item) = trimmed
            .strip_prefix("- ")
            .or((trimmed == "-").then_some(""))
        {
            let di = *dash_indent.get_or_insert(ind);
            if ind == di {
                let mut step = Step {
                    line: lineno,
                    ..Step::default()
                };
                step.text.push_str(raw);
                step.text.push('\n');
                if let Some((k, v)) = key_of(item) {
                    step.keys.push((k.to_string(), v.to_string(), lineno));
                }
                job.steps.push(step);
                continue;
            }
        }
        let Some(step) = job.steps.last_mut() else {
            if mentions_tree(raw) {
                wf.stray.push(lineno);
            }
            continue;
        };
        step.text.push_str(raw);
        step.text.push('\n');
        // A key at the step's own indentation (dash + 2).
        if Some(ind) == dash_indent.map(|d| d + 2) {
            if let Some((k, v)) = key_of(trimmed) {
                step.keys.push((k.to_string(), v.to_string(), lineno));
            }
        }
    }
    wf
}

/// The `tree-<name>` tokens a step's text references.
fn referenced(text: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for quote in ['\'', '"'] {
        let needle = format!("{quote}tree-");
        let mut rest = text;
        while let Some(i) = rest.find(&needle) {
            let after = &rest[i + needle.len()..];
            let end = after.find(quote).unwrap_or(after.len());
            let name = &after[..end];
            if !name.is_empty() && !out.iter().any(|n| n == name) {
                out.push(name.to_string());
            }
            rest = &after[end..];
        }
    }
    out
}

/// A single-line scalar's value, or why it cannot be read with certainty.
fn scalar(raw: &str) -> Result<String, &'static str> {
    let v = raw.trim();
    if v.is_empty() || v.starts_with('|') || v.starts_with('>') {
        return Err("a block scalar — write the command on one line");
    }
    if v.starts_with('&') || v.starts_with('*') {
        return Err("an anchor or alias");
    }
    let value = if let Some(inner) = v.strip_prefix('"') {
        let Some(inner) = inner.strip_suffix('"') else {
            return Err("an unterminated quoted scalar");
        };
        if inner.contains(['\\', '"']) {
            return Err("a quoted scalar with escapes");
        }
        inner.to_string()
    } else if let Some(inner) = v.strip_prefix('\'') {
        let Some(inner) = inner.strip_suffix('\'') else {
            return Err("an unterminated quoted scalar");
        };
        if inner.contains('\'') {
            return Err("a quoted scalar with escapes");
        }
        inner.to_string()
    } else {
        if v.contains(" #") || v.contains(": ") || v.starts_with(['{', '[', '!', '%', '@', '`']) {
            return Err("a plain scalar YAML may read differently — quote it");
        }
        v.to_string()
    };
    if value.contains("${{") {
        return Err("`${{ }}` interpolation");
    }
    Ok(value)
}

/// Every problem in `workflows` (path, text) against `gates`.
pub fn check_texts(gates: &[TreeGate], workflows: &[(String, String)]) -> Vec<Problem> {
    let mut problems = Vec::new();
    let mut seen: Vec<&str> = Vec::new();
    for (file, text) in workflows {
        let wf = read_workflow(text);
        for line in &wf.stray {
            problems.push(Problem {
                file: file.clone(),
                line: *line,
                what: "a tree gate referenced outside a step — only a step may be skipped on one"
                    .into(),
            });
        }
        for job in &wf.jobs {
            for step in &job.steps {
                let names = referenced(&step.text);
                if names.is_empty() {
                    continue;
                }
                let at = |what: String| Problem {
                    file: file.clone(),
                    line: step.line,
                    what,
                };
                if names.len() > 1 {
                    problems.push(at(format!(
                        "one step is gated on several tree gates ({}) — a gate proves one command",
                        names.join(", ")
                    )));
                    continue;
                }
                let name = &names[0];
                let Some(gate) = gates.iter().find(|g| &g.name == name) else {
                    problems.push(at(format!("`tree-{name}` is not declared in {MANIFEST}")));
                    continue;
                };
                seen.push(&gate.name);
                let inherited: Vec<(usize, Inherited)> =
                    wf.inherits.iter().chain(&job.inherits).copied().collect();
                if let Some((l, _)) = inherited.iter().find(|(_, k)| *k == Inherited::Other) {
                    problems.push(Problem {
                        file: file.clone(),
                        line: *l,
                        what: format!(
                            "`tree-{name}` is skipped in a job that inherits `env:` or \
                             `defaults:` — they change what `run:` does; move them onto \
                             the steps that need them"
                        ),
                    });
                    continue;
                }
                if let Some((l, _)) = inherited.first() {
                    if !is_simple(&gate.normalized()) {
                        problems.push(Problem {
                            file: file.clone(),
                            line: *l,
                            what: format!(
                                "`tree-{name}` inherits `shell: bash`, which is accepted only \
                                 for a simple command — this one has a pipe, list, \
                                 redirection or substitution"
                            ),
                        });
                        continue;
                    }
                }
                let mut run = None;
                let mut bad = None;
                for (k, v, l) in &step.keys {
                    match k.as_str() {
                        "run" => run = Some((v, *l)),
                        "env" | "shell" => {
                            bad = Some(format!("a step-level `{k}:` changes what `run:` does"))
                        }
                        "working-directory" => match (scalar(v), &gate.cwd) {
                            (Ok(dir), Some(cwd))
                                if dir.trim_end_matches('/').trim_start_matches("./")
                                    == cwd.as_str() => {}
                            _ => {
                                bad = Some(
                                    "`working-directory:` differs from the gate's `cwd=`".into(),
                                )
                            }
                        },
                        _ => {}
                    }
                }
                if bad.is_none() && gate.cwd.is_some() {
                    let has_wd = step.keys.iter().any(|(k, _, _)| k == "working-directory");
                    if !has_wd {
                        bad = Some(format!(
                            "the gate runs in `{}` (cwd=) but the step has no \
                             `working-directory:`",
                            gate.cwd.as_deref().unwrap_or("")
                        ));
                    }
                }
                if let Some(why) = bad {
                    problems.push(at(format!("`tree-{name}`: {why}")));
                    continue;
                }
                let Some((raw, line)) = run else {
                    problems.push(at(format!("`tree-{name}` gates a step with no `run:`")));
                    continue;
                };
                match scalar(raw) {
                    Err(why) => problems.push(Problem {
                        file: file.clone(),
                        line,
                        what: format!("`tree-{name}`: `run:` is {why}"),
                    }),
                    Ok(value) => {
                        let got = normalize_command(&value);
                        let want = gate.normalized();
                        if got != want {
                            problems.push(Problem {
                                file: file.clone(),
                                line,
                                what: format!(
                                    "`tree-{name}` runs `{got}` here but `{want}` in {MANIFEST}:{}",
                                    gate.lineno
                                ),
                            });
                        }
                    }
                }
            }
        }
    }
    for gate in gates {
        if !seen.contains(&gate.name.as_str()) {
            problems.push(Problem {
                file: MANIFEST.into(),
                line: gate.lineno,
                what: format!(
                    "`tree-{}` is declared but no workflow step is skipped on it",
                    gate.name
                ),
            });
        }
    }
    problems
}

/// The built-in test gates a CI step may be skipped on (#288).
pub const BUILTIN_TEST_GATES: &[&str] = &[
    "pre-push-cargo-test",
    "pre-push-go-test",
    "pre-push-pytest",
    "pre-push-run-tests-js",
];

/// Flags that change what a run prints, never its verdict.
const NOISE: &[&str] = &["-q", "--quiet", "-v", "--verbose"];

/// Whether `command` runs what the built-in `gate` runs locally, under the
/// stated equivalences (#288, the t03 survey):
///
/// - `pre-push-cargo-test`: `cargo test`, with `--workspace` and
///   `--all-features` optional (the local gate passes both; a single-package
///   repository is the same suite without them).
/// - `pre-push-go-test`: `go test ./...`.
/// - `pre-push-pytest`: `pytest`, bare, as `python -m pytest`, or under
///   `uv run` with `--no-sync` or `--frozen`.
/// - `pre-push-run-tests-js`: one of the scripts the local gate runs
///   (`typecheck`, `test:unit`, `test`), through npm, pnpm or yarn.
///
/// `-q`/`-v` are ignored everywhere. Anything else differs: a coverage
/// floor, `-race`, `--locked`, a package subset, a `make` target, a pipe.
fn builtin_matches(gate: &str, command: &str) -> bool {
    if !is_simple(command) {
        return false;
    }
    let tokens: Vec<&str> = command
        .split_whitespace()
        .filter(|t| !NOISE.contains(t))
        .collect();
    match gate {
        "pre-push-cargo-test" => {
            tokens.starts_with(&["cargo", "test"])
                && tokens[2..]
                    .iter()
                    .all(|t| matches!(*t, "--workspace" | "--all-features"))
        }
        "pre-push-go-test" => tokens == ["go", "test", "./..."],
        "pre-push-pytest" => {
            let rest: Vec<&str> = match tokens.as_slice() {
                ["uv", "run", rest @ ..] => rest
                    .iter()
                    .copied()
                    .filter(|t| !matches!(*t, "--no-sync" | "--frozen"))
                    .collect(),
                ["python" | "python3", "-m", rest @ ..] => rest.to_vec(),
                other => other.to_vec(),
            };
            rest == ["pytest"]
        }
        "pre-push-run-tests-js" => {
            let script = match tokens.as_slice() {
                ["npm" | "pnpm" | "yarn", "test"] => Some("test"),
                ["npm" | "pnpm", "run", s] => Some(*s),
                ["pnpm" | "yarn", s] => Some(*s),
                _ => None,
            };
            matches!(script, Some("typecheck" | "test:unit" | "test"))
        }
        _ => false,
    }
}

/// The built-in test gate a step is skipped on (`!contains(…, '<gate>')`),
/// if any. A step that runs only WHEN attested (`contains(…)` without `!`)
/// reports the skip and is not one.
fn skipped_builtin(text: &str) -> Option<&'static str> {
    if !text.contains("!contains(") {
        return None;
    }
    BUILTIN_TEST_GATES
        .iter()
        .copied()
        .find(|g| text.contains(&format!("'{g}'")) || text.contains(&format!("\"{g}\"")))
}

/// Every CI step skipped on a built-in test gate whose command is not that
/// gate's (#288). Reported at warn severity: about 25 repositories differ
/// today, and a blocking check would stop their commits on upgrade. The same
/// fail-closed reading as the tree gates: what cannot be read with certainty
/// differs.
pub fn builtin_drift_texts(workflows: &[(String, String)]) -> Vec<Problem> {
    let mut problems = Vec::new();
    for (file, text) in workflows {
        let wf = read_workflow(text);
        for job in &wf.jobs {
            for step in &job.steps {
                let Some(gate) = skipped_builtin(&step.text) else {
                    continue;
                };
                let at = |line: usize, what: String| Problem {
                    file: file.clone(),
                    line,
                    what: format!(
                        "`{gate}` {what} — CI skips this step on a signature of a \
                         different command"
                    ),
                };
                let inherited: Vec<(usize, Inherited)> =
                    wf.inherits.iter().chain(&job.inherits).copied().collect();
                if let Some((l, _)) = inherited.iter().find(|(_, k)| *k == Inherited::Other) {
                    problems.push(at(
                        *l,
                        "is skipped in a job that inherits `env:` or `defaults:`".into(),
                    ));
                    continue;
                }
                let mut run = None;
                let mut bad = None;
                for (k, v, l) in &step.keys {
                    match k.as_str() {
                        "run" => run = Some((v, *l)),
                        "env" | "shell" | "working-directory" => {
                            bad = Some((*l, format!("gates a step with its own `{k}:`")))
                        }
                        _ => {}
                    }
                }
                if let Some((l, why)) = bad {
                    problems.push(at(l, why));
                    continue;
                }
                let Some((raw, line)) = run else {
                    problems.push(at(step.line, "gates a step with no `run:`".into()));
                    continue;
                };
                match scalar(raw) {
                    Err(why) => problems.push(at(line, format!("gates a `run:` that is {why}"))),
                    Ok(value) => {
                        let got = normalize_command(&value);
                        if !builtin_matches(gate, &got) {
                            problems.push(at(line, format!("gates `{got}`")));
                        }
                    }
                }
            }
        }
    }
    problems
}

/// [`builtin_drift_texts`] over `root`'s workflows.
pub fn builtin_drift(root: &Path) -> Vec<Problem> {
    builtin_drift_texts(&read_workflows(root))
}

/// Every workflow file under `root`, as (relative path, text), sorted.
fn read_workflows(root: &Path) -> Vec<(String, String)> {
    let mut workflows = Vec::new();
    for dir in WORKFLOW_DIRS {
        let Ok(entries) = std::fs::read_dir(root.join(dir)) else {
            continue;
        };
        let mut paths: Vec<_> = entries
            .filter_map(Result::ok)
            .map(|e| e.path())
            .filter(|p| matches!(p.extension().and_then(|e| e.to_str()), Some("yml" | "yaml")))
            .collect();
        paths.sort();
        for p in paths {
            if let Ok(text) = std::fs::read_to_string(&p) {
                let rel = p.strip_prefix(root).unwrap_or(&p).display().to_string();
                workflows.push((rel, text));
            }
        }
    }
    workflows
}

/// Read `root`'s manifest and workflows, and compare them.
pub fn check_repo(root: &Path) -> Vec<Problem> {
    let Ok(manifest) = std::fs::read_to_string(root.join(MANIFEST)) else {
        return Vec::new();
    };
    let gates = tree_gates(&manifest);
    if gates.is_empty() {
        return Vec::new();
    }
    check_texts(&gates, &read_workflows(root))
}

/// The pre-commit check. A built-in test gate's drift warns (#288); a tree
/// gate's blocks. `Inert` when there is neither a tree gate nor a step
/// skipped on a built-in one.
pub fn run(settings: &crate::config::Settings) -> Outcome {
    let root = repo_root();
    let root = Path::new(&root);
    let drift = builtin_drift(root);
    for p in &drift {
        warn(&crate::ui::sanitize(&p.to_string()));
    }
    let declares = std::fs::read_to_string(root.join(MANIFEST))
        .map(|t| !tree_gates(&t).is_empty())
        .unwrap_or(false);
    let problems = if declares {
        check_repo(root)
    } else {
        Vec::new()
    };
    if problems.is_empty() {
        return match (declares, drift.is_empty()) {
            (_, false) => Outcome::Warned,
            (true, true) => {
                ok(settings, "tree gates match their CI steps");
                Outcome::Passed
            }
            (false, true) => Outcome::Inert,
        };
    }
    for p in &problems {
        eprintln!("  {}", crate::ui::sanitize(&p.to_string()));
    }
    fail(&format!(
        "{} tree-gate parity problem(s) — fix the workflow or the {} line; run {} to re-check",
        problems.len(),
        MANIFEST,
        hl(concat!(crate::bin!(), " tree-parity"))
    ));
    Outcome::Failed
}

#[cfg(test)]
mod tests {
    use super::*;

    fn drift(step_run: &str) -> Vec<Problem> {
        let text = format!(
            "name: ci\non:\n  push:\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - id: attest\n        uses: fredericrous/attest@v1\n      - if: ${{{{ !contains(fromJSON(steps.attest.outputs.gates || '[]'), 'pre-push-cargo-test') }}}}\n        {step_run}\n"
        );
        builtin_drift_texts(&[(".github/workflows/ci.yaml".into(), text)])
    }

    /// #288: a step skipped on a built-in test gate must run that gate's
    /// command, under the stated equivalences.
    #[test]
    fn a_builtin_gate_step_is_compared_with_the_local_command() {
        assert_eq!(drift("run: cargo test"), vec![]);
        assert_eq!(
            drift("run: cargo test --workspace --all-features -q"),
            vec![]
        );
        let locked = drift("run: cargo test --workspace --locked");
        assert_eq!(locked.len(), 1, "{locked:?}");
        assert!(locked[0].what.contains("pre-push-cargo-test"), "{locked:?}");
        assert_eq!(drift("run: make test").len(), 1);
        assert_eq!(
            drift("run: |\n          cargo test").len(),
            1,
            "a block scalar differs"
        );
        assert_eq!(
            drift("run: cargo test\n        env:\n          X: 1").len(),
            1
        );
    }

    #[test]
    fn the_builtin_equivalences() {
        assert!(builtin_matches("pre-push-go-test", "go test ./..."));
        assert!(!builtin_matches("pre-push-go-test", "go test -race ./..."));
        assert!(builtin_matches(
            "pre-push-pytest",
            "uv run --no-sync pytest"
        ));
        assert!(builtin_matches("pre-push-pytest", "python -m pytest -q"));
        assert!(!builtin_matches(
            "pre-push-pytest",
            "uv run pytest --cov-fail-under=80"
        ));
        assert!(builtin_matches(
            "pre-push-run-tests-js",
            "pnpm run test:unit"
        ));
        assert!(builtin_matches("pre-push-run-tests-js", "npm test"));
        assert!(!builtin_matches("pre-push-run-tests-js", "pnpm coverage"));
        assert!(!builtin_matches(
            "pre-push-cargo-test",
            "cargo test | tee log"
        ));
    }

    /// A step that runs only when attested reports the skip; it is not one.
    #[test]
    fn a_step_run_when_attested_is_not_a_skipped_one() {
        assert_eq!(
            skipped_builtin("if: ${{ contains(fromJSON(x), 'pre-push-cargo-test') }}"),
            None
        );
        assert_eq!(
            skipped_builtin("if: ${{ !contains(fromJSON(x), 'pre-push-cargo-test') }}"),
            Some("pre-push-cargo-test")
        );
    }

    fn gates(text: &str) -> Vec<TreeGate> {
        let g = tree_gates(text);
        assert!(!g.is_empty(), "no gate parsed from {text:?}");
        g
    }

    fn check(manifest: &str, workflow: &str) -> Vec<Problem> {
        check_texts(
            &gates(manifest),
            &[(
                ".forgejo/workflows/ci.yaml".to_string(),
                workflow.to_string(),
            )],
        )
    }

    const ESLINT: &str = "tree eslint eslint * attest npm run lint -- {cache}";

    fn wf(step_run: &str) -> String {
        format!(
            "name: ci\non:\n  push:\njobs:\n  checks:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - id: attest\n        uses: fredericrous/attest@v1\n      - name: Lint\n        if: ${{{{ !contains(fromJSON(steps.attest.outputs.gates || '[]'), 'tree-eslint') }}}}\n        {step_run}\n"
        )
    }

    #[test]
    fn parity_matching_run_passes() {
        assert_eq!(check(ESLINT, &wf("run: npm run lint")), vec![]);
    }

    #[test]
    fn parity_quoted_run_passes() {
        assert_eq!(check(ESLINT, &wf("run: 'npm run lint'")), vec![]);
    }

    #[test]
    fn parity_drifted_run_fails() {
        let p = check(ESLINT, &wf("run: npm run lint -- --max-warnings 0"));
        assert_eq!(p.len(), 1, "{p:?}");
        assert!(p[0]
            .what
            .contains("runs `npm run lint -- --max-warnings 0` here"));
    }

    #[test]
    fn parity_block_scalar_rejected() {
        let p = check(ESLINT, &wf("run: |\n          npm run lint"));
        assert_eq!(p.len(), 1, "{p:?}");
        assert!(p[0].what.contains("block scalar"));
    }

    #[test]
    fn parity_anchor_rejected() {
        let p = check(ESLINT, &wf("run: *lint"));
        assert!(p[0].what.contains("anchor"), "{p:?}");
    }

    #[test]
    fn parity_interpolation_rejected() {
        let p = check(ESLINT, &wf("run: npm run ${{ matrix.task }}"));
        assert!(p[0].what.contains("interpolation"), "{p:?}");
    }

    #[test]
    fn parity_step_env_rejected() {
        let p = check(
            ESLINT,
            &wf("env:\n          CI: '1'\n        run: npm run lint"),
        );
        assert!(p[0].what.contains("step-level `env:`"), "{p:?}");
    }

    #[test]
    fn parity_step_shell_rejected() {
        let p = check(ESLINT, &wf("shell: bash\n        run: npm run lint"));
        assert!(p[0].what.contains("step-level `shell:`"), "{p:?}");
    }

    #[test]
    fn parity_undeclared_working_directory_rejected() {
        let p = check(
            ESLINT,
            &wf("working-directory: web\n        run: npm run lint"),
        );
        assert!(p[0].what.contains("working-directory"), "{p:?}");
    }

    #[test]
    fn parity_declared_cwd_passes() {
        let p = check(
            "tree eslint eslint * attest cwd=web npm run lint",
            &wf("working-directory: web\n        run: npm run lint"),
        );
        assert_eq!(p, vec![]);
    }

    #[test]
    fn parity_cwd_without_working_directory_rejected() {
        let p = check(
            "tree eslint eslint * attest cwd=web npm run lint",
            &wf("run: npm run lint"),
        );
        assert!(p[0].what.contains("no `working-directory:`"), "{p:?}");
    }

    #[test]
    fn parity_job_env_rejected() {
        let w = wf("run: npm run lint").replace(
            "    runs-on: ubuntu-latest\n",
            "    runs-on: ubuntu-latest\n    env:\n      NODE_ENV: test\n",
        );
        let p = check(ESLINT, &w);
        assert!(p[0].what.contains("inherits"), "{p:?}");
    }

    #[test]
    fn parity_job_defaults_rejected() {
        let w = wf("run: npm run lint").replace(
            "    runs-on: ubuntu-latest\n",
            "    runs-on: ubuntu-latest\n    defaults:\n      run:\n        working-directory: web\n",
        );
        let p = check(ESLINT, &w);
        assert!(p[0].what.contains("inherits"), "{p:?}");
    }

    #[test]
    fn parity_workflow_shell_bash_accepted_for_a_simple_command() {
        let w = wf("run: npm run lint")
            .replace("jobs:\n", "defaults:\n  run:\n    shell: bash\njobs:\n");
        assert_eq!(check(ESLINT, &w), vec![]);
    }

    #[test]
    fn parity_job_shell_bash_accepted_for_a_simple_command() {
        let w = wf("run: npm run lint").replace(
            "    runs-on: ubuntu-latest\n",
            "    runs-on: ubuntu-latest\n    defaults:\n      run:\n        shell: bash\n",
        );
        assert_eq!(check(ESLINT, &w), vec![]);
    }

    #[test]
    fn parity_shell_bash_rejected_for_a_pipeline() {
        let w = wf("run: npm run lint | tee lint.log")
            .replace("jobs:\n", "defaults:\n  run:\n    shell: bash\njobs:\n");
        let p = check(
            "tree eslint eslint * attest npm run lint | tee lint.log",
            &w,
        );
        assert!(p[0].what.contains("simple command"), "{p:?}");
    }

    #[test]
    fn parity_other_shell_rejected() {
        let w =
            wf("run: npm run lint").replace("jobs:\n", "defaults:\n  run:\n    shell: sh\njobs:\n");
        let p = check(ESLINT, &w);
        assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
    }

    #[test]
    fn parity_shell_bash_plus_working_directory_rejected() {
        let w = wf("run: npm run lint").replace(
            "jobs:\n",
            "defaults:\n  run:\n    shell: bash\n    working-directory: web\njobs:\n",
        );
        let p = check(ESLINT, &w);
        assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
    }

    #[test]
    fn parity_workflow_env_still_rejected_beside_shell_bash() {
        let w = wf("run: npm run lint").replace(
            "jobs:\n",
            "defaults:\n  run:\n    shell: bash\nenv:\n  CI: '1'\njobs:\n",
        );
        let p = check(ESLINT, &w);
        assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
    }

    #[test]
    fn parity_undeclared_gate_rejected() {
        let p = check(
            "tree prettier prettier * attest npx prettier --check .",
            &wf("run: npm run lint"),
        );
        assert!(
            p.iter()
                .any(|p| p.what.contains("`tree-eslint` is not declared")),
            "{p:?}"
        );
        assert!(
            p.iter().any(|p| p.what.contains("no workflow step")),
            "{p:?}"
        );
    }

    #[test]
    fn parity_declared_gate_without_step_rejected() {
        let p = check(
            ESLINT,
            "name: ci\njobs:\n  a:\n    steps:\n      - run: true\n",
        );
        assert_eq!(p.len(), 1, "{p:?}");
        assert!(p[0].what.contains("no workflow step is skipped on it"));
    }

    #[test]
    fn parity_job_level_reference_rejected() {
        let w = "name: ci\njobs:\n  lint:\n    if: ${{ !contains(fromJSON(needs.a.outputs.gates), 'tree-eslint') }}\n    steps:\n      - run: npm run lint\n";
        let p = check(ESLINT, w);
        assert!(p.iter().any(|p| p.what.contains("outside a step")), "{p:?}");
    }

    #[test]
    fn parity_two_gates_on_one_step_rejected() {
        let w = wf("run: npm run lint").replace(
            "'tree-eslint') }}",
            "'tree-eslint') && !contains(fromJSON(steps.attest.outputs.gates), 'tree-prettier') }}",
        );
        let p = check(
            "tree eslint eslint * attest npm run lint\ntree prettier prettier * attest npx prettier --check .",
            &w,
        );
        let several = p
            .iter()
            .find(|p| p.what.contains("several tree gates"))
            .unwrap_or_else(|| panic!("{p:?}"));
        // The problem names the step's own line (`- name: Lint`), where the
        // reader has to look.
        assert_eq!(several.line, 11, "{several:?}");
    }
}