adrs-core 0.9.0

Core library for managing Architecture Decision Records
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! ADR linting using mdbook-lint rules.
//!
//! This module provides unified linting for ADRs, combining per-file validation
//! (title format, required sections, date format) with repository-level checks
//! (sequential numbering, duplicate detection, broken links).

use crate::{Adr, Repository, Result};
use mdbook_lint_core::Document;
use mdbook_lint_core::rule::{CollectionRule, Rule};
use mdbook_lint_rulesets::adr::{
    Adr001, Adr002, Adr003, Adr004, Adr005, Adr006, Adr007, Adr008, Adr009, Adr010, Adr011, Adr012,
    Adr013, Adr014, Adr015, Adr016, Adr017,
};
use std::path::PathBuf;

/// Severity level for lint issues.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum IssueSeverity {
    /// Informational message.
    Info,
    /// Warning that should be addressed.
    Warning,
    /// Error that needs to be fixed.
    Error,
}

impl std::fmt::Display for IssueSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IssueSeverity::Info => write!(f, "info"),
            IssueSeverity::Warning => write!(f, "warning"),
            IssueSeverity::Error => write!(f, "error"),
        }
    }
}

impl From<mdbook_lint_core::Severity> for IssueSeverity {
    fn from(severity: mdbook_lint_core::Severity) -> Self {
        match severity {
            mdbook_lint_core::Severity::Error => IssueSeverity::Error,
            mdbook_lint_core::Severity::Warning => IssueSeverity::Warning,
            mdbook_lint_core::Severity::Info => IssueSeverity::Info,
        }
    }
}

/// A unified issue type for both per-file lint violations and repository-level diagnostics.
#[derive(Debug, Clone)]
pub struct Issue {
    /// The rule that produced this issue (e.g., "ADR001", "adr-title-format").
    pub rule_id: String,
    /// Human-readable rule name.
    pub rule_name: String,
    /// The severity of this issue.
    pub severity: IssueSeverity,
    /// A human-readable message describing the issue.
    pub message: String,
    /// The path to the affected file, if applicable.
    pub path: Option<PathBuf>,
    /// Line number (1-based), if applicable.
    pub line: Option<usize>,
    /// Column number (1-based), if applicable.
    pub column: Option<usize>,
    /// The ADR number, if applicable.
    pub adr_number: Option<u32>,
    /// Related ADR numbers (for issues involving multiple ADRs).
    pub related_adrs: Vec<u32>,
}

impl Issue {
    /// Create a new issue from an mdbook-lint violation.
    fn from_violation(
        violation: mdbook_lint_core::Violation,
        path: Option<PathBuf>,
        adr_number: Option<u32>,
    ) -> Self {
        Self {
            rule_id: violation.rule_id,
            rule_name: violation.rule_name,
            severity: violation.severity.into(),
            message: violation.message,
            path,
            line: Some(violation.line),
            column: Some(violation.column),
            adr_number,
            related_adrs: Vec::new(),
        }
    }
}

/// Results from linting.
#[derive(Debug, Default)]
pub struct LintReport {
    /// All issues found.
    pub issues: Vec<Issue>,
}

impl LintReport {
    /// Create a new empty report.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an issue to the report.
    pub fn add(&mut self, issue: Issue) {
        self.issues.push(issue);
    }

    /// Check if there are any errors.
    pub fn has_errors(&self) -> bool {
        self.issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Error)
    }

    /// Check if there are any warnings.
    pub fn has_warnings(&self) -> bool {
        self.issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Warning)
    }

    /// Check if the report is clean (no warnings or errors).
    pub fn is_clean(&self) -> bool {
        !self.has_errors() && !self.has_warnings()
    }

    /// Get the count of issues by severity.
    pub fn count_by_severity(&self, severity: IssueSeverity) -> usize {
        self.issues
            .iter()
            .filter(|i| i.severity == severity)
            .count()
    }

    /// Sort issues by severity (errors first), then by path, then by line.
    pub fn sort(&mut self) {
        self.issues.sort_by(|a, b| {
            b.severity
                .cmp(&a.severity)
                .then_with(|| a.path.cmp(&b.path))
                .then_with(|| a.line.cmp(&b.line))
        });
    }
}

/// Lint a single ADR file.
///
/// Runs all per-file lint rules against the ADR content.
pub fn lint_adr(adr: &Adr) -> Result<LintReport> {
    let mut report = LintReport::new();

    // Get the file content
    let Some(path) = &adr.path else {
        return Ok(report); // No path, nothing to lint
    };

    let content = std::fs::read_to_string(path)?;

    // Create mdbook-lint Document
    let doc = match Document::new(content, path.clone()) {
        Ok(d) => d,
        Err(e) => {
            report.add(Issue {
                rule_id: "parse-error".to_string(),
                rule_name: "parse-error".to_string(),
                severity: IssueSeverity::Error,
                message: format!("Failed to parse document: {e}"),
                path: Some(path.clone()),
                line: None,
                column: None,
                adr_number: Some(adr.number),
                related_adrs: Vec::new(),
            });
            return Ok(report);
        }
    };

    // Run all single-document rules
    let rules: Vec<Box<dyn Rule>> = vec![
        Box::new(Adr001::default()),
        Box::new(Adr002::default()),
        Box::new(Adr003::default()),
        Box::new(Adr004::default()),
        Box::new(Adr005::default()),
        Box::new(Adr006::default()),
        Box::new(Adr007::default()),
        Box::new(Adr008::default()),
        Box::new(Adr009::default()),
        Box::new(Adr014::default()),
        Box::new(Adr015::default()),
        Box::new(Adr016::default()),
        Box::new(Adr017::default()),
    ];

    for rule in rules {
        match rule.check(&doc) {
            Ok(violations) => {
                for violation in violations {
                    report.add(Issue::from_violation(
                        violation,
                        Some(path.clone()),
                        Some(adr.number),
                    ));
                }
            }
            Err(e) => {
                report.add(Issue {
                    rule_id: rule.id().to_string(),
                    rule_name: rule.name().to_string(),
                    severity: IssueSeverity::Error,
                    message: format!("Rule failed: {e}"),
                    path: Some(path.clone()),
                    line: None,
                    column: None,
                    adr_number: Some(adr.number),
                    related_adrs: Vec::new(),
                });
            }
        }
    }

    Ok(report)
}

/// Lint all ADRs in a repository (per-file checks only).
pub fn lint_all(repo: &Repository) -> Result<LintReport> {
    let mut report = LintReport::new();
    let adrs = repo.list()?;

    for adr in &adrs {
        let adr_report = lint_adr(adr)?;
        report.issues.extend(adr_report.issues);
    }

    report.sort();
    Ok(report)
}

/// Run repository-level checks (collection rules).
///
/// These checks analyze the ADR set as a whole:
/// - Sequential numbering (ADR011)
/// - Duplicate numbers (ADR012)
/// - Broken links (ADR013)
/// - Superseded ADRs have replacements (ADR010)
pub fn check_repository(repo: &Repository) -> Result<LintReport> {
    let mut report = LintReport::new();
    let adrs = repo.list()?;

    // Build documents for collection rules
    let mut documents = Vec::new();
    for adr in &adrs {
        if let Some(path) = &adr.path {
            let content = std::fs::read_to_string(path)?;
            if let Ok(doc) = Document::new(content, path.clone()) {
                documents.push(doc);
            }
        }
    }

    // Run collection rules
    let collection_rules: Vec<Box<dyn CollectionRule>> = vec![
        Box::new(Adr010),
        Box::new(Adr011),
        Box::new(Adr012),
        Box::new(Adr013),
    ];

    for rule in collection_rules {
        match rule.check_collection(&documents) {
            Ok(violations) => {
                for violation in violations {
                    // Collection rule violations may have path in the message
                    // We need to parse it out or handle it differently
                    report.add(Issue {
                        rule_id: rule.id().to_string(),
                        rule_name: rule.name().to_string(),
                        severity: violation.severity.into(),
                        message: violation.message,
                        path: None, // Collection rules may span multiple files
                        line: if violation.line > 0 {
                            Some(violation.line)
                        } else {
                            None
                        },
                        column: if violation.column > 0 {
                            Some(violation.column)
                        } else {
                            None
                        },
                        adr_number: None,
                        related_adrs: Vec::new(),
                    });
                }
            }
            Err(e) => {
                report.add(Issue {
                    rule_id: rule.id().to_string(),
                    rule_name: rule.name().to_string(),
                    severity: IssueSeverity::Error,
                    message: format!("Rule failed: {e}"),
                    path: None,
                    line: None,
                    column: None,
                    adr_number: None,
                    related_adrs: Vec::new(),
                });
            }
        }
    }

    report.sort();
    Ok(report)
}

/// Run all checks and filter out issues matching ignored rule IDs/names.
///
/// Ignored rules are `repo.config().doctor.ignore` unioned with `extra_ignore`
/// (e.g. CLI `--ignore` flags for a single invocation). Matching is
/// case-insensitive against both `Issue.rule_id` and `Issue.rule_name`.
///
/// Returns the filtered report and the count of issues that were suppressed.
pub fn check_all_filtered(
    repo: &Repository,
    extra_ignore: &[String],
) -> Result<(LintReport, usize)> {
    let mut report = LintReport::new();

    // Use list_with_errors to capture parse failures
    let (adrs, parse_errors) = repo.list_with_errors()?;

    // Report parse errors as lint issues
    for (path, error) in &parse_errors {
        report.add(Issue {
            rule_id: "parse-error".to_string(),
            rule_name: "adr-parse-error".to_string(),
            severity: IssueSeverity::Error,
            message: format!("Failed to parse ADR: {error}"),
            path: Some(path.clone()),
            line: None,
            column: None,
            adr_number: None,
            related_adrs: Vec::new(),
        });
    }

    // Run per-file lint on successfully parsed ADRs
    for adr in &adrs {
        let adr_report = lint_adr(adr)?;
        report.issues.extend(adr_report.issues);
    }

    // Run repository-level checks (these still use repo.list() internally,
    // which is fine — they only need successfully parsed ADRs)
    let repo_report = check_repository(repo)?;
    report.issues.extend(repo_report.issues);

    report.sort();

    let ignore_set: std::collections::HashSet<String> = repo
        .config()
        .doctor
        .ignore
        .iter()
        .chain(extra_ignore.iter())
        .map(|s| s.to_lowercase())
        .collect();

    if ignore_set.is_empty() {
        return Ok((report, 0));
    }

    let before = report.issues.len();
    report.issues.retain(|issue| {
        !ignore_set.contains(&issue.rule_id.to_lowercase())
            && !ignore_set.contains(&issue.rule_name.to_lowercase())
    });
    let suppressed = before - report.issues.len();

    Ok((report, suppressed))
}

/// Run all checks: per-file lint + repository-level checks.
///
/// Also reports files that look like ADRs (digit-prefixed `.md` files in the
/// ADR directory) but could not be parsed (e.g., invalid YAML frontmatter).
pub fn check_all(repo: &Repository) -> Result<LintReport> {
    check_all_filtered(repo, &[]).map(|(report, _)| report)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Adr;

    #[test]
    fn test_issue_severity_ordering() {
        assert!(IssueSeverity::Error > IssueSeverity::Warning);
        assert!(IssueSeverity::Warning > IssueSeverity::Info);
    }

    #[test]
    fn test_lint_report_empty() {
        let report = LintReport::new();
        assert!(report.is_clean());
        assert!(!report.has_errors());
        assert!(!report.has_warnings());
    }

    #[test]
    fn test_lint_report_with_issues() {
        let mut report = LintReport::new();
        report.add(Issue {
            rule_id: "ADR001".to_string(),
            rule_name: "adr-title-format".to_string(),
            severity: IssueSeverity::Error,
            message: "Title format invalid".to_string(),
            path: Some(PathBuf::from("0001-test.md")),
            line: Some(1),
            column: Some(1),
            adr_number: Some(1),
            related_adrs: Vec::new(),
        });

        assert!(report.has_errors());
        assert!(!report.is_clean());
        assert_eq!(report.count_by_severity(IssueSeverity::Error), 1);
    }

    #[test]
    fn test_lint_valid_nygard_adr() {
        // Uses the actual ADR #0001 text produced by `adrs init`. The word "described"
        // previously triggered an ADR014 false positive (fixed in mdbook-lint-rulesets 0.14.3).
        let content = r#"# 1. Record architecture decisions

Date: 2024-03-04

## Status

Accepted

## Context

We need to record the architectural decisions made on this project.

## Decision

We will use Architecture Decision Records, as described by Michael Nygard in his article "Documenting Architecture Decisions".

## Consequences

See Michael Nygard's article, linked above. For a lightweight ADR toolset, see Nat Pryce's adr-tools.
"#;
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir
            .path()
            .join("adr")
            .join("0001-record-architecture-decisions.md");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, content).unwrap();

        let mut adr = Adr::new(1, "Record architecture decisions");
        adr.path = Some(path);

        let report = lint_adr(&adr).unwrap();

        // Print any issues for debugging
        for issue in &report.issues {
            println!(
                "{}: {} ({}:{})",
                issue.rule_id,
                issue.message,
                issue.line.unwrap_or(0),
                issue.column.unwrap_or(0)
            );
        }

        assert!(report.is_clean(), "Expected no issues for valid Nygard ADR");
    }

    #[test]
    fn test_lint_invalid_adr_missing_status() {
        let content = r#"# 1. Test decision

Date: 2024-03-04

## Context

Some context.

## Decision

Some decision.

## Consequences

Some consequences.
"#;
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("adr").join("0001-test-decision.md");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, content).unwrap();

        let mut adr = Adr::new(1, "Test decision");
        adr.path = Some(path);

        let report = lint_adr(&adr).unwrap();

        // Should have at least one issue (missing status)
        assert!(
            !report.is_clean(),
            "Expected issues for ADR missing status section"
        );
        assert!(
            report.issues.iter().any(|i| i.rule_id == "ADR002"),
            "Expected ADR002 (missing status) violation"
        );
    }

    #[test]
    fn test_nygard_bare_minimal_template_passes_doctor() {
        // Regression for #330: a file produced by the Nygard bare-minimal
        // template must not trip any doctor error (it previously emitted no
        // `Date:` line and failed with ADR003). Empty-section ADR014 warnings
        // are inherent to the variant and are not errors.
        use crate::{Adr, Config, Repository, Template, TemplateFormat, TemplateVariant};

        let temp = tempfile::tempdir().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let template =
            Template::builtin_with_variant(TemplateFormat::Nygard, TemplateVariant::BareMinimal);
        let adr = Adr::new(2, "Bare minimal regression");
        let rendered = template
            .render(&adr, &Config::default(), &std::collections::HashMap::new())
            .unwrap();
        let path = repo.adr_path().join("0002-bare-minimal-regression.md");
        std::fs::write(&path, rendered).unwrap();

        let report = check_all(&repo).unwrap();
        let file_errors: Vec<_> = report
            .issues
            .iter()
            .filter(|i| i.severity == IssueSeverity::Error)
            .filter(|i| {
                i.path
                    .as_ref()
                    .is_some_and(|p| p.to_string_lossy().contains("0002-bare-minimal-regression"))
            })
            .collect();
        assert!(
            file_errors.is_empty(),
            "nygard bare-minimal output should have no doctor errors, got: {file_errors:?}"
        );
    }

    #[test]
    fn test_check_all_reports_parse_errors() {
        use crate::Repository;

        let temp = tempfile::tempdir().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        // Write an ADR with invalid YAML (bad date)
        let bad_content =
            "---\nnumber: 2\nstatus: accepted\ndate: not-a-date\n---\n\n# 2. Bad Date\n";
        std::fs::write(repo.adr_path().join("0002-bad-date.md"), bad_content).unwrap();

        let report = check_all(&repo).unwrap();

        let parse_errors: Vec<_> = report
            .issues
            .iter()
            .filter(|i| i.rule_id == "parse-error")
            .collect();

        assert_eq!(parse_errors.len(), 1, "should report 1 parse error");
        assert_eq!(parse_errors[0].severity, IssueSeverity::Error);
        assert!(
            parse_errors[0]
                .path
                .as_ref()
                .unwrap()
                .to_string_lossy()
                .contains("0002-bad-date.md")
        );
    }

    #[test]
    fn test_check_all_no_parse_errors_for_string_decision_makers() {
        use crate::Repository;

        let temp = tempfile::tempdir().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        // Issue #216: decision-makers as string should not cause a parse error
        let content = "---\nnumber: 2\nstatus: accepted\ndate: 2026-03-18\ndecision-makers: alice\n---\n\n# 2. Test\n\n## Context\n\nContext.\n\n## Decision\n\nDecision.\n\n## Consequences\n\nConsequences.\n";
        std::fs::write(repo.adr_path().join("0002-test.md"), content).unwrap();

        let report = check_all(&repo).unwrap();

        let parse_errors: Vec<_> = report
            .issues
            .iter()
            .filter(|i| i.rule_id == "parse-error")
            .collect();

        assert!(
            parse_errors.is_empty(),
            "string decision-makers should not cause parse error, got: {:?}",
            parse_errors.iter().map(|i| &i.message).collect::<Vec<_>>()
        );
    }
    // ========== check_repository collection rules (issue #239) ==========

    fn make_nygard_adr(number: u32, title: &str, status: &str, links: &str) -> String {
        format!(
            "# {}. {}\n\nDate: 2024-01-01\n\n## Status\n\n{}{}\n## Context\n\nSome context.\n\n## Decision\n\nA decision.\n\n## Consequences\n\nSome consequences.\n",
            number, title, status, links
        )
    }

    #[test]
    fn test_check_repository_broken_link_adr013() {
        use crate::Repository;

        let temp = tempfile::tempdir().unwrap();
        // init creates ADR #1 automatically
        let repo = Repository::init(temp.path(), None, false).unwrap();
        let adr_dir = repo.adr_path();

        // ADR 2 links to nonexistent ADR 99
        std::fs::write(
            adr_dir.join("0002-second.md"),
            make_nygard_adr(
                2,
                "Second",
                "Accepted",
                "\n\nSupersedes [99. Unknown](0099-unknown.md)\n",
            ),
        )
        .unwrap();

        let report = check_repository(&repo).unwrap();

        // Should have an ADR013 (broken links) issue
        let has_adr013 = report.issues.iter().any(|i| i.rule_id == "ADR013");
        assert!(
            has_adr013,
            "Expected ADR013 broken-link issue, got: {:?}",
            report.issues.iter().map(|i| &i.rule_id).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_check_repository_sequential_gap_adr011() {
        use crate::Repository;

        let temp = tempfile::tempdir().unwrap();
        // init creates ADR #1 automatically; write #2 and #4 to create a gap at #3
        let repo = Repository::init(temp.path(), None, false).unwrap();
        let adr_dir = repo.adr_path();

        // ADRs 1, 2, 4 -- gap at 3
        std::fs::write(
            adr_dir.join("0002-second.md"),
            make_nygard_adr(2, "Second", "Accepted", ""),
        )
        .unwrap();
        std::fs::write(
            adr_dir.join("0004-fourth.md"),
            make_nygard_adr(4, "Fourth", "Accepted", ""),
        )
        .unwrap();

        let report = check_repository(&repo).unwrap();

        // Should have an ADR011 (sequential gap) issue
        let has_adr011 = report.issues.iter().any(|i| i.rule_id == "ADR011");
        assert!(
            has_adr011,
            "Expected ADR011 sequential-gap issue, got: {:?}",
            report.issues.iter().map(|i| &i.rule_id).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_check_repository_clean_repo_has_no_issues() {
        use crate::Repository;

        let temp = tempfile::tempdir().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        let adr_dir = repo.adr_path();

        // Repository::init creates ADR #1 automatically -- use #2 and #3 to avoid duplicate
        std::fs::write(
            adr_dir.join("0002-second.md"),
            make_nygard_adr(2, "Second", "Accepted", ""),
        )
        .unwrap();
        std::fs::write(
            adr_dir.join("0003-third.md"),
            make_nygard_adr(3, "Third", "Proposed", ""),
        )
        .unwrap();

        let report = check_repository(&repo).unwrap();

        let collection_rule_ids = ["ADR010", "ADR011", "ADR012", "ADR013"];
        let collection_issues: Vec<_> = report
            .issues
            .iter()
            .filter(|i| collection_rule_ids.contains(&i.rule_id.as_str()))
            .collect();

        assert!(
            collection_issues.is_empty(),
            "Clean repo should have no collection-rule issues, got: {:?}",
            collection_issues
                .iter()
                .map(|i| format!("{}: {}", i.rule_id, i.message))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_check_all_combines_lint_and_repository_checks() {
        use crate::Repository;

        let temp = tempfile::tempdir().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        let adr_dir = repo.adr_path();

        // Create a valid ADR so check_all has something to process
        std::fs::write(
            adr_dir.join("0001-first.md"),
            make_nygard_adr(1, "First", "Accepted", ""),
        )
        .unwrap();

        // check_all should succeed and return a report
        let report = check_all(&repo).unwrap();

        // With a valid sequential repo, no collection-rule violations
        let adr011 = report
            .issues
            .iter()
            .filter(|i| i.rule_id == "ADR011")
            .count();
        assert_eq!(
            adr011, 0,
            "Single valid ADR should have no sequential-gap issue"
        );
    }

    // ========== check_all_filtered / [doctor].ignore (issue #316) ==========

    #[test]
    fn test_check_all_filtered_suppresses_ignored_rule() {
        use crate::Repository;

        let temp = tempfile::tempdir().unwrap();
        // init creates ADR #1 automatically; write #2 and #4 to create a gap at #3,
        // which trips ADR011 (Warning severity, confirmed via
        // test_check_repository_sequential_gap_adr011).
        let repo = Repository::init(temp.path(), None, false).unwrap();
        let adr_dir = repo.adr_path();
        std::fs::write(
            adr_dir.join("0002-second.md"),
            make_nygard_adr(2, "Second", "Accepted", ""),
        )
        .unwrap();
        std::fs::write(
            adr_dir.join("0004-fourth.md"),
            make_nygard_adr(4, "Fourth", "Accepted", ""),
        )
        .unwrap();

        // Unfiltered: check_repository still reports ADR011.
        let unfiltered = check_repository(&repo).unwrap();
        let unfiltered_adr011 = unfiltered
            .issues
            .iter()
            .filter(|i| i.rule_id == "ADR011")
            .count();
        assert!(
            unfiltered_adr011 > 0,
            "expected check_repository to report ADR011 before filtering"
        );

        // Write adrs.toml with a lowercase ignore entry, then re-open the repository
        // so the config is loaded from disk (Repository::init keeps the in-memory
        // config it built at creation time).
        std::fs::write(
            temp.path().join("adrs.toml"),
            "adr_dir = \"doc/adr\"\n\n[doctor]\nignore = [\"adr011\"]\n",
        )
        .unwrap();
        let repo = Repository::open(temp.path()).unwrap();
        assert_eq!(repo.config().doctor.ignore, vec!["adr011".to_string()]);

        // check_all (and check_all_filtered) should no longer contain ADR011,
        // proving case-insensitive matching against the real rule_id "ADR011".
        let filtered = check_all(&repo).unwrap();
        let filtered_adr011 = filtered
            .issues
            .iter()
            .filter(|i| i.rule_id == "ADR011")
            .count();
        assert_eq!(
            filtered_adr011, 0,
            "check_all should suppress ADR011 issues per [doctor].ignore"
        );

        // check_repository (unfiltered) should still report ADR011 -- filtering
        // is check_all-level only.
        let still_unfiltered = check_repository(&repo).unwrap();
        assert!(
            still_unfiltered
                .issues
                .iter()
                .any(|i| i.rule_id == "ADR011"),
            "check_repository should remain unfiltered"
        );
    }

    #[test]
    fn test_check_all_filtered_returns_suppressed_count() {
        use crate::Repository;

        let temp = tempfile::tempdir().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        let adr_dir = repo.adr_path();
        std::fs::write(
            adr_dir.join("0002-second.md"),
            make_nygard_adr(2, "Second", "Accepted", ""),
        )
        .unwrap();
        std::fs::write(
            adr_dir.join("0004-fourth.md"),
            make_nygard_adr(4, "Fourth", "Accepted", ""),
        )
        .unwrap();

        let unfiltered = check_all(&repo).unwrap();
        let unfiltered_adr011 = unfiltered
            .issues
            .iter()
            .filter(|i| i.rule_id == "ADR011")
            .count();
        assert!(unfiltered_adr011 > 0);

        std::fs::write(
            temp.path().join("adrs.toml"),
            "adr_dir = \"doc/adr\"\n\n[doctor]\nignore = [\"ADR011\"]\n",
        )
        .unwrap();
        let repo = Repository::open(temp.path()).unwrap();

        let (filtered, suppressed_count) = check_all_filtered(&repo, &[]).unwrap();
        assert_eq!(suppressed_count, unfiltered_adr011);
        assert!(
            filtered.issues.iter().all(|i| i.rule_id != "ADR011"),
            "filtered report should not contain ADR011"
        );
    }
}