-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstaller.py
More file actions
1339 lines (1095 loc) · 41.8 KB
/
Copy pathinstaller.py
File metadata and controls
1339 lines (1095 loc) · 41.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
"""Interactive installer module for java-codebase-rag.
This module provides the `install` subcommand that walks users through:
1. Java source detection
2. Embedding model selection
3. Agent host selection
4. Scope selection (project/user)
5. Artifact deployment (MCP config, skill, agent)
6. YAML config generation and indexing
"""
import json
import os
import shutil
import sys
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Literal, NamedTuple
import yaml
Scope = Literal["project", "user"]
# MCP server name constant
_MCP_SERVER_NAME = "java-codebase-rag"
# Exit code constants
EXIT_SUCCESS = 0
EXIT_PARTIAL = 1
EXIT_FATAL = 2
class ArtifactResult(NamedTuple):
"""Result of deploying a single artifact."""
path: Path
success: bool
error: str | None
@dataclass(frozen=True)
class HostConfig:
"""Configuration for an agent host."""
name: str # "claude-code", "qwen-code", "gigacode"
dir_name: str # ".claude", ".qwen", ".gigacode"
mcp_project: str # ".mcp.json", ".qwen/settings.json", ".gigacode/settings.json"
mcp_user: str # ".claude.json", ".qwen/settings.json", ".gigacode/settings.json"
def scope_path(self, scope: Scope, cwd: Path) -> Path:
"""Return the host directory for the given scope."""
if scope == "project":
return cwd / self.dir_name
else: # user
return Path.home() / self.dir_name
def mcp_config_path(self, scope: Scope, cwd: Path) -> Path:
"""Return the full path to the MCP config file."""
if scope == "project":
return cwd / self.mcp_project
else: # user
return Path.home() / self.mcp_user
def skills_dir(self, scope: Scope, cwd: Path) -> Path:
"""Return the skills directory path."""
return self.scope_path(scope, cwd) / "skills"
def agents_dir(self, scope: Scope, cwd: Path) -> Path:
"""Return the agents directory path."""
return self.scope_path(scope, cwd) / "agents"
HOSTS: dict[str, HostConfig] = {
"claude-code": HostConfig(
name="claude-code",
dir_name=".claude",
mcp_project=".mcp.json",
mcp_user=".claude.json",
),
"qwen-code": HostConfig(
name="qwen-code",
dir_name=".qwen",
mcp_project=".qwen/settings.json",
mcp_user=".qwen/settings.json",
),
"gigacode": HostConfig(
name="gigacode",
dir_name=".gigacode",
mcp_project=".gigacode/settings.json",
mcp_user=".gigacode/settings.json",
),
}
def prompt(
prompt_type: str,
message: str,
*,
choices=None,
default=None,
) -> list[str] | str | bool:
"""Interactive prompt that dispatches to questionary on TTY, returns default otherwise.
Args:
prompt_type: Type of prompt ("checkbox", "select", "text", "confirm")
message: Prompt message to display
choices: List of choices (for checkbox/select)
default: Default value to return when not interactive
Returns:
- checkbox: list[str] of selected values
- select: str of selected value
- text: str of entered text
- confirm: bool (True/False)
"""
if not sys.stdin.isatty():
return default
# Lazy import questionary only when needed (TTY)
import questionary
from prompt_toolkit.styles import Style
# Strip default ANSI colors — rely on ●/○ indicators only, no fg/bg highlights
# noinherit prevents prompt_toolkit from merging in questionary's default fg colors
no_color_style = Style(
[
("highlighted", "noinherit"),
("selected", "noinherit"),
("pointer", "noinherit bold"),
]
)
try:
if prompt_type == "checkbox":
return questionary.checkbox(message, choices=choices, style=no_color_style).ask()
elif prompt_type == "select":
return questionary.select(message, choices=choices, style=no_color_style).ask()
elif prompt_type == "text":
return questionary.text(message, default=default, style=no_color_style).ask()
elif prompt_type == "confirm":
return questionary.confirm(message, style=no_color_style).ask()
else:
raise ValueError(f"Unknown prompt_type: {prompt_type}")
except KeyboardInterrupt:
# User Ctrl+C is a clean abort, not a traceback
raise SystemExit(2)
def detect_java_directories(source_root: Path) -> list[Path]:
"""Return Maven/Gradle module roots. If root has build file, returns [Path('.')].
Checks if source_root itself contains a build file (pom.xml, build.gradle, build.gradle.kts).
If YES: returns [Path(".")] — the entire project is indexed as one unit.
If NO: scans immediate children for directories containing build files.
Args:
source_root: Root directory to scan for Java projects
Returns:
List of detected module roots (relative to source_root)
Raises:
SystemExit(2): If no build files found in source_root or immediate children
"""
build_files = ["pom.xml", "build.gradle", "build.gradle.kts"]
# Check if source_root itself has a build file
for bf in build_files:
if (source_root / bf).is_file():
return [Path(".")]
# Scan immediate children for build files
detected = []
for child in source_root.iterdir():
if not child.is_dir():
continue
# Check if this child directory has a build file
for bf in build_files:
if (child / bf).is_file():
detected.append(Path(child.name))
break
if not detected:
print(f"Error: No Java build files (pom.xml, build.gradle, build.gradle.kts) found in {source_root} or its immediate children.")
raise SystemExit(2)
return detected
def confirm_source_root(cwd: Path, *, non_interactive: bool) -> Path:
"""Show cwd as source root, let user accept or change it. Returns resolved source_root.
Args:
cwd: Current working directory (default source root)
non_interactive: If True, return cwd without prompting
Returns:
Resolved source root path
"""
if non_interactive:
return cwd
message = f"Source root [{cwd}]:"
user_input = prompt("text", message, default=str(cwd))
if not user_input or user_input == str(cwd):
return cwd
# Expand ~ and $HOME
expanded = os.path.expandvars(user_input.strip())
expanded = os.path.expanduser(expanded)
result = Path(expanded)
# Validate path exists and is a directory
while not result.is_dir():
print(f"Error: Path {result} does not exist or is not a directory.")
user_input = prompt("text", "Source root:", default=str(cwd))
if not user_input or user_input == str(cwd):
return cwd
expanded = os.path.expandvars(user_input.strip())
expanded = os.path.expanduser(expanded)
result = Path(expanded)
return result.resolve()
def resolve_model(model_input: str | None, *, non_interactive: bool) -> str:
"""Resolve embedding model path or 'auto'.
Args:
model_input: User-provided model path or None
non_interactive: If True, return "auto" without prompting
Returns:
Resolved model string ("auto" or a valid path)
"""
if model_input:
# Expand ~ and $HOME
expanded = os.path.expandvars(model_input.strip())
expanded = os.path.expanduser(expanded)
model_path = Path(expanded)
if model_path.exists():
return str(model_path)
# Path not found
if non_interactive:
print(f"Warning: Model path {model_input} not found, falling back to 'auto'.")
return "auto"
confirmed = prompt(
"confirm",
f"Model path {model_input} not found. Use 'auto' instead?",
)
if confirmed:
return "auto"
else:
# Re-prompt for model path
new_input = prompt("text", "Enter model path (or 'auto'):", default="auto")
if new_input == "auto" or not new_input:
return "auto"
return resolve_model(new_input, non_interactive=non_interactive)
if non_interactive:
return "auto"
# Interactive with no CLI input: prompt for model
user_input = prompt("text", "Embedding model path (or 'auto'):", default="auto")
if user_input == "auto" or not user_input:
return "auto"
return resolve_model(user_input, non_interactive=False)
def select_hosts(*, non_interactive: bool, cli_agents: list[str] | None) -> list[HostConfig]:
"""Select agent hosts from checkbox or CLI flags. Returns list of selected HostConfig.
Args:
non_interactive: If True, use CLI flags only
cli_agents: List of agent names from CLI flags
Returns:
List of selected HostConfig objects
Raises:
SystemExit(2): If no agents selected or invalid agent name
"""
if cli_agents:
# Validate agent names
for agent in cli_agents:
if agent not in HOSTS:
print(f"Error: Unknown agent '{agent}'. Valid agents: {', '.join(HOSTS.keys())}")
raise SystemExit(2)
return [HOSTS[agent] for agent in cli_agents]
if non_interactive:
print("Error: --agent flag is required in non-interactive mode.")
print(f"Valid agents: {', '.join(HOSTS.keys())}")
raise SystemExit(2)
# Interactive: show checkbox with claude-code pre-selected (most common)
# Changed from all pre-selected to avoid confusion
host_names = list(HOSTS.keys())
choices = [
{"name": name, "value": name, "checked": (name == "claude-code")}
for name in host_names
]
print("Note: You can select multiple agent hosts with Space. Navigate with arrow keys.")
selected = prompt("checkbox", "Select agent hosts to configure:", choices=choices)
if not selected:
# User unselected all - prompt to re-select or abort
retry = prompt(
"confirm",
"At least one agent host is required. Re-select hosts?",
)
if retry:
return select_hosts(non_interactive=False, cli_agents=None)
else:
raise SystemExit(2)
# Show confirmation of what will be deployed
print(f"Will deploy to: {', '.join(selected)}")
return [HOSTS[name] for name in selected]
def select_scope(*, non_interactive: bool, cli_scope: str | None) -> Scope:
"""Select 'project' or 'user' scope.
Args:
non_interactive: If True, return "project" without prompting
cli_scope: Scope from CLI flag
Returns:
Selected scope ("project" or "user")
"""
if cli_scope:
if cli_scope not in ("project", "user"):
print(f"Error: Invalid scope '{cli_scope}'. Must be 'project' or 'user'.")
raise SystemExit(2)
return cli_scope # type: ignore
if non_interactive:
return "project"
# Interactive: prompt for scope
print("Note: 'project' scope stores configs in the project directory.")
print(" 'user' scope stores configs in your home directory.")
selected = prompt(
"select",
"Select installation scope:",
choices=["project", "user"],
)
if not selected:
return "project"
print(f"Selected scope: {selected}")
return selected # type: ignore
def resolve_mcp_command(*, non_interactive: bool) -> str:
"""Resolve the absolute path to java-codebase-rag-mcp.
Returns the path string for use as MCP 'command' value.
Args:
non_interactive: If True, exit with code 2 when not found
Returns:
Absolute path to java-codebase-rag-mcp executable
Raises:
SystemExit(2): If not found and non-interactive, or user aborts
"""
mcp_path = shutil.which("java-codebase-rag-mcp")
if mcp_path:
return mcp_path
# Not found on PATH
if non_interactive:
print("Error: `java-codebase-rag-mcp` not found on PATH.")
print("Ensure `java-codebase-rag` is installed, then re-run with `--non-interactive --agent <host>`.")
raise SystemExit(2)
# Interactive: prompt user for path
print("Warning: `java-codebase-rag-mcp` not found on PATH.")
user_path = prompt(
"text",
"Enter the full path to java-codebase-rag-mcp (or 'abort'):",
default="abort",
)
if user_path == "abort" or not user_path:
raise SystemExit(2)
# Expand and validate the provided path
expanded = os.path.expandvars(user_path.strip())
expanded = os.path.expanduser(expanded)
path_obj = Path(expanded)
while not path_obj.is_file():
print(f"Error: Path {path_obj} does not exist or is not a file.")
user_path = prompt(
"text",
"Enter the full path to java-codebase-rag-mcp (or 'abort'):",
default="abort",
)
if user_path == "abort" or not user_path:
raise SystemExit(2)
expanded = os.path.expandvars(user_path.strip())
expanded = os.path.expanduser(expanded)
path_obj = Path(expanded)
# Check if executable
if not os.access(path_obj, os.X_OK):
print(f"Warning: {path_obj} is not executable. This may cause issues.")
return str(path_obj.resolve())
def merge_mcp_config(config_path: Path, host: HostConfig, *, mcp_command: str) -> bool:
"""Read, merge, write MCP config. Returns True if entry was added/updated.
Args:
config_path: Path to MCP config file
host: HostConfig for the agent host
mcp_command: Resolved absolute path to java-codebase-rag-mcp
Returns:
True if entry was added/updated, False if no change needed
Raises:
ValueError: If existing config file cannot be parsed as JSON
"""
# Read existing config (or start with empty dict)
if config_path.is_file():
try:
with open(config_path, "r") as f:
config = json.load(f)
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse {config_path}: {e}") from e
else:
config = {}
# Ensure mcpServers key exists
if "mcpServers" not in config:
config["mcpServers"] = {}
# Prepare new entry
new_entry = {"command": mcp_command, "type": "stdio"}
existing_entry = config["mcpServers"].get(_MCP_SERVER_NAME)
# Check if entry already exists with same config
if existing_entry == new_entry:
return False
# Merge/update entry
config["mcpServers"][_MCP_SERVER_NAME] = new_entry
# Write atomically (write to tmp, then rename)
tmp_name = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
dir=config_path.parent,
prefix=f".{config_path.name}.",
delete=False,
) as tmp:
json.dump(config, tmp, indent=2)
tmp.flush()
os.fsync(tmp.fileno())
tmp_name = tmp.name
# Atomic rename
os.rename(tmp_name, config_path)
return True
except (IOError, OSError) as e:
if tmp_name:
try:
os.unlink(tmp_name)
except OSError:
pass
raise RuntimeError(f"Failed to write {config_path}: {e}") from e
def _read_package_artifact(relative_path: str) -> str:
"""Read a shipped artifact from package data. Returns UTF-8 text."""
from importlib.resources import files
package = files("java_codebase_rag.install_data")
return package.joinpath(relative_path).read_text(encoding="utf-8")
def deploy_artifacts(
hosts: list[HostConfig],
scope: Scope,
cwd: Path,
*,
non_interactive: bool,
mcp_command: str,
) -> list[ArtifactResult]:
"""Deploy artifacts (MCP config, skill, agent) to selected hosts.
Args:
hosts: List of HostConfig objects to deploy to
scope: Installation scope ("project" or "user")
cwd: Current working directory
non_interactive: If True, skip overwrite prompts
mcp_command: Resolved absolute path to java-codebase-rag-mcp
Returns:
List of ArtifactResult objects for each deployment
"""
results = []
for host in hosts:
# Deploy MCP config
mcp_config_path = host.mcp_config_path(scope, cwd)
mcp_result = _deploy_mcp_config(
mcp_config_path,
host,
non_interactive=non_interactive,
mcp_command=mcp_command,
)
results.append(mcp_result)
# Deploy skill
skills_dir = host.skills_dir(scope, cwd)
skill_dest = skills_dir / "explore-codebase" / "SKILL.md"
skill_result = _deploy_file(
skill_dest,
"skills/explore-codebase/SKILL.md",
artifact_type="skill",
non_interactive=non_interactive,
)
results.append(skill_result)
# Deploy agent
agents_dir = host.agents_dir(scope, cwd)
agent_dest = agents_dir / "explorer-rag-enhanced.md"
agent_result = _deploy_file(
agent_dest,
"agents/explorer-rag-enhanced.md",
artifact_type="agent",
non_interactive=non_interactive,
)
results.append(agent_result)
return results
def _deploy_mcp_config(
config_path: Path,
host: HostConfig,
*,
non_interactive: bool,
mcp_command: str,
) -> ArtifactResult:
"""Deploy MCP config file."""
try:
# Ensure parent directory exists
config_path.parent.mkdir(parents=True, exist_ok=True)
# Check writability
if not _is_writable(config_path.parent):
return ArtifactResult(
path=config_path,
success=False,
error=f"Directory not writable: {config_path.parent}",
)
# Merge config (returns True if updated, False if already current)
merge_mcp_config(config_path, host, mcp_command=mcp_command)
return ArtifactResult(path=config_path, success=True, error=None)
except ValueError as e:
return ArtifactResult(path=config_path, success=False, error=str(e))
except Exception as e:
return ArtifactResult(path=config_path, success=False, error=str(e))
def _deploy_file(
dest_path: Path,
package_relative_path: str,
*,
artifact_type: str,
non_interactive: bool,
) -> ArtifactResult:
"""Deploy a single file from package data to destination."""
try:
# Ensure parent directory exists
dest_path.parent.mkdir(parents=True, exist_ok=True)
# Check writability
if not _is_writable(dest_path.parent):
return ArtifactResult(
path=dest_path,
success=False,
error=f"Directory not writable: {dest_path.parent}",
)
# Read package data
content = _read_package_artifact(package_relative_path)
# Check if file exists
if dest_path.is_file():
# Check if content is identical
existing_content = dest_path.read_text(encoding="utf-8")
if content == existing_content:
return ArtifactResult(path=dest_path, success=True, error=None)
# File exists with different content - prompt for overwrite
if non_interactive:
# Skip in non-interactive mode
return ArtifactResult(
path=dest_path,
success=False,
error="File exists (skipped in non-interactive mode)",
)
# Interactive: prompt for overwrite
choice = prompt(
"select",
f"{artifact_type.capitalize()} file exists at {dest_path}",
choices=[
{"name": "Overwrite", "value": "overwrite"},
{"name": "Skip", "value": "skip"},
{"name": "Abort", "value": "abort"},
],
)
if choice == "skip":
return ArtifactResult(
path=dest_path,
success=False,
error="Skipped by user",
)
elif choice == "abort":
raise SystemExit(2)
# Write file
dest_path.write_text(content, encoding="utf-8")
return ArtifactResult(path=dest_path, success=True, error=None)
except SystemExit:
raise
except Exception as e:
return ArtifactResult(path=dest_path, success=False, error=str(e))
def _is_writable(path: Path) -> bool:
"""Check if a directory is writable."""
try:
test_file = path / ".write_test_java_codebase_rag"
test_file.touch()
test_file.unlink()
return True
except (OSError, IOError):
return False
def generate_yaml_config(
source_root: Path,
model: str,
microservice_roots: list[str] | None,
existing_yaml: dict | None,
) -> str:
"""Generate .java-codebase-rag.yml content from installer answers.
Args:
source_root: Source root directory
model: Embedding model path or "auto"
microservice_roots: List of microservice roots (None means all)
existing_yaml: Existing YAML data for re-run update mode
Returns:
YAML configuration string
"""
# Start with existing YAML or empty dict
config = existing_yaml.copy() if existing_yaml else {}
# Write microservice_roots only if subset selected
if microservice_roots:
config["microservice_roots"] = microservice_roots
elif "microservice_roots" in config:
# Remove if not needed (was set before but user wants all)
del config["microservice_roots"]
# Write embedding.model only if not auto
if model != "auto":
if "embedding" not in config:
config["embedding"] = {}
config["embedding"]["model"] = model
elif "embedding" in config and "model" in config["embedding"]:
# Remove model if using auto
if config["embedding"] == {"model": model}:
del config["embedding"]
else:
config["embedding"].pop("model", None)
# Keys NOT written by installer (preserved if present):
# - source_root (config.py resolves from walk-up discovery)
# - index_dir (config.py defaults to <source_root>/.java-codebase-rag)
# - embedding.device (user can add manually)
# - hints.enabled (defaults to True in config.py)
# - brownfield_overrides (user-managed)
return yaml.dump(config, default_flow_style=False, sort_keys=False)
def update_gitignore(cwd: Path) -> None:
"""Add .java-codebase-rag/ to .gitignore if not already present.
Args:
cwd: Current working directory
"""
gitignore_path = cwd / ".gitignore"
# Check if git repo
if not (cwd / ".git").is_dir():
return
# Read existing .gitignore or create new
if gitignore_path.is_file():
lines = gitignore_path.read_text(encoding="utf-8").splitlines()
else:
lines = []
# Check for pattern (with or without trailing slash)
pattern_to_check = ".java-codebase-rag"
already_present = any(
line.strip().rstrip("/") == pattern_to_check or line.strip() == f"{pattern_to_check}/"
for line in lines
)
if not already_present:
lines.append("")
lines.append("# java-codebase-rag index directory")
lines.append(".java-codebase-rag/")
gitignore_path.write_text("\n".join(lines), encoding="utf-8")
def run_init_if_needed(
source_root: Path,
index_dir: Path,
model: str,
*,
non_interactive: bool,
quiet: bool,
) -> bool:
"""Run init if index directory has no artifacts. Return True if init was run.
Args:
source_root: Source root directory
index_dir: Index directory path
model: Embedding model path or "auto"
non_interactive: If True, suppress prompts
quiet: If True, suppress output
Returns:
True if init was run, False if skipped
"""
from java_codebase_rag.config import (
index_dir_has_existing_artifacts,
resolve_operator_config,
)
from java_codebase_rag.pipeline import run_build_ast_graph, run_cocoindex_update
has_existing, _ = index_dir_has_existing_artifacts(index_dir)
if has_existing:
print("Index already exists. Run `java-codebase-rag reprocess` to rebuild.")
return False
print("Creating index...")
cfg = resolve_operator_config(
source_root=source_root,
cli_index_dir=None, # use default (<source_root>/.java-codebase-rag)
cli_embedding_model=model if model != "auto" else None,
)
cfg.apply_to_os_environ()
env = cfg.subprocess_env()
# Run CocoIndex update
coco = run_cocoindex_update(env, full_reprocess=False, quiet=quiet)
if coco.returncode != 0:
print(f"Error: CocoIndex update failed with code {coco.returncode}")
return False
# Run AST graph build
g = run_build_ast_graph(
source_root=cfg.source_root,
kuzu_path=cfg.kuzu_path,
verbose=not quiet,
quiet=quiet,
env=env,
)
if g.returncode != 0:
print(f"Error: AST graph build failed with code {g.returncode}")
return False
print("Index created successfully.")
return True
def handle_rerun(cwd: Path, *, non_interactive: bool) -> dict | None:
"""If .java-codebase-rag.yml exists, offer update/fresh-start. Return existing YAML data or None.
Args:
cwd: Current working directory
non_interactive: If True, default to "Update" mode
Returns:
Parsed existing YAML data if updating, None if starting fresh
"""
config_path = cwd / ".java-codebase-rag.yml"
if not config_path.is_file():
return None
try:
with open(config_path, "r") as f:
existing_config = yaml.safe_load(f) or {}
except yaml.YAMLError as e:
print(f"Warning: Failed to parse existing config: {e}")
return None
if non_interactive:
# Default to update mode in non-interactive
print(f"Found existing config at {config_path}")
return existing_config
# Interactive: show current values and ask
print(f"Found existing config at {config_path}")
print("Current configuration:")
for key, value in existing_config.items():
print(f" {key}: {value}")
choice = prompt(
"select",
"Choose an action:",
choices=[
{"name": "Update (keep existing values)", "value": "update"},
{"name": "Start fresh (new config)", "value": "fresh"},
{"name": "Abort", "value": "abort"},
],
)
if choice == "abort":
raise SystemExit(2)
elif choice == "fresh":
return None
else: # update
return existing_config
def detect_configured_hosts(cwd: Path) -> list[tuple[HostConfig, str]]:
"""Scan project + user config files for java-codebase-rag MCP entries.
Args:
cwd: Current working directory (for project-scope configs)
Returns:
List of (host_config, scope) tuples where scope is "project" or "user"
"""
detected = []
# Check all hosts in both project and user scopes
for host_name, host_config in HOSTS.items():
# Check project scope
project_mcp_path = host_config.mcp_config_path("project", cwd)
if _has_java_codebase_rag_entry(project_mcp_path):
detected.append((host_config, "project"))
# Check user scope
user_mcp_path = host_config.mcp_config_path("user", cwd)
if _has_java_codebase_rag_entry(user_mcp_path):
detected.append((host_config, "user"))
return detected
def _has_java_codebase_rag_entry(config_path: Path) -> bool:
"""Check if MCP config file has a java-codebase-rag entry.
Args:
config_path: Path to MCP config file
Returns:
True if file exists and contains java-codebase-rag in mcpServers
"""
if not config_path.is_file():
return False
try:
with open(config_path, "r") as f:
config = json.load(f)
except (json.JSONDecodeError, IOError, OSError):
return False
mcp_servers = config.get("mcpServers", {})
return _MCP_SERVER_NAME in mcp_servers
def refresh_artifacts(
host: HostConfig,
scope: str,
cwd: Path,
*,
force: bool,
dry_run: bool,
) -> list[ArtifactResult]:
"""Overwrite skill and agent files from package data. Skip MCP if entry is correct.
Args:
host: HostConfig for the agent host
scope: Installation scope ("project" or "user")
cwd: Current working directory
force: If True, overwrite all files even if matching
dry_run: If True, print changes without writing
Returns:
List of ArtifactResult objects for each artifact
"""
results = []
# Refresh skill file
skills_dir = host.skills_dir(scope, cwd)
skill_dest = skills_dir / "explore-codebase" / "SKILL.md"
skill_result = _refresh_file(
skill_dest,
"skills/explore-codebase/SKILL.md",
artifact_type="skill",
force=force,
dry_run=dry_run,
)
results.append(skill_result)
# Refresh agent file
agents_dir = host.agents_dir(scope, cwd)
agent_dest = agents_dir / "explorer-rag-enhanced.md"
agent_result = _refresh_file(
agent_dest,
"agents/explorer-rag-enhanced.md",
artifact_type="agent",
force=force,
dry_run=dry_run,
)
results.append(agent_result)
# Refresh MCP config (update command path if needed)
mcp_config_path = host.mcp_config_path(scope, cwd)
mcp_result = _refresh_mcp_config(mcp_config_path, host, force=force, dry_run=dry_run)
results.append(mcp_result)
return results
def _refresh_file(
dest_path: Path,
package_relative_path: str,
*,
artifact_type: str,
force: bool,
dry_run: bool,
) -> ArtifactResult:
"""Refresh a single file from package data.
Args:
dest_path: Destination file path
package_relative_path: Path relative to install_data
artifact_type: Type of artifact (for error messages)
force: If True, overwrite even if matching
dry_run: If True, print without writing
Returns:
ArtifactResult with success status
"""
try:
# Read package data
package_content = _read_package_artifact(package_relative_path)
# Check if file exists
if dest_path.is_file():
existing_content = dest_path.read_text(encoding="utf-8")
# Skip if content matches and not forcing
if package_content == existing_content and not force:
return ArtifactResult(path=dest_path, success=True, error=None)
# Content differs or force mode
if dry_run:
print(f"Would update {artifact_type} file at {dest_path}")
return ArtifactResult(path=dest_path, success=True, error=None)
elif dry_run:
print(f"Would create {artifact_type} file at {dest_path}")
return ArtifactResult(path=dest_path, success=True, error=None)