-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_java_codebase_rag_cli.py
More file actions
1498 lines (1266 loc) · 56.8 KB
/
Copy pathtest_java_codebase_rag_cli.py
File metadata and controls
1498 lines (1266 loc) · 56.8 KB
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
from __future__ import annotations
import contextlib
import io
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path
import pytest
from java_codebase_rag import cli as cli_mod
from java_codebase_rag.config import emit_legacy_env_hints_if_present, resolve_operator_config
@pytest.fixture(scope="session", autouse=True)
def _install_java_codebase_rag_entrypoint() -> None:
"""Install editable package so ``java-codebase-rag`` exists for subprocess CLI tests.
Session-scoped: one ``pip install -e`` per pytest run (slow but matches real entrypoints).
"""
repo_root = Path(__file__).resolve().parent.parent
subprocess.run(
[sys.executable, "-m", "pip", "install", "-e", str(repo_root)],
check=True,
capture_output=True,
text=True,
)
def _cocoindex_available() -> bool:
return (Path(sys.executable).parent / "cocoindex").is_file()
def _base_env(corpus_root: Path, ladybug_db_path: Path | None = None) -> dict[str, str]:
env = os.environ.copy()
env["JAVA_CODEBASE_RAG_SOURCE_ROOT"] = str(corpus_root)
if ladybug_db_path is not None:
env["JAVA_CODEBASE_RAG_INDEX_DIR"] = str(ladybug_db_path.parent)
return env
def _java_codebase_rag_exe() -> str:
venv_exe = Path(sys.executable).parent / "java-codebase-rag"
if venv_exe.is_file():
return str(venv_exe)
exe = shutil.which("java-codebase-rag")
assert exe is not None, "expected installed java-codebase-rag entrypoint"
return exe
def _run_cli(args: list[str], *, env: dict[str, str], stdin: str | None = None) -> subprocess.CompletedProcess:
exe = _java_codebase_rag_exe()
return subprocess.run(
[exe, *args],
capture_output=True,
text=True,
env=env,
input=stdin,
check=False,
)
def test_cli_init_refuses_when_index_paths_non_empty(tmp_path: Path) -> None:
idx = tmp_path / "idx"
idx.mkdir()
(idx / "code_graph.lbug").mkdir()
env = os.environ.copy()
env["JAVA_CODEBASE_RAG_INDEX_DIR"] = str(idx)
env["JAVA_CODEBASE_RAG_SOURCE_ROOT"] = str(tmp_path)
proc = _run_cli(["init", "--source-root", str(tmp_path), "--index-dir", str(idx)], env=env)
assert proc.returncode == 2
payload = json.loads(proc.stdout)
assert payload.get("success") is False
assert "non_empty_paths" in payload or "non_empty" in (payload.get("message") or "").lower()
def test_cli_erase_refuses_non_tty_without_yes(tmp_path: Path) -> None:
idx = tmp_path / "idx2"
idx.mkdir()
env = os.environ.copy()
env["JAVA_CODEBASE_RAG_INDEX_DIR"] = str(idx)
env["JAVA_CODEBASE_RAG_SOURCE_ROOT"] = str(tmp_path)
proc = subprocess.run(
[_java_codebase_rag_exe(), "erase", "--source-root", str(tmp_path), "--index-dir", str(idx)],
capture_output=True,
text=True,
env=env,
stdin=subprocess.DEVNULL,
check=False,
)
assert proc.returncode == 2
assert "non-interactive" in proc.stderr.lower() or "--yes" in proc.stderr
def test_cli_erase_succeeds_with_yes_flag(tmp_path: Path) -> None:
idx = tmp_path / "idx3"
idx.mkdir()
(idx / "stub.txt").write_text("x", encoding="utf-8")
env = os.environ.copy()
env["JAVA_CODEBASE_RAG_INDEX_DIR"] = str(idx)
env["JAVA_CODEBASE_RAG_SOURCE_ROOT"] = str(tmp_path)
proc = _run_cli(
["erase", "--source-root", str(tmp_path), "--index-dir", str(idx), "--yes"],
env=env,
)
assert proc.returncode == 0, proc.stderr + proc.stdout
def test_erase_removes_graph_file_cocoindex_dir_and_hash_store(tmp_path: Path) -> None:
"""erase must delete code_graph.lbug (file), cocoindex.db (dir), .graph_hashes.json.
Regression for issue #346: a type-blind delete left both on disk.
shutil.rmtree is a silent no-op on a regular file (code_graph.lbug), and
Path.unlink raises IsADirectoryError on cocoindex.db (a directory) — both
swallowed — and .graph_hashes.json was never targeted. The follow-up init
then refused because code_graph.lbug survived.
"""
idx = tmp_path / "erase_artifacts"
idx.mkdir()
# Real on-disk layout: graph is a single FILE, cocoindex state is a DIR.
(idx / "code_graph.lbug").write_bytes(b"fake-kuzu-db")
(idx / "cocoindex.db").mkdir()
(idx / "cocoindex.db" / "state.json").write_text("{}", encoding="utf-8")
(idx / ".graph_hashes.json").write_text("{}", encoding="utf-8")
env = os.environ.copy()
env["JAVA_CODEBASE_RAG_INDEX_DIR"] = str(idx)
env["JAVA_CODEBASE_RAG_SOURCE_ROOT"] = str(tmp_path)
proc = _run_cli(
["erase", "--source-root", str(tmp_path), "--index-dir", str(idx), "--yes"],
env=env,
)
assert proc.returncode == 0, proc.stderr + proc.stdout
assert not (idx / "code_graph.lbug").exists(), "erase left code_graph.lbug on disk"
assert not (idx / "cocoindex.db").exists(), "erase left cocoindex.db/ on disk"
assert not (idx / ".graph_hashes.json").exists(), "erase left .graph_hashes.json on disk"
def test_embedding_model_precedence_cli_over_env_over_yaml_over_default(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.delenv("JAVA_CODEBASE_RAG_INDEX_DIR", raising=False)
monkeypatch.delenv("SBERT_MODEL", raising=False)
(tmp_path / ".java-codebase-rag.yml").write_text(
"embedding:\n model: from-yaml\n",
encoding="utf-8",
)
r = resolve_operator_config(
source_root=tmp_path,
cli_embedding_model="from-cli",
)
assert r.embedding_model == "from-cli"
monkeypatch.delenv("SBERT_MODEL", raising=False)
r2 = resolve_operator_config(source_root=tmp_path, cli_embedding_model=None)
assert r2.embedding_model == "from-yaml"
monkeypatch.setenv("SBERT_MODEL", "from-env")
r3 = resolve_operator_config(source_root=tmp_path, cli_embedding_model=None)
assert r3.embedding_model == "from-env"
monkeypatch.delenv("SBERT_MODEL", raising=False)
(tmp_path / ".java-codebase-rag.yml").unlink(missing_ok=True)
r4 = resolve_operator_config(source_root=tmp_path, cli_embedding_model=None)
assert "MiniLM" in r4.embedding_model
def test_embedding_model_yaml_expands_tilde(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.delenv("SBERT_MODEL", raising=False)
monkeypatch.setenv("HOME", str(tmp_path / "home"))
(tmp_path / ".java-codebase-rag.yml").write_text(
"embedding:\n model: ~/models/minilm\n",
encoding="utf-8",
)
cfg = resolve_operator_config(source_root=tmp_path)
assert cfg.embedding_model == str(tmp_path / "home" / "models" / "minilm")
assert cfg.embedding_model_source == "yaml"
def test_embedding_model_yaml_expands_envvar(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.delenv("SBERT_MODEL", raising=False)
monkeypatch.setenv("MY_MODEL_DIR", "/abs/models")
(tmp_path / ".java-codebase-rag.yml").write_text(
"embedding:\n model: $MY_MODEL_DIR/minilm\n",
encoding="utf-8",
)
cfg = resolve_operator_config(source_root=tmp_path)
assert cfg.embedding_model == "/abs/models/minilm"
assert cfg.embedding_model_source == "yaml"
def test_embedding_model_yaml_hub_id_not_expanded(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.delenv("SBERT_MODEL", raising=False)
(tmp_path / ".java-codebase-rag.yml").write_text(
"embedding:\n model: BAAI/bge-small-en-v1.5\n",
encoding="utf-8",
)
cfg = resolve_operator_config(source_root=tmp_path)
assert cfg.embedding_model == "BAAI/bge-small-en-v1.5"
assert cfg.embedding_model_source == "yaml"
def test_embedding_model_cli_quoted_tilde_expanded(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""UC10b: quoted CLI argument bypasses shell expansion; helper canonicalises."""
monkeypatch.delenv("SBERT_MODEL", raising=False)
monkeypatch.setenv("HOME", str(tmp_path / "home"))
cfg = resolve_operator_config(
source_root=tmp_path,
cli_embedding_model="~/cli/x", # quoted in shell → arrives literal
)
assert cfg.embedding_model == str(tmp_path / "home" / "cli" / "x")
assert cfg.embedding_model_source == "cli"
def test_embedding_model_yaml_unresolved_var_keeps_literal_stderr_hint_uc9(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str],
) -> None:
monkeypatch.delenv("SBERT_MODEL", raising=False)
(tmp_path / ".java-codebase-rag.yml").write_text(
"embedding:\n model: $UNDEFINED_FOO/x\n",
encoding="utf-8",
)
cfg = resolve_operator_config(source_root=tmp_path)
assert cfg.embedding_model == "$UNDEFINED_FOO/x"
assert cfg.embedding_model_source == "yaml"
err = capsys.readouterr().err
assert "unresolved variable" in err
def test_embedding_device_precedence_cli_over_env_over_yaml_over_default(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.delenv("JAVA_CODEBASE_RAG_INDEX_DIR", raising=False)
(tmp_path / ".java-codebase-rag.yml").write_text(
"embedding:\n device: cuda\n",
encoding="utf-8",
)
monkeypatch.delenv("SBERT_DEVICE", raising=False)
r = resolve_operator_config(source_root=tmp_path, cli_embedding_device="mps")
assert r.embedding_device == "mps"
r2 = resolve_operator_config(source_root=tmp_path, cli_embedding_device=None)
assert r2.embedding_device == "cuda"
monkeypatch.setenv("SBERT_DEVICE", "cpu")
r3 = resolve_operator_config(source_root=tmp_path, cli_embedding_device=None)
assert r3.embedding_device == "cpu"
def test_hints_enabled_defaults_to_true(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("JAVA_CODEBASE_RAG_HINTS_ENABLED", raising=False)
r = resolve_operator_config(source_root=tmp_path)
assert r.hints_enabled is True
assert r.hints_enabled_source == "default"
def test_hints_enabled_env_over_yaml_over_default(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("JAVA_CODEBASE_RAG_HINTS_ENABLED", raising=False)
(tmp_path / ".java-codebase-rag.yml").write_text(
"hints:\n enabled: false\n", encoding="utf-8",
)
r = resolve_operator_config(source_root=tmp_path)
assert r.hints_enabled is False
assert r.hints_enabled_source == "yaml"
monkeypatch.setenv("JAVA_CODEBASE_RAG_HINTS_ENABLED", "1")
r2 = resolve_operator_config(source_root=tmp_path)
assert r2.hints_enabled is True
assert r2.hints_enabled_source == "env"
def test_yaml_config_ignores_legacy_filename_reads_new_filename(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("JAVA_CODEBASE_RAG_INDEX_DIR", raising=False)
monkeypatch.delenv("SBERT_MODEL", raising=False)
(tmp_path / ".lancedb-mcp.yml").write_text("embedding:\n model: legacy-yaml\n", encoding="utf-8")
(tmp_path / ".java-codebase-rag.yml").write_text("embedding:\n model: new-yaml\n", encoding="utf-8")
r = resolve_operator_config(source_root=tmp_path, cli_embedding_model=None)
assert r.embedding_model == "new-yaml"
def test_index_dir_defaults_to_dot_java_codebase_rag_under_project_root(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("JAVA_CODEBASE_RAG_INDEX_DIR", raising=False)
r = resolve_operator_config(source_root=tmp_path, cli_index_dir=None)
assert r.index_dir == (tmp_path / ".java-codebase-rag").resolve()
assert r.index_dir_source == "default"
def test_index_dir_precedence_cli_over_env_over_yaml_over_default(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("JAVA_CODEBASE_RAG_INDEX_DIR", raising=False)
(tmp_path / ".java-codebase-rag.yml").write_text("index_dir: from-yaml\n", encoding="utf-8")
a = tmp_path / "a"
b = tmp_path / "b"
c = tmp_path / "c"
for p in (a, b, c):
p.mkdir()
r = resolve_operator_config(source_root=tmp_path, cli_index_dir=str(c))
assert r.index_dir == c.resolve()
r2 = resolve_operator_config(source_root=tmp_path, cli_index_dir=None)
assert r2.index_dir == (tmp_path / "from-yaml").resolve()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(b))
r3 = resolve_operator_config(source_root=tmp_path, cli_index_dir=None)
assert r3.index_dir == b.resolve()
def test_ladybug_path_derived_as_index_dir_code_graph_kuzu(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("JAVA_CODEBASE_RAG_INDEX_DIR", raising=False)
r = resolve_operator_config(source_root=tmp_path, cli_index_dir=str(tmp_path / "idx"))
assert r.ladybug_path == r.index_dir / "code_graph.lbug"
def test_help_output_includes_three_group_labels() -> None:
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = cli_mod.main(["--help"])
assert rc == 0
out = buf.getvalue()
assert "Lifecycle" in out
assert "Introspection" in out
assert "Analysis" in out
def test_java_codebase_rag_cli_module_importable() -> None:
import java_codebase_rag.cli # noqa: PLC0415
assert callable(java_codebase_rag.cli.main)
def test_refresh_hidden_alias_deprecates_on_stderr(tmp_path: Path) -> None:
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
rc = cli_mod.main(["refresh", "--help"])
assert rc == 0
err = buf.getvalue()
assert "deprecated" in err.lower()
assert "reprocess" in err.lower()
@pytest.mark.skipif(not _cocoindex_available(), reason="cocoindex not installed in venv")
def test_increment_emits_kuzu_stale_warning_block(
corpus_root: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that increment does NOT emit stale warning by default (new behavior).
The stale warning is now only emitted with --vectors-only flag.
This test verifies the new default behavior where graph IS updated.
"""
idx = tmp_path / "idx_inc"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(corpus_root))
init_rc = cli_mod.main(
["init", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert init_rc == 0
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
rc = cli_mod.main(
["increment", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert rc == 0
err = buf.getvalue()
# Should NOT contain old stale warning
assert "WARNING: AST graph (Kuzu) incremental rebuild is not yet implemented." not in err
assert "java-codebase-rag reprocess" not in err
assert cli_mod.LADYBUG_INCREMENTAL_TRACKING_ISSUE_URL not in err
def test_meta_reports_embedding_setting_source(corpus_root: Path, ladybug_db_path: Path) -> None:
env = _base_env(corpus_root, ladybug_db_path)
env["SBERT_MODEL"] = "env-model"
proc = _run_cli(
["meta", "--source-root", str(corpus_root), "--embedding-model", "cli-model"],
env=env,
)
assert proc.returncode == 0, proc.stderr
payload = json.loads(proc.stdout)
assert payload.get("embedding_model") == "cli-model"
assert payload.get("embedding_model_source") == "cli"
def test_legacy_env_var_set_emits_stderr_hint(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
monkeypatch.setenv("LANCEDB_URI", "http://ignored")
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
emit_legacy_env_hints_if_present()
emit_legacy_env_hints_if_present()
err = buf.getvalue()
assert "LANCEDB_URI" in err
assert "JAVA_CODEBASE_RAG_INDEX_DIR" in err
assert err.count("LANCEDB_URI") == 1
@pytest.mark.skipif(not _cocoindex_available(), reason="cocoindex not installed in venv")
def test_init_after_erase_succeeds(corpus_root: Path, tmp_path: Path) -> None:
"""Build a real index, erase it, then init again from a clean slate.
Regression for issue #346: the previous body erased an *empty* index dir and
then inited, so it never exercised "erase a real graph -> re-init" and stayed
green while erase silently left code_graph.lbug on disk.
"""
idx = tmp_path / "lifecycle_idx"
idx.mkdir(parents=True)
env = os.environ.copy()
env["JAVA_CODEBASE_RAG_INDEX_DIR"] = str(idx)
env["JAVA_CODEBASE_RAG_SOURCE_ROOT"] = str(corpus_root.resolve())
init1 = _run_cli(
["init", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
env=env,
)
assert init1.returncode == 0, init1.stdout + init1.stderr
assert (idx / "code_graph.lbug").exists(), "init did not build code_graph.lbug"
e1 = _run_cli(
["erase", "--source-root", str(corpus_root), "--index-dir", str(idx), "--yes"],
env=env,
)
assert e1.returncode == 0, e1.stderr
assert not (idx / "code_graph.lbug").exists(), "erase left code_graph.lbug on disk"
init2 = _run_cli(
["init", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
env=env,
)
assert init2.returncode == 0, init2.stdout + init2.stderr
@pytest.mark.skipif(not _cocoindex_available(), reason="cocoindex not installed in venv")
def test_cli_lifecycle_round_trip_init_increment_meta_erase(
corpus_root: Path, tmp_path: Path,
) -> None:
"""Test lifecycle round-trip: init -> increment -> meta -> erase.
This test verifies that increment updates both Lance and graph (new behavior).
"""
idx = tmp_path / "rt_idx"
env = os.environ.copy()
env["JAVA_CODEBASE_RAG_INDEX_DIR"] = str(idx)
env["JAVA_CODEBASE_RAG_SOURCE_ROOT"] = str(corpus_root.resolve())
e0 = _run_cli(
["erase", "--source-root", str(corpus_root), "--index-dir", str(idx), "--yes"],
env=env,
)
assert e0.returncode == 0, e0.stderr
init = _run_cli(
["init", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
env=env,
)
assert init.returncode == 0, init.stdout + init.stderr
inc = _run_cli(
["increment", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
env=env,
)
assert inc.returncode == 0, inc.stdout + inc.stderr
# Should NOT contain old stale warning (new behavior)
assert "WARNING: AST graph" not in inc.stderr
# Should contain new success message
assert "Lance + graph updated" in inc.stdout
meta = _run_cli(["meta", "--source-root", str(corpus_root), "--index-dir", str(idx)], env=env)
assert meta.returncode == 0, meta.stderr
er = _run_cli(
["erase", "--source-root", str(corpus_root), "--index-dir", str(idx), "--yes"],
env=env,
)
assert er.returncode == 0, er.stderr
@pytest.mark.skipif(not _cocoindex_available(), reason="cocoindex not installed in venv")
def test_increment_runs_graph_update(
corpus_root: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that increment updates graph by default (no --vectors-only)."""
idx = tmp_path / "idx_graph_update"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(corpus_root))
init_rc = cli_mod.main(
["init", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert init_rc == 0
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
rc = cli_mod.main(
["increment", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert rc == 0
# Should NOT contain stale warning
err = buf.getvalue()
assert "WARNING: AST graph" not in err
def test_increment_vectors_only_skips_graph(
corpus_root: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that increment --vectors-only emits stale warning and skips graph update."""
idx = tmp_path / "idx_vectors_only"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(corpus_root))
init_rc = cli_mod.main(
["init", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert init_rc == 0
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
rc = cli_mod.main(
["increment", "--vectors-only", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert rc == 0
err = buf.getvalue()
# Should contain stale warning
assert "WARNING: AST graph (LadybugDB) incremental rebuild is not yet implemented." in err
assert "java-codebase-rag reprocess" in err
assert cli_mod.LADYBUG_INCREMENTAL_TRACKING_ISSUE_URL in err
def test_increment_cli_help_mentions_vectors_only(
corpus_root: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that increment --help mentions --vectors-only flag."""
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = cli_mod.main(["increment", "--help"])
assert rc == 0
help_text = buf.getvalue()
assert "--vectors-only" in help_text
assert "Run only cocoindex catch-up" in help_text
def test_increment_cli_help_no_longer_says_lance_only(
corpus_root: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that increment --help no longer says 'Lance only'."""
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = cli_mod.main(["increment", "--help"])
assert rc == 0
help_text = buf.getvalue()
# Should NOT say "Lance only" in help
assert "Lance only" not in help_text
# Should say it updates graph
assert "graph" in help_text.lower()
def test_increment_first_run_falls_back_to_full(
corpus_root: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that increment on fresh index (no graph hashes) falls back to full rebuild."""
idx = tmp_path / "idx_first_run"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(corpus_root))
# Run init first
init_rc = cli_mod.main(
["init", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert init_rc == 0
# Remove hash file to simulate first run after upgrade
hash_file = idx / ".graph_hashes.json"
if hash_file.exists():
hash_file.unlink()
buf = io.StringIO()
buf_err = io.StringIO()
with contextlib.redirect_stdout(buf):
with contextlib.redirect_stderr(buf_err):
rc = cli_mod.main(
["increment", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert rc == 0
err = buf_err.getvalue()
# Should fall back to full rebuild gracefully
assert "fell back to full graph rebuild" in err
# Should still succeed
assert "increment completed (Lance + graph updated)" in buf.getvalue()
def test_reprocess_graph_only_then_increment_graph_is_noop(
corpus_root: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The reported scenario, exercised through the real CLI wiring.
``reprocess --graph-only`` rebuilds the graph and seeds ``.graph_hashes.json``
(via ``write_ladybug`` -> ``_init_hash_tracker``); the next ``increment``'s
graph stage must be a no-op, NOT a second full rebuild.
cocoindex is stubbed so ``increment`` runs only its real graph stage (no
embedding model needed). ``reprocess --graph-only`` needs no cocoindex
regardless, so this test runs in the normal (non-heavy) suite.
"""
idx = tmp_path / "idx_reprocess_then_increment"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(corpus_root))
rc = cli_mod.main(
["reprocess", "--graph-only", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert rc == 0, "reprocess --graph-only must succeed"
# reprocess --graph-only must seed the hash store.
hash_file = idx / ".graph_hashes.json"
assert hash_file.exists(), "hash store not seeded by reprocess --graph-only"
# Inject a ghost entry for a file that does not exist — the exact "N removed
# files every run" symptom. On bank-chat (which has Feign/Kafka clients) the
# scoped path this triggers reaches _write_clients_producers_and_calls, so a
# missing-field MemberEntry default here used to crash into a full fallback.
data = json.loads(hash_file.read_text(encoding="utf-8"))
data["ghost/DoesNotExist.java"] = "0" * 64
hash_file.write_text(json.dumps(data), encoding="utf-8")
# Stub cocoindex so increment exercises ONLY its graph stage.
def _noop_coco(env, *, full_reprocess, quiet, verbose=True, lance_project_root=None, on_progress=None, on_progress_console=None):
return subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr="")
monkeypatch.setattr(cli_mod, "run_cocoindex_update", _noop_coco)
buf_out = io.StringIO()
buf_err = io.StringIO()
with contextlib.redirect_stdout(buf_out), contextlib.redirect_stderr(buf_err):
rc2 = cli_mod.main(
["increment", "--source-root", str(corpus_root), "--index-dir", str(idx), "--quiet"],
)
assert rc2 == 0
# The graph stage must NOT have fallen back to a full rebuild.
assert "fell back to full graph rebuild" not in buf_err.getvalue()
assert "increment completed (Lance + graph updated)" in buf_out.getvalue()
# The ghost must be pruned, so the next increment is clean.
after = json.loads(hash_file.read_text(encoding="utf-8"))
assert "ghost/DoesNotExist.java" not in after
@pytest.mark.skipif(not _cocoindex_available(), reason="cocoindex not installed in venv")
def test_increment_updates_lance_after_touch_java_file(corpus_root: Path, tmp_path: Path) -> None:
import lancedb # noqa: PLC0415
work = tmp_path / "corpus_copy"
shutil.copytree(corpus_root, work, dirs_exist_ok=False)
idx = tmp_path / "catchup_idx"
env = os.environ.copy()
env["JAVA_CODEBASE_RAG_INDEX_DIR"] = str(idx)
env["JAVA_CODEBASE_RAG_SOURCE_ROOT"] = str(work.resolve())
_run_cli(
["erase", "--source-root", str(work), "--index-dir", str(idx), "--yes"],
env=env,
)
init = _run_cli(
["init", "--source-root", str(work), "--index-dir", str(idx), "--quiet"],
env=env,
)
assert init.returncode == 0, init.stderr
marker = "package com.bank.chat.assign;\n\nclass CliScenariosTouchMarker { int x; }\n"
touch_path = (
work
/ "chat-assign"
/ "src"
/ "main"
/ "java"
/ "com"
/ "bank"
/ "chat"
/ "assign"
/ "CliScenariosTouchMarker.java"
)
touch_path.parent.mkdir(parents=True, exist_ok=True)
touch_path.write_text(marker, encoding="utf-8")
inc = _run_cli(
["increment", "--source-root", str(work), "--index-dir", str(idx), "--quiet"],
env=env,
)
assert inc.returncode == 0, inc.stderr
db2 = lancedb.connect(str(idx))
tbl2 = db2.open_table("javacodeindex_java_code")
texts = tbl2.to_arrow().column("text").to_pylist()
joined = "\n".join(str(t or "") for t in texts)
assert "CliScenariosTouchMarker" in joined
def test_cli_meta_outputs_valid_json_when_piped(corpus_root, ladybug_db_path) -> None:
env = _base_env(corpus_root, ladybug_db_path)
proc = _run_cli(["meta", "--source-root", str(corpus_root)], env=env)
assert proc.returncode == 0, proc.stderr
payload = json.loads(proc.stdout)
assert "edge_counts" in payload
def test_cli_tables_lists_known_table(corpus_root, ladybug_db_path) -> None:
env = _base_env(corpus_root, ladybug_db_path)
proc = _run_cli(["tables", "--source-root", str(corpus_root)], env=env)
assert proc.returncode == 0, proc.stderr
payload = json.loads(proc.stdout)
assert "java" in payload["tables"]
assert "graph" in payload
def test_cli_unresolved_calls_list_and_stats(corpus_root, ladybug_db_path) -> None:
env = _base_env(corpus_root, ladybug_db_path)
stats_proc = _run_cli(
["unresolved-calls", "stats", "--source-root", str(corpus_root), "--by", "reason"],
env=env,
)
assert stats_proc.returncode == 0, stats_proc.stderr
stats = json.loads(stats_proc.stdout)
assert stats.get("success") is True
assert int(stats.get("total") or 0) >= 1
assert stats.get("buckets")
list_proc = _run_cli(
[
"unresolved-calls",
"list",
"--source-root",
str(corpus_root),
"--reason",
"chained_receiver",
"--limit",
"5",
],
env=env,
)
assert list_proc.returncode == 0, list_proc.stderr
listed = json.loads(list_proc.stdout)
assert listed.get("success") is True
sites = listed.get("sites") or []
assert sites
assert all(str(s.get("id") or "").startswith("ucs:") for s in sites)
assert all(s.get("reason") == "chained_receiver" for s in sites)
bad_reason = _run_cli(
[
"unresolved-calls",
"list",
"--source-root",
str(corpus_root),
"--reason",
"phantom",
],
env=env,
)
assert bad_reason.returncode != 0
def test_cli_diagnose_ignore_walked_path(corpus_root, ladybug_db_path) -> None:
env = _base_env(corpus_root, ladybug_db_path)
path = "chat-assign/src/main/java/com/bank/chat/assign/service/ChatManagementService.java"
proc = _run_cli(["diagnose-ignore", "--source-root", str(corpus_root), path], env=env)
assert proc.returncode == 0, proc.stderr
payload = json.loads(proc.stdout)
assert payload["ignored"] is False
def test_cli_diagnose_ignore_unconditional_prune(corpus_root, ladybug_db_path) -> None:
env = _base_env(corpus_root, ladybug_db_path)
proc = _run_cli(["diagnose-ignore", "--source-root", str(corpus_root), ".git/foo"], env=env)
assert proc.returncode == 0, proc.stderr
payload = json.loads(proc.stdout)
assert payload["ignored"] is True
def test_cli_analyze_pr_with_diff_file(corpus_root, ladybug_db_path, tmp_path) -> None:
env = _base_env(corpus_root, ladybug_db_path)
diff_path = tmp_path / "sample.diff"
diff_path.write_text(
"""diff --git a/chat-assign/src/main/java/com/bank/chat/assign/service/ChatManagementService.java b/chat-assign/src/main/java/com/bank/chat/assign/service/ChatManagementService.java
--- a/chat-assign/src/main/java/com/bank/chat/assign/service/ChatManagementService.java
+++ b/chat-assign/src/main/java/com/bank/chat/assign/service/ChatManagementService.java
@@ -48,5 +48,5 @@
@Transactional
public void assign(AssignmentRequest request) {
- if (request.getConversationId() == null || request.getConversationId().isBlank()) {
+ if (request.getConversationId() == null || request.getConversationId().isBlank() ) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "conversationId required");
}
""",
encoding="utf-8",
)
proc = _run_cli(
["analyze-pr", "--source-root", str(corpus_root), "--diff-file", str(diff_path)],
env=env,
)
assert proc.returncode == 0, proc.stderr
payload = json.loads(proc.stdout)
assert "risk_score" in payload
assert "blast_radius_total" in payload
def test_cli_analyze_pr_with_diff_stdin(corpus_root, ladybug_db_path) -> None:
env = _base_env(corpus_root, ladybug_db_path)
diff_text = """diff --git a/chat-assign/src/main/java/com/bank/chat/assign/service/ChatManagementService.java b/chat-assign/src/main/java/com/bank/chat/assign/service/ChatManagementService.java
--- a/chat-assign/src/main/java/com/bank/chat/assign/service/ChatManagementService.java
+++ b/chat-assign/src/main/java/com/bank/chat/assign/service/ChatManagementService.java
@@ -48,5 +48,5 @@
@Transactional
public void assign(AssignmentRequest request) {
- if (request.getConversationId() == null || request.getConversationId().isBlank()) {
+ if (request.getConversationId() == null || request.getConversationId().isBlank() ) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "conversationId required");
}
"""
proc = _run_cli(
["analyze-pr", "--source-root", str(corpus_root), "--diff-stdin"],
env=env,
stdin=diff_text,
)
assert proc.returncode == 0, proc.stderr
payload = json.loads(proc.stdout)
assert "risk_score" in payload
def test_reprocess_vectors_only_skips_graph(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
idx = tmp_path / "idx_vo"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(tmp_path))
def fake_coco(*_a: object, **_k: object) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(
args=["coco", "u", "t", "f"],
returncode=0,
stdout="",
stderr="",
)
def graph_should_not_run(**_kwargs: object) -> subprocess.CompletedProcess[str]:
raise AssertionError("graph builder must not run for --vectors-only")
monkeypatch.setattr(cli_mod, "run_cocoindex_update", fake_coco)
monkeypatch.setattr(cli_mod, "run_build_ast_graph", graph_should_not_run)
class _NonTty(io.StringIO):
def isatty(self) -> bool:
return False
nout = _NonTty()
monkeypatch.setattr(cli_mod.sys, "stdout", nout)
rc = cli_mod.main(
["reprocess", "--source-root", str(tmp_path), "--index-dir", str(idx), "--vectors-only"],
)
assert rc == 0
payload = json.loads(nout.getvalue())
assert payload["phases_run"] == ["vectors"]
def test_reprocess_graph_only_skips_vectors(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
idx = tmp_path / "idx_go"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(tmp_path))
def coco_should_not_run(*_a: object, **_k: object) -> subprocess.CompletedProcess[str]:
raise AssertionError("cocoindex must not run for --graph-only")
def fake_graph(**_kwargs: object) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(
args=["py", "build_ast_graph.py"],
returncode=0,
stdout="",
stderr="",
)
monkeypatch.setattr(cli_mod, "run_cocoindex_update", coco_should_not_run)
monkeypatch.setattr(cli_mod, "run_build_ast_graph", fake_graph)
out = io.StringIO()
monkeypatch.setattr(cli_mod.sys, "stdout", out)
rc = cli_mod.main(
["reprocess", "--source-root", str(tmp_path), "--index-dir", str(idx), "--graph-only"],
)
assert rc == 0
assert json.loads(out.getvalue())["phases_run"] == ["graph"]
def test_reprocess_mutually_exclusive_flags_rejected(tmp_path: Path) -> None:
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
rc = cli_mod.main(
[
"reprocess",
"--source-root",
str(tmp_path),
"--vectors-only",
"--graph-only",
],
)
assert rc == 2
err = buf.getvalue()
assert "not allowed with argument" in err or "mutually exclusive" in err.lower()
def test_reprocess_graph_only_build_failure_returns_exit_1(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
idx = tmp_path / "idx_gf"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(tmp_path))
def fake_graph(**_kwargs: object) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(
args=["py", "build_ast_graph.py"],
returncode=9,
stdout="",
stderr="boom",
)
monkeypatch.setattr(cli_mod, "run_build_ast_graph", fake_graph)
out = io.StringIO()
monkeypatch.setattr(cli_mod.sys, "stdout", out)
rc = cli_mod.main(
["reprocess", "--source-root", str(tmp_path), "--index-dir", str(idx), "--graph-only"],
)
assert rc == 1
payload = json.loads(out.getvalue())
assert payload["phases_run"] == ["graph"]
assert payload["graph_exit_code"] == 9
def test_reprocess_vectors_only_emits_graph_stale_warning(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
idx = tmp_path / "idx_wv"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(tmp_path))
def fake_coco(*_a: object, **_k: object) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(
args=["coco", "u", "t", "f"],
returncode=0,
stdout="",
stderr="",
)
monkeypatch.setattr(cli_mod, "run_cocoindex_update", fake_coco)
monkeypatch.setattr(
cli_mod,
"run_build_ast_graph",
lambda **_k: subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr=""),
)
err = io.StringIO()
out = io.StringIO()
monkeypatch.setattr(cli_mod.sys, "stderr", err)
monkeypatch.setattr(cli_mod.sys, "stdout", out)
rc = cli_mod.main(
["reprocess", "--source-root", str(tmp_path), "--index-dir", str(idx), "--vectors-only"],
)
assert rc == 0
assert "code_graph.lbug" in err.getvalue()
def test_reprocess_graph_only_emits_vectors_stale_warning(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
idx = tmp_path / "idx_wg"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(tmp_path))
def fake_graph(**_kwargs: object) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(
args=["py", "build_ast_graph.py"],
returncode=0,
stdout="",
stderr="",
)
monkeypatch.setattr(cli_mod, "run_build_ast_graph", fake_graph)
err = io.StringIO()
out = io.StringIO()
monkeypatch.setattr(cli_mod.sys, "stderr", err)
monkeypatch.setattr(cli_mod.sys, "stdout", out)
rc = cli_mod.main(
["reprocess", "--source-root", str(tmp_path), "--index-dir", str(idx), "--graph-only"],
)
assert rc == 0
assert "Lance tables under" in err.getvalue()
assert str(idx) in err.getvalue()
def test_reprocess_vectors_only_setup_failure_returns_exit_2_without_phase(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
idx = tmp_path / "idx_vs"
idx.mkdir()
monkeypatch.setenv("JAVA_CODEBASE_RAG_INDEX_DIR", str(idx))
monkeypatch.setenv("JAVA_CODEBASE_RAG_SOURCE_ROOT", str(tmp_path))