1pub 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#[derive(Debug)]
79pub struct GateCtx {
80 pub repo_root: Utf8PathBuf,
82 filter: PathFilter,
85 docs_root: Option<Utf8PathBuf>,
88}
89
90impl GateCtx {
91 #[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 #[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 #[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 #[must_use]
124 pub fn named_docs_root(&self) -> Option<&Utf8Path> {
125 self.docs_root.as_deref()
126 }
127
128 #[must_use]
132 pub fn path(&self, relative: impl AsRef<Utf8Path>) -> Utf8PathBuf {
133 self.repo_root.join(relative)
134 }
135
136 fn relative(&self, path: &Utf8Path) -> Utf8PathBuf {
142 crate::domain::path_filter::project(path, &self.repo_root)
143 }
144
145 #[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 #[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 #[must_use]
171 pub const fn filter(&self) -> &PathFilter {
172 &self.filter
173 }
174}
175
176#[derive(Debug, Clone, PartialEq, Eq)]
178pub enum Violation {
179 Finding(Finding),
181 Layout(String),
184 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#[derive(Debug, Error)]
200pub enum GateError {
201 #[error("{path}: {source}")]
203 Io {
204 path: Utf8PathBuf,
206 source: std::io::Error,
208 },
209 #[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
236pub type GateResult = Result<Vec<Violation>, GateError>;
238
239pub type GateFn = fn(&GateCtx, &[String]) -> GateResult;
241
242#[derive(Debug)]
244pub struct GateSpec {
245 pub id: GateId,
247 pub name: &'static str,
249 pub include: &'static [&'static str],
257 pub types: Option<&'static str>,
263 pub exclude: &'static [&'static str],
266 pub always_run: bool,
268 pub discovers: bool,
278 pub warns: bool,
285 pub cites: &'static [RuleId],
287 pub run: GateFn,
289}
290
291#[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
298pub 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 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 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 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 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
681pub const PRUNED_DIRS: &[&str] = &[
684 ".git",
685 "node_modules",
686 ".venv",
687 "vendor",
688 "third-party",
689 "target",
690 "dist",
691];
692
693#[must_use]
695pub fn line_count(text: &str) -> usize {
696 text.matches('\n').count()
697}
698
699pub 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#[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
731fn 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 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#[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 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 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 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 pub fn ki_fixture_upstream(upstream: &str, body: &str) -> tempfile::TempDir {
811 ki_fixture_filing("filed", upstream, body)
812 }
813
814 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 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 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}