reference-query 0.35.2

Reference Query — find the code you're looking for.
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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
//! End-to-end: drive the real `rq` binary through index → search → learn.
//!
//! Hermetic and reproducible — no shell `cd`, no git required. Each run uses an
//! isolated `RQ_DB`, a fresh temp repo, and sets the subprocess working
//! directory, so the shell's cwd is irrelevant.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Unique temp paths for this test (repo dir + db file), cleaned first.
fn scratch(label: &str) -> (PathBuf, PathBuf) {
    let base = std::env::temp_dir();
    let dir = base.join(format!("rq-e2e-{}-{label}", std::process::id()));
    let db = base.join(format!("rq-e2e-{}-{label}.db", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    for suffix in ["", "-wal", "-shm"] {
        let _ = fs::remove_file(format!("{}{suffix}", db.display()));
    }
    fs::create_dir_all(&dir).unwrap();
    (dir, db)
}

/// Run the built binary with an isolated db and a set working directory.
/// Detached warming is off so each invocation is hermetic (no child process
/// racing the test's asserts/cleanup); the detach path has its own test.
fn rq(db: &Path, cwd: &Path, args: &[&str]) -> (bool, String) {
    let out = Command::new(env!("CARGO_BIN_EXE_rq"))
        .args(args)
        .current_dir(cwd)
        .env("RQ_DB", db)
        .env("RQ_WARM_DETACH", "0")
        .output()
        .expect("run rq");
    (
        out.status.success(),
        String::from_utf8_lossy(&out.stdout).into_owned(),
    )
}

fn first_line(s: &str) -> &str {
    s.lines().next().unwrap_or("")
}

/// Run a `-v` search and report whether it spawned a background warm (traced to
/// stderr). Lets tests assert on the warm decision without timing flakiness.
fn warmed(db: &Path, cwd: &Path, query: &str) -> bool {
    let run = Command::new(env!("CARGO_BIN_EXE_rq"))
        .args(["-v", query, "--no-record"])
        .current_dir(cwd)
        .env("RQ_DB", db)
        .output()
        .expect("run rq");
    String::from_utf8_lossy(&run.stderr).contains("background warm")
}

/// `git init` a directory (no commits needed) so it reads as a git repo.
fn git_init(dir: &Path) {
    let _ = Command::new("git")
        .arg("init")
        .arg("-q")
        .current_dir(dir)
        .output();
}

/// `git init` + commit everything, so files are *tracked* (warming enumerates a
/// committed repo from `git ls-files`, not a filesystem walk).
fn git_init_commit(dir: &Path) {
    git_init(dir);
    let git = |args: &[&str]| {
        let _ = Command::new("git").args(args).current_dir(dir).output();
    };
    git(&["add", "-A"]);
    git(&[
        "-c",
        "user.email=t@e.st",
        "-c",
        "user.name=test",
        "commit",
        "-qm",
        "init",
    ]);
}

#[test]
fn index_search_and_learn_through_the_cli() {
    let (dir, db) = scratch("learn");
    fs::write(dir.join("alpha.rb"), "class HandlerA\nend\n").unwrap();
    fs::write(dir.join("beta.rb"), "class HandlerB\nend\n").unwrap();

    // index the working directory
    let (ok, out) = rq(&db, &dir, &["--index"]);
    assert!(ok, "index failed: {out}");
    assert!(out.contains("symbol"), "index output: {out}");

    // search — the tie breaks alphabetically, so HandlerA leads
    let (ok, out) = rq(&db, &dir, &["handler"]);
    assert!(ok, "search failed: {out}");
    assert!(
        first_line(&out).contains("HandlerA"),
        "search output: {out}"
    );

    // record that the user opened HandlerB for "handler"
    let (ok, _) = rq(
        &db,
        &dir,
        &["--record", "--file", "beta.rb", "--line", "1", "handler"],
    );
    assert!(ok, "record failed");

    // now HandlerB leads
    let (ok, out) = rq(&db, &dir, &["handler"]);
    assert!(ok, "second search failed: {out}");
    assert!(
        first_line(&out).contains("HandlerB"),
        "after learning, expected HandlerB first: {out}"
    );

    // status shows the repo
    let (ok, out) = rq(&db, &dir, &["--status"]);
    assert!(ok, "status failed: {out}");
    assert!(out.contains("local:"), "status output: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn a_strong_match_suppresses_the_scattered_tail() {
    // when the query lands an exact/prefix name match, fuzzy near-matches are
    // dropped — `employeescontroller` keeps EmployeesController, not the scattered
    // EmployeeStatusController (employee + s + …controller, skipping "tatus").
    let (dir, db) = scratch("gate");
    fs::write(
        dir.join("employees_controller.rb"),
        "class EmployeesController\nend\n",
    )
    .unwrap();
    fs::write(
        dir.join("employee_status_controller.rb"),
        "class EmployeeStatusController\nend\n",
    )
    .unwrap();
    rq(&db, &dir, &["--index"]);

    let (_, out) = rq(
        &db,
        &dir,
        &["employeescontroller", "--no-record", "--ndjson"],
    );
    assert!(out.contains("EmployeesController"), "exact kept: {out}");
    assert!(
        !out.contains("EmployeeStatusController"),
        "scattered fuzzy dropped: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn a_wildcard_bridges_an_explicit_gap() {
    // `*` reaches across words the fuzzy matcher deliberately won't skip:
    // `widget*controller` finds WidgetAlphaBravoController, where the plain
    // `widgetcontroller` query is rejected (it would have to skip whole words).
    // An unrelated file stays out.
    let (dir, db) = scratch("wildcard");
    fs::write(
        dir.join("widget_alpha_bravo_controller.rb"),
        "class WidgetAlphaBravoController\nend\n",
    )
    .unwrap();
    fs::write(dir.join("gadget_service.rb"), "class GadgetService\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    let (ok, out) = rq(&db, &dir, &["widget*controller", "--no-record", "--ndjson"]);
    assert!(ok, "wildcard search should match: {out}");
    assert!(
        out.contains("WidgetAlphaBravoController"),
        "star bridges the gap: {out}"
    );
    assert!(!out.contains("GadgetService"), "non-match excluded: {out}");

    // the same query without the star is too scattered for the fuzzy matcher
    let (matched, _) = rq(&db, &dir, &["widgetcontroller", "--no-record"]);
    assert!(!matched, "plain fuzzy won't skip whole words");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn cold_index_builds_a_working_fuzzy_index() {
    // a cold `--index` defers per-row FTS and rebuilds the trigram index in bulk;
    // a mid-word substring (not a prefix of the name) only resolves through that
    // FTS recall, so this proves the bulk rebuild produced a usable index
    let (dir, db) = scratch("coldfts");
    fs::write(dir.join("a.rb"), "class AlphaWidgetController\nend\n").unwrap();
    let (ok, out) = rq(&db, &dir, &["--index"]);
    assert!(ok, "index failed: {out}");

    // "widget" is mid-word in AlphaWidgetController — exact/prefix can't reach it
    let (ok, out) = rq(&db, &dir, &["widget", "--no-record"]);
    assert!(ok, "fuzzy recall should find it: {out}");
    assert!(out.contains("AlphaWidgetController"), "fts recall: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn a_compact_namespaced_class_is_found_by_its_leaf_name() {
    // `class A::B::EmployeesController` must be found by `employeescontroller`
    // (its leaf), and must survive next to a top-level EmployeesController — the
    // relevance gate shouldn't prune a legitimate exact-leaf match
    let (dir, db) = scratch("namespaced");
    fs::write(
        dir.join("a.rb"),
        "class My::Module::EmployeesController\n  def index; end\nend\n",
    )
    .unwrap();
    fs::write(
        dir.join("b.rb"),
        "class EmployeesController\n  def show; end\nend\n",
    )
    .unwrap();
    rq(&db, &dir, &["--index"]);

    let (ok, out) = rq(
        &db,
        &dir,
        &["employeescontroller", "--no-record", "--ndjson"],
    );
    assert!(ok, "search failed: {out}");
    // both files surface — the namespaced one isn't pruned
    assert!(out.contains("a.rb"), "namespaced class kept: {out}");
    assert!(out.contains("b.rb"), "top-level class kept: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn a_qualified_query_resolves_to_the_method_in_the_named_scope() {
    // `Foo::Bar#baz` must find the `baz` defined inside `Foo::Bar` and, since a
    // scope match exists, suppress the same-named `baz` in another scope.
    let (dir, db) = scratch("qualified");
    fs::write(
        dir.join("a.rb"),
        "module Foo\n  class Bar\n    def baz; end\n  end\nend\n",
    )
    .unwrap();
    fs::write(
        dir.join("b.rb"),
        "module Other\n  class Bar\n    def baz; end\n  end\nend\n",
    )
    .unwrap();
    rq(&db, &dir, &["--index"]);

    let (ok, out) = rq(&db, &dir, &["Foo::Bar#baz", "--no-record", "--ndjson"]);
    assert!(ok, "search failed: {out}");
    assert!(out.contains("a.rb"), "in-scope baz surfaces: {out}");
    assert!(
        !out.contains("b.rb"),
        "out-of-scope baz is gated out: {out}"
    );

    // fallback: no `baz` lives in `Nope::Bar`, so both still surface rather than
    // returning nothing — the scope was a hint, not a hard filter
    let (ok, out) = rq(&db, &dir, &["Nope::Bar#baz", "--no-record", "--ndjson"]);
    assert!(ok, "fallback search failed: {out}");
    assert!(
        out.contains("a.rb") && out.contains("b.rb"),
        "no scope match falls back to all candidates: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn json_results_carry_the_definition_span() {
    // a result reports line..=end_line so a caller can read the exact span
    let (dir, db) = scratch("endline");
    fs::write(
        dir.join("a.rb"),
        "class Widget\n  def go\n    1\n  end\nend\n",
    )
    .unwrap();
    rq(&db, &dir, &["--index"]);

    let (ok, out) = rq(&db, &dir, &["Widget", "-l", "1", "--ndjson"]);
    assert!(ok, "search failed: {out}");
    // class Widget spans line 1 through its `end` on line 5
    assert!(out.contains("\"line\":1"), "start line present: {out}");
    assert!(out.contains("\"end_line\":5"), "end line present: {out}");
    // absent optionals are omitted, not null — same shape as --symbols
    assert!(
        !out.contains("\"parent\":null"),
        "no null fields in hit JSON: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn show_prints_the_body_when_confident_and_lists_when_not() {
    let (dir, db) = scratch("show");
    fs::write(
        dir.join("a.rb"),
        "class Widget\n  def go\n    42\n  end\nend\n",
    )
    .unwrap();
    // two same-named classes so a bare fuzzy query is ambiguous
    fs::write(dir.join("b.rb"), "class Thing\nend\nclass Thang\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    // confident (exact, dominant): --show prints the full source span as `body`
    let (ok, out) = rq(&db, &dir, &["--show", "Widget", "-j", "--no-record"]);
    assert!(ok, "show failed: {out}");
    assert!(
        out.contains("\"body\""),
        "confident show carries body: {out}"
    );
    assert!(
        out.contains("def go"),
        "body has the definition source: {out}"
    );
    assert!(!out.contains("\"score\""), "score dropped from JSON: {out}");
    assert!(out.contains("\"confidence\""), "confidence present: {out}");

    // ambiguous (two fuzzy `Th*` matches): no body, falls back to the list
    let (_ok, out) = rq(&db, &dir, &["--show", "Th", "-j", "--no-record"]);
    assert!(
        !out.contains("\"body\""),
        "ambiguous show prints no body: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn a_leading_kind_keyword_filters_like_dash_k() {
    // `rq class Widget` and `rq method go` scope by kind without needing -k, and
    // without quoting. A same-named symbol of another kind is filtered out.
    let (dir, db) = scratch("kindkw");
    fs::write(
        dir.join("a.rb"),
        "class Widget\n  def go; end\nend\nmodule Widget\nend\n",
    )
    .unwrap();
    rq(&db, &dir, &["--index"]);

    // unquoted keyword restricts to the class, dropping the module of the same name
    let (ok, out) = rq(&db, &dir, &["class", "Widget", "--no-record", "--ndjson"]);
    assert!(ok, "keyword search failed: {out}");
    assert!(out.contains("\"kind\":\"class\""), "class kept: {out}");
    assert!(
        !out.contains("\"kind\":\"module\""),
        "module filtered: {out}"
    );

    // the method keyword finds the def; equivalent to -k method
    let (ok, out) = rq(&db, &dir, &["method", "go", "--no-record", "--ndjson"]);
    assert!(ok, "method keyword failed: {out}");
    assert!(out.contains("\"kind\":\"method\""), "method found: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn a_search_does_not_leak_another_indexed_repo() {
    // two repos in one index; a query from inside repo A must never surface repo
    // B's definitions — the reported leak. `--all-repos` opts back into both.
    let (dir_a, db) = scratch("repo-a");
    let dir_b = dir_a.with_file_name(format!("rq-e2e-{}-repo-b", std::process::id()));
    let _ = fs::remove_dir_all(&dir_b);
    fs::create_dir_all(&dir_b).unwrap();
    fs::write(dir_a.join("a.rb"), "class Alpha\nend\n").unwrap();
    fs::write(dir_b.join("b.rb"), "class Gadget\nend\n").unwrap();
    rq(&db, &dir_a, &["--index"]);
    rq(&db, &dir_b, &["--index"]);

    // Gadget lives only in repo B; from repo A it's a definitive miss, not B's hit
    let (ok, out) = rq(&db, &dir_a, &["Gadget", "--no-record", "--ndjson"]);
    assert!(!ok, "no Gadget in repo A — should miss");
    assert!(!out.contains("b.rb"), "must not leak repo B: {out}");
    assert!(
        out.contains("\"status\":\"no_match\""),
        "reports no_match: {out}"
    );

    // --all-repos opts into the cross-repo search and finds it
    let (ok, out) = rq(
        &db,
        &dir_a,
        &["Gadget", "--all-repos", "--no-record", "--ndjson"],
    );
    assert!(ok, "--all-repos should find Gadget in repo B: {out}");
    assert!(out.contains("b.rb"), "cross-repo hit surfaces: {out}");

    let _ = fs::remove_dir_all(&dir_a);
    let _ = fs::remove_dir_all(&dir_b);
}

#[test]
fn a_clean_complete_repo_does_not_re_warm_on_search() {
    // a fully-indexed, clean git repo is provably unchanged (HEAD matches, no
    // dirty files), so a search must skip the background warm entirely rather
    // than re-walk the whole tree per query — at any size
    let (dir, db) = scratch("nowarm");
    fs::write(dir.join("a.rb"), "class Widget\nend\n").unwrap();
    git_init_commit(&dir);
    rq(&db, &dir, &["--index"]);

    assert!(
        !warmed(&db, &dir, "widget"),
        "clean complete repo should not re-warm"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn a_tracked_edit_warms_but_a_new_untracked_file_does_not() {
    // the dirty check skips the untracked-file scan for speed: a tracked edit
    // still triggers a warm (so the change is picked up), but a brand-new
    // untracked file is the accepted tradeoff — not seen until committed/indexed
    let (dir, db) = scratch("dirty-check");
    fs::write(dir.join("a.rb"), "class Widget\nend\n").unwrap();
    git_init_commit(&dir);
    rq(&db, &dir, &["--index"]);

    fs::write(dir.join("a.rb"), "class Widget\n  def go; end\nend\n").unwrap();
    assert!(warmed(&db, &dir, "widget"), "tracked edit triggers a warm");

    // restore the tracked file to its committed content (tree clean again), then
    // add an untracked file — which the cheaper check intentionally ignores
    fs::write(dir.join("a.rb"), "class Widget\nend\n").unwrap();
    fs::write(dir.join("b.rb"), "class Gadget\nend\n").unwrap();
    assert!(
        !warmed(&db, &dir, "widget"),
        "a new untracked file does not trigger a warm (accepted tradeoff)"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn indexing_a_subdir_scopes_to_it_but_keeps_root_relative_paths() {
    // `rq --index <subdir>` seeds only that subtree in this run, yet stores
    // paths relative to the repo root so a later search still resolves them
    let (dir, db) = scratch("index-subdir");
    fs::create_dir_all(dir.join("sub")).unwrap();
    fs::create_dir_all(dir.join("other")).unwrap();
    fs::write(dir.join("sub/a.rb"), "class InScope\nend\n").unwrap();
    fs::write(dir.join("other/b.rb"), "class OutOfScope\nend\n").unwrap();
    git_init_commit(&dir);

    let (ok, out) = rq(&db, &dir, &["--index", "sub"]);
    assert!(ok, "scoped index failed: {out}");
    assert!(out.contains("subtree"), "subdir index is a seed: {out}");
    assert!(
        out.contains("1 files"),
        "this run indexed exactly the one in-scope file: {out}"
    );

    // the seeded class is found, at a repo-root-relative path
    let (ok, out) = rq(&db, &dir, &["inscope", "--no-record", "--ndjson"]);
    assert!(ok, "search failed: {out}");
    assert!(out.contains("InScope"), "in-scope class indexed: {out}");
    assert!(
        out.contains("\"file\":\"sub/a.rb\""),
        "path is root-relative, not subdir-relative: {out}"
    );

    // the seed is not a fence: searching warms the rest of the repo, so the
    // out-of-scope class is found — and persisted
    let (found, out) = rq(&db, &dir, &["outofscope", "--no-record", "--ndjson"]);
    assert!(found, "warming finds the out-of-scope class: {out}");
    assert!(out.contains("\"file\":\"other/b.rb\""), "warm hit: {out}");
    let (_, status) = rq(&db, &dir, &["--status", "--ndjson"]);
    assert!(
        status.contains("\"files\":2"),
        "warming persisted the rest of the repo: {status}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn empty_status_points_at_the_real_index_flag() {
    // the hint must name the actual flag (`rq --index`), not a non-existent
    // `rq index` subcommand
    let (dir, db) = scratch("empty-status");
    let (ok, out) = rq(&db, &dir, &["--status"]);
    assert!(ok, "status on an empty db should succeed: {out}");
    assert!(out.contains("rq --index"), "hint names the flag: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn open_launches_and_records_the_pick() {
    // `rq --open` picks the top hit, records it as a selection (so ranking
    // learns), and execs the launcher. RQ_OPEN drives a harmless command here.
    let (dir, db) = scratch("open");
    fs::write(dir.join("user.rb"), "class User\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    // RQ_OPEN runs `true` — exits 0, no editor needed; non-TTY takes the top hit
    let run = Command::new(env!("CARGO_BIN_EXE_rq"))
        .args(["--open", "user"])
        .current_dir(&dir)
        .env("RQ_DB", &db)
        .env("RQ_OPEN", "true")
        .output()
        .expect("run rq");
    assert!(run.status.success(), "open should exit 0 via the launcher");

    // with no launcher and no editor, --open prints the resolved path:line
    let run = Command::new(env!("CARGO_BIN_EXE_rq"))
        .args(["--open", "user", "--no-record"])
        .current_dir(&dir)
        .env("RQ_DB", &db)
        .env_remove("EDITOR")
        .env_remove("VISUAL")
        .env("PATH", "/nonexistent") // hide any `code` on PATH
        .output()
        .expect("run rq");
    let printed = String::from_utf8_lossy(&run.stdout);
    assert!(
        printed.trim().ends_with("user.rb:1"),
        "prints resolved path:line: {printed}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn drop_honors_json_output() {
    // --drop --json/-J report what was removed, so a script can act on it
    let (dir, db) = scratch("drop-json");
    fs::write(dir.join("a.rb"), "class Widget\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    let (ok, out) = rq(&db, &dir, &["--drop", "--json"]);
    assert!(ok, "drop --json failed: {out}");
    assert!(out.trim_start().starts_with('{'), "json object: {out}");
    assert!(out.contains("\"dropped\": true"), "reports dropped: {out}");

    // already gone → compact ndjson, dropped:false, still exit 0 (idempotent)
    let (ok, out) = rq(&db, &dir, &["--drop", "--ndjson"]);
    assert!(ok, "second drop should not error: {out}");
    let line = out.lines().next().unwrap_or("");
    assert!(
        line.starts_with('{') && line.contains("\"dropped\":false"),
        "ndjson dropped:false: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn drop_removes_a_repos_index() {
    // --drop is the inverse of --index: the repo disappears from coverage, and
    // dropping again is idempotent (a clear message, no error)
    let (dir, db) = scratch("drop");
    fs::write(dir.join("a.rb"), "class Widget\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    let (_, before) = rq(&db, &dir, &["--status"]);
    assert!(before.contains("symbol"), "indexed before drop: {before}");

    let (ok, out) = rq(&db, &dir, &["--drop"]);
    assert!(ok, "drop failed: {out}");
    assert!(out.contains("dropped"), "drop confirms: {out}");

    let (ok2, after) = rq(&db, &dir, &["--status"]);
    assert!(ok2, "status after drop: {after}");
    assert!(
        !after.contains("symbol"),
        "coverage gone after drop: {after}"
    );

    // idempotent: nothing left to drop, but not an error
    let (ok3, again) = rq(&db, &dir, &["--drop"]);
    assert!(ok3, "second drop should not error: {again}");
    assert!(again.contains("not indexed"), "idempotent message: {again}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn record_is_a_searchable_word_not_a_subcommand() {
    let (dir, db) = scratch("disambig");
    fs::write(dir.join("a.rb"), "class Widget\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    // `rq record` searches for the symbol "record" (no hook, no match here)
    let (ok, out) = rq(&db, &dir, &["record"]);
    assert!(!ok, "no-match search should exit non-zero");
    assert!(out.is_empty(), "expected no result lines, got: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn status_and_index_honor_json_output() {
    let (dir, db) = scratch("ops-json");
    fs::write(dir.join("a.rb"), "class Widget\nend\n").unwrap();

    // --index --json: a single object with this-run and total counts
    let (ok, out) = rq(&db, &dir, &["--index", "--json"]);
    assert!(ok, "index --json failed: {out}");
    assert!(
        out.trim_start().starts_with('{'),
        "index json object: {out}"
    );
    assert!(out.contains("\"files_added\""), "index run counts: {out}");
    assert!(out.contains("\"repo\""), "index repo field: {out}");

    // --status --json: an array of coverage rows
    let (ok, out) = rq(&db, &dir, &["--status", "--json"]);
    assert!(ok, "status --json failed: {out}");
    assert!(
        out.trim_start().starts_with('['),
        "status json array: {out}"
    );
    assert!(
        out.contains("\"status\": \"complete\""),
        "status field: {out}"
    );

    // --status -J: one compact object per line
    let (ok, out) = rq(&db, &dir, &["--status", "--ndjson"]);
    assert!(ok, "status -J failed: {out}");
    let line = out.lines().next().unwrap_or("");
    assert!(
        line.starts_with('{') && line.ends_with('}') && line.contains("\"repo\""),
        "ndjson object per line: {out}"
    );

    // with nothing indexed, --status --json is still well-formed (an empty array)
    rq(&db, &dir, &["--drop"]);
    let (ok, out) = rq(&db, &dir, &["--status", "--json"]);
    assert!(ok && out.trim() == "[]", "empty status json is []: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn json_and_ndjson_output() {
    let (dir, db) = scratch("json");
    fs::write(dir.join("alpha.rb"), "class HandlerA\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    // --json: a pretty array with named fields
    let (ok, out) = rq(&db, &dir, &["handler", "--json"]);
    assert!(ok, "json search failed: {out}");
    assert!(
        out.trim_start().starts_with('['),
        "expected a JSON array: {out}"
    );
    assert!(out.contains("\"name\": \"HandlerA\""), "name field: {out}");
    assert!(out.contains("\"file\": \"alpha.rb\""), "file field: {out}");
    assert!(out.contains("\"repo\":"), "repo field: {out}");
    assert!(
        out.contains("\"signature\": \"class HandlerA\""),
        "signature: {out}"
    );

    // --ndjson: one compact object per line
    let (ok, out) = rq(&db, &dir, &["handler", "--ndjson"]);
    assert!(ok, "ndjson search failed: {out}");
    let first = out.lines().next().unwrap_or("");
    assert!(
        first.starts_with('{') && first.ends_with('}'),
        "object per line: {out}"
    );
    assert!(
        first.contains("\"name\":\"HandlerA\""),
        "compact name: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn path_filter_restricts_results() {
    let (dir, db) = scratch("path");
    fs::create_dir_all(dir.join("app/services")).unwrap();
    fs::create_dir_all(dir.join("app/models")).unwrap();
    fs::write(
        dir.join("app/services/widget.rb"),
        "class WidgetService\nend\n",
    )
    .unwrap();
    fs::write(dir.join("app/models/widget.rb"), "class Widget\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    // unfiltered: both files match "widget"
    let (_, out) = rq(&db, &dir, &["widget", "--ndjson"]);
    assert!(
        out.contains("app/models/widget.rb"),
        "expected models hit: {out}"
    );
    assert!(
        out.contains("app/services/widget.rb"),
        "expected services hit: {out}"
    );

    // --path app/services: only the services result survives
    let (ok, out) = rq(&db, &dir, &["widget", "--path", "app/services", "--ndjson"]);
    assert!(ok, "path search failed: {out}");
    assert!(
        out.contains("app/services/widget.rb"),
        "services hit kept: {out}"
    );
    assert!(
        !out.contains("app/models/widget.rb"),
        "models hit filtered out: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn path_filter_accepts_absolute_and_relative_paths() {
    let (dir, db) = scratch("path-abs");
    fs::create_dir_all(dir.join("app/services")).unwrap();
    fs::create_dir_all(dir.join("app/models")).unwrap();
    fs::write(
        dir.join("app/services/widget.rb"),
        "class WidgetService\nend\n",
    )
    .unwrap();
    fs::write(dir.join("app/models/widget.rb"), "class Widget\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    // absolute, ./-relative, and bare repo-relative all normalize to the same
    // filter and keep only the services hit.
    let abs = dir.join("app/services");
    let abs = abs.to_str().unwrap();
    for spec in [abs, "./app/services", "app/services"] {
        let (ok, out) = rq(&db, &dir, &["widget", "--path", spec, "--ndjson"]);
        assert!(ok, "path search failed for {spec:?}: {out}");
        assert!(
            out.contains("app/services/widget.rb"),
            "services kept for {spec:?}: {out}"
        );
        assert!(
            !out.contains("app/models/widget.rb"),
            "models filtered for {spec:?}: {out}"
        );
    }

    // a path outside the repo normalizes to nothing, not everything
    let (_, out) = rq(
        &db,
        &dir,
        &["widget", "--path", "/nonexistent/elsewhere", "--ndjson"],
    );
    assert!(
        !out.contains("\"file\":"),
        "outside path yields no hits: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn limit_caps_the_number_of_results() {
    let (dir, db) = scratch("limit");
    fs::write(dir.join("a.rb"), "class HandlerA\nend\n").unwrap();
    fs::write(dir.join("b.rb"), "class HandlerB\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    let (ok, out) = rq(&db, &dir, &["handler", "--limit", "1", "--ndjson"]);
    assert!(ok, "limited search failed: {out}");
    assert_eq!(out.lines().count(), 1, "expected exactly one result: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn index_a_subset_of_a_repo() {
    let (dir, db) = scratch("subset");
    fs::create_dir_all(dir.join("app/services")).unwrap();
    fs::create_dir_all(dir.join("app/models")).unwrap();
    fs::write(dir.join("app/services/charge.rb"), "class Charge\nend\n").unwrap();
    fs::write(dir.join("app/models/account.rb"), "class Account\nend\n").unwrap();
    // a git repo, so a search won't live-scan the whole tree (defeating the point)
    git_init(&dir);

    // seed only the services subtree: this run indexes just that, and
    // coverage stays warming (a seed, not a fence)
    let (ok, out) = rq(&db, &dir, &["--index", "--path", "app/services", "-J"]);
    assert!(ok, "subset index failed: {out}");
    assert!(out.contains("\"scope\":\"subtree\""), "seed marker: {out}");
    assert!(out.contains("\"files\":1"), "seeded one file: {out}");
    let (_, status) = rq(&db, &dir, &["--status", "--ndjson"]);
    assert!(
        status.contains("\"status\":\"warming\""),
        "a seed leaves coverage warming: {status}"
    );

    // the seeded subtree is searchable, with a repo-relative path
    let (ok, out) = rq(&db, &dir, &["charge", "--ndjson"]);
    assert!(ok, "charge search failed: {out}");
    assert!(
        out.contains("\"file\":\"app/services/charge.rb\""),
        "subset hit: {out}"
    );

    // a symbol outside the seed: warming continues over the rest of the repo,
    // finds it, and persists it
    let (ok, out) = rq(&db, &dir, &["account", "--ndjson"]);
    assert!(ok, "warming finds the unseeded symbol: {out}");
    assert!(
        out.contains("\"file\":\"app/models/account.rb\""),
        "warm hit: {out}"
    );
    let (_, status) = rq(&db, &dir, &["--status", "--ndjson"]);
    assert!(
        status.contains("\"files\":2"),
        "warming persisted the rest: {status}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn positional_paths_filter_like_rg() {
    let (dir, db) = scratch("pospath");
    fs::create_dir_all(dir.join("app/services")).unwrap();
    fs::create_dir_all(dir.join("app/models")).unwrap();
    fs::write(
        dir.join("app/services/widget.rb"),
        "class WidgetService\nend\n",
    )
    .unwrap();
    fs::write(dir.join("app/models/widget.rb"), "class Widget\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    // path given positionally after the query, rg-style
    let (ok, out) = rq(&db, &dir, &["widget", "app/services", "--ndjson"]);
    assert!(ok, "positional-path search failed: {out}");
    assert!(
        out.contains("app/services/widget.rb"),
        "services hit kept: {out}"
    );
    assert!(
        !out.contains("app/models/widget.rb"),
        "models hit filtered out: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn no_record_still_returns_results() {
    let (dir, db) = scratch("norec");
    fs::write(dir.join("a.rb"), "class Widget\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    let (ok, out) = rq(&db, &dir, &["widget", "--no-record", "--ndjson"]);
    assert!(ok, "no-record search failed: {out}");
    assert!(out.contains("\"name\":\"Widget\""), "result present: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn kind_filter_scopes_by_symbol_kind() {
    let (dir, db) = scratch("kind");
    fs::write(dir.join("a.rb"), "class Charge\n  def charge\n  end\nend\n").unwrap();
    rq(&db, &dir, &["--index"]);

    // both a class and a method match "charge"
    let (_, out) = rq(&db, &dir, &["charge", "--ndjson"]);
    assert!(out.contains("\"kind\":\"class\""), "class present: {out}");
    assert!(out.contains("\"kind\":\"method\""), "method present: {out}");

    // -k m (shortcut for method) keeps only the method
    let (ok, out) = rq(&db, &dir, &["charge", "-k", "m", "--ndjson"]);
    assert!(ok, "kind search failed: {out}");
    assert!(out.contains("\"kind\":\"method\""), "method kept: {out}");
    assert!(
        !out.contains("\"kind\":\"class\""),
        "class filtered out: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn first_query_warms_the_index_without_an_explicit_reindex() {
    // A git repo that was never explicitly indexed: the first query opportunistically
    // warms the index (time-bounded) and still answers.
    let (dir, db) = scratch("warm");
    git_init(&dir);
    fs::write(dir.join("widget.rb"), "class Widget\nend\n").unwrap();

    let (ok, out) = rq(&db, &dir, &["widget", "--ndjson"]);
    assert!(ok, "cold search failed: {out}");
    assert!(out.contains("\"name\":\"Widget\""), "result present: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn explicitly_indexes_and_recognizes_a_non_git_directory() {
    // A non-git directory (no git_init): you can still index it explicitly, and
    // a later search recognizes it as the current repo and self-heals.
    let (dir, db) = scratch("nongit");
    fs::write(dir.join("widget.rb"), "class Widget\nend\n").unwrap();

    let (ok, out) = rq(&db, &dir, &["--index"]);
    assert!(ok, "index of a non-git dir failed: {out}");

    let (ok, out) = rq(&db, &dir, &["widget", "--ndjson"]);
    assert!(ok, "search failed: {out}");
    assert!(out.contains("\"name\":\"Widget\""), "result present: {out}");
    // recognized as the current repo → the current-repo boost applies
    assert!(
        out.contains("current_repo"),
        "current-repo boost applied: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn lang_filter_scopes_by_language() {
    let (dir, db) = scratch("lang");
    fs::write(dir.join("widget.rb"), "class Widget\nend\n").unwrap();
    fs::write(dir.join("widget.rs"), "pub struct Widget {}\n").unwrap();
    rq(&db, &dir, &["--index"]);

    // both languages match "widget"
    let (_, out) = rq(&db, &dir, &["widget", "--ndjson"]);
    assert!(out.contains("\"language\":\"ruby\""), "ruby present: {out}");
    assert!(out.contains("\"language\":\"rust\""), "rust present: {out}");

    // -x rs keeps only rust
    let (ok, out) = rq(&db, &dir, &["widget", "-x", "rs", "--ndjson"]);
    assert!(ok, "lang search failed: {out}");
    assert!(out.contains("\"language\":\"rust\""), "rust kept: {out}");
    assert!(
        !out.contains("\"language\":\"ruby\""),
        "ruby filtered: {out}"
    );

    // -x r matches ruby + rust (prefix match) — both kept
    let (_, out) = rq(&db, &dir, &["widget", "-x", "r", "--ndjson"]);
    assert!(
        out.contains("\"language\":\"ruby\"") && out.contains("\"language\":\"rust\""),
        "both kept for -x r: {out}"
    );

    // spelled out keeps only that language
    let (_, out) = rq(&db, &dir, &["widget", "-x", "ruby", "--ndjson"]);
    assert!(out.contains("\"language\":\"ruby\""), "ruby kept: {out}");
    assert!(
        !out.contains("\"language\":\"rust\""),
        "rust filtered: {out}"
    );

    // -x py matches neither → no results
    let (ok, out) = rq(&db, &dir, &["widget", "-x", "py", "--ndjson"]);
    assert!(!ok, "no python here, should exit non-zero");
    assert!(
        out.contains("\"status\":\"no_match\""),
        "a definitive miss reports no_match: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn searching_from_a_subdirectory_uses_the_repo_root() {
    // Regression: warming/indexing must key off the repo root, not the cwd. A
    // search run from a subdirectory previously re-keyed the same repo under
    // subdir-relative paths and a fresh checkout root, so the reconcile and
    // staleness revalidation forgot everything indexed from the root.
    let (dir, db) = scratch("subdir");
    git_init(&dir);
    let sub = dir.join("nested");
    fs::create_dir_all(&sub).unwrap();
    fs::write(dir.join("top.rb"), "class TopWidget\nend\n").unwrap();
    fs::write(sub.join("deep.rb"), "class DeepWidget\nend\n").unwrap();

    // index the whole repo from its root — paths are repo-root-relative
    let (ok, _) = rq(&db, &dir, &["--index"]);
    assert!(ok);
    let (_, out) = rq(&db, &dir, &["DeepWidget", "--no-record"]);
    assert!(out.contains("nested/deep.rb"), "root-relative path: {out}");

    // searching from the subdirectory must reuse the same repo, not fork a new
    // one keyed at the subdir — the top-level symbol stays found, and there's
    // still exactly one repository with both files.
    let (_, out) = rq(&db, &sub, &["TopWidget", "--no-record"]);
    assert!(
        out.contains("TopWidget"),
        "top symbol found from subdir: {out}"
    );
    let (_, status) = rq(&db, &dir, &["--status"]);
    assert_eq!(
        status.lines().count(),
        1,
        "one repo, not re-keyed: {status}"
    );
    assert!(status.contains("2 files"), "both files retained: {status}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn warming_a_committed_repo_indexes_tracked_source() {
    // A committed git repo enumerates candidates from `git ls-files` (reading
    // git's index) instead of walking the filesystem — the path that keeps a huge
    // repo from burning its warm budget on a non-source tree. The tracked source
    // is found on the first search; a non-source file is ignored.
    let (dir, db) = scratch("gitwarm");
    fs::create_dir_all(dir.join("lib")).unwrap();
    fs::write(dir.join("lib/widget.rb"), "class Widget\nend\n").unwrap();
    fs::write(dir.join("README.md"), "# docs, not source\n").unwrap();
    git_init_commit(&dir);

    let (ok, out) = rq(&db, &dir, &["Widget", "--no-record"]);
    assert!(ok, "warmed search failed: {out}");
    assert!(
        out.contains("lib/widget.rb"),
        "tracked source warmed: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn a_cold_repo_blocks_to_an_answer_instead_of_a_false_miss() {
    // The core fix: a query against an unindexed repo would otherwise hit the
    // bounded budget and see a *false* "no matches" while the symbol sits
    // unindexed. With a tiny answer budget the old bounded path gives up first;
    // now the query blocks and keeps indexing until the answer appears. This is
    // the *programmatic* (--json, non-TTY) path — correctness for agents/scripts,
    // no progress UI.
    let (dir, db) = scratch("block-json");
    fs::write(dir.join("widget.rb"), "class Widget\nend\n").unwrap();
    git_init_commit(&dir);

    let run = Command::new(env!("CARGO_BIN_EXE_rq"))
        .args(["Widget", "--no-record", "--json"])
        .current_dir(&dir)
        .env("RQ_DB", &db)
        .env("RQ_ANSWER_BUDGET_MS", "1") // bounded path would give up immediately
        .output()
        .expect("run rq");
    let out = String::from_utf8_lossy(&run.stdout);
    assert!(
        run.status.success(),
        "a programmatic query should block until it finds the symbol; \
         stdout={out:?} stderr={:?}",
        String::from_utf8_lossy(&run.stderr)
    );
    assert!(out.contains("widget.rb"), "found in the right file: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn an_interactive_cold_repo_shows_progress_and_finds_the_answer() {
    // The human path: forcing interactive turns on the stderr heads-up + Ctrl-C
    // handling, but the blocking-until-answered behavior is the same as --json.
    let (dir, db) = scratch("block-tty");
    fs::write(dir.join("widget.rb"), "class Widget\nend\n").unwrap();
    git_init_commit(&dir);

    let run = Command::new(env!("CARGO_BIN_EXE_rq"))
        .args(["Widget", "--no-record"])
        .current_dir(&dir)
        .env("RQ_DB", &db)
        .env("RQ_ANSWER_BUDGET_MS", "1")
        .env("RQ_ASSUME_INTERACTIVE", "1") // pretend a TTY
        .output()
        .expect("run rq");
    let out = String::from_utf8_lossy(&run.stdout);
    assert!(run.status.success(), "should find the symbol: {out:?}");
    assert!(out.contains("widget.rb"), "found in the right file: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn an_incomplete_index_reports_an_indeterminate_miss_not_a_definitive_one() {
    // A miss while the index is still warming is "not yet", not "absent". Capping
    // the pass below the repo size keeps coverage "warming", so a query for a
    // symbol that isn't in the indexed slice must exit 2 (indeterminate) — letting
    // an agent retry rather than conclude the symbol doesn't exist.
    let (dir, db) = scratch("indeterminate");
    for i in 0..20 {
        fs::write(
            dir.join(format!("m{i:02}.rb")),
            format!("class Widget{i}\nend\n"),
        )
        .unwrap();
    }
    git_init_commit(&dir);

    let run = Command::new(env!("CARGO_BIN_EXE_rq"))
        .args(["Nonexistent", "--no-record", "--json"])
        .current_dir(&dir)
        .env("RQ_DB", &db)
        .env("RQ_COLLECT_CAP", "5") // one pass can't finish → stays "warming"
        .output()
        .expect("run rq");
    let out = String::from_utf8_lossy(&run.stdout);
    assert!(
        out.contains("\"status\": \"warming\""),
        "an incomplete-index miss reports warming in JSON: {out:?}"
    );
    assert_eq!(
        run.status.code(),
        Some(2),
        "an incomplete-index miss is indeterminate (exit 2), not definitive"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn no_wait_returns_without_blocking_on_a_rebuild() {
    // `--no-wait` is the agent/script escape hatch: a query issued while the index
    // is (re)building must answer from the committed index *now*, never
    // block-until-answered on the writer. A default programmatic miss on an
    // incomplete index blocks up to the wait budget before giving up (see
    // `an_incomplete_index_reports_an_indeterminate_miss_not_a_definitive_one`);
    // here the wait budget is 10 minutes, so if --no-wait blocked at all this test
    // would hang. It returns at once instead — an honest `warming` miss (exit 2,
    // "retry"), not a multi-minute hang and not a false definitive absence.
    let (dir, db) = scratch("no-wait");
    fs::write(dir.join("widget.rb"), "class Widget\nend\n").unwrap();
    git_init_commit(&dir);

    // Both spellings must return at once (not block): the bare flag and its
    // duration form `--wait 0`. RQ_WAIT_BUDGET_MS is 10 minutes throughout, so a
    // block on either would hang the test.
    for flags in [["--no-wait"].as_slice(), ["--wait", "0"].as_slice()] {
        let mut args = vec!["Nonexistent", "--no-record", "--json"];
        args.extend_from_slice(flags);
        let run = Command::new(env!("CARGO_BIN_EXE_rq"))
            .args(&args)
            .current_dir(&dir)
            .env("RQ_DB", &db)
            .env("RQ_WARM_DETACH", "0") // hermetic: no detached child races cleanup
            .env("RQ_WAIT_BUDGET_MS", "600000") // a block, if it happened, would hang the test
            .output()
            .expect("run rq");
        let out = String::from_utf8_lossy(&run.stdout);
        assert!(
            out.contains("\"status\": \"warming\""),
            "{flags:?} miss on a not-yet-complete index reports warming (retry), \
             not a block or a false absence: {out:?}"
        );
        assert_eq!(
            run.status.code(),
            Some(2),
            "{flags:?} miss on an incomplete index is indeterminate (exit 2)"
        );
    }

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn symbols_outlines_a_file_in_line_order() {
    let (dir, db) = scratch("symbols");
    fs::write(
        dir.join("widget.rb"),
        "class Widget\n  def build\n  end\n  def render\n  end\nend\n",
    )
    .unwrap();
    fs::write(dir.join("other.rb"), "class Other\nend\n").unwrap();
    git_init_commit(&dir);

    // ndjson outline: the file's symbols, in line order, with kind/parent/signature.
    let (ok, out) = rq(&db, &dir, &["--symbols", "widget.rb", "--ndjson"]);
    assert!(ok, "symbols failed: {out}");
    let lines: Vec<&str> = out.lines().collect();
    assert_eq!(lines.len(), 3, "class + two methods: {out}");
    assert!(
        first_line(&out).contains("\"name\":\"Widget\""),
        "class first: {out}"
    );
    assert!(out.contains("\"name\":\"build\""), "build present: {out}");
    assert!(
        out.contains("\"parent\":\"Widget\""),
        "method nests under class: {out}"
    );
    assert!(
        out.contains("\"signature\":\"def build\""),
        "signature read: {out}"
    );
    // scoped to the named file only
    assert!(!out.contains("Other"), "other file excluded: {out}");

    // --kind filters the outline to just methods (drops the class).
    let (ok, out) = rq(
        &db,
        &dir,
        &["--symbols", "widget.rb", "-k", "method", "--ndjson"],
    );
    assert!(ok, "filtered symbols failed: {out}");
    assert_eq!(out.lines().count(), 2, "two methods only: {out}");
    assert!(
        !out.contains("\"name\":\"Widget\""),
        "class filtered out: {out}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn bare_invocation_prints_help() {
    let (dir, db) = scratch("help");
    let (ok, out) = rq(&db, &dir, &[]);
    assert!(ok, "bare rq should exit 0");
    assert!(
        out.contains("rq finds where a symbol is defined"),
        "help banner: {out}"
    );
    assert!(out.contains("Usage:"), "usage in help: {out}");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn detached_warm_finishes_coverage_in_the_background() {
    let (dir, db) = scratch("detach");
    for i in 0..30 {
        fs::write(
            dir.join(format!("f{i:02}.rb")),
            format!("class K{i:02}\nend\n"),
        )
        .unwrap();
    }
    git_init_commit(&dir);

    // Cap each in-process pass tiny so the answering query can't finish the
    // sweep itself; detached warming (on) must pick up the remainder. The
    // child inherits the cap, so it needs several passes — exercising its
    // sweep-until-complete loop too.
    let out = Command::new(env!("CARGO_BIN_EXE_rq"))
        .args(["K00", "--no-record"])
        .current_dir(&dir)
        .env("RQ_DB", &db)
        .env("RQ_WARM_DETACH", "1")
        .env("RQ_COLLECT_CAP", "5")
        .output()
        .expect("run rq");
    assert!(
        out.status.success(),
        "search failed: {}",
        String::from_utf8_lossy(&out.stdout)
    );

    // the detached child completes the sweep with no further queries
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
    loop {
        let (_, status) = rq(&db, &dir, &["--status", "--ndjson"]);
        if status.contains("\"status\":\"complete\"") && status.contains("\"files\":30") {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "detached warm never completed: {status}"
        );
        std::thread::sleep(std::time::Duration::from_millis(200));
    }

    let _ = fs::remove_dir_all(&dir);
}