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
use std::process::Command;
use std::io::Write;

fn cx() -> Command {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_cx"));
    cmd.current_dir(env!("CARGO_MANIFEST_DIR"));
    cmd
}

/// Create a temporary directory with a fake git repo for isolated tests.
/// Returns the temp dir (dropped = cleaned up).
fn temp_project(files: &[(&str, &str)]) -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    // Create .git so cx finds project root
    std::fs::create_dir(dir.path().join(".git")).unwrap();
    for (path, content) in files {
        let full = dir.path().join(path);
        if let Some(parent) = full.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        let mut f = std::fs::File::create(&full).unwrap();
        f.write_all(content.as_bytes()).unwrap();
    }
    dir
}

fn cx_in(dir: &std::path::Path) -> Command {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_cx"));
    cmd.current_dir(dir);
    cmd
}

#[test]
fn overview_main_rs() {
    let out = cx().args(["overview", "src/main.rs"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    assert!(stdout.contains("{name,kind,signature}:"), "should have TOON header: {stdout}");
    assert!(stdout.contains("main,fn,"));
    assert!(stdout.contains("resolve_root,fn,"));
}

#[test]
fn symbols_kind_fn() {
    let out = cx().args(["symbols", "--kind", "fn", "--all"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success());
    assert!(stdout.contains("main,fn,"));
    assert!(stdout.contains("print_toon,fn,"));
}

#[test]
fn definition_main() {
    let out = cx().args(["definition", "--name", "main"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success());
    assert!(stdout.contains("src/main.rs"), "{stdout}");
    assert!(stdout.contains("fn main()"), "{stdout}");
    assert!(stdout.contains("Cli::parse()"), "{stdout}");
}

#[test]
fn overview_nonexistent_exits_1() {
    let out = cx().args(["overview", "nonexistent.rs"]).output().unwrap();
    assert_eq!(out.status.code(), Some(1));
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("nonexistent.rs"), "stderr should mention the file: {stderr}");
}

#[test]
fn symbols_no_match_exits_0() {
    let out = cx().args(["symbols", "--name", "zzz_no_match"]).output().unwrap();
    assert_eq!(out.status.code(), Some(0));
}

#[test]
fn json_overview() {
    let out = cx().args(["--json", "overview", "src/main.rs"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success());
    let parsed: serde_json::Value = serde_json::from_str(&stdout)
        .expect("should be valid JSON");
    assert!(parsed.is_array());
}

#[test]
fn json_definition_always_array() {
    let out = cx().args(["--json", "definition", "--name", "main"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success());
    let parsed: serde_json::Value = serde_json::from_str(&stdout)
        .expect("should be valid JSON");
    // Always an array, even for single results (audit fix)
    assert!(parsed.is_array(), "definition JSON should always be an array: {stdout}");
    assert_eq!(parsed.as_array().unwrap().len(), 1);
}

// --- Definition --from and --max-lines tests ---

#[test]
fn definition_from_disambiguates() {
    let dir = temp_project(&[
        ("src/a.rs", "pub fn helper() { 1 }\n"),
        ("src/b.rs", "pub fn helper() { 2 }\n"),
    ]);

    // Without --from: should find both
    let out = cx_in(dir.path()).args(["--json", "definition", "--name", "helper"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(parsed.as_array().unwrap().len(), 2, "should find both: {stdout}");

    // With --from: should find only one
    let out2 = cx_in(dir.path())
        .args(["--json", "definition", "--name", "helper", "--from", "src/a.rs"])
        .output()
        .unwrap();
    let stdout2 = String::from_utf8_lossy(&out2.stdout);
    let parsed2: serde_json::Value = serde_json::from_str(&stdout2).unwrap();
    let arr = parsed2.as_array().unwrap();
    assert_eq!(arr.len(), 1, "should find one: {stdout2}");
    assert_eq!(arr[0]["file"].as_str().unwrap(), "src/a.rs");
}

#[test]
fn definition_max_lines_truncates() {
    // Create a file with a long function
    let mut body = String::from("pub fn big() {\n");
    for i in 0..250 {
        body.push_str(&format!("    let x{i} = {i};\n"));
    }
    body.push_str("}\n");

    let dir = temp_project(&[("src/big.rs", &body)]);

    // Default max-lines (200) should truncate
    let out = cx_in(dir.path())
        .args(["--json", "definition", "--name", "big"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let item = &parsed.as_array().unwrap()[0];
    assert_eq!(item["truncated"].as_bool(), Some(true), "should be truncated: {stdout}");
    assert!(item["lines"].as_u64().unwrap() > 200, "should report total lines: {stdout}");
}

// --- Cache ---

#[test]
fn cache_path_prints_path() {
    let dir = temp_project(&[("src/main.rs", "fn main() {}\n")]);
    let out = cx_in(dir.path()).args(["cache", "path"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    assert!(stdout.contains("indexes/") || stdout.contains("indexes\\"), "should contain indexes path: {stdout}");
    assert!(stdout.trim().ends_with(".db"), "should end with .db: {stdout}");
}

#[test]
fn cache_clean_removes_index() {
    let dir = temp_project(&[("src/main.rs", "fn main() {}\n")]);

    // Build the index first
    let out = cx_in(dir.path()).args(["overview", "src/main.rs"]).output().unwrap();
    assert!(out.status.success());

    // Get the cache path
    let out = cx_in(dir.path()).args(["cache", "path"]).output().unwrap();
    let cache_path = String::from_utf8_lossy(&out.stdout).trim().to_string();
    assert!(std::path::Path::new(&cache_path).exists(), "index should exist after build");

    // Clean it
    let out = cx_in(dir.path()).args(["cache", "clean"]).output().unwrap();
    assert!(out.status.success());
    assert!(!std::path::Path::new(&cache_path).exists(), "index should be gone after clean");
}

#[test]
fn index_not_in_repo_root() {
    let dir = temp_project(&[("src/main.rs", "fn main() {}\n")]);
    let _ = cx_in(dir.path()).args(["overview", "src/main.rs"]).output().unwrap();

    // No .cx-index.db in the repo root
    assert!(!dir.path().join(".cx-index.db").exists(), "should not create .cx-index.db in repo root");
}

// --- Version ---

#[test]
fn version_flag() {
    let out = cx().arg("--version").output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.starts_with("cx "), "should print version: {stdout}");
}

// --- Error messages ---

#[test]
fn unsupported_file_type_error() {
    let dir = temp_project(&[
        ("README.md", "# Hello\n"),
        ("src/main.rs", "fn main() {}\n"),
    ]);
    let out = cx_in(dir.path()).args(["overview", "README.md"]).output().unwrap();
    assert_eq!(out.status.code(), Some(1));
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("unsupported file type: .md"), "should hint at unsupported type: {stderr}");
}

#[test]
fn no_matches_stderr() {
    let out = cx().args(["definition", "--name", "zzz_nonexistent"]).output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("no matches"), "should print no matches: {stderr}");
}

// --- Definition --kind filter ---

#[test]
fn definition_kind_filter() {
    let dir = temp_project(&[
        ("src/lib.rs", "pub struct Foo;\npub fn Foo() {}\n"),
    ]);
    let out = cx_in(dir.path())
        .args(["--json", "definition", "--name", "Foo", "--kind", "fn"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let arr = parsed.as_array().unwrap();
    assert_eq!(arr.len(), 1, "should find only the fn, not the struct: {stdout}");
    assert!(arr[0]["body"].as_str().unwrap().contains("fn Foo()"));
}

// --- References --file filter ---

#[test]
fn references_file_filter() {
    let dir = temp_project(&[
        ("src/a.rs", "pub struct Foo;\nfn use_foo(f: Foo) {}\n"),
        ("src/b.rs", "use crate::Foo;\nfn bar(f: Foo) {}\n"),
    ]);
    let out = cx_in(dir.path())
        .args(["references", "--name", "Foo", "--file", "src/a.rs"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    // Should only contain src/a.rs references, not src/b.rs
    assert!(stdout.contains("src/a.rs"), "should find refs in a.rs: {stdout}");
    assert!(!stdout.contains("src/b.rs"), "should not include b.rs: {stdout}");
}

// --- References dedup ---

#[test]
fn references_dedup_same_line() {
    let dir = temp_project(&[
        ("src/lib.rs", "fn convert(x: Foo) -> Foo { x }\npub struct Foo;\n"),
    ]);
    let out = cx_in(dir.path())
        .args(["--json", "references", "--name", "Foo"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let arr = parsed.as_array().unwrap();
    // Line 1 has Foo twice (param + return), should be deduped to one entry
    let line1_refs: Vec<_> = arr.iter().filter(|r| r["line"] == 1).collect();
    assert_eq!(line1_refs.len(), 1, "same-line refs should be deduped: {stdout}");
}

// --- Directory overview ---

#[test]
fn overview_directory_single_level() {
    let dir = temp_project(&[
        ("src/main.rs", "fn main() {}\n"),
        ("src/lib.rs", "pub fn hello() {}\npub struct Config;\n"),
        ("src/util/helpers.rs", "pub fn help() {}\n"),
        ("src/util/math.rs", "pub fn add() {}\npub fn sub() {}\n"),
    ]);
    let out = cx_in(dir.path()).args(["overview", "src/"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    // Should show util/ as a subdirectory, not individual files inside it
    assert!(stdout.contains("util/"), "should group util as subdir: {stdout}");
    assert!(!stdout.contains("helpers.rs"), "should not show nested files: {stdout}");
    // Direct files should be listed
    assert!(stdout.contains("main.rs"), "should show direct file: {stdout}");
    assert!(stdout.contains("lib.rs"), "should show direct file: {stdout}");
}

#[test]
fn overview_directory_root() {
    let dir = temp_project(&[
        ("src/main.rs", "fn main() {}\n"),
        ("src/lib.rs", "pub fn hello() {}\n"),
    ]);
    let out = cx_in(dir.path()).args(["overview", "."]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    assert!(stdout.contains("src/"), "should show src as subdir: {stdout}");
}

#[test]
fn overview_directory_filters_test_files() {
    let dir = temp_project(&[
        ("src/app.ts", "export function main() {}\n"),
        ("src/app.test.ts", "describe('app', () => {})\n"),
        ("tests/integration.rs", "fn test_it() {}\n"),
    ]);
    let out = cx_in(dir.path()).args(["overview", "."]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    // Test files and test directories should be excluded
    assert!(!stdout.contains("app.test.ts"), "should filter test files: {stdout}");
    assert!(!stdout.contains("tests/"), "should filter test dirs: {stdout}");
}

#[test]
fn overview_directory_nonexistent() {
    let dir = temp_project(&[("src/main.rs", "fn main() {}\n")]);
    let out = cx_in(dir.path()).args(["overview", "nonexistent/"]).output().unwrap();
    assert_eq!(out.status.code(), Some(1));
}

// --- JSON output for definition ---

#[test]
fn json_definition_has_expected_fields() {
    let out = cx().args(["--json", "definition", "--name", "main"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let item = &parsed.as_array().unwrap()[0];
    assert!(item["file"].is_string());
    assert!(item["line"].is_number());
    assert!(item["body"].is_string());
}

// --- Pagination tests ---

#[test]
fn definition_default_limit_truncates() {
    let dir = temp_project(&[
        ("src/a.rs", "pub fn helper() { 1 }\n"),
        ("src/b.rs", "pub fn helper() { 2 }\n"),
        ("src/c.rs", "pub fn helper() { 3 }\n"),
        ("src/d.rs", "pub fn helper() { 4 }\n"),
        ("src/e.rs", "pub fn helper() { 5 }\n"),
    ]);

    // Default limit for definition is 3
    let out = cx_in(dir.path())
        .args(["--json", "definition", "--name", "helper"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    // Should be paginated JSON (object with total/results)
    assert!(parsed.is_object(), "paginated output should be an object: {stdout}");
    assert_eq!(parsed["total"].as_u64().unwrap(), 5);
    assert_eq!(parsed["results"].as_array().unwrap().len(), 3);

    // Stderr should contain the pagination hint
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("3/5"), "should show 3/5 in hint: {stderr}");
    assert!(stderr.contains("--offset 3"), "should suggest next offset: {stderr}");
    assert!(stderr.contains("--all"), "should suggest --all: {stderr}");
}

#[test]
fn definition_offset_paginates() {
    let dir = temp_project(&[
        ("src/a.rs", "pub fn helper() { 1 }\n"),
        ("src/b.rs", "pub fn helper() { 2 }\n"),
        ("src/c.rs", "pub fn helper() { 3 }\n"),
        ("src/d.rs", "pub fn helper() { 4 }\n"),
        ("src/e.rs", "pub fn helper() { 5 }\n"),
    ]);

    // Get the second page — offset > 0 so always gets envelope
    let out = cx_in(dir.path())
        .args(["--json", "definition", "--name", "helper", "--offset", "3"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert!(parsed.is_object(), "offset > 0 should produce paginated envelope: {stdout}");
    assert_eq!(parsed["total"].as_u64().unwrap(), 5);
    assert_eq!(parsed["offset"].as_u64().unwrap(), 3);
    assert_eq!(parsed["results"].as_array().unwrap().len(), 2);
}

#[test]
fn definition_all_bypasses_limit() {
    let dir = temp_project(&[
        ("src/a.rs", "pub fn helper() { 1 }\n"),
        ("src/b.rs", "pub fn helper() { 2 }\n"),
        ("src/c.rs", "pub fn helper() { 3 }\n"),
        ("src/d.rs", "pub fn helper() { 4 }\n"),
        ("src/e.rs", "pub fn helper() { 5 }\n"),
    ]);

    let out = cx_in(dir.path())
        .args(["--json", "--all", "definition", "--name", "helper"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert!(parsed.is_array(), "should be bare array with --all: {stdout}");
    assert_eq!(parsed.as_array().unwrap().len(), 5);
}

#[test]
fn definition_from_skips_default_limit() {
    // Create 5 symbols with the same name across 5 files, plus 5 in a.rs
    // Default definition limit is 3, so without --from we'd get truncated.
    // With --from, all 5 from a.rs should be returned (proving limit is bypassed).
    let dir = temp_project(&[
        ("src/a.rs", "pub fn thing() { 1 }\npub fn thing2() { 2 }\nstruct thing3;\nstruct thing4;\nenum thing5 {}\n"),
        ("src/b.rs", "pub fn thing() { 10 }\n"),
        ("src/c.rs", "pub fn thing() { 20 }\n"),
        ("src/d.rs", "pub fn thing() { 30 }\n"),
        ("src/e.rs", "pub fn thing() { 40 }\n"),
    ]);

    // With --from src/a.rs: should return only the 1 match in a.rs (exact name match)
    // but crucially, without a default limit being applied
    let out = cx_in(dir.path())
        .args(["--json", "definition", "--name", "thing", "--from", "src/a.rs"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    // Bare array — no pagination envelope because --from disables default limit
    assert!(parsed.is_array(), "should be bare array when --from used: {stdout}");
    let arr = parsed.as_array().unwrap();
    assert_eq!(arr.len(), 1);
    assert!(arr[0]["file"].as_str().unwrap().contains("a.rs"));

    // Without --from: 5 total matches, default limit 3 → paginated
    let out2 = cx_in(dir.path())
        .args(["--json", "definition", "--name", "thing"])
        .output()
        .unwrap();
    let stdout2 = String::from_utf8_lossy(&out2.stdout);
    let parsed2: serde_json::Value = serde_json::from_str(&stdout2).unwrap();
    assert!(parsed2.is_object(), "without --from should be paginated: {stdout2}");
    assert_eq!(parsed2["total"].as_u64().unwrap(), 5);
    assert_eq!(parsed2["results"].as_array().unwrap().len(), 3);
}

#[test]
fn definition_explicit_limit_overrides_default() {
    let dir = temp_project(&[
        ("src/a.rs", "pub fn helper() { 1 }\n"),
        ("src/b.rs", "pub fn helper() { 2 }\n"),
        ("src/c.rs", "pub fn helper() { 3 }\n"),
        ("src/d.rs", "pub fn helper() { 4 }\n"),
        ("src/e.rs", "pub fn helper() { 5 }\n"),
    ]);

    let out = cx_in(dir.path())
        .args(["--json", "--limit", "2", "definition", "--name", "helper"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert!(parsed.is_object(), "should be paginated: {stdout}");
    assert_eq!(parsed["results"].as_array().unwrap().len(), 2);
    assert_eq!(parsed["total"].as_u64().unwrap(), 5);
}

#[test]
fn symbols_pagination_hint_on_stderr() {
    let dir = temp_project(&[
        ("src/a.rs", "pub fn a1() {}\npub fn a2() {}\n"),
        ("src/b.rs", "pub fn b1() {}\npub fn b2() {}\n"),
    ]);

    let out = cx_in(dir.path())
        .args(["--limit", "2", "symbols"])
        .output()
        .unwrap();
    assert!(out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("2/4"), "should show 2/4: {stderr}");
    assert!(stderr.contains("--offset 2"), "should suggest next offset: {stderr}");
}

#[test]
fn references_pagination() {
    let dir = temp_project(&[
        ("src/a.rs", "pub struct Foo;\nfn use1(f: Foo) {}\nfn use2(f: Foo) {}\n"),
        ("src/b.rs", "use crate::Foo;\nfn use3(f: Foo) {}\n"),
    ]);

    let out = cx_in(dir.path())
        .args(["--json", "--limit", "2", "references", "--name", "Foo"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    // Should be paginated if total > 2
    if parsed.is_object() {
        assert_eq!(parsed["results"].as_array().unwrap().len(), 2);
        assert!(parsed["total"].as_u64().unwrap() >= 2);
    }
    // If total happens to be exactly 2, it won't paginate — that's fine
}

#[test]
fn json_paginated_has_metadata() {
    let dir = temp_project(&[
        ("src/a.rs", "pub fn helper() { 1 }\n"),
        ("src/b.rs", "pub fn helper() { 2 }\n"),
        ("src/c.rs", "pub fn helper() { 3 }\n"),
        ("src/d.rs", "pub fn helper() { 4 }\n"),
    ]);

    let out = cx_in(dir.path())
        .args(["--json", "--limit", "2", "definition", "--name", "helper"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert!(parsed["total"].is_number(), "should have total: {stdout}");
    assert!(parsed["offset"].is_number(), "should have offset: {stdout}");
    assert!(parsed["limit"].is_number(), "should have limit: {stdout}");
    assert!(parsed["results"].is_array(), "should have results: {stdout}");
    assert_eq!(parsed["offset"].as_u64().unwrap(), 0);
    assert_eq!(parsed["limit"].as_u64().unwrap(), 2);
}

#[test]
fn no_pagination_when_under_limit() {
    // Single match — should produce bare array, no pagination metadata
    let out = cx().args(["--json", "definition", "--name", "main"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert!(parsed.is_array(), "single result should be bare array: {stdout}");
}

// --- Directory filtering ---

fn dir_project() -> tempfile::TempDir {
    temp_project(&[
        ("src/lib.rs", "pub fn alpha() {}\npub fn beta() {}\n"),
        ("src/util.rs", "pub fn gamma() {}\n"),
        ("tests/test_main.rs", "fn test_alpha() {}\n"),
    ])
}

#[test]
fn symbols_file_directory_returns_all_files_in_dir() {
    let dir = dir_project();
    let out = cx_in(dir.path()).args(["symbols", "--kind", "fn", "--file", "src"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    assert!(stdout.contains("alpha"), "should find alpha in src/: {stdout}");
    assert!(stdout.contains("gamma"), "should find gamma in src/: {stdout}");
    assert!(!stdout.contains("test_alpha"), "should not include tests/: {stdout}");
}

#[test]
fn symbols_file_directory_shows_file_column() {
    let dir = dir_project();
    let out = cx_in(dir.path()).args(["--json", "symbols", "--kind", "fn", "--file", "src"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let arr = parsed.as_array().unwrap();
    assert!(arr.iter().all(|r| r.get("file").is_some()), "directory query should include file column: {stdout}");
}

#[test]
fn symbols_file_single_file_hides_file_column() {
    let dir = dir_project();
    let out = cx_in(dir.path()).args(["--json", "symbols", "--kind", "fn", "--file", "src/lib.rs"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let arr = parsed.as_array().unwrap();
    assert!(arr.iter().all(|r| r.get("file").is_none()), "single-file query should omit file column: {stdout}");
}

#[test]
fn references_file_directory() {
    let dir = dir_project();
    let out = cx_in(dir.path()).args(["references", "--name", "alpha", "--file", "src"]).output().unwrap();
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
}

#[test]
fn kind_counts_file_directory() {
    let dir = dir_project();
    let out = cx_in(dir.path()).args(["symbols", "--kinds", "--file", "src"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    assert!(stdout.contains("fn"), "should list fn kind: {stdout}");
}

#[test]
fn definition_from_directory() {
    let dir = dir_project();
    let out = cx_in(dir.path()).args(["definition", "--name", "alpha", "--from", "src"]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
    assert!(stdout.contains("alpha"), "should find alpha from src/: {stdout}");
}

#[test]
fn symbols_file_nonexistent_directory() {
    let dir = dir_project();
    let out = cx_in(dir.path()).args(["symbols", "--file", "nonexistent"]).output().unwrap();
    assert_eq!(out.status.code(), Some(1));
}

#[test]
fn symbols_file_empty_directory() {
    let dir = dir_project();
    std::fs::create_dir(dir.path().join("empty")).unwrap();
    let out = cx_in(dir.path()).args(["symbols", "--file", "empty"]).output().unwrap();
    assert_eq!(out.status.code(), Some(1));
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("no indexed files under"), "should report empty dir: {stderr}");
}

#[test]
fn overview_directory_from_subdirectory() {
    let dir = dir_project();
    let out = cx_in(&dir.path().join("src")).args(["overview", "."]).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "overview from subdir should work: {}", String::from_utf8_lossy(&out.stderr));
    assert!(stdout.contains("alpha") || stdout.contains("lib.rs"), "should find files in src/: {stdout}");
}