repograph-core 0.3.0

Core library for repograph: registering, grouping, and exposing local git repositories as structured context for AI agents.
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
//! Read-only health checks against the on-disk config.
//!
//! `DoctorReport::run` walks a closed catalog of [`Check`]s against a loaded
//! [`Config`] and emits one [`Finding`] per check per target.
//!
//! Every check is read-only; no config writes, no network operations, no
//! `git fetch`. The report is the contract: a stable, versioned envelope
//! downstream consumers (CI health gates, the future MCP server) can parse
//! without ambiguity.

use std::path::Path;

use serde::Serialize;

use crate::config::Config;
use crate::context::resolve_agent_docs;
use crate::error::RepographError;
use crate::git::validate_git_repo;

/// Current schema version of the [`DoctorReport`] JSON envelope. Additive-only
/// at `1`; any breaking change bumps this.
pub const DOCTOR_SCHEMA_VERSION: u32 = 1;

/// Severity of a single [`Finding`]. Ordering is `Error > Warn > Ok` so the
/// sort in `DoctorReport::run` puts the most pressing findings first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// The check passed for this target.
    Ok,
    /// The check surfaced a sub-optimal-but-non-broken state.
    Warn,
    /// The check surfaced a broken state that gates exit code `1`.
    Error,
}

impl Severity {
    const fn rank(self) -> u8 {
        match self {
            Self::Error => 2,
            Self::Warn => 1,
            Self::Ok => 0,
        }
    }
}

impl PartialOrd for Severity {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Severity {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.rank().cmp(&other.rank())
    }
}

/// Closed catalog of the v1 health checks. Adding a variant is a deliberate
/// schema extension — downstream consumers branch on this enum's string value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub enum Check {
    /// Config file exists at the resolved config dir.
    ConfigPresent,
    /// Config file parses as TOML. Only run when `ConfigPresent` passed.
    ConfigParse,
    /// `[agents]` section is present in the config.
    AgentsConfigured,
    /// `[settings].projects_root`, if set, points at an existing directory.
    ProjectsRootExists,
    /// Per repo: the registered path exists on disk.
    RepoPathExists,
    /// Per repo: the path opens as a `git2::Repository`. Only run when
    /// `RepoPathExists` passed for the same repo.
    RepoIsGitRepo,
    /// Per workspace member: the member name resolves to a registered repo.
    WorkspaceMembersResolve,
    /// Per repo × per selected agent: at least one file matches the agent's
    /// pattern set. Only run when `AgentsConfigured` passed and the
    /// selection is non-empty.
    AgentDocPresent,
}

/// One row in the report.
///
/// `target` is opaque to the renderer — it's the string the human / agent
/// reads to know which repo / workspace / config path the finding is about.
/// By convention: a bare name (`"api"`, `"acme"`), a `"<repo> / <agent>"`
/// pair, or a config-file path.
#[derive(Debug, Clone, Serialize)]
pub struct Finding {
    pub check: Check,
    pub severity: Severity,
    pub target: String,
    pub message: String,
}

/// Tally of findings by severity. `total == ok + warn + error == checks.len()`.
#[derive(Debug, Clone, Copy, Default, Serialize)]
pub struct Summary {
    pub ok: u32,
    pub warn: u32,
    pub error: u32,
    pub total: u32,
}

/// Top-level payload emitted by `repograph doctor`. `schema_version` is the
/// contract — additive-only at `1`; breaking changes bump it.
#[derive(Debug, Clone, Serialize)]
pub struct DoctorReport {
    pub schema_version: u32,
    pub generated_at: String,
    pub checks: Vec<Finding>,
    pub summary: Summary,
}

impl DoctorReport {
    /// Run every check applicable to the given config-load outcome and return
    /// a sorted [`DoctorReport`].
    ///
    /// - `config_load` is `Ok(&config)` when the config loaded (including the
    ///   "missing file → empty config" case), or `Err(&err)` when the load
    ///   itself surfaced an error (malformed TOML, I/O error other than
    ///   `NotFound`). The binary maps `PermissionDenied` to exit `4` *before*
    ///   calling this function; what reaches here is `ConfigParse` or other
    ///   non-permission `Io` failures.
    /// - `config_path` is the file the `ConfigPresent` check probes and
    ///   reports in its `target` field.
    /// - `generated_at` is the RFC 3339 UTC timestamp the binary stamps via
    ///   the `time` crate (core stays free of time deps, same pattern as
    ///   `context-command`).
    #[must_use]
    pub fn run(
        config_load: Result<&Config, &RepographError>,
        config_path: &Path,
        generated_at: String,
    ) -> Self {
        let mut findings: Vec<Finding> = Vec::new();
        let file_exists = config_path.is_file();
        findings.push(config_present_finding(config_path, file_exists));

        let config = match config_load {
            Ok(c) => {
                if file_exists {
                    findings.push(Finding {
                        check: Check::ConfigParse,
                        severity: Severity::Ok,
                        target: config_path.display().to_string(),
                        message: "config file is valid TOML".to_string(),
                    });
                }
                c
            }
            Err(err) => {
                findings.push(Finding {
                    check: Check::ConfigParse,
                    severity: Severity::Error,
                    target: config_path.display().to_string(),
                    message: format!("config could not be loaded: {err}"),
                });
                return assemble(findings, generated_at);
            }
        };

        let agents_configured = config.agents().is_some();
        findings.push(agents_configured_finding(config_path, agents_configured));
        if let Some(f) = projects_root_finding(config) {
            findings.push(f);
        }

        for (name, repo) in config.repos() {
            findings.extend(check_repo(name, &repo.path));
        }
        findings.extend(check_workspaces(config));

        if agents_configured {
            findings.extend(check_agent_docs(config));
        }

        assemble(findings, generated_at)
    }
}

fn config_present_finding(config_path: &Path, file_exists: bool) -> Finding {
    if file_exists {
        Finding {
            check: Check::ConfigPresent,
            severity: Severity::Ok,
            target: config_path.display().to_string(),
            message: "config file is present".to_string(),
        }
    } else {
        Finding {
            check: Check::ConfigPresent,
            severity: Severity::Error,
            target: config_path.display().to_string(),
            message: "config file does not exist".to_string(),
        }
    }
}

fn agents_configured_finding(config_path: &Path, agents_configured: bool) -> Finding {
    if agents_configured {
        Finding {
            check: Check::AgentsConfigured,
            severity: Severity::Ok,
            target: config_path.display().to_string(),
            message: "[agents] section is present".to_string(),
        }
    } else {
        Finding {
            check: Check::AgentsConfigured,
            severity: Severity::Warn,
            target: config_path.display().to_string(),
            message: "[agents] section missing — run `repograph init`".to_string(),
        }
    }
}

fn projects_root_finding(config: &Config) -> Option<Finding> {
    let root = config.settings()?.projects_root.as_deref()?;
    if root.is_dir() {
        Some(Finding {
            check: Check::ProjectsRootExists,
            severity: Severity::Ok,
            target: root.display().to_string(),
            message: "[settings].projects_root exists".to_string(),
        })
    } else {
        Some(Finding {
            check: Check::ProjectsRootExists,
            severity: Severity::Warn,
            target: root.display().to_string(),
            message: format!(
                "[settings].projects_root does not exist: {}",
                root.display()
            ),
        })
    }
}

fn check_workspaces(config: &Config) -> Vec<Finding> {
    let mut out = Vec::new();
    for (ws_name, workspace) in config.workspaces() {
        for member in &workspace.members {
            if config.repos().contains_key(member) {
                out.push(Finding {
                    check: Check::WorkspaceMembersResolve,
                    severity: Severity::Ok,
                    target: format!("{ws_name} / {member}"),
                    message: "member resolves to a registered repo".to_string(),
                });
            } else {
                out.push(Finding {
                    check: Check::WorkspaceMembersResolve,
                    severity: Severity::Warn,
                    target: ws_name.clone(),
                    message: format!(
                        "workspace member '{member}' is not a registered repo (dangling)"
                    ),
                });
            }
        }
    }
    out
}

fn check_agent_docs(config: &Config) -> Vec<Finding> {
    let mut out = Vec::new();
    let selected: &[crate::agents::AgentId] =
        config.agents().map_or(&[], |a| a.selected.as_slice());
    if selected.is_empty() {
        return out;
    }
    for (name, repo) in config.repos() {
        if !repo.path.is_dir() {
            continue;
        }
        for agent in selected {
            let (docs, _) = resolve_agent_docs(&repo.path, std::slice::from_ref(agent));
            let has_file = docs.iter().any(|d| !d.files.is_empty());
            let target = format!("{name} / {}", agent.as_str());
            if has_file {
                out.push(Finding {
                    check: Check::AgentDocPresent,
                    severity: Severity::Ok,
                    target,
                    message: "at least one matching agent doc found".to_string(),
                });
            } else {
                out.push(Finding {
                    check: Check::AgentDocPresent,
                    severity: Severity::Warn,
                    target,
                    message: format!(
                        "no files matched {} patterns ({})",
                        agent.as_str(),
                        agent.file_patterns().join(", ")
                    ),
                });
            }
        }
    }
    out
}

fn check_repo(name: &str, repo_path: &Path) -> Vec<Finding> {
    let mut out = Vec::with_capacity(2);
    if repo_path.exists() {
        out.push(Finding {
            check: Check::RepoPathExists,
            severity: Severity::Ok,
            target: name.to_string(),
            message: format!("path exists: {}", repo_path.display()),
        });
        match validate_git_repo(repo_path) {
            Ok(_) => out.push(Finding {
                check: Check::RepoIsGitRepo,
                severity: Severity::Ok,
                target: name.to_string(),
                message: "path is a git repository".to_string(),
            }),
            Err(e) => out.push(Finding {
                check: Check::RepoIsGitRepo,
                severity: Severity::Error,
                target: name.to_string(),
                message: format!("path is not a git repository: {e}"),
            }),
        }
    } else {
        out.push(Finding {
            check: Check::RepoPathExists,
            severity: Severity::Error,
            target: name.to_string(),
            message: format!("path does not exist: {}", repo_path.display()),
        });
    }
    out
}

fn assemble(mut findings: Vec<Finding>, generated_at: String) -> DoctorReport {
    findings.sort_by(|a, b| {
        b.severity
            .cmp(&a.severity)
            .then_with(|| a.check.cmp(&b.check))
            .then_with(|| a.target.cmp(&b.target))
    });
    let summary = findings.iter().fold(Summary::default(), |mut acc, f| {
        match f.severity {
            Severity::Ok => acc.ok += 1,
            Severity::Warn => acc.warn += 1,
            Severity::Error => acc.error += 1,
        }
        acc.total += 1;
        acc
    });
    DoctorReport {
        schema_version: DOCTOR_SCHEMA_VERSION,
        generated_at,
        checks: findings,
        summary,
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]
    use super::*;
    use crate::agents::AgentId;
    use crate::config::{Agents, CONFIG_FILE_NAME, Repo, Settings};
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn ts() -> String {
        "2026-05-24T00:00:00Z".to_string()
    }

    fn init_git_repo(parent: &Path, name: &str) -> PathBuf {
        let path = parent.join(name);
        std::fs::create_dir_all(&path).unwrap();
        let repo = git2::Repository::init(&path).unwrap();
        let sig = git2::Signature::now("T", "t@e").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            index.write_tree().unwrap()
        };
        let tree = repo.find_tree(tree_id).unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
            .unwrap();
        crate::path::canonicalize(&path).unwrap()
    }

    fn write_config(dir: &Path, body: &str) {
        std::fs::create_dir_all(dir).unwrap();
        std::fs::write(dir.join(CONFIG_FILE_NAME), body).unwrap();
    }

    fn count(report: &DoctorReport, check: Check, severity: Severity) -> usize {
        report
            .checks
            .iter()
            .filter(|f| f.check == check && f.severity == severity)
            .count()
    }

    #[test]
    fn missing_config_file_emits_config_present_error() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let cfg = Config::default();
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(count(&report, Check::ConfigPresent, Severity::Error), 1);
        assert!(report.summary.error >= 1);
    }

    #[test]
    fn config_load_error_short_circuits_after_parse() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        // Synthesize a parse failure using a real RepographError::ConfigParse.
        write_config(tmp.path(), "[unterminated");
        let err = Config::load(tmp.path()).unwrap_err();
        let report = DoctorReport::run(Err(&err), &path, ts());
        assert_eq!(count(&report, Check::ConfigParse, Severity::Error), 1);
        // Catalog short-circuits: no per-repo checks even if config might have them.
        assert!(
            report
                .checks
                .iter()
                .all(|f| matches!(f.check, Check::ConfigPresent | Check::ConfigParse))
        );
    }

    #[test]
    fn agents_missing_emits_warn_and_skips_agent_doc_present() {
        let tmp = TempDir::new().unwrap();
        let repo = init_git_repo(tmp.path(), "api");
        let mut cfg = Config::default();
        cfg.add_repo(
            "api".into(),
            Repo {
                path: repo,
                description: None,
                stack: vec![],
            },
        )
        .unwrap();
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(count(&report, Check::AgentsConfigured, Severity::Warn), 1);
        assert_eq!(count(&report, Check::AgentDocPresent, Severity::Ok), 0);
        assert_eq!(count(&report, Check::AgentDocPresent, Severity::Warn), 0);
    }

    #[test]
    fn projects_root_missing_emits_warn() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.set_settings(Some(Settings {
            projects_root: Some(tmp.path().join("does-not-exist")),
        }));
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(count(&report, Check::ProjectsRootExists, Severity::Warn), 1);
    }

    #[test]
    fn projects_root_existing_emits_ok() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.set_settings(Some(Settings {
            projects_root: Some(tmp.path().to_path_buf()),
        }));
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(count(&report, Check::ProjectsRootExists, Severity::Ok), 1);
    }

    #[test]
    fn missing_repo_path_emits_error_and_skips_git_check() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.add_repo(
            "ghost".into(),
            Repo {
                path: tmp.path().join("does-not-exist"),
                description: None,
                stack: vec![],
            },
        )
        .unwrap();
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(count(&report, Check::RepoPathExists, Severity::Error), 1);
        assert_eq!(count(&report, Check::RepoIsGitRepo, Severity::Error), 0);
        assert_eq!(count(&report, Check::RepoIsGitRepo, Severity::Ok), 0);
        assert!(report.summary.error >= 1);
    }

    #[test]
    fn non_git_path_emits_repo_path_ok_and_git_error() {
        let tmp = TempDir::new().unwrap();
        let plain_dir = tmp.path().join("notes");
        std::fs::create_dir_all(&plain_dir).unwrap();
        let mut cfg = Config::default();
        cfg.add_repo(
            "notes".into(),
            Repo {
                path: plain_dir,
                description: None,
                stack: vec![],
            },
        )
        .unwrap();
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(count(&report, Check::RepoPathExists, Severity::Ok), 1);
        assert_eq!(count(&report, Check::RepoIsGitRepo, Severity::Error), 1);
    }

    #[test]
    fn healthy_git_repo_emits_both_ok() {
        let tmp = TempDir::new().unwrap();
        let repo = init_git_repo(tmp.path(), "api");
        let mut cfg = Config::default();
        cfg.add_repo(
            "api".into(),
            Repo {
                path: repo,
                description: None,
                stack: vec![],
            },
        )
        .unwrap();
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(count(&report, Check::RepoPathExists, Severity::Ok), 1);
        assert_eq!(count(&report, Check::RepoIsGitRepo, Severity::Ok), 1);
    }

    #[test]
    fn dangling_workspace_member_emits_warn() {
        let tmp = TempDir::new().unwrap();
        let repo = init_git_repo(tmp.path(), "api");
        let mut cfg = Config::default();
        cfg.add_repo(
            "api".into(),
            Repo {
                path: repo,
                description: None,
                stack: vec![],
            },
        )
        .unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        cfg.add_members("acme", &["api".into()]).unwrap();
        // Forcibly tombstone: remove `api` from registry so the workspace
        // member becomes dangling.
        cfg.remove_repo("api").unwrap();
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        let dangling = report
            .checks
            .iter()
            .filter(|f| {
                f.check == Check::WorkspaceMembersResolve
                    && f.severity == Severity::Warn
                    && f.message.contains("api")
            })
            .count();
        assert_eq!(dangling, 1);
        assert_eq!(report.summary.error, 0);
    }

    #[test]
    fn agent_doc_missing_emits_warn() {
        let tmp = TempDir::new().unwrap();
        let repo = init_git_repo(tmp.path(), "api");
        // No CLAUDE.md written.
        let mut cfg = Config::default();
        cfg.add_repo(
            "api".into(),
            Repo {
                path: repo,
                description: None,
                stack: vec![],
            },
        )
        .unwrap();
        cfg.set_agents(Some(Agents {
            selected: vec![AgentId::ClaudeCode],
        }));
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(count(&report, Check::AgentDocPresent, Severity::Warn), 1);
        assert_eq!(report.summary.error, 0);
    }

    #[test]
    fn agent_doc_present_emits_ok() {
        let tmp = TempDir::new().unwrap();
        let repo = init_git_repo(tmp.path(), "api");
        std::fs::write(repo.join("CLAUDE.md"), "context\n").unwrap();
        let mut cfg = Config::default();
        cfg.add_repo(
            "api".into(),
            Repo {
                path: repo,
                description: None,
                stack: vec![],
            },
        )
        .unwrap();
        cfg.set_agents(Some(Agents {
            selected: vec![AgentId::ClaudeCode],
        }));
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(count(&report, Check::AgentDocPresent, Severity::Ok), 1);
        assert_eq!(report.summary.error, 0);
        assert_eq!(report.summary.warn, 0);
    }

    #[test]
    fn summary_totals_match_findings() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.set_agents(Some(Agents { selected: vec![] }));
        cfg.save(tmp.path()).unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        assert_eq!(
            report.summary.total,
            report.summary.ok + report.summary.warn + report.summary.error
        );
        assert_eq!(report.summary.total as usize, report.checks.len());
    }

    #[test]
    fn findings_sorted_severity_desc_then_check_asc_then_target_asc() {
        // Synthesize a report with mixed severities and verify the sort order.
        let findings = vec![
            Finding {
                check: Check::AgentDocPresent,
                severity: Severity::Ok,
                target: "z".into(),
                message: String::new(),
            },
            Finding {
                check: Check::RepoPathExists,
                severity: Severity::Error,
                target: "a".into(),
                message: String::new(),
            },
            Finding {
                check: Check::AgentsConfigured,
                severity: Severity::Warn,
                target: "b".into(),
                message: String::new(),
            },
            Finding {
                check: Check::ConfigPresent,
                severity: Severity::Ok,
                target: "a".into(),
                message: String::new(),
            },
        ];
        let report = assemble(findings, ts());
        let order: Vec<_> = report
            .checks
            .iter()
            .map(|f| (f.severity, f.check, f.target.clone()))
            .collect();
        assert_eq!(order[0].0, Severity::Error);
        assert_eq!(order[1].0, Severity::Warn);
        assert_eq!(order[2].0, Severity::Ok);
        assert_eq!(order[3].0, Severity::Ok);
        // Ok ties: check name ascending — ConfigPresent < AgentDocPresent in enum order
        // (variants declared in spec order, not alphabetical — adjust the test if needed).
        // Re-check sort: derive `Ord` on Check sorts by variant declaration order.
        // ConfigPresent is declared first, so it comes before AgentDocPresent.
        assert!(matches!(order[2].1, Check::ConfigPresent));
        assert!(matches!(order[3].1, Check::AgentDocPresent));
    }

    #[test]
    fn severity_ordering_error_is_max() {
        assert!(Severity::Error > Severity::Warn);
        assert!(Severity::Warn > Severity::Ok);
        assert!(Severity::Error > Severity::Ok);
    }

    #[test]
    fn json_envelope_has_documented_top_level_keys() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join(CONFIG_FILE_NAME);
        let cfg = Config::default();
        let report = DoctorReport::run(Ok(&cfg), &path, ts());
        let v = serde_json::to_value(&report).unwrap();
        assert_eq!(v["schema_version"], 1);
        assert!(v["generated_at"].is_string());
        assert!(v["checks"].is_array());
        assert!(v["summary"].is_object());
        assert!(v["summary"]["total"].is_number());
    }

    #[test]
    fn check_serializes_as_pascal_case_variant_name() {
        let f = Finding {
            check: Check::RepoIsGitRepo,
            severity: Severity::Ok,
            target: "x".into(),
            message: "y".into(),
        };
        let v = serde_json::to_value(&f).unwrap();
        assert_eq!(v["check"], "RepoIsGitRepo");
        assert_eq!(v["severity"], "ok");
    }
}