token-codegraph 0.5.3

Code intelligence tool that builds a semantic knowledge graph from Rust, Go, and Java codebases
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
// Rust guideline compliant 2025-10-17
// Updated 2026-03-23: compact bordered table for status output
use clap::{Parser, Subcommand};
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};
use std::process;

use codegraph::codegraph::CodeGraph;
use codegraph::context::{format_context_as_json, format_context_as_markdown};
use codegraph::types::*;

struct Spinner {
    frames: &'static [&'static str],
    idx: usize,
}

impl Spinner {
    fn new() -> Self {
        Self {
            frames: &["", "", "", "", "", "", "", "", "", ""],
            idx: 0,
        }
    }

    fn tick(&mut self, message: &str) {
        let frame = self.frames[self.idx % self.frames.len()];
        self.idx += 1;
        let mut stderr = std::io::stderr();
        let _ = write!(stderr, "\r\x1b[2K{} {}", frame, message);
        let _ = stderr.flush();
    }

    fn done(message: &str) {
        let mut stderr = std::io::stderr();
        let _ = writeln!(stderr, "\r\x1b[2K\x1b[32m✔\x1b[0m {}", message);
        let _ = stderr.flush();
    }
}

/// Code intelligence for Rust codebases.
#[derive(Parser)]
#[command(name = "codegraph", about = "Code intelligence for Rust, Go, and Java codebases")]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Sync the index (creates it if missing, incremental by default)
    Sync {
        /// Project path (default: current directory)
        path: Option<String>,
        /// Force a full re-index
        #[arg(short, long)]
        force: bool,
    },
    /// Show project statistics
    Status {
        /// Project path (default: current directory)
        path: Option<String>,
        /// Output as JSON
        #[arg(short, long)]
        json: bool,
    },
    /// Search for symbols
    Query {
        /// Search query
        search: String,
        /// Project path
        #[arg(short, long)]
        path: Option<String>,
        /// Maximum results
        #[arg(short, long, default_value = "10")]
        limit: usize,
    },
    /// Build context for a task
    Context {
        /// Task description
        task: String,
        /// Project path
        #[arg(short, long)]
        path: Option<String>,
        /// Maximum symbols
        #[arg(short = 'n', long, default_value = "20")]
        max_nodes: usize,
        /// Output format (markdown or json)
        #[arg(short, long, default_value = "markdown")]
        format: String,
    },
    /// Start MCP server over stdio
    Serve {
        /// Project path
        #[arg(short, long)]
        path: Option<String>,
    },
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();
    if let Err(e) = run(cli).await {
        eprintln!("Error: {}", e);
        process::exit(1);
    }
}

async fn run(cli: Cli) -> codegraph::errors::Result<()> {
    let command = match cli.command {
        Some(cmd) => cmd,
        None => return handle_no_command().await,
    };
    match command {
        Commands::Sync { path, force } => {
            let project_path = resolve_path(path);
            if force || !CodeGraph::is_initialized(&project_path) {
                if !force {
                    eprintln!("No existing index found — performing full index");
                }
                init_and_index(&project_path).await?;
            } else {
                let cg = CodeGraph::open(&project_path).await?;
                let spinner = std::cell::RefCell::new(Spinner::new());
                let result = cg
                    .sync_with_progress(|phase, detail| {
                        let msg = if detail.is_empty() {
                            phase.to_string()
                        } else {
                            format!("{phase} {detail}")
                        };
                        spinner.borrow_mut().tick(&msg);
                    })
                    .await?;
                Spinner::done(&format!(
                    "sync done — {} added, {} modified, {} removed in {}ms",
                    result.files_added,
                    result.files_modified,
                    result.files_removed,
                    result.duration_ms
                ));
            }
        }
        Commands::Status { path, json } => {
            let project_path = resolve_path(path);
            let cg = ensure_initialized(&project_path).await?;
            let stats = cg.get_stats().await?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&stats).unwrap_or_default()
                );
            } else {
                let tokens_saved = cg.get_tokens_saved().await.unwrap_or(0);
                print!("{}", include_str!("resources/logo.ansi"));
                print_status_table(&stats, tokens_saved);
            }
        }
        Commands::Query {
            search,
            path,
            limit,
        } => {
            let project_path = resolve_path(path);
            let cg = ensure_initialized(&project_path).await?;
            let results = cg.search(&search, limit).await?;
            if results.is_empty() {
                println!("No results found for '{}'", search);
            } else {
                for r in &results {
                    println!(
                        "{} ({}) - {}:{}",
                        r.node.name,
                        r.node.kind.as_str(),
                        r.node.file_path,
                        r.node.start_line
                    );
                    if let Some(sig) = &r.node.signature {
                        println!("  {}", sig);
                    }
                }
            }
        }
        Commands::Context {
            task,
            path,
            max_nodes,
            format,
        } => {
            let project_path = resolve_path(path);
            let cg = ensure_initialized(&project_path).await?;
            let output_format = if format == "json" {
                OutputFormat::Json
            } else {
                OutputFormat::Markdown
            };
            let options = BuildContextOptions {
                max_nodes,
                format: output_format.clone(),
                ..Default::default()
            };
            let context = cg.build_context(&task, &options).await?;
            match output_format {
                OutputFormat::Json => {
                    println!("{}", format_context_as_json(&context));
                }
                OutputFormat::Markdown => {
                    println!("{}", format_context_as_markdown(&context));
                }
            }
        }
        Commands::Serve { path } => {
            let project_path = resolve_path(path);
            let cg = ensure_initialized(&project_path).await?;
            let server = codegraph::mcp::McpServer::new(cg).await;
            server.run().await?;
        }
    }
    Ok(())
}

/// When invoked with no subcommand, offer to create the index if none exists.
async fn handle_no_command() -> codegraph::errors::Result<()> {
    let project_path = resolve_path(None);
    if CodeGraph::is_initialized(&project_path) {
        // Already initialized — show help via clap
        let _ = <Cli as clap::CommandFactory>::command().print_help();
        eprintln!();
        return Ok(());
    }
    eprint!(
        "No CodeGraph index found at '{}'. Create one now? [Y/n] ",
        project_path.display()
    );
    io::stderr().flush().ok();
    let mut answer = String::new();
    io::stdin()
        .lock()
        .read_line(&mut answer)
        .map_err(|e| codegraph::errors::CodeGraphError::Config {
            message: format!("failed to read stdin: {}", e),
        })?;
    let answer = answer.trim();
    if answer.is_empty() || answer.eq_ignore_ascii_case("y") {
        init_and_index(&project_path).await?;
    }
    Ok(())
}

/// Initializes a new project (if needed) and runs a full index.
async fn init_and_index(project_path: &Path) -> codegraph::errors::Result<CodeGraph> {
    let cg = if CodeGraph::is_initialized(project_path) {
        CodeGraph::open(project_path).await?
    } else {
        let cg = CodeGraph::init(project_path).await?;
        eprintln!("Initialized CodeGraph at {}", project_path.display());
        cg
    };
    let spinner = std::cell::RefCell::new(Spinner::new());
    let result = cg.index_all_with_progress(|file| {
        spinner.borrow_mut().tick(&format!("indexing {}", file));
    }).await?;
    Spinner::done(&format!(
        "indexing done — {} files, {} nodes, {} edges in {}ms",
        result.file_count, result.node_count, result.edge_count, result.duration_ms
    ));
    Ok(cg)
}

/// Opens an existing project, or tells the user to run `codegraph sync` first.
async fn ensure_initialized(project_path: &Path) -> codegraph::errors::Result<CodeGraph> {
    if CodeGraph::is_initialized(project_path) {
        return CodeGraph::open(project_path).await;
    }
    Err(codegraph::errors::CodeGraphError::Config {
        message: format!(
            "no CodeGraph index found at '{}' — run 'codegraph sync' first",
            project_path.display()
        ),
    })
}

/// Formats a token count into a human-readable string (e.g. "12.3k", "1.5M").
fn format_token_count(tokens: u64) -> String {
    if tokens >= 1_000_000 {
        format!("{:.1}M", tokens as f64 / 1_000_000.0)
    } else if tokens >= 1_000 {
        format!("{:.1}k", tokens as f64 / 1_000.0)
    } else {
        tokens.to_string()
    }
}

/// Formats a byte count into a human-readable string (e.g. "798.0 MB").
fn format_bytes(bytes: u64) -> String {
    if bytes >= 1_073_741_824 {
        format!("{:.1} GB", bytes as f64 / 1_073_741_824.0)
    } else if bytes >= 1_048_576 {
        format!("{:.1} MB", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{} B", bytes)
    }
}

/// Formats a number with comma separators (e.g. 243302 -> "243,302").
fn format_number(n: u64) -> String {
    let s = n.to_string();
    let mut result = String::new();
    for (i, ch) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.push(',');
        }
        result.push(ch);
    }
    result.chars().rev().collect()
}

/// Formats a single table cell with left-aligned label and right-aligned value.
fn format_cell(label: &str, value: &str, width: usize) -> String {
    let content_len = label.len() + value.len();
    let pad = width.saturating_sub(2 + content_len);
    format!(" {}{}{} ", label, " ".repeat(pad), value)
}

/// Builds a horizontal separator line (e.g. ├──┬──┬──┤).
fn table_separator(left: char, mid: char, right: char, cell_width: usize, num_cols: usize) -> String {
    let mut line = String::from(left);
    for i in 0..num_cols {
        line.push_str(&"".repeat(cell_width));
        line.push(if i < num_cols - 1 { mid } else { right });
    }
    line
}

/// Prints the status output as a compact bordered table.
fn print_status_table(stats: &codegraph::types::GraphStats, tokens_saved: u64) {
    let version = env!("CARGO_PKG_VERSION");
    let num_cols = 3;

    // Prepare sorted node kinds
    let mut sorted_kinds: Vec<_> = stats.nodes_by_kind.iter().collect();
    sorted_kinds.sort_by_key(|(k, _)| (*k).clone());

    let num_kind_rows = sorted_kinds.len().div_ceil(num_cols);

    // Determine cell width from the widest node-kind entry
    let max_kind_len = sorted_kinds
        .iter()
        .map(|(k, _)| k.len())
        .max()
        .unwrap_or(10);
    let max_count_len = sorted_kinds
        .iter()
        .map(|(_, c)| format_number(**c).len())
        .max()
        .unwrap_or(5);
    // Ensure the cell also fits stat labels like "DB Size" + "798.0 MB"
    let cell_width = (max_kind_len + max_count_len + 3).max(22);
    let inner_width = cell_width * num_cols + (num_cols - 1);

    // Title row
    let title = format!("CodeGraph v{}", version);
    let tokens_text = format!("Tokens saved ~{}", format_token_count(tokens_saved));
    let title_pad = inner_width.saturating_sub(2 + title.len() + tokens_text.len());

    println!("{}", table_separator('', '', '', cell_width, num_cols));
    println!(
        "{}{}\x1b[32m{}\x1b[0m │",
        title,
        " ".repeat(title_pad),
        tokens_text
    );

    // Stats rows
    println!("{}", table_separator('', '', '', cell_width, num_cols));

    // Build the languages summary string
    let languages_str = {
        let mut langs: Vec<_> = stats.files_by_language.iter().collect();
        langs.sort_by(|a, b| b.1.cmp(a.1));
        langs
            .iter()
            .map(|(lang, count)| format!("{} ({})", lang, count))
            .collect::<Vec<_>>()
            .join(", ")
    };

    let db_size = format_bytes(stats.db_size_bytes);
    let source_size = format_bytes(stats.total_source_bytes);
    let stats_rows: Vec<Vec<(&str, String)>> = if stats.total_source_bytes > 0 {
        vec![
            vec![
                ("Files", format_number(stats.file_count)),
                ("Nodes", format_number(stats.node_count)),
                ("Edges", format_number(stats.edge_count)),
            ],
            vec![
                ("DB Size", db_size),
                ("Source", source_size),
                ("Languages", languages_str),
            ],
        ]
    } else {
        vec![vec![
            ("Files", format_number(stats.file_count)),
            ("Nodes", format_number(stats.node_count)),
            ("Edges", format_number(stats.edge_count)),
        ],
        vec![
            ("DB Size", db_size),
            ("Languages", languages_str),
            ("", String::new()),
        ]]
    };

    for row in &stats_rows {
        print!("");
        for (i, (label, value)) in row.iter().enumerate() {
            if label.is_empty() {
                print!("{}", " ".repeat(cell_width));
            } else {
                print!("{}", format_cell(label, value, cell_width));
            }
            print!("{}", if i < num_cols - 1 { "" } else { "\n" });
        }
    }

    // Node kinds section
    if !sorted_kinds.is_empty() {
        println!("{}", table_separator('', '', '', cell_width, num_cols));

        for r in 0..num_kind_rows {
            print!("");
            for c in 0..num_cols {
                let idx = r + c * num_kind_rows;
                if idx < sorted_kinds.len() {
                    let (kind, count) = &sorted_kinds[idx];
                    print!("{}", format_cell(kind, &format_number(**count), cell_width));
                } else {
                    print!("{}", " ".repeat(cell_width));
                }
                print!("{}", if c < num_cols - 1 { "" } else { "\n" });
            }
        }
    }

    println!("{}", table_separator('', '', '', cell_width, num_cols));
}

/// Resolves an optional path argument to an absolute `PathBuf`.
///
/// Defaults to the current working directory if no path is provided.
fn resolve_path(path: Option<String>) -> PathBuf {
    match path {
        Some(p) => PathBuf::from(p),
        None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
    }
}