cartog 0.34.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
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
//! Cross-cutting helpers shared by the command modules: DB open, token-budget
//! output, the declared-identity bridge (`declared_for`), and the "no result"
//! diagnostics (`empty_index_hint`, `did_you_mean`).
//!
//! The spinner/progress plumbing lives in [`super::progress`]; this module holds
//! the data-path helpers that every command body reaches for.

use std::path::Path;

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

use cartog_db::{Database, DbError};

/// The project's declared identity, resolved from `[project]` plus its README.
///
/// The one place the bin-side `ProjectConfig` meets the library-side
/// `registry_hook`, which cannot import it. The read-only diagnostics
/// (`doctor`'s advisory row, `config`'s resolved view) call this directly: they
/// report what a *working* config would store and already refuse to run against
/// a rejected one. Registry **writers** go through [`declared_update_for`],
/// which is what distinguishes "no `[project]`" from "unknown `[project]`".
pub(crate) fn declared_for(
    project: Option<&crate::config::ProjectConfig>,
    root: &Path,
) -> cartog_registry::Declared {
    crate::registry_hook::resolve_declared(
        project.and_then(crate::config::ProjectConfig::name),
        project.and_then(crate::config::ProjectConfig::description),
        root,
    )
}

/// What this run may learn about `[project]`.
///
/// An enum, not an `Option<&ProjectConfig>`: a rejected `.cartog.toml` collapses
/// to a *default* config, which is indistinguishable from "no config file" at
/// the type level. Sending the resulting empty `[project]` as a write wiped the
/// stored declared name and swapped the description for the README fallback, so
/// one parse error anywhere in the file erased what the project says it is.
#[derive(Debug, Clone, Copy)]
pub enum ProjectSource<'a> {
    /// Config loaded, or no config file: resolve name + README fallback (Set).
    Config(Option<&'a crate::config::ProjectConfig>),
    /// A config file exists but was rejected: its `[project]` is unknown, so
    /// the stored identity must be left alone (Keep).
    Rejected,
}

/// The registry update a config-aware writer should send.
///
/// `Keep` is not "nothing to say" — it is the only correct answer when the
/// config could not be read, since `Set` overwrites all three declared columns
/// including with `NULL`.
pub(crate) fn declared_update_for(
    source: ProjectSource<'_>,
    root: &Path,
) -> cartog_registry::DeclaredUpdate {
    match source {
        ProjectSource::Config(project) => {
            cartog_registry::DeclaredUpdate::Set(declared_for(project, root))
        }
        ProjectSource::Rejected => cartog_registry::DeclaredUpdate::Keep,
    }
}

/// Open the DB for a **read** command without ever creating a `.cartog/`.
///
/// If the main DB file is absent (a config-less, un-indexed repo), this returns
/// an empty in-memory `Database` so the ~13 read command bodies are unchanged:
/// every query just comes back empty and [`empty_index_hint`] fires, pointing
/// the user at `cartog init` / `cartog index`. Write commands must use
/// [`open_db_create`] instead — they are gated on consent *above* `main`'s
/// dispatch, so they never reach this fallback.
pub(crate) fn open_db(path: &Path, embedding_dim: usize) -> Result<Database> {
    match Database::open_existing(path, embedding_dim) {
        Ok(db) => Ok(db),
        // No index yet → empty in-memory DB; the command returns empty + hint
        // and, crucially, no `.cartog/` is materialized for an un-opted repo.
        Err(DbError::NotFound { .. }) => {
            Database::open_memory().map_err(|e| open_db_error(path, e.into()))
        }
        Err(e) => Err(open_db_error(path, e.into())),
    }
}

/// Open the DB for a **write** command (`index` / `rag index`), creating the
/// `.cartog/` directory + file if needed. Used only after the consent gate in
/// `main` has confirmed the project is opted in — so this materializing the
/// `.cartog/` is intended, not a surprise.
pub(crate) fn open_db_create(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.
pub(crate) 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)]
pub(crate) 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.
pub(crate) 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.
pub(crate) 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).
pub(crate) fn empty_index_hint(db: &Database) -> &'static str {
    match db.is_empty() {
        Ok(true) => " (index is empty — run 'cartog init' then '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.
pub(crate) 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(", "))
}

/// `skip_serializing_if` predicate for counters that are absent when zero.
///
/// A zero count is noise in `--json`: "nothing was elided" and "nothing was
/// skipped" are the uninteresting default, and omitting the field keeps a
/// consumer from having to special-case it.
pub(crate) fn is_zero(n: &usize) -> bool {
    *n == 0
}

#[cfg(test)]
mod tests {
    use super::*;
    use cartog_core::{Symbol, SymbolKind};

    /// A config declaring `[project]` name and/or description.
    fn project(name: Option<&str>, description: Option<&str>) -> crate::config::ProjectConfig {
        crate::config::ProjectConfig {
            name: name.map(str::to_string),
            description: description.map(str::to_string),
        }
    }

    #[test]
    fn the_declared_name_reaches_the_resolved_identity() {
        // The bridge is the only place `[project] name` crosses into the
        // registry types, so a dropped field here is invisible everywhere else.
        let dir = tempfile::TempDir::new().unwrap();
        let cfg = project(Some("billing-service"), None);

        let declared = declared_for(Some(&cfg), dir.path());

        assert_eq!(declared.name.as_deref(), Some("billing-service"));
    }

    #[test]
    fn the_declared_description_reaches_the_resolved_identity_with_its_source() {
        let dir = tempfile::TempDir::new().unwrap();
        let cfg = project(None, Some("Invoices."));

        let declared = declared_for(Some(&cfg), dir.path());

        let d = declared.description.expect("a resolved description");
        assert_eq!(d.text, "Invoices.");
        assert_eq!(d.source, cartog_registry::DescriptionSource::Config);
    }

    #[test]
    fn surrounding_whitespace_is_trimmed_off_both_declared_values() {
        // The accessors trim; the bridge must use them rather than the raw
        // fields, or a padded TOML value renders with its padding.
        let dir = tempfile::TempDir::new().unwrap();
        let cfg = project(Some("  billing-service  "), Some("  Invoices.  "));

        let declared = declared_for(Some(&cfg), dir.path());

        assert_eq!(declared.name.as_deref(), Some("billing-service"));
        assert_eq!(
            declared.description.map(|d| d.text).as_deref(),
            Some("Invoices.")
        );
    }

    #[test]
    fn no_project_section_resolves_from_the_readme_alone() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("README.md"), "Only the readme.\n").unwrap();

        let declared = declared_for(None, dir.path());

        assert_eq!(declared.name, None);
        let d = declared.description.expect("the readme fallback");
        assert_eq!(d.source, cartog_registry::DescriptionSource::Readme);
    }

    #[test]
    fn a_rejected_config_keeps_the_stored_identity_rather_than_resolving_one() {
        // A rejected config's `[project]` is unknown, not absent: resolving a
        // README fallback here would overwrite the declared name and
        // description a working config had stored.
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("README.md"), "A readme paragraph.\n").unwrap();

        let update = declared_update_for(ProjectSource::Rejected, dir.path());

        assert_eq!(update, cartog_registry::DeclaredUpdate::Keep);
    }

    #[test]
    fn a_loaded_config_resolves_a_set_update() {
        let dir = tempfile::TempDir::new().unwrap();
        let cfg = project(Some("billing-service"), Some("Invoices."));

        let update = declared_update_for(ProjectSource::Config(Some(&cfg)), dir.path());

        let cartog_registry::DeclaredUpdate::Set(declared) = update else {
            panic!("a loaded config must resolve a Set update");
        };
        assert_eq!(declared.name.as_deref(), Some("billing-service"));
    }

    #[test]
    fn an_absent_config_file_still_resolves_a_set_update_from_the_readme() {
        // No config file at all is a *known* empty `[project]`, unlike a
        // rejected one — the README fallback applies and must be written.
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("README.md"), "A readme paragraph.\n").unwrap();

        let update = declared_update_for(ProjectSource::Config(None), dir.path());

        let cartog_registry::DeclaredUpdate::Set(declared) = update else {
            panic!("an absent config must still resolve a Set update");
        };
        assert_eq!(
            declared.description.map(|d| d.text).as_deref(),
            Some("A readme paragraph.")
        );
    }

    fn db_with_symbol(name: &str) -> Database {
        use cartog_core::FileInfo;
        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
    }

    #[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"));
    }

    #[test]
    fn empty_index_hint_mentions_init() {
        let db = Database::open_memory().unwrap();
        assert!(empty_index_hint(&db).contains("cartog init"));
    }

    #[test]
    fn open_db_falls_back_to_memory_without_creating_dir() {
        // A read command on a fresh, un-indexed repo must NOT materialize
        // `.cartog/` — it gets an empty in-memory DB and the empty-index hint.
        let tmp = tempfile::TempDir::new().unwrap();
        let db_path = tmp.path().join(".cartog").join("db.sqlite");

        let db = open_db(&db_path, cartog_db::DEFAULT_EMBEDDING_DIM).unwrap();
        assert!(db.is_empty().unwrap(), "fallback DB must be empty");
        assert!(
            !db_path.parent().unwrap().exists(),
            "open_db must NOT create .cartog/ for a read on a fresh repo"
        );
    }

    #[test]
    fn open_db_opens_an_existing_index() {
        use cartog_core::FileInfo;
        let tmp = tempfile::TempDir::new().unwrap();
        let db_path = tmp.path().join(".cartog").join("db.sqlite");
        // Materialize a real on-disk DB with a sentinel symbol.
        {
            let db = Database::open(&db_path, cartog_db::DEFAULT_EMBEDDING_DIM).unwrap();
            db.upsert_file(&FileInfo {
                path: "a.rs".into(),
                last_modified: 0.0,
                hash: "h".into(),
                language: "rust".into(),
                num_symbols: 1,
            })
            .unwrap();
            db.insert_symbols(&[Symbol::new(
                "SentinelSym",
                SymbolKind::Class,
                "a.rs",
                1,
                2,
                0,
                10,
                None,
            )])
            .unwrap();
        }
        // open_db must reopen THAT on-disk DB, not fall back to an empty
        // in-memory one — so the sentinel is still there.
        let db = open_db(&db_path, cartog_db::DEFAULT_EMBEDDING_DIM).unwrap();
        let hits = db.search("SentinelSym", None, None, 5).unwrap();
        assert!(
            hits.iter().any(|s| s.name == "SentinelSym"),
            "open_db must reopen the on-disk index (sentinel present), not the in-memory fallback"
        );
    }

    proptest::proptest! {
        /// `s[..cut]` would panic if `cut` landed mid-codepoint.
        #[test]
        fn truncate_never_panics(s in ".*", budget in 0u32..64) {
            let _ = truncate_to_budget(&s, budget);
        }

        /// Within budget → returned verbatim, no notice. Budget is derived from
        /// the string so every case exercises the in-budget branch (a fixed
        /// budget range would reject most strings via prop_assume).
        #[test]
        fn truncate_within_budget_is_verbatim(s in ".{0,200}", slack in 0u32..50) {
            let budget = (s.len() as u32).div_ceil(4) + slack;
            proptest::prop_assert_eq!(truncate_to_budget(&s, budget), s);
        }

        /// When truncation fires, the kept content stays within the byte budget.
        #[test]
        fn truncate_respects_byte_budget(s in ".{0,500}", budget in 0u32..200) {
            let max_bytes = (budget as usize) * 4;
            proptest::prop_assume!(s.len() > max_bytes);
            let notice = "\n... (truncated to fit token budget)";
            let out = truncate_to_budget(&s, budget);
            proptest::prop_assert!(out.ends_with(notice), "truncated output must carry the notice");
            let content = &out[..out.len() - notice.len()];
            proptest::prop_assert!(
                content.len() <= max_bytes,
                "kept {} content bytes > {} budget",
                content.len(),
                max_bytes
            );
        }
    }
}