tessera-codegraph 0.8.0

A local, deterministic semantic code graph and MCP server for AI coding agents. 11 languages, personalized PageRank impact, hallucination validator, call-path tracing, graph export, incremental indexing.
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
use std::io::Read;
use std::path::PathBuf;
use std::time::Duration;

use anyhow::{anyhow, Result};
use clap::{Parser, Subcommand, ValueEnum};

use tessera_codegraph::bench::{self, BenchOptions};
use tessera_codegraph::completions::{self, CompletionShell};
use tessera_codegraph::db;
use tessera_codegraph::doctor::{self, DoctorOptions};
use tessera_codegraph::indexer::{self, IndexOptions};
use tessera_codegraph::init::{self, InitOptions};
use tessera_codegraph::mcp;
use tessera_codegraph::mcp_http;
use tessera_codegraph::query;
use tessera_codegraph::snapshot;
use tessera_codegraph::types::{GraphEngineKind, Language, SearchOptions, UnusedOptions};
use tessera_codegraph::watch::{self, WatchOptions};
use tessera_codegraph::{ExportGroupBy, ExportOptions};

#[derive(Debug, Parser)]
#[command(name = "tessera")]
#[command(version)]
#[command(about = "Semantic code graph and MCP server for AI coding agents")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Clone, ValueEnum)]
enum LangArg {
    Typescript,
    Tsx,
    Javascript,
    Python,
    Go,
    Rust,
    Java,
    C,
    Cpp,
    Csharp,
    Ruby,
    Php,
}

impl From<LangArg> for Language {
    fn from(value: LangArg) -> Self {
        match value {
            LangArg::Typescript => Language::TypeScript,
            LangArg::Tsx => Language::Tsx,
            LangArg::Javascript => Language::JavaScript,
            LangArg::Python => Language::Python,
            LangArg::Go => Language::Go,
            LangArg::Rust => Language::Rust,
            LangArg::Java => Language::Java,
            LangArg::C => Language::C,
            LangArg::Cpp => Language::Cpp,
            LangArg::Csharp => Language::CSharp,
            LangArg::Ruby => Language::Ruby,
            LangArg::Php => Language::Php,
        }
    }
}

#[derive(Debug, Clone, ValueEnum, Default)]
enum GraphFormat {
    #[default]
    Mermaid,
    Dot,
}

#[derive(Debug, Clone, Copy, ValueEnum, Default)]
enum GraphGroupArg {
    #[default]
    None,
    File,
    Directory,
    Language,
}

impl From<GraphGroupArg> for ExportGroupBy {
    fn from(value: GraphGroupArg) -> Self {
        match value {
            GraphGroupArg::None => ExportGroupBy::None,
            GraphGroupArg::File => ExportGroupBy::File,
            GraphGroupArg::Directory => ExportGroupBy::Directory,
            GraphGroupArg::Language => ExportGroupBy::Language,
        }
    }
}

impl GraphFormat {
    fn as_str(&self) -> &'static str {
        match self {
            GraphFormat::Mermaid => "mermaid",
            GraphFormat::Dot => "dot",
        }
    }
}

#[derive(Debug, Clone, ValueEnum, Default)]
enum EngineArg {
    #[default]
    Sqlite,
    Cozo,
}

impl From<EngineArg> for GraphEngineKind {
    fn from(value: EngineArg) -> Self {
        match value {
            EngineArg::Sqlite => GraphEngineKind::Sqlite,
            EngineArg::Cozo => GraphEngineKind::Cozo,
        }
    }
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum CompletionShellArg {
    Bash,
    Zsh,
    Fish,
    Powershell,
}

impl From<CompletionShellArg> for CompletionShell {
    fn from(value: CompletionShellArg) -> Self {
        match value {
            CompletionShellArg::Bash => CompletionShell::Bash,
            CompletionShellArg::Zsh => CompletionShell::Zsh,
            CompletionShellArg::Fish => CompletionShell::Fish,
            CompletionShellArg::Powershell => CompletionShell::Powershell,
        }
    }
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Index a repository into a SQLite semantic graph (incremental by default).
    Index {
        /// Repository or directory to index.
        path: PathBuf,
        /// SQLite database path.
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        /// Re-index from scratch instead of using the sha-diff incremental path.
        #[arg(long)]
        full: bool,
        /// Skip writing the memory-mapped snapshot at the end of indexing.
        #[arg(long)]
        no_snapshot: bool,
        /// Graph engine to use for impact queries. Cozo requires `--features cozo`.
        #[arg(long, value_enum, default_value_t = EngineArg::Sqlite)]
        graph_engine: EngineArg,
    },
    /// Watch a repository and incrementally re-index when source files change.
    Watch {
        /// Repository or directory to watch.
        path: PathBuf,
        /// SQLite database path.
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        /// Re-index from scratch instead of using the sha-diff incremental path.
        #[arg(long)]
        full: bool,
        /// Skip writing the memory-mapped snapshot after indexing.
        #[arg(long)]
        no_snapshot: bool,
        /// Poll interval in milliseconds.
        #[arg(long, default_value_t = 500)]
        poll_ms: u64,
        /// Debounce interval in milliseconds after a detected change.
        #[arg(long, default_value_t = 250)]
        debounce_ms: u64,
        /// Run one indexing pass and exit. Useful for smoke tests and CI.
        #[arg(long)]
        once: bool,
    },
    /// Check local Tessera setup and print actionable diagnostics.
    Doctor {
        /// Repository root to inspect.
        #[arg(long, default_value = ".")]
        root: PathBuf,
        /// SQLite database path.
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Create project-local Tessera defaults and optional integration snippets.
    Init {
        /// Repository root to initialize.
        #[arg(default_value = ".")]
        root: PathBuf,
        /// SQLite database path to write into generated snippets.
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        /// Create local git hooks that run `tessera index .`.
        #[arg(long)]
        git_hooks: bool,
        /// Create MCP config snippets under `.tessera/mcp/`.
        #[arg(long)]
        mcp_configs: bool,
        /// Overwrite existing generated files.
        #[arg(long)]
        force: bool,
        #[arg(long)]
        json: bool,
    },
    /// Print shell completion script.
    Completions {
        #[arg(value_enum)]
        shell: CompletionShellArg,
    },
    /// Find symbol definitions by name.
    FindDefinition {
        symbol: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Find call/reference sites for a symbol.
    FindReferences {
        symbol: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Return a token-cheap semantic outline for a file or directory.
    GetOutline {
        path: PathBuf,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Return a symbol body plus immediate dependencies.
    ExpandSymbol {
        symbol: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Return transitive callers ranked by personalised PageRank.
    Impact {
        symbol: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long, default_value_t = 4)]
        depth: usize,
        /// Explain ranking and matching decisions in human output.
        #[arg(long, alias = "why")]
        explain: bool,
        #[arg(long)]
        json: bool,
    },
    /// Check whether a symbol exists in the graph; suggest near-misses if not.
    Validate {
        symbol: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        /// Explain bloom and near-miss decisions in human output.
        #[arg(long, alias = "why")]
        explain: bool,
        #[arg(long)]
        json: bool,
    },
    /// Parse a code snippet and validate every call against the graph.
    ValidateSnippet {
        #[arg(long, value_enum)]
        language: LangArg,
        /// Read the snippet from this file. If omitted, read from stdin.
        #[arg(long)]
        file: Option<PathBuf>,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Print index statistics.
    Stats {
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Fuzzy / glob search across indexed symbols, filterable by kind,
    /// language, exported, and path prefix.
    Search {
        /// Substring, identifier, or `glob*` pattern.
        pattern: String,
        /// Filter by symbol kind (function, method, class, struct, …).
        /// Repeat or comma-separate to allow multiple.
        #[arg(long, value_delimiter = ',')]
        kind: Vec<String>,
        /// Filter by language (typescript, java, python, …).
        #[arg(long, value_delimiter = ',')]
        language: Vec<String>,
        /// Only show exported symbols (`--exported`) or only non-exported
        /// (`--exported=false`).
        #[arg(long, num_args = 0..=1, default_missing_value = "true")]
        exported: Option<bool>,
        /// Match symbols whose file path starts with this prefix.
        #[arg(long)]
        path: Option<String>,
        #[arg(long, default_value_t = 50)]
        limit: usize,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        /// Explain fuzzy/glob scoring and filters in human output.
        #[arg(long, alias = "why")]
        explain: bool,
        #[arg(long)]
        json: bool,
    },
    /// Find indexed symbols with no inbound references or call edges.
    Unused {
        /// Filter by symbol kind (function, method, class, struct, ...).
        /// Repeat or comma-separate to allow multiple.
        #[arg(long, value_delimiter = ',')]
        kind: Vec<String>,
        /// Filter by language (typescript, java, python, ...).
        #[arg(long, value_delimiter = ',')]
        language: Vec<String>,
        /// Only show exported symbols (`--exported`) or only non-exported
        /// (`--exported=false`).
        #[arg(long, num_args = 0..=1, default_missing_value = "true")]
        exported: Option<bool>,
        /// Match symbols whose file path starts with this prefix.
        #[arg(long)]
        path: Option<String>,
        #[arg(long, default_value_t = 50)]
        limit: usize,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        /// Explain why symbols qualify as unused in human output.
        #[arg(long, alias = "why")]
        explain: bool,
        #[arg(long)]
        json: bool,
    },
    /// Bundle body + dep signatures + caller signatures + tests for an agent
    /// to "understand" a symbol in one tool call.
    ContextPack {
        symbol: String,
        /// Token budget (default 1500).
        #[arg(long, default_value_t = 1500)]
        budget: usize,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Recommend the cheapest Tessera tool sequence for an agent task.
    PlanQuery {
        /// Natural-language task shape, for example "edit findById safely".
        task: String,
        /// Optional symbol to substitute into the recommended commands.
        #[arg(long)]
        symbol: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Bundle validation, signature, siblings, context, and tests before editing.
    EditPrep {
        symbol: String,
        /// Token budget for the embedded context pack (default 1800).
        #[arg(long, default_value_t = 1800)]
        budget: usize,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Map a git range to changed symbols + their PageRank-impacted callers.
    DiffImpact {
        /// Base git ref (e.g. `main`, `origin/main`, `HEAD~5`).
        from: String,
        /// Tip ref (defaults to `HEAD`).
        #[arg(long)]
        to: Option<String>,
        #[arg(long, default_value_t = 3)]
        depth: usize,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// List the imports declared in a file or directory.
    Imports {
        path: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// List files that import a given module / source path.
    ImportedBy {
        source: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Return just the signature (and, for containers, member signatures) of a symbol.
    Signature {
        symbol: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Symbols that share callers with the target — the cluster to refactor together.
    Siblings {
        symbol: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Return the minimal set of tests whose call graph touches the symbol.
    TestsFor {
        symbol: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Find the shortest call path from one symbol to another (A calls … calls B).
    Connect {
        from: String,
        to: String,
        #[arg(long, default_value_t = 8)]
        depth: usize,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Export the call graph as Graphviz DOT or Mermaid (whole graph, or a
    /// neighbourhood with `--from`).
    Export {
        /// Output format.
        #[arg(long, value_enum, default_value_t = GraphFormat::Mermaid)]
        format: GraphFormat,
        /// Restrict to the forward call subgraph rooted at this symbol.
        #[arg(long)]
        from: Option<String>,
        /// Traversal depth when `--from` is given.
        #[arg(long, default_value_t = 3)]
        depth: usize,
        /// Maximum number of edges to emit.
        #[arg(long, default_value_t = 800)]
        limit: usize,
        /// Group rendered graph nodes.
        #[arg(long, value_enum, default_value_t = GraphGroupArg::None)]
        group_by: GraphGroupArg,
        /// Hide test/spec nodes and their edges from the export.
        #[arg(long)]
        collapse_tests: bool,
        /// Only include edges whose endpoints are exported symbols.
        #[arg(long)]
        exported_only: bool,
        /// Write a self-contained Mermaid preview HTML file.
        #[arg(long)]
        html_out: Option<PathBuf>,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Run a benchmark and emit the perf chart used in the README.
    Bench {
        #[arg(long)]
        path: Option<PathBuf>,
        #[arg(long)]
        probe: Option<String>,
        /// Synthetic-repo size when no --path is given.
        #[arg(long, default_value_t = 50)]
        scale: usize,
        #[arg(long)]
        out: Option<PathBuf>,
        #[arg(long)]
        json: bool,
    },
    /// (Re)build the memory-mapped snapshot used by the MCP server.
    Snapshot {
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
    },
    /// Run the MCP server over stdio.
    Mcp {
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
    },
    /// Run the MCP server over local HTTP with a simple SSE readiness endpoint.
    McpHttp {
        /// Address to bind, for example 127.0.0.1:8765.
        #[arg(long, default_value = "127.0.0.1:8765")]
        addr: String,
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
    },
    /// Start a tiny interactive query shell.
    Shell {
        #[arg(long, default_value = ".tessera/tessera.db")]
        db: PathBuf,
    },
}

fn main() -> Result<()> {
    #[cfg(windows)]
    {
        return std::thread::Builder::new()
            .name("tessera-main".to_string())
            .stack_size(8 * 1024 * 1024)
            .spawn(run)?
            .join()
            .map_err(|_| anyhow!("tessera main thread panicked"))?;
    }

    #[cfg(not(windows))]
    run()
}

fn run() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Index {
            path,
            db,
            full,
            no_snapshot,
            graph_engine,
        } => {
            let engine: GraphEngineKind = graph_engine.into();
            if matches!(engine, GraphEngineKind::Cozo) && !cfg!(feature = "cozo") {
                return Err(anyhow!(
                    "Cozo backend not compiled in. Rebuild with `cargo install --features cozo`."
                ));
            }
            let options = IndexOptions {
                full,
                build_snapshot: !no_snapshot,
            };
            let report = indexer::index_path_with(&path, &db, options)?;
            let mode = match report.mode {
                indexer::IndexMode::Full => "full",
                indexer::IndexMode::Incremental => "incremental",
            };
            println!(
                "[{mode}] indexed {} files (+{} reused, -{} removed), {} symbols, {} references into {} in {}ms",
                report.files_indexed,
                report.files_reused,
                report.files_removed,
                report.symbols_indexed,
                report.references_indexed,
                db.display(),
                report.elapsed_ms
            );
            print_index_warnings(&report.warnings);
        }
        Commands::Watch {
            path,
            db,
            full,
            no_snapshot,
            poll_ms,
            debounce_ms,
            once,
        } => {
            let options = WatchOptions {
                poll_interval: Duration::from_millis(poll_ms),
                debounce: Duration::from_millis(debounce_ms),
                index_options: IndexOptions {
                    full,
                    build_snapshot: !no_snapshot,
                },
                once,
            };
            watch::watch_path(&path, &db, options)?;
        }
        Commands::Doctor { root, db, json } => {
            let result = doctor::run(DoctorOptions { root, db_path: db })?;
            print_result(result, json)?;
        }
        Commands::Init {
            root,
            db,
            git_hooks,
            mcp_configs,
            force,
            json,
        } => {
            let result = init::run(InitOptions {
                root,
                db_path: db,
                git_hooks,
                mcp_configs,
                force,
            })?;
            print_result(result, json)?;
        }
        Commands::Completions { shell } => {
            print!("{}", completions::generate(shell.into()));
        }
        Commands::FindDefinition { symbol, db, json } => {
            print_result(query::find_definition(&db, &symbol)?, json)?;
        }
        Commands::FindReferences { symbol, db, json } => {
            print_result(query::find_references(&db, &symbol)?, json)?;
        }
        Commands::GetOutline { path, db, json } => {
            print_result(query::get_outline(&db, &path)?, json)?;
        }
        Commands::ExpandSymbol { symbol, db, json } => {
            print_result(query::expand_symbol(&db, &symbol)?, json)?;
        }
        Commands::Impact {
            symbol,
            db,
            depth,
            explain,
            json,
        } => {
            let result = query::impact(&db, &symbol, depth)?;
            print_result(&result, json)?;
            if explain && !json {
                explain_impact(&result);
            }
        }
        Commands::Validate {
            symbol,
            db,
            explain,
            json,
        } => {
            let result = query::validate(&db, &symbol)?;
            print_result(&result, json)?;
            if explain && !json {
                explain_validate(&result);
            }
        }
        Commands::ValidateSnippet {
            language,
            file,
            db,
            json,
        } => {
            let code = match file {
                Some(path) => std::fs::read_to_string(path)?,
                None => {
                    let mut buf = String::new();
                    std::io::stdin().read_to_string(&mut buf)?;
                    buf
                }
            };
            let result = query::validate_snippet(&db, &code, language.into())?;
            print_result(result, json)?;
        }
        Commands::Stats { db, json } => {
            print_result(query::stats(&db)?, json)?;
        }
        Commands::TestsFor { symbol, db, json } => {
            print_result(query::tests_for(&db, &symbol)?, json)?;
        }
        Commands::Connect {
            from,
            to,
            depth,
            db,
            json,
        } => {
            print_result(query::connect(&db, &from, &to, depth)?, json)?;
        }
        Commands::Export {
            format,
            from,
            depth,
            limit,
            group_by,
            collapse_tests,
            exported_only,
            html_out,
            db,
            json,
        } => {
            let mut options = ExportOptions::new(format.as_str(), from.as_deref(), depth, limit);
            options.group_by = group_by.into();
            options.collapse_tests = collapse_tests;
            options.exported_only = exported_only;
            options.html_out = html_out;
            print_result(query::export_with_options(&db, options)?, json)?;
        }
        Commands::ContextPack {
            symbol,
            budget,
            db,
            json,
        } => {
            print_result(query::context_pack(&db, &symbol, budget)?, json)?;
        }
        Commands::PlanQuery { task, symbol, json } => {
            print_result(query::plan_query(&task, symbol.as_deref()), json)?;
        }
        Commands::EditPrep {
            symbol,
            budget,
            db,
            json,
        } => {
            print_result(query::edit_prep(&db, &symbol, budget)?, json)?;
        }
        Commands::DiffImpact {
            from,
            to,
            depth,
            db,
            json,
        } => {
            print_result(query::diff_impact(&db, &from, to.as_deref(), depth)?, json)?;
        }
        Commands::Imports { path, db, json } => {
            print_result(query::imports(&db, &path)?, json)?;
        }
        Commands::ImportedBy { source, db, json } => {
            print_result(query::imported_by(&db, &source)?, json)?;
        }
        Commands::Signature { symbol, db, json } => {
            print_result(query::signature(&db, &symbol)?, json)?;
        }
        Commands::Siblings { symbol, db, json } => {
            print_result(query::siblings(&db, &symbol)?, json)?;
        }
        Commands::Search {
            pattern,
            kind,
            language,
            exported,
            path,
            limit,
            db,
            explain,
            json,
        } => {
            let options = SearchOptions {
                kinds: kind,
                languages: language,
                exported,
                path_prefix: path,
                limit,
            };
            let result = query::search(&db, &pattern, options)?;
            print_result(&result, json)?;
            if explain && !json {
                explain_search(&result);
            }
        }
        Commands::Unused {
            kind,
            language,
            exported,
            path,
            limit,
            db,
            explain,
            json,
        } => {
            let options = UnusedOptions {
                kinds: kind,
                languages: language,
                exported,
                path_prefix: path,
                limit,
            };
            let result = query::unused(&db, options)?;
            print_result(&result, json)?;
            if explain && !json {
                explain_unused(&result);
            }
        }
        Commands::Bench {
            path,
            probe,
            scale,
            out,
            json,
        } => {
            let result = bench::run(BenchOptions {
                path,
                probe_symbol: probe,
                scale: Some(scale),
            })?;
            if let Some(out_path) = out {
                std::fs::write(&out_path, &result.chart)?;
            }
            if json {
                println!("{}", serde_json::to_string_pretty(&result)?);
            } else {
                println!("{}", result.chart);
            }
        }
        Commands::Snapshot { db } => {
            let conn = db::open(&db)?;
            let snapshot_path = db
                .parent()
                .map(|p| p.join("snapshot.bin"))
                .unwrap_or_else(|| PathBuf::from("snapshot.bin"));
            snapshot::build(&conn, &snapshot_path)?;
            println!("snapshot written to {}", snapshot_path.display());
        }
        Commands::Mcp { db } => mcp::serve_stdio(&db)?,
        Commands::McpHttp { addr, db } => mcp_http::serve(&addr, &db)?,
        Commands::Shell { db } => query::shell(&db)?,
    }

    Ok(())
}

fn print_result<T>(value: T, json: bool) -> Result<()>
where
    T: serde::Serialize + std::fmt::Display,
{
    if json {
        println!("{}", serde_json::to_string_pretty(&value)?);
    } else {
        println!("{value}");
    }
    Ok(())
}

fn explain_impact(result: &tessera_codegraph::types::ImpactResult) {
    println!("\nWhy:");
    println!("  Impact walks the reverse call graph: callee -> transitive callers.");
    println!("  Scores combine personalised PageRank, caller fan-in/out, exported status, test-path coverage, and depth decay.");
    if let Some(top) = result.callers.first() {
        println!(
            "  Top caller `{}` ranked first with pagerank {:.4}, fanout_in {}, fanout_out {}, exported={}, depth_decay {:.2}.",
            top.symbol.qualified_name,
            top.breakdown.pagerank,
            top.breakdown.fanout_in,
            top.breakdown.fanout_out,
            top.breakdown.exported,
            top.breakdown.depth_decay
        );
    }
}

fn explain_validate(result: &tessera_codegraph::types::ValidateResult) {
    println!("\nWhy:");
    println!("  Validate checks the Bloom filter first; a miss means the symbol is definitely absent from the indexed names.");
    println!("  If unresolved, candidates come from trigram search and are ranked by Jaro-Winkler similarity.");
    println!(
        "  bloom_hit={} candidates={}",
        result.bloom_hit,
        result.candidates.len()
    );
}

fn explain_search(result: &tessera_codegraph::types::SearchResult) {
    println!("\nWhy:");
    if result.query.contains('*') {
        println!("  Search treated the pattern as a glob and ranked matching names deterministically by match quality and qualified name.");
    } else {
        println!("  Search used trigram fuzzy lookup and ranked hits by Jaro-Winkler similarity against name and qualified_name.");
    }
    println!("  Returned hits are also filtered by any kind, language, exported, path, and limit options supplied.");
}

fn explain_unused(result: &tessera_codegraph::types::UnusedResult) {
    println!("\nWhy:");
    println!("  A symbol is reported unused only when both inbound refs and inbound call edges are zero for its simple and qualified names.");
    println!(
        "  Test-path symbols are excluded, then kind/language/exported/path filters are applied."
    );
    if let Some(first) = result.symbols.first() {
        println!(
            "  `{}` has inbound_refs={} and inbound_edges={}.",
            first.symbol.qualified_name, first.inbound_refs, first.inbound_edges
        );
    }
}

fn print_index_warnings(warnings: &[indexer::IndexWarning]) {
    if warnings.is_empty() {
        return;
    }
    eprintln!("indexed with {} warning(s):", warnings.len());
    for warning in warnings.iter().take(5) {
        eprintln!("  {}: {}", warning.path, warning.message);
    }
    if warnings.len() > 5 {
        eprintln!("  ... {} more", warnings.len() - 5);
    }
}