cqs 1.21.0

Code intelligence and RAG for AI agents. Semantic search, call graphs, impact analysis, type dependencies, and smart context assembly — in single tool calls. 54 languages + L5X/L5K PLC exports, 91.2% Recall@1 (BGE-large), 0.951 MRR (296 queries). Local ML, GPU-accelerated.
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
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
//! CLI integration tests for batch mode
//!
//! Tests `cqs batch` — reads commands from stdin, outputs JSONL.
//! Reuses the graph project fixture from cli_graph_test.rs.

use assert_cmd::Command;
use predicates::prelude::*;
use serial_test::serial;
use std::fs;
use tempfile::TempDir;

/// Get a Command for the cqs binary
fn cqs() -> Command {
    #[allow(deprecated)]
    Command::cargo_bin("cqs").expect("Failed to find cqs binary")
}

/// Create a project with call relationships for batch testing.
fn setup_graph_project() -> TempDir {
    let dir = TempDir::new().expect("Failed to create temp dir");
    let src = dir.path().join("src");
    fs::create_dir(&src).expect("Failed to create src dir");

    fs::write(
        src.join("lib.rs"),
        r#"
/// Entry point
pub fn main() {
    let data = process(42);
    println!("{}", data);
}

/// Process input through validation and transformation
pub fn process(input: i32) -> String {
    let valid = validate(input);
    if valid {
        transform(input)
    } else {
        String::from("invalid")
    }
}

/// Check if input is positive
fn validate(input: i32) -> bool {
    input > 0
}

/// Double and format the input
fn transform(input: i32) -> String {
    format!("result: {}", input * 2)
}
"#,
    )
    .expect("Failed to write lib.rs");

    fs::write(
        src.join("tests.rs"),
        r#"
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_process() {
        let result = process(5);
        assert_eq!(result, "result: 10");
    }
}
"#,
    )
    .expect("Failed to write tests.rs");

    dir
}

/// Initialize and index a project.
fn init_and_index(dir: &TempDir) {
    cqs()
        .args(["init"])
        .current_dir(dir.path())
        .assert()
        .success();

    cqs()
        .args(["index"])
        .current_dir(dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("Index complete"));
}

// =============================================================================
// Batch mode integration tests
// =============================================================================

#[test]
#[serial]
fn test_batch_single_command() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callers process\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");
    assert!(parsed.is_array(), "callers should return a JSON array");
}

#[test]
#[serial]
fn test_batch_multiple_commands() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callers process\ncallees main\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.trim().lines().collect();
    assert_eq!(lines.len(), 2, "Should have two JSONL lines");

    // Both lines should be valid JSON
    for line in &lines {
        let parsed: serde_json::Value =
            serde_json::from_str(line).expect("Each line should be valid JSON");
        assert!(parsed.is_array() || parsed.is_object());
    }
}

#[test]
#[serial]
fn test_batch_error_handling() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("unknown_cmd foo\n")
        .output()
        .expect("Failed to run batch");

    assert!(
        output.status.success(),
        "Batch should not crash on bad input"
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");
    assert!(
        parsed.get("error").is_some(),
        "Should have error field: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_batch_comments_and_blanks() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("# comment\n\ncallers process\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.trim().lines().collect();
    assert_eq!(
        lines.len(),
        1,
        "Only the callers command should produce output"
    );
}

#[test]
#[serial]
fn test_batch_quit() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callers process\nquit\ncallers main\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.trim().lines().collect();
    assert_eq!(
        lines.len(),
        1,
        "Should only output the first command (before quit)"
    );
}

#[test]
#[serial]
fn test_batch_stats() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("stats\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");
    assert!(
        parsed.get("total_chunks").is_some(),
        "Stats should have total_chunks: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_batch_explain() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("explain process\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");
    assert!(
        parsed.get("callers").is_some(),
        "Explain should have callers: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("callees").is_some(),
        "Explain should have callees: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_batch_dead() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("dead\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");
    assert!(
        parsed.get("dead").is_some() || parsed.get("total_dead").is_some(),
        "Dead should have dead code fields: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_batch_callees() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callees process\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");
    assert!(
        parsed.get("calls").is_some(),
        "Callees should have calls field: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("count").is_some(),
        "Callees should have count field: {}",
        stdout.trim()
    );
}

// =============================================================================
// Pipeline integration tests
// =============================================================================

#[test]
#[serial]
fn test_pipeline_callers_to_explain() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callers process | explain\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    // Pipeline envelope
    assert_eq!(parsed.get("stages").and_then(|v| v.as_u64()), Some(2));
    assert!(parsed.get("results").is_some(), "Should have results array");
    assert!(
        parsed.get("pipeline").is_some(),
        "Should have pipeline field"
    );
    assert!(
        parsed.get("total_inputs").is_some(),
        "Should have total_inputs"
    );
}

#[test]
#[serial]
fn test_pipeline_three_stages() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callees main | callers | explain\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    assert_eq!(
        parsed.get("stages").and_then(|v| v.as_u64()),
        Some(3),
        "Should be 3-stage pipeline: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_pipeline_empty_upstream() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    // Search for something that doesn't exist → 0 names → empty pipeline result
    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callers xyznonexistent99 | explain\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    // Should get empty results, not an error
    let results = parsed.get("results").and_then(|v| v.as_array());
    assert!(results.is_some(), "Should have results: {}", stdout.trim());
    assert_eq!(
        results.unwrap().len(),
        0,
        "Should have 0 results for nonexistent function"
    );
    assert_eq!(parsed.get("total_inputs").and_then(|v| v.as_u64()), Some(0));
}

#[test]
#[serial]
fn test_pipeline_ineligible_downstream() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callers process | stats\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    let error = parsed.get("error").and_then(|v| v.as_str()).unwrap_or("");
    assert!(
        error.contains("Cannot pipe into 'stats'"),
        "Should reject non-pipeable downstream: {}",
        error
    );
}

#[test]
#[serial]
fn test_pipeline_single_stage_no_pipe() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    // No pipe → should use normal dispatch, NOT pipeline envelope
    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callers process\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    // Should be a bare array (callers output), NOT a pipeline envelope
    assert!(
        parsed.is_array(),
        "Single command should not produce pipeline envelope: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("pipeline").is_none(),
        "Should not have pipeline field"
    );
}

#[test]
#[serial]
fn test_pipeline_quoted_pipe_in_query() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    // Pipe inside quotes should NOT be treated as a pipeline separator.
    // shell_words tokenizes "foo | bar" as a single token, so no standalone `|`.
    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("search \"foo | bar\"\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    // Should be a normal search result (with results key), not a pipeline
    assert!(
        parsed.get("results").is_some() || parsed.get("error").is_some(),
        "Should be normal search output: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("pipeline").is_none(),
        "Quoted pipe should not trigger pipeline"
    );
}

#[test]
#[serial]
fn test_pipeline_mixed_with_single() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    // Mix of pipeline and single commands in one batch session
    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("callers process | explain\nstats\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.trim().lines().collect();
    assert_eq!(lines.len(), 2, "Should have two JSONL lines");

    // First line: pipeline result
    let line1: serde_json::Value =
        serde_json::from_str(lines[0]).expect("First line should be valid JSON");
    assert!(
        line1.get("pipeline").is_some(),
        "First line should be pipeline envelope"
    );

    // Second line: stats (single command)
    let line2: serde_json::Value =
        serde_json::from_str(lines[1]).expect("Second line should be valid JSON");
    assert!(
        line2.get("total_chunks").is_some(),
        "Second line should be stats output"
    );
}

// =============================================================================
// HP-4: High-value batch command integration tests
// =============================================================================

#[test]
#[serial]
fn test_batch_impact() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("impact process\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    assert_eq!(
        parsed.get("name").and_then(|v| v.as_str()),
        Some("process"),
        "Impact should report the target function: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("callers").is_some(),
        "Impact should have callers field: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("tests").is_some(),
        "Impact should have tests field: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("caller_count").is_some(),
        "Impact should have caller_count: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("test_count").is_some(),
        "Impact should have test_count: {}",
        stdout.trim()
    );

    // `process` is called by `main` -> at least 1 caller
    let caller_count = parsed
        .get("caller_count")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    assert!(
        caller_count >= 1,
        "process should have at least 1 caller (main), got {}",
        caller_count
    );
}

#[test]
#[serial]
fn test_batch_impact_with_suggest_tests() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("impact process --suggest-tests\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    assert!(
        parsed.get("test_suggestions").is_some(),
        "Impact with --suggest-tests should have test_suggestions: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_batch_trace_connected() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    // main calls process, process calls validate -- trace should find a path
    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("trace main validate\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    assert_eq!(
        parsed.get("source").and_then(|v| v.as_str()),
        Some("main"),
        "Trace should report source: {}",
        stdout.trim()
    );
    assert_eq!(
        parsed.get("target").and_then(|v| v.as_str()),
        Some("validate"),
        "Trace should report target: {}",
        stdout.trim()
    );
    assert_eq!(
        parsed.get("found").and_then(|v| v.as_bool()),
        Some(true),
        "Trace should find a path from main to validate: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("path").is_some(),
        "Trace should have path field when found: {}",
        stdout.trim()
    );

    // Path should have at least 2 hops (main -> process -> validate)
    let path = parsed.get("path").and_then(|v| v.as_array());
    assert!(
        path.is_some_and(|p| p.len() >= 2),
        "Trace path should have >= 2 hops: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_batch_trace_disconnected() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    // validate does not call main -- trace should fail to find a path
    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("trace validate main\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    assert_eq!(
        parsed.get("found").and_then(|v| v.as_bool()),
        Some(false),
        "Trace should not find a path from validate to main: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_batch_similar() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("similar process\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    assert_eq!(
        parsed.get("target").and_then(|v| v.as_str()),
        Some("process"),
        "Similar should report the target function: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("results").is_some(),
        "Similar should have results array: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("total").is_some(),
        "Similar should have total field: {}",
        stdout.trim()
    );

    // With 4 functions in the fixture, there should be at least 1 similar result
    let results = parsed.get("results").and_then(|v| v.as_array());
    assert!(
        results.is_some_and(|r| !r.is_empty()),
        "Similar should find at least one result for process: {}",
        stdout.trim()
    );

    // Each result should have name, file, score
    let first = results.unwrap().first().unwrap();
    assert!(first.get("name").is_some(), "Result should have name field");
    assert!(first.get("file").is_some(), "Result should have file field");
    assert!(
        first.get("score").is_some(),
        "Result should have score field"
    );
}

#[test]
#[serial]
fn test_batch_stale() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("stale\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    assert!(
        parsed.get("stale").is_some(),
        "Stale should have stale array: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("missing").is_some(),
        "Stale should have missing array: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("stale_count").is_some(),
        "Stale should have stale_count: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("missing_count").is_some(),
        "Stale should have missing_count: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("total_indexed").is_some(),
        "Stale should have total_indexed: {}",
        stdout.trim()
    );

    // Freshly indexed project should have 0 stale and 0 missing
    assert_eq!(
        parsed.get("stale_count").and_then(|v| v.as_u64()),
        Some(0),
        "Fresh index should have 0 stale files"
    );
    assert_eq!(
        parsed.get("missing_count").and_then(|v| v.as_u64()),
        Some(0),
        "Fresh index should have 0 missing files"
    );
    // Should have indexed at least our 2 files
    let total = parsed
        .get("total_indexed")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    assert!(
        total >= 2,
        "Should have indexed at least 2 files, got {}",
        total
    );
}

#[test]
#[serial]
fn test_batch_health() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("health\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    assert!(
        parsed.get("stats").is_some(),
        "Health should have stats object: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("stale_count").is_some(),
        "Health should have stale_count: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("missing_count").is_some(),
        "Health should have missing_count: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("dead_confident").is_some(),
        "Health should have dead_confident: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("dead_possible").is_some(),
        "Health should have dead_possible: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("hotspots").is_some(),
        "Health should have hotspots: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("note_count").is_some(),
        "Health should have note_count: {}",
        stdout.trim()
    );

    // Stats sub-object should have chunk/file counts
    let stats = parsed.get("stats").unwrap();
    assert!(
        stats.get("total_chunks").is_some(),
        "Stats should have total_chunks: {}",
        stdout.trim()
    );
    assert!(
        stats.get("total_files").is_some(),
        "Stats should have total_files: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_batch_gather() {
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("gather \"process input\"\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("Should be valid JSON");

    assert!(
        parsed.get("query").is_some(),
        "Gather should have query field: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("chunks").is_some(),
        "Gather should have chunks array: {}",
        stdout.trim()
    );

    // Gather should find at least one chunk for "process input"
    let chunks = parsed.get("chunks").and_then(|v| v.as_array());
    assert!(
        chunks.is_some_and(|c| !c.is_empty()),
        "Gather should find at least one chunk for 'process input': {}",
        stdout.trim()
    );

    // The expansion_capped and search_degraded fields should be present
    assert!(
        parsed.get("expansion_capped").is_some(),
        "Gather should have expansion_capped: {}",
        stdout.trim()
    );
    assert!(
        parsed.get("search_degraded").is_some(),
        "Gather should have search_degraded: {}",
        stdout.trim()
    );
}

#[test]
#[serial]
fn test_batch_multiple_hp4_commands() {
    // Verify multiple HP-4 commands work in a single batch session
    let dir = setup_graph_project();
    init_and_index(&dir);

    let output = cqs()
        .args(["batch"])
        .current_dir(dir.path())
        .write_stdin("impact process\nstale\nhealth\n")
        .output()
        .expect("Failed to run batch");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.trim().lines().collect();
    assert_eq!(lines.len(), 3, "Should have three JSONL lines");

    // Line 1: impact
    let l1: serde_json::Value =
        serde_json::from_str(lines[0]).expect("Impact line should be valid JSON");
    assert!(
        l1.get("name").is_some() && l1.get("callers").is_some(),
        "Line 1 should be impact output"
    );

    // Line 2: stale
    let l2: serde_json::Value =
        serde_json::from_str(lines[1]).expect("Stale line should be valid JSON");
    assert!(
        l2.get("stale_count").is_some(),
        "Line 2 should be stale output"
    );

    // Line 3: health
    let l3: serde_json::Value =
        serde_json::from_str(lines[2]).expect("Health line should be valid JSON");
    assert!(l3.get("stats").is_some(), "Line 3 should be health output");
}