amont-runtime 1.2.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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
//! `amont.conf` — checks a repository declares for itself.
//!
//! A third party cannot add a Rust module without rebuilding this binary, so
//! extension means declared commands.
//!
//! The manifest is **committed at the repository root**, and that is the point.
//! `.git/hooks` is not committed, so under the old filename-prefix mechanism a
//! team could never actually share a custom hook — every member had to install
//! it by hand, and nothing told them when it changed. That flaw mattered more
//! than the lexicographic ordering usually cited against prefixes.
//!
//! ```text
//! # stage       name        scope   severity  command
//! pre-commit    shellcheck  *.sh    block     scripts/lint-shell.sh
//! pre-push      smoke       *       warn      make smoke
//! ```
//!
//! Whitespace-delimited, in file order. TOML would be nicer to write and costs a
//! dependency tree that would then run on every commit in ninety-six
//! repositories; for four fields and a command, the twenty lines of parsing win.
//! See `scripts/check-no-deps.sh` for why that trade is the default here.
//!
//! ## No shell
//!
//! The command is split on whitespace and executed directly. There is no shell,
//! so no pipes, no redirection, no globbing and no quoting. Two reasons, and the
//! second is the one that decided it: Windows has no `sh`, and every emulation
//! of one this project has tried has been a source of bugs; and a manifest line
//! that silently gained shell semantics would be a much larger thing to have
//! introduced than it looks. A pipeline belongs in a script the line invokes.
//!
//! ## A line that cannot be understood is not skipped
//!
//! A malformed line means a check the repository asked for is not running, which
//! is precisely the "looks verified, enforced nothing" failure `Outcome` exists
//! to name. So a broken line still produces a check — one that runs to
//! `Unavailable` and says why. It appears in the dispatcher's "could not run"
//! roll-up like any other gap, rather than needing a mechanism of its own.

use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::OnceLock;

use crate::check::{Check, Fix, Outcome, Scope, Severity, Stage};
use crate::hooks::common::Restaged;
use crate::registry::{Ctx, CHECKS, ENTRYPOINTS};

pub const MANIFEST: &str = "amont.conf";

/// Why a line could not be used.
///
/// A type rather than a `String`: the prose belongs in `Display`, and a caller
/// that wants to ask "was this a duplicate?" should not have to grep for the
/// word. The tests used to assert on substrings, which coupled them to wording
/// and would have kept passing if the wording stayed while the meaning changed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
    MissingFields,
    MissingName,
    /// Names a check compiled into the binary.
    NameTaken(String),
    /// The name is a trigger, or carries one as a prefix.
    ///
    /// `pre-commit  pre-commit-clippy  …` would declare a check whose SHORT
    /// name is another check's full id, so `hook.skip pre-commit-clippy` would
    /// mean two things at once. The stage column supplies the trigger; writing
    /// it again in the name is the one way to make an id ambiguous.
    TriggerInName(String),
    /// A second USABLE line claiming a name already claimed ON THE SAME
    /// TRIGGER. The same name on both triggers is two checks, not a clash.
    Duplicate(String),
    BadStage(String),
    BadScope(String),
    BadSeverity(String),
    /// A `pre-push` line asked to rewrite files.
    ///
    /// Refused HERE, beside `NameTaken` and `Duplicate`, rather than as a
    /// runtime "contract violation" at push time: same fact, discovered
    /// earlier, by more people, at the moment it is cheapest to fix. A pre-push
    /// hook must not modify the worktree or index — the pushed commit would
    /// then differ from the tree the developer is looking at.
    FixOnPrePush,
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::MissingFields => {
                write!(f, "expected 5 fields: stage name scope severity command")
            }
            ParseError::MissingName => write!(f, "missing name"),
            ParseError::NameTaken(n) => write!(f, "{n:?} already names a check"),
            ParseError::TriggerInName(n) => write!(
                f,
                "{n:?} must not be a trigger or start with one — the stage column says which"
            ),
            ParseError::Duplicate(n) => write!(f, "{n:?} is declared twice on one trigger"),
            ParseError::BadStage(t) => {
                write!(f, "stage {t:?} must be `pre-commit` or `pre-push`")
            }
            ParseError::BadScope(t) => write!(f, "scope {t:?} must be `*` or `*.<ext>`"),
            ParseError::FixOnPrePush => write!(
                f,
                "`fix` is only for pre-commit — a pre-push hook must not rewrite files"
            ),
            ParseError::BadSeverity(t) => {
                write!(f, "severity {t:?} must be `block` or `warn`")
            }
        }
    }
}

/// A line that parsed. Every field means something.
///
/// `program` and `args` rather than one `argv`: a runnable check must have a
/// command, and splitting the head off makes that structural instead of a
/// `split_first` guard that can only ever be dead code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Declared {
    /// `Fix::Rewrite` when the command column began `fix `.
    pub fix: Fix,
    pub name: String,
    pub stage: Stage,
    pub severity: Severity,
    /// Extensions that gate it. Empty means any change — the `*` scope.
    pub exts: Vec<String>,
    pub program: String,
    pub args: Vec<String>,
}

impl Declared {
    /// `<trigger>-<name>`, the same shape a built-in has.
    ///
    /// This is what `hook.skip` and `amont.severity.<key>` resolve against,
    /// so a declared check answers to its trigger and its short name exactly as
    /// a compiled-in one does. Before it had an id, `hook.skip pre-commit`
    /// silenced fifteen built-ins and left every declared check running.
    pub fn id(&self) -> String {
        format!("{}-{}", self.stage.as_str(), self.name)
    }

    /// The command as written, for display.
    pub fn command(&self) -> String {
        std::iter::once(self.program.as_str())
            .chain(self.args.iter().map(String::as_str))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

/// One manifest line: usable, or not.
///
/// A SUM, not a struct with an `Option<why>` beside the fields. The struct
/// form let a broken line carry a severity, a scope and an argv that meant
/// nothing — and it produced a wrong diagnosis: because broken and usable
/// entries shared one list, a valid line was rejected as "declared twice" for
/// colliding with a line that could not run. Dedup now sees only `Usable`.
///
/// Separate from `External` because the fleet reads ninety-six manifests and may
/// re-read them on every refresh, while `External` holds a `Scope` whose
/// `&'static` slices are LEAKED.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Line {
    Usable(Declared),
    Broken {
        /// The declared name, or `<file>:<lineno>` when the line has none — a
        /// gap has to be nameable to be reportable.
        name: String,
        /// Broken lines land on pre-commit unless the stage token parsed: seen
        /// on every commit beats seen on every push.
        stage: Stage,
        lineno: usize,
        why: ParseError,
    },
}

impl Line {
    pub fn name(&self) -> &str {
        match self {
            Line::Usable(d) => &d.name,
            Line::Broken { name, .. } => name,
        }
    }
    pub fn stage(&self) -> Stage {
        match self {
            Line::Usable(d) => d.stage,
            Line::Broken { stage, .. } => *stage,
        }
    }
    /// `Some(reason)` when this line declares a check that cannot run.
    pub fn broken(&self) -> Option<String> {
        match self {
            Line::Usable(_) => None,
            Line::Broken { lineno, why, .. } => Some(format!("line {lineno}: {why}")),
        }
    }

    /// `<trigger>-<name>`, matching `Declared::id` and `External::id`. A broken
    /// line has one too: `hook.skip pre-commit` should silence its nag exactly
    /// as it silences the checks that do run.
    pub fn id(&self) -> String {
        format!("{}-{}", self.stage().as_str(), self.name())
    }

    /// Consume into the identity every line has, and either the declaration or
    /// the reason there is none.
    ///
    /// Both consumers — `External::from` and the fleet's projection — used to
    /// destructure this by hand, and both carried an arm for a combination the
    /// type forbids, because they computed the reason BEFORE matching. Written
    /// once, that arm has nowhere to appear.
    pub fn into_parts(self) -> (String, Stage, Result<Declared, String>) {
        let name = self.name().to_string();
        let stage = self.stage();
        let parsed = match self {
            Line::Usable(d) => Ok(d),
            Line::Broken { lineno, why, .. } => Err(format!("line {lineno}: {why}")),
        };
        (name, stage, parsed)
    }
}

/// A check a repository declares, rather than one compiled in.
pub struct External {
    /// `<trigger>-<name>` — what `hook.skip` and `amont.severity.<key>`
    /// resolve against, and what `Check::name` returns. Built-ins have had this
    /// shape all along; declared checks answering to a bare name were invisible
    /// to `hook.skip pre-commit`.
    pub id: String,
    /// The name as written in the manifest — the "short name" of the vocabulary
    /// — used for messages. A line too malformed to name itself falls back to
    /// its position, and reading `pre-commit-amont.conf:3` back to somebody
    /// helps nobody.
    pub short_name: String,
    pub stage: Stage,
    pub kind: Kind,
}

/// The two things an external can be. `Scope` and `Severity` live only on the
/// runnable side, so a broken external cannot carry a severity nobody applies.
pub enum Kind {
    Runnable {
        scope: Scope,
        severity: Severity,
        program: String,
        args: Vec<String>,
        fix: Fix,
    },
    Unusable {
        why: String,
    },
}

impl Check for External {
    fn name(&self) -> &str {
        &self.id
    }
    fn stage(&self) -> Stage {
        self.stage
    }
    /// Derived for an unusable check rather than stored: it never runs, so its
    /// scope is a question with no answer, and computing one here keeps the
    /// DATA from carrying a value that means nothing.
    fn scope(&self) -> Scope {
        match &self.kind {
            Kind::Runnable { scope, .. } => *scope,
            Kind::Unusable { .. } => Scope::ALWAYS,
        }
    }
    fn severity(&self) -> Severity {
        match &self.kind {
            Kind::Runnable { severity, .. } => *severity,
            // Never consulted: an unusable check reports `Unavailable`, which
            // no severity can turn into a block.
            Kind::Unusable { .. } => Severity::Warn,
        }
    }

    fn run(&self, ctx: &Ctx) -> Outcome {
        let (scope, program, args, fix) = match &self.kind {
            Kind::Runnable {
                scope,
                program,
                args,
                fix,
                ..
            } => (scope, program, args, *fix),
            Kind::Unusable { why } => {
                crate::hooks::common::warn(&format!(
                    "{MANIFEST}: {}{}",
                    crate::ui::highlight(&self.short_name),
                    // Carries repo tokens: `BadStage("…")` quotes the manifest.
                    crate::ui::sanitize(why)
                ));
                return Outcome::Unavailable;
            }
        };

        // The scope gate lives HERE, unlike a built-in's, which enforces its own
        // in its first three lines. A declared command has no way to know what
        // was staged, so if this did not gate it, `*.sh` would run on every
        // commit and the column would be decoration.
        //
        // Which files to test against depends on the stage: what is staged for
        // a commit, what is being pushed for a push. `*` short-circuits before
        // either is computed, which is the common case.
        // A check whose whole job is to rewrite has nothing to say when nobody
        // asked for rewriting — so it does not RUN, rather than running and
        // having its result discarded. Gating only the re-staging let the
        // command edit files with `amont.fix` off, which is precisely the
        // surprise the gate exists to prevent.
        //
        // `Unavailable`, not `Passed`. `check.rs` defines `Unavailable` as
        // "COULD NOT RUN — a tool is missing, or the opt-in config is absent",
        // which is exactly this; `Passed` is the one verdict it must not
        // report, because the dispatcher's roll-up and the fleet dashboard
        // then show a check that never executed as clean. With a message,
        // because every other `Unavailable` in this codebase says what was
        // missing and an unexplained count on every commit is worse than none.
        if fix == Fix::Rewrite && !crate::hooks::common::fixing_enabled() {
            crate::hooks::common::warn(&format!(
                "{}: declares fix, and {} is off — not run",
                crate::ui::highlight(&self.short_name),
                crate::ui::highlight("amont.fix")
            ));
            return Outcome::Unavailable;
        }

        let in_scope = match self.stage {
            Stage::PreCommit => crate::hooks::common::staged_files(&[]),
            Stage::PrePush => crate::pushrefs::changed_files(ctx.push.get()),
        };
        if !scope.files.is_empty() && !scope.matches(&in_scope) {
            return Outcome::Passed;
        }
        let root = crate::hooks::common::repo_root();
        let mut cmd = Command::new(program);
        cmd.args(args).current_dir(&root).stdin(Stdio::null());
        crate::hooks::common::strip_git_env(&mut cmd);
        match cmd.status() {
            // A command that could not be STARTED has not judged anything. This
            // is the distinction `Outcome` was added for: reporting a missing
            // `shellcheck` as a lint failure sends someone hunting for a lint
            // error that does not exist.
            Err(e) => {
                crate::hooks::common::warn(&format!(
                    "{MANIFEST}: {} could not run {}{}",
                    crate::ui::highlight(&self.short_name),
                    crate::ui::highlight(program),
                    // The io error's text embeds the program name it tried.
                    crate::ui::sanitize(&e.to_string())
                ));
                Outcome::Unavailable
            }
            Ok(s) if s.success() => {
                // A declared fixer that ran clean may still have rewritten
                // something; re-stage exactly what moved. Only its own scope,
                // so it cannot stage a file it never looked at.
                if fix == Fix::Rewrite && crate::hooks::common::fixing_enabled() {
                    match crate::hooks::common::restage(&scoped(scope, &in_scope)) {
                        Restaged::Staged => {
                            crate::hooks::common::ok(&format!(
                                "{} fixed and re-staged",
                                crate::ui::highlight(&self.short_name)
                            ));
                            return Outcome::Fixed;
                        }
                        // `git add` failed, so the index still holds whatever
                        // the command has already replaced on disk. This used
                        // to be indistinguishable from "nothing moved" and was
                        // reported as a pass.
                        Restaged::Failed(stuck) => {
                            crate::hooks::common::fail(&format!(
                                "{} rewrote files but {} failed — the index still holds the \
                                 OLD content: {}",
                                crate::ui::highlight(&self.short_name),
                                crate::ui::highlight("git add"),
                                crate::ui::sanitize(&stuck.join(", "))
                            ));
                            return Outcome::Failed;
                        }
                        Restaged::Nothing => {}
                    }
                }
                Outcome::Passed
            }
            Ok(_) => {
                crate::hooks::common::fail(&format!(
                    "{} failed (output above)",
                    crate::ui::highlight(&self.short_name)
                ));
                Outcome::Failed
            }
        }
    }
}

/// The paths this check's scope actually covers.
fn scoped(scope: &Scope, paths: &[String]) -> Vec<String> {
    if scope.files.is_empty() {
        return paths.to_vec();
    }
    paths
        .iter()
        .filter(|p| scope.files.iter().any(|e| p.ends_with(e)))
        .cloned()
        .collect()
}

/// `Scope` holds `&'static` slices so a built-in can be a `const`. A parsed
/// manifest has neither, so its extension list is leaked.
///
/// This is bounded and deliberate: the manifest is read at most once per
/// process, holds a handful of short strings, and the process is a git hook that
/// exits in milliseconds. The alternative — a lifetime on `Scope` — would
/// propagate through the trait, both dispatchers and the fleet crate to buy back
/// a few hundred bytes that the kernel reclaims moments later.
fn leak(exts: Vec<String>) -> &'static [&'static str] {
    let refs: Vec<&'static str> = exts
        .into_iter()
        .map(|s| &*Box::leak(s.into_boxed_str()))
        .collect();
    Box::leak(refs.into_boxed_slice())
}

/// `*` means any change; `*.sh` or `*.sh,*.bash` gate on extensions.
///
/// No `opt_in` counterpart, because the manifest IS the opt-in: a repository
/// that does not want the check deletes the line.
///
/// Returns owned extensions rather than a `Scope`, so validating a manifest
/// costs nothing permanent. Only `External::from` turns these into the
/// `&'static` form `Scope` requires.
fn parse_scope(token: &str) -> Result<Vec<String>, ParseError> {
    if token == "*" {
        return Ok(Vec::new());
    }
    let mut exts = Vec::new();
    for part in token.split(',') {
        let ext = part
            .strip_prefix('*')
            .filter(|ext| ext.starts_with('.'))
            .ok_or_else(|| ParseError::BadScope(part.to_string()))?;
        exts.push(ext.to_string());
    }
    Ok(exts)
}

fn parse_stage(token: &str) -> Option<Stage> {
    match token {
        "pre-commit" => Some(Stage::PreCommit),
        "pre-push" => Some(Stage::PrePush),
        _ => None,
    }
}

/// An identity already spoken for. An external must not be able to shadow
/// `pre-push-branch-protect` — nor silently lose to it, which is what a
/// first-match lookup would do without this.
///
/// Judged on the ID, which is why `clippy` on `pre-push` is now legal: it is
/// `pre-push-clippy`, a different check from `pre-commit-clippy`. Judged on the
/// bare name, as it was, the two collided and the second was refused.
///
fn name_is_taken(id: &str) -> bool {
    CHECKS.iter().any(|c| c.name == id) || ENTRYPOINTS.iter().any(|(n, _)| *n == id)
}

/// A short name that says its own trigger — either by being one, or by starting
/// with one.
///
/// Both make an id ambiguous rather than merely ugly. `pre-commit` as a name
/// gives `hook.skip pre-commit` two readings; `pre-commit-clippy` as a name
/// gives a check whose SHORT name is the built-in's FULL id, so one skip
/// silences both. The stage column already says which trigger this is.
fn name_says_its_trigger(name: &str) -> bool {
    crate::TRIGGERS
        .iter()
        .any(|t| name == *t || name.starts_with(&format!("{t}-")))
}

/// The four leading tokens and the untouched remainder, or `None` when the line
/// does not have them.
///
/// The arity is in the TYPE. Returning a `Vec` made "four or it is malformed"
/// a rule every caller had to remember and none could be checked against.
///
/// NOT `splitn(5, char::is_whitespace)`: that splits at the FIRST whitespace
/// character every time, so a file aligned into columns — which is how the
/// format invites you to write it — yields empty fields for every run of
/// spaces after the first.
fn tokenise(line: &str) -> Option<([&str; 4], &str)> {
    let mut fields: [&str; 4] = [""; 4];
    let mut rest = line;
    for slot in fields.iter_mut() {
        rest = rest.trim_start();
        let i = rest.find(char::is_whitespace)?;
        *slot = &rest[..i];
        rest = &rest[i..];
    }
    let command = rest.trim();
    (!command.is_empty()).then_some((fields, command))
}

pub fn parse_lines(text: &str) -> Vec<Line> {
    let mut out: Vec<Line> = Vec::new();
    for (i, raw) in text.lines().enumerate() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let lineno = i + 1;
        out.push(parse_line(lineno, line, &out));
    }
    out
}

/// One line, given the lines already accepted.
///
/// `earlier` is read ONLY for the duplicate check, and only its `Usable`
/// entries — a line that cannot run does not reserve its name. Before this, a
/// valid declaration was rejected as "declared twice" for colliding with a
/// broken one, which pointed the reader at the wrong line entirely.
fn parse_line(lineno: usize, line: &str, earlier: &[Line]) -> Line {
    let (fields, command) = match tokenise(line) {
        Some(t) => t,
        // No name to report: fall back to the position, which is the only
        // handle a reader has on a line this malformed.
        None => {
            return broken_at(
                lineno,
                name_or_position(tokenise(line).map(|(f, _)| f[1]).unwrap_or(""), lineno),
                None,
                ParseError::MissingFields,
            )
        }
    };
    let [stage_tok, declared, scope_tok, severity_tok] = fields;
    let stage = parse_stage(stage_tok);
    let name = name_or_position(declared, lineno);
    let fail = |why| broken_at(lineno, name.clone(), stage, why);

    if declared.is_empty() {
        return fail(ParseError::MissingName);
    }
    // The stage is settled BEFORE the name is judged, because the identity
    // being judged is `<trigger>-<name>` and there is no such thing without a
    // trigger. Ordered the other way, a line with an unusable stage was refused
    // for a name clash that could not be assessed yet.
    let Some(stage) = stage else {
        return fail(ParseError::BadStage(stage_tok.to_string()));
    };
    if name_says_its_trigger(declared) {
        return fail(ParseError::TriggerInName(declared.to_string()));
    }
    let id = format!("{}-{}", stage.as_str(), declared);
    if name_is_taken(&id) {
        return fail(ParseError::NameTaken(declared.to_string()));
    }
    if earlier
        .iter()
        .any(|l| matches!(l, Line::Usable(d) if d.id() == id))
    {
        return fail(ParseError::Duplicate(declared.to_string()));
    }
    let exts = match parse_scope(scope_tok) {
        Ok(e) => e,
        Err(why) => return fail(why),
    };
    let Some(severity) = Severity::parse(severity_tok) else {
        return fail(ParseError::BadSeverity(severity_tok.to_string()));
    };
    // `fix` is a trailing marker on the command column rather than a sixth
    // field, so every manifest written before this still parses.
    let (command, wants_fix) = match command.strip_prefix("fix ") {
        Some(rest) => (rest.trim(), true),
        None => (command, false),
    };
    if wants_fix && stage == Stage::PrePush {
        return fail(ParseError::FixOnPrePush);
    }
    // `tokenise` guarantees a non-empty command, so the split cannot fail.
    let mut argv = command.split_whitespace().map(str::to_owned);
    let Some(program) = argv.next() else {
        return fail(ParseError::MissingFields);
    };
    Line::Usable(Declared {
        fix: if wants_fix { Fix::Rewrite } else { Fix::None },
        name: declared.to_string(),
        stage,
        severity,
        exts,
        program,
        args: argv.collect(),
    })
}

fn name_or_position(declared: &str, lineno: usize) -> String {
    if declared.is_empty() {
        format!("{MANIFEST}:{lineno}")
    } else {
        declared.to_string()
    }
}

fn broken_at(lineno: usize, name: String, stage: Option<Stage>, why: ParseError) -> Line {
    Line::Broken {
        name,
        stage: stage.unwrap_or(Stage::PreCommit),
        lineno,
        why,
    }
}

impl From<Line> for External {
    fn from(l: Line) -> External {
        let (name, stage, parsed) = l.into_parts();
        let kind = match parsed {
            Ok(d) => Kind::Runnable {
                scope: if d.exts.is_empty() {
                    Scope::ALWAYS
                } else {
                    Scope::files(leak(d.exts))
                },
                severity: d.severity,
                program: d.program,
                args: d.args,
                fix: d.fix,
            },
            Err(why) => Kind::Unusable { why },
        };
        let id = format!("{}-{}", stage.as_str(), name);
        External {
            id,
            short_name: name,
            stage,
            kind,
        }
    }
}

pub fn parse(text: &str) -> Vec<External> {
    parse_lines(text).into_iter().map(External::from).collect()
}

/// The manifest for `root`, or an empty list. Read once per process.
pub fn read(root: &Path) -> Vec<External> {
    std::fs::read_to_string(root.join(MANIFEST))
        .map(|t| parse(&t))
        .unwrap_or_default()
}

/// The same file, without building the `Scope`s — for a reader that inspects
/// many repositories and must not leak once per manifest per refresh.
pub fn read_lines(root: &Path) -> Vec<Line> {
    std::fs::read_to_string(root.join(MANIFEST))
        .map(|t| parse_lines(&t))
        .unwrap_or_default()
}

/// Every external declared by the repository this process is running in.
///
/// A `static OnceLock` rather than a leak: the borrow is genuinely `'static`
/// because the storage is, and it also guarantees the file is read once however
/// many checks ask for it.
///
/// `pub(crate)`, NOT `pub`. The answer depends on the working directory at the
/// FIRST call and is then cached for the life of the process — safe in a hook,
/// which handles one repository and exits, and a trap for anything that walks
/// many. The fleet crate reads `read_lines(path)` instead, which takes the
/// repository it means.
pub(crate) fn externals() -> &'static [External] {
    static EXTERNALS: OnceLock<Vec<External>> = OnceLock::new();
    EXTERNALS.get_or_init(|| {
        let root = crate::hooks::common::repo_root();
        let root = Path::new(&root);
        // ONE read. The bytes that get PARSED and the bytes that get HASHED
        // have to be the same bytes: this used to `read(root)` and then let
        // `trust::state` open the file a second time, so anything that changed
        // it in between — a `git checkout`, a watcher, a `make` target already
        // running — produced a trust decision about content that is not the
        // content about to be executed. `record_verified` closes this at trust
        // time and has a test named for it; the run path had the same gap.
        let Ok(bytes) = std::fs::read(root.join(MANIFEST)) else {
            return Vec::new();
        };
        // Non-UTF-8 yields no externals, as it always has: `parse` takes a
        // `&str`, and a manifest we cannot read as text is one we cannot act
        // on. Not lossy — that would invent a manifest nobody wrote.
        let Ok(text) = String::from_utf8(bytes.clone()) else {
            return Vec::new();
        };
        gate(parse(&text), crate::trust::state_of(root, &bytes))
    })
}

/// Apply a trust verdict to what the manifest declared.
///
/// Untrusted declarations are kept and DISABLED, not dropped. The names stay
/// visible in `amont list`, in the dashboard and in the "could not run"
/// roll-up, because a repository quietly declaring checks that never run is the
/// failure this project is arranged against — and the reader needs to know
/// there is a decision waiting for them.
///
/// Split out from `externals` because that function is a `OnceLock` keyed on
/// the process's own repository and so cannot be tested; this is the part with
/// the rule in it.
pub(crate) fn gate(declared: Vec<External>, state: crate::trust::State) -> Vec<External> {
    match crate::trust::why(state) {
        None => declared,
        Some(reason) => declared
            .into_iter()
            .map(|external| External {
                kind: Kind::Unusable {
                    why: reason.to_string(),
                },
                ..external
            })
            .collect(),
    }
}

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

    fn one(text: &str) -> Line {
        let mut v = parse_lines(text);
        assert_eq!(v.len(), 1, "expected one entry from {text:?}");
        v.pop().expect("one")
    }

    /// The error a line produced, as a VALUE. Tests used to match on the prose,
    /// which coupled them to wording and would have kept passing if the wording
    /// stayed while the meaning changed.
    fn why(l: &Line) -> ParseError {
        match l {
            Line::Broken { why, .. } => why.clone(),
            Line::Usable(d) => panic!("{} parsed when it should not have", d.name),
        }
    }

    fn usable(l: &Line) -> &Declared {
        match l {
            Line::Usable(d) => d,
            Line::Broken { name, why, .. } => panic!("{name} failed to parse: {why}"),
        }
    }

    #[test]
    fn parses_the_documented_example() {
        let v = parse_lines(
            "# stage       name        scope   severity  command\n\
             pre-commit    shellcheck  *.sh    block     scripts/lint-shell.sh\n\
             pre-push      smoke       *       warn      make smoke\n",
        );
        assert_eq!(v.len(), 2);

        let a = usable(&v[0]);
        assert_eq!(a.name, "shellcheck");
        assert_eq!(a.stage, Stage::PreCommit);
        assert_eq!(a.severity, Severity::Block);
        assert_eq!(a.program, "scripts/lint-shell.sh");
        assert!(a.args.is_empty());
        assert_eq!(a.exts, [".sh"]);

        let b = usable(&v[1]);
        assert_eq!(b.stage, Stage::PrePush);
        assert_eq!(b.severity, Severity::Warn);
        // A command with arguments is split, not handed to a shell.
        assert_eq!(b.program, "make");
        assert_eq!(b.args, ["smoke"]);
        assert!(b.exts.is_empty(), "`*` gates on nothing");
    }

    /// Blank lines and comments are not entries, and must not become broken
    /// ones — a file that is mostly documentation would otherwise report a
    /// dozen gaps.
    #[test]
    fn comments_and_blank_lines_produce_nothing() {
        assert!(parse_lines("\n  \n# just a comment\n\t# indented\n").is_empty());
    }

    /// The rule the module commits to: a line that cannot be understood still
    /// yields a check, so its absence is visible. Matched by VARIANT.
    #[test]
    fn a_malformed_line_becomes_a_visible_gap() {
        let cases: [(&str, ParseError); 4] = [
            (
                "pre-commit shellcheck *.sh block\n",
                ParseError::MissingFields,
            ),
            (
                "nonsense shellcheck *.sh block x\n",
                ParseError::BadStage("nonsense".into()),
            ),
            (
                "pre-commit shellcheck ?.sh block x\n",
                ParseError::BadScope("?.sh".into()),
            ),
            (
                "pre-commit shellcheck *.sh loud x\n",
                ParseError::BadSeverity("loud".into()),
            ),
        ];
        for (text, expected) in cases {
            assert_eq!(why(&one(text)), expected, "for {text:?}");
        }
    }

    /// The prose still has to locate the line, even though the tests no longer
    /// depend on its wording.
    #[test]
    fn a_gap_reports_where_it_is() {
        let l = one("pre-commit shellcheck *.sh loud x\n");
        let said = l.broken().expect("broken");
        assert!(said.contains("line 1"), "{said}");
        assert!(said.contains("severity"), "{said}");
    }

    /// `fix` on a pre-push line is refused where every other bad declaration is
    /// refused — on every commit, named and located — rather than as a runtime
    /// "contract violation" discovered later at push time by fewer people.
    #[test]
    fn fix_is_refused_on_a_pre_push_line() {
        assert_eq!(
            why(&one("pre-push  smoke  *  block  fix make smoke\n")),
            ParseError::FixOnPrePush
        );
        // …and accepted on pre-commit.
        let line = one("pre-commit  fmt  *  block  fix make format\n");
        let declared = usable(&line);
        assert_eq!(declared.fix, Fix::Rewrite);
        assert_eq!(declared.program, "make");
        assert_eq!(declared.args, ["format"]);
    }

    /// Every manifest written before `fix` existed must still parse the same.
    #[test]
    fn a_command_that_merely_starts_with_fix_is_not_a_marker() {
        let line = one("pre-commit  x  *  block  fixup-tool --check\n");
        let declared = usable(&line);
        assert_eq!(declared.fix, Fix::None);
        assert_eq!(declared.program, "fixup-tool");
    }

    /// A gap with no name cannot be reported, and a line this broken has none.
    #[test]
    fn a_nameless_line_is_named_after_its_position() {
        let l = one("pre-commit\n");
        assert_eq!(l.name(), "amont.conf:1");
        assert_eq!(why(&l), ParseError::MissingFields);
    }

    /// An external must not be able to take a built-in's id — it would either
    /// shadow `pre-push-branch-protect` or silently lose to it, and neither is
    /// something a repository should be able to do by editing a text file.
    ///
    /// Judged on the id, so the same declaration is refused on one trigger and
    /// accepted on the other. That is not a loophole: `pre-push-clippy` is a
    /// different check from `pre-commit-clippy`, and nothing is shadowed.
    #[test]
    fn a_built_in_id_is_refused() {
        assert_eq!(
            why(&one("pre-commit clippy *.rs block x\n")),
            ParseError::NameTaken("clippy".into())
        );
        assert!(matches!(
            one("pre-push clippy *.rs block x\n"),
            Line::Usable(_)
        ));
        // And a pre-push built-in is protected on pre-push, not on pre-commit,
        // for the same reason.
        assert_eq!(
            why(&one("pre-push branch-protect * block x\n")),
            ParseError::NameTaken("branch-protect".into())
        );
        assert!(matches!(
            one("pre-commit branch-protect * block x\n"),
            Line::Usable(_)
        ));
    }

    /// The stage column says which trigger a line is for. Saying it again in
    /// the name is the one way to make an id ambiguous: `pre-commit-clippy` as
    /// a NAME is a check whose short name is the built-in's full id, so one
    /// `hook.skip` would silence both.
    #[test]
    fn a_name_that_says_its_own_trigger_is_refused() {
        for name in ["pre-commit", "pre-push", "pre-commit-clippy", "pre-push-x"] {
            assert_eq!(
                why(&one(&format!("pre-commit {name} * block x\n"))),
                ParseError::TriggerInName(name.into()),
                "{name}"
            );
        }
        // A name that merely begins with the same letters is fine — the trigger
        // has to be followed by the separator to count.
        assert!(matches!(
            one("pre-commit pre-commitish * block x\n"),
            Line::Usable(_)
        ));
    }

    /// Two USABLE lines with one ID: the second cannot be addressed by
    /// `hook.skip` or by a severity override, so it is refused.
    #[test]
    fn a_duplicate_id_is_refused() {
        let v = parse_lines(
            "pre-commit smoke * block a\n\
             pre-commit smoke * block b\n",
        );
        assert_eq!(v.len(), 2);
        assert_eq!(usable(&v[0]).id(), "pre-commit-smoke");
        assert_eq!(why(&v[1]), ParseError::Duplicate("smoke".into()));
    }

    /// The same name on both triggers is TWO checks, and this used to refuse
    /// the second. Somebody wanting a `show-unicorn` on commit and on push had
    /// no way to write it, and no way to skip or downgrade one without the
    /// other — the bare name could not tell them apart.
    #[test]
    fn the_same_name_on_two_triggers_is_allowed() {
        let v = parse_lines(
            "pre-commit show-unicorn * block a\n\
             pre-push   show-unicorn * block b\n",
        );
        assert_eq!(v.len(), 2);
        assert_eq!(usable(&v[0]).id(), "pre-commit-show-unicorn");
        assert_eq!(usable(&v[1]).id(), "pre-push-show-unicorn");

        // And each is separately addressable, while the short name takes both —
        // which is the whole vocabulary, applied to declared checks.
        for (id, only) in [
            ("pre-commit-show-unicorn", "pre-push-show-unicorn"),
            ("pre-push-show-unicorn", "pre-commit-show-unicorn"),
        ] {
            assert!(crate::skip_suppresses(id, id));
            assert!(!crate::skip_suppresses(only, id));
        }
        assert!(crate::skip_suppresses(
            "pre-commit-show-unicorn",
            "show-unicorn"
        ));
        assert!(crate::skip_suppresses(
            "pre-push-show-unicorn",
            "show-unicorn"
        ));
        assert!(crate::skip_suppresses(
            "pre-commit-show-unicorn",
            "pre-commit"
        ));
        assert!(!crate::skip_suppresses(
            "pre-push-show-unicorn",
            "pre-commit"
        ));
    }

    /// A line that cannot run does not RESERVE its name.
    ///
    /// It used to: broken and usable entries shared one list, so a valid
    /// declaration was rejected as "declared twice" for colliding with a line
    /// that could never execute — pointing the reader at the wrong line, and
    /// forcing them to fix the first before the second would work at all.
    #[test]
    fn a_broken_line_does_not_reserve_its_name() {
        let v = parse_lines(
            "pre-commit smoke * LOUD   make a\n\
             pre-commit smoke * block  make b\n",
        );
        assert_eq!(v.len(), 2);
        assert_eq!(why(&v[0]), ParseError::BadSeverity("LOUD".into()));
        let good = usable(&v[1]);
        assert_eq!(good.name, "smoke");
        assert_eq!(good.program, "make");
    }

    /// Alignment is cosmetic. A file someone has lined up with tabs, or not
    /// lined up at all, must parse identically.
    #[test]
    fn field_alignment_does_not_matter() {
        let spaced = one("pre-commit      shellcheck    *.sh      block     make lint\n");
        let tabbed = one("pre-commit\tshellcheck\t*.sh\tblock\tmake lint\n");
        assert_eq!(usable(&spaced), usable(&tabbed));
        assert_eq!(usable(&spaced).args, ["lint"]);
    }

    #[test]
    fn several_extensions_can_gate_one_check() {
        let e = External::from(one("pre-commit shell *.sh,*.bash block make lint\n"));
        assert!(e.scope().matches(&["a.bash".into()]));
        assert!(e.scope().matches(&["a.sh".into()]));
        assert!(!e.scope().matches(&["a.zsh".into()]));
    }

    /// `tokenise` states its arity in the type, so "four tokens then a command"
    /// is checked rather than remembered.
    #[test]
    fn tokenise_wants_four_fields_and_a_command() {
        assert!(tokenise("a b c").is_none(), "too few fields");
        assert!(tokenise("a b c d").is_none(), "four fields, no command");
        // Trailing whitespace reaches the four fields but still leaves nothing
        // to run — the case the `?` on the last field cannot catch.
        assert!(
            tokenise("a b c d   ").is_none(),
            "command is all whitespace"
        );
        assert!(tokenise("a b c d\t").is_none(), "command is a tab");
        let (fields, cmd) = tokenise("a  b\tc   d   run it").expect("four and a command");
        assert_eq!(fields, ["a", "b", "c", "d"]);
        assert_eq!(cmd, "run it");
    }

    /// An unusable line carries no command at all — the type has nowhere to put
    /// one, which is the point of the split.
    #[test]
    fn an_unusable_external_holds_no_command() {
        let e = External::from(one("pre-commit shellcheck *.sh loud echo hi\n"));
        assert!(matches!(e.kind, Kind::Unusable { .. }));
        // And it can never block, whatever severity anyone configures.
        assert_eq!(e.severity(), Severity::Warn);
    }

    /// A missing manifest is the normal case and must not be an error.
    #[test]
    fn a_repository_with_no_manifest_declares_nothing() {
        assert!(read(Path::new("/nonexistent-c8f2")).is_empty());
        assert!(read_lines(Path::new("/nonexistent-c8f2")).is_empty());
    }

    /// `Line` exists to spare the dashboard a leak, not to become a second
    /// opinion about what a manifest says.
    #[test]
    fn the_leaking_and_non_leaking_parsers_agree() {
        let text = "pre-commit  shellcheck  *.sh,*.bash  block  make lint\n\
                    pre-push    smoke       *            warn   make smoke\n\
                    pre-commit  broken      ?            block  x\n";
        let lines = parse_lines(text);
        let externals = parse(text);
        assert_eq!(lines.len(), externals.len());
        for (l, e) in lines.iter().zip(&externals) {
            assert_eq!(l.id(), e.name(), "the id is what a check answers to");
            assert_eq!(
                l.name(),
                e.short_name,
                "and the short name is what it is called"
            );
            assert_eq!(l.stage(), e.stage());
            assert_eq!(
                l.broken().is_some(),
                matches!(e.kind, Kind::Unusable { .. })
            );
            if let Line::Usable(d) = l {
                assert_eq!(d.severity, e.severity());
                // The scope the dashboard would DESCRIBE is the scope the
                // dispatcher would ENFORCE.
                assert_eq!(d.exts, e.scope().files);
            }
        }
    }
}