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