cartomancer 0.8.0

PR review tool with blast radius awareness — opengrep + cartog + LLM
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
//! Doctor command — verify that all dependencies and configuration are healthy.

use std::time::Duration;

use anyhow::Result;
use serde::Serialize;

use cartomancer_core::config::AppConfig;

/// Result of a single doctor check.
#[derive(Serialize)]
pub struct CheckResult {
    pub name: &'static str,
    pub status: CheckStatus,
    pub message: String,
}

/// Outcome of a single doctor check.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckStatus {
    /// Check passed.
    Ok,
    /// Non-blocking issue (e.g. optional dependency missing).
    Warn,
    /// Blocking failure — the tool cannot operate correctly.
    Error,
}

impl CheckStatus {
    fn icon(self) -> &'static str {
        match self {
            CheckStatus::Ok => "+",
            CheckStatus::Warn => "!",
            CheckStatus::Error => "x",
        }
    }
}

/// Structured doctor report with summary counts.
#[derive(Serialize)]
pub struct DoctorReport {
    pub checks: Vec<CheckResult>,
    pub summary: DoctorSummary,
}

#[derive(Serialize)]
pub struct DoctorSummary {
    pub total: usize,
    pub ok: usize,
    pub warn: usize,
    pub error: usize,
}

impl CheckResult {
    fn ok(name: &'static str, message: impl Into<String>) -> Self {
        Self {
            name,
            status: CheckStatus::Ok,
            message: message.into(),
        }
    }

    fn warn(name: &'static str, message: impl Into<String>) -> Self {
        Self {
            name,
            status: CheckStatus::Warn,
            message: message.into(),
        }
    }

    fn fail(name: &'static str, message: impl Into<String>) -> Self {
        Self {
            name,
            status: CheckStatus::Error,
            message: message.into(),
        }
    }
}

/// Run all doctor checks and return a structured report.
pub async fn run_checks(config: &AppConfig) -> DoctorReport {
    let checks = vec![
        check_config(config),
        check_git(),
        check_opengrep().await,
        check_custom_rules(config),
        check_knowledge(config),
        check_cartog(),
        check_cartog_db(config),
        check_github_token(config),
        check_llm_provider(config).await,
        check_storage(config),
    ];

    build_report(checks)
}

fn build_report(checks: Vec<CheckResult>) -> DoctorReport {
    let ok = checks
        .iter()
        .filter(|c| c.status == CheckStatus::Ok)
        .count();
    let warn = checks
        .iter()
        .filter(|c| c.status == CheckStatus::Warn)
        .count();
    let error = checks
        .iter()
        .filter(|c| c.status == CheckStatus::Error)
        .count();

    DoctorReport {
        summary: DoctorSummary {
            total: checks.len(),
            ok,
            warn,
            error,
        },
        checks,
    }
}

/// Print report as a text checklist.
pub fn print_text(report: &DoctorReport) {
    print!("{}", format_text(report));
}

/// Format the text report. Pure for testability.
pub fn format_text(report: &DoctorReport) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let _ = writeln!(out, "Cartomancer Doctor\n");
    for check in &report.checks {
        let _ = writeln!(
            out,
            "  [{}] {}: {}",
            check.status.icon(),
            check.name,
            check.message
        );
    }
    out.push('\n');
    let s = &report.summary;
    let _ = if s.error > 0 {
        writeln!(
            out,
            "{} checks passed, {} warnings, {} errors",
            s.ok, s.warn, s.error
        )
    } else if s.warn > 0 {
        writeln!(out, "{} checks passed, {} warnings", s.ok, s.warn)
    } else {
        writeln!(out, "All {} checks passed", s.ok)
    };
    out
}

/// Print report as JSON.
pub fn print_json(report: &DoctorReport) -> Result<()> {
    println!("{}", serialize_report(report)?);
    Ok(())
}

/// Serialize the report as pretty JSON. Pure for testability.
pub fn serialize_report(report: &DoctorReport) -> Result<String> {
    Ok(serde_json::to_string_pretty(report)?)
}

// --- Individual checks ---

/// Check custom rules directory (if configured).
fn check_custom_rules(config: &AppConfig) -> CheckResult {
    let Some(ref rules_dir) = config.opengrep.rules_dir else {
        return CheckResult::ok("custom-rules", "disabled (rules_dir not set)");
    };
    if rules_dir.is_empty() {
        return CheckResult::ok("custom-rules", "disabled (rules_dir is empty)");
    }

    // Use current directory as base for path validation
    let base = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
    match crate::path_security::validate_path_within(&base, rules_dir) {
        Err(e) => CheckResult::fail("custom-rules", format!("path rejected: {e}")),
        Ok(validated) => {
            if !validated.is_dir() {
                return CheckResult::ok(
                    "custom-rules",
                    format!("{rules_dir} not found (default rules only)"),
                );
            }

            let yaml_count = std::fs::read_dir(&validated)
                .map(|entries| {
                    entries
                        .filter_map(|e| e.ok())
                        .filter(|e| {
                            e.path()
                                .extension()
                                .map(|ext| ext == "yaml" || ext == "yml")
                                .unwrap_or(false)
                        })
                        .count()
                })
                .unwrap_or(0);

            if yaml_count == 0 {
                CheckResult::warn(
                    "custom-rules",
                    format!("{rules_dir} exists but contains no .yaml/.yml files"),
                )
            } else {
                CheckResult::ok(
                    "custom-rules",
                    format!("{yaml_count} rule file(s) in {rules_dir}"),
                )
            }
        }
    }
}

/// Check knowledge file for LLM deepening (if configured).
fn check_knowledge(config: &AppConfig) -> CheckResult {
    let Some(ref knowledge_file) = config.knowledge.knowledge_file else {
        return CheckResult::ok("knowledge", "disabled (no knowledge_file)");
    };
    if knowledge_file.is_empty() {
        return CheckResult::ok("knowledge", "disabled (knowledge_file is empty)");
    }

    let base = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
    match crate::path_security::validate_path_within(&base, knowledge_file) {
        Err(e) => CheckResult::fail("knowledge", format!("path rejected: {e}")),
        Ok(validated) => {
            if !validated.exists() {
                return CheckResult::ok(
                    "knowledge",
                    format!("{knowledge_file} not found (default prompts only)"),
                );
            }

            match std::fs::metadata(&validated) {
                Ok(meta) => {
                    let size = meta.len() as usize;
                    let max = config.knowledge.max_knowledge_chars;
                    if size > max {
                        CheckResult::warn(
                            "knowledge",
                            format!(
                                "{knowledge_file} ({size} bytes) exceeds max_knowledge_chars ({max}), will be truncated"
                            ),
                        )
                    } else {
                        CheckResult::ok("knowledge", format!("{knowledge_file} ({size} bytes)"))
                    }
                }
                Err(e) => {
                    CheckResult::warn("knowledge", format!("cannot read {knowledge_file}: {e}"))
                }
            }
        }
    }
}

/// Validate the loaded configuration via `AppConfig::validate()`.
fn check_config(config: &AppConfig) -> CheckResult {
    match config.validate() {
        Ok(()) => CheckResult::ok("config", "valid"),
        Err(e) => CheckResult::fail("config", e),
    }
}

/// Check that a GitHub token is available (config or `GITHUB_TOKEN` env).
fn check_github_token(config: &AppConfig) -> CheckResult {
    let has_token = config
        .github
        .token
        .as_deref()
        .map(|s| !s.trim().is_empty())
        .unwrap_or(false)
        || std::env::var("GITHUB_TOKEN")
            .map(|v| !v.trim().is_empty())
            .unwrap_or(false);

    if has_token {
        CheckResult::ok("github-token", "found")
    } else {
        CheckResult::warn(
            "github-token",
            "not set (set GITHUB_TOKEN or github.token in config for review/serve)",
        )
    }
}

/// Verify that `opengrep` is in PATH and responds to `--version` within 10s.
async fn check_opengrep() -> CheckResult {
    let fut = tokio::process::Command::new("opengrep")
        .arg("--version")
        .output();

    let output = match tokio::time::timeout(Duration::from_secs(10), fut).await {
        Ok(result) => result,
        Err(_) => {
            return CheckResult::fail("opengrep", "timed out waiting for opengrep --version");
        }
    };

    match output {
        Ok(output) if output.status.success() => {
            let version = String::from_utf8_lossy(&output.stdout);
            let version = version.trim();
            // Some tools print version to stderr
            let version = if version.is_empty() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                stderr.trim().to_string()
            } else {
                version.to_string()
            };
            let label = if version.is_empty() {
                "found".to_string()
            } else {
                version.lines().next().unwrap_or("found").to_string()
            };
            CheckResult::ok("opengrep", label)
        }
        Ok(output) => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            CheckResult::fail(
                "opengrep",
                format!(
                    "exited with code {}{}",
                    output.status.code().unwrap_or(-1),
                    stderr.trim()
                ),
            )
        }
        Err(_) => CheckResult::fail(
            "opengrep",
            "not found in PATH (install: https://github.com/opengrep/opengrep)",
        ),
    }
}

/// Check whether `cartog` CLI is available (optional — warns if missing).
fn check_cartog() -> CheckResult {
    match std::process::Command::new("cartog")
        .arg("--version")
        .output()
    {
        Ok(output) if output.status.success() => {
            let version = String::from_utf8_lossy(&output.stdout);
            let version = version.trim();
            let label = if version.is_empty() {
                "found".to_string()
            } else {
                version.lines().next().unwrap_or("found").to_string()
            };
            CheckResult::ok(
                "cartog",
                format!("{label} (run `cartog index .` to build the code graph)"),
            )
        }
        Ok(output) => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            let detail = if !stderr.trim().is_empty() {
                stderr.trim().to_string()
            } else {
                stdout.trim().to_string()
            };
            CheckResult::warn(
                "cartog",
                format!(
                    "exited with code {}{}",
                    output.status.code().unwrap_or(-1),
                    detail
                ),
            )
        }
        Err(e) => CheckResult::warn(
            "cartog",
            format!(
                "not found in PATH ({}) — graph enrichment will be skipped (install: cargo install cartog)",
                e.kind()
            ),
        ),
    }
}

/// Check that `git` is in PATH — required for cloning and `review --work-dir` flows.
fn check_git() -> CheckResult {
    match std::process::Command::new("git").arg("--version").output() {
        Ok(output) if output.status.success() => {
            let version = String::from_utf8_lossy(&output.stdout);
            CheckResult::ok("git", version.trim().to_string())
        }
        Ok(output) => CheckResult::fail(
            "git",
            format!("exited with code {}", output.status.code().unwrap_or(-1)),
        ),
        Err(_) => CheckResult::fail(
            "git",
            "not found in PATH (required for `review` and `serve`)",
        ),
    }
}

/// Check that the configured cartog database exists — warns if missing, because
/// graph enrichment is optional but strongly recommended.
fn check_cartog_db(config: &AppConfig) -> CheckResult {
    let path = std::path::Path::new(&config.severity.cartog_db_path);
    if path.exists() {
        CheckResult::ok("cartog-db", format!("found at {}", path.display()))
    } else {
        CheckResult::warn(
            "cartog-db",
            format!(
                "{} not found — graph enrichment will be skipped (run `cartog index .`)",
                path.display()
            ),
        )
    }
}

/// Create the configured LLM provider and run its health check.
async fn check_llm_provider(config: &AppConfig) -> CheckResult {
    let provider_name = format!("{:?}", config.llm.provider).to_lowercase();
    match crate::llm::create_provider(&config.llm, config.knowledge.system_prompt.as_deref()) {
        Ok(provider) => match provider.health_check().await {
            Ok(()) => CheckResult::ok("llm-provider", format!("{} reachable", provider_name)),
            Err(e) => CheckResult::warn(
                "llm-provider",
                format!("{} unreachable — {}", provider_name, e),
            ),
        },
        Err(e) => CheckResult::warn(
            "llm-provider",
            format!("{} not configured — {}", provider_name, e),
        ),
    }
}

/// Verify that the SQLite store can be opened at the configured `db_path`.
fn check_storage(config: &AppConfig) -> CheckResult {
    match cartomancer_store::store::Store::open(&config.storage.db_path) {
        Ok(_) => CheckResult::ok("storage", config.storage.db_path.to_string()),
        Err(e) => CheckResult::fail(
            "storage",
            format!("cannot open {}: {}", config.storage.db_path, e),
        ),
    }
}

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

    #[test]
    fn check_status_icon_mapping() {
        assert_eq!(CheckStatus::Ok.icon(), "+");
        assert_eq!(CheckStatus::Warn.icon(), "!");
        assert_eq!(CheckStatus::Error.icon(), "x");
    }

    #[test]
    fn check_result_status() {
        assert_eq!(CheckResult::ok("t", "").status, CheckStatus::Ok);
        assert_eq!(CheckResult::warn("t", "").status, CheckStatus::Warn);
        assert_eq!(CheckResult::fail("t", "").status, CheckStatus::Error);
    }

    #[test]
    fn check_config_valid_default() {
        let config = AppConfig::default();
        let result = check_config(&config);
        assert_eq!(result.status, CheckStatus::Ok);
    }

    #[test]
    fn check_github_token_missing() {
        let saved = std::env::var_os("GITHUB_TOKEN");
        std::env::remove_var("GITHUB_TOKEN");

        let config = AppConfig::default();
        let result = check_github_token(&config);

        // Restore before asserting so panics don't leave env dirty
        match saved {
            Some(val) => std::env::set_var("GITHUB_TOKEN", val),
            None => std::env::remove_var("GITHUB_TOKEN"),
        }

        assert_eq!(result.status, CheckStatus::Warn);
        assert!(result.message.contains("not set"));
    }

    #[test]
    fn check_github_token_from_config() {
        let mut config = AppConfig::default();
        config.github.token = Some("ghp_test".into());
        let result = check_github_token(&config);
        assert_eq!(result.status, CheckStatus::Ok);
    }

    #[test]
    fn check_storage_memory() {
        let mut config = AppConfig::default();
        config.storage.db_path = ":memory:".into();
        let result = check_storage(&config);
        assert_eq!(result.status, CheckStatus::Ok);
    }

    #[test]
    fn check_storage_bad_path() {
        let tmp = tempfile::tempdir().unwrap();
        let mut config = AppConfig::default();
        config.storage.db_path = tmp.path().to_string_lossy().into_owned();
        let result = check_storage(&config);
        drop(tmp);
        assert_eq!(result.status, CheckStatus::Error);
    }

    #[test]
    fn build_report_summary_counts() {
        let checks = vec![
            CheckResult::ok("a", "ok"),
            CheckResult::warn("b", "warning"),
            CheckResult::fail("c", "error"),
        ];
        let report = build_report(checks);
        assert_eq!(report.summary.total, 3);
        assert_eq!(report.summary.ok, 1);
        assert_eq!(report.summary.warn, 1);
        assert_eq!(report.summary.error, 1);
    }

    #[test]
    fn check_git_finds_binary() {
        // CI runners and dev machines are expected to have git in PATH.
        let result = check_git();
        assert_eq!(result.status, CheckStatus::Ok, "msg: {}", result.message);
        assert!(result.message.contains("git version"));
    }

    #[test]
    fn check_cartog_db_missing_warns() {
        let mut config = AppConfig::default();
        config.severity.cartog_db_path = "/nonexistent/path/.cartog.db".into();
        let result = check_cartog_db(&config);
        assert_eq!(result.status, CheckStatus::Warn);
        assert!(result.message.contains("not found"));
    }

    #[test]
    fn check_cartog_db_present_ok() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let mut config = AppConfig::default();
        config.severity.cartog_db_path = tmp.path().to_string_lossy().into_owned();
        let result = check_cartog_db(&config);
        assert_eq!(result.status, CheckStatus::Ok);
    }

    #[test]
    fn serialize_report_pretty_contains_fields() {
        let report = build_report(vec![
            CheckResult::ok("a", "fine"),
            CheckResult::warn("b", "missing"),
        ]);
        let json = serialize_report(&report).unwrap();
        // Pretty-printed JSON uses newlines
        assert!(
            json.contains('\n'),
            "pretty JSON should contain newlines: {json}"
        );
        // Round-trip to make sure the shape is correct
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(v["checks"][0]["name"], "a");
        assert_eq!(v["checks"][0]["status"], "ok");
        assert_eq!(v["checks"][1]["status"], "warn");
        assert_eq!(v["summary"]["total"], 2);
        assert_eq!(v["summary"]["ok"], 1);
        assert_eq!(v["summary"]["warn"], 1);
    }

    #[test]
    fn format_text_all_ok_branch() {
        let out = format_text(&build_report(vec![
            CheckResult::ok("a", "fine"),
            CheckResult::ok("b", "also fine"),
        ]));
        assert!(out.contains("Cartomancer Doctor"));
        assert!(out.contains("[+] a: fine"));
        assert!(out.contains("[+] b: also fine"));
        assert!(out.contains("All 2 checks passed"));
        assert!(!out.contains("warnings"));
    }

    #[test]
    fn format_text_warn_branch() {
        let out = format_text(&build_report(vec![
            CheckResult::ok("a", "fine"),
            CheckResult::warn("b", "missing"),
        ]));
        assert!(out.contains("[!] b: missing"));
        assert!(out.contains("1 checks passed, 1 warnings"));
        assert!(!out.contains("errors"));
    }

    #[test]
    fn format_text_error_branch() {
        let out = format_text(&build_report(vec![
            CheckResult::ok("a", "fine"),
            CheckResult::warn("b", "missing"),
            CheckResult::fail("c", "broken"),
        ]));
        assert!(out.contains("[x] c: broken"));
        assert!(out.contains("1 checks passed, 1 warnings, 1 errors"));
    }

    #[test]
    fn check_status_serializes_lowercase() {
        assert_eq!(serde_json::to_string(&CheckStatus::Ok).unwrap(), "\"ok\"");
        assert_eq!(
            serde_json::to_string(&CheckStatus::Warn).unwrap(),
            "\"warn\""
        );
        assert_eq!(
            serde_json::to_string(&CheckStatus::Error).unwrap(),
            "\"error\""
        );
    }
}