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_cites_a_live_rule;
13pub mod adr_filename_shape;
14pub mod adr_word_cap;
15pub mod agents_digest_size;
16pub mod budget;
17pub mod chapter_size_cap;
18pub mod comparison_dated_tables;
19pub mod comparison_escaped_pipes;
20pub mod comparison_legend;
21pub mod comparison_one_reference_per_cell;
22pub mod comparison_verdict_word;
23pub mod gate_message_cites_a_rule;
24pub mod instance_manifest;
25pub mod ki_bugzilla_report_width;
26pub mod ki_checked_date;
27pub mod ki_filename_shape;
28pub mod ki_filing;
29pub mod ki_mechanism_walkthrough;
30pub mod ki_record;
31pub mod ki_report_body;
32pub mod ki_retire_when;
33pub mod ki_state;
34pub mod markdown_prose;
35pub mod no_personal_path;
36pub mod no_self_narration;
37pub mod prose_stays_unwrapped;
38pub mod spec_requirement_parts;
39pub mod spec_rule_id_unique;
40pub mod spec_size_cap;
41pub mod spec_trailing_section;
42pub mod spec_verify_hooks_exist;
43pub mod suppression_names_its_case;
44pub mod tracking_registry;
45
46use std::fmt;
47
48use camino::{Utf8Path, Utf8PathBuf};
49use thiserror::Error;
50
51use crate::domain::finding::Finding;
52use crate::domain::gate_id::GateId;
53use crate::domain::path_filter::PathFilter;
54use crate::domain::rule_id::RuleId;
55
56/// Where a gate runs: the repository root pre-commit invoked it from, and
57/// the subject filter that bounds what it judges there.
58///
59/// # Subject paths and support paths
60///
61/// A *subject* path is one whose content the gate judges and which can
62/// appear in a finding. A *support* path is one the gate reads to know what
63/// to judge: the canon manifest, the known-issue records, the docs-root
64/// resolution, the tracking registry. The filter governs subject paths.
65/// [`Self::path`] and [`read_text`] stay open, because a filter that reached
66/// support paths would let a project disable a gate by excluding the file
67/// that configures it.
68///
69/// # Every route a subject path takes
70///
71/// There are two, and each passes through [`Self::subjects`], so a gate
72/// author cannot reach an unfiltered subject list:
73///
74/// 1. The `&[String]` a gate is handed, filtered in `commands::gate`.
75/// 2. [`walk_files`], which filters before it returns.
76///
77/// `canon::every_subject_producer_is_filter_aware` holds that list.
78#[derive(Debug)]
79pub struct GateCtx {
80    /// The repository root; every path a gate reads or reports is relative to it.
81    pub repo_root: Utf8PathBuf,
82    /// What this gate may judge. Private, so the only way to a subject list
83    /// is [`Self::subjects`].
84    filter: PathFilter,
85    /// The documentation root a caller already knows, which discovery then
86    /// does not guess.
87    docs_root: Option<Utf8PathBuf>,
88}
89
90impl GateCtx {
91    /// A context rooted at the given repository, judging everything.
92    ///
93    /// This is the shape every test and every internal caller wants. The
94    /// command path uses [`Self::with_filter`].
95    #[must_use]
96    pub fn new(repo_root: impl Into<Utf8PathBuf>) -> Self {
97        Self {
98            repo_root: repo_root.into(),
99            filter: PathFilter::permissive(),
100            docs_root: None,
101        }
102    }
103
104    /// A context whose gate judges only what the filter admits.
105    #[must_use]
106    pub fn with_filter(repo_root: impl Into<Utf8PathBuf>, filter: PathFilter) -> Self {
107        Self {
108            repo_root: repo_root.into(),
109            filter,
110            docs_root: None,
111        }
112    }
113
114    /// The same context with its documentation root named, as a landing
115    /// that has not written its record yet knows it.
116    #[must_use]
117    pub fn with_docs_root(mut self, docs_root: impl Into<Utf8PathBuf>) -> Self {
118        self.docs_root = Some(docs_root.into());
119        self
120    }
121
122    /// The documentation root the caller named, where it named one.
123    #[must_use]
124    pub fn named_docs_root(&self) -> Option<&Utf8Path> {
125        self.docs_root.as_deref()
126    }
127
128    /// Resolve a repository-relative path for reading.
129    ///
130    /// Deliberately unfiltered: a gate reads its support files through here.
131    #[must_use]
132    pub fn path(&self, relative: impl AsRef<Utf8Path>) -> Utf8PathBuf {
133        self.repo_root.join(relative)
134    }
135
136    /// The form a pattern speaks, for one candidate.
137    ///
138    /// See [`crate::domain::path_filter::project`], which both this and
139    /// `--explain` use, so the two never disagree about which file a path
140    /// names.
141    fn relative(&self, path: &Utf8Path) -> Utf8PathBuf {
142        crate::domain::path_filter::project(path, &self.repo_root)
143    }
144
145    /// The subset of `candidates` this gate judges.
146    ///
147    /// Every subject path pre-commit or an operator hands a gate comes
148    /// through here, and the registry whitelist binds.
149    #[must_use]
150    pub fn subjects<P: AsRef<Utf8Path>>(&self, candidates: impl IntoIterator<Item = P>) -> Vec<P> {
151        candidates
152            .into_iter()
153            .filter(|path| self.filter.judges(&self.relative(path.as_ref())))
154            .collect()
155    }
156
157    /// The subset of `candidates` this gate's exclusions leave.
158    ///
159    /// For a subject set the gate discovered itself. See
160    /// [`PathFilter::retains`].
161    #[must_use]
162    pub fn retained<P: AsRef<Utf8Path>>(&self, candidates: impl IntoIterator<Item = P>) -> Vec<P> {
163        candidates
164            .into_iter()
165            .filter(|path| self.filter.retains(&self.relative(path.as_ref())))
166            .collect()
167    }
168
169    /// The filter itself, for `--explain` and for the renderer.
170    #[must_use]
171    pub const fn filter(&self) -> &PathFilter {
172        &self.filter
173    }
174}
175
176/// One line a failing gate prints.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub enum Violation {
179    /// A rule violation, rendered as its `FAIL <domain>:<rule> ...` line.
180    Finding(Finding),
181    /// The repository does not have the shape the gate needs; rendered as
182    /// `FAIL <reason>` with no rule to cite.
183    Layout(String),
184    /// A continuation line under a preceding violation, rendered verbatim.
185    Note(String),
186}
187
188impl fmt::Display for Violation {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        match self {
191            Self::Finding(finding) => finding.fmt(f),
192            Self::Layout(reason) => write!(f, "FAIL {reason}"),
193            Self::Note(text) => f.write_str(text),
194        }
195    }
196}
197
198/// A gate that could not run at all — distinct from one that found violations.
199#[derive(Debug, Error)]
200pub enum GateError {
201    /// A file the gate needed could not be read.
202    #[error("{path}: {source}")]
203    Io {
204        /// The path that failed.
205        path: Utf8PathBuf,
206        /// The underlying failure.
207        source: std::io::Error,
208    },
209    /// The instance's debt file cannot be trusted, so no budget gate can
210    /// judge against it.
211    #[error("{0}")]
212    Debt(crate::domain::debt::DebtError),
213}
214
215impl GateError {
216    pub(crate) fn io(path: impl Into<Utf8PathBuf>, source: std::io::Error) -> Self {
217        Self::Io {
218            path: path.into(),
219            source,
220        }
221    }
222}
223
224impl From<GateError> for crate::error::AppError {
225    fn from(error: GateError) -> Self {
226        match error {
227            GateError::Io { path, source } => {
228                let kind = source.kind();
229                Self::Io(std::io::Error::new(kind, format!("{path}: {source}")))
230            }
231            GateError::Debt(error) => Self::Debt(error),
232        }
233    }
234}
235
236/// What every gate returns: the violations it found, or why it could not run.
237pub type GateResult = Result<Vec<Violation>, GateError>;
238
239/// The implementation shape shared by every gate.
240pub type GateFn = fn(&GateCtx, &[String]) -> GateResult;
241
242/// One registry row: everything the deliveries need to know about a gate.
243#[derive(Debug)]
244pub struct GateSpec {
245    /// The gate's identity.
246    pub id: GateId,
247    /// The display name pre-commit shows.
248    pub name: &'static str,
249    /// The subject paths this gate judges, as include globs with
250    /// `{docs_root}` left templated.
251    ///
252    /// Every row states them, under
253    /// `release:a-delivered-gate-reads-what-the-convention-owns`. An empty
254    /// list judges everything the excludes leave, and a row that states one
255    /// carries a comment saying why.
256    pub include: &'static [&'static str],
257    /// The `types:` scope, when the gate takes one.
258    ///
259    /// Pre-commit applies it in addition to the rendered patterns. `sdd
260    /// gate` does not, which is why `--explain` prints it rather than
261    /// folding it into the answer.
262    pub types: Option<&'static str>,
263    /// The subject paths this gate never judges, as exclude globs with
264    /// `{docs_root}` left templated.
265    pub exclude: &'static [&'static str],
266    /// Whether the gate runs regardless of which files changed.
267    pub always_run: bool,
268    /// Whether the gate resolves its own subject set rather than judging
269    /// the paths it is handed.
270    ///
271    /// For such a gate the discovery is the include, so
272    /// [`GateCtx::retained`] applies and the registry whitelist does not.
273    /// `always_run` is not this: `agents-digest-size` runs always and still
274    /// judges what [`walk_files`] hands it, which the registry include
275    /// narrows. `--explain` reads this field, so a wrong value makes the
276    /// diagnostic contradict the gate.
277    pub discovers: bool,
278    /// Whether the gate reports in warning mode.
279    ///
280    /// A warning gate prints each finding as a `WARN` line and exits zero,
281    /// and its rendered hook is verbose, so pre-commit shows the lines of a
282    /// passing hook. It gives adopters one release to conform before the
283    /// same gate fails.
284    pub warns: bool,
285    /// Every rule the gate can cite in a finding.
286    pub cites: &'static [RuleId],
287    /// The implementation.
288    pub run: GateFn,
289}
290
291/// Look up one gate's registry row.
292#[must_use]
293pub fn spec(id: GateId) -> &'static GateSpec {
294    let index = GateId::ALL.iter().position(|g| *g == id).unwrap_or(0);
295    &GATES[index]
296}
297
298/// The delivered gate set, in [`GateId::ALL`] order.
299pub static GATES: &[GateSpec] = &[
300    GateSpec {
301        id: GateId::AdrCitesALiveRule,
302        name: "decision record citations resolve",
303        include: &[r"{docs_root}/decisions/*.md"],
304        types: None,
305        exclude: &[],
306        always_run: true,
307        discovers: true,
308        warns: false,
309        cites: adr_cites_a_live_rule::CITES,
310        run: adr_cites_a_live_rule::run,
311    },
312    GateSpec {
313        id: GateId::AdrFilenameShape,
314        name: "decision record filename shape",
315        include: &[r"{docs_root}/decisions/*.md"],
316        types: None,
317        exclude: &[],
318        always_run: false,
319        discovers: false,
320        warns: false,
321        cites: adr_filename_shape::CITES,
322        run: adr_filename_shape::run,
323    },
324    GateSpec {
325        id: GateId::AdrWordCap,
326        name: "decision record word cap",
327        include: &[r"{docs_root}/decisions/*.md"],
328        types: None,
329        exclude: &[],
330        always_run: true,
331        discovers: true,
332        warns: false,
333        cites: adr_word_cap::CITES,
334        run: adr_word_cap::run,
335    },
336    GateSpec {
337        id: GateId::AgentsDigestSize,
338        name: "agent digest size",
339        include: &[r"**/AGENTS.md"],
340        types: None,
341        exclude: &[],
342        always_run: true,
343        discovers: false,
344        warns: false,
345        cites: agents_digest_size::CITES,
346        run: agents_digest_size::run,
347    },
348    GateSpec {
349        id: GateId::ChapterSizeCap,
350        name: "chapter and catalog size",
351        include: &[r"**/*.md"],
352        types: None,
353        exclude: &[],
354        always_run: true,
355        discovers: false,
356        warns: false,
357        cites: chapter_size_cap::CITES,
358        run: chapter_size_cap::run,
359    },
360    GateSpec {
361        id: GateId::ComparisonDatedTables,
362        name: "comparison tables are dated",
363        include: &[r"**/COMPARISON-*.md"],
364        types: None,
365        exclude: &[],
366        always_run: false,
367        discovers: false,
368        warns: false,
369        cites: comparison_dated_tables::CITES,
370        run: comparison_dated_tables::run,
371    },
372    GateSpec {
373        id: GateId::ComparisonEscapedPipes,
374        name: "comparison table pipes are escaped",
375        include: &[r"**/COMPARISON-*.md"],
376        types: None,
377        exclude: &[],
378        always_run: false,
379        discovers: false,
380        warns: false,
381        cites: comparison_escaped_pipes::CITES,
382        run: comparison_escaped_pipes::run,
383    },
384    GateSpec {
385        id: GateId::ComparisonLegend,
386        name: "comparison legend",
387        include: &[r"**/COMPARISON-*.md"],
388        types: None,
389        exclude: &[],
390        always_run: false,
391        discovers: false,
392        warns: false,
393        cites: comparison_legend::CITES,
394        run: comparison_legend::run,
395    },
396    GateSpec {
397        id: GateId::ComparisonOneReferencePerCell,
398        name: "one reference per comparison cell",
399        include: &[r"**/COMPARISON-*.md"],
400        types: None,
401        exclude: &[],
402        always_run: false,
403        discovers: false,
404        warns: false,
405        cites: comparison_one_reference_per_cell::CITES,
406        run: comparison_one_reference_per_cell::run,
407    },
408    GateSpec {
409        id: GateId::ComparisonVerdictWord,
410        name: "comparison verdict word",
411        include: &[r"**/COMPARISON-*.md"],
412        types: None,
413        exclude: &[],
414        always_run: false,
415        discovers: false,
416        warns: false,
417        cites: comparison_verdict_word::CITES,
418        run: comparison_verdict_word::run,
419    },
420    GateSpec {
421        id: GateId::GateMessageCitesARule,
422        name: "gate messages cite a rule",
423        // Judges the registry itself, not a path in the tree: the
424        // subject is every gate row, and the specs it resolves them
425        // against are support.
426        include: &[],
427        types: None,
428        exclude: &[],
429        always_run: true,
430        discovers: false,
431        warns: false,
432        cites: gate_message_cites_a_rule::CITES,
433        run: gate_message_cites_a_rule::run,
434    },
435    GateSpec {
436        id: GateId::InstanceManifest,
437        name: "instance manifest",
438        include: &[crate::domain::paths::MANIFEST_PATH],
439        types: None,
440        exclude: &[],
441        always_run: true,
442        discovers: true,
443        warns: false,
444        cites: instance_manifest::CITES,
445        run: instance_manifest::run,
446    },
447    GateSpec {
448        id: GateId::KiBugzillaReportWidth,
449        name: "Bugzilla report width",
450        include: &[r"{docs_root}/reference/known-issues/*.md"],
451        types: None,
452        exclude: &[],
453        always_run: true,
454        discovers: true,
455        warns: false,
456        cites: ki_bugzilla_report_width::CITES,
457        run: ki_bugzilla_report_width::run,
458    },
459    GateSpec {
460        id: GateId::KiCheckedDate,
461        name: "known issue last-check date",
462        include: &[r"{docs_root}/reference/known-issues/*.md"],
463        types: None,
464        exclude: &[],
465        always_run: true,
466        discovers: true,
467        warns: false,
468        cites: ki_checked_date::CITES,
469        run: ki_checked_date::run,
470    },
471    GateSpec {
472        id: GateId::KiFilenameShape,
473        name: "known issue filename shape",
474        include: &[r"{docs_root}/reference/known-issues/*.md"],
475        types: None,
476        exclude: &[],
477        always_run: false,
478        discovers: false,
479        warns: false,
480        cites: ki_filename_shape::CITES,
481        run: ki_filename_shape::run,
482    },
483    GateSpec {
484        id: GateId::KiFiling,
485        name: "known issue filing state",
486        include: &[r"{docs_root}/reference/known-issues/*.md"],
487        types: None,
488        exclude: &[],
489        always_run: true,
490        discovers: true,
491        warns: false,
492        cites: ki_filing::CITES,
493        run: ki_filing::run,
494    },
495    GateSpec {
496        id: GateId::KiMechanismWalkthrough,
497        name: "known issue mechanism walkthrough",
498        include: &[r"{docs_root}/reference/known-issues/*.md"],
499        types: None,
500        exclude: &[],
501        always_run: true,
502        discovers: true,
503        warns: false,
504        cites: ki_mechanism_walkthrough::CITES,
505        run: ki_mechanism_walkthrough::run,
506    },
507    GateSpec {
508        id: GateId::KiReportBody,
509        name: "known issue report body",
510        include: &[r"{docs_root}/reference/known-issues/*.md"],
511        types: None,
512        exclude: &[],
513        always_run: true,
514        discovers: true,
515        warns: false,
516        cites: ki_report_body::CITES,
517        run: ki_report_body::run,
518    },
519    GateSpec {
520        id: GateId::KiRetireWhen,
521        name: "known issue retirement condition",
522        include: &[r"{docs_root}/reference/known-issues/*.md"],
523        types: None,
524        exclude: &[],
525        always_run: true,
526        discovers: true,
527        warns: false,
528        cites: ki_retire_when::CITES,
529        run: ki_retire_when::run,
530    },
531    GateSpec {
532        id: GateId::KiState,
533        name: "known issue state",
534        include: &[r"{docs_root}/reference/known-issues/*.md"],
535        types: None,
536        exclude: &[],
537        always_run: true,
538        discovers: true,
539        warns: false,
540        cites: ki_state::CITES,
541        run: ki_state::run,
542    },
543    GateSpec {
544        id: GateId::NoPersonalPath,
545        name: "no personal path",
546        // Judges the whole project. Whether a string is a real person's
547        // home directory does not depend on which conventions a project
548        // follows, so a false positive is nearly impossible and the value
549        // is entirely in breadth. v0.6.5 anchored this to the documentation
550        // root over two register collisions, which a leak check does not
551        // have: a rendered release block carries no home directory. A
552        // project that needs a path exempt reserves it
553        // under `instance:the-project-declares-what-its-gates-judge`.
554        include: &[],
555        types: Some("text"),
556        exclude: &[],
557        always_run: false,
558        discovers: false,
559        warns: false,
560        cites: no_personal_path::CITES,
561        run: no_personal_path::run,
562    },
563    GateSpec {
564        id: GateId::NoSelfNarration,
565        name: "documents state the present",
566        include: &[r"{docs_root}/{specs,decisions,guides,reference,explanation}/**/*.md"],
567        types: Some("markdown"),
568        exclude: &[r"{docs_root}/decisions/**"],
569        always_run: false,
570        discovers: false,
571        warns: false,
572        cites: no_self_narration::CITES,
573        run: no_self_narration::run,
574    },
575    GateSpec {
576        id: GateId::ProseStaysUnwrapped,
577        name: "prose lines stay unwrapped",
578        include: &[r"{docs_root}/{specs,decisions,guides,reference,explanation}/**/*.md"],
579        types: Some("markdown"),
580        // A generated `CHANGELOG.md` is exempt, and the gate skips it by
581        // name. An exclude here would match no file the include selects,
582        // so the hook runner's useless-exclude check would refuse it.
583        exclude: &[],
584        always_run: false,
585        discovers: false,
586        warns: false,
587        cites: prose_stays_unwrapped::CITES,
588        run: prose_stays_unwrapped::run,
589    },
590    GateSpec {
591        id: GateId::SpecRequirementParts,
592        name: "spec requirement parts",
593        include: &[r"{docs_root}/specs/SPEC-*.md"],
594        types: None,
595        exclude: &[],
596        always_run: false,
597        discovers: false,
598        warns: false,
599        cites: spec_requirement_parts::CITES,
600        run: spec_requirement_parts::run,
601    },
602    GateSpec {
603        id: GateId::SpecRuleIdUnique,
604        name: "spec rule IDs are unique",
605        include: &[r"{docs_root}/specs/SPEC-*.md"],
606        types: None,
607        exclude: &[],
608        always_run: true,
609        discovers: true,
610        warns: false,
611        cites: spec_rule_id_unique::CITES,
612        run: spec_rule_id_unique::run,
613    },
614    GateSpec {
615        id: GateId::SpecSizeCap,
616        name: "spec size cap",
617        include: &[r"{docs_root}/specs/SPEC-*.md"],
618        types: None,
619        exclude: &[],
620        always_run: true,
621        discovers: true,
622        warns: false,
623        cites: spec_size_cap::CITES,
624        run: spec_size_cap::run,
625    },
626    GateSpec {
627        id: GateId::SpecTrailingSection,
628        name: "spec trailing section",
629        include: &[r"{docs_root}/specs/SPEC-*.md"],
630        types: None,
631        exclude: &[],
632        always_run: false,
633        discovers: false,
634        warns: false,
635        cites: spec_trailing_section::CITES,
636        run: spec_trailing_section::run,
637    },
638    GateSpec {
639        id: GateId::SpecVerifyHooksExist,
640        name: "spec hook references exist",
641        include: &[r"{docs_root}/specs/SPEC-*.md"],
642        types: None,
643        exclude: &[],
644        always_run: true,
645        discovers: true,
646        warns: false,
647        cites: spec_verify_hooks_exist::CITES,
648        run: spec_verify_hooks_exist::run,
649    },
650    GateSpec {
651        id: GateId::SuppressionNamesItsCase,
652        name: "suppressions name a known issue",
653        // Judges every file in the project, because a `KI-` citation can be
654        // written in any of them and this gate reads no language. The
655        // documentation root is out: a specification, a chapter, and a
656        // record each write the token while teaching it. The known-issue
657        // records it resolves a case against are support.
658        include: &[],
659        types: None,
660        exclude: &[r"{docs_root}/**"],
661        always_run: true,
662        discovers: false,
663        warns: false,
664        cites: suppression_names_its_case::CITES,
665        run: suppression_names_its_case::run,
666    },
667    GateSpec {
668        id: GateId::TrackingRegistry,
669        name: "tracking registry is valid and current",
670        include: &[r"{docs_root}/reference/tracking.yaml"],
671        types: None,
672        exclude: &[],
673        always_run: true,
674        discovers: true,
675        warns: false,
676        cites: tracking_registry::CITES,
677        run: tracking_registry::run,
678    },
679];
680
681/// The directories every repository walk prunes: vendored or generated trees
682/// a consumer cannot be asked to author.
683pub const PRUNED_DIRS: &[&str] = &[
684    ".git",
685    "node_modules",
686    ".venv",
687    "vendor",
688    "third-party",
689    "target",
690    "dist",
691];
692
693/// Count the newline-terminated lines of a text, as `wc -l` does.
694#[must_use]
695pub fn line_count(text: &str) -> usize {
696    text.matches('\n').count()
697}
698
699/// Read a repository-relative text file for a gate.
700///
701/// # Errors
702///
703/// [`GateError::Io`] naming the path when the file cannot be read.
704pub fn read_text(ctx: &GateCtx, relative: impl AsRef<Utf8Path>) -> Result<String, GateError> {
705    let relative = relative.as_ref();
706    std::fs::read_to_string(ctx.path(relative)).map_err(|source| GateError::io(relative, source))
707}
708
709/// Every value a front-matter key carries, in the order the keys appear.
710///
711/// The scan is the leading `---` block alone, so a `state:` line in the
712/// prose below it is text about the record rather than the record's own
713/// field. A key stated twice yields two entries, which is what makes
714/// "exactly one" decidable.
715#[must_use]
716pub fn front_matter_values(text: &str, key: &str) -> Vec<String> {
717    let mut lines = text.lines();
718    if lines.next() != Some("---") {
719        return Vec::new();
720    }
721    lines
722        .take_while(|line| *line != "---")
723        .filter_map(|line| {
724            line.strip_prefix(key)
725                .and_then(|rest| rest.strip_prefix(':'))
726        })
727        .map(|value| value.trim().to_string())
728        .collect()
729}
730
731/// The traversal pruner: [`PRUNED_DIRS`] as an `ignore` override.
732///
733/// `Override` is the right tool here and the wrong one in
734/// [`crate::domain::path_filter`]. Pruning wants one boolean per directory
735/// and no provenance, which is exactly what it gives.
736fn pruner(root: &Utf8Path) -> ignore::overrides::Override {
737    let mut builder = ignore::overrides::OverrideBuilder::new(root.as_std_path());
738    for dir in PRUNED_DIRS {
739        // `!` marks an exclude in `Override`'s own grammar, which is not
740        // the restricted grammar `PathFilter` carries.
741        let _ = builder.add(&format!("!{dir}/**"));
742        let _ = builder.add(&format!("!{dir}"));
743    }
744    builder
745        .build()
746        .unwrap_or_else(|_| ignore::overrides::Override::empty())
747}
748
749/// Walk the repository and yield every file as a `./`-prefixed
750/// repository-relative path in sorted order.
751///
752/// The walk prunes [`PRUNED_DIRS`] and honours the repository's committed
753/// `.gitignore`. It honours no machine-local ignore source: `.git/info/exclude`,
754/// the user's global excludes file, and ignore files above the repository
755/// root are all disabled, because a gate whose answer depends on whose
756/// checkout it runs in is not a gate.
757#[must_use]
758pub fn walk_files(ctx: &GateCtx) -> Vec<Utf8PathBuf> {
759    let root = ctx.repo_root.as_std_path();
760    let mut files: Vec<Utf8PathBuf> = ignore::WalkBuilder::new(root)
761        .standard_filters(false)
762        .git_ignore(true)
763        .git_exclude(false)
764        .git_global(false)
765        .ignore(false)
766        .parents(false)
767        .require_git(false)
768        .hidden(false)
769        .overrides(pruner(&ctx.repo_root))
770        .build()
771        .filter_map(Result::ok)
772        .filter(|entry| entry.file_type().is_some_and(|kind| kind.is_file()))
773        .filter_map(|entry| {
774            let relative = entry.path().strip_prefix(root).ok()?.to_str()?;
775            Some(Utf8PathBuf::from(format!("./{relative}")))
776        })
777        .collect();
778    files.sort();
779    ctx.subjects(files)
780}
781
782#[cfg(test)]
783pub(crate) mod tests_support {
784    /// A repository holding one known-issue record with the given `state:`
785    /// value and `retire_when:` line.
786    pub fn ki_fixture_state(state: &str, retire_line: &str) -> tempfile::TempDir {
787        ki_record(&format!(
788            "---\nupstream: https://example.invalid/issues\nstate: {state}\nfiling: gathering\n{retire_line}---\n# Vendor issue\n## How it works\nRun.\n"
789        ))
790    }
791
792    /// A repository holding one known-issue record with the given `state:`
793    /// value and `checked:` line.
794    pub fn ki_fixture_checked(state: &str, checked_line: &str) -> tempfile::TempDir {
795        ki_record(&format!(
796            "---\nupstream: https://example.invalid/issues\nstate: {state}\nfiling: gathering\nretire_when: release >= 2.0\n{checked_line}---\n# Vendor issue\n## How it works\nRun.\n"
797        ))
798    }
799
800    /// A repository holding one known-issue record with a conforming
801    /// frontmatter and the given body.
802    pub fn ki_fixture_body(body: &str) -> tempfile::TempDir {
803        ki_record(&format!(
804            "---\nupstream: https://example.invalid/issues\nstate: masked\nfiling: gathering\nretire_when: release >= 2.0\n---\n{body}"
805        ))
806    }
807
808    /// A repository holding one filed known-issue record with the given
809    /// `upstream:` value and body.
810    pub fn ki_fixture_upstream(upstream: &str, body: &str) -> tempfile::TempDir {
811        ki_fixture_filing("filed", upstream, body)
812    }
813
814    /// A repository holding one known-issue record with the given `filing:`
815    /// value, `upstream:` value and body.
816    pub fn ki_fixture_filing(filing: &str, upstream: &str, body: &str) -> tempfile::TempDir {
817        ki_record(&format!(
818            "---\nupstream: {upstream}\nstate: masked\nfiling: {filing}\nretire_when: release >= 2.0\n---\n{body}"
819        ))
820    }
821
822    fn ki_record(text: &str) -> tempfile::TempDir {
823        let dir = tempfile::tempdir().unwrap();
824        let records = dir.path().join("_docs/reference/known-issues");
825        std::fs::create_dir_all(&records).unwrap();
826        std::fs::write(records.join("KI-vendor.md"), text).unwrap();
827        dir
828    }
829}
830
831#[cfg(test)]
832mod tests {
833    use super::*;
834
835    /// A repository holding one file at each named path.
836    fn tree(paths: &[(&str, &str)]) -> tempfile::TempDir {
837        let dir = tempfile::tempdir().expect("a scratch directory");
838        for (path, body) in paths {
839            let full = dir.path().join(path);
840            if let Some(parent) = full.parent() {
841                std::fs::create_dir_all(parent).expect("the parent exists");
842            }
843            std::fs::write(&full, body).expect("the file is written");
844        }
845        dir
846    }
847
848    fn walked(dir: &tempfile::TempDir) -> Vec<String> {
849        let root = Utf8PathBuf::from_path_buf(dir.path().to_path_buf())
850            .expect("the scratch path is UTF-8");
851        walk_files(&GateCtx::new(root))
852            .into_iter()
853            .map(|p| p.to_string())
854            .collect()
855    }
856
857    #[test]
858    fn walk_files_skips_a_gitignored_file() {
859        let dir = tree(&[
860            (".gitignore", "generated.md\n"),
861            ("generated.md", "x\n"),
862            ("kept.md", "x\n"),
863        ]);
864        let files = walked(&dir);
865        assert!(files.contains(&"./kept.md".to_string()));
866        assert!(
867            !files.contains(&"./generated.md".to_string()),
868            "a git-ignored file still reached a walking gate: {files:?}"
869        );
870    }
871
872    #[test]
873    fn walk_files_ignores_a_machine_local_exclude_file() {
874        // The hostile case. A machine-local exclude must not hide a governed
875        // file, or one operator's checkout reports a violation another's
876        // does not.
877        let dir = tree(&[
878            (".git/info/exclude", "governed.md\n"),
879            ("governed.md", "x\n"),
880        ]);
881        assert!(
882            walked(&dir).contains(&"./governed.md".to_string()),
883            "a machine-local exclude hid a governed file"
884        );
885    }
886
887    #[test]
888    fn walk_files_still_prunes_the_pruned_dirs() {
889        let dir = tree(&[
890            ("target/debug/artifact", "x\n"),
891            ("node_modules/pkg/index.js", "x\n"),
892            ("src/main.rs", "x\n"),
893        ]);
894        let files = walked(&dir);
895        assert_eq!(files, vec!["./src/main.rs".to_string()]);
896    }
897
898    #[test]
899    fn walk_files_yields_dotted_paths() {
900        let dir = tree(&[(".markdownlint/base.yaml", "x\n")]);
901        assert!(walked(&dir).contains(&"./.markdownlint/base.yaml".to_string()));
902    }
903
904    #[test]
905    fn registry_covers_every_gate_exactly_once_in_order() {
906        assert_eq!(GATES.len(), GateId::ALL.len());
907        for (row, id) in GATES.iter().zip(GateId::ALL) {
908            assert_eq!(row.id, *id);
909            assert_eq!(spec(*id).id, *id);
910        }
911    }
912
913    #[test]
914    fn every_gate_declares_the_rules_it_cites() {
915        for row in GATES {
916            assert!(!row.cites.is_empty(), "{} cites nothing", row.id);
917        }
918    }
919
920    #[test]
921    fn cited_rules_resolve_in_the_embedded_specs() {
922        let defined = crate::embedded::spec_rule_ids();
923        for row in GATES {
924            for rule in row.cites {
925                assert!(
926                    defined.contains(rule.as_str()),
927                    "{}: {rule} is undefined",
928                    row.id
929                );
930            }
931        }
932    }
933}