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