docpact 0.1.1

Deterministic documentation governance CLI for AI-assisted software teams.
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
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use miette::Result;
use serde::Serialize;

use crate::AppExit;
use crate::cli::{DoctorArgs, DoctorOutputFormat};
use crate::config::{
    CONFIG_FILE, ConfigBlockSourceKind, EffectiveConfig, ImpactLayout, detect_impact_layout,
    load_effective_configs, normalize_path, path_relative_to, resolve_rule_path,
    root_dir_from_option,
};

pub const DOCTOR_SCHEMA_VERSION: &str = "docpact.doctor.v1";

const CODE_MISSING_CONFIG: &str = "missing-config";
const CODE_CONFIG_LOAD_FAILED: &str = "config-load-failed";
const CODE_EMPTY_RULE_GRAPH: &str = "empty-rule-graph";
const CODE_MISSING_COVERAGE_SCOPE: &str = "missing-coverage-scope";
const CODE_MISSING_GOVERNED_DOCS: &str = "missing-governed-docs";
const CODE_MISSING_DOC_INVENTORY: &str = "missing-doc-inventory";
const CODE_MISSING_FRESHNESS_CONFIG: &str = "missing-freshness-config";

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct DoctorReport {
    pub schema_version: String,
    pub tool_name: String,
    pub tool_version: String,
    pub summary: DoctorSummary,
    pub configs: Vec<DoctorConfig>,
    pub findings: Vec<DoctorFinding>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct DoctorSummary {
    pub config_present: bool,
    pub layout: String,
    pub effective_config_count: usize,
    pub inherited_config_count: usize,
    pub rule_count: usize,
    pub coverage_configured: bool,
    pub routing_configured: bool,
    pub doc_inventory_configured: bool,
    pub freshness_configured: bool,
    pub routing_intent_count: usize,
    pub governed_doc_count: usize,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct DoctorConfig {
    pub source: String,
    pub base_dir: String,
    pub rule_count: usize,
    pub governed_doc_count: usize,
    pub inheritance_enabled: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_profile: Option<String>,
    pub coverage_resolution: String,
    pub routing_resolution: String,
    pub doc_inventory_resolution: String,
    pub freshness_resolution: String,
    pub routing_intent_count: usize,
    pub override_add_count: usize,
    pub override_replace_count: usize,
    pub override_disable_count: usize,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct DoctorFinding {
    pub code: String,
    pub severity: String,
    pub message: String,
    pub source: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum DoctorSeverity {
    Warn,
    Error,
}

impl DoctorSeverity {
    fn as_str(self) -> &'static str {
        match self {
            Self::Warn => "warn",
            Self::Error => "error",
        }
    }
}

pub fn run(args: DoctorArgs) -> Result<AppExit> {
    let report = execute(&args)?;
    emit_report(&report, args.format);
    Ok(AppExit::Success)
}

pub fn execute(args: &DoctorArgs) -> Result<DoctorReport> {
    let root_dir = root_dir_from_option(args.root.as_deref())?;
    let config_path = resolve_config_path(&root_dir, args.config.as_deref());
    let config_source = display_config_source(&root_dir, &config_path);

    if !config_path.exists() {
        return Ok(report_with_findings(
            DoctorSummary {
                config_present: false,
                layout: "none".into(),
                effective_config_count: 0,
                inherited_config_count: 0,
                rule_count: 0,
                coverage_configured: false,
                routing_configured: false,
                doc_inventory_configured: false,
                freshness_configured: false,
                routing_intent_count: 0,
                governed_doc_count: 0,
            },
            Vec::new(),
            vec![DoctorFinding {
                code: CODE_MISSING_CONFIG.into(),
                severity: DoctorSeverity::Error.as_str().into(),
                message: format!(
                    "No docpact config was found at `{}`. Create a config before onboarding the repository.",
                    config_source
                ),
                source: config_source,
            }],
        ));
    }

    let layout = match detect_impact_layout(&root_dir, args.config.as_deref()) {
        Ok(layout) => layout,
        Err(error) => {
            let message = error.to_string();
            let source = extract_config_source(&message).unwrap_or_else(|| config_source.clone());
            return Ok(report_with_findings(
                DoctorSummary {
                    config_present: true,
                    layout: "unknown".into(),
                    effective_config_count: 0,
                    inherited_config_count: 0,
                    rule_count: 0,
                    coverage_configured: false,
                    routing_configured: false,
                    doc_inventory_configured: false,
                    freshness_configured: false,
                    routing_intent_count: 0,
                    governed_doc_count: 0,
                },
                Vec::new(),
                vec![DoctorFinding {
                    code: CODE_CONFIG_LOAD_FAILED.into(),
                    severity: DoctorSeverity::Error.as_str().into(),
                    message,
                    source,
                }],
            ));
        }
    };

    let effective_configs = match load_effective_configs(&root_dir, args.config.as_deref()) {
        Ok(configs) => configs,
        Err(error) => {
            let message = error.to_string();
            let source = extract_config_source(&message).unwrap_or_else(|| config_source.clone());
            return Ok(report_with_findings(
                DoctorSummary {
                    config_present: true,
                    layout: layout_label(layout).into(),
                    effective_config_count: 0,
                    inherited_config_count: 0,
                    rule_count: 0,
                    coverage_configured: false,
                    routing_configured: false,
                    doc_inventory_configured: false,
                    freshness_configured: false,
                    routing_intent_count: 0,
                    governed_doc_count: 0,
                },
                Vec::new(),
                vec![DoctorFinding {
                    code: CODE_CONFIG_LOAD_FAILED.into(),
                    severity: DoctorSeverity::Error.as_str().into(),
                    message,
                    source,
                }],
            ));
        }
    };

    let configs = build_doctor_configs(&effective_configs);
    let rule_count = effective_configs
        .iter()
        .map(|config| config.rules.len())
        .sum();
    let governed_doc_count = effective_configs
        .iter()
        .flat_map(|config| {
            config.rules.iter().flat_map(|loaded| {
                loaded
                    .rule
                    .required_docs
                    .iter()
                    .map(|doc| resolve_rule_path(&loaded.base_dir, &doc.path))
            })
        })
        .collect::<BTreeSet<_>>()
        .len();
    let coverage_configured = effective_configs.iter().any(|config| {
        !config.coverage.coverage.include.is_empty() || !config.coverage.coverage.exclude.is_empty()
    });
    let doc_inventory_configured = effective_configs.iter().any(|config| {
        !config.doc_inventory.doc_inventory.include.is_empty()
            || !config.doc_inventory.doc_inventory.exclude.is_empty()
    });
    let routing_configured = effective_configs
        .iter()
        .any(|config| !config.routing.routing.intents.is_empty());
    let freshness_configured = effective_configs
        .iter()
        .any(|config| config.freshness.resolution.origin_kind != ConfigBlockSourceKind::Default);
    let routing_intent_count = effective_configs
        .iter()
        .map(|config| config.routing.routing.intents.len())
        .sum();
    let inherited_config_count = effective_configs
        .iter()
        .filter(|config| config.inheritance.is_some())
        .count();

    let summary = DoctorSummary {
        config_present: true,
        layout: layout_label(layout).into(),
        effective_config_count: effective_configs.len(),
        inherited_config_count,
        rule_count,
        coverage_configured,
        routing_configured,
        doc_inventory_configured,
        freshness_configured,
        routing_intent_count,
        governed_doc_count,
    };

    let mut findings = Vec::new();
    if summary.rule_count == 0 {
        findings.push(DoctorFinding {
            code: CODE_EMPTY_RULE_GRAPH.into(),
            severity: DoctorSeverity::Error.as_str().into(),
            message:
                "The loaded config graph contains zero rules. Add at least one rule before relying on docpact enforcement."
                    .into(),
            source: config_source.clone(),
        });
    } else {
        if summary.governed_doc_count == 0 {
            findings.push(DoctorFinding {
                code: CODE_MISSING_GOVERNED_DOCS.into(),
                severity: DoctorSeverity::Error.as_str().into(),
                message:
                    "The loaded rules do not resolve to any governed required docs. Add `requiredDocs` targets before using lint as a governance signal."
                        .into(),
                source: config_source.clone(),
            });
        }

        if !summary.coverage_configured {
            findings.push(DoctorFinding {
                code: CODE_MISSING_COVERAGE_SCOPE.into(),
                severity: DoctorSeverity::Warn.as_str().into(),
                message:
                    "No coverage scope is configured; diff coverage defaults to all changed paths. Configure `coverage.include` or `coverage.exclude` if the intended governance scope is narrower."
                        .into(),
                source: config_source.clone(),
            });
        }

        if !summary.doc_inventory_configured {
            findings.push(DoctorFinding {
                code: CODE_MISSING_DOC_INVENTORY.into(),
                severity: DoctorSeverity::Warn.as_str().into(),
                message:
                    "No explicit doc inventory scope is configured; repository coverage audit will infer inventory from all tracked Markdown/YAML docs."
                        .into(),
                source: config_source.clone(),
            });
        }

        if !summary.freshness_configured {
            findings.push(DoctorFinding {
                code: CODE_MISSING_FRESHNESS_CONFIG.into(),
                severity: DoctorSeverity::Warn.as_str().into(),
                message:
                    "No explicit freshness config is present; repository freshness audit falls back to default thresholds."
                        .into(),
                source: config_source,
            });
        }
    }

    findings.sort_by(|left, right| {
        (&left.severity, &left.code, &left.source, &left.message).cmp(&(
            &right.severity,
            &right.code,
            &right.source,
            &right.message,
        ))
    });

    Ok(report_with_findings(summary, configs, findings))
}

fn report_with_findings(
    summary: DoctorSummary,
    configs: Vec<DoctorConfig>,
    findings: Vec<DoctorFinding>,
) -> DoctorReport {
    DoctorReport {
        schema_version: DOCTOR_SCHEMA_VERSION.into(),
        tool_name: env!("CARGO_PKG_NAME").into(),
        tool_version: env!("CARGO_PKG_VERSION").into(),
        summary,
        configs,
        findings,
    }
}

fn emit_report(report: &DoctorReport, format: DoctorOutputFormat) {
    match format {
        DoctorOutputFormat::Text => emit_text_report(report),
        DoctorOutputFormat::Json => println!(
            "{}",
            serde_json::to_string_pretty(report).expect("doctor report should serialize")
        ),
    }
}

fn emit_text_report(report: &DoctorReport) {
    println!("Docpact doctor:");
    println!(
        "Summary: config_present={}, layout={}, effective_configs={}, inherited_configs={}, rule_count={}, coverage_configured={}, routing_configured={}, doc_inventory_configured={}, freshness_configured={}, routing_intents={}, governed_doc_count={}",
        report.summary.config_present,
        report.summary.layout,
        report.summary.effective_config_count,
        report.summary.inherited_config_count,
        report.summary.rule_count,
        report.summary.coverage_configured,
        report.summary.routing_configured,
        report.summary.doc_inventory_configured,
        report.summary.freshness_configured,
        report.summary.routing_intent_count,
        report.summary.governed_doc_count,
    );
    println!("Configs:");
    if report.configs.is_empty() {
        println!("- none");
    } else {
        for config in &report.configs {
            println!(
                "- source={} base_dir={} inherited={} profile={} rules={} governed_docs={} coverage_resolution={} routing_resolution={} doc_inventory_resolution={} freshness_resolution={} routing_intents={} overrides(add={},replace={},disable={})",
                config.source,
                if config.base_dir.is_empty() {
                    ".".to_string()
                } else {
                    config.base_dir.clone()
                },
                config.inheritance_enabled,
                config
                    .workspace_profile
                    .clone()
                    .unwrap_or_else(|| "-".into()),
                config.rule_count,
                config.governed_doc_count,
                config.coverage_resolution,
                config.routing_resolution,
                config.doc_inventory_resolution,
                config.freshness_resolution,
                config.routing_intent_count,
                config.override_add_count,
                config.override_replace_count,
                config.override_disable_count,
            );
        }
    }
    println!("Findings:");
    if report.findings.is_empty() {
        println!("- none");
        return;
    }

    for finding in &report.findings {
        println!(
            "- [{}] {} {}: {}",
            finding.severity, finding.code, finding.source, finding.message
        );
    }
}

fn resolve_config_path(root_dir: &Path, config_override: Option<&Path>) -> PathBuf {
    match config_override {
        Some(path) => path.to_path_buf(),
        None => root_dir.join(CONFIG_FILE),
    }
}

fn display_config_source(root_dir: &Path, path: &Path) -> String {
    if path.is_absolute() {
        path_relative_to(root_dir, path)
    } else {
        normalize_path(&path.to_string_lossy())
    }
}

fn layout_label(layout: ImpactLayout) -> &'static str {
    match layout {
        ImpactLayout::Repo => "repo",
        ImpactLayout::Workspace => "workspace",
        ImpactLayout::None => "none",
    }
}

fn extract_config_source(message: &str) -> Option<String> {
    for marker in [
        " is not a valid docpact config file.",
        " is not valid YAML for docpact.",
    ] {
        if let Some(index) = message.find(marker) {
            return Some(message[..index].to_string());
        }
    }
    None
}

fn build_doctor_configs(effective_configs: &[EffectiveConfig]) -> Vec<DoctorConfig> {
    effective_configs
        .iter()
        .map(|config| {
            let governed_doc_count = config
                .rules
                .iter()
                .flat_map(|loaded| {
                    loaded
                        .rule
                        .required_docs
                        .iter()
                        .map(|doc| resolve_rule_path(&loaded.base_dir, &doc.path))
                })
                .collect::<BTreeSet<_>>()
                .len();

            DoctorConfig {
                source: config.source.clone(),
                base_dir: config.base_dir.clone(),
                rule_count: config.rules.len(),
                governed_doc_count,
                inheritance_enabled: config.inheritance.is_some(),
                workspace_profile: config
                    .inheritance
                    .as_ref()
                    .map(|inheritance| inheritance.workspace_profile.clone()),
                coverage_resolution: config.coverage.resolution.origin_kind.as_str().into(),
                routing_resolution: config.routing.resolution.origin_kind.as_str().into(),
                doc_inventory_resolution: config
                    .doc_inventory
                    .resolution
                    .origin_kind
                    .as_str()
                    .into(),
                freshness_resolution: config.freshness.resolution.origin_kind.as_str().into(),
                routing_intent_count: config.routing.routing.intents.len(),
                override_add_count: config
                    .inheritance
                    .as_ref()
                    .map(|inheritance| inheritance.add_count)
                    .unwrap_or(0),
                override_replace_count: config
                    .inheritance
                    .as_ref()
                    .map(|inheritance| inheritance.replace_count)
                    .unwrap_or(0),
                override_disable_count: config
                    .inheritance
                    .as_ref()
                    .map(|inheritance| inheritance.disable_count)
                    .unwrap_or(0),
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::PathBuf;
    use std::time::{SystemTime, UNIX_EPOCH};

    use super::{
        CODE_CONFIG_LOAD_FAILED, CODE_EMPTY_RULE_GRAPH, CODE_MISSING_CONFIG,
        CODE_MISSING_COVERAGE_SCOPE, CODE_MISSING_DOC_INVENTORY, CODE_MISSING_FRESHNESS_CONFIG,
        CODE_MISSING_GOVERNED_DOCS, DOCTOR_SCHEMA_VERSION, execute,
    };
    use crate::cli::{DoctorArgs, DoctorOutputFormat};
    use crate::config::CONFIG_FILE;

    fn temp_dir(prefix: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time should be valid")
            .as_nanos();
        let path = std::env::temp_dir().join(format!("{prefix}-{nanos}-{}", std::process::id()));
        fs::create_dir_all(&path).expect("temp dir should be created");
        path
    }

    fn base_args(root: &std::path::Path) -> DoctorArgs {
        DoctorArgs {
            root: Some(root.to_path_buf()),
            config: None,
            format: DoctorOutputFormat::Json,
        }
    }

    #[test]
    fn doctor_reports_missing_config() {
        let root = temp_dir("docpact-doctor-missing");

        let report = execute(&base_args(&root)).expect("doctor should execute");

        assert_eq!(report.schema_version, DOCTOR_SCHEMA_VERSION);
        assert!(!report.summary.config_present);
        assert_eq!(report.summary.layout, "none");
        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].code, CODE_MISSING_CONFIG);
    }

    #[test]
    fn doctor_reports_empty_rule_graph() {
        let root = temp_dir("docpact-doctor-empty");
        fs::create_dir_all(root.join(".docpact")).expect("doc root should exist");
        fs::write(
            root.join(CONFIG_FILE),
            r#"version: 1
layout: repo
rules: []
"#,
        )
        .expect("config should be written");

        let report = execute(&base_args(&root)).expect("doctor should execute");

        assert_eq!(report.summary.config_present, true);
        assert_eq!(report.summary.rule_count, 0);
        assert_eq!(report.findings[0].code, CODE_EMPTY_RULE_GRAPH);
    }

    #[test]
    fn doctor_reports_governance_gaps_without_repeating_strict_validation() {
        let root = temp_dir("docpact-doctor-gaps");
        fs::create_dir_all(root.join(".docpact")).expect("doc root should exist");
        fs::write(
            root.join(CONFIG_FILE),
            r#"version: 1
layout: repo
rules:
  - id: no-governed-docs
    scope: repo
    repo: sample
    triggers:
      - path: src/**
        kind: code
    requiredDocs: []
    reason: sample
"#,
        )
        .expect("config should be written");

        let report = execute(&base_args(&root)).expect("doctor should execute");

        assert_eq!(report.summary.rule_count, 1);
        let codes = report
            .findings
            .iter()
            .map(|finding| finding.code.as_str())
            .collect::<Vec<_>>();
        assert!(codes.contains(&CODE_MISSING_GOVERNED_DOCS));
        assert!(codes.contains(&CODE_MISSING_COVERAGE_SCOPE));
        assert!(codes.contains(&CODE_MISSING_DOC_INVENTORY));
        assert!(codes.contains(&CODE_MISSING_FRESHNESS_CONFIG));
        assert!(!codes.contains(&"invalid-config"));
    }

    #[test]
    fn doctor_reports_explicit_config_load_failures() {
        let root = temp_dir("docpact-doctor-invalid");
        fs::create_dir_all(root.join(".docpact")).expect("doc root should exist");
        fs::write(root.join(CONFIG_FILE), "layout: [").expect("config should be written");

        let report = execute(&base_args(&root)).expect("doctor should execute");

        assert_eq!(report.summary.layout, "unknown");
        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].code, CODE_CONFIG_LOAD_FAILED);
    }

    #[test]
    fn doctor_marks_explicit_scopes_and_thresholds_as_configured() {
        let root = temp_dir("docpact-doctor-configured");
        fs::create_dir_all(root.join(".docpact")).expect("doc root should exist");
        fs::write(
            root.join(CONFIG_FILE),
            r#"version: 1
layout: repo
coverage:
  include:
    - src/**
docInventory:
  include:
    - docs/**
freshness:
  warn_after_commits: 10
  warn_after_days: 30
  critical_after_days: 60
routing:
  intents:
    api:
      paths:
        - src/**
rules:
  - id: api-docs
    scope: repo
    repo: sample
    triggers:
      - path: src/**
        kind: code
    requiredDocs:
      - path: docs/api.md
    reason: sample
"#,
        )
        .expect("config should be written");

        let report = execute(&base_args(&root)).expect("doctor should execute");

        assert!(report.summary.coverage_configured);
        assert!(report.summary.routing_configured);
        assert!(report.summary.doc_inventory_configured);
        assert!(report.summary.freshness_configured);
        assert_eq!(report.summary.routing_intent_count, 1);
        assert_eq!(report.summary.governed_doc_count, 1);
        assert!(report.findings.is_empty());
    }

    #[test]
    fn doctor_reports_inheritance_and_override_details() {
        let root = temp_dir("docpact-doctor-inheritance");
        fs::create_dir_all(root.join(".docpact")).expect("doc root should exist");
        fs::create_dir_all(root.join("service/.docpact")).expect("service doc root should exist");
        fs::write(
            root.join(CONFIG_FILE),
            r#"version: 1
layout: workspace
workspace:
  name: demo
  profiles:
    default:
      coverage:
        include:
          - src/**
      docInventory:
        include:
          - docs/**
      freshness:
        warn_after_commits: 10
        warn_after_days: 30
        critical_after_days: 60
      routing:
        intents:
          service:
            paths:
              - src/**
      rules:
        - id: inherited-rule
          scope: workspace
          repo: workspace
          triggers:
            - path: src/**
              kind: code
          requiredDocs:
            - path: docs/guide.md
          reason: inherited
        - id: inherited-disable
          scope: workspace
          repo: workspace
          triggers:
            - path: src/legacy/**
              kind: code
          requiredDocs:
            - path: docs/legacy.md
          reason: disable me
rules:
  - id: root-only
    scope: workspace
    repo: workspace
    triggers:
      - path: AGENTS.md
        kind: doc
    requiredDocs:
      - path: .docpact/config.yaml
    reason: root
"#,
        )
        .expect("root config");
        fs::write(
            root.join("service/.docpact/config.yaml"),
            r#"version: 1
layout: repo
inherit:
  workspace_profile: default
overrides:
  rules:
    add:
      - id: local-extra
        scope: repo
        repo: service
        triggers:
          - path: src/payments/**
            kind: code
        requiredDocs:
          - path: docs/payments.md
        reason: local
    replace:
      - id: inherited-rule
        scope: repo
        repo: service
        triggers:
          - path: src/app/**
            kind: code
        requiredDocs:
          - path: docs/app.md
        reason: replaced
    disable:
      - id: inherited-disable
        reason: not applicable
  coverage:
    mode: merge
    include:
      - tests/**
  docInventory:
    mode: replace
    include:
      - README.md
  freshness:
    mode: replace
    warn_after_commits: 21
    warn_after_days: 34
    critical_after_days: 55
  routing:
    mode: merge
    intents:
      payments:
        paths:
          - src/payments/**
"#,
        )
        .expect("service config");

        let report = execute(&base_args(&root)).expect("doctor should execute");

        assert_eq!(report.summary.layout, "workspace");
        assert_eq!(report.summary.effective_config_count, 2);
        assert_eq!(report.summary.inherited_config_count, 1);

        let service = report
            .configs
            .iter()
            .find(|config| config.base_dir == "service")
            .expect("service config should exist");
        assert!(service.inheritance_enabled);
        assert_eq!(service.workspace_profile.as_deref(), Some("default"));
        assert_eq!(service.override_add_count, 1);
        assert_eq!(service.override_replace_count, 1);
        assert_eq!(service.override_disable_count, 1);
        assert_eq!(service.coverage_resolution, "override-merge");
        assert_eq!(service.routing_resolution, "override-merge");
        assert_eq!(service.doc_inventory_resolution, "override-replace");
        assert_eq!(service.freshness_resolution, "override-replace");
        assert_eq!(service.routing_intent_count, 2);
    }
}