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
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
//! `cartog search --all` — one symbol query, fanned out across the machine's
//! other indexed projects.
//!
//! **Fan out and group; never consolidate.** The registry supplies the
//! candidate database paths, each is opened **read-only** and queried on its
//! own, and results stay grouped under the project they came from. Three things
//! this deliberately does not do:
//!
//! - **No merged database.** Merging graphs is a documented non-goal: it adds a
//!   second staleness surface and breaks per-repo `.cartog/` deletability,
//!   gitignore and per-project remote sync. Every hit here is read live from the
//!   project that owns it.
//! - **No merged ranking.** `in_degree` centrality is per-graph and dominates
//!   ordering, so a flat cross-project list cannot be ranked defensibly without
//!   a ranking benchmark that does not exist. Grouping sidesteps the question
//!   rather than guessing at it.
//! - **No writes.** A registry row grants discovery, not write access. The
//!   read-only open is the enforcement, not a convention.
//!
//! Exact-symbol search federates precisely because names match or they do not,
//! with no score to normalize. Semantic search does not share that property and
//! is not built here.

use std::path::{Path, PathBuf};

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

use cartog_core::{Compact, Symbol};
use cartog_db::{Database, MAX_SEARCH_LIMIT};
use cartog_registry::ProjectRow;

use crate::cli::SymbolKindFilter;

/// Databases queried when the user names no filter.
///
/// A fan-out is cheap (a read-only open plus one indexed lookup — measured at
/// ~2ms per project), but it is not free and it is unbounded by nature: the
/// registry grows with every project on the machine. The cap keeps a default
/// `--all` predictable; `--max-projects` raises it, and the response says when
/// the cap elided anything so a missing project is never silent.
const DEFAULT_MAX_PROJECTS: usize = 10;

/// Upper bound on `--max-projects`, mirroring the MCP tool's clamp.
const MAX_FANOUT_PROJECTS: usize = 50;

/// How a project's databases are chosen for one federated query.
#[derive(Debug, Clone, Default)]
pub struct FanoutFilter {
    /// Keep only projects whose root is inside this directory.
    pub under: Option<PathBuf>,
    /// Keep only projects that indexed this language.
    pub lang: Option<String>,
    pub max_projects: Option<usize>,
}

/// How the result is rendered, grouped so the fan-out signature stays readable.
#[derive(Debug, Clone, Copy)]
pub struct OutputOpts {
    pub json: bool,
    pub compact: bool,
    pub token_budget: Option<u32>,
}

#[derive(Debug, Serialize)]
pub struct FederatedResults {
    /// One entry per project that answered, most-populous project first.
    /// Ranking is **within** a project only.
    projects: Vec<ProjectHits>,
    /// Projects whose database could not be read, each with the reason. Named
    /// rather than dropped: silently omitting one would read as "no matches
    /// there".
    #[serde(skip_serializing_if = "Vec::is_empty")]
    unreadable: Vec<UnreadableJson>,
    queried: usize,
    /// Candidates left unqueried by the cap, so a partial answer says so.
    #[serde(skip_serializing_if = "super::shared::is_zero")]
    elided_by_cap: usize,
    total_matches: usize,
}

/// A project that matched the filter but could not be queried.
#[derive(Debug, Serialize)]
struct UnreadableJson {
    name: String,
    /// Why the read failed. A schema drift, a corrupt file, an `EACCES` on the
    /// `.cartog/` directory and a `SQLITE_BUSY` are all different problems with
    /// different fixes, so collapsing them to one guessed cause sent the reader
    /// after the wrong one.
    reason: String,
}

#[derive(Debug, Serialize)]
struct ProjectHits {
    name: String,
    root: String,
    db_path: String,
    /// Repository-authored text: data on every surface, never instructions.
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    symbols: Vec<Symbol>,
}

/// Run `query` against every project the filter selects.
pub fn cmd_search_all(
    current_db: &Path,
    query: &str,
    kind: Option<SymbolKindFilter>,
    limit: u32,
    filter: &FanoutFilter,
    out: OutputOpts,
) -> Result<()> {
    let OutputOpts {
        json,
        compact,
        token_budget,
    } = out;
    let listing = cartog_registry::list_projects(cartog_db::CURRENT_SCHEMA_VERSION);
    if !listing.available {
        bail!(
            "no project registry on this machine, so there are no other projects to search \
             (CARTOG_REGISTRY is disabled, or nothing has been indexed yet)"
        );
    }

    let (candidates, elided_by_cap) = select_candidates(listing.projects, current_db, filter);
    if candidates.is_empty() {
        // Not an error: an empty selection is a real answer, and the filter the
        // user typed is the thing to report back.
        let empty = FederatedResults {
            projects: Vec::new(),
            unreadable: Vec::new(),
            queried: 0,
            elided_by_cap,
            total_matches: 0,
        };
        // The cap cannot reach here: it clamps to >= 1 and truncates after
        // counting, so an elision always leaves a candidate queried — the clamp
        // is pinned by `the_project_cap_is_clamped_to_the_same_range_as_the_mcp_tool`
        // below, and the same invariant by `the_cap_cannot_elide_every_candidate`
        // in cartog-mcp. `describe` names whichever filter was actually applied,
        // or the registry itself when none was.
        return super::shared::output(&empty, json, token_budget, |_| {
            format!("No other indexed project matches {}.\n", describe(filter))
        });
    }

    let kind_filter = match kind {
        Some(SymbolKindFilter::All) | None => None,
        Some(k) => Some(cartog_core::SymbolKind::from(k)),
    };
    // Same ceiling as the single-project search: a fan-out must not become a
    // way to ask for more rows per project than `cartog search` allows.
    let limit = limit.min(MAX_SEARCH_LIMIT);

    let mut projects = Vec::new();
    let mut unreadable = Vec::new();
    let queried = candidates.len();
    for row in candidates {
        match query_one(&row, query, kind_filter, limit, compact) {
            Ok(symbols) if symbols.is_empty() => {}
            Ok(symbols) => projects.push(ProjectHits {
                name: row.display_name().to_string(),
                root: row.root.display().to_string(),
                db_path: row.db_path.display().to_string(),
                description: row.description.as_ref().map(|d| d.text.clone()),
                symbols,
            }),
            Err(e) => unreadable.push(UnreadableJson {
                name: row.display_name().to_string(),
                // Root cause, not the wrapper: `open_readonly`'s outer message
                // says little, and the schema-drift/IO detail is what the
                // reader needs.
                reason: e.root_cause().to_string(),
            }),
        }
    }

    let total_matches = projects.iter().map(|p| p.symbols.len()).sum();
    let results = FederatedResults {
        projects,
        unreadable,
        queried,
        elided_by_cap,
        total_matches,
    };

    let query = query.to_string();
    super::shared::output(&results, json, token_budget, |r| render(r, &query))
}

/// Choose which projects to query, and count what the cap left out.
///
/// **Duplicated** as `select_fanout_candidates` in
/// `crates/cartog-mcp/src/tools/search.rs`, because no existing crate can host
/// the shared version: `cartog-registry` deliberately carries no `cartog-db`
/// dependency (so a graph-schema bump never forces a registry migration) and
/// `cartog-db` depends only on `cartog-core`. A behaviour change here needs the
/// same change there, or the CLI and the MCP tool answer differently.
///
/// Excludes the project the caller is already in: `cartog search` without
/// `--all` covers that, and listing it twice would double-report every hit.
/// Ordered most-symbols-first so the cap keeps the substantial projects rather
/// than whichever the registry happened to return first.
fn select_candidates(
    rows: Vec<ProjectRow>,
    current_db: &Path,
    filter: &FanoutFilter,
) -> (Vec<ProjectRow>, usize) {
    let current = canonical(current_db);
    let mut kept: Vec<ProjectRow> = rows
        .into_iter()
        .filter(|r| canonical(&r.db_path) != current)
        .filter(|r| !r.markers.missing)
        .filter(|r| matches_filter(r, filter))
        .collect();

    // Descending by symbol count; an unmeasurable project sorts last but stays
    // eligible, since a name lookup does not need a readable schema.
    kept.sort_by(|a, b| {
        b.symbol_count
            .unwrap_or(0)
            .cmp(&a.symbol_count.unwrap_or(0))
            .then_with(|| a.display_name().cmp(b.display_name()))
    });

    // Clamped to match `select_fanout_candidates` in cartog-mcp: an unclamped 0
    // truncates every candidate away, and the caller then reports "nothing
    // matched the filter" when something did match and was elided.
    let cap = filter
        .max_projects
        .unwrap_or(DEFAULT_MAX_PROJECTS)
        .clamp(1, MAX_FANOUT_PROJECTS);
    let elided = kept.len().saturating_sub(cap);
    kept.truncate(cap);
    (kept, elided)
}

/// Whether one row passes the `--under` / `--lang` filters.
///
/// `--under` compares canonicalized paths so `~/work` and `~/work/` behave the
/// same and a symlinked root cannot slip past a prefix test.
fn matches_filter(row: &ProjectRow, filter: &FanoutFilter) -> bool {
    if let Some(under) = &filter.under {
        if !canonical(&row.root).starts_with(canonical(under)) {
            return false;
        }
    }
    if let Some(lang) = &filter.lang {
        let wanted = lang.to_ascii_lowercase();
        if !row
            .languages
            .iter()
            .any(|(l, _)| l.eq_ignore_ascii_case(&wanted))
        {
            return false;
        }
    }
    true
}

/// Query one project's database, read-only.
///
/// Read-only is the write-access boundary, not a convention: a registry row
/// grants discovery only. `open_readonly` also refuses a schema this binary
/// does not own, which is the right outcome — a drifted graph's rows cannot be
/// trusted, so the project is reported unreadable rather than half-answered.
fn query_one(
    row: &ProjectRow,
    query: &str,
    kind: Option<cartog_core::SymbolKind>,
    limit: u32,
    compact: bool,
) -> Result<Vec<Symbol>> {
    let db = Database::open_readonly(&row.db_path)?;
    let mut symbols = db.search(query, kind, None, limit)?;
    if compact {
        symbols.compact_in_place();
    }
    Ok(symbols)
}

/// `canonicalize` when the path exists, else the path as given — so a filter
/// still behaves sensibly for a project whose database has been removed.
fn canonical(p: &Path) -> PathBuf {
    // Expand `~` first: a quoted or config-sourced `~/work` reaches here
    // literally (the shell only expands it unquoted), and `canonicalize` leaves
    // it alone — so the `starts_with` test would match nothing and the fan-out
    // would silently return zero projects. `backfill.rs` and `[database] path`
    // expand the same way.
    let expanded = crate::config::expand_tilde(p.to_path_buf());
    expanded.canonicalize().unwrap_or(expanded)
}

/// The active filter in words, for a "nothing matched" message that names what
/// was actually applied rather than just reporting emptiness.
fn describe(filter: &FanoutFilter) -> String {
    let mut parts = Vec::new();
    if let Some(u) = &filter.under {
        parts.push(format!("under {}", u.display()));
    }
    if let Some(l) = &filter.lang {
        parts.push(format!("language {l}"));
    }
    if parts.is_empty() {
        return "this machine's registry".to_string();
    }
    parts.join(" and ")
}

fn render(r: &FederatedResults, query: &str) -> String {
    // Builds the header, then *falls through* to the unreadable/elided
    // sections rather than returning. Returning early here reported "no
    // symbols matched" when in truth no database had been read successfully —
    // a false negative that reads as "the symbol is not there".
    let mut out = if r.projects.is_empty() {
        let searched = r.queried.saturating_sub(r.unreadable.len());
        if searched == 0 && r.queried > 0 {
            format!(
                "No project could be searched for '{query}' — none of the {} candidate{} \
                 could be read.\n",
                r.queried,
                if r.queried == 1 { "" } else { "s" },
            )
        } else {
            format!(
                "No symbols matching '{query}' in {searched} other project{}.\n",
                if searched == 1 { "" } else { "s" },
            )
        }
    } else {
        header(r, query)
    };

    if !r.projects.is_empty() {
        out.push_str(&hits(r));
    }
    out.push_str(&diagnostics(r));
    out
}

/// The "N matches across M projects" line.
fn header(r: &FederatedResults, query: &str) -> String {
    format!(
        "{} match{} for '{query}' across {} of {} project{}:\n",
        r.total_matches,
        if r.total_matches == 1 { "" } else { "es" },
        r.projects.len(),
        r.queried,
        if r.queried == 1 { "" } else { "s" },
    )
}

/// One block per project that returned matches.
fn hits(r: &FederatedResults) -> String {
    let mut out = String::new();
    for p in &r.projects {
        out.push('\n');
        out.push_str(&format!("{} ({})\n", p.name, p.root));
        if let Some(d) = &p.description {
            out.push_str(&format!("  {d}\n"));
        }
        for s in &p.symbols {
            out.push_str(&format!(
                "  {:<28} {}:{}\n",
                s.name, s.file_path, s.start_line
            ));
        }
        // The actionable field: this is what the reader passes to --db next.
        out.push_str(&format!("  --db {}\n", p.db_path));
    }
    out
}

/// Why an answer may be partial: unreadable projects and the project cap.
///
/// Appended whether or not anything matched — a search that read nothing, or
/// stopped at the cap, must say so even when the match list is empty.
fn diagnostics(r: &FederatedResults) -> String {
    let mut out = String::new();
    if !r.unreadable.is_empty() {
        out.push_str(&format!(
            "\n{} project{} could not be read:\n",
            r.unreadable.len(),
            if r.unreadable.len() == 1 { "" } else { "s" },
        ));
        for u in &r.unreadable {
            out.push_str(&format!("  {}: {}\n", u.name, u.reason));
        }
    }
    if r.elided_by_cap > 0 {
        out.push_str(&format!(
            "\n{} more project{} matched but were not queried — raise --max-projects to include them.\n",
            r.elided_by_cap,
            if r.elided_by_cap == 1 { "" } else { "s" },
        ));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use cartog_registry::{Description, DescriptionSource, Markers};

    fn row(name: &str, root: &str, symbols: Option<u32>, langs: &[&str]) -> ProjectRow {
        ProjectRow {
            id: format!("serve-{name}"),
            db_path: PathBuf::from(format!("{root}/.cartog/db.sqlite")),
            root: PathBuf::from(root),
            name: name.to_string(),
            declared_name: None,
            description: None,
            languages: langs.iter().map(|l| ((*l).to_string(), 10)).collect(),
            schema_version: Some(8),
            file_count: Some(10),
            symbol_count: symbols,
            edge_count: None,
            resolved_count: None,
            embedding_count: None,
            embed_provider: None,
            embed_model: None,
            embed_dim: None,
            last_indexed: None,
            last_seen: 0,
            markers: Markers::default(),
        }
    }

    #[test]
    fn the_callers_own_project_is_never_queried() {
        // `cartog search` already covers the current project; including it here
        // would double-report every hit.
        let mine = PathBuf::from("/w/a/.cartog/db.sqlite");
        let rows = vec![
            row("a", "/w/a", Some(5), &["rust"]),
            row("b", "/w/b", Some(5), &["rust"]),
        ];

        let (kept, _) = select_candidates(rows, &mine, &FanoutFilter::default());

        let names: Vec<&str> = kept.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["b"],
            "the caller's own project must be excluded"
        );
    }

    #[test]
    fn a_project_whose_database_is_gone_is_not_queried() {
        let mut gone = row("gone", "/w/gone", Some(5), &["rust"]);
        gone.markers = Markers {
            missing: true,
            ..Markers::default()
        };
        let rows = vec![gone, row("here", "/w/here", Some(5), &["rust"])];

        let (kept, _) = select_candidates(rows, Path::new("/w/x/db"), &FanoutFilter::default());

        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].name, "here");
    }

    #[test]
    fn under_keeps_only_projects_inside_that_subtree() {
        let rows = vec![
            row("in", "/w/team/in", Some(5), &["rust"]),
            row("out", "/other/out", Some(5), &["rust"]),
        ];
        let filter = FanoutFilter {
            under: Some(PathBuf::from("/w/team")),
            ..FanoutFilter::default()
        };

        let (kept, _) = select_candidates(rows, Path::new("/none"), &filter);

        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].name, "in");
    }

    #[test]
    fn lang_keeps_only_projects_that_indexed_that_language() {
        let rows = vec![
            row("rb", "/w/rb", Some(5), &["ruby", "markdown"]),
            row("ts", "/w/ts", Some(5), &["typescript"]),
        ];
        let filter = FanoutFilter {
            lang: Some("ruby".to_string()),
            ..FanoutFilter::default()
        };

        let (kept, _) = select_candidates(rows, Path::new("/none"), &filter);

        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].name, "rb");
    }

    #[test]
    fn lang_matching_ignores_case() {
        let rows = vec![row("ts", "/w/ts", Some(5), &["TypeScript"])];
        let filter = FanoutFilter {
            lang: Some("typescript".to_string()),
            ..FanoutFilter::default()
        };

        assert_eq!(
            select_candidates(rows, Path::new("/none"), &filter).0.len(),
            1
        );
    }

    #[test]
    fn under_and_lang_compose_as_an_and() {
        let rows = vec![
            row("both", "/w/team/both", Some(5), &["ruby"]),
            row("wrong-lang", "/w/team/ts", Some(5), &["typescript"]),
            row("wrong-path", "/other/rb", Some(5), &["ruby"]),
        ];
        let filter = FanoutFilter {
            under: Some(PathBuf::from("/w/team")),
            lang: Some("ruby".to_string()),
            max_projects: None,
        };

        let (kept, _) = select_candidates(rows, Path::new("/none"), &filter);

        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].name, "both");
    }

    #[test]
    fn the_cap_keeps_the_largest_projects_and_reports_what_it_dropped() {
        // A silent truncation would let an agent conclude "that's everything".
        let rows = vec![
            row("small", "/w/small", Some(1), &["rust"]),
            row("big", "/w/big", Some(9000), &["rust"]),
            row("mid", "/w/mid", Some(50), &["rust"]),
        ];
        let filter = FanoutFilter {
            max_projects: Some(2),
            ..FanoutFilter::default()
        };

        let (kept, elided) = select_candidates(rows, Path::new("/none"), &filter);

        assert_eq!(
            kept.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
            vec!["big", "mid"],
            "the cap must keep the most-populous projects"
        );
        assert_eq!(elided, 1, "the dropped project must be counted, not hidden");
    }

    #[test]
    fn an_unmeasurable_project_stays_eligible_but_sorts_last() {
        // A name lookup does not need a readable schema, so a project with no
        // recorded counts must still be searchable.
        let rows = vec![
            row("unknown", "/w/unknown", None, &[]),
            row("known", "/w/known", Some(10), &["rust"]),
        ];

        let (kept, _) = select_candidates(rows, Path::new("/none"), &FanoutFilter::default());

        assert_eq!(
            kept.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
            vec!["known", "unknown"]
        );
    }

    #[test]
    fn the_project_cap_is_clamped_to_the_same_range_as_the_mcp_tool() {
        // Parity with `select_fanout_candidates` in cartog-mcp. Unclamped, a 0
        // truncated every candidate away and the caller then reported "nothing
        // matched the filter" while --json showed a non-zero elided count.
        let rows: Vec<ProjectRow> = (0..60)
            .map(|i| row(&format!("p{i}"), &format!("/w/p{i}"), Some(i), &["rust"]))
            .collect();

        let zero = FanoutFilter {
            max_projects: Some(0),
            ..FanoutFilter::default()
        };
        let (kept, _) = select_candidates(rows.clone(), Path::new("/none"), &zero);
        assert_eq!(kept.len(), 1, "a cap of 0 must still query one project");

        let huge = FanoutFilter {
            max_projects: Some(usize::MAX),
            ..FanoutFilter::default()
        };
        let (kept, elided) = select_candidates(rows, Path::new("/none"), &huge);
        assert_eq!(kept.len(), 50, "the cap must be bounded above");
        assert_eq!(elided, 10);
    }

    #[test]
    fn under_expands_a_leading_tilde() {
        // A quoted or config-sourced `~/work` reaches the filter literally.
        // Unexpanded, `starts_with` matched nothing and the fan-out silently
        // returned zero projects.
        let home = std::env::var("HOME").expect("HOME must be set");
        let rows = vec![
            row("in", &format!("{home}/work/in"), Some(5), &["rust"]),
            row("out", "/elsewhere/out", Some(5), &["rust"]),
        ];
        let filter = FanoutFilter {
            under: Some(PathBuf::from("~/work")),
            ..FanoutFilter::default()
        };

        let (kept, _) = select_candidates(rows, Path::new("/none"), &filter);

        assert_eq!(
            kept.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
            vec!["in"],
            "a tilde in --under must expand to $HOME"
        );
    }

    fn results(
        projects: Vec<ProjectHits>,
        unreadable: Vec<UnreadableJson>,
        queried: usize,
        elided_by_cap: usize,
    ) -> FederatedResults {
        let total_matches = projects.iter().map(|p| p.symbols.len()).sum();
        FederatedResults {
            projects,
            unreadable,
            queried,
            elided_by_cap,
            total_matches,
        }
    }

    fn unreadable(name: &str, reason: &str) -> UnreadableJson {
        UnreadableJson {
            name: name.to_string(),
            reason: reason.to_string(),
        }
    }

    #[test]
    fn a_search_where_every_candidate_was_unreadable_does_not_claim_no_match() {
        // "No symbols matching X" implies the projects were searched. When
        // none could be read, that is a false negative: the reader concludes
        // the symbol is not there.
        let r = results(
            Vec::new(),
            vec![unreadable(
                "legacy-service",
                "schema_version mismatch: expects 8, DB has 3",
            )],
            1,
            0,
        );

        let out = render(&r, "CreateOrder");

        assert!(
            out.contains("could not be searched") || out.contains("could not be read"),
            "must say the search could not run, got: {out}"
        );
        assert!(
            !out.contains("No symbols matching"),
            "must not claim a genuine no-match, got: {out}"
        );
        assert!(
            out.contains("legacy-service") && out.contains("schema_version"),
            "the reason must survive an empty match list, got: {out}"
        );
    }

    #[test]
    fn an_empty_result_still_reports_projects_elided_by_the_cap() {
        // A capped search that matched nothing must not read as complete.
        let r = results(Vec::new(), Vec::new(), 2, 7);

        let out = render(&r, "Widget");

        assert!(
            out.contains('7') && out.contains("--max-projects"),
            "the elision notice must survive an empty match list, got: {out}"
        );
    }

    #[test]
    fn a_readable_project_with_no_hit_still_reports_a_genuine_no_match() {
        // The complement: don't over-correct into never saying "no match".
        let r = results(Vec::new(), Vec::new(), 3, 0);

        let out = render(&r, "Nope");

        assert!(
            out.contains("No symbols matching"),
            "a real no-match must still read as one, got: {out}"
        );
    }

    #[test]
    fn describe_names_the_filter_that_matched_nothing() {
        // An empty result must say what was actually applied, not just "none".
        let filter = FanoutFilter {
            under: Some(PathBuf::from("/w/team")),
            lang: Some("ruby".to_string()),
            max_projects: None,
        };
        let text = describe(&filter);

        assert!(text.contains("/w/team"), "got {text}");
        assert!(text.contains("ruby"), "got {text}");
    }

    /// The zero-candidate line names the filter that was applied, or the
    /// registry when none was — never a filter the user did not set.
    ///
    /// The MCP surface got this wrong in the other direction (it hardcoded
    /// "none matched the filter"), so the CLI's behaviour is pinned here rather
    /// than left to `describe`'s unit test alone.
    #[test]
    fn the_zero_candidate_line_names_only_what_was_applied() {
        let no_filter = FanoutFilter {
            under: None,
            lang: None,
            max_projects: None,
        };
        let line = format!(
            "No other indexed project matches {}.\n",
            describe(&no_filter)
        );
        assert!(
            line.contains("this machine's registry"),
            "with no filter set, blame the registry, not a filter: {line}"
        );
        assert!(
            !line.contains("under") && !line.contains("language"),
            "must not name a filter the caller never set: {line}"
        );

        let filtered = FanoutFilter {
            under: Some(PathBuf::from("/w/team")),
            lang: None,
            max_projects: None,
        };
        let line = format!(
            "No other indexed project matches {}.\n",
            describe(&filtered)
        );
        assert!(line.contains("/w/team"), "name the applied filter: {line}");
    }

    #[test]
    fn a_description_is_carried_through_for_routing() {
        // The description is why an agent can pick the right project, so it
        // must survive into the response.
        let mut r = row("svc", "/w/svc", Some(5), &["ruby"]);
        r.description = Some(Description {
            text: "Handles billing.".to_string(),
            source: DescriptionSource::Config,
        });

        let (kept, _) = select_candidates(vec![r], Path::new("/none"), &FanoutFilter::default());

        assert_eq!(
            kept[0].description.as_ref().map(|d| d.text.as_str()),
            Some("Handles billing.")
        );
    }
}