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: &[r"**/CHANGELOG.md"],
581 always_run: false,
582 discovers: false,
583 warns: false,
584 cites: prose_stays_unwrapped::CITES,
585 run: prose_stays_unwrapped::run,
586 },
587 GateSpec {
588 id: GateId::SpecRequirementParts,
589 name: "spec requirement parts",
590 include: &[r"{docs_root}/specs/SPEC-*.md"],
591 types: None,
592 exclude: &[],
593 always_run: false,
594 discovers: false,
595 warns: false,
596 cites: spec_requirement_parts::CITES,
597 run: spec_requirement_parts::run,
598 },
599 GateSpec {
600 id: GateId::SpecRuleIdUnique,
601 name: "spec rule IDs are unique",
602 include: &[r"{docs_root}/specs/SPEC-*.md"],
603 types: None,
604 exclude: &[],
605 always_run: true,
606 discovers: true,
607 warns: false,
608 cites: spec_rule_id_unique::CITES,
609 run: spec_rule_id_unique::run,
610 },
611 GateSpec {
612 id: GateId::SpecSizeCap,
613 name: "spec size cap",
614 include: &[r"{docs_root}/specs/SPEC-*.md"],
615 types: None,
616 exclude: &[],
617 always_run: true,
618 discovers: true,
619 warns: false,
620 cites: spec_size_cap::CITES,
621 run: spec_size_cap::run,
622 },
623 GateSpec {
624 id: GateId::SpecTrailingSection,
625 name: "spec trailing section",
626 include: &[r"{docs_root}/specs/SPEC-*.md"],
627 types: None,
628 exclude: &[],
629 always_run: false,
630 discovers: false,
631 warns: false,
632 cites: spec_trailing_section::CITES,
633 run: spec_trailing_section::run,
634 },
635 GateSpec {
636 id: GateId::SpecVerifyHooksExist,
637 name: "spec hook references exist",
638 include: &[r"{docs_root}/specs/SPEC-*.md"],
639 types: None,
640 exclude: &[],
641 always_run: true,
642 discovers: true,
643 warns: false,
644 cites: spec_verify_hooks_exist::CITES,
645 run: spec_verify_hooks_exist::run,
646 },
647 GateSpec {
648 id: GateId::SuppressionNamesItsCase,
649 name: "suppressions name a known issue",
650 include: &[],
656 types: None,
657 exclude: &[r"{docs_root}/**"],
658 always_run: true,
659 discovers: false,
660 warns: false,
661 cites: suppression_names_its_case::CITES,
662 run: suppression_names_its_case::run,
663 },
664 GateSpec {
665 id: GateId::TrackingRegistry,
666 name: "tracking registry is valid and current",
667 include: &[r"{docs_root}/reference/tracking.yaml"],
668 types: None,
669 exclude: &[],
670 always_run: true,
671 discovers: true,
672 warns: false,
673 cites: tracking_registry::CITES,
674 run: tracking_registry::run,
675 },
676];
677
678pub const PRUNED_DIRS: &[&str] = &[
681 ".git",
682 "node_modules",
683 ".venv",
684 "vendor",
685 "third-party",
686 "target",
687 "dist",
688];
689
690#[must_use]
692pub fn line_count(text: &str) -> usize {
693 text.matches('\n').count()
694}
695
696pub fn read_text(ctx: &GateCtx, relative: impl AsRef<Utf8Path>) -> Result<String, GateError> {
702 let relative = relative.as_ref();
703 std::fs::read_to_string(ctx.path(relative)).map_err(|source| GateError::io(relative, source))
704}
705
706#[must_use]
713pub fn front_matter_values(text: &str, key: &str) -> Vec<String> {
714 let mut lines = text.lines();
715 if lines.next() != Some("---") {
716 return Vec::new();
717 }
718 lines
719 .take_while(|line| *line != "---")
720 .filter_map(|line| {
721 line.strip_prefix(key)
722 .and_then(|rest| rest.strip_prefix(':'))
723 })
724 .map(|value| value.trim().to_string())
725 .collect()
726}
727
728fn pruner(root: &Utf8Path) -> ignore::overrides::Override {
734 let mut builder = ignore::overrides::OverrideBuilder::new(root.as_std_path());
735 for dir in PRUNED_DIRS {
736 let _ = builder.add(&format!("!{dir}/**"));
739 let _ = builder.add(&format!("!{dir}"));
740 }
741 builder
742 .build()
743 .unwrap_or_else(|_| ignore::overrides::Override::empty())
744}
745
746#[must_use]
755pub fn walk_files(ctx: &GateCtx) -> Vec<Utf8PathBuf> {
756 let root = ctx.repo_root.as_std_path();
757 let mut files: Vec<Utf8PathBuf> = ignore::WalkBuilder::new(root)
758 .standard_filters(false)
759 .git_ignore(true)
760 .git_exclude(false)
761 .git_global(false)
762 .ignore(false)
763 .parents(false)
764 .require_git(false)
765 .hidden(false)
766 .overrides(pruner(&ctx.repo_root))
767 .build()
768 .filter_map(Result::ok)
769 .filter(|entry| entry.file_type().is_some_and(|kind| kind.is_file()))
770 .filter_map(|entry| {
771 let relative = entry.path().strip_prefix(root).ok()?.to_str()?;
772 Some(Utf8PathBuf::from(format!("./{relative}")))
773 })
774 .collect();
775 files.sort();
776 ctx.subjects(files)
777}
778
779#[cfg(test)]
780pub(crate) mod tests_support {
781 pub fn ki_fixture_state(state: &str, retire_line: &str) -> tempfile::TempDir {
784 ki_record(&format!(
785 "---\nupstream: https://example.invalid/issues\nstate: {state}\nfiling: gathering\n{retire_line}---\n# Vendor issue\n## How it works\nRun.\n"
786 ))
787 }
788
789 pub fn ki_fixture_checked(state: &str, checked_line: &str) -> tempfile::TempDir {
792 ki_record(&format!(
793 "---\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"
794 ))
795 }
796
797 pub fn ki_fixture_body(body: &str) -> tempfile::TempDir {
800 ki_record(&format!(
801 "---\nupstream: https://example.invalid/issues\nstate: masked\nfiling: gathering\nretire_when: release >= 2.0\n---\n{body}"
802 ))
803 }
804
805 pub fn ki_fixture_upstream(upstream: &str, body: &str) -> tempfile::TempDir {
808 ki_fixture_filing("filed", upstream, body)
809 }
810
811 pub fn ki_fixture_filing(filing: &str, upstream: &str, body: &str) -> tempfile::TempDir {
814 ki_record(&format!(
815 "---\nupstream: {upstream}\nstate: masked\nfiling: {filing}\nretire_when: release >= 2.0\n---\n{body}"
816 ))
817 }
818
819 fn ki_record(text: &str) -> tempfile::TempDir {
820 let dir = tempfile::tempdir().unwrap();
821 let records = dir.path().join("_docs/reference/known-issues");
822 std::fs::create_dir_all(&records).unwrap();
823 std::fs::write(records.join("KI-vendor.md"), text).unwrap();
824 dir
825 }
826}
827
828#[cfg(test)]
829mod tests {
830 use super::*;
831
832 fn tree(paths: &[(&str, &str)]) -> tempfile::TempDir {
834 let dir = tempfile::tempdir().expect("a scratch directory");
835 for (path, body) in paths {
836 let full = dir.path().join(path);
837 if let Some(parent) = full.parent() {
838 std::fs::create_dir_all(parent).expect("the parent exists");
839 }
840 std::fs::write(&full, body).expect("the file is written");
841 }
842 dir
843 }
844
845 fn walked(dir: &tempfile::TempDir) -> Vec<String> {
846 let root = Utf8PathBuf::from_path_buf(dir.path().to_path_buf())
847 .expect("the scratch path is UTF-8");
848 walk_files(&GateCtx::new(root))
849 .into_iter()
850 .map(|p| p.to_string())
851 .collect()
852 }
853
854 #[test]
855 fn walk_files_skips_a_gitignored_file() {
856 let dir = tree(&[
857 (".gitignore", "generated.md\n"),
858 ("generated.md", "x\n"),
859 ("kept.md", "x\n"),
860 ]);
861 let files = walked(&dir);
862 assert!(files.contains(&"./kept.md".to_string()));
863 assert!(
864 !files.contains(&"./generated.md".to_string()),
865 "a git-ignored file still reached a walking gate: {files:?}"
866 );
867 }
868
869 #[test]
870 fn walk_files_ignores_a_machine_local_exclude_file() {
871 let dir = tree(&[
875 (".git/info/exclude", "governed.md\n"),
876 ("governed.md", "x\n"),
877 ]);
878 assert!(
879 walked(&dir).contains(&"./governed.md".to_string()),
880 "a machine-local exclude hid a governed file"
881 );
882 }
883
884 #[test]
885 fn walk_files_still_prunes_the_pruned_dirs() {
886 let dir = tree(&[
887 ("target/debug/artifact", "x\n"),
888 ("node_modules/pkg/index.js", "x\n"),
889 ("src/main.rs", "x\n"),
890 ]);
891 let files = walked(&dir);
892 assert_eq!(files, vec!["./src/main.rs".to_string()]);
893 }
894
895 #[test]
896 fn walk_files_yields_dotted_paths() {
897 let dir = tree(&[(".markdownlint/base.yaml", "x\n")]);
898 assert!(walked(&dir).contains(&"./.markdownlint/base.yaml".to_string()));
899 }
900
901 #[test]
902 fn registry_covers_every_gate_exactly_once_in_order() {
903 assert_eq!(GATES.len(), GateId::ALL.len());
904 for (row, id) in GATES.iter().zip(GateId::ALL) {
905 assert_eq!(row.id, *id);
906 assert_eq!(spec(*id).id, *id);
907 }
908 }
909
910 #[test]
911 fn every_gate_declares_the_rules_it_cites() {
912 for row in GATES {
913 assert!(!row.cites.is_empty(), "{} cites nothing", row.id);
914 }
915 }
916
917 #[test]
918 fn cited_rules_resolve_in_the_embedded_specs() {
919 let defined = crate::embedded::spec_rule_ids();
920 for row in GATES {
921 for rule in row.cites {
922 assert!(
923 defined.contains(rule.as_str()),
924 "{}: {rule} is undefined",
925 row.id
926 );
927 }
928 }
929 }
930}