adrs-core 0.7.3

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
//! Health checks for ADR repositories.

use crate::{Adr, Repository, Result};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

/// The severity level of a diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    /// Informational message.
    Info,
    /// Warning that should be addressed.
    Warning,
    /// Error that needs to be fixed.
    Error,
}

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

/// A diagnostic message from a health check.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    /// The severity of this diagnostic.
    pub severity: Severity,
    /// The check that produced this diagnostic.
    pub check: Check,
    /// A human-readable message describing the issue.
    pub message: String,
    /// The path to the affected file, if applicable.
    pub path: Option<PathBuf>,
    /// The ADR number, if applicable.
    pub adr_number: Option<u32>,
}

impl Diagnostic {
    /// Create a new diagnostic.
    pub fn new(severity: Severity, check: Check, message: impl Into<String>) -> Self {
        Self {
            severity,
            check,
            message: message.into(),
            path: None,
            adr_number: None,
        }
    }

    /// Set the path for this diagnostic.
    pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Set the ADR number for this diagnostic.
    pub fn with_adr(mut self, number: u32) -> Self {
        self.adr_number = Some(number);
        self
    }
}

/// The type of health check.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Check {
    /// Check for duplicate ADR numbers.
    DuplicateNumbers,
    /// Check for proper file naming (4-digit padded IDs).
    FileNaming,
    /// Check that all ADRs have a status.
    MissingStatus,
    /// Check that linked ADRs exist.
    BrokenLinks,
    /// Check for sequential numbering gaps.
    NumberingGaps,
    /// Check that superseded ADRs have a superseding link.
    SupersededLinks,
}

impl std::fmt::Display for Check {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Check::DuplicateNumbers => write!(f, "duplicate-numbers"),
            Check::FileNaming => write!(f, "file-naming"),
            Check::MissingStatus => write!(f, "missing-status"),
            Check::BrokenLinks => write!(f, "broken-links"),
            Check::NumberingGaps => write!(f, "numbering-gaps"),
            Check::SupersededLinks => write!(f, "superseded-links"),
        }
    }
}

/// Results from running health checks.
#[derive(Debug, Default)]
pub struct DoctorReport {
    /// All diagnostics found.
    pub diagnostics: Vec<Diagnostic>,
}

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

    /// Add a diagnostic to the report.
    pub fn add(&mut self, diagnostic: Diagnostic) {
        self.diagnostics.push(diagnostic);
    }

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

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

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

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

/// Run all health checks on a repository.
pub fn check(repo: &Repository) -> Result<DoctorReport> {
    let adrs = repo.list()?;
    let mut report = DoctorReport::new();

    check_duplicate_numbers(&adrs, &mut report);
    check_file_naming(&adrs, &mut report);
    check_missing_status(&adrs, &mut report);
    check_broken_links(&adrs, &mut report);
    check_numbering_gaps(&adrs, &mut report);
    check_superseded_links(&adrs, &mut report);

    // Sort diagnostics by severity (errors first)
    report
        .diagnostics
        .sort_by(|a, b| b.severity.cmp(&a.severity));

    Ok(report)
}

/// Check for duplicate ADR numbers.
fn check_duplicate_numbers(adrs: &[Adr], report: &mut DoctorReport) {
    let mut seen: HashMap<u32, Vec<&Adr>> = HashMap::new();

    for adr in adrs {
        seen.entry(adr.number).or_default().push(adr);
    }

    for (number, duplicates) in seen {
        if duplicates.len() > 1 {
            let paths: Vec<_> = duplicates
                .iter()
                .filter_map(|a| a.path.as_ref().and_then(|p| p.file_name()))
                .map(|p| p.to_string_lossy())
                .collect();

            report.add(
                Diagnostic::new(
                    Severity::Error,
                    Check::DuplicateNumbers,
                    format!(
                        "ADR number {} is used by multiple files: {}",
                        number,
                        paths.join(", ")
                    ),
                )
                .with_adr(number),
            );
        }
    }
}

/// Check for proper file naming (4-digit padded IDs).
fn check_file_naming(adrs: &[Adr], report: &mut DoctorReport) {
    for adr in adrs {
        if let Some(path) = &adr.path
            && let Some(filename) = path.file_name().and_then(|f| f.to_str())
        {
            let expected_prefix = format!("{:04}-", adr.number);
            if !filename.starts_with(&expected_prefix) {
                report.add(
                    Diagnostic::new(
                        Severity::Warning,
                        Check::FileNaming,
                        format!(
                            "File '{}' should start with '{}'",
                            filename, expected_prefix
                        ),
                    )
                    .with_path(path)
                    .with_adr(adr.number),
                );
            }
        }
    }
}

/// Check that all ADRs have a status.
fn check_missing_status(adrs: &[Adr], report: &mut DoctorReport) {
    use crate::AdrStatus;

    for adr in adrs {
        // Check for custom empty status
        if let AdrStatus::Custom(s) = &adr.status
            && s.trim().is_empty()
        {
            report.add(
                Diagnostic::new(
                    Severity::Warning,
                    Check::MissingStatus,
                    format!("ADR {} '{}' has an empty status", adr.number, adr.title),
                )
                .with_path(adr.path.clone().unwrap_or_default())
                .with_adr(adr.number),
            );
        }
    }
}

/// Check that linked ADRs exist.
fn check_broken_links(adrs: &[Adr], report: &mut DoctorReport) {
    let existing_numbers: HashSet<u32> = adrs.iter().map(|a| a.number).collect();

    for adr in adrs {
        for link in &adr.links {
            if !existing_numbers.contains(&link.target) {
                report.add(
                    Diagnostic::new(
                        Severity::Error,
                        Check::BrokenLinks,
                        format!(
                            "ADR {} '{}' links to non-existent ADR {}",
                            adr.number, adr.title, link.target
                        ),
                    )
                    .with_path(adr.path.clone().unwrap_or_default())
                    .with_adr(adr.number),
                );
            }
        }
    }
}

/// Check for gaps in sequential numbering.
fn check_numbering_gaps(adrs: &[Adr], report: &mut DoctorReport) {
    if adrs.is_empty() {
        return;
    }

    let mut numbers: Vec<u32> = adrs.iter().map(|a| a.number).collect();
    numbers.sort();
    numbers.dedup();

    let min = *numbers.first().unwrap();
    let max = *numbers.last().unwrap();

    let missing: Vec<u32> = (min..=max).filter(|n| !numbers.contains(n)).collect();

    if !missing.is_empty() {
        let missing_str = if missing.len() <= 5 {
            missing
                .iter()
                .map(|n| n.to_string())
                .collect::<Vec<_>>()
                .join(", ")
        } else {
            format!(
                "{}, ... ({} total)",
                missing[..3]
                    .iter()
                    .map(|n| n.to_string())
                    .collect::<Vec<_>>()
                    .join(", "),
                missing.len()
            )
        };

        report.add(Diagnostic::new(
            Severity::Info,
            Check::NumberingGaps,
            format!("Missing ADR numbers in sequence: {}", missing_str),
        ));
    }
}

/// Check that superseded ADRs have proper links.
fn check_superseded_links(adrs: &[Adr], report: &mut DoctorReport) {
    use crate::{AdrStatus, LinkKind};

    for adr in adrs {
        if adr.status == AdrStatus::Superseded {
            let has_superseded_by_link = adr
                .links
                .iter()
                .any(|link| link.kind == LinkKind::SupersededBy);

            if !has_superseded_by_link {
                report.add(
                    Diagnostic::new(
                        Severity::Warning,
                        Check::SupersededLinks,
                        format!(
                            "ADR {} '{}' has status 'Superseded' but no 'Superseded by' link",
                            adr.number, adr.title
                        ),
                    )
                    .with_path(adr.path.clone().unwrap_or_default())
                    .with_adr(adr.number),
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AdrLink, AdrStatus, LinkKind};

    #[test]
    fn test_duplicate_numbers() {
        let adrs = vec![
            {
                let mut adr = Adr::new(1, "First");
                adr.path = Some(PathBuf::from("0001-first.md"));
                adr
            },
            {
                let mut adr = Adr::new(1, "Duplicate");
                adr.path = Some(PathBuf::from("0001-duplicate.md"));
                adr
            },
        ];

        let mut report = DoctorReport::new();
        check_duplicate_numbers(&adrs, &mut report);

        assert_eq!(report.diagnostics.len(), 1);
        assert_eq!(report.diagnostics[0].severity, Severity::Error);
        assert_eq!(report.diagnostics[0].check, Check::DuplicateNumbers);
    }

    #[test]
    fn test_file_naming() {
        let adrs = vec![{
            let mut adr = Adr::new(1, "Test");
            adr.path = Some(PathBuf::from("1-test.md")); // Missing padding
            adr
        }];

        let mut report = DoctorReport::new();
        check_file_naming(&adrs, &mut report);

        assert_eq!(report.diagnostics.len(), 1);
        assert_eq!(report.diagnostics[0].severity, Severity::Warning);
        assert_eq!(report.diagnostics[0].check, Check::FileNaming);
    }

    #[test]
    fn test_broken_links() {
        let adrs = vec![{
            let mut adr = Adr::new(1, "Test");
            adr.links.push(AdrLink {
                target: 99, // Doesn't exist
                kind: LinkKind::Supersedes,
                description: None,
            });
            adr
        }];

        let mut report = DoctorReport::new();
        check_broken_links(&adrs, &mut report);

        assert_eq!(report.diagnostics.len(), 1);
        assert_eq!(report.diagnostics[0].severity, Severity::Error);
        assert_eq!(report.diagnostics[0].check, Check::BrokenLinks);
    }

    #[test]
    fn test_numbering_gaps() {
        let adrs = vec![
            Adr::new(1, "First"),
            Adr::new(3, "Third"), // Missing 2
            Adr::new(5, "Fifth"), // Missing 4
        ];

        let mut report = DoctorReport::new();
        check_numbering_gaps(&adrs, &mut report);

        assert_eq!(report.diagnostics.len(), 1);
        assert_eq!(report.diagnostics[0].severity, Severity::Info);
        assert!(report.diagnostics[0].message.contains("2"));
        assert!(report.diagnostics[0].message.contains("4"));
    }

    #[test]
    fn test_superseded_without_link() {
        let adrs = vec![{
            let mut adr = Adr::new(1, "Old Decision");
            adr.status = AdrStatus::Superseded;
            // No SupersededBy link
            adr
        }];

        let mut report = DoctorReport::new();
        check_superseded_links(&adrs, &mut report);

        assert_eq!(report.diagnostics.len(), 1);
        assert_eq!(report.diagnostics[0].severity, Severity::Warning);
        assert_eq!(report.diagnostics[0].check, Check::SupersededLinks);
    }

    #[test]
    fn test_healthy_repo() {
        let adrs = vec![
            {
                let mut adr = Adr::new(1, "First");
                adr.path = Some(PathBuf::from("0001-first.md"));
                adr.status = AdrStatus::Accepted;
                adr
            },
            {
                let mut adr = Adr::new(2, "Second");
                adr.path = Some(PathBuf::from("0002-second.md"));
                adr.status = AdrStatus::Proposed;
                adr
            },
        ];

        let mut report = DoctorReport::new();
        check_duplicate_numbers(&adrs, &mut report);
        check_file_naming(&adrs, &mut report);
        check_broken_links(&adrs, &mut report);
        check_numbering_gaps(&adrs, &mut report);
        check_superseded_links(&adrs, &mut report);

        assert!(report.is_healthy());
    }
}