cartog 0.21.1

Code graph indexer for LLM coding agents. Map your codebase, navigate by graph.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use anyhow::{Context, Result};
use serde::Serialize;

use crate::cli::{EdgeKindFilter, SymbolKindFilter};
use crate::config::CartogConfig;
use cartog_core::{EdgeKind, SymbolKind};
use cartog_db::{Database, MAX_SEARCH_LIMIT};
use cartog_indexer as indexer;
use cartog_rag as rag;
use cartog_watch::{self as watch, WatchConfig};

pub mod ide;
pub mod init;
pub mod mermaid;
pub mod remote;

/// Stderr progress reporter for long-running CLI commands.
///
/// On a TTY it renders an animated spinner whose label tracks the current
/// phase. On a non-TTY (the Claude Code SessionStart hook, CI, piped output)
/// it prints a plain line on each phase change plus a periodic heartbeat, so a
/// multi-minute first index is never silent. Use [`Spinner::set_phase`] from a
/// progress callback to update the label/heartbeat.
struct Spinner {
    stop: Arc<AtomicBool>,
    phase: Arc<Mutex<String>>,
    handle: Option<std::thread::JoinHandle<()>>,
}

impl Spinner {
    fn start(label: &'static str) -> Option<Self> {
        let is_tty = std::io::stderr().is_terminal();
        // Non-TTY callers (CI, pipes, scripts capturing stderr) stay silent by
        // default — only opt in via CARTOG_PROGRESS=1, which the Claude Code
        // SessionStart hook sets so its long first index isn't a silent wait.
        if !is_tty && std::env::var_os("CARTOG_PROGRESS").is_none() {
            return None;
        }
        let stop = Arc::new(AtomicBool::new(false));
        let phase = Arc::new(Mutex::new(label.to_string()));
        let stop_clone = Arc::clone(&stop);
        let phase_clone = Arc::clone(&phase);
        let handle = std::thread::spawn(move || {
            if is_tty {
                Self::run_tty(&stop_clone, &phase_clone);
            } else {
                Self::run_plain(&stop_clone, &phase_clone);
            }
        });
        Some(Self {
            stop,
            phase,
            handle: Some(handle),
        })
    }

    /// Update the displayed phase. On a non-TTY this prints a new line
    /// immediately so each phase boundary is visible in the hook log.
    fn set_phase(&self, phase: impl Into<String>) {
        if let Ok(mut p) = self.phase.lock() {
            *p = phase.into();
        }
    }

    fn run_tty(stop: &AtomicBool, phase: &Mutex<String>) {
        const FRAMES: &[&str] = &["", "", "", "", "", "", "", "", "", ""];
        let mut i = 0usize;
        let start = std::time::Instant::now();
        while !stop.load(Ordering::Relaxed) {
            let elapsed = start.elapsed().as_secs();
            let label = phase.lock().map(|p| p.clone()).unwrap_or_default();
            let mut err = std::io::stderr().lock();
            // \r + clear-to-eol + frame + label + elapsed
            let _ = write!(err, "\r\x1b[K{} {label} ({elapsed}s)", FRAMES[i]);
            let _ = err.flush();
            drop(err);
            i = (i + 1) % FRAMES.len();
            std::thread::sleep(Duration::from_millis(100));
        }
        // Clear the spinner line on exit.
        let mut err = std::io::stderr().lock();
        let _ = write!(err, "\r\x1b[K");
        let _ = err.flush();
    }

    /// Non-TTY heartbeat: emit a line whenever the phase changes, plus one
    /// every 5s while a phase is still running, so the hook output is never
    /// silent for minutes. No carriage returns or escape codes — plain log.
    fn run_plain(stop: &AtomicBool, phase: &Mutex<String>) {
        let start = std::time::Instant::now();
        let mut last_label = String::new();
        let mut last_emit = std::time::Instant::now();
        while !stop.load(Ordering::Relaxed) {
            let label = phase.lock().map(|p| p.clone()).unwrap_or_default();
            let changed = label != last_label;
            if changed || last_emit.elapsed() >= Duration::from_secs(5) {
                let elapsed = start.elapsed().as_secs();
                eprintln!("  {label}… ({elapsed}s)");
                last_label = label;
                last_emit = std::time::Instant::now();
            }
            std::thread::sleep(Duration::from_millis(200));
        }
    }

    fn stop(mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(h) = self.handle.take() {
            let _ = h.join();
        }
    }
}

impl Drop for Spinner {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(h) = self.handle.take() {
            let _ = h.join();
        }
    }
}

/// Capitalize the first character of a phase label for CLI display. Phase
/// wording itself is owned by `ProgressUpdate::label()` in the indexer/rag
/// crates; the spinner only adjusts presentation.
fn capitalize_phase(label: String) -> String {
    let mut chars = label.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => label,
    }
}

/// Build a progress callback that drives `spinner`'s phase label from a
/// `label_of` projection. Returns the callback plus the `Arc<Spinner>` the
/// caller must keep alive for the duration of the work, then pass to
/// [`stop_spinner`]. Centralizes the Arc lifecycle so the explicit
/// `Arc::into_inner` stop is reliable (no stray clone keeps the count above 1).
fn spinner_callback<U>(
    spinner: &Option<Arc<Spinner>>,
    label_of: fn(&U) -> String,
) -> Option<impl Fn(U)> {
    spinner.as_ref().map(|s| {
        let s = Arc::clone(s);
        move |u: U| s.set_phase(capitalize_phase(label_of(&u)))
    })
}

/// Stop and join a spinner created via [`Spinner::start`] + `Arc::new`. The
/// callback built by [`spinner_callback`] must already be dropped so the Arc
/// strong count is 1 and `Arc::into_inner` succeeds.
fn stop_spinner(spinner: Option<Arc<Spinner>>) {
    if let Some(s) = spinner.and_then(Arc::into_inner) {
        s.stop();
    }
}

fn open_db(path: &Path, embedding_dim: usize) -> Result<Database> {
    Database::open(path, embedding_dim).map_err(|e| open_db_error(path, e.into()))
}

/// Map a database-open failure to an actionable message naming the path and the
/// fix. Corruption ("not a database") and read-only mounts produce the most
/// confusing raw SQLite errors, so they get specific remediation; anything else
/// keeps a generic wrapper with the path. The original error is the cause.
fn open_db_error(path: &Path, err: anyhow::Error) -> anyhow::Error {
    let raw = err.to_string().to_ascii_lowercase();
    let p = path.display();
    let hint = if raw.contains("not a database") {
        format!(
            "database at {p} is corrupt or not a cartog database — \
             delete it and run `cartog index .` to rebuild"
        )
    } else if raw.contains("readonly") || raw.contains("read-only") {
        format!(
            "database at {p} is not writable — check the file and directory \
             permissions, or set [database].path to a writable location"
        )
    } else {
        format!("failed to open cartog database at {p}")
    };
    err.context(hint)
}

/// Estimate token count from a string using chars/4 approximation.
#[cfg(test)]
fn estimate_tokens(s: &str) -> u32 {
    (s.len() as u32).div_ceil(4)
}

/// Truncate a string to fit within a token budget, appending a truncation notice.
fn truncate_to_budget(s: &str, max_tokens: u32) -> String {
    let max_bytes = (max_tokens as usize) * 4;
    if s.len() <= max_bytes {
        return s.to_string();
    }
    // Find a char boundary at or before max_bytes, leaving room for notice
    let notice = "\n... (truncated to fit token budget)";
    let target = max_bytes.saturating_sub(notice.len());
    // UTF-8 chars are at most 4 bytes, so we only need to check 4 positions back.
    let cut = (target.saturating_sub(3)..=target)
        .rev()
        .find(|&i| s.is_char_boundary(i))
        .unwrap_or(0);
    let mut out = s[..cut].to_string();
    out.push_str(notice);
    out
}

/// Print `data` as pretty JSON if `json` is true, otherwise call `human_fmt`.
/// When `token_budget` is Some, truncate human-readable output to fit.
fn output<T: Serialize>(
    data: &T,
    json: bool,
    token_budget: Option<u32>,
    human_fmt: impl FnOnce(&T) -> String,
) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(data)?);
    } else {
        let text = human_fmt(data);
        match token_budget {
            Some(budget) => print!("{}", truncate_to_budget(&text, budget)),
            None => print!("{}", text),
        }
    }
    Ok(())
}

/// Hint suffix appended to "no result" messages when the index is empty, so a
/// fresh user can tell "you haven't indexed yet" from a genuine no-match.
/// Returns `""` when the index has symbols (the common case).
fn empty_index_hint(db: &Database) -> &'static str {
    match db.is_empty() {
        Ok(true) => " (index is empty — run 'cartog index .' first)",
        _ => "",
    }
}

/// Suggestion suffix for "no result" messages: when a navigation command
/// (refs/callees/impact/hierarchy) finds no exact match but the fuzzy search
/// surfaces similarly-named symbols, list them so the user can correct a typo
/// or partial name. Returns `""` when the index is empty (the empty-index hint
/// covers that) or when there are no near matches.
fn did_you_mean(db: &Database, name: &str) -> String {
    if name.is_empty() || matches!(db.is_empty(), Ok(true)) {
        return String::new();
    }
    let candidates = match db.search(name, None, None, 5) {
        Ok(c) => c,
        Err(_) => return String::new(),
    };
    // An exact match means the symbol exists but genuinely has no edges/results;
    // suggesting it would be noise.
    if candidates.iter().any(|s| s.name == name) || candidates.is_empty() {
        return String::new();
    }
    let names: Vec<&str> = candidates.iter().map(|s| s.name.as_str()).collect();
    format!(" — did you mean: {}?", names.join(", "))
}

/// Build or rebuild the code graph index.
pub fn cmd_index(
    db_path: &Path,
    path: &str,
    force: bool,
    lsp: bool,
    json: bool,
    embedding_dim: usize,
) -> Result<()> {
    let root = Path::new(path);
    let db = open_db(db_path, embedding_dim)?;

    let spinner = if json {
        None
    } else {
        Spinner::start("Indexing").map(Arc::new)
    };
    let cb = spinner_callback(&spinner, indexer::ProgressUpdate::label);
    let cb_ref: Option<indexer::ProgressCallback<'_>> =
        cb.as_ref().map(|f| f as &(dyn Fn(_) + Send + Sync));
    let result = indexer::index_directory(&db, root, force, lsp, cb_ref, None);
    drop(cb);
    stop_spinner(spinner);
    let result = result?;

    // No-op run: nothing was added or removed this pass. The delta counters
    // are all zero, so the standard "0 symbols, 0 edges" line reads like a
    // failure. Report DB state instead — "up to date" when the index has
    // content, or "no indexable files" for an empty/unsupported tree.
    if !json && result.files_indexed == 0 && result.files_removed == 0 {
        let s = db.stats()?;
        if s.num_symbols == 0 {
            println!("No indexable files found under '{path}'.");
        } else {
            println!(
                "Index up to date ({} files, {} symbols unchanged)",
                s.num_files, s.num_symbols
            );
        }
        return Ok(());
    }

    output(&result, json, None, |r| {
        let lsp_part = if r.edges_lsp_resolved > 0
            || r.edges_marked_unresolvable > 0
            || r.edges_marked_external > 0
        {
            let mut s = format!(
                " ({} heuristic + {} LSP",
                r.edges_resolved, r.edges_lsp_resolved
            );
            if r.edges_marked_unresolvable > 0 {
                s.push_str(&format!(
                    ", {} marked unresolvable",
                    r.edges_marked_unresolvable
                ));
            }
            if r.edges_marked_external > 0 {
                s.push_str(&format!(", {} external", r.edges_marked_external));
            }
            s.push(')');
            s
        } else {
            String::new()
        };
        let sym_detail = if r.symbols_modified > 0 || r.symbols_unchanged > 0 {
            format!(
                " ({} new, {} modified, {} unchanged, {} removed)",
                r.symbols_added, r.symbols_modified, r.symbols_unchanged, r.symbols_removed
            )
        } else {
            String::new()
        };
        let unsupported = if r.files_unsupported > 0 {
            let breakdown = r
                .unsupported_by_ext
                .iter()
                .take(5)
                .map(|(ext, n)| format!("{n} .{ext}"))
                .collect::<Vec<_>>()
                .join(", ");
            format!(
                "\n  {} files in unsupported languages not indexed ({breakdown})",
                r.files_unsupported
            )
        } else {
            String::new()
        };
        format!(
            "Indexed {} files ({} skipped, {} removed)\n  {} symbols{}, {} edges ({} resolved{}){}\n",
            r.files_indexed,
            r.files_skipped,
            r.files_removed,
            r.symbols_added + r.symbols_modified + r.symbols_unchanged,
            sym_detail,
            r.edges_added,
            r.edges_resolved + r.edges_lsp_resolved,
            lsp_part,
            unsupported,
        )
    })
}

/// Show symbols and structure of a file.
pub fn cmd_outline(
    db_path: &Path,
    file: &str,
    json: bool,
    token_budget: Option<u32>,
    embedding_dim: usize,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;
    let symbols = db.outline(file)?;
    // Don't count empty results — an empty-index call or a typo'd file path
    // didn't actually save the user any tokens vs grep + read.
    if !symbols.is_empty() {
        db.log_query("outline", "cli");
    }
    let file = file.to_string();
    output(&symbols, json, token_budget, |syms| {
        if syms.is_empty() {
            return format!("No symbols found in {file}{}\n", empty_index_hint(&db));
        }
        let mut out = String::new();
        for sym in syms {
            let indent = if sym.parent_id.is_some() { "  " } else { "" };
            let async_prefix = if sym.is_async { "async " } else { "" };
            match sym.kind {
                SymbolKind::Import => {
                    let text = sym.signature.as_deref().unwrap_or(&sym.name);
                    out.push_str(&format!("{indent}{text}  L{}\n", sym.start_line));
                }
                _ => {
                    let sig = sym.signature.as_deref().unwrap_or("");
                    out.push_str(&format!(
                        "{indent}{async_prefix}{kind} {name}{sig}  L{start}-{end}\n",
                        kind = sym.kind,
                        name = sym.name,
                        start = sym.start_line,
                        end = sym.end_line,
                    ));
                }
            }
        }
        out
    })
}

/// Find what a symbol calls.
pub fn cmd_callees(
    db_path: &Path,
    name: &str,
    json: bool,
    token_budget: Option<u32>,
    embedding_dim: usize,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;
    let edges = db.callees(name)?;
    if !edges.is_empty() {
        db.log_query("callees", "cli");
    }
    let name = name.to_string();
    output(&edges, json, token_budget, |edges| {
        if edges.is_empty() {
            return format!(
                "No callees found for '{name}'{}{}\n",
                empty_index_hint(&db),
                did_you_mean(&db, &name)
            );
        }
        let mut out = String::new();
        for edge in edges {
            out.push_str(&format!(
                "{target}  {file}:{line}\n",
                target = edge.target_name,
                file = edge.file_path,
                line = edge.line,
            ));
        }
        out
    })
}

/// Transitive impact analysis — what breaks if this changes?
pub fn cmd_impact(
    db_path: &Path,
    name: &str,
    depth: u32,
    json: bool,
    token_budget: Option<u32>,
    embedding_dim: usize,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;
    let results = db.impact(name, depth)?;
    if !results.is_empty() {
        db.log_query("impact", "cli");
    }
    let name = name.to_string();

    #[derive(Serialize)]
    struct ImpactEntry {
        edge: cartog_core::Edge,
        depth: u32,
    }

    let items: Vec<ImpactEntry> = results
        .into_iter()
        .map(|(edge, d)| ImpactEntry { edge, depth: d })
        .collect();

    output(&items, json, token_budget, |items| {
        if items.is_empty() {
            return format!(
                "No impact found for '{name}'{}{}\n",
                empty_index_hint(&db),
                did_you_mean(&db, &name)
            );
        }
        let mut out = String::new();
        for entry in items {
            let indent = "  ".repeat(entry.depth as usize);
            out.push_str(&format!(
                "{indent}{kind}  {source}  {file}:{line}\n",
                kind = entry.edge.kind,
                source = entry.edge.source_id,
                file = entry.edge.file_path,
                line = entry.edge.line,
            ));
        }
        out
    })
}

/// All references to a symbol (calls, imports, inherits, references, raises).
pub fn cmd_refs(
    db_path: &Path,
    name: &str,
    kind: Option<EdgeKindFilter>,
    json: bool,
    token_budget: Option<u32>,
    embedding_dim: usize,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;
    let kind_filter = kind.map(EdgeKind::from);
    let results = db.refs(name, kind_filter)?;
    if !results.is_empty() {
        db.log_query("refs", "cli");
    }
    let name = name.to_string();

    #[derive(Serialize)]
    struct RefEntry {
        edge: cartog_core::Edge,
        source: Option<cartog_core::Symbol>,
    }

    let items: Vec<RefEntry> = results
        .into_iter()
        .map(|(edge, sym)| RefEntry { edge, source: sym })
        .collect();

    output(&items, json, token_budget, |items| {
        if items.is_empty() {
            return format!(
                "No references found for '{name}'{}{}\n",
                empty_index_hint(&db),
                did_you_mean(&db, &name)
            );
        }
        let mut out = String::new();
        for entry in items {
            let source_name = entry
                .source
                .as_ref()
                .map(|s| s.name.as_str())
                .unwrap_or(&entry.edge.source_id);
            out.push_str(&format!(
                "{kind}  {source}  {file}:{line}\n",
                kind = entry.edge.kind,
                source = source_name,
                file = entry.edge.file_path,
                line = entry.edge.line,
            ));
        }
        out
    })
}

/// Show inheritance hierarchy for a class.
pub fn cmd_hierarchy(
    db_path: &Path,
    name: &str,
    json: bool,
    mermaid: bool,
    token_budget: Option<u32>,
    embedding_dim: usize,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;
    let pairs = db.hierarchy(name)?;
    if !pairs.is_empty() {
        db.log_query("hierarchy", "cli");
    }
    let name = name.to_string();

    // --json wins if both flags are set (matches the documented behavior).
    if mermaid && !json {
        // Surface the same diagnostic the plain branch shows so users running
        // --mermaid on a typo or empty index get the did-you-mean hint
        // alongside the bare `graph TD` document.
        if pairs.is_empty() {
            eprintln!(
                "No hierarchy found for '{name}'{}{}",
                empty_index_hint(&db),
                did_you_mean(&db, &name)
            );
        }
        print!("{}", mermaid::render_hierarchy(&pairs));
        return Ok(());
    }

    #[derive(Serialize)]
    struct HierarchyEntry {
        child: String,
        parent: String,
    }

    let items: Vec<HierarchyEntry> = pairs
        .into_iter()
        .map(|(child, parent)| HierarchyEntry { child, parent })
        .collect();

    output(&items, json, token_budget, |items| {
        if items.is_empty() {
            return format!(
                "No hierarchy found for '{name}'{}{}\n",
                empty_index_hint(&db),
                did_you_mean(&db, &name)
            );
        }
        let mut out = String::new();
        for entry in items {
            out.push_str(&format!("{} -> {}\n", entry.child, entry.parent));
        }
        out
    })
}

/// File-level import dependencies.
pub fn cmd_deps(
    db_path: &Path,
    file: &str,
    json: bool,
    mermaid: bool,
    token_budget: Option<u32>,
    embedding_dim: usize,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;
    let edges = db.file_deps(file)?;
    if !edges.is_empty() {
        db.log_query("deps", "cli");
    }
    let file = file.to_string();

    if mermaid && !json {
        // Surface the same diagnostic the plain branch shows so users running
        // --mermaid against an unindexed file or empty index get the hint.
        if edges.is_empty() {
            eprintln!(
                "No dependencies found for '{file}'{}",
                empty_index_hint(&db)
            );
        }
        let targets: Vec<(String, u32)> = edges
            .iter()
            .map(|e| (e.target_name.clone(), e.line))
            .collect();
        print!("{}", mermaid::render_deps(&file, &targets));
        return Ok(());
    }

    output(&edges, json, token_budget, |edges| {
        if edges.is_empty() {
            return format!(
                "No dependencies found for '{file}'{}\n",
                empty_index_hint(&db)
            );
        }
        let mut out = String::new();
        for edge in edges {
            out.push_str(&format!(
                "{target}  L{line}\n",
                target = edge.target_name,
                line = edge.line
            ));
        }
        out
    })
}

/// Search for symbols by name (case-insensitive prefix + substring match).
#[allow(clippy::too_many_arguments)]
pub fn cmd_search(
    db_path: &Path,
    query: &str,
    kind: Option<SymbolKindFilter>,
    file: Option<&str>,
    limit: u32,
    json: bool,
    token_budget: Option<u32>,
    embedding_dim: usize,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;
    let kind_filter = match kind {
        Some(SymbolKindFilter::All) | None => None,
        Some(k) => Some(cartog_core::SymbolKind::from(k)),
    };
    let limit = limit.min(MAX_SEARCH_LIMIT);
    let symbols = db.search(query, kind_filter, file, limit)?;
    if !symbols.is_empty() {
        db.log_query("search", "cli");
    }
    let query = query.to_string();

    output(&symbols, json, token_budget, |syms| {
        if syms.is_empty() {
            return format!(
                "No symbols found matching '{query}'{}\n",
                empty_index_hint(&db)
            );
        }
        let mut out = String::new();
        for sym in syms {
            out.push_str(&format!(
                "{kind}  {name}  {file}:{line}\n",
                kind = sym.kind,
                name = sym.name,
                file = sym.file_path,
                line = sym.start_line,
            ));
        }
        out
    })
}

/// Upload the local index DB to S3-compatible storage.
pub fn cmd_push(
    db_path: &Path,
    config: &CartogConfig,
    cli_remote: Option<&str>,
    json: bool,
) -> Result<()> {
    remote::push_index(db_path, config, cli_remote, json)
}

/// Download an index DB from S3-compatible storage into the local project.
pub fn cmd_pull(
    db_path: &Path,
    config: &CartogConfig,
    cli_remote: Option<&str>,
    force: bool,
    no_sign_request: bool,
    json: bool,
) -> Result<()> {
    remote::pull_index(db_path, config, cli_remote, force, no_sign_request, json)
}

mod savings;
use savings::{render_savings, savings_scope_label};

/// Index statistics summary.
pub fn cmd_stats(
    db_path: &Path,
    json: bool,
    token_budget: Option<u32>,
    embedding_dim: usize,
    savings: bool,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;

    if savings {
        let report = db.savings_breakdown()?;
        let scope = savings_scope_label(db_path);
        return output(&report, json, token_budget, |r| render_savings(&scope, r));
    }

    let stats = db.stats()?;
    output(&stats, json, token_budget, |stats| {
        let mut out = String::new();
        out.push_str(&format!("Files:    {}\n", stats.num_files));
        out.push_str(&format!("Symbols:  {}\n", stats.num_symbols));
        let mut edge_parts = vec![format!("{} resolved", stats.num_resolved)];
        if stats.num_external > 0 {
            edge_parts.push(format!("{} external", stats.num_external));
        }
        if stats.num_unresolvable > 0 {
            edge_parts.push(format!("{} unresolvable", stats.num_unresolvable));
        }
        out.push_str(&format!(
            "Edges:    {} ({})\n",
            stats.num_edges,
            edge_parts.join(", ")
        ));
        if !stats.languages.is_empty() {
            out.push_str("Languages:\n");
            for (lang, count) in &stats.languages {
                out.push_str(&format!("  {lang}: {count} files\n"));
            }
        }
        if !stats.symbol_kinds.is_empty() {
            out.push_str("Symbols by kind:\n");
            for (kind, count) in &stats.symbol_kinds {
                out.push_str(&format!("  {kind}: {count}\n"));
            }
        }
        if stats.num_files == 0 {
            out.push_str("\nIndex is empty — run `cartog index .` to build the code graph.\n");
        }
        out
    })
}

/// Token-budget-aware codebase summary: file tree + top symbols ranked by centrality.
pub fn cmd_map(
    db_path: &Path,
    tokens: u32,
    json: bool,
    mermaid: bool,
    embedding_dim: usize,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;
    let files = db.all_files()?;

    if files.is_empty() {
        if json {
            println!("{{}}");
        } else if mermaid {
            // Tell the user to index before pasting the (empty) diagram.
            eprintln!("No files indexed. Run `cartog index .` first.");
            println!("graph TD\n    repo[\"Repo (empty)\"]");
        } else {
            println!("No files indexed. Run 'cartog index .' first.");
        }
        return Ok(());
    }

    // Log AFTER the empty-files guard so no-op calls on an unindexed repo
    // don't inflate `cartog savings`.
    db.log_query("map", "cli");

    if mermaid && !json {
        // Honor the token budget by walking files until we exhaust it. The
        // emitted lines look like:
        //   repo --> f_<sane>_<hash8>["<label>"]
        //   f_<sane>_<hash8> --> s_<sane>_<hash8>["<name> (<kind>)"]
        // so per-file overhead is roughly `len(path) * 2 + len(prefix+hash) * 2 + 30`
        // and per-leaf overhead is roughly `len(path) + len(name) * 2 + len(kind) + 50`.
        // The constants are deliberately conservative — better to underfill
        // than overshoot the documented `--tokens` budget.
        let budget_bytes = (tokens as usize) * 4;
        let mut included_files: Vec<&str> = Vec::new();
        let mut size = "graph TD\n    repo[\"Repo\"]\n".len();
        // f_<sanitized>_<hash8> has at least len(path)+13 bytes of ID overhead.
        const FILE_ID_OVERHEAD: usize = 13;
        // s_<sanitized>_<hash8> for a "<file>::<name>" raw key — even longer.
        const SYM_ID_OVERHEAD: usize = 13;
        for f in &files {
            let edge_cost = f.len() * 2 + FILE_ID_OVERHEAD + 30;
            if size + edge_cost > budget_bytes && !included_files.is_empty() {
                break;
            }
            size += edge_cost;
            included_files.push(f.as_str());
        }
        // HashSet so per-symbol membership is O(1), not O(N).
        let included_set: std::collections::HashSet<&str> =
            included_files.iter().copied().collect();
        // Add top symbols per file until budget runs out.
        let symbols = db.top_symbols(500)?;
        let mut symbols_by_file: std::collections::BTreeMap<String, Vec<(String, String)>> =
            std::collections::BTreeMap::new();
        for sym in &symbols {
            if !included_set.contains(sym.file_path.as_str()) {
                continue;
            }
            // The actual emitted leaf carries the file path inside the
            // sym ID (`s_<sanitize(file::name)>_<hash>`), plus the file ID
            // again on the source side of `-->`. Account for both.
            let leaf_cost = sym.name.len() * 2 + sym.file_path.len() + SYM_ID_OVERHEAD * 2 + 50;
            if size + leaf_cost > budget_bytes {
                break;
            }
            size += leaf_cost;
            symbols_by_file
                .entry(sym.file_path.clone())
                .or_default()
                .push((sym.name.clone(), sym.kind.as_str().to_string()));
        }
        let included_owned: Vec<String> = included_files.iter().map(|s| (*s).to_string()).collect();
        let symbols_vec: Vec<(String, Vec<(String, String)>)> =
            symbols_by_file.into_iter().collect();
        print!("{}", mermaid::render_map(&included_owned, &symbols_vec));
        return Ok(());
    }

    if json {
        // For JSON, return structured data without budget constraints
        let symbols = db.top_symbols(200)?;

        #[derive(Serialize)]
        struct MapResult {
            files: Vec<String>,
            top_symbols: Vec<cartog_core::Symbol>,
        }

        let result = MapResult {
            files,
            top_symbols: symbols,
        };
        println!("{}", serde_json::to_string_pretty(&result)?);
        return Ok(());
    }

    // Human-readable: build file tree, then fill remaining budget with symbols
    let budget_bytes = (tokens as usize) * 4;

    // Phase 1: file tree
    let mut out = String::new();
    out.push_str(&format!("# Codebase Map ({} files)\n\n", files.len()));
    for file in &files {
        out.push_str(&format!("  {file}\n"));
    }

    let tree_bytes = out.len();
    let remaining = budget_bytes.saturating_sub(tree_bytes);

    if remaining < 100 {
        print!("{}", truncate_to_budget(&out, tokens));
        return Ok(());
    }

    // Phase 2: top symbols by centrality, grouped by file
    out.push_str("\n# Top Symbols (by reference count)\n\n");

    let symbols = db.top_symbols(500)?;
    let mut current_file = "";

    for sym in &symbols {
        if out.len() >= budget_bytes {
            break;
        }

        if sym.file_path != current_file {
            let header = format!("\n{}:\n", sym.file_path);
            if out.len() + header.len() > budget_bytes {
                break;
            }
            out.push_str(&header);
            current_file = &sym.file_path;
        }

        let sig = sym.signature.as_deref().unwrap_or("");
        let line = format!(
            "  {kind} {name}{sig}  L{start}-{end}  ({refs} refs)\n",
            kind = sym.kind,
            name = sym.name,
            start = sym.start_line,
            end = sym.end_line,
            refs = sym.in_degree,
        );

        if out.len() + line.len() > budget_bytes {
            break;
        }
        out.push_str(&line);
    }

    print!("{out}");
    Ok(())
}

/// Show symbols affected by recent git changes.
pub fn cmd_changes(
    db_path: &Path,
    commits: u32,
    kind: Option<SymbolKindFilter>,
    json: bool,
    token_budget: Option<u32>,
    embedding_dim: usize,
) -> Result<()> {
    let db = open_db(db_path, embedding_dim)?;
    let root = std::env::current_dir()?;

    // Log AFTER the git call succeeds; otherwise non-git directories inflate
    // the savings counter via the `?` propagating an error.
    let changed_files = indexer::git_recently_changed_files(&root, commits)?;
    db.log_query("changes", "cli");

    if changed_files.is_empty() {
        if json {
            println!("[]");
        } else {
            println!("No files changed in the last {commits} commits.");
        }
        return Ok(());
    }

    let kind_filter = match kind {
        Some(SymbolKindFilter::All) | None => None,
        Some(k) => Some(cartog_core::SymbolKind::from(k)),
    };
    let symbols = db.symbols_for_files(&changed_files, kind_filter)?;

    let result = cartog_core::ChangesResult {
        changed_files,
        symbols,
    };

    output(&result, json, token_budget, |r| {
        let mut out = format!(
            "{} files changed in last {} commits, {} symbols affected\n\n",
            r.changed_files.len(),
            commits,
            r.symbols.len()
        );
        let mut current_file = "";
        for sym in &r.symbols {
            if sym.file_path != current_file {
                current_file = &sym.file_path;
                out.push_str(&format!("{current_file}:\n"));
            }
            let sig = sym.signature.as_deref().unwrap_or("");
            out.push_str(&format!(
                "  {kind} {name}{sig}  L{start}-{end}\n",
                kind = sym.kind,
                name = sym.name,
                start = sym.start_line,
                end = sym.end_line,
            ));
        }
        let files_with_symbols: std::collections::HashSet<&str> =
            r.symbols.iter().map(|s| s.file_path.as_str()).collect();
        let unindexed: Vec<_> = r
            .changed_files
            .iter()
            .filter(|f| !files_with_symbols.contains(f.as_str()))
            .collect();
        if !unindexed.is_empty() {
            out.push_str(&format!(
                "\n{} changed files not in index:\n",
                unindexed.len()
            ));
            for f in unindexed {
                out.push_str(&format!("  {f}\n"));
            }
        }
        out
    })
}

// ── RAG Commands ──

/// Download the embedding model.
pub fn cmd_rag_setup(json: bool) -> Result<()> {
    let spinner = if json {
        None
    } else {
        // One-time notice so the multi-hundred-MB download isn't a silent wait.
        // Size matches docs/usage.md (embedding ~80MB + reranker ~1.1GB).
        eprintln!("Downloading embedding + re-ranker models (~1.2GB, one-time)…");
        Spinner::start("Downloading models")
    };
    // Download bi-encoder (embeddings)
    let embed_result = rag::setup::download_model();
    // Download cross-encoder (re-ranking)
    let rerank_result = rag::setup::download_cross_encoder();
    if let Some(s) = spinner {
        s.stop();
    }
    let embed_result = embed_result?;
    let rerank_result = rerank_result?;

    #[derive(serde::Serialize)]
    struct CombinedSetup {
        embedding: rag::setup::SetupResult,
        reranker: rag::setup::SetupResult,
    }

    let combined = CombinedSetup {
        embedding: embed_result,
        reranker: rerank_result,
    };

    output(&combined, json, None, |c| {
        format!(
            "Embedding model: {}\nRe-ranker model: {}\nModels ready. You can now run 'cartog rag index'.\n",
            c.embedding.model_dir, c.reranker.model_dir
        )
    })
}

/// Build embedding index for semantic search.
pub fn cmd_rag_index(
    db_path: &Path,
    path: &str,
    force: bool,
    json: bool,
    provider_config: &rag::EmbeddingProviderConfig,
) -> Result<()> {
    let root = Path::new(path);
    let mut provider = rag::create_embedding_provider(provider_config)?;
    let db = open_db(db_path, provider.dimension())?;
    db.reconcile_embedding_fingerprint(&rag::fingerprint_of(provider.as_ref()))
        .context("failed to reconcile embedding fingerprint")?;

    let spinner = if json {
        None
    } else {
        Spinner::start("Indexing code graph").map(Arc::new)
    };
    let ix_cb = spinner_callback(&spinner, indexer::ProgressUpdate::label);
    let ix_cb_ref: Option<indexer::ProgressCallback<'_>> =
        ix_cb.as_ref().map(|f| f as &(dyn Fn(_) + Send + Sync));
    let index_res = indexer::index_directory(&db, root, false, false, ix_cb_ref, None);
    drop(ix_cb);
    stop_spinner(spinner);
    let _index_result = index_res?;

    let spinner = if json {
        None
    } else {
        Spinner::start("Embedding symbols").map(Arc::new)
    };
    let rag_cb = spinner_callback(&spinner, rag::indexer::ProgressUpdate::label);
    let rag_cb_ref: Option<rag::indexer::ProgressCallback<'_>> =
        rag_cb.as_ref().map(|f| f as &(dyn Fn(_) + Send + Sync));
    let embed_res = rag::indexer::index_embeddings(&db, provider.as_mut(), force, rag_cb_ref, None);
    drop(rag_cb);
    stop_spinner(spinner);
    let result = embed_res?;

    output(&result, json, None, |r| {
        format!(
            "Embedded {} symbols ({} skipped, {} total with content)\n",
            r.symbols_embedded, r.symbols_skipped, r.total_content_symbols
        )
    })
}

/// Semantic search over code symbols.
#[allow(clippy::too_many_arguments)]
pub fn cmd_rag_search(
    db_path: &Path,
    query: &str,
    kind: Option<SymbolKindFilter>,
    limit: u32,
    json: bool,
    token_budget: Option<u32>,
    provider_config: &rag::EmbeddingProviderConfig,
    tuning: &rag::search::SearchTuning,
) -> Result<()> {
    let mut provider = rag::create_embedding_provider(provider_config)?;
    let db = open_db(db_path, provider.dimension())?;
    // NOTE: `cartog rag search` deliberately does NOT call
    // `reconcile_embedding_fingerprint`. The reconcile is destructive
    // (drops `symbol_vec` on mismatch) and can race a primary
    // `cartog serve` writer if the user's `.cartog.toml` changed since
    // last index. Search is read-only by nature; if the fingerprint
    // mismatches, the user gets the embeddings produced by the previous
    // provider — possibly poor results, but no data loss. Re-embedding
    // is `cartog rag index`'s job, which DOES reconcile.
    let kind_filter = match kind {
        Some(SymbolKindFilter::All) => rag::search::KindFilter::All,
        Some(k) => rag::search::KindFilter::Exact(cartog_core::SymbolKind::from(k)),
        None => rag::search::KindFilter::CodeOnly,
    };

    // Lazy reranker: the cross-encoder ONNX model is loaded only if retrieval
    // produced enough candidates for `rerank_min` to fire. For a one-shot CLI
    // command that may return fewer than `rerank_min` hits, this avoids
    // ~100-200ms of model-load latency + memory on every invocation.
    let reranker_factory = if provider_config.reranker_provider == "none" {
        None
    } else {
        let name = provider_config.reranker_provider.clone();
        Some(move || rag::create_reranker_provider(&name))
    };
    let search_result = rag::search::hybrid_search_tuned_lazy(
        &db,
        query,
        limit,
        kind_filter,
        provider.as_mut(),
        reranker_factory,
        tuning,
    )?;
    db.log_query("rag_search", "cli");
    let query = query.to_string();

    output(&search_result, json, token_budget, |sr| {
        if sr.results.is_empty() {
            let mut out = format!("No results found for '{query}'\n");
            if sr.fts_count == 0 && sr.vec_count == 0 {
                out.push_str("Hint: run 'cartog rag index' to build the semantic search index.\n");
            }
            return out;
        }
        let mut out = format!(
            "Found {} results (FTS: {}, vector: {}, merged: {})\n\n",
            sr.results.len(),
            sr.fts_count,
            sr.vec_count,
            sr.merged_count
        );
        for (i, r) in sr.results.iter().enumerate() {
            let sources = r
                .sources
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join("+");
            let rerank_str = r
                .rerank_score
                .map(|s| format!(" rerank={s:.2}"))
                .unwrap_or_default();
            out.push_str(&format!(
                "{}. {} {}  {}:{}-{}  [{}] score={:.4}{rerank_str}\n",
                i + 1,
                r.symbol.kind,
                r.symbol.name,
                r.symbol.file_path,
                r.symbol.start_line,
                r.symbol.end_line,
                sources,
                r.rrf_score,
            ));
            if let Some(ref content) = r.content {
                let preview: String = content
                    .lines()
                    .take(3)
                    .map(|l| format!("    {l}"))
                    .collect::<Vec<_>>()
                    .join("\n");
                out.push_str(&format!("{preview}\n\n"));
            }
        }
        out
    })
}

mod config_display;
pub use config_display::cmd_config;

mod doctor;
pub use doctor::cmd_doctor;

/// Watch for file changes and auto-re-index.
#[allow(clippy::too_many_arguments)]
pub fn cmd_watch(
    db_path: &Path,
    path: &str,
    debounce: u64,
    rag: bool,
    rag_delay: u64,
    provider_config: rag::EmbeddingProviderConfig,
    json: bool,
) -> Result<()> {
    let mut config = WatchConfig::new(PathBuf::from(path));
    config.debounce = Duration::from_secs(debounce);
    config.rag = rag;
    config.rag_delay = Duration::from_secs(rag_delay);
    config.rag_config = provider_config;
    config.json_events = json;
    // pid_lock_dir/slot must be both-or-neither: a sandboxed host with no
    // resolvable state dir falls back to untracked mode rather than hard-
    // failing on the inverse half-config check in validate_pid_lock_config.
    config.pid_lock_dir = crate::state::default_state_dir();
    config.pid_lock_slot = config
        .pid_lock_dir
        .as_ref()
        .map(|_| crate::state::slot_for_db("watch", db_path));

    let db_path_str = db_path.to_string_lossy();
    watch::run_watch(config, &db_path_str)
}

mod self_cmd;
pub use self_cmd::{
    cmd_self_migrate_db, cmd_self_rollback, cmd_self_update, cmd_self_version, UpdateMode,
};

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

    #[test]
    fn capitalized_index_phase_labels() {
        use indexer::ProgressUpdate as U;
        let cap = |u: &U| capitalize_phase(u.label());
        assert_eq!(cap(&U::Walking), "Scanning files");
        assert_eq!(cap(&U::Parsing { total: 12 }), "Parsing 12 files");
        assert_eq!(cap(&U::Storing { total: 5 }), "Storing 5 files");
        assert_eq!(cap(&U::ResolvingLsp), "Resolving edges with LSP");
    }

    #[test]
    fn capitalized_rag_phase_labels() {
        use rag::indexer::ProgressUpdate as U;
        let cap = |u: &U| capitalize_phase(u.label());
        assert_eq!(cap(&U::Preparing), "Preparing");
        assert_eq!(
            cap(&U::Embedding {
                processed: 64,
                total: 256
            }),
            "Embedding 64/256"
        );
        assert_eq!(cap(&U::Storing), "Storing embeddings");
    }

    #[test]
    fn capitalize_phase_handles_empty() {
        assert_eq!(capitalize_phase(String::new()), "");
    }

    #[test]
    fn empty_index_hint_present_on_fresh_db() {
        // Non-empty case is covered by cartog-db's is_empty_reflects_symbol_presence.
        let db = Database::open_memory().unwrap();
        assert!(empty_index_hint(&db).contains("cartog index"));
    }

    fn db_with_symbol(name: &str) -> Database {
        use cartog_core::{FileInfo, Symbol};
        let db = Database::open_memory().unwrap();
        db.upsert_file(&FileInfo {
            path: "a.rs".into(),
            last_modified: 0.0,
            hash: "h".into(),
            language: "rust".into(),
            num_symbols: 1,
        })
        .unwrap();
        let sym = Symbol::new(name, SymbolKind::Class, "a.rs", 1, 2, 0, 10, None);
        db.insert_symbols(&[sym]).unwrap();
        db
    }

    #[test]
    fn open_db_error_corrupt_names_path_and_rebuild() {
        let e = anyhow::anyhow!("file is not a database");
        let msg = open_db_error(Path::new("/p/.cartog/db.sqlite"), e).to_string();
        assert!(msg.contains("/p/.cartog/db.sqlite"), "names path: {msg}");
        assert!(msg.contains("corrupt"), "{msg}");
        assert!(msg.contains("cartog index"), "{msg}");
    }

    #[test]
    fn open_db_error_readonly_names_path_and_permissions() {
        let e = anyhow::anyhow!("attempt to write a readonly database");
        let msg = open_db_error(Path::new("/p/db.sqlite"), e).to_string();
        assert!(msg.contains("/p/db.sqlite"), "{msg}");
        assert!(msg.contains("permission"), "{msg}");
    }

    #[test]
    fn open_db_error_generic_keeps_path() {
        let e = anyhow::anyhow!("disk full");
        let msg = open_db_error(Path::new("/p/db.sqlite"), e).to_string();
        assert!(msg.contains("/p/db.sqlite"), "{msg}");
    }

    #[test]
    fn did_you_mean_suggests_near_matches() {
        let db = db_with_symbol("ReviewResult");
        let hint = did_you_mean(&db, "Revie");
        assert!(hint.contains("did you mean"), "got: {hint}");
        assert!(hint.contains("ReviewResult"), "got: {hint}");
    }

    #[test]
    fn did_you_mean_silent_on_exact_match() {
        // An exact match means the symbol exists but has no edges — no suggestion.
        let db = db_with_symbol("ReviewResult");
        assert_eq!(did_you_mean(&db, "ReviewResult"), "");
    }

    #[test]
    fn did_you_mean_silent_on_empty_index() {
        let db = Database::open_memory().unwrap();
        assert_eq!(did_you_mean(&db, "Whatever"), "");
    }

    #[test]
    fn did_you_mean_silent_when_no_candidates() {
        let db = db_with_symbol("ReviewResult");
        assert_eq!(did_you_mean(&db, "ZZZnomatch"), "");
    }

    #[test]
    fn test_estimate_tokens() {
        assert_eq!(estimate_tokens(""), 0);
        assert_eq!(estimate_tokens("a"), 1);
        assert_eq!(estimate_tokens("abcd"), 1);
        assert_eq!(estimate_tokens("abcde"), 2);
        assert_eq!(estimate_tokens("abcdefgh"), 2);
    }

    #[test]
    fn test_truncate_to_budget_within_limit() {
        let text = "short text";
        let result = truncate_to_budget(text, 100);
        assert_eq!(result, text);
    }

    #[test]
    fn test_truncate_to_budget_exceeds_limit() {
        let text = "a".repeat(200);
        let result = truncate_to_budget(&text, 10);
        assert!(result.len() <= 40 + 50); // budget bytes + notice
        assert!(result.ends_with("... (truncated to fit token budget)"));
    }

    #[test]
    fn test_truncate_to_budget_exact_boundary() {
        let text = "abcd"; // 4 bytes = 1 token
        let result = truncate_to_budget(text, 1);
        assert_eq!(result, "abcd");
    }

    #[test]
    fn test_truncate_to_budget_unicode() {
        // Each emoji is 4 bytes
        let text = "Hello 🌍🌍🌍🌍🌍🌍🌍🌍🌍🌍";
        let result = truncate_to_budget(text, 5);
        assert!(result.ends_with("... (truncated to fit token budget)"));
        // Should not panic on char boundary issues
    }

    // ── cmd_* command bodies over a real indexed DB ───────────────────
    //
    // Drive the read commands end-to-end against a temp DB populated from a
    // small Python fixture. The commands print to stdout (so output content
    // can't be asserted directly), but calling them exercises the real query,
    // the human/JSON formatter closures, the empty-result did-you-mean paths,
    // and the token-budget branch — returning Ok/Err is the observable
    // contract. Query-log side effects are verified via savings_breakdown.

    const CMD_FIXTURE_SRC: &str = "\
class Animal:
    def speak(self):
        return helper()


class Dog(Animal):
    def speak(self):
        return helper()


def helper():
    return 42


def main():
    d = Dog()
    return d.speak()
";

    /// Index `CMD_FIXTURE_SRC` as `lib.py` and return the DB path. The TempDir
    /// is returned so the caller keeps it alive for the test's duration. The
    /// index root is a named subdir: the walker prunes dot-prefixed dirs, and
    /// a bare TempDir name starts with ".tmp".
    fn indexed_db() -> (tempfile::TempDir, std::path::PathBuf) {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("project");
        std::fs::create_dir(&root).unwrap();
        std::fs::write(root.join("lib.py"), CMD_FIXTURE_SRC).unwrap();
        let db_path = tmp.path().join("cartog.db");
        let db = Database::open(&db_path, 384).unwrap();
        indexer::index_directory(&db, &root, true, false, None, None).expect("fixture indexes");
        drop(db);
        (tmp, db_path)
    }

    /// Logged query count — a delta proves a command hit the query layer
    /// (commands print to stdout, so rendered content can't be asserted here).
    fn queries_logged(db_path: &std::path::Path) -> u64 {
        Database::open(db_path, 384)
            .unwrap()
            .savings_breakdown()
            .unwrap()
            .total_queries
    }

    #[test]
    fn cmd_outline_runs_a_query_for_a_populated_file() {
        let (_tmp, db) = indexed_db();
        let before = queries_logged(&db);
        cmd_outline(&db, "lib.py", false, None, 384).expect("outline ok");
        assert_eq!(
            queries_logged(&db),
            before + 1,
            "outline of a populated file must run exactly one query"
        );
    }

    #[test]
    fn cmd_outline_json_branch_does_not_error() {
        let (_tmp, db) = indexed_db();
        cmd_outline(&db, "lib.py", true, None, 384).expect("outline --json ok");
    }

    #[test]
    fn cmd_outline_unknown_file_does_not_error() {
        let (_tmp, db) = indexed_db();
        cmd_outline(&db, "missing.py", false, None, 384).expect("outline of unknown file is ok");
    }

    #[test]
    fn cmd_refs_runs_a_query_per_invocation_with_and_without_kind_filter() {
        let (_tmp, db) = indexed_db();
        let before = queries_logged(&db);
        cmd_refs(&db, "helper", None, false, None, 384).expect("refs ok");
        cmd_refs(&db, "helper", Some(EdgeKindFilter::Calls), false, None, 384)
            .expect("refs --kind calls ok");
        assert_eq!(
            queries_logged(&db),
            before + 2,
            "each refs invocation must run a query"
        );
    }

    #[test]
    fn cmd_refs_near_miss_name_takes_the_did_you_mean_branch_without_error() {
        let (_tmp, db) = indexed_db();
        // Empty result triggers the did_you_mean / empty_index_hint branch.
        cmd_refs(&db, "helpe", None, false, None, 384).expect("refs of near-miss name is ok");
    }

    #[test]
    fn cmd_callees_logs_a_query_only_when_it_finds_results() {
        let (_tmp, db) = indexed_db();
        let before = queries_logged(&db);
        cmd_callees(&db, "main", false, None, 384).expect("callees ok");
        let after_hit = queries_logged(&db);
        cmd_callees(&db, "no_such_symbol", false, None, 384).expect("empty callees is ok");
        let after_miss = queries_logged(&db);

        assert_eq!(after_hit, before + 1, "a callees hit logs one query");
        assert_eq!(
            after_miss, after_hit,
            "an empty callees result must not log a query"
        );
    }

    #[test]
    fn cmd_impact_plain_and_json_branches_do_not_error() {
        let (_tmp, db) = indexed_db();
        cmd_impact(&db, "helper", 3, false, None, 384).expect("impact ok");
        cmd_impact(&db, "helper", 3, true, None, 384).expect("impact --json ok");
    }

    #[test]
    fn cmd_hierarchy_plain_json_and_mermaid_branches_do_not_error() {
        let (_tmp, db) = indexed_db();
        cmd_hierarchy(&db, "Dog", false, false, None, 384).expect("hierarchy ok");
        cmd_hierarchy(&db, "Dog", true, false, None, 384).expect("hierarchy --json ok");
        cmd_hierarchy(&db, "Dog", false, true, None, 384).expect("hierarchy --mermaid ok");
    }

    #[test]
    fn cmd_deps_plain_and_mermaid_branches_do_not_error() {
        let (_tmp, db) = indexed_db();
        cmd_deps(&db, "lib.py", false, false, None, 384).expect("deps ok");
        cmd_deps(&db, "lib.py", false, true, None, 384).expect("deps --mermaid ok");
    }

    #[test]
    fn cmd_search_runs_a_query_for_each_filter_and_budget_branch() {
        let (_tmp, db) = indexed_db();
        let before = queries_logged(&db);
        cmd_search(&db, "Anim", None, None, 30, false, None, 384).expect("search ok");
        cmd_search(
            &db,
            "speak",
            Some(SymbolKindFilter::Method),
            Some("lib.py"),
            30,
            false,
            None,
            384,
        )
        .expect("search with kind + file filter ok");
        // Token-budget branch.
        cmd_search(&db, "e", None, None, 30, false, Some(50), 384).expect("search --tokens ok");
        assert_eq!(
            queries_logged(&db),
            before + 3,
            "each search invocation must run a query"
        );
    }

    #[test]
    fn cmd_search_empty_result_does_not_error() {
        let (_tmp, db) = indexed_db();
        cmd_search(&db, "zzz_no_match", None, None, 30, false, None, 384)
            .expect("empty search is ok");
    }

    #[test]
    fn cmd_stats_plain_json_and_savings_branches_do_not_error() {
        let (_tmp, db) = indexed_db();
        cmd_stats(&db, false, None, 384, false).expect("stats ok");
        cmd_stats(&db, true, None, 384, false).expect("stats --json ok");
        cmd_stats(&db, false, None, 384, true).expect("stats --savings ok");
    }

    #[test]
    fn cmd_map_plain_json_and_mermaid_branches_do_not_error() {
        let (_tmp, db) = indexed_db();
        cmd_map(&db, 1000, false, false, 384).expect("map ok");
        cmd_map(&db, 1000, true, false, 384).expect("map --json ok");
        cmd_map(&db, 1000, false, true, 384).expect("map --mermaid ok");
    }
}