cartog 0.30.0

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
//! Semantic-search commands backed by embeddings: `rag setup` (model download),
//! `rag index` (embed the graph), `rag search` (hybrid FTS5 + vector), and
//! `context` (token-budgeted task bundle).

use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Result};

use super::progress::{install_cancel_probe, spinner_callback, stop_spinner, Spinner};
use super::shared::{empty_index_hint, open_db, output};
use cartog_core::Compact;
use cartog_indexer as indexer;
use cartog_rag as rag;

/// Download the embedding model.
pub fn cmd_rag_setup(json: bool, provider_config: &rag::EmbeddingProviderConfig) -> Result<()> {
    let reranker_model = provider_config.reranker_model.as_deref();
    let spinner = if json {
        None
    } else {
        // One-time notice so the multi-hundred-MB download isn't a silent wait.
        eprintln!(
            "Downloading embedding (~80MB) + re-ranker ({}) models, one-time…",
            reranker_model.unwrap_or(rag::DEFAULT_RERANKER_MODEL)
        );
        Spinner::start("Downloading models")
    };
    // Download bi-encoder (embeddings)
    let embed_result = rag::setup::download_model();
    // Download cross-encoder (re-ranking) — the configured model, not always the default.
    let rerank_result =
        rag::setup::download_cross_encoder(reranker_model, provider_config.intra_threads);
    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,
    redact: indexer::RedactionConfig,
    filter: &indexer::WalkFilter,
) -> Result<()> {
    let root = Path::new(path);
    // Install the handler first so Ctrl-C also covers the (potentially long,
    // first-run) embedding-model download inside create_embedding_provider.
    let cancel = install_cancel_probe();
    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")?;

    // Progress on stderr; `Spinner::start` self-gates (TTY or CARTOG_PROGRESS).
    let spinner = 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 ix_cancel: indexer::CancelProbe<'_> = &cancel;
    let index_res = indexer::index_directory(
        &db,
        root,
        false,
        false,
        ix_cb_ref,
        Some(ix_cancel),
        redact,
        &std::collections::HashMap::new(),
        filter,
    );
    drop(ix_cb);
    stop_spinner(spinner);
    match index_res {
        Ok(_) => {}
        Err(e) if indexer::is_cancelled(&e) => {
            if !json {
                eprintln!("Indexing cancelled; the index was left unchanged.");
            }
            return Ok(());
        }
        Err(e) => return Err(e),
    }

    let spinner = 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 rag_cancel: rag::indexer::CancelProbe<'_> = &cancel;
    let embed_res =
        rag::indexer::index_embeddings(&db, provider.as_mut(), force, rag_cb_ref, Some(rag_cancel));
    drop(rag_cb);
    stop_spinner(spinner);
    let result = match embed_res {
        Ok(r) => r,
        // Flushed batches persist on an incremental run; a --force/upgrade run
        // cleared up front, so re-run to rebuild. Either way, re-run to finish.
        Err(e) if indexer::is_cancelled(&e) => {
            if !json {
                eprintln!("Embedding cancelled; re-run to finish.");
            }
            return Ok(());
        }
        Err(e) => return Err(e),
    };

    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<crate::cli::SymbolKindFilter>,
    limit: u32,
    json: bool,
    compact: 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(crate::cli::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();
        let model = provider_config.reranker_model.clone();
        let threads = provider_config.intra_threads;
        Some(move || rag::create_reranker_provider(&name, model.as_deref(), threads))
    };
    let mut search_result = rag::search::hybrid_search_tuned_lazy(
        &db,
        query,
        limit,
        kind_filter,
        provider.as_mut(),
        reranker_factory,
        tuning,
    )?;
    if compact {
        search_result.compact_in_place();
    }
    db.log_query("rag_search", "cli");
    let query = query.to_string();
    // Gate the "build the index" hint on whether embeddings actually exist, not
    // on the result counts: kind-filtered retrieval can legitimately yield
    // fts/vec_count == 0 for a code query that only matched docs, even with a
    // fully-built index.
    let embeddings_built = db.embedding_count().map(|n| n > 0).unwrap_or(false);

    output(&search_result, json, token_budget, |sr| {
        render_rag_search(sr, &query, embeddings_built)
    })
}

/// Render the human-readable `rag search` output.
///
/// `embeddings_built` gates the index hints: `vec_count == 0` alone is not a
/// reliable signal — kind-filtered retrieval can legitimately yield zero
/// vector hits on a fully-built index.
fn render_rag_search(
    sr: &rag::search::HybridSearchResult,
    query: &str,
    embeddings_built: bool,
) -> String {
    if sr.results.is_empty() {
        let mut out = format!("No results found for '{query}'\n");
        if !embeddings_built {
            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",
        sr.results.len(),
        sr.fts_count,
        sr.vec_count,
        sr.merged_count
    );
    if !embeddings_built {
        out.push_str(
            "Hint: keyword (FTS) matches only — run 'cartog rag index' to enable semantic search.\n",
        );
    }
    out.push('\n');
    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
}

/// Build a token-budgeted task-context bundle for a natural-language task.
pub fn cmd_context(
    db_path: &Path,
    task: &str,
    tokens: u32,
    json: bool,
    compact: bool,
    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())?;

    // Build the bundle in its own scope so the provider/reranker borrows end
    // before the `output` closure (which re-borrows `&db`) runs.
    let mut ctx = {
        let mut reranker = if provider_config.reranker_provider == "none" {
            None
        } else {
            rag::create_reranker_provider(
                &provider_config.reranker_provider,
                provider_config.reranker_model.as_deref(),
                provider_config.intra_threads,
            )
        };
        let opts = rag::context::ContextOptions {
            tuning: *tuning,
            ..Default::default()
        };
        // `match` (not `as_deref_mut`) keeps the reranker borrow scoped to the
        // call so it drops before `output` re-borrows `db`.
        match reranker.as_mut() {
            Some(r) => rag::context::build_task_context(
                &db,
                task,
                tokens,
                provider.as_mut(),
                Some(r.as_mut()),
                &opts,
            ),
            None => {
                rag::context::build_task_context(&db, task, tokens, provider.as_mut(), None, &opts)
            }
        }?
    };
    if !ctx.entries.is_empty() {
        db.log_query("context", "cli");
    }
    // Compact trims the per-entry symbol noise but keeps the budgeted bodies —
    // a context bundle's whole value is its inline bodies.
    if compact {
        ctx.compact_in_place();
    }
    let task = task.to_string();

    output(&ctx, json, None, |ctx| {
        if ctx.entries.is_empty() {
            return format!("No context found for '{task}'{}\n", empty_index_hint(&db));
        }
        let mut out = format!(
            "Context for '{task}' ({} symbols, ~{} tokens)\n\n",
            ctx.entries.len(),
            ctx.approx_tokens
        );
        for entry in &ctx.entries {
            out.push_str(&format!(
                "[{reason:?}] {kind} {name}  {file}:{line}\n",
                reason = entry.reason,
                kind = entry.symbol.kind,
                name = entry.symbol.name,
                file = entry.symbol.file_path,
                line = entry.symbol.start_line,
            ));
            if let Some(body) = &entry.content {
                for l in body.lines() {
                    out.push_str(&format!("    {l}\n"));
                }
                out.push('\n');
            }
        }
        out
    })
}

// No CLI test for `cmd_context`: it builds a real embedding provider
// (ONNX model), so it can't run model-independently in CI. The fusion
// logic is covered by `cartog_rag::context` unit tests (MockEmbeddingProvider)
// and the `cartog_context` MCP tool test (test_provider).

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

    fn fts_only_search_result() -> rag::search::HybridSearchResult {
        rag::search::HybridSearchResult {
            results: vec![rag::search::SearchResult {
                symbol: cartog_core::Symbol::new(
                    "foo",
                    cartog_core::SymbolKind::Function,
                    "a.py",
                    1,
                    10,
                    0,
                    100,
                    None,
                ),
                content: None,
                rrf_score: 0.016,
                rerank_score: None,
                sources: vec![],
            }],
            fts_count: 1,
            vec_count: 0,
            merged_count: 1,
        }
    }

    #[test]
    fn rag_search_render_hints_when_results_found_but_embeddings_missing() {
        let out = render_rag_search(&fts_only_search_result(), "foo", false);
        assert!(
            out.contains("cartog rag index"),
            "FTS-only results without embeddings must hint at 'cartog rag index'; got:\n{out}"
        );
    }

    #[test]
    fn rag_search_render_no_hint_when_embeddings_built() {
        let out = render_rag_search(&fts_only_search_result(), "foo", true);
        assert!(
            !out.contains("Hint:"),
            "vec_count == 0 with a built index is legitimate, no hint expected; got:\n{out}"
        );
    }
}