Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
1184 lines (1045 loc) · 36.5 KB
/
Copy pathcli.py
File metadata and controls
1184 lines (1045 loc) · 36.5 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
import asyncio
import json
import time
from collections.abc import Callable
from fnmatch import fnmatch
from functools import partial
from importlib.metadata import version as get_version
from pathlib import Path
import typer
from loguru import logger
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from . import cgr_state
from . import cli_help as ch
from . import constants as cs
from . import logs as ls
from .config import load_ignore_patterns, settings
from .graph_updater import GraphUpdater
from .main import (
_create_configuration_table,
app_context,
connect_memgraph,
export_graph_to_file,
main_async,
main_optimize_async,
main_single_query,
prompt_for_unignored_directories,
style,
update_model_settings,
)
from .parser_loader import load_parsers
from .services.graph_service import MemgraphIngestor
from .services.protobuf_service import ProtobufFileIngestor
from .stack import StackManager
from .stack.cli import cli as daemon_cli
from .stack.constants import StackState
from .stack.manager import StackError
from .tools.health_checker import HealthChecker
from .tools.language import cli as language_cli
from .types_defs import DeadCodeRow, PropertyValue, ResultRow
from .utils.path_utils import derive_project_name, resolve_repo_path
from .vector_store import delete_project_embeddings
from .workspaces import WorkspaceConfig, WorkspaceError, load_workspace
from .workspaces.cli import cli as workspace_cli
app = typer.Typer(
name=cs.PACKAGE_NAME,
help=ch.APP_DESCRIPTION,
no_args_is_help=True,
add_completion=False,
)
def _version_callback(value: bool) -> None:
if value:
app_context.console.print(
cs.CLI_MSG_VERSION.format(
package=cs.PACKAGE_NAME, version=get_version(cs.PACKAGE_NAME)
),
highlight=False,
)
raise typer.Exit()
def validate_models_early() -> None:
try:
orchestrator_config = settings.active_orchestrator_config
orchestrator_config.validate_api_key(cs.ModelRole.ORCHESTRATOR)
cypher_config = settings.active_cypher_config
cypher_config.validate_api_key(cs.ModelRole.CYPHER)
except ValueError as e:
app_context.console.print(style(str(e), cs.Color.RED))
raise typer.Exit(1) from e
def _update_and_validate_models(orchestrator: str | None, cypher: str | None) -> None:
try:
update_model_settings(orchestrator, cypher)
except ValueError as e:
app_context.console.print(style(str(e), cs.Color.RED))
raise typer.Exit(1) from e
validate_models_early()
@app.callback()
def _global_options(
version: bool | None = typer.Option(
None,
"--version",
"-v",
help=ch.HELP_VERSION,
callback=_version_callback,
is_eager=True,
),
quiet: bool = typer.Option(
False,
"--quiet",
"-q",
help="Suppress non-essential output (progress messages, banners, informational logs).",
is_eager=True,
),
) -> None:
settings.QUIET = quiet
if quiet:
logger.remove()
logger.add(lambda msg: app_context.console.print(msg, end=""), level="ERROR")
def _info(msg: str) -> None:
if not settings.QUIET:
app_context.console.print(msg)
def _load_workspace_or_exit(workspace: str | None) -> WorkspaceConfig | None:
if workspace is None:
return None
try:
return load_workspace(workspace)
except WorkspaceError as e:
app_context.console.print(style(str(e), cs.Color.RED))
raise typer.Exit(1) from e
def _sync_workspace(
config: WorkspaceConfig,
batch_size: int,
exclude: list[str] | None,
) -> None:
total = len(config.repos)
if total == 0:
_info(
style(cs.CLI_MSG_WORKSPACE_EMPTY.format(name=config.name), cs.Color.YELLOW)
)
return
_info(
style(
cs.CLI_MSG_WORKSPACE_SYNCING.format(name=config.name, count=total),
cs.Color.CYAN,
)
)
for idx, repo in enumerate(config.repos, start=1):
repo_path = repo.repo_path()
_info(
style(
cs.CLI_MSG_WORKSPACE_SYNC_REPO.format(
idx=idx,
total=total,
path=repo_path,
project_name=repo.project_name,
),
cs.Color.CYAN,
)
)
_run_graph_sync(
repo=repo_path,
project_name=repo.project_name,
batch_size=batch_size,
exclude=exclude,
interactive_setup=False,
)
def _resolve_active_projects(projects: str | None, default_project: str) -> list[str]:
if projects:
parsed = [p.strip() for p in projects.split(",") if p.strip()]
if parsed:
return parsed
return [default_project]
def _maybe_start_stack() -> None:
mgr = StackManager()
if mgr.status().state == StackState.RUNNING:
return
try:
mgr.ensure_running()
except StackError as e:
app_context.console.print(style(str(e), cs.Color.RED))
raise typer.Exit(1) from e
def _run_graph_sync(
repo: Path,
project_name: str,
batch_size: int,
exclude: list[str] | None,
interactive_setup: bool,
clean: bool = False,
output: str | None = None,
) -> None:
cgrignore = load_ignore_patterns(repo)
cli_excludes = frozenset(exclude) if exclude else frozenset()
exclude_paths = cli_excludes | cgrignore.exclude or None
unignore_paths: frozenset[str] | None
if interactive_setup:
unignore_paths = prompt_for_unignored_directories(repo, exclude)
else:
unignore_paths = cgrignore.unignore or None
elapsed = time.monotonic()
with connect_memgraph(batch_size) as ingestor:
if clean:
_info(style(cs.CLI_MSG_CLEANING_DB, cs.Color.YELLOW))
ingestor.clean_database()
_delete_hash_cache(repo)
ingestor.ensure_constraints()
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=ingestor,
repo_path=repo,
parsers=parsers,
queries=queries,
unignore_paths=unignore_paths,
exclude_paths=exclude_paths,
project_name=project_name,
)
updater.run()
cgr_state.record_sync(project_name)
if output:
_info(style(cs.CLI_MSG_EXPORTING_TO.format(path=output), cs.Color.CYAN))
if not export_graph_to_file(ingestor, output):
raise typer.Exit(1)
elapsed = time.monotonic() - elapsed
if updater.skipped_because_in_sync:
app_context.console.print(
style(
cs.CLI_MSG_SYNC_SKIPPED.format(project=project_name, elapsed=elapsed),
cs.Color.CYAN,
cs.StyleModifier.DIM,
)
)
else:
app_context.console.print(
style(
cs.CLI_MSG_SYNC_DONE.format(project=project_name, elapsed=elapsed),
cs.Color.CYAN,
cs.StyleModifier.NONE,
)
)
def _delete_hash_cache(repo_path: Path) -> None:
cache_path = repo_path / cs.HASH_CACHE_FILENAME
if cache_path.exists():
_info(
style(
cs.CLI_MSG_CLEANING_HASH_CACHE.format(path=cache_path),
cs.Color.YELLOW,
)
)
cache_path.unlink(missing_ok=True)
dir_mtimes_path = repo_path / cs.DIR_MTIMES_FILENAME
dir_mtimes_path.unlink(missing_ok=True)
def _resolve_and_validate_repo(repo_path: str | None) -> Path:
resolved = resolve_repo_path(repo_path, settings.TARGET_REPO_PATH)
if not resolved.exists():
app_context.console.print(
style(cs.CLI_ERR_PATH_NOT_EXISTS.format(path=resolved), cs.Color.RED)
)
raise typer.Exit(1)
if not resolved.is_dir():
app_context.console.print(
style(cs.CLI_ERR_PATH_NOT_DIR.format(path=resolved), cs.Color.RED)
)
raise typer.Exit(1)
if not (resolved / cs.GIT_DIR_NAME).exists():
app_context.console.print(
style(cs.CLI_WARN_NOT_GIT_REPO.format(path=resolved), cs.Color.YELLOW)
)
return resolved
def _cleanup_project_embeddings(ingestor: MemgraphIngestor, project_name: str) -> None:
rows = ingestor.fetch_all(
cs.CYPHER_QUERY_PROJECT_NODE_IDS,
{cs.KEY_PROJECT_NAME: project_name},
)
node_ids: list[int] = []
for row in rows:
node_id = row.get(cs.KEY_NODE_ID)
if isinstance(node_id, int):
node_ids.append(node_id)
delete_project_embeddings(project_name, node_ids)
@app.command(help=ch.CMD_START)
def start(
repo_path: str | None = typer.Option(
None, "--repo-path", help=ch.HELP_REPO_PATH_RETRIEVAL
),
update_graph: bool = typer.Option(
False,
"--update-graph",
help=ch.HELP_UPDATE_GRAPH,
),
clean: bool = typer.Option(
False,
"--clean",
help=ch.HELP_CLEAN_DB,
),
output: str | None = typer.Option(
None,
"-o",
"--output",
help=ch.HELP_OUTPUT_GRAPH,
),
orchestrator: str | None = typer.Option(
None,
"--orchestrator",
help=ch.HELP_ORCHESTRATOR,
),
cypher: str | None = typer.Option(
None,
"--cypher",
help=ch.HELP_CYPHER_MODEL,
),
no_confirm: bool = typer.Option(
False,
"--no-confirm",
help=ch.HELP_NO_CONFIRM,
),
no_instructions: bool = typer.Option(
False,
"--no-instructions",
help=ch.HELP_NO_INSTRUCTIONS,
),
batch_size: int | None = typer.Option(
None,
"--batch-size",
min=1,
help=ch.HELP_BATCH_SIZE,
),
project_name: str | None = typer.Option(
None,
"--project-name",
help=ch.HELP_PROJECT_NAME,
),
exclude: list[str] | None = typer.Option(
None,
"--exclude",
help=ch.HELP_EXCLUDE_PATTERNS,
),
interactive_setup: bool = typer.Option(
False,
"--interactive-setup",
help=ch.HELP_INTERACTIVE_SETUP,
),
ask_agent: str | None = typer.Option(
None,
"-a",
"--ask-agent",
help=ch.HELP_ASK_AGENT,
),
output_format: cs.QueryFormat = typer.Option(
cs.QueryFormat.TABLE,
"--output-format",
help=ch.HELP_QUERY_OUTPUT_FORMAT,
),
no_start_stack: bool = typer.Option(
False,
"--no-start-stack",
help=ch.HELP_NO_START_STACK,
),
no_sync: bool = typer.Option(
False,
"--no-sync",
help=ch.HELP_NO_SYNC,
),
projects: str | None = typer.Option(
None,
"--projects",
help=ch.HELP_PROJECTS,
),
workspace: str | None = typer.Option(
None,
"--workspace",
help=ch.HELP_WORKSPACE,
),
) -> None:
app_context.session.confirm_edits = not no_confirm
app_context.session.load_cgr_instructions = not no_instructions
if output_format == cs.QueryFormat.JSON and not ask_agent:
app_context.console.print(
style(cs.CLI_ERR_JSON_REQUIRES_ASK_AGENT, cs.Color.RED)
)
raise typer.Exit(1)
resolved_repo = _resolve_and_validate_repo(repo_path)
target_repo_path = str(resolved_repo)
resolved_project_name = project_name or derive_project_name(resolved_repo)
if output and not update_graph:
app_context.console.print(
style(cs.CLI_ERR_OUTPUT_REQUIRES_UPDATE, cs.Color.RED)
)
raise typer.Exit(1)
if not no_start_stack:
_maybe_start_stack()
effective_batch_size = settings.resolve_batch_size(batch_size)
if clean and not update_graph:
repo_to_clean = Path(target_repo_path)
with connect_memgraph(effective_batch_size) as ingestor:
_info(style(cs.CLI_MSG_CLEANING_DB, cs.Color.YELLOW))
ingestor.clean_database()
_delete_hash_cache(repo_to_clean)
_info(style(cs.CLI_MSG_CLEAN_DONE, cs.Color.GREEN))
return
_update_and_validate_models(orchestrator, cypher)
if not ask_agent and not update_graph:
app_context.console.print(_create_configuration_table(target_repo_path))
if update_graph:
_info(
style(cs.CLI_MSG_UPDATING_GRAPH.format(path=resolved_repo), cs.Color.GREEN)
)
if not interactive_setup:
_info(style(cs.CLI_MSG_AUTO_EXCLUDE, cs.Color.YELLOW))
_run_graph_sync(
repo=resolved_repo,
project_name=resolved_project_name,
batch_size=effective_batch_size,
exclude=exclude,
interactive_setup=interactive_setup,
clean=clean,
output=output,
)
_info(style(cs.CLI_MSG_GRAPH_UPDATED, cs.Color.GREEN))
return
workspace_config = _load_workspace_or_exit(workspace)
sync_task: Callable[[], None] | None = None
sync_message = cs.MSG_SYNCING_KNOWLEDGE_GRAPH
if not no_sync:
if workspace_config is not None:
sync_task = partial(
_sync_workspace, workspace_config, effective_batch_size, exclude
)
sync_message = cs.MSG_SYNCING_WORKSPACE.format(
name=workspace_config.name, count=len(workspace_config.repos)
)
else:
sync_task = partial(
_run_graph_sync,
repo=resolved_repo,
project_name=resolved_project_name,
batch_size=effective_batch_size,
exclude=exclude,
interactive_setup=interactive_setup,
)
if workspace_config is not None:
active_projects = workspace_config.project_names()
if projects:
active_projects = _resolve_active_projects(projects, active_projects[0])
else:
active_projects = _resolve_active_projects(projects, resolved_project_name)
try:
if ask_agent:
if sync_task is not None:
sync_task()
main_single_query(
target_repo_path,
effective_batch_size,
ask_agent,
active_projects=active_projects,
output_format=output_format,
)
else:
asyncio.run(
main_async(
target_repo_path,
effective_batch_size,
active_projects=active_projects,
show_config_table=False,
pre_chat_sync=sync_task,
pre_chat_sync_message=sync_message,
)
)
except KeyboardInterrupt:
app_context.console.print(style(cs.CLI_MSG_APP_TERMINATED, cs.Color.RED))
except ValueError as e:
app_context.console.print(
style(cs.CLI_ERR_STARTUP.format(error=e), cs.Color.RED)
)
@app.command(help=ch.CMD_INDEX)
def index(
repo_path: str | None = typer.Option(
None, "--repo-path", help=ch.HELP_REPO_PATH_INDEX
),
output_proto_dir: str = typer.Option(
...,
"-o",
"--output-proto-dir",
help=ch.HELP_OUTPUT_PROTO_DIR,
),
split_index: bool = typer.Option(
False,
"--split-index",
help=ch.HELP_SPLIT_INDEX,
),
exclude: list[str] | None = typer.Option(
None,
"--exclude",
help=ch.HELP_EXCLUDE_PATTERNS,
),
interactive_setup: bool = typer.Option(
False,
"--interactive-setup",
help=ch.HELP_INTERACTIVE_SETUP,
),
) -> None:
repo_to_index = _resolve_and_validate_repo(repo_path)
_info(style(cs.CLI_MSG_INDEXING_AT.format(path=repo_to_index), cs.Color.GREEN))
_info(style(cs.CLI_MSG_OUTPUT_TO.format(path=output_proto_dir), cs.Color.CYAN))
cgrignore = load_ignore_patterns(repo_to_index)
cli_excludes = frozenset(exclude) if exclude else frozenset()
exclude_paths = cli_excludes | cgrignore.exclude or None
unignore_paths: frozenset[str] | None = None
if interactive_setup:
unignore_paths = prompt_for_unignored_directories(repo_to_index, exclude)
else:
_info(style(cs.CLI_MSG_AUTO_EXCLUDE, cs.Color.YELLOW))
unignore_paths = cgrignore.unignore or None
try:
ingestor = ProtobufFileIngestor(
output_path=output_proto_dir, split_index=split_index
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=ingestor,
repo_path=repo_to_index,
parsers=parsers,
queries=queries,
unignore_paths=unignore_paths,
exclude_paths=exclude_paths,
)
updater.run()
_info(style(cs.CLI_MSG_INDEXING_DONE, cs.Color.GREEN))
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_INDEXING.format(error=e), cs.Color.RED)
)
logger.exception(ls.INDEXING_FAILED)
raise typer.Exit(1) from e
@app.command(help=ch.CMD_EXPORT)
def export(
output: str = typer.Option(..., "-o", "--output", help=ch.HELP_OUTPUT_PATH),
format_json: bool = typer.Option(
True, "--json/--no-json", help=ch.HELP_FORMAT_JSON
),
batch_size: int | None = typer.Option(
None,
"--batch-size",
min=1,
help=ch.HELP_BATCH_SIZE,
),
) -> None:
if not format_json:
app_context.console.print(style(cs.CLI_ERR_ONLY_JSON, cs.Color.RED))
raise typer.Exit(1)
_info(style(cs.CLI_MSG_CONNECTING_MEMGRAPH, cs.Color.CYAN))
effective_batch_size = settings.resolve_batch_size(batch_size)
try:
with connect_memgraph(effective_batch_size) as ingestor:
_info(style(cs.CLI_MSG_EXPORTING_DATA, cs.Color.CYAN))
if not export_graph_to_file(ingestor, output):
raise typer.Exit(1)
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_EXPORT_FAILED.format(error=e), cs.Color.RED)
)
logger.exception(ls.EXPORT_ERROR.format(error=e))
raise typer.Exit(1) from e
@app.command(help=ch.CMD_OPTIMIZE)
def optimize(
language: str = typer.Argument(
...,
help=ch.HELP_LANGUAGE_ARG,
),
repo_path: str | None = typer.Option(
None, "--repo-path", help=ch.HELP_REPO_PATH_OPTIMIZE
),
reference_document: str | None = typer.Option(
None,
"--reference-document",
help=ch.HELP_REFERENCE_DOC,
),
orchestrator: str | None = typer.Option(
None,
"--orchestrator",
help=ch.HELP_ORCHESTRATOR,
),
cypher: str | None = typer.Option(
None,
"--cypher",
help=ch.HELP_CYPHER_MODEL,
),
no_confirm: bool = typer.Option(
False,
"--no-confirm",
help=ch.HELP_NO_CONFIRM,
),
no_instructions: bool = typer.Option(
False,
"--no-instructions",
help=ch.HELP_NO_INSTRUCTIONS,
),
batch_size: int | None = typer.Option(
None,
"--batch-size",
min=1,
help=ch.HELP_BATCH_SIZE,
),
) -> None:
app_context.session.confirm_edits = not no_confirm
app_context.session.load_cgr_instructions = not no_instructions
target_repo_path = str(_resolve_and_validate_repo(repo_path))
_update_and_validate_models(orchestrator, cypher)
try:
asyncio.run(
main_optimize_async(
language,
target_repo_path,
reference_document,
orchestrator,
cypher,
batch_size,
)
)
except KeyboardInterrupt:
app_context.console.print(style(cs.CLI_MSG_APP_TERMINATED, cs.Color.RED))
except ValueError as e:
app_context.console.print(
style(cs.CLI_ERR_STARTUP.format(error=e), cs.Color.RED)
)
@app.command(name=ch.CLICommandName.MCP_SERVER, help=ch.CMD_MCP_SERVER)
def mcp_server(
transport: cs.MCPTransport = typer.Option(
cs.MCPTransport.STDIO, help=ch.HELP_MCP_TRANSPORT
),
host: str = typer.Option(None, help=ch.HELP_MCP_HTTP_HOST),
port: int = typer.Option(None, help=ch.HELP_MCP_HTTP_PORT),
) -> None:
try:
if transport == cs.MCPTransport.HTTP:
from codebase_rag.mcp import serve_http
resolved_host = host or settings.MCP_HTTP_HOST
resolved_port = port or settings.MCP_HTTP_PORT
asyncio.run(serve_http(host=resolved_host, port=resolved_port))
else:
from codebase_rag.mcp import serve_stdio
asyncio.run(serve_stdio())
except KeyboardInterrupt:
app_context.console.print(style(cs.CLI_MSG_APP_TERMINATED, cs.Color.RED))
except ValueError as e:
app_context.console.print(
style(cs.CLI_ERR_CONFIG.format(error=e), cs.Color.RED)
)
_info(style(cs.CLI_MSG_HINT_TARGET_REPO, cs.Color.YELLOW))
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_MCP_SERVER.format(error=e), cs.Color.RED)
)
@app.command(name=ch.CLICommandName.GRAPH_LOADER, help=ch.CMD_GRAPH_LOADER)
def graph_loader_command(
graph_file: str = typer.Argument(..., help=ch.HELP_GRAPH_FILE),
) -> None:
from .graph_loader import load_graph
try:
graph = load_graph(graph_file)
summary = graph.summary()
app_context.console.print(style(cs.CLI_MSG_GRAPH_SUMMARY, cs.Color.GREEN))
app_context.console.print(f" Total nodes: {summary['total_nodes']}")
app_context.console.print(
f" Total relationships: {summary['total_relationships']}"
)
app_context.console.print(
f" Node types: {list(summary['node_labels'].keys())}"
)
app_context.console.print(
f" Relationship types: {list(summary['relationship_types'].keys())}"
)
app_context.console.print(
f" Exported at: {summary['metadata']['exported_at']}"
)
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_LOAD_GRAPH.format(error=e), cs.Color.RED)
)
raise typer.Exit(1) from e
@app.command(
name=ch.CLICommandName.LANGUAGE,
help=ch.CMD_LANGUAGE,
context_settings={"allow_extra_args": True, "allow_interspersed_args": False},
)
def language_command(ctx: typer.Context) -> None:
language_cli(ctx.args, standalone_mode=False)
@app.command(
name=ch.CLICommandName.DAEMON,
help=ch.CMD_DAEMON,
context_settings={"allow_extra_args": True, "allow_interspersed_args": False},
)
def daemon_command(ctx: typer.Context) -> None:
daemon_cli(ctx.args, standalone_mode=False)
@app.command(
name=ch.CLICommandName.WORKSPACE,
help=ch.CMD_WORKSPACE,
context_settings={"allow_extra_args": True, "allow_interspersed_args": False},
)
def workspace_command(ctx: typer.Context) -> None:
workspace_cli(ctx.args, standalone_mode=False)
@app.command(name=ch.CLICommandName.STOP, help=ch.CMD_STOP)
def stop_command() -> None:
mgr = StackManager()
try:
mgr.down()
except StackError as e:
app_context.console.print(style(str(e), cs.Color.RED))
raise typer.Exit(1) from e
_info(style("stack stopped", cs.Color.GREEN))
@app.command(name=ch.CLICommandName.STATUS, help=ch.CMD_STATUS)
def status_command() -> None:
status = StackManager().status()
app_context.console.print(
f"stack: {status.state.value} "
f"(memgraph={status.memgraph_endpoint} reachable={status.memgraph_reachable}, "
f"qdrant={status.qdrant_endpoint} reachable={status.qdrant_reachable})"
)
app_context.console.print(f"compose: {status.compose_file}")
timestamps = cgr_state.read_sync_timestamps()
if not timestamps:
app_context.console.print("syncs: (no projects synced via cgr yet)")
return
app_context.console.print("syncs:")
for project, ts in sorted(timestamps.items()):
app_context.console.print(f" - {project}: last sync {ts}")
@app.command(name=ch.CLICommandName.DOCTOR, help=ch.CMD_DOCTOR)
def doctor() -> None:
checker = HealthChecker()
results = checker.run_all_checks()
passed, total = checker.get_summary()
table = Table(show_header=False, box=None, padding=(0, 2))
table.add_column(style="cyan", no_wrap=False)
for result in results:
status = "✓" if result.passed else "✗"
status_color = cs.Color.GREEN if result.passed else cs.Color.RED
status_text = style(status, status_color, cs.StyleModifier.NONE)
check_name = f"{status_text} {result.name}"
table.add_row(check_name)
panel = Panel(
table,
title="Health Check",
border_style="dim",
padding=(1, 2),
)
app_context.console.print(panel)
app_context.console.print()
summary_text = f"{passed}/{total} checks passed"
if passed == total:
app_context.console.print(style(summary_text, cs.Color.GREEN))
else:
app_context.console.print(style(summary_text, cs.Color.YELLOW))
failed_checks = [r for r in results if not r.passed and r.error]
if failed_checks:
app_context.console.print()
app_context.console.print(style("Failed checks details:", cs.Color.YELLOW))
for result in failed_checks:
error_msg = f" {result.name}: {result.error}"
app_context.console.print(
style(error_msg, cs.Color.YELLOW, cs.StyleModifier.NONE)
)
if passed < total:
raise typer.Exit(1)
def _build_stats_table(
title: str,
col_label: str,
rows: list[ResultRow],
get_label: Callable[[ResultRow], str],
total_label: str,
) -> Table:
table = Table(
title=style(title, cs.Color.GREEN),
show_header=True,
header_style=f"{cs.StyleModifier.BOLD} {cs.Color.MAGENTA}",
)
table.add_column(col_label, style=cs.Color.CYAN)
table.add_column(cs.CLI_STATS_COL_COUNT, style=cs.Color.YELLOW, justify="right")
total = 0
for row in rows:
raw_count = row.get("count", 0)
count = int(raw_count) if isinstance(raw_count, int | float) else 0
total += count
table.add_row(get_label(row), f"{count:,}")
table.add_section()
table.add_row(
style(total_label, cs.Color.GREEN),
style(f"{total:,}", cs.Color.GREEN),
)
return table
@app.command(name=ch.CLICommandName.STATS, help=ch.CMD_STATS)
def stats() -> None:
from .cypher_queries import (
CYPHER_STATS_NODE_COUNTS,
CYPHER_STATS_RELATIONSHIP_COUNTS,
)
app_context.console.print(style(cs.CLI_MSG_CONNECTING_STATS, cs.Color.CYAN))
try:
with connect_memgraph(batch_size=1) as ingestor:
node_results = ingestor.fetch_all(CYPHER_STATS_NODE_COUNTS)
rel_results = ingestor.fetch_all(CYPHER_STATS_RELATIONSHIP_COUNTS)
app_context.console.print(
_build_stats_table(
cs.CLI_STATS_NODE_TITLE,
cs.CLI_STATS_COL_NODE_TYPE,
node_results,
lambda r: ":".join(r.get("labels", [])) or cs.CLI_STATS_UNKNOWN,
cs.CLI_STATS_TOTAL_NODES,
)
)
app_context.console.print()
app_context.console.print(
_build_stats_table(
cs.CLI_STATS_REL_TITLE,
cs.CLI_STATS_COL_REL_TYPE,
rel_results,
lambda r: str(r.get("type", cs.CLI_STATS_UNKNOWN)),
cs.CLI_STATS_TOTAL_RELS,
)
)
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_STATS_FAILED.format(error=e), cs.Color.RED)
)
logger.exception(ls.STATS_ERROR.format(error=e))
raise typer.Exit(1) from e
def _resolve_dead_code_project(
project_name: str | None, projects: list[str]
) -> str | None:
if project_name:
return project_name.strip()
if len(projects) == 1:
return projects[0]
return None
def _dead_code_params(
project_name: str,
entry_points: list[str],
decorator_roots: list[str],
) -> dict[str, PropertyValue]:
root_decorators = sorted(
{d.lower() for d in cs.DEFAULT_ROOT_DECORATORS}
| {d.lower() for d in decorator_roots}
)
# (H) test_patterns is always passed: with tests included it makes test
# (H) functions roots; with tests excluded it filters test modules out of the
# (H) module-load root clause so test-only code is not kept alive.
return {
"project_prefix": f"{project_name}{cs.SEPARATOR_DOT}",
"root_decorators": root_decorators,
"entry_points": list(entry_points),
"test_patterns": list(cs.TEST_PATH_PATTERNS),
}
def _filter_excluded_rows(rows: list[ResultRow], exclude: list[str]) -> list[ResultRow]:
# (H) Drop candidates whose file path matches an exclude glob (generated dirs
# (H) like client/core or *.gen.* have no in-repo caller, so every symbol
# (H) reports as dead). fnmatch treats '*' as spanning '/', so '*client/core*'
# (H) matches at any depth.
if not exclude:
return rows
return [
row
for row in rows
if not any(
fnmatch(str(row.get(cs.KEY_PATH) or ""), pattern) for pattern in exclude
)
]
def _to_dead_code_row(row: ResultRow) -> DeadCodeRow:
start = row.get(cs.KEY_START_LINE, 0)
end = row.get(cs.KEY_END_LINE, 0)
return DeadCodeRow(
label=str(row.get(cs.KEY_LABEL, "")),
name=str(row.get(cs.KEY_NAME, "")),
qualified_name=str(row.get(cs.KEY_QUALIFIED_NAME, "")),
start_line=int(start) if isinstance(start, int | float) else 0,
end_line=int(end) if isinstance(end, int | float) else 0,
)
def _build_dead_code_table(candidates: list[DeadCodeRow], project_name: str) -> Table:
table = Table(
title=style(
cs.CLI_DEADCODE_TABLE_TITLE.format(project_name=project_name),
cs.Color.GREEN,
),
show_header=True,
header_style=f"{cs.StyleModifier.BOLD} {cs.Color.MAGENTA}",
)
table.add_column(cs.CLI_DEADCODE_COL_KIND, style=cs.Color.MAGENTA)
table.add_column(cs.CLI_DEADCODE_COL_QUALIFIED_NAME, style=cs.Color.CYAN)
table.add_column(cs.CLI_DEADCODE_COL_LINES, style=cs.Color.YELLOW, justify="right")
for row in candidates:
table.add_row(
row["label"],
row["qualified_name"],
cs.CLI_DEADCODE_LINE_RANGE.format(
start=row["start_line"], end=row["end_line"]
),
)
return table
def _emit_dead_code(
candidates: list[DeadCodeRow],
output_format: cs.DeadCodeFormat,
output: Path | None,
project_name: str,