Skip to main content

spec_driven_docs/
gates.rs

1//! The delivered gates: every check an instance wires as a pre-commit hook.
2//!
3//! This module owns the registry — identity, display name, hook wiring,
4//! citable rules, and implementation for each gate — so a gate cannot exist
5//! unwired: the exhaustive match over [`GateId`] is the declaration. Gate
6//! implementations live one per file below; rendering the registry into
7//! pre-commit YAML and running one gate from the command line live in
8//! `services` and `commands`.
9
10pub mod paths;
11
12pub mod adr_filename_shape;
13pub mod adr_word_cap;
14pub mod agents_digest_size;
15pub mod chapter_size_cap;
16pub mod comparison_dated_tables;
17pub mod comparison_escaped_pipes;
18pub mod comparison_legend;
19pub mod comparison_one_reference_per_cell;
20pub mod comparison_verdict_word;
21pub mod gate_message_cites_a_rule;
22pub mod instance_manifest;
23pub mod ki_bugzilla_report_width;
24pub mod ki_filename_shape;
25pub mod ki_mechanism_walkthrough;
26pub mod ki_report_body;
27pub mod ki_retire_when;
28pub mod no_self_narration;
29pub mod prose_stays_unwrapped;
30pub mod spec_requirement_parts;
31pub mod spec_rule_id_unique;
32pub mod spec_size_cap;
33pub mod spec_verify_hooks_exist;
34pub mod suppression_names_its_case;
35
36use std::fmt;
37
38use camino::{Utf8Path, Utf8PathBuf};
39use thiserror::Error;
40
41use crate::domain::finding::Finding;
42use crate::domain::gate_id::GateId;
43use crate::domain::rule_id::RuleId;
44
45/// Where a gate runs: the repository root pre-commit invoked it from.
46#[derive(Debug, Clone)]
47pub struct GateCtx {
48    /// The repository root; every path a gate reads or reports is relative to it.
49    pub repo_root: Utf8PathBuf,
50}
51
52impl GateCtx {
53    /// A context rooted at the given repository.
54    #[must_use]
55    pub fn new(repo_root: impl Into<Utf8PathBuf>) -> Self {
56        Self {
57            repo_root: repo_root.into(),
58        }
59    }
60
61    /// Resolve a repository-relative path for reading.
62    #[must_use]
63    pub fn path(&self, relative: impl AsRef<Utf8Path>) -> Utf8PathBuf {
64        self.repo_root.join(relative)
65    }
66}
67
68/// One line a failing gate prints.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum Violation {
71    /// A rule violation, rendered as its `FAIL <domain>:<rule> ...` line.
72    Finding(Finding),
73    /// The repository does not have the shape the gate needs; rendered as
74    /// `FAIL <reason>` with no rule to cite.
75    Layout(String),
76    /// A continuation line under a preceding violation, rendered verbatim.
77    Note(String),
78}
79
80impl fmt::Display for Violation {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        match self {
83            Self::Finding(finding) => finding.fmt(f),
84            Self::Layout(reason) => write!(f, "FAIL {reason}"),
85            Self::Note(text) => f.write_str(text),
86        }
87    }
88}
89
90/// A gate that could not run at all — distinct from one that found violations.
91#[derive(Debug, Error)]
92pub enum GateError {
93    /// A file the gate needed could not be read.
94    #[error("{path}: {source}")]
95    Io {
96        /// The path that failed.
97        path: Utf8PathBuf,
98        /// The underlying failure.
99        source: std::io::Error,
100    },
101}
102
103impl GateError {
104    pub(crate) fn io(path: impl Into<Utf8PathBuf>, source: std::io::Error) -> Self {
105        Self::Io {
106            path: path.into(),
107            source,
108        }
109    }
110}
111
112impl From<GateError> for crate::error::AppError {
113    fn from(error: GateError) -> Self {
114        match error {
115            GateError::Io { path, source } => {
116                let kind = source.kind();
117                Self::Io(std::io::Error::new(kind, format!("{path}: {source}")))
118            }
119        }
120    }
121}
122
123/// What every gate returns: the violations it found, or why it could not run.
124pub type GateResult = Result<Vec<Violation>, GateError>;
125
126/// The implementation shape shared by every gate.
127pub type GateFn = fn(&GateCtx, &[String]) -> GateResult;
128
129/// One registry row: everything the deliveries need to know about a gate.
130#[derive(Debug)]
131pub struct GateSpec {
132    /// The gate's identity.
133    pub id: GateId,
134    /// The display name pre-commit shows.
135    pub name: &'static str,
136    /// The default `files:` pattern, with `{docs_root}` left templated.
137    pub files: Option<&'static str>,
138    /// The `types:` scope, when the gate takes one.
139    pub types: Option<&'static str>,
140    /// The default `exclude:` pattern, with `{docs_root}` left templated.
141    pub exclude: Option<&'static str>,
142    /// Whether the gate runs regardless of which files changed.
143    pub always_run: bool,
144    /// Every rule the gate can cite in a finding.
145    pub cites: &'static [RuleId],
146    /// The implementation.
147    pub run: GateFn,
148}
149
150/// Look up one gate's registry row.
151#[must_use]
152pub fn spec(id: GateId) -> &'static GateSpec {
153    let index = GateId::ALL.iter().position(|g| *g == id).unwrap_or(0);
154    &GATES[index]
155}
156
157/// The delivered gate set, in [`GateId::ALL`] order.
158pub static GATES: &[GateSpec] = &[
159    GateSpec {
160        id: GateId::AdrFilenameShape,
161        name: "decision record filename shape",
162        files: Some(r"^{docs_root}/decisions/.*\.md$"),
163        types: None,
164        exclude: None,
165        always_run: false,
166        cites: adr_filename_shape::CITES,
167        run: adr_filename_shape::run,
168    },
169    GateSpec {
170        id: GateId::AdrWordCap,
171        name: "decision record word cap",
172        files: None,
173        types: None,
174        exclude: None,
175        always_run: true,
176        cites: adr_word_cap::CITES,
177        run: adr_word_cap::run,
178    },
179    GateSpec {
180        id: GateId::AgentsDigestSize,
181        name: "agent digest size",
182        files: None,
183        types: None,
184        exclude: None,
185        always_run: true,
186        cites: agents_digest_size::CITES,
187        run: agents_digest_size::run,
188    },
189    GateSpec {
190        id: GateId::ChapterSizeCap,
191        name: "chapter and catalog size",
192        files: None,
193        types: None,
194        exclude: None,
195        always_run: true,
196        cites: chapter_size_cap::CITES,
197        run: chapter_size_cap::run,
198    },
199    GateSpec {
200        id: GateId::ComparisonDatedTables,
201        name: "comparison tables are dated",
202        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
203        types: None,
204        exclude: None,
205        always_run: false,
206        cites: comparison_dated_tables::CITES,
207        run: comparison_dated_tables::run,
208    },
209    GateSpec {
210        id: GateId::ComparisonEscapedPipes,
211        name: "comparison table pipes are escaped",
212        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
213        types: None,
214        exclude: None,
215        always_run: false,
216        cites: comparison_escaped_pipes::CITES,
217        run: comparison_escaped_pipes::run,
218    },
219    GateSpec {
220        id: GateId::ComparisonLegend,
221        name: "comparison legend",
222        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
223        types: None,
224        exclude: None,
225        always_run: false,
226        cites: comparison_legend::CITES,
227        run: comparison_legend::run,
228    },
229    GateSpec {
230        id: GateId::ComparisonOneReferencePerCell,
231        name: "one reference per comparison cell",
232        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
233        types: None,
234        exclude: None,
235        always_run: false,
236        cites: comparison_one_reference_per_cell::CITES,
237        run: comparison_one_reference_per_cell::run,
238    },
239    GateSpec {
240        id: GateId::ComparisonVerdictWord,
241        name: "comparison verdict word",
242        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
243        types: None,
244        exclude: None,
245        always_run: false,
246        cites: comparison_verdict_word::CITES,
247        run: comparison_verdict_word::run,
248    },
249    GateSpec {
250        id: GateId::GateMessageCitesARule,
251        name: "gate messages cite a rule",
252        files: None,
253        types: None,
254        exclude: None,
255        always_run: true,
256        cites: gate_message_cites_a_rule::CITES,
257        run: gate_message_cites_a_rule::run,
258    },
259    GateSpec {
260        id: GateId::InstanceManifest,
261        name: "instance manifest",
262        files: None,
263        types: None,
264        exclude: None,
265        always_run: true,
266        cites: instance_manifest::CITES,
267        run: instance_manifest::run,
268    },
269    GateSpec {
270        id: GateId::KiBugzillaReportWidth,
271        name: "Bugzilla report width",
272        files: None,
273        types: None,
274        exclude: None,
275        always_run: true,
276        cites: ki_bugzilla_report_width::CITES,
277        run: ki_bugzilla_report_width::run,
278    },
279    GateSpec {
280        id: GateId::KiFilenameShape,
281        name: "known issue filename shape",
282        files: Some(r"^{docs_root}/reference/known-issues/.*\.md$"),
283        types: None,
284        exclude: None,
285        always_run: false,
286        cites: ki_filename_shape::CITES,
287        run: ki_filename_shape::run,
288    },
289    GateSpec {
290        id: GateId::KiMechanismWalkthrough,
291        name: "known issue mechanism walkthrough",
292        files: None,
293        types: None,
294        exclude: None,
295        always_run: true,
296        cites: ki_mechanism_walkthrough::CITES,
297        run: ki_mechanism_walkthrough::run,
298    },
299    GateSpec {
300        id: GateId::KiReportBody,
301        name: "known issue report body",
302        files: None,
303        types: None,
304        exclude: None,
305        always_run: true,
306        cites: ki_report_body::CITES,
307        run: ki_report_body::run,
308    },
309    GateSpec {
310        id: GateId::KiRetireWhen,
311        name: "known issue retirement condition",
312        files: None,
313        types: None,
314        exclude: None,
315        always_run: true,
316        cites: ki_retire_when::CITES,
317        run: ki_retire_when::run,
318    },
319    GateSpec {
320        id: GateId::NoSelfNarration,
321        name: "documents state the present",
322        files: None,
323        types: Some("markdown"),
324        exclude: Some("^{docs_root}/decisions/"),
325        always_run: false,
326        cites: no_self_narration::CITES,
327        run: no_self_narration::run,
328    },
329    GateSpec {
330        id: GateId::ProseStaysUnwrapped,
331        name: "prose lines stay unwrapped",
332        files: None,
333        types: Some("markdown"),
334        exclude: Some(r"(?:^|/)CHANGELOG\.md$"),
335        always_run: false,
336        cites: prose_stays_unwrapped::CITES,
337        run: prose_stays_unwrapped::run,
338    },
339    GateSpec {
340        id: GateId::SpecRequirementParts,
341        name: "spec requirement parts",
342        files: Some(r"^{docs_root}/specs/SPEC-.*\.md$"),
343        types: None,
344        exclude: None,
345        always_run: false,
346        cites: spec_requirement_parts::CITES,
347        run: spec_requirement_parts::run,
348    },
349    GateSpec {
350        id: GateId::SpecRuleIdUnique,
351        name: "spec rule IDs are unique",
352        files: None,
353        types: None,
354        exclude: None,
355        always_run: true,
356        cites: spec_rule_id_unique::CITES,
357        run: spec_rule_id_unique::run,
358    },
359    GateSpec {
360        id: GateId::SpecSizeCap,
361        name: "spec size cap",
362        files: None,
363        types: None,
364        exclude: None,
365        always_run: true,
366        cites: spec_size_cap::CITES,
367        run: spec_size_cap::run,
368    },
369    GateSpec {
370        id: GateId::SpecVerifyHooksExist,
371        name: "spec hook references exist",
372        files: None,
373        types: None,
374        exclude: None,
375        always_run: true,
376        cites: spec_verify_hooks_exist::CITES,
377        run: spec_verify_hooks_exist::run,
378    },
379    GateSpec {
380        id: GateId::SuppressionNamesItsCase,
381        name: "suppressions name a known issue",
382        files: None,
383        types: None,
384        exclude: None,
385        always_run: true,
386        cites: suppression_names_its_case::CITES,
387        run: suppression_names_its_case::run,
388    },
389];
390
391/// The directories every repository walk prunes: vendored or generated trees
392/// a consumer cannot be asked to author.
393pub const PRUNED_DIRS: &[&str] = &[".git", "node_modules", ".venv", "vendor", "target", "dist"];
394
395/// Count the newline-terminated lines of a text, as `wc -l` does.
396#[must_use]
397pub fn line_count(text: &str) -> usize {
398    text.matches('\n').count()
399}
400
401/// Read a repository-relative text file for a gate.
402///
403/// # Errors
404///
405/// [`GateError::Io`] naming the path when the file cannot be read.
406pub fn read_text(ctx: &GateCtx, relative: impl AsRef<Utf8Path>) -> Result<String, GateError> {
407    let relative = relative.as_ref();
408    std::fs::read_to_string(ctx.path(relative)).map_err(|source| GateError::io(relative, source))
409}
410
411/// Walk the repository, pruning [`PRUNED_DIRS`], and yield every file as a
412/// `./`-prefixed repository-relative path in sorted order.
413#[must_use]
414pub fn walk_files(ctx: &GateCtx) -> Vec<Utf8PathBuf> {
415    let root = ctx.repo_root.as_std_path();
416    let mut files: Vec<Utf8PathBuf> = walkdir::WalkDir::new(root)
417        .into_iter()
418        .filter_entry(|entry| {
419            !(entry.file_type().is_dir()
420                && entry.depth() > 0
421                && entry
422                    .file_name()
423                    .to_str()
424                    .is_some_and(|name| PRUNED_DIRS.contains(&name)))
425        })
426        .filter_map(Result::ok)
427        .filter(|entry| entry.file_type().is_file())
428        .filter_map(|entry| {
429            let relative = entry.path().strip_prefix(root).ok()?.to_str()?;
430            Some(Utf8PathBuf::from(format!("./{relative}")))
431        })
432        .collect();
433    files.sort();
434    files
435}
436
437#[cfg(test)]
438pub(crate) mod tests_support {
439    /// A repository holding one known-issue record with the given
440    /// `retire_when:` line and a conforming body.
441    pub fn ki_fixture(retire_line: &str) -> tempfile::TempDir {
442        ki_record(&format!(
443            "---\nupstream: https://example.invalid/issues\n{retire_line}---\n# Vendor issue\n## How it works\nRun.\n"
444        ))
445    }
446
447    /// A repository holding one known-issue record with a conforming
448    /// frontmatter and the given body.
449    pub fn ki_fixture_body(body: &str) -> tempfile::TempDir {
450        ki_record(&format!(
451            "---\nupstream: https://example.invalid/issues\nretire_when: release >= 2.0\n---\n{body}"
452        ))
453    }
454
455    /// A repository holding one known-issue record with the given
456    /// `upstream:` value and body.
457    pub fn ki_fixture_upstream(upstream: &str, body: &str) -> tempfile::TempDir {
458        ki_record(&format!(
459            "---\nupstream: {upstream}\nretire_when: release >= 2.0\n---\n{body}"
460        ))
461    }
462
463    fn ki_record(text: &str) -> tempfile::TempDir {
464        let dir = tempfile::tempdir().unwrap();
465        let records = dir.path().join("_docs/reference/known-issues");
466        std::fs::create_dir_all(&records).unwrap();
467        std::fs::write(records.join("KI-vendor.md"), text).unwrap();
468        dir
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475
476    #[test]
477    fn registry_covers_every_gate_exactly_once_in_order() {
478        assert_eq!(GATES.len(), GateId::ALL.len());
479        for (row, id) in GATES.iter().zip(GateId::ALL) {
480            assert_eq!(row.id, *id);
481            assert_eq!(spec(*id).id, *id);
482        }
483    }
484
485    #[test]
486    fn every_gate_declares_the_rules_it_cites() {
487        for row in GATES {
488            assert!(!row.cites.is_empty(), "{} cites nothing", row.id);
489        }
490    }
491
492    #[test]
493    fn cited_rules_resolve_in_the_embedded_specs() {
494        let defined = crate::embedded::spec_rule_ids();
495        for row in GATES {
496            for rule in row.cites {
497                assert!(
498                    defined.contains(rule.as_str()),
499                    "{}: {rule} is undefined",
500                    row.id
501                );
502            }
503        }
504    }
505}