greengate_runtime/policy.rs
1//! Committed repo policy — the team's decisions, shipped with the repository.
2//!
3//! `amont.conf` could always ADD checks; it could never say anything about
4//! the built-ins, so "clippy is warn-only here" meant every teammate running
5//! the same `git config` incantation, unverified. `severity` and `skip`
6//! lines close that: committed, reviewed like code, and trust-gated exactly
7//! like declared checks — a repository you cloned to read cannot weaken your
8//! safety net until you consent.
9//!
10//! Precedence is a specificity ladder decided per KEY: built-in default <
11//! system config < global config < POLICY < local config < worktree <
12//! command-line. Between different keys naming the same check, specificity
13//! (full id > short name > trigger) decides, whatever the source — a local
14//! `greengate.severity.pre-commit warn` must never be unbeatable by policy, and
15//! a policy full-id beats a local trigger. Skips are a UNION of all sources:
16//! there is no unskip mechanism anywhere, so ordering has nothing to decide.
17//!
18//! There is no store. A `Policy` is owned by the [`crate::config::Settings`]
19//! each entrypoint builds after `manifest::load`, and borrowed from there —
20//! the shape `Ctx` already used for `manifest` and `push`.
21//!
22//! It WAS a process-global `OnceLock`, which was correct for the hook path
23//! (one process, one repository) and wrong as a contract: a multi-repo walker
24//! had to KNOW not to seed it, `amont-fleet` carried that knowledge as a
25//! comment, and no test could assert the rule because asserting it would have
26//! meant seeding it. Now the rule needs no remembering — a scanner cannot
27//! corrupt a store that does not exist. Every RULE here stays a pure function
28//! over `&Policy`.
29
30use crate::check::Severity;
31use crate::manifest::{Line, PolicyLine};
32
33/// What a trusted manifest's policy lines add up to.
34#[derive(Debug, Default, Clone, PartialEq, Eq)]
35pub struct Policy {
36 /// `(target, severity)` in file order — later lines overwrite earlier
37 /// ones at fold time, matching git config's own precedence rule.
38 pub severities: Vec<(String, Severity)>,
39 /// Skip targets, resolved by the same three-way naming `hook.skip` uses.
40 pub skips: Vec<String>,
41 /// Committed defaults for allowlisted config keys, by FULL git key
42 /// (`greengate.timeout`). Values are raw strings — GIT parses them at read
43 /// time (`config::typed_literal`), so no second config dialect exists.
44 pub settings: std::collections::BTreeMap<String, String>,
45}
46
47impl Policy {
48 pub fn is_empty(&self) -> bool {
49 self.severities.is_empty() && self.skips.is_empty() && self.settings.is_empty()
50 }
51
52 /// Collect the policy from parsed lines, and say which targets name
53 /// nothing — validated here, over the WHOLE file, because `parse_line`
54 /// sees only earlier lines and a `severity smoke warn` written above its
55 /// own `pre-commit smoke …` declaration would be wrongly refused.
56 ///
57 /// The naming universe is built-ins plus the file's CHECK lines only
58 /// (`Line::is_check`) — a `tool ruff …` pin must not make
59 /// `severity ruff warn` look valid, and `Broken` lines count because a
60 /// broken line still produces a check id that `hook.skip` can reach.
61 ///
62 /// An unmatched target is a NOTE, not a `Line::Broken` — a broken line
63 /// manufactures a check named after itself, and a phantom
64 /// `pre-commit-clipy` helps nobody.
65 pub fn from_lines(lines: &[Line]) -> (Policy, Vec<String>) {
66 Policy::from_lines_of(lines, crate::manifest::MANIFEST)
67 }
68
69 /// [`Policy::from_lines`] for the file named `manifest`, which the notes
70 /// name.
71 pub fn from_lines_of(lines: &[Line], manifest: &str) -> (Policy, Vec<String>) {
72 let mut policy = Policy::default();
73 let mut notes = Vec::new();
74 let names_something = |target: &str| {
75 crate::registry::CHECKS
76 .iter()
77 .any(|c| crate::names_check(c.name, target).is_some())
78 || lines
79 .iter()
80 .filter(|l| l.is_check())
81 .any(|l| crate::names_check(&l.id(), target).is_some())
82 };
83 for line in lines {
84 let Line::Policy { what, lineno } = line else {
85 continue;
86 };
87 let target = match what {
88 PolicyLine::Severity { target, .. } | PolicyLine::Skip { target } => target,
89 PolicyLine::Set { key, value } => {
90 // Allowlisted at parse; later lines overwrite earlier
91 // ones, the same rule config itself applies.
92 policy.settings.insert(key.clone(), value.clone());
93 continue;
94 }
95 };
96 if !names_something(target) {
97 let kind = match what {
98 PolicyLine::Severity { .. } => "severity",
99 PolicyLine::Skip { .. } => "skip",
100 // Set lines took the `continue` above; unreachable here.
101 PolicyLine::Set { .. } => unreachable!("set lines have no target"),
102 };
103 notes.push(format!(
104 "{manifest}:{lineno}: {kind} {target:?} names no check here"
105 ));
106 continue;
107 }
108 match what {
109 PolicyLine::Severity { target, severity } => {
110 policy.severities.push((target.clone(), *severity));
111 }
112 PolicyLine::Skip { target } => policy.skips.push(target.clone()),
113 PolicyLine::Set { .. } => unreachable!("set lines have no target"),
114 }
115 }
116 (policy, notes)
117 }
118}
119
120/// The union `hook.skip` resolution sees: machine skips plus policy skips.
121/// A union and not a ladder — nothing anywhere can UN-skip, so there is no
122/// conflict for ordering to settle.
123pub fn union_skips(config_skips: Vec<String>, policy: &Policy) -> Vec<String> {
124 let mut all = config_skips;
125 for s in &policy.skips {
126 if !all.contains(s) {
127 all.push(s.clone());
128 }
129 }
130 all
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136 use crate::manifest::parse_lines;
137
138 #[test]
139 fn collects_severities_and_skips_in_file_order() {
140 let lines = parse_lines(
141 "severity clippy warn\nskip yamllint\nseverity pre-push-cargo-test block\n",
142 );
143 let (p, notes) = Policy::from_lines(&lines);
144 assert!(notes.is_empty(), "{notes:?}");
145 assert_eq!(
146 p.severities,
147 vec![
148 ("clippy".to_string(), Severity::Warn),
149 ("pre-push-cargo-test".to_string(), Severity::Block),
150 ]
151 );
152 assert_eq!(p.skips, vec!["yamllint".to_string()]);
153 }
154
155 /// A target can be a declared check — including one written BELOW the
156 /// policy line, which is why validation is a whole-file pass.
157 #[test]
158 fn a_declared_check_below_the_policy_line_still_validates() {
159 let lines =
160 parse_lines("severity smoke warn\npre-commit smoke * block ./smoke.sh\n");
161 let (p, notes) = Policy::from_lines(&lines);
162 assert!(notes.is_empty(), "{notes:?}");
163 assert_eq!(p.severities.len(), 1);
164 }
165
166 /// A tool pin must not lend its name to the validation universe.
167 #[test]
168 fn a_tool_pin_does_not_validate_a_policy_target() {
169 let lines = parse_lines("tool ruffian 0.4\nseverity ruffian warn\n");
170 let (p, notes) = Policy::from_lines(&lines);
171 assert!(p.severities.is_empty());
172 assert_eq!(notes.len(), 1, "{notes:?}");
173 assert!(notes[0].contains("names no check here"), "{notes:?}");
174 assert!(notes[0].contains("greengate.conf:2"), "{notes:?}");
175 }
176
177 /// A typo is a note with a position, never a phantom check.
178 #[test]
179 fn an_unmatched_target_is_a_note_not_a_check() {
180 let lines = parse_lines("severity clipy warn\n");
181 let (p, notes) = Policy::from_lines(&lines);
182 assert!(p.is_empty());
183 assert_eq!(
184 notes,
185 vec!["greengate.conf:1: severity \"clipy\" names no check here"]
186 );
187 }
188
189 /// Triggers and short names resolve exactly as `hook.skip` resolves them.
190 #[test]
191 fn triggers_and_short_names_are_valid_targets() {
192 let lines = parse_lines("skip pre-commit\nseverity ban-terms warn\n");
193 let (p, notes) = Policy::from_lines(&lines);
194 assert!(notes.is_empty(), "{notes:?}");
195 assert_eq!(p.skips, vec!["pre-commit".to_string()]);
196 assert_eq!(p.severities.len(), 1);
197 }
198
199 #[test]
200 fn union_adds_policy_skips_without_duplicating() {
201 let p = Policy {
202 severities: Vec::new(),
203 skips: vec!["yamllint".into(), "clippy".into()],
204 settings: std::collections::BTreeMap::new(),
205 };
206 let got = union_skips(vec!["clippy".into()], &p);
207 assert_eq!(got, vec!["clippy".to_string(), "yamllint".to_string()]);
208 }
209}