cx-cli 0.6.5

Semantic code navigation for AI agents
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
use std::fs;
use std::path::{Path, PathBuf};

use memchr::memmem;
use serde::Serialize;

use crate::index::{FileData, Index, Symbol, SymbolKind};
use crate::language::{self, detect_language};
use crate::output::{print_toon, print_json};
use crate::util::glob::glob_match;

// --- Pagination ---

/// Pagination parameters resolved from CLI flags.
pub struct Pagination {
    /// Max results to return (None = unlimited).
    pub limit: Option<usize>,
    /// Number of results to skip.
    pub offset: usize,
}

/// Result of applying pagination to a result set.
struct Paginated<T> {
    /// The visible slice after offset + limit.
    items: Vec<T>,
    /// Total number of results before pagination.
    total: usize,
    /// The offset that was applied.
    offset: usize,
    /// The limit that was applied (None = unlimited).
    limit: Option<usize>,
}

impl<T> Paginated<T> {
    /// True when results were cut off (more items exist after this page).
    fn was_truncated(&self) -> bool {
        self.offset + self.items.len() < self.total
    }

    /// True when JSON output should use the paginated envelope
    /// (either truncated or mid-pagination via offset).
    fn needs_envelope(&self) -> bool {
        self.was_truncated() || self.offset > 0
    }
}

fn paginate<T>(items: Vec<T>, pg: &Pagination) -> Paginated<T> {
    let total = items.len();
    let visible = items.into_iter()
        .skip(pg.offset)
        .take(pg.limit.unwrap_or(usize::MAX))
        .collect();
    Paginated { items: visible, total, offset: pg.offset, limit: pg.limit }
}

/// Wraps results with pagination metadata for JSON output.
#[derive(Serialize)]
struct PaginatedJson<'a, T: Serialize> {
    total: usize,
    offset: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    limit: Option<usize>,
    results: &'a [T],
}

/// Emit a compact pagination hint on stderr.
fn emit_pagination_hint(total: usize, offset: usize, shown: usize, subject: &str, narrow_hint: &str) {
    let next_offset = offset + shown;
    eprintln!(
        "cx: {}/{} {} | {} to narrow | --offset {} for more | --all",
        shown, total, subject, narrow_hint, next_offset
    );
}

fn print_paginated_json<T: Serialize>(pg: &Paginated<T>) {
    let wrapper = PaginatedJson {
        total: pg.total,
        offset: pg.offset,
        limit: pg.limit,
        results: &pg.items,
    };
    print_json(&wrapper);
}

// --- Serializable output types ---

#[derive(Serialize)]
struct SymbolRowOut {
    #[serde(skip_serializing_if = "Option::is_none")]
    file: Option<String>,
    name: String,
    kind: String,
    signature: String,
}

#[derive(Serialize)]
struct DefinitionResult {
    file: String,
    line: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    truncated: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    lines: Option<usize>,
    body: String,
}

// --- Query implementations ---

struct SymbolRow<'a> {
    file: &'a Path,
    symbol: &'a Symbol,
}

/// Execute the symbols query with optional file, name glob, and kind filters.
/// When scoped to a single file, omits the file column from output.
pub fn symbols(
    index: &Index,
    file: Option<&Path>,
    name_glob: Option<&str>,
    kind_filter: Option<SymbolKind>,
    json: bool,
    pg: &Pagination,
) -> i32 {
    let mut rows: Vec<SymbolRow<'_>> = Vec::new();

    let rel_path = file.map(|f| make_relative(f, &index.root));

    let files_to_search: Vec<(&PathBuf, &FileData)> = match rel_path {
        Some(ref rel) => match resolve_file_filter(rel, index) {
            Ok(v) => v,
            Err(code) => return code,
        },
        None => index.entries.iter().collect(),
    };
    let is_single_file = file.is_some() && files_to_search.len() == 1;

    for (path, data) in files_to_search {
        for sym in &data.symbols {
            if let Some(pattern) = name_glob
                && !glob_match(pattern, &sym.name) {
                    continue;
                }

            if let Some(kind) = kind_filter
                && sym.kind != kind {
                    continue;
                }

            rows.push(SymbolRow {
                file: path,
                symbol: sym,
            });
        }
    }

    if rows.is_empty() {
        eprintln!("cx: no matches");
        return 0;
    }

    rows.sort_by(|a, b| a.file.cmp(b.file).then(a.symbol.name.cmp(&b.symbol.name)));

    let single_file = is_single_file;
    let out: Vec<SymbolRowOut> = rows
        .into_iter()
        .map(|r| SymbolRowOut {
            file: if single_file { None } else { Some(display_path(r.file)) },
            name: r.symbol.name.clone(),
            kind: r.symbol.kind.as_str().to_string(),
            signature: r.symbol.signature.clone(),
        })
        .collect();

    let paged = paginate(out, pg);

    if json {
        if paged.needs_envelope() {
            print_paginated_json(&paged);
        } else {
            print_json(&paged.items);
        }
    } else {
        print_toon(&paged.items);
    }

    if paged.was_truncated() {
        emit_pagination_hint(paged.total, paged.offset, paged.items.len(), "symbols", "--file PATH | --kind KIND");
    }

    0
}

/// Serializable row for kind_counts output.
#[derive(Serialize)]
struct KindCountRow {
    kind: String,
    count: usize,
}

/// List distinct symbol kinds with their counts, optionally scoped to a file.
pub fn kind_counts(
    index: &Index,
    file: Option<&Path>,
    json: bool,
) -> i32 {
    let rel_path = file.map(|f| make_relative(f, &index.root));

    let files_to_search: Vec<(&PathBuf, &FileData)> = match rel_path {
        Some(ref rel) => match resolve_file_filter(rel, index) {
            Ok(v) => v,
            Err(code) => return code,
        },
        None => index.entries.iter().collect(),
    };

    let mut counts: std::collections::BTreeMap<&'static str, usize> = std::collections::BTreeMap::new();
    for (_path, data) in files_to_search {
        for sym in &data.symbols {
            *counts.entry(sym.kind.as_str()).or_insert(0) += 1;
        }
    }

    if counts.is_empty() {
        eprintln!("cx: no symbols in index");
        return 0;
    }

    let mut rows: Vec<KindCountRow> = counts
        .into_iter()
        .map(|(kind, count)| KindCountRow { kind: kind.to_string(), count })
        .collect();
    rows.sort_by(|a, b| b.count.cmp(&a.count));

    if json {
        print_json(&rows);
    } else {
        print_toon(&rows);
    }

    0
}

/// Execute the definition query: find symbol by exact name, return its body.
pub fn definition(
    index: &Index,
    name: &str,
    from: Option<&Path>,
    kind_filter: Option<SymbolKind>,
    max_lines: usize,
    json: bool,
    pg: &Pagination,
) -> i32 {
    let from_rel = from.map(|f| make_relative(f, &index.root));

    let mut matches: Vec<(&PathBuf, &Symbol)> = Vec::new();
    for (path, data) in &index.entries {
        for sym in &data.symbols {
            if sym.name == name {
                if let Some(kind) = kind_filter
                    && sym.kind != kind {
                        continue;
                    }
                matches.push((path, sym));
            }
        }
    }

    if let Some(ref from_path) = from_rel {
        let is_dir = index.root.join(from_path).is_dir();
        let from_matches: Vec<_> = matches
            .iter()
            .filter(|(path, _)| {
                if is_dir { path.starts_with(from_path) } else { *path == from_path }
            })
            .cloned()
            .collect();
        if !from_matches.is_empty() {
            matches = from_matches;
        }
    }

    if matches.is_empty() {
        eprintln!("cx: no matches");
        return 0;
    }

    // Sort by symbol priority (types first) then by file path
    matches.sort_by(|a, b| {
        symbol_priority(a.1.kind).cmp(&symbol_priority(b.1.kind))
            .then(a.0.cmp(b.0))
    });

    // Paginate matches BEFORE reading bodies to avoid pointless disk I/O
    let paged_matches = paginate(matches, pg);

    let results: Vec<DefinitionResult> = paged_matches.items
        .iter()
        .map(|(path, sym)| {
            let (body, start_line) = read_body(&index.root, path, sym.byte_range)
                .unwrap_or((String::new(), 0));
            let line_count = body.lines().count();
            let truncated = line_count > max_lines;

            let display_body = if truncated {
                body.lines()
                    .take(max_lines)
                    .collect::<Vec<_>>()
                    .join("\n")
            } else {
                body
            };

            DefinitionResult {
                file: display_path(path),
                line: start_line,
                truncated: if truncated { Some(true) } else { None },
                lines: if truncated { Some(line_count) } else { None },
                body: display_body,
            }
        })
        .collect();

    if json {
        if paged_matches.needs_envelope() {
            let wrapper = PaginatedJson {
                total: paged_matches.total,
                offset: paged_matches.offset,
                limit: paged_matches.limit,
                results: &results,
            };
            print_json(&wrapper);
        } else {
            print_json(&results);
        }
    } else {
        for (i, r) in results.iter().enumerate() {
            if i > 0 {
                println!();
            }
            print!("file: {}\nline: {}", r.file, r.line);
            if let Some(total) = r.lines {
                print!("\ntruncated: {} lines total", total);
            }
            println!("\n---\n{}", r.body);
        }
    }

    if paged_matches.was_truncated() {
        let subject = format!("definitions for \"{}\"", name);
        emit_pagination_hint(paged_matches.total, paged_matches.offset, results.len(), &subject, "--from PATH");
    }

    0
}

#[derive(Serialize)]
struct ReferenceRow {
    file: String,
    line: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    caller: Option<String>,
    context: String,
}

/// Find the enclosing symbol for a byte offset in a file's symbol list.
fn find_enclosing_symbol(symbols: &[Symbol], byte_offset: usize) -> Option<&str> {
    symbols
        .iter()
        .filter(|s| s.byte_range.0 <= byte_offset && byte_offset < s.byte_range.1)
        // Pick the tightest enclosing symbol (smallest range)
        .min_by_key(|s| s.byte_range.1 - s.byte_range.0)
        .map(|s| s.name.as_str())
}

/// Unique caller row for --unique mode.
#[derive(Serialize)]
struct UniqueCallerRow {
    file: String,
    caller: String,
    line: usize,
}

/// Find all usages of a symbol name across project files.
pub fn references(
    index: &Index,
    name: &str,
    file: Option<&Path>,
    unique: bool,
    json: bool,
    pg: &Pagination,
) -> i32 {
    let rel_path = file.map(|f| make_relative(f, &index.root));

    let files_to_search: Vec<(&PathBuf, &FileData)> = match rel_path {
        Some(ref rel) => match resolve_file_filter(rel, index) {
            Ok(v) => v,
            Err(code) => return code,
        },
        None => index.entries.iter().collect(),
    };

    let mut rows: Vec<ReferenceRow> = Vec::new();
    let name_bytes = name.as_bytes();

    for (path, data) in files_to_search {
        let abs_path = index.root.join(path);
        let source = match fs::read(&abs_path) {
            Ok(s) => s,
            Err(_) => continue,
        };

        // Skip files that can't possibly contain the name
        if memmem::find(&source, name_bytes).is_none() {
            continue;
        }

        let refs = match language::find_references(&data.meta.language, &source, &abs_path, name) {
            Ok(r) => r,
            Err(language::LangError::NotInstalled(lang)) => {
                eprintln!("cx: {} grammar not installed — run: cx lang add {}", lang, lang);
                return 1;
            }
            Err(_) => continue,
        };
        if refs.is_empty() {
            continue;
        }

        // Convert to str once per file for context extraction
        let text = std::str::from_utf8(&source).ok();
        let lines: Vec<&str> = text.map(|t| t.lines().collect()).unwrap_or_default();

        for r in refs {
            let context = lines
                .get(r.line.wrapping_sub(1))
                .map(|l| l.trim().to_string())
                .unwrap_or_default();
            let caller = find_enclosing_symbol(&data.symbols, r.byte_offset)
                .map(|s| s.to_string());
            rows.push(ReferenceRow {
                file: display_path(path),
                line: r.line,
                caller,
                context,
            });
        }
    }

    if rows.is_empty() {
        eprintln!("cx: no matches");
        return 0;
    }

    rows.sort_by(|a, b| a.file.cmp(&b.file).then(a.line.cmp(&b.line)));
    rows.dedup_by(|a, b| a.file == b.file && a.line == b.line);

    let narrow_hint = "--file PATH";

    if unique {
        // Deduplicate to one row per (file, caller) pair
        let mut seen = std::collections::HashSet::new();
        let unique_rows: Vec<UniqueCallerRow> = rows
            .into_iter()
            .filter_map(|r| {
                let caller = r.caller?;
                if seen.insert((r.file.clone(), caller.clone())) {
                    Some(UniqueCallerRow { file: r.file, caller, line: r.line })
                } else {
                    None
                }
            })
            .collect();
        if unique_rows.is_empty() {
            eprintln!("cx: no callers found");
            return 0;
        }
        let paged = paginate(unique_rows, pg);
        if json {
            if paged.needs_envelope() { print_paginated_json(&paged); } else { print_json(&paged.items); }
        } else {
            print_toon(&paged.items);
        }
        if paged.was_truncated() {
            let subject = format!("references for \"{}\"", name);
            emit_pagination_hint(paged.total, paged.offset, paged.items.len(), &subject, narrow_hint);
        }
    } else {
        let paged = paginate(rows, pg);
        if json {
            if paged.needs_envelope() { print_paginated_json(&paged); } else { print_json(&paged.items); }
        } else {
            print_toon(&paged.items);
        }
        if paged.was_truncated() {
            let subject = format!("references for \"{}\"", name);
            emit_pagination_hint(paged.total, paged.offset, paged.items.len(), &subject, narrow_hint);
        }
    }

    0
}

// --- Directory overview ---

const DIR_OVERVIEW_MAX_SYMBOLS: usize = 10;

#[derive(Serialize)]
struct DirOverviewRow {
    file: String,
    symbols: String,
}

#[derive(Serialize)]
struct DirOverviewFullRow {
    file: String,
    name: String,
    kind: String,
    signature: String,
}

/// Priority for symbol kinds in directory overview: lower = shown first.
fn symbol_priority(kind: SymbolKind) -> u8 {
    match kind {
        SymbolKind::Struct | SymbolKind::Enum | SymbolKind::Trait
        | SymbolKind::Interface | SymbolKind::Class => 0,
        SymbolKind::Fn | SymbolKind::Const | SymbolKind::Type
        | SymbolKind::Module | SymbolKind::Event => 1,
        SymbolKind::Field => 2,
    }
}

/// Check if a file path looks like a test file based on naming conventions.
fn is_test_file(path: &Path) -> bool {
    for component in path.components() {
        if let std::path::Component::Normal(s) = component {
            let s = s.to_str().unwrap_or("");
            if s == "tests" || s == "test" || s == "__tests__" {
                return true;
            }
        }
    }
    let name = match path.file_name().and_then(|n| n.to_str()) {
        Some(n) => n,
        None => return false,
    };
    // Go: *_test.go
    if name.ends_with("_test.go") { return true; }
    // JS/TS: *.test.* or *.spec.*
    for ext in &[".test.ts", ".test.tsx", ".test.js", ".test.jsx",
                 ".spec.ts", ".spec.tsx", ".spec.js", ".spec.jsx"] {
        if name.ends_with(ext) { return true; }
    }
    // Python: test_*.py
    if name.starts_with("test_") && name.ends_with(".py") { return true; }
    // Ruby: *_spec.rb
    if name.ends_with("_spec.rb") { return true; }
    false
}

/// Extract the immediate child component of `path` relative to `dir`.
/// Returns `None` if the path is not under `dir`.
/// For a direct child file, returns the full relative path.
/// For a nested file, returns just the first subdirectory component (with trailing /).
fn child_component(path: &Path, dir: &Path) -> Option<PathBuf> {
    let relative = if dir.as_os_str().is_empty() {
        path.to_path_buf()
    } else {
        path.strip_prefix(dir).ok()?.to_path_buf()
    };
    let mut components = relative.components();
    let first = components.next()?;
    if components.next().is_some() {
        // Nested — return just the subdir name
        Some(PathBuf::from(first.as_os_str()))
    } else {
        // Direct child file
        Some(relative)
    }
}

/// Show a single-level overview of files and subdirectories.
pub fn dir_overview(
    index: &Index,
    dir: &Path,
    full: bool,
    json: bool,
    pg: &Pagination,
) -> i32 {
    let rel_dir = make_relative(dir, &index.root);
    // Normalize "." to empty path so starts_with matches all entries
    let rel_dir = if rel_dir == Path::new(".") { PathBuf::new() } else { rel_dir };

    let all_entries: Vec<(&PathBuf, &FileData)> = index
        .entries
        .iter()
        .filter(|(path, _)| rel_dir.as_os_str().is_empty() || path.starts_with(&rel_dir))
        .filter(|(path, _)| !is_test_file(path))
        .collect();

    if all_entries.is_empty() {
        eprintln!("cx: no indexed files under {}", display_path(&rel_dir));
        return 1;
    }

    // Partition into direct files and subdirectory aggregates
    let mut direct_files: Vec<(&PathBuf, &FileData)> = Vec::new();
    let mut subdirs: std::collections::BTreeMap<String, (usize, usize)> = std::collections::BTreeMap::new();

    for (path, data) in &all_entries {
        let child = match child_component(path, &rel_dir) {
            Some(c) => c,
            None => continue,
        };
        let non_test_count = data.symbols.iter().filter(|s| !s.is_test).count();
        if child.components().count() == 1 && child.extension().is_some() {
            // Direct child file
            direct_files.push((path, data));
        } else {
            // Subdirectory — aggregate
            let dir_name = child.to_string_lossy().to_string();
            let entry = subdirs.entry(dir_name).or_insert((0, 0));
            entry.0 += 1;
            entry.1 += non_test_count;
        }
    }

    direct_files.sort_by_key(|(path, _)| *path);

    // Shared: format subdir display path
    let format_subdir = |dir_name: &str| -> String {
        if rel_dir.as_os_str().is_empty() {
            format!("{}/", dir_name)
        } else {
            format!("{}/{}/", display_path(&rel_dir), dir_name)
        }
    };

    fn prepare_symbols(data: &FileData) -> Vec<&Symbol> {
        let mut syms: Vec<&Symbol> = data.symbols.iter()
            .filter(|s| !s.is_test)
            .collect();
        syms.sort_by(|a, b| symbol_priority(a.kind).cmp(&symbol_priority(b.kind))
            .then(a.name.cmp(&b.name)));
        syms
    }

    if full {
        let mut rows: Vec<DirOverviewFullRow> = Vec::new();
        for (dir_name, (file_count, sym_count)) in &subdirs {
            rows.push(DirOverviewFullRow {
                file: format_subdir(dir_name),
                name: format!("({} files, {} symbols)", file_count, sym_count),
                kind: String::new(),
                signature: String::new(),
            });
        }
        for (path, data) in &direct_files {
            let syms = prepare_symbols(data);
            if syms.is_empty() { continue; }
            let total = syms.len();
            for sym in syms.iter().take(DIR_OVERVIEW_MAX_SYMBOLS) {
                rows.push(DirOverviewFullRow {
                    file: display_path(path),
                    name: sym.name.clone(),
                    kind: sym.kind.as_str().to_string(),
                    signature: sym.signature.clone(),
                });
            }
            if total > DIR_OVERVIEW_MAX_SYMBOLS {
                rows.push(DirOverviewFullRow {
                    file: display_path(path),
                    name: format!("... (+{} more)", total - DIR_OVERVIEW_MAX_SYMBOLS),
                    kind: String::new(),
                    signature: String::new(),
                });
            }
        }
        let paged = paginate(rows, pg);
        if json {
            if paged.needs_envelope() { print_paginated_json(&paged); } else { print_json(&paged.items); }
        } else {
            print_toon(&paged.items);
        }
        if paged.was_truncated() {
            emit_pagination_hint(paged.total, paged.offset, paged.items.len(), "entries", "cx overview <subdir>");
        }
    } else {
        let mut rows: Vec<DirOverviewRow> = Vec::new();
        for (dir_name, (file_count, sym_count)) in &subdirs {
            rows.push(DirOverviewRow {
                file: format_subdir(dir_name),
                symbols: format!("({} files, {} symbols)", file_count, sym_count),
            });
        }
        for (path, data) in &direct_files {
            let syms = prepare_symbols(data);
            if syms.is_empty() { continue; }
            let total = syms.len();
            // Deduplicate names (e.g. overloaded type params)
            let mut seen = std::collections::HashSet::new();
            let names: Vec<&str> = syms.iter()
                .take(DIR_OVERVIEW_MAX_SYMBOLS)
                .map(|s| s.name.as_str())
                .filter(|n| seen.insert(*n))
                .collect();
            let shown = names.len();
            let suffix = if total > shown {
                format!(", ... (+{} more)", total - shown)
            } else {
                String::new()
            };
            rows.push(DirOverviewRow {
                file: display_path(path),
                symbols: format!("{}{}", names.join(", "), suffix),
            });
        }
        let paged = paginate(rows, pg);
        if json {
            if paged.needs_envelope() { print_paginated_json(&paged); } else { print_json(&paged.items); }
        } else {
            print_toon(&paged.items);
        }
        if paged.was_truncated() {
            emit_pagination_hint(paged.total, paged.offset, paged.items.len(), "entries", "cx overview <subdir>");
        }
    }

    0
}

fn read_body(root: &Path, file: &Path, byte_range: (usize, usize)) -> Option<(String, usize)> {
    let abs_path = root.join(file);
    let source = fs::read(&abs_path).ok()?;
    let (start, end) = byte_range;
    if end > source.len() {
        return None;
    }
    let line = source[..start].iter().filter(|&&b| b == b'\n').count() + 1;
    let body = String::from_utf8_lossy(&source[start..end]).to_string();
    Some((body, line))
}

/// Display a path using forward slashes (consistent across platforms).
fn display_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn resolve_file_filter<'a>(
    rel: &Path,
    index: &'a Index,
) -> Result<Vec<(&'a PathBuf, &'a FileData)>, i32> {
    if let Some(kv) = index.entries.get_key_value(rel) {
        return Ok(vec![kv]);
    }
    let abs = index.root.join(rel);
    if abs.is_dir() {
        let matches: Vec<_> = index
            .entries
            .iter()
            .filter(|(path, _)| path.starts_with(rel))
            .collect();
        if matches.is_empty() {
            eprintln!("cx: no indexed files under {}", display_path(rel));
            return Err(1);
        }
        return Ok(matches);
    }
    if abs.exists() && detect_language(&abs).is_none() {
        let ext = abs.extension().and_then(|e| e.to_str()).unwrap_or("(none)");
        eprintln!("cx: unsupported file type: .{}", ext);
    } else {
        eprintln!("cx: file not in index: {}", display_path(rel));
    }
    Err(1)
}

/// Make a path relative to the project root if it's absolute,
/// or resolve it from cwd if relative.
fn make_relative(path: &Path, root: &Path) -> PathBuf {
    if path.is_absolute() {
        path.strip_prefix(root).unwrap_or(path).to_path_buf()
    } else {
        let cwd = std::env::current_dir().unwrap_or_default();
        let abs = cwd.join(path);
        abs.strip_prefix(root).unwrap_or(path).to_path_buf()
    }
}

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

    #[test]
    fn display_path_normalizes_backslashes() {
        assert_eq!(display_path(Path::new("src/main.rs")), "src/main.rs");
        assert_eq!(display_path(Path::new("src\\main.rs")), "src/main.rs");
        assert_eq!(display_path(Path::new("src\\sub\\file.rs")), "src/sub/file.rs");
    }

    // --- is_test_file tests ---

    #[test]
    fn test_file_go() {
        assert!(is_test_file(Path::new("pkg/handler_test.go")));
        assert!(!is_test_file(Path::new("pkg/handler.go")));
    }

    #[test]
    fn test_file_ts_js() {
        assert!(is_test_file(Path::new("src/app.test.ts")));
        assert!(is_test_file(Path::new("src/app.test.tsx")));
        assert!(is_test_file(Path::new("src/app.spec.js")));
        assert!(is_test_file(Path::new("src/app.spec.jsx")));
        assert!(!is_test_file(Path::new("src/app.ts")));
    }

    #[test]
    fn test_file_python() {
        assert!(is_test_file(Path::new("test_utils.py")));
        assert!(!is_test_file(Path::new("utils_test.py"))); // Python convention is test_ prefix
        assert!(!is_test_file(Path::new("test_utils.rs"))); // wrong extension
    }

    #[test]
    fn test_file_ruby() {
        assert!(is_test_file(Path::new("models/user_spec.rb")));
        assert!(!is_test_file(Path::new("models/user.rb")));
    }

    #[test]
    fn test_file_directory() {
        assert!(is_test_file(Path::new("tests/unit/foo.rs")));
        assert!(is_test_file(Path::new("test/foo.js")));
        assert!(is_test_file(Path::new("src/__tests__/app.tsx")));
        assert!(!is_test_file(Path::new("src/foo.rs")));
    }

    #[test]
    fn test_file_normal_files() {
        assert!(!is_test_file(Path::new("src/main.rs")));
        assert!(!is_test_file(Path::new("lib/utils.ts")));
        assert!(!is_test_file(Path::new("index.js")));
    }

    // --- symbol_priority tests ---

    #[test]
    fn symbol_priority_ordering() {
        // Types should come before functions, which come before methods
        assert!(symbol_priority(SymbolKind::Struct) < symbol_priority(SymbolKind::Fn));
        assert!(symbol_priority(SymbolKind::Enum) < symbol_priority(SymbolKind::Fn));
        assert!(symbol_priority(SymbolKind::Trait) < symbol_priority(SymbolKind::Fn));
        assert!(symbol_priority(SymbolKind::Interface) < symbol_priority(SymbolKind::Fn));
        assert!(symbol_priority(SymbolKind::Class) < symbol_priority(SymbolKind::Fn));
        assert!(symbol_priority(SymbolKind::Fn) < symbol_priority(SymbolKind::Field));
    }
}