codegraph-engine 2.3.0__py3-none-any.whl → 3.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. codegraph/__init__.py +1 -1
  2. codegraph/__main__.py +7 -0
  3. codegraph/agent_brain.py +253 -2
  4. codegraph/agent_capabilities.py +1348 -67
  5. codegraph/agent_rules.py +2 -1
  6. codegraph/api_drift.py +455 -0
  7. codegraph/architecture_rules.py +123 -0
  8. codegraph/async_queue/__init__.py +50 -0
  9. codegraph/async_queue/detectors/__init__.py +48 -0
  10. codegraph/async_queue/detectors/celery.py +160 -0
  11. codegraph/async_queue/detectors/kafka.py +168 -0
  12. codegraph/async_queue/detectors/rabbitmq.py +116 -0
  13. codegraph/async_queue/detectors/redis.py +130 -0
  14. codegraph/async_queue/detectors/sqs.py +135 -0
  15. codegraph/async_queue/models.py +161 -0
  16. codegraph/async_queue/otel_models.py +74 -0
  17. codegraph/async_queue/otel_parser.py +337 -0
  18. codegraph/async_queue/reconciler.py +427 -0
  19. codegraph/async_queue/scanner.py +291 -0
  20. codegraph/async_queue/traversal.py +447 -0
  21. codegraph/change_impact.py +320 -110
  22. codegraph/changelog.py +170 -0
  23. codegraph/cli.py +1605 -62
  24. codegraph/cli_output.py +17 -2
  25. codegraph/context.py +135 -24
  26. codegraph/context_freshness.py +2 -0
  27. codegraph/database/__init__.py +14 -0
  28. codegraph/database/extractor.py +712 -17
  29. codegraph/database/interrogation.py +388 -2
  30. codegraph/database/schema_drift.py +862 -0
  31. codegraph/dataflow_propagation.py +118 -0
  32. codegraph/dead_code.py +387 -0
  33. codegraph/epistemic.py +15 -0
  34. codegraph/evidence_contract.py +34 -3
  35. codegraph/federation.py +245 -0
  36. codegraph/frameworks.py +234 -12
  37. codegraph/frameworks_nestjs.py +502 -0
  38. codegraph/frameworks_nextjs.py +337 -0
  39. codegraph/frameworks_react.py +457 -0
  40. codegraph/freshness.py +2 -0
  41. codegraph/frontend_html.py +109 -0
  42. codegraph/git.py +2 -0
  43. codegraph/git_state.py +2 -0
  44. codegraph/graph/traversal.py +150 -7
  45. codegraph/graph_csr.py +218 -0
  46. codegraph/incremental.py +150 -0
  47. codegraph/indexing/__init__.py +7 -1
  48. codegraph/indexing/classifier.py +5 -0
  49. codegraph/indexing/indexer.py +292 -38
  50. codegraph/indexing/languages/__init__.py +1 -0
  51. codegraph/indexing/languages/cpp.py +457 -0
  52. codegraph/indexing/languages/go.py +459 -0
  53. codegraph/indexing/languages/jvm.py +583 -0
  54. codegraph/indexing/languages/rust.py +507 -0
  55. codegraph/indexing/models.py +15 -1
  56. codegraph/indexing/parser.py +385 -9
  57. codegraph/indexing/pool.py +136 -0
  58. codegraph/indexing/protocols.py +220 -0
  59. codegraph/indexing/scanner.py +23 -0
  60. codegraph/indexing/templates.py +418 -0
  61. codegraph/interrogation.py +207 -39
  62. codegraph/lsp.py +318 -0
  63. codegraph/lsp_bridge/__init__.py +16 -0
  64. codegraph/lsp_bridge/bridge.py +102 -0
  65. codegraph/lsp_bridge/client.py +207 -0
  66. codegraph/lsp_bridge/models.py +71 -0
  67. codegraph/mcp/server.py +502 -29
  68. codegraph/memory/trajectory.py +282 -0
  69. codegraph/models.py +7 -0
  70. codegraph/monorepo.py +3 -0
  71. codegraph/multi_agent/__init__.py +13 -0
  72. codegraph/multi_agent/coordinator.py +229 -0
  73. codegraph/multi_agent/models.py +76 -0
  74. codegraph/optimizer.py +42 -5
  75. codegraph/polymorphism.py +95 -0
  76. codegraph/pr_review.py +296 -0
  77. codegraph/process_lifecycle.py +50 -12
  78. codegraph/reachability.py +198 -0
  79. codegraph/reachability_index.py +74 -0
  80. codegraph/refactor/__init__.py +48 -0
  81. codegraph/refactor/models.py +114 -0
  82. codegraph/refactor/patcher.py +348 -0
  83. codegraph/refactor/renamer.py +844 -0
  84. codegraph/refactor/transactions.py +414 -0
  85. codegraph/repair.py +233 -0
  86. codegraph/resolver.py +1357 -161
  87. codegraph/retrieval_policy.py +22 -1
  88. codegraph/roblox.py +2174 -0
  89. codegraph/route_composer.py +7 -0
  90. codegraph/route_topology.py +172 -0
  91. codegraph/runtime/__init__.py +25 -0
  92. codegraph/runtime/collector.py +155 -0
  93. codegraph/runtime/db_watcher.py +191 -0
  94. codegraph/runtime/ingestor.py +30 -10
  95. codegraph/runtime/otel_receiver.py +208 -0
  96. codegraph/runtime/port_inspector.py +304 -0
  97. codegraph/runtime/runner.py +155 -6
  98. codegraph/runtime/trace_linker.py +175 -0
  99. codegraph/sandbox.py +215 -0
  100. codegraph/search/hybrid.py +26 -0
  101. codegraph/security/supply_chain.py +188 -0
  102. codegraph/security/taint.py +421 -0
  103. codegraph/semantic_decorators.py +34 -3
  104. codegraph/structural_diff.py +2 -0
  105. codegraph/styles.py +144 -0
  106. codegraph/symbol_history.py +2 -0
  107. codegraph/test_gen.py +437 -0
  108. codegraph/tsconfig.py +236 -0
  109. codegraph/ui/__init__.py +6 -0
  110. codegraph/ui/server.py +876 -0
  111. codegraph/watcher.py +323 -0
  112. {codegraph_engine-2.3.0.dist-info → codegraph_engine-3.0.1.dist-info}/METADATA +365 -67
  113. codegraph_engine-3.0.1.dist-info/RECORD +164 -0
  114. {codegraph_engine-2.3.0.dist-info → codegraph_engine-3.0.1.dist-info}/WHEEL +1 -1
  115. codegraph_engine-2.3.0.dist-info/RECORD +0 -94
  116. {codegraph_engine-2.3.0.dist-info → codegraph_engine-3.0.1.dist-info}/entry_points.txt +0 -0
  117. {codegraph_engine-2.3.0.dist-info → codegraph_engine-3.0.1.dist-info}/licenses/LICENSE +0 -0
  118. {codegraph_engine-2.3.0.dist-info → codegraph_engine-3.0.1.dist-info}/top_level.txt +0 -0
codegraph/cli.py CHANGED
@@ -2,8 +2,9 @@ from __future__ import annotations
2
2
 
3
3
  import json
4
4
  import sqlite3
5
+ import sys
5
6
  from pathlib import Path
6
- from typing import Annotated
7
+ from typing import Annotated, Any
7
8
 
8
9
  import typer
9
10
 
@@ -54,7 +55,14 @@ def main(
54
55
  ] = False,
55
56
  ) -> None:
56
57
  """Evidence-backed local codebase intelligence for MCP clients and AI agents."""
57
- pass
58
+ if sys.platform == "win32":
59
+ try:
60
+ if hasattr(sys.stdout, "reconfigure"):
61
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
62
+ if hasattr(sys.stderr, "reconfigure"):
63
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
64
+ except Exception:
65
+ pass
58
66
 
59
67
 
60
68
  def _resolve_repo(
@@ -232,11 +240,73 @@ def init(
232
240
  typer.echo(f"Initialized CodeGraph repository at {target_repo.resolve()} (indexed {indexed_cnt} files)")
233
241
 
234
242
 
243
+ @app.command()
244
+ def watch(
245
+ path: Annotated[Path | None, typer.Argument(help="Repository path to watch (default: current directory)")] = None,
246
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
247
+ debounce_ms: Annotated[int, typer.Option("--debounce", "--debounce-ms", help="Debounce delay in milliseconds")] = 250,
248
+ quiet: Annotated[bool, typer.Option("--quiet", "-q", help="Suppress real-time change logs")] = False,
249
+ verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Show verbose reindex logs")] = False,
250
+ ) -> None:
251
+ """Watch repository for changes and update index in real-time (< 15ms per file)."""
252
+ target_repo = _resolve_repo(path, repository)
253
+ from codegraph.watcher import RepositoryWatcher
254
+
255
+ def _on_batch_complete(res: dict[str, Any]) -> None:
256
+ if quiet:
257
+ return
258
+ reindexed = res.get("reindexed", [])
259
+ deleted = res.get("deleted", [])
260
+ skipped = res.get("skipped", [])
261
+ ms = res.get("elapsed_ms", 0.0)
262
+ gen = res.get("generation")
263
+ gen_str = f" [gen {gen}]" if gen is not None else ""
264
+
265
+ parts: list[str] = []
266
+ if reindexed:
267
+ parts.append(f"reindexed {len(reindexed)} file(s): {', '.join(str(p) for p in reindexed[:3])}{'...' if len(reindexed) > 3 else ''}")
268
+ if deleted:
269
+ parts.append(f"removed {len(deleted)} file(s): {', '.join(str(p) for p in deleted[:3])}{'...' if len(deleted) > 3 else ''}")
270
+ if verbose and skipped:
271
+ parts.append(f"skipped {len(skipped)} unchanged file(s)")
272
+
273
+ if parts:
274
+ typer.echo(f"[WATCH] {'; '.join(parts)} in {ms:.1f}ms{gen_str}")
275
+ elif verbose:
276
+ typer.echo(f"[WATCH] Clean flush in {ms:.1f}ms{gen_str}")
277
+
278
+ typer.echo(f"Watching {target_repo.resolve()} for changes (debounce {debounce_ms}ms)... Press Ctrl+C to stop.")
279
+ watcher = RepositoryWatcher(
280
+ target_repo,
281
+ debounce_delay_sec=debounce_ms / 1000.0,
282
+ on_batch_complete=_on_batch_complete,
283
+ )
284
+ watcher.run_forever()
285
+
286
+
287
+ @app.command()
288
+ def ui(
289
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
290
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
291
+ port: Annotated[int, typer.Option("--port", "-p", help="Port for UI dashboard")] = 8765,
292
+ host: Annotated[str, typer.Option("--host", help="Host interface")] = "127.0.0.1",
293
+ no_browser: Annotated[bool, typer.Option("--no-browser", help="Do not automatically open browser")] = False,
294
+ ) -> None:
295
+ """Launch the interactive CodeGraph Knowledge Graph and UI Dashboard in your browser."""
296
+ target_repo = _resolve_repo(path, repository)
297
+ from codegraph.ui import start_ui_server
298
+
299
+ start_ui_server(target_repo, host=host, port=port, open_browser=not no_browser)
300
+
301
+
235
302
  @app.command()
236
303
  def search(
237
304
  query: str,
238
305
  repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
239
306
  top_k: int = 10,
307
+ ext: Annotated[str | None, typer.Option("--ext", "-e", help="Comma-separated file extensions (e.g. ts,tsx,jsx)")] = None,
308
+ package: Annotated[str | None, typer.Option("--package", "-p", help="Monorepo package scope filter (e.g. dundoo-react)")] = None,
309
+ path_prefix: Annotated[str | None, typer.Option("--path-prefix", help="Subdirectory path prefix filter")] = None,
240
310
  json_output: Annotated[bool, typer.Option("--json")] = False,
241
311
  ) -> None:
242
312
  """Search indexed code with exact evidence."""
@@ -261,8 +331,42 @@ def search(
261
331
  )
262
332
  )
263
333
  return
334
+
335
+ file_types = [e.strip().lstrip(".") for e in ext.split(",") if e.strip()] if ext else None
336
+ effective_path_filter: str | None = path_prefix
337
+ if package:
338
+ from codegraph.monorepo import discover_workspace
339
+ ws = discover_workspace(repo)
340
+ pkg_info = ws.packages.get(package)
341
+ if pkg_info:
342
+ effective_path_filter = pkg_info.root_path
343
+ else:
344
+ effective_path_filter = package
345
+
264
346
  with _indexer(repo).session() as con:
265
- result = [r.as_dict() for r in search_code(con, query, top_k)]
347
+ if file_types or effective_path_filter:
348
+ from codegraph.search.hybrid import search_code as search_code_rich
349
+ raw_hits = search_code_rich(
350
+ con,
351
+ query,
352
+ repo_path=repo,
353
+ path_filter=effective_path_filter,
354
+ file_types=file_types,
355
+ top_k=top_k,
356
+ )
357
+ result = [
358
+ {
359
+ "file": str(h.get("path") or h.get("file") or ""),
360
+ "start_line": int(str(h.get("line") or h.get("start_line") or "1")),
361
+ "end_line": int(str(h.get("line") or h.get("end_line") or "1")),
362
+ "symbol": str(h.get("symbol") or ""),
363
+ "score": float(str(h.get("score") or "1.0")),
364
+ "snippet": str(h.get("snippet") or h.get("matched_text") or ""),
365
+ }
366
+ for h in raw_hits
367
+ ]
368
+ else:
369
+ result = [r.as_dict() for r in search_code(con, query, top_k)]
266
370
  typer.echo(
267
371
  json.dumps(result, indent=2)
268
372
  if json_output
@@ -318,6 +422,7 @@ def trace(
318
422
  callees: Annotated[bool, typer.Option("--callees", help="Trace direct callees")] = False,
319
423
  both: Annotated[bool, typer.Option("--both", help="Trace both callers and callees")] = False,
320
424
  depth: Annotated[int, typer.Option("--depth", "-d", help="Max trace depth (clamped to max 5)")] = 2,
425
+ compact: Annotated[bool, typer.Option("--compact", help="Emit compact human-readable summary")] = False,
321
426
  ) -> None:
322
427
  """Trace a symbol definition, callers, and callees with explicit confidence labels."""
323
428
  repo = _resolve_repo(repository=repository)
@@ -373,6 +478,33 @@ def trace(
373
478
  )
374
479
  )
375
480
  return
481
+ if compact:
482
+ cli_echo(f"Trace for: {symbol}")
483
+ definitions = [x for x in res if x.get("relationship") == "DEFINES"]
484
+ handlers = [x for x in res if x.get("relationship") == "HANDLED_BY"]
485
+ caller_list = [x for x in res if x.get("relationship") == "CALLER"]
486
+ callee_list = [x for x in res if x.get("relationship") == "CALLEE"]
487
+ if definitions:
488
+ cli_echo(" Definitions:")
489
+ for d in definitions[:5]:
490
+ cli_echo(f" - {d.get('symbol')} ({d.get('file')}:{d.get('start_line')})")
491
+ if handlers:
492
+ cli_echo(" Handled by Routes:")
493
+ for h in handlers[:5]:
494
+ cli_echo(f" - {h.get('symbol')} ({h.get('file')}:{h.get('start_line')})")
495
+ if caller_list:
496
+ cli_echo(f" Callers ({len(caller_list)} total):")
497
+ for c in caller_list[:15]:
498
+ cli_echo(f" - {c.get('symbol')} at {c.get('file')}:{c.get('start_line')} [{c.get('confidence')}]")
499
+ if len(caller_list) > 15:
500
+ cli_echo(f" ... and {len(caller_list) - 15} more")
501
+ if callee_list:
502
+ cli_echo(f" Callees ({len(callee_list)} total):")
503
+ for c in callee_list[:15]:
504
+ cli_echo(f" - {c.get('symbol')} at {c.get('file')}:{c.get('start_line')} [{c.get('confidence')}]")
505
+ if len(callee_list) > 15:
506
+ cli_echo(f" ... and {len(callee_list) - 15} more")
507
+ return
376
508
  typer.echo(json.dumps(res, indent=2))
377
509
 
378
510
 
@@ -497,6 +629,200 @@ def routes(
497
629
  typer.echo(f" [{r['http_method']}] {r['route_path']} -> {r['handler']} ({r['file']}:{r['line']}) [{r['framework']}]")
498
630
 
499
631
 
632
+ @app.command("schema-drift")
633
+ def schema_drift(
634
+ route: Annotated[str | None, typer.Option("--route", help="Route path or endpoint to check for schema drift")] = None,
635
+ handler: Annotated[str | None, typer.Option("--handler", "-h", help="Handler symbol to check for schema drift")] = None,
636
+ table: Annotated[str | None, typer.Option("--table", "-t", help="Target table name (optional, inferred from mutation lineage)")] = None,
637
+ schema: Annotated[str | None, typer.Option("--schema", "-s", help="Schema class name (optional, inferred from handler signature)")] = None,
638
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
639
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
640
+ json_output: Annotated[bool, typer.Option("--json", help="Output raw JSON array")] = False,
641
+ ) -> None:
642
+ """Detect Pydantic / Form validation drift against destination database table columns."""
643
+ from codegraph.database.schema_drift import detect_schema_drift
644
+
645
+ repo = _resolve_repo(path, repository)
646
+ if not _ensure_indexed(repo):
647
+ return
648
+ target = route or handler or ""
649
+ if not target:
650
+ typer.echo("Error: Please specify --route or --handler to check for schema drift.")
651
+ raise typer.Exit(code=1)
652
+ with _indexer(repo).session() as con:
653
+ res = detect_schema_drift(con, repo, route_or_handler=target, target_table=table, schema_name=schema)
654
+ if json_output:
655
+ typer.echo(json.dumps(res, indent=2))
656
+ else:
657
+ if res.get("status") == "error":
658
+ typer.echo(f"Error: {res.get('error')}")
659
+ raise typer.Exit(code=1)
660
+ typer.echo(f"Schema Drift Report for {target} -> {res.get('target_table')} ({res.get('schema_name')}):")
661
+ typer.echo(f" Mode: {res.get('schema_mode', 'STATIC_TYPED')}")
662
+ recon = res.get("runtime_reconciliation", {})
663
+ if recon.get("is_observed"):
664
+ typer.echo(f" Runtime SQL: Observed ({recon.get('observation_count')} query executions)")
665
+ if recon.get("last_sql_sample"):
666
+ typer.echo(f" Sample Query: {recon.get('last_sql_sample')}")
667
+ else:
668
+ typer.echo(" Runtime SQL: NOT_OBSERVED_AT_RUNTIME (Run dev server or ingest traces to observe live queries)")
669
+ typer.echo(f" Total Issues: {res.get('drift_count')} (Critical: {res.get('critical_count')}, Warning: {res.get('warning_count')}, Info: {res.get('info_count')})")
670
+ for iss in res.get("issues", []):
671
+ typer.echo(f" [{iss['severity']}] {iss['drift_type']} on '{iss['field_name']}': {iss['message']}")
672
+
673
+
674
+ @app.command("api-drift")
675
+ def api_drift_cmd(
676
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
677
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
678
+ json_output: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
679
+ ) -> None:
680
+ """Detect cross-language client-server API contract drift (404s, 405s, and TypeScript-to-Backend type drift)."""
681
+ from codegraph.api_drift import detect_api_contract_drift
682
+
683
+ repo = _resolve_repo(path, repository)
684
+ if not _ensure_indexed(repo):
685
+ return
686
+
687
+ with _indexer(repo).session() as con:
688
+ report = detect_api_contract_drift(con, repo)
689
+
690
+ if json_output:
691
+ typer.echo(json.dumps(report.as_dict(), indent=2))
692
+ else:
693
+ if not report.has_drift:
694
+ typer.echo("No API contract drift detected.")
695
+ typer.echo(f"Verified {report.total_client_calls} client data fetches against {report.total_backend_routes} backend routes ({report.matched_calls} matched).")
696
+ else:
697
+ typer.echo(f"API Contract Drift Detected ({len(report.drifts)} issues):")
698
+ typer.echo(f"Client Calls: {report.total_client_calls} | Backend Routes: {report.total_backend_routes} | Matched: {report.matched_calls}\n")
699
+ for d in report.drifts:
700
+ typer.echo(f" [{d.severity}] {d.kind}")
701
+ typer.echo(f" Client: {d.client_method} {d.client_route} ({d.client_file}:{d.client_line})")
702
+ if d.backend_route:
703
+ typer.echo(f" Backend: {d.backend_route} -> {d.backend_handler} ({d.backend_file})")
704
+ if d.field_name:
705
+ typer.echo(f" Field: {d.field_name} (Client: {d.client_field_type} vs Backend: {d.backend_field_type})")
706
+ typer.echo(f" Message: {d.message}\n")
707
+
708
+
709
+ @app.command("api_drift", hidden=True)
710
+ def api_drift_alias(
711
+ path: Annotated[Path | None, typer.Argument(help="Repository path")] = None,
712
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
713
+ json_output: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
714
+ ) -> None:
715
+ """Alias for api-drift."""
716
+ api_drift_cmd(path=path, repository=repository, json_output=json_output)
717
+
718
+
719
+ @app.command("dead-code")
720
+ def dead_code_cmd(
721
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
722
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
723
+ max_symbols: Annotated[int, typer.Option("--max-symbols", "-m", help="Max dead symbols to display")] = 50,
724
+ json_output: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
725
+ ) -> None:
726
+ """Detect zero-caller functions/classes, uncalled zombie HTTP routes, and orphaned database tables."""
727
+ from codegraph.dead_code import analyze_dead_code
728
+
729
+ repo = _resolve_repo(path, repository)
730
+ if not _ensure_indexed(repo):
731
+ return
732
+
733
+ with _indexer(repo).session() as con:
734
+ report = analyze_dead_code(con, repo, max_symbols=max_symbols)
735
+
736
+ if json_output:
737
+ typer.echo(json.dumps(report.as_dict(), indent=2))
738
+ return
739
+
740
+ typer.echo(f"CodeGraph Dead Code & Zombie Route Report for {repo.name}:")
741
+ typer.echo(f" Runtime Telemetry: {'PRESENT' if report.runtime_traces_present else 'ABSENT (Routes marked UNOBSERVED_AT_RUNTIME)'}")
742
+ typer.echo(f" Total Flagged: {report.total_dead_count}")
743
+ typer.echo(f" Dead Symbols: {len(report.dead_symbols)}")
744
+ typer.echo(f" Zombie Routes: {len(report.zombie_routes)}")
745
+ typer.echo(f" Orphaned Tables: {len(report.orphaned_tables)}\n")
746
+
747
+ if report.dead_symbols:
748
+ typer.echo("Dead Symbols (0 Static Callers, 0 Runtime Invocations):")
749
+ for s in report.dead_symbols:
750
+ typer.echo(f" - [{s.kind}] {s.name} ({s.file_path}:{s.line}) [{s.confidence}]")
751
+ typer.echo()
752
+
753
+ if report.zombie_routes:
754
+ typer.echo("Zombie & Unobserved HTTP Routes:")
755
+ for r in report.zombie_routes:
756
+ typer.echo(f" - [{r.http_method}] {r.route_path} -> {r.handler_name} ({r.file_path}:{r.line}) [{r.status}]")
757
+ typer.echo()
758
+
759
+ if report.orphaned_tables:
760
+ typer.echo("Orphaned Database Tables (0 Readers, 0 Writers):")
761
+ for t in report.orphaned_tables:
762
+ typer.echo(f" - {t.table_name} ({t.file_path}:{t.line}) [{t.confidence}]")
763
+
764
+
765
+ @app.command("otel-listen")
766
+ def otel_listen_cmd(
767
+ port: Annotated[int, typer.Option("--port", "-p", help="Listening port for OTLP HTTP receiver (default: 4318)")] = 4318,
768
+ host: Annotated[str, typer.Option("--host", "-h", help="Listening host (default: 127.0.0.1)")] = "127.0.0.1",
769
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
770
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
771
+ ) -> None:
772
+ """Run lightweight embedded OpenTelemetry (OTLP/HTTP) trace receiver streaming into .codegraph.sqlite3."""
773
+ import asyncio
774
+
775
+ from codegraph.runtime.otel_receiver import run_otel_listener
776
+
777
+ repo = _resolve_repo(path, repository)
778
+ if not _ensure_indexed(repo):
779
+ return
780
+
781
+ indexer = _indexer(repo)
782
+
783
+ def on_batch(result: dict[str, Any]) -> None:
784
+ events = result.get("ingested_events", 0)
785
+ edges = result.get("edges_created", 0)
786
+ typer.echo(f"[OTLP] Ingested trace batch: {events} spans -> {edges} runtime graph edges")
787
+
788
+ async def main() -> None:
789
+ receiver = await run_otel_listener(
790
+ db_path=indexer.db_path,
791
+ host=host,
792
+ port=port,
793
+ on_batch=on_batch,
794
+ )
795
+ typer.echo(f"CodeGraph OTLP HTTP Receiver listening on http://{host}:{port}/v1/traces")
796
+ typer.echo(f"Export traces using: export OTEL_EXPORTER_OTLP_ENDPOINT=http://{host}:{port}")
797
+ typer.echo("Press Ctrl+C to terminate.")
798
+ try:
799
+ while True:
800
+ await asyncio.sleep(1)
801
+ except (KeyboardInterrupt, asyncio.CancelledError):
802
+ await receiver.stop()
803
+ typer.echo("\nOTLP Receiver stopped.")
804
+
805
+ try:
806
+ asyncio.run(main())
807
+ except KeyboardInterrupt:
808
+ pass
809
+
810
+
811
+ @app.command("lsp")
812
+ def lsp_cmd(
813
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
814
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
815
+ ) -> None:
816
+ """Run Language Server Protocol (LSP) server over stdio for IDE integration (VS Code, Neovim, Helix)."""
817
+ from codegraph.lsp import run_stdio_lsp_server
818
+
819
+ repo = _resolve_repo(path, repository)
820
+ if not _ensure_indexed(repo):
821
+ return
822
+
823
+ run_stdio_lsp_server(repo)
824
+
825
+
500
826
  @app.command()
501
827
  def imports(
502
828
  path: Annotated[str | None, typer.Argument(help="Repository-relative file path to inspect imports for (default: inspect all imports)")] = None,
@@ -627,6 +953,38 @@ def run_cmd(
627
953
  raise typer.Exit(code=exit_code)
628
954
 
629
955
 
956
+ @app.command("ingest")
957
+ def ingest_cli_cmd(
958
+ source: Annotated[Path, typer.Argument(help="Path to OpenTelemetry JSON/JSONL, SQL query log, or trace file")],
959
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
960
+ format: Annotated[str, typer.Option("--format", "-f", help="Trace format: auto | otel | json | sql_log")] = "auto",
961
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
962
+ ) -> None:
963
+ """Ingest runtime traces (OpenTelemetry, JSON, or SQL query logs) into repository index."""
964
+ repo = _resolve_repo(None, repository)
965
+ if not _ensure_indexed(repo):
966
+ raise typer.Exit(code=1)
967
+
968
+ if not source.exists():
969
+ cli_echo(f"Error: Trace source file '{source}' does not exist.")
970
+ raise typer.Exit(code=1)
971
+
972
+ content = source.read_text(encoding="utf-8", errors="replace")
973
+ indexer = _indexer(repo)
974
+ with indexer.session() as con:
975
+ from codegraph.runtime.ingestor import ingest_runtime_traces
976
+
977
+ res = ingest_runtime_traces(con, content, repository=repo, format=format)
978
+
979
+ if json_output:
980
+ cli_echo(json.dumps(res, indent=2), json_mode=True)
981
+ else:
982
+ cli_echo("Runtime Ingestion Complete:")
983
+ cli_echo(f" Events Ingested: {res.get('events_ingested', 0)}")
984
+ cli_echo(f" Edges Upserted: {res.get('edges_upserted', 0)}")
985
+ cli_echo(f" Generation: {res.get('runtime_generation', 1)}")
986
+
987
+
630
988
  def _run_server(
631
989
  path: Path | None,
632
990
  repository: Path | None,
@@ -983,7 +1341,10 @@ def context(
983
1341
  mode=mode,
984
1342
  explain=explain,
985
1343
  )
986
- typer.echo(json.dumps(packet.as_dict(), indent=2))
1344
+ if json_output:
1345
+ typer.echo(json.dumps(packet.as_dict(), indent=2))
1346
+ else:
1347
+ typer.echo(packet.format_human())
987
1348
 
988
1349
 
989
1350
  @app.command("explain-context")
@@ -1409,51 +1770,89 @@ def git_diff_cmd(
1409
1770
  cli_echo(f"Affected Tests: {len(s_rep.affected_tests)} ({', '.join(s_rep.affected_tests[:5])})")
1410
1771
 
1411
1772
 
1412
- @app.command("git-impact")
1413
- def git_impact_cmd(
1414
- base: Annotated[str, typer.Argument(help="Base Git ref (default: HEAD~1)")] = "HEAD~1",
1415
- head: Annotated[str, typer.Argument(help="Head Git ref (default: HEAD)")] = "HEAD",
1773
+ @app.command("impact")
1774
+ def impact_cmd(
1775
+ base: Annotated[str, typer.Option("--base", "-b", help="Base Git ref (default: HEAD~1)")] = "HEAD~1",
1776
+ head: Annotated[str, typer.Option("--head", "-h", help="Head Git ref (default: HEAD)")] = "HEAD",
1777
+ symbol: Annotated[str | None, typer.Option("--symbol", "-s", help="Analyze blast radius for a specific symbol on-demand")] = None,
1416
1778
  depth: Annotated[int, typer.Option("--depth", "-d", help="Max caller traversal depth")] = 2,
1417
1779
  max_results: Annotated[int, typer.Option("--max-results", "-m", help="Max items per category")] = 30,
1418
1780
  tree: Annotated[bool, typer.Option("--tree", "-t", help="Display visual impact tree")] = False,
1419
- path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
1781
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
1420
1782
  repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
1421
1783
  json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
1422
1784
  ) -> None:
1423
- """Compute deep downstream change impact across callers, callees, framework routes, tests, and DB."""
1785
+ """Compute deep downstream change impact across callers, frontend UI, framework routes, tests, and DB."""
1424
1786
  from codegraph.change_impact import get_deep_change_impact
1425
1787
 
1426
1788
  repo = _resolve_repo(path, repository)
1427
1789
  indexer = _indexer(repo)
1428
1790
 
1429
1791
  with indexer.session() as con:
1430
- imp = get_deep_change_impact(repo, con, base=base, head=head, max_depth=depth, max_results=max_results)
1792
+ imp = get_deep_change_impact(
1793
+ repo, con, base=base, head=head, max_depth=depth, max_results=max_results, symbol=symbol
1794
+ )
1431
1795
 
1432
1796
  if json_output:
1433
1797
  cli_echo(json.dumps(imp.as_dict(), indent=2), json_mode=True)
1434
1798
  else:
1435
- cli_echo(f"Deep Change Impact Analysis: {base} -> {head}")
1436
- cli_echo(f"Blast Radius Score: {imp.blast_radius_score} / 100")
1437
- cli_echo(f"Total Impacted Items: {imp.total_impacted_count}")
1438
- cli_echo(f"Direct Callers: {len(imp.direct_callers)}")
1439
- cli_echo(f"Transitive Callers: {len(imp.transitive_callers)}")
1440
- cli_echo(f"Affected Routes: {len(imp.affected_routes)}")
1441
- cli_echo(f"Covering Tests: {len(imp.affected_tests)}")
1442
- cli_echo(f"DB Writers: {len(imp.db_writers)}")
1443
- cli_echo(f"Monorepo Packages: {len(imp.affected_packages)}")
1799
+ target_title = f"Symbol '{symbol}'" if symbol else f"Git Diff: {base} -> {head}"
1800
+ cli_echo(f"Semantic Change Impact Analysis: {target_title}")
1801
+ cli_echo(f" PR Risk Level: [{imp.risk_level}] (Score: {imp.blast_radius_score} / 100)")
1802
+ cli_echo(f" Total Impacted Items: {imp.total_impacted_count}")
1803
+ cli_echo(f" Direct Callers: {len(imp.direct_callers)}")
1804
+ cli_echo(f" Transitive Callers: {len(imp.transitive_callers)}")
1805
+ if imp.affected_frontend_components:
1806
+ cli_echo(f" Frontend UI Impact: {len(imp.affected_frontend_components)} components")
1807
+ cli_echo(f" Affected Routes: {len(imp.affected_routes)}")
1808
+ cli_echo(f" Covering Tests: {len(imp.affected_tests)}")
1809
+ cli_echo(f" DB Writers: {len(imp.db_writers)}")
1810
+ cli_echo(f" Monorepo Packages: {len(imp.affected_packages)}")
1811
+
1812
+ if imp.breaking_change_flags:
1813
+ cli_echo(f"\n ⚠️ Breaking Risk Flags: {', '.join(imp.breaking_change_flags)}")
1814
+
1815
+ if imp.recommended_test_command:
1816
+ cli_echo(f"\n 🎯 Recommended Test Run: {imp.recommended_test_command}")
1444
1817
 
1445
1818
  if tree or imp.total_impacted_count > 0:
1446
1819
  cli_echo("\nImpact Tree:")
1447
1820
  for s in imp.changed_symbols[:10]:
1448
- cli_echo(f" └── 📄 [{s.get('change_type', 'MODIFIED')}] {s.get('path', '')}::{s.get('name', '')}")
1821
+ cli_echo(f" └── [{s.get('change_type', 'MODIFIED')}] {s.get('path', '')}::{s.get('name', '')}")
1822
+ for fe in imp.affected_frontend_components[:5]:
1823
+ cli_echo(f" ├── UI: {fe.file}::{fe.name} (fetches route)")
1449
1824
  for c in imp.direct_callers[:8]:
1450
- cli_echo(f" ├── 📞 CALLER: {c.file}::{c.name} (depth 1)")
1825
+ cli_echo(f" ├── CALLER: {c.file}::{c.name} (depth 1)")
1451
1826
  for r in imp.affected_routes[:5]:
1452
- cli_echo(f" ├── 🌐 ROUTE: {r.name} -> {r.file}")
1827
+ cli_echo(f" ├── ROUTE: {r.name} -> {r.file}")
1453
1828
  for t in imp.affected_tests[:5]:
1454
- cli_echo(f" ├── 🧪 TEST: {t.file}::{t.name}")
1829
+ cli_echo(f" ├── TEST: {t.file}::{t.name}")
1455
1830
  for db in imp.db_writers[:5]:
1456
- cli_echo(f" └── 💾 DB: {db.relationship} {db.name} in {db.file}")
1831
+ cli_echo(f" └── DB: {db.relationship} {db.name} in {db.file}")
1832
+
1833
+
1834
+ @app.command("git-impact", hidden=True)
1835
+ def git_impact_alias(
1836
+ base: Annotated[str, typer.Argument(help="Base Git ref (default: HEAD~1)")] = "HEAD~1",
1837
+ head: Annotated[str, typer.Argument(help="Head Git ref (default: HEAD)")] = "HEAD",
1838
+ depth: Annotated[int, typer.Option("--depth", "-d", help="Max caller traversal depth")] = 2,
1839
+ max_results: Annotated[int, typer.Option("--max-results", "-m", help="Max items per category")] = 30,
1840
+ tree: Annotated[bool, typer.Option("--tree", "-t", help="Display visual impact tree")] = False,
1841
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
1842
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
1843
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
1844
+ ) -> None:
1845
+ """Backward-compatible alias for codegraph impact."""
1846
+ impact_cmd(
1847
+ base=base,
1848
+ head=head,
1849
+ depth=depth,
1850
+ max_results=max_results,
1851
+ tree=tree,
1852
+ path=path,
1853
+ repository=repository,
1854
+ json_output=json_output,
1855
+ )
1457
1856
 
1458
1857
 
1459
1858
  @app.command("git-conflicts")
@@ -1477,7 +1876,7 @@ def git_conflicts_cmd(
1477
1876
  cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
1478
1877
  else:
1479
1878
  cli_echo(f"Semantic Conflict Analysis: {base} <-> {head}")
1480
- cli_echo(f"Status: {'⚠️ CONFLICTS DETECTED' if rep.has_conflicts else '✅ CLEAN (0 conflicts)'}")
1879
+ cli_echo(f"Status: {'[!] CONFLICTS DETECTED' if rep.has_conflicts else '[OK] CLEAN (0 conflicts)'}")
1481
1880
  cli_echo(f"Total Conflicts: {rep.total_conflicts}")
1482
1881
  cli_echo(f"Summary: {rep.summary}")
1483
1882
  if rep.conflicts:
@@ -1489,67 +1888,1211 @@ def git_conflicts_cmd(
1489
1888
  cli_echo(f" Head ({head}): {c.head_file} ({c.head_evidence})")
1490
1889
 
1491
1890
 
1492
- @app.command("check-freshness")
1493
- def check_freshness_cli_cmd(
1494
- task: Annotated[str, typer.Argument(help="Task prompt to verify context freshness for")] = "",
1891
+ agent_memory_app = typer.Typer(
1892
+ help="Long-term agent trajectory & debugging memory store.",
1893
+ no_args_is_help=True,
1894
+ )
1895
+ app.add_typer(agent_memory_app, name="agent-memory")
1896
+
1897
+
1898
+ @agent_memory_app.command("store")
1899
+ def memory_store_cmd(
1900
+ title: Annotated[str, typer.Option("--title", "-t", help="Title or summary of the debugging session/decision")],
1901
+ resolution: Annotated[str, typer.Option("--resolution", "-r", help="Resolution or architectural fix applied")],
1902
+ category: Annotated[str, typer.Option("--category", "-c", help="Category: BUG_FIX, ARCHITECTURE_DECISION, TEST_PATTERN, ROOT_CAUSE")] = "BUG_FIX",
1903
+ symptoms: Annotated[str, typer.Option("--symptoms", "-s", help="Observed symptoms or error traces")] = "",
1904
+ root_cause: Annotated[str, typer.Option("--root-cause", help="Identified root cause")] = "",
1905
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
1906
+ repository: Annotated[Path | None, typer.Option("--repository", "--repo", help="Repository path")] = None,
1907
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
1908
+ ) -> None:
1909
+ """Store an agent debugging trajectory or architectural decision into persistent memory."""
1910
+ from codegraph.memory.trajectory import get_trajectory_memory_store
1911
+
1912
+ repo = _resolve_repo(path, repository)
1913
+ store = get_trajectory_memory_store(repo)
1914
+ record = store.store(
1915
+ title=title,
1916
+ resolution=resolution,
1917
+ category=category,
1918
+ symptoms=symptoms,
1919
+ root_cause=root_cause,
1920
+ )
1921
+
1922
+ if json_output:
1923
+ cli_echo(json.dumps(record.as_dict(), indent=2), json_mode=True)
1924
+ else:
1925
+ cli_echo(f"Stored Agent Memory Record [{record.id}]:")
1926
+ cli_echo(f" Category: {record.category}")
1927
+ cli_echo(f" Title: {record.title}")
1928
+ cli_echo(f" Resolution: {record.resolution}")
1929
+
1930
+
1931
+ @agent_memory_app.command("search")
1932
+ def memory_search_cmd(
1933
+ query: Annotated[str, typer.Argument(help="Search query matching symptoms, title, root cause, or resolution")],
1934
+ category: Annotated[str | None, typer.Option("--category", "-c", help="Filter by category")] = None,
1935
+ limit: Annotated[int, typer.Option("--limit", "-l", help="Max records to return")] = 5,
1936
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
1937
+ repository: Annotated[Path | None, typer.Option("--repository", "--repo", help="Repository path")] = None,
1938
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
1939
+ ) -> None:
1940
+ """Search past agent debugging memories and architectural decisions using FTS5 BM25 ranking."""
1941
+ from codegraph.memory.trajectory import get_trajectory_memory_store
1942
+
1943
+ repo = _resolve_repo(path, repository)
1944
+ store = get_trajectory_memory_store(repo)
1945
+ records = store.search(query=query, category=category, limit=limit)
1946
+
1947
+ if json_output:
1948
+ cli_echo(json.dumps([r.as_dict() for r in records], indent=2), json_mode=True)
1949
+ else:
1950
+ cli_echo(f"Found {len(records)} Agent Memory Record(s) for '{query}':")
1951
+ for r in records:
1952
+ cli_echo(f"\n [{r.category}] {r.title} (Relevance: {r.score})")
1953
+ if r.symptoms:
1954
+ cli_echo(f" Symptoms: {r.symptoms}")
1955
+ if r.root_cause:
1956
+ cli_echo(f" Root Cause: {r.root_cause}")
1957
+ cli_echo(f" Resolution: {r.resolution}")
1958
+
1959
+
1960
+ @agent_memory_app.command("list")
1961
+ def memory_list_cmd(
1962
+ limit: Annotated[int, typer.Option("--limit", "-l", help="Max records to return")] = 10,
1963
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
1964
+ repository: Annotated[Path | None, typer.Option("--repository", "--repo", help="Repository path")] = None,
1965
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
1966
+ ) -> None:
1967
+ """List recent agent memories."""
1968
+ from codegraph.memory.trajectory import get_trajectory_memory_store
1969
+
1970
+ repo = _resolve_repo(path, repository)
1971
+ store = get_trajectory_memory_store(repo)
1972
+ records = store.list_recent(limit=limit)
1973
+
1974
+ if json_output:
1975
+ cli_echo(json.dumps([r.as_dict() for r in records], indent=2), json_mode=True)
1976
+ else:
1977
+ cli_echo(f"Recent Agent Memories ({len(records)}):")
1978
+ for r in records:
1979
+ cli_echo(f" [{r.id}] ({r.category}) {r.title} - {r.created_at}")
1980
+
1981
+
1982
+ @agent_memory_app.command("clear")
1983
+ def memory_clear_cmd(
1984
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
1985
+ repository: Annotated[Path | None, typer.Option("--repository", "--repo", help="Repository path")] = None,
1986
+ ) -> None:
1987
+ """Clear all agent memory records for the repository."""
1988
+ from codegraph.memory.trajectory import get_trajectory_memory_store
1989
+
1990
+ repo = _resolve_repo(path, repository)
1991
+ store = get_trajectory_memory_store(repo)
1992
+ store.clear()
1993
+ cli_echo("Agent memory cleared.")
1994
+
1995
+
1996
+ federate_app = typer.Typer(
1997
+ help="Cross-repository & microservice graph federation commands.",
1998
+ no_args_is_help=True,
1999
+ )
2000
+ app.add_typer(federate_app, name="federate")
2001
+
2002
+
2003
+ @federate_app.command("scan")
2004
+ def federate_scan_cmd(
2005
+ workspace_root: Annotated[Path | None, typer.Argument(help="Workspace directory containing repositories (default: current directory)")] = None,
2006
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2007
+ ) -> None:
2008
+ """Discover federated repositories and index sizes in a multi-repo workspace."""
2009
+ from codegraph.federation import federate_workspace
2010
+
2011
+ root = workspace_root or Path.cwd()
2012
+ report = federate_workspace(root)
2013
+
2014
+ if json_output:
2015
+ cli_echo(json.dumps(report.as_dict(), indent=2), json_mode=True)
2016
+ else:
2017
+ cli_echo(f"Federated Workspace: {report.workspace_root}")
2018
+ cli_echo(f"Discovered Repositories ({len(report.repos)}):")
2019
+ for r in report.repos:
2020
+ cli_echo(f" - [{r.name}] {r.path}")
2021
+ cli_echo(f" Symbols: {r.symbol_count} | Routes: {r.route_count} | Database: {r.db_path}")
2022
+
2023
+
2024
+ @federate_app.command("routes")
2025
+ def federate_routes_cmd(
2026
+ workspace_root: Annotated[Path | None, typer.Argument(help="Workspace directory containing repositories (default: current directory)")] = None,
2027
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2028
+ ) -> None:
2029
+ """Resolve cross-repository HTTP and RPC service-to-service links across microservices."""
2030
+ from codegraph.federation import federate_workspace
2031
+
2032
+ root = workspace_root or Path.cwd()
2033
+ report = federate_workspace(root)
2034
+
2035
+ if json_output:
2036
+ cli_echo(json.dumps(report.as_dict(), indent=2), json_mode=True)
2037
+ else:
2038
+ cli_echo(f"Cross-Repository Route Links in {report.workspace_root}:")
2039
+ if not report.cross_repo_links:
2040
+ cli_echo(" No cross-repository route calls discovered.")
2041
+ for link in report.cross_repo_links:
2042
+ cli_echo(
2043
+ f" [{link.confidence}] {link.source_repo}:{link.source_file} ({link.source_symbol})\n"
2044
+ f" --[{link.http_method} {link.route_path}]-->\n"
2045
+ f" {link.target_repo}:{link.target_file} ({link.target_handler})"
2046
+ )
2047
+
2048
+
2049
+ @app.command("generate-tests")
2050
+ def generate_tests_cmd(
2051
+ target: Annotated[str, typer.Argument(help="Symbol name, canonical ID, or HTTP route path to generate tests for")],
2052
+ framework: Annotated[str | None, typer.Option("--framework", "-f", help="Target test framework (pytest, jest, testez)")] = None,
2053
+ output_file: Annotated[Path | None, typer.Option("--output-file", "-o", help="Write generated test suite to file")] = None,
1495
2054
  path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
1496
2055
  repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
1497
2056
  json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
1498
2057
  ) -> None:
1499
- """Validate whether compiled context remains VALID, PARTIALLY_STALE, or STALE against repository changes."""
1500
- from codegraph.context import get_context
1501
- from codegraph.context_freshness import check_context_freshness
2058
+ """Generate production-ready test scaffolding with fixtures, dependency mocks, and boundary test cases."""
2059
+ from codegraph.test_gen import generate_test_scaffolding
1502
2060
 
1503
2061
  repo = _resolve_repo(path, repository)
1504
2062
  indexer = _indexer(repo)
1505
2063
 
1506
2064
  with indexer.session() as con:
1507
- # Generate baseline context if task provided
1508
- ctx = get_context(con, repo, task or "general repository overview", mode="FAST")
1509
- rep = check_context_freshness(ctx, repo, con=con)
2065
+ scaffold = generate_test_scaffolding(con, target=target, repository=repo, framework=framework)
2066
+
2067
+ if output_file:
2068
+ output_file.parent.mkdir(parents=True, exist_ok=True)
2069
+ output_file.write_text(scaffold.test_code, encoding="utf-8")
2070
+ cli_echo(f"Wrote generated test scaffold to {output_file}")
2071
+
2072
+ if json_output:
2073
+ cli_echo(json.dumps(scaffold.as_dict(), indent=2), json_mode=True)
2074
+ elif not output_file:
2075
+ cli_echo(f"Generated {scaffold.framework} Test Scaffold for '{scaffold.target_symbol}':")
2076
+ cli_echo(f"Target Source File: {scaffold.target_file}")
2077
+ cli_echo(f"SuggestedTest File: {scaffold.suggested_test_file}")
2078
+ if scaffold.mock_requirements:
2079
+ cli_echo("\nDetected Mock Requirements:")
2080
+ for m in scaffold.mock_requirements:
2081
+ cli_echo(f" - [{m.mock_type}] {m.target}: {m.description}")
2082
+ cli_echo("\n--- Generated Test Code ---")
2083
+ cli_echo(scaffold.test_code)
2084
+
2085
+
2086
+ @app.command("pr-review")
2087
+ def pr_review_cmd(
2088
+ base: Annotated[str, typer.Argument(help="Base Git branch/commit (default: main)")] = "main",
2089
+ head: Annotated[str, typer.Argument(help="Head Git branch/commit (default: HEAD)")] = "HEAD",
2090
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2091
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2092
+ output_file: Annotated[Path | None, typer.Option("--output-file", "-o", help="Write markdown review to file")] = None,
2093
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2094
+ ) -> None:
2095
+ """Generate comprehensive semantic PR review evaluating structural diffs, contract breaks, affected routes, and test coverage."""
2096
+ from codegraph.pr_review import generate_pr_review
2097
+
2098
+ repo = _resolve_repo(path, repository)
2099
+ indexer = _indexer(repo)
2100
+
2101
+ with indexer.session() as con:
2102
+ rep = generate_pr_review(repo, base_ref=base, head_ref=head, con=con)
2103
+
2104
+ if output_file:
2105
+ output_file.write_text(rep.markdown_report, encoding="utf-8")
1510
2106
 
1511
2107
  if json_output:
1512
2108
  cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
1513
2109
  else:
1514
- cli_echo(f"Context Freshness Status: {rep.status.value}")
1515
- cli_echo(f"Reason: {rep.reason}")
1516
- cli_echo(f"Recommended Action: {rep.recommended_action}")
1517
- if rep.changed_relevant_files:
1518
- cli_echo(f"Changed Relevant Files: {', '.join(rep.changed_relevant_files)}")
1519
- if rep.unrelated_changed_files:
1520
- cli_echo(f"Unrelated Changed Files: {len(rep.unrelated_changed_files)} file(s)")
2110
+ cli_echo(rep.markdown_report)
1521
2111
 
1522
2112
 
1523
- @app.command("symbol-history")
1524
- def symbol_history_cli_cmd(
1525
- symbol: Annotated[str, typer.Argument(help="Symbol name to trace across Git history")],
1526
- file_path: Annotated[str | None, typer.Option("--file", "-f", help="File path where symbol is located")] = None,
1527
- max_commits: Annotated[int, typer.Option("--max-commits", "-m", help="Max commits to inspect")] = 15,
1528
- path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2113
+ security_app = typer.Typer(no_args_is_help=True, help="Security SAST taint tracking and vulnerability audit.")
2114
+ app.add_typer(security_app, name="security")
2115
+
2116
+
2117
+ @security_app.command("audit")
2118
+ def security_audit_cmd(
2119
+ entrypoint: Annotated[str | None, typer.Option("--entrypoint", "-e", help="Optional entrypoint symbol or handler")] = None,
2120
+ cwe: Annotated[str | None, typer.Option("--cwe", help="Filter by CWE identifier (e.g. CWE-89, CWE-78, CWE-22, CWE-918, CWE-502)")] = None,
2121
+ max_depth: Annotated[int, typer.Option("--max-depth", help="Maximum AST traversal depth")] = 12,
2122
+ sarif: Annotated[bool, typer.Option("--sarif", help="Output OASIS SARIF 2.1.0 format for GitHub Code Scanning")] = False,
2123
+ sarif_output: Annotated[Path | None, typer.Option("--sarif-output", help="Write SARIF 2.1.0 JSON report to file")] = None,
2124
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
1529
2125
  repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
1530
2126
  json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
1531
2127
  ) -> None:
1532
- """Trace deterministic symbol evolution across Git history: introduced, modified, moved, renamed, or deleted."""
1533
- from codegraph.symbol_history import trace_symbol_history
2128
+ """Analyze source-to-sink dataflow taint paths for injection and security vulnerabilities."""
2129
+ from codegraph.security.taint import audit_repository_taint
1534
2130
 
1535
2131
  repo = _resolve_repo(path, repository)
1536
2132
  indexer = _indexer(repo)
1537
2133
 
1538
2134
  with indexer.session() as con:
1539
- rep = trace_symbol_history(repo, symbol=symbol, path=file_path, con=con, max_commits=max_commits)
2135
+ rep = audit_repository_taint(repo, con=con, entrypoint_symbol=entrypoint, filter_cwe=cwe, max_depth=max_depth)
1540
2136
 
1541
- if json_output:
2137
+ if sarif_output:
2138
+ sarif_data = rep.to_sarif()
2139
+ sarif_output.write_text(json.dumps(sarif_data, indent=2), encoding="utf-8")
2140
+ if not json_output and not sarif:
2141
+ cli_echo(f"Exported SARIF 2.1.0 report with {rep.total_vulnerabilities} findings to {sarif_output}")
2142
+
2143
+ if sarif:
2144
+ cli_echo(json.dumps(rep.to_sarif(), indent=2), json_mode=True)
2145
+ elif json_output:
1542
2146
  cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
1543
2147
  else:
1544
- cli_echo(f"Symbol History: {symbol}")
1545
- cli_echo(f"Status: {rep.status} ({rep.detail})")
1546
- for ev in rep.events:
1547
- cli_echo(f"\n [{ev.event_type}] Commit {ev.commit_sha[:8]} on {ev.date} by {ev.author}")
1548
- cli_echo(f" Message: {ev.message}")
1549
- cli_echo(f" Location: {ev.path}")
1550
- cli_echo(f" Evidence: {ev.evidence} (confidence: {ev.confidence})")
1551
-
2148
+ cli_echo(f"Security SAST Taint Audit for {repo.name}:")
2149
+ cli_echo(f" Total Vulnerabilities: {rep.total_vulnerabilities}")
2150
+ cli_echo(f" Critical: {rep.critical_count} | High: {rep.high_count} | Medium: {rep.medium_count} | Low: {rep.low_count}")
2151
+ for v in rep.vulnerabilities:
2152
+ cli_echo(f"\n • [{v.severity.value}] {v.cwe_id}: {v.vulnerability_type}")
2153
+ cli_echo(f" Source: {v.source_expr} ({v.file_path}:{v.source_line})")
2154
+ cli_echo(f" Sink: {v.sink_expr} ({v.file_path}:{v.sink_line})")
2155
+ cli_echo(f" Remediation: {v.remediation}")
2156
+
2157
+
2158
+ @app.command("repair")
2159
+ def repair_cmd(
2160
+ quick: Annotated[bool, typer.Option("--quick", help="Run quick check only without deep FTS & orphaned FK cleanup")] = False,
2161
+ vacuum: Annotated[bool, typer.Option("--vacuum", help="Run SQLite VACUUM to defragment index pages")] = False,
2162
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
2163
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2164
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2165
+ ) -> None:
2166
+ """Perform automated self-healing, integrity check, dangling FK pruning, FTS rebuild, and WAL checkpointing."""
2167
+ from codegraph.repair import repair_repository_index
2168
+
2169
+ repo = _resolve_repo(path, repository)
2170
+ rep = repair_repository_index(repo, deep=not quick, vacuum=vacuum)
2171
+
2172
+ if json_output:
2173
+ cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
2174
+ else:
2175
+ cli_echo(f"Database Index Self-Healing for {repo.name}: Status: {rep.status}")
2176
+ cli_echo(f" Integrity Check: {'PASSED' if rep.integrity_check_passed else 'FAILED'}")
2177
+ cli_echo(f" FTS5 Rebuilt: {rep.fts_rebuilt}")
2178
+ cli_echo(f" WAL Checkpoint: {rep.wal_checkpointed}")
2179
+ cli_echo(f" Stale Locks: {rep.stale_locks_cleared}")
2180
+ if rep.actions_taken:
2181
+ cli_echo(" Actions Taken:")
2182
+ for act in rep.actions_taken:
2183
+ cli_echo(f" - {act}")
2184
+ if rep.issues_found:
2185
+ cli_echo(" Issues Found:")
2186
+ for issue in rep.issues_found:
2187
+ cli_echo(f" ! {issue}")
2188
+
2189
+
2190
+ lsp_bridge_app = typer.Typer(no_args_is_help=True, help="Language Server Protocol (LSP) diagnostics bridge.")
2191
+ app.add_typer(lsp_bridge_app, name="lsp-bridge")
2192
+
2193
+
2194
+ @lsp_bridge_app.command("status")
2195
+ def lsp_status_cmd(
2196
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
2197
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2198
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2199
+ ) -> None:
2200
+ """Discover available Language Server Protocol (LSP) daemons on host system."""
2201
+ from codegraph.lsp_bridge.bridge import detect_lsp_servers
2202
+
2203
+ repo = _resolve_repo(path, repository)
2204
+ servers = detect_lsp_servers(repo)
2205
+ if json_output:
2206
+ cli_echo(json.dumps(servers, indent=2), json_mode=True)
2207
+ else:
2208
+ cli_echo(f"Discovered LSP Language Servers for {repo.name}:")
2209
+ if not servers:
2210
+ cli_echo(" No language servers found in PATH (pyright-langserver, gopls, rust-analyzer, clangd).")
2211
+ for lang, bin_path in servers.items():
2212
+ cli_echo(f" • {lang}: {bin_path}")
2213
+
2214
+
2215
+ @lsp_bridge_app.command("diagnostics")
2216
+ def lsp_diagnostics_cmd(
2217
+ file: Annotated[str | None, typer.Option("--file", "-f", help="Specific file to query diagnostics for")] = None,
2218
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
2219
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2220
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2221
+ ) -> None:
2222
+ """Collect live compiler diagnostics and type errors from Language Server Protocol daemons."""
2223
+ from codegraph.lsp_bridge.bridge import collect_lsp_diagnostics
2224
+
2225
+ repo = _resolve_repo(path, repository)
2226
+ rep = collect_lsp_diagnostics(repo, file_path=file)
2227
+
2228
+ if json_output:
2229
+ cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
2230
+ else:
2231
+ cli_echo(f"LSP Diagnostics for {repo.name} [Status: {rep.status}]:")
2232
+ cli_echo(f" Total Diagnostics: {rep.total_diagnostics} (Errors: {rep.error_count}, Warnings: {rep.warning_count})")
2233
+ for d in rep.diagnostics:
2234
+ cli_echo(f" • [{d.severity.value}] {d.file_path}:{d.line}:{d.column} - {d.message} ({d.source})")
2235
+
2236
+
2237
+ swarm_app = typer.Typer(no_args_is_help=True, help="Multi-agent swarm coordination and file lease management.")
2238
+ app.add_typer(swarm_app, name="swarm")
2239
+
2240
+
2241
+ @swarm_app.command("status")
2242
+ def swarm_status_cmd(
2243
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
2244
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2245
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2246
+ ) -> None:
2247
+ """Display active AI coding agent sessions, leased files, and semantic conflicts."""
2248
+ from codegraph.multi_agent.coordinator import MultiAgentCoordinator
2249
+
2250
+ repo = _resolve_repo(path, repository)
2251
+ coord = MultiAgentCoordinator(repo)
2252
+ rep = coord.get_status_report()
2253
+
2254
+ if json_output:
2255
+ cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
2256
+ else:
2257
+ cli_echo(f"Multi-Agent Swarm Status for {repo.name}:")
2258
+ cli_echo(f" Active Agents: {rep.total_agents} | Active Leases: {rep.active_leases_count} | Conflicts: {rep.conflicts_count}")
2259
+ for a in rep.agents:
2260
+ cli_echo(f" • Agent [{a.agent_id}] '{a.name}': {a.task_description}")
2261
+ for lease in rep.leases:
2262
+ cli_echo(f" • Lease: {lease.file_path} held by {lease.agent_id} ({lease.lease_type})")
2263
+ for c in rep.conflicts:
2264
+ cli_echo(f" ! CONFLICT: {c.file_path} - {c.reason}")
2265
+
2266
+
2267
+ @swarm_app.command("claim")
2268
+ def swarm_claim_cmd(
2269
+ agent_id: Annotated[str, typer.Option("--agent-id", "-a", help="Agent identifier")] = "agent-1",
2270
+ file: Annotated[str, typer.Argument(help="File path to lease")] = "",
2271
+ shared: Annotated[bool, typer.Option("--shared", help="Claim shared read lease instead of exclusive write")] = False,
2272
+ ttl: Annotated[float, typer.Option("--ttl", help="Lease TTL in seconds")] = 60.0,
2273
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2274
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2275
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2276
+ ) -> None:
2277
+ """Claim a lease lock on a file for an AI agent."""
2278
+ from codegraph.multi_agent.coordinator import MultiAgentCoordinator
2279
+
2280
+ repo = _resolve_repo(path, repository)
2281
+ coord = MultiAgentCoordinator(repo)
2282
+ lease_type = "SHARED_READ" if shared else "EXCLUSIVE_WRITE"
2283
+ ok, msg = coord.claim_lease(agent_id=agent_id, file_path=file, lease_type=lease_type, ttl_seconds=ttl)
2284
+
2285
+ if json_output:
2286
+ cli_echo(json.dumps({"success": ok, "message": msg, "file": file, "agent_id": agent_id}, indent=2), json_mode=True)
2287
+ else:
2288
+ cli_echo(f"{'SUCCESS' if ok else 'FAILED'}: {msg}")
2289
+
2290
+
2291
+ @app.command("lint-arch")
2292
+ def lint_arch_cmd(
2293
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
2294
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2295
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2296
+ ) -> None:
2297
+ """Enforce declarative architectural invariants and layer boundary rules."""
2298
+ from codegraph.architecture_rules import evaluate_architecture_rules
2299
+
2300
+ repo = _resolve_repo(path, repository)
2301
+ indexer = _indexer(repo)
2302
+ with indexer.session() as con:
2303
+ rep = evaluate_architecture_rules(repo, con)
2304
+
2305
+ if json_output:
2306
+ cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
2307
+ else:
2308
+ cli_echo(f"Architecture Rule Check for {repo.name}: Status: {rep.status}")
2309
+ cli_echo(f" Rules Checked: {rep.total_rules_checked} | Violations: {rep.violations_count}")
2310
+ for v in rep.violations:
2311
+ cli_echo(f" • [{v.severity}] {v.source_file}:{v.line} -> {v.target_entity} ({v.rule_name})")
2312
+ cli_echo(f" Message: {v.message}")
2313
+
2314
+
2315
+ @app.command("reachability")
2316
+ def reachability_cmd(
2317
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
2318
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2319
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2320
+ ) -> None:
2321
+ """Perform DI-aware root-to-leaf reachability analysis and dead code elimination."""
2322
+ from codegraph.reachability import compute_di_aware_reachability
2323
+
2324
+ repo = _resolve_repo(path, repository)
2325
+ indexer = _indexer(repo)
2326
+ with indexer.session() as con:
2327
+ rep = compute_di_aware_reachability(repo, con)
2328
+
2329
+ if json_output:
2330
+ cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
2331
+ else:
2332
+ cli_echo(f"DI-Aware Reachability & Dead Code for {repo.name}:")
2333
+ cli_echo(f" Total Symbols: {rep.total_symbols} | Reachable: {rep.reachable_count} | Unreachable: {rep.unreachable_count} ({rep.dead_code_percentage:.1f}%)")
2334
+ cli_echo(f" Root Entrypoints: {rep.root_entrypoints_count}")
2335
+ for s in rep.unreachable_symbols[:20]:
2336
+ cli_echo(f" • [{s.kind}] {s.name} ({s.file_path}:{s.line}) [CONFIDENCE: {s.confidence}]")
2337
+
2338
+
2339
+ @app.command("changelog")
2340
+ def changelog_cmd(
2341
+ base: Annotated[str, typer.Option("--base", "-b", help="Base Git revision")] = "HEAD~1",
2342
+ head: Annotated[str, typer.Option("--head", "-h", help="Head Git revision")] = "HEAD",
2343
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
2344
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2345
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2346
+ ) -> None:
2347
+ """Synthesize human-readable release changelog and breaking change report from AST diffs."""
2348
+ from codegraph.changelog import generate_semantic_changelog
2349
+
2350
+ repo = _resolve_repo(path, repository)
2351
+ rep = generate_semantic_changelog(repo, base_ref=base, head_ref=head)
2352
+
2353
+ if json_output:
2354
+ cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
2355
+ else:
2356
+ cli_echo(rep.markdown_changelog)
2357
+
2358
+
2359
+ @security_app.command("supply-chain")
2360
+ def security_supply_chain_cmd(
2361
+ package: Annotated[str | None, typer.Option("--package", "-p", help="Filter by specific package name")] = None,
2362
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
2363
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2364
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2365
+ ) -> None:
2366
+ """Inspect dependency manifests and trace internal call site reachability for packages."""
2367
+ from codegraph.security.supply_chain import analyze_supply_chain
2368
+
2369
+ repo = _resolve_repo(path, repository)
2370
+ indexer = _indexer(repo)
2371
+ with indexer.session() as con:
2372
+ rep = analyze_supply_chain(repo, con=con, target_package=package)
2373
+
2374
+ if json_output:
2375
+ cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
2376
+ else:
2377
+ cli_echo(f"Dependency Supply Chain Reachability for {repo.name}:")
2378
+ cli_echo(f" Total Dependencies: {rep.total_dependencies} | Actively Imported: {rep.actively_imported_count} | Call Sites: {rep.total_call_sites}")
2379
+ cli_echo(f" Manifests: {', '.join(rep.manifests_found)}")
2380
+ for pkg in rep.packages[:25]:
2381
+ status_str = f"IMPORTED ({pkg.call_sites_count} call sites)" if pkg.is_actively_imported else "UNINVOKED"
2382
+ cli_echo(f" • {pkg.name} ({pkg.version_spec}) [{pkg.manifest_file}]: {status_str}")
2383
+
2384
+
2385
+ @app.command("check-freshness")
2386
+ def check_freshness_cli_cmd(
2387
+ task: Annotated[str, typer.Argument(help="Task prompt to verify context freshness for")] = "",
2388
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2389
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2390
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2391
+ ) -> None:
2392
+ """Validate whether compiled context remains VALID, PARTIALLY_STALE, or STALE against repository changes."""
2393
+ from codegraph.context import get_context
2394
+ from codegraph.context_freshness import check_context_freshness
2395
+
2396
+ repo = _resolve_repo(path, repository)
2397
+ indexer = _indexer(repo)
2398
+
2399
+ with indexer.session() as con:
2400
+ # Generate baseline context if task provided
2401
+ ctx = get_context(con, repo, task or "general repository overview", mode="FAST")
2402
+ rep = check_context_freshness(ctx, repo, con=con)
2403
+
2404
+ if json_output:
2405
+ cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
2406
+ else:
2407
+ cli_echo(f"Context Freshness Status: {rep.status.value}")
2408
+ cli_echo(f"Reason: {rep.reason}")
2409
+ cli_echo(f"Recommended Action: {rep.recommended_action}")
2410
+ if rep.changed_relevant_files:
2411
+ cli_echo(f"Changed Relevant Files: {', '.join(rep.changed_relevant_files)}")
2412
+ if rep.unrelated_changed_files:
2413
+ cli_echo(f"Unrelated Changed Files: {len(rep.unrelated_changed_files)} file(s)")
2414
+
2415
+
2416
+ @app.command("symbol-history")
2417
+ def symbol_history_cli_cmd(
2418
+ symbol: Annotated[str, typer.Argument(help="Symbol name to trace across Git history")],
2419
+ file_path: Annotated[str | None, typer.Option("--file", "-f", help="File path where symbol is located")] = None,
2420
+ max_commits: Annotated[int, typer.Option("--max-commits", "-m", help="Max commits to inspect")] = 15,
2421
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2422
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2423
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2424
+ ) -> None:
2425
+ """Trace deterministic symbol evolution across Git history: introduced, modified, moved, renamed, or deleted."""
2426
+ from codegraph.symbol_history import trace_symbol_history
2427
+
2428
+ repo = _resolve_repo(path, repository)
2429
+ indexer = _indexer(repo)
2430
+
2431
+ with indexer.session() as con:
2432
+ rep = trace_symbol_history(repo, symbol=symbol, path=file_path, con=con, max_commits=max_commits)
2433
+
2434
+ if json_output:
2435
+ cli_echo(json.dumps(rep.as_dict(), indent=2), json_mode=True)
2436
+ else:
2437
+ cli_echo(f"Symbol History: {symbol}")
2438
+ cli_echo(f"Status: {rep.status} ({rep.detail})")
2439
+ for ev in rep.events:
2440
+ cli_echo(f"\n [{ev.event_type}] Commit {ev.commit_sha[:8]} on {ev.date} by {ev.author}")
2441
+ cli_echo(f" Message: {ev.message}")
2442
+ cli_echo(f" Location: {ev.path}")
2443
+ cli_echo(f" Evidence: {ev.evidence} (confidence: {ev.confidence})")
2444
+
2445
+
2446
+ refactor_app = typer.Typer(no_args_is_help=True, help="Deterministic, syntax-validated AST refactoring and atomic rollback.")
2447
+ app.add_typer(refactor_app, name="refactor")
2448
+
2449
+
2450
+ @refactor_app.command("rename")
2451
+ def refactor_rename_cli_cmd(
2452
+ target: Annotated[str, typer.Argument(help="Exact symbol name or qualified name to rename")],
2453
+ new_name: Annotated[str, typer.Argument(help="New valid Python identifier name")],
2454
+ apply: Annotated[bool, typer.Option("--apply", help="Apply changes atomically to disk (default is dry-run)")] = False,
2455
+ force: Annotated[bool, typer.Option("--force", help="Force rename despite UNKNOWN/POSSIBLE uncertainty")] = False,
2456
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2457
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2458
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2459
+ ) -> None:
2460
+ """Perform deterministic, syntax-validated, transaction-safe AST rename."""
2461
+ from codegraph.refactor.renamer import execute_safe_rename
2462
+
2463
+ repo = _resolve_repo(path, repository)
2464
+ indexer = _indexer(repo)
2465
+
2466
+ with indexer.session() as con:
2467
+ result = execute_safe_rename(
2468
+ repository=repo,
2469
+ con=con,
2470
+ target=target,
2471
+ new_name=new_name,
2472
+ dry_run=not apply,
2473
+ force_uncertain=force,
2474
+ )
2475
+
2476
+ if json_output:
2477
+ cli_echo(json.dumps(result.to_dict(), indent=2), json_mode=True)
2478
+ else:
2479
+ cli_echo(f"Refactor Status: {result.status}")
2480
+ cli_echo(f"Target: {result.target_symbol} -> {result.new_name}")
2481
+ cli_echo(f"Risk: {result.risk}")
2482
+ cli_echo(f"Files Changed: {result.files_changed}")
2483
+ cli_echo(f"Spans Count: {result.spans_count}")
2484
+ if result.rollback_id:
2485
+ cli_echo(f"Rollback ID: {result.rollback_id}")
2486
+ if result.uncertainty_reasons:
2487
+ cli_echo("\nUncertainty Reasons:")
2488
+ for reason in result.uncertainty_reasons:
2489
+ cli_echo(f" - {reason}")
2490
+ if result.tests_affected:
2491
+ cli_echo(f"Affected Tests: {', '.join(result.tests_affected)}")
2492
+ if result.routes_affected:
2493
+ cli_echo(f"Affected Routes: {', '.join(result.routes_affected)}")
2494
+ if result.diffs:
2495
+ cli_echo("\nUnified Diffs:")
2496
+ for p, diff in result.diffs.items():
2497
+ cli_echo(f"--- {p} ---")
2498
+ cli_echo(diff)
2499
+ if result.errors:
2500
+ cli_echo("\nErrors:")
2501
+ for err in result.errors:
2502
+ cli_echo(f" ! {err}")
2503
+
2504
+
2505
+ @refactor_app.command("patch")
2506
+ def refactor_patch_cli_cmd(
2507
+ patch_file: Annotated[Path, typer.Argument(help="Path to JSON file containing patch specifications (or '-' for stdin)")],
2508
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2509
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2510
+ dry_run: Annotated[bool, typer.Option("--dry-run", "-d", help="Preview patch without modifying disk")] = False,
2511
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2512
+ ) -> None:
2513
+ """Atomically apply or preview a multi-file semantic patch with pre-flight syntax validation and rollback support."""
2514
+ import sys
2515
+
2516
+ from codegraph.refactor.models import RefactorStatus
2517
+ from codegraph.refactor.patcher import apply_semantic_patch, preview_semantic_patch
2518
+
2519
+ repo = _resolve_repo(path, repository)
2520
+
2521
+ if str(patch_file) == "-":
2522
+ raw_text = sys.stdin.read()
2523
+ else:
2524
+ if not patch_file.exists():
2525
+ cli_echo(f"Error: Patch file '{patch_file}' not found.", err=True)
2526
+ raise typer.Exit(1)
2527
+ raw_text = patch_file.read_text(encoding="utf-8")
2528
+
2529
+ try:
2530
+ data = json.loads(raw_text)
2531
+ patch_specs = data if isinstance(data, list) else data.get("patches", [data])
2532
+ except Exception as e:
2533
+ cli_echo(f"Error: Invalid JSON in patch file: {e}", err=True)
2534
+ raise typer.Exit(1) from e
2535
+
2536
+ if dry_run:
2537
+ result = preview_semantic_patch(repo, patch_specs)
2538
+ else:
2539
+ result = apply_semantic_patch(repo, patch_specs, dry_run=False)
2540
+ if result.status == RefactorStatus.APPLIED:
2541
+ try:
2542
+ indexer = _indexer(repo)
2543
+ indexer.index()
2544
+ except Exception:
2545
+ pass
2546
+
2547
+ if json_output:
2548
+ cli_echo(json.dumps(result.to_dict(), indent=2), json_mode=True)
2549
+ else:
2550
+ mode_label = "DRY-RUN PREVIEW" if dry_run else "COMMIT"
2551
+ cli_echo(f"Semantic Patch ({mode_label}): {result.status}")
2552
+ cli_echo(f"Files Changed: {result.files_changed}")
2553
+ if result.rollback_id:
2554
+ cli_echo(f"Rollback ID: {result.rollback_id}")
2555
+ if result.diffs:
2556
+ cli_echo("\nDiffs:")
2557
+ for p, d in result.diffs.items():
2558
+ cli_echo(f"--- {p} ---")
2559
+ cli_echo(d)
2560
+ if result.errors:
2561
+ cli_echo("\nErrors:")
2562
+ for err in result.errors:
2563
+ cli_echo(f" ! {err}")
2564
+
2565
+
2566
+ @refactor_app.command("undo")
2567
+ def refactor_undo_cli_cmd(
2568
+ transaction_id: Annotated[str, typer.Argument(help="Transaction ID to rollback")],
2569
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2570
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2571
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON format")] = False,
2572
+ ) -> None:
2573
+ """Atomically rollback an applied refactoring transaction."""
2574
+ from codegraph.refactor.models import RefactorStatus
2575
+ from codegraph.refactor.transactions import rollback_refactor
2576
+
2577
+ repo = _resolve_repo(path, repository)
2578
+ result = rollback_refactor(repo, transaction_id)
2579
+ if result.status == RefactorStatus.ROLLED_BACK:
2580
+ try:
2581
+ indexer = _indexer(repo)
2582
+ indexer.index()
2583
+ except Exception:
2584
+ pass
2585
+
2586
+ if json_output:
2587
+ cli_echo(json.dumps(result.to_dict(), indent=2), json_mode=True)
2588
+ else:
2589
+ cli_echo(f"Rollback Status: {result.status}")
2590
+ cli_echo(f"Transaction ID: {transaction_id}")
2591
+ cli_echo(f"Files Restored: {result.files_changed}")
2592
+ if result.errors:
2593
+ cli_echo("\nErrors:")
2594
+ for err in result.errors:
2595
+ cli_echo(f" ! {err}")
2596
+
2597
+
2598
+ # ---------------------------------------------------------------------------
2599
+ # Async Queue Subcommands
2600
+ # ---------------------------------------------------------------------------
2601
+ async_app = typer.Typer(
2602
+ no_args_is_help=True,
2603
+ help="Asynchronous message queues, distributed task linking, and cross-service traces.",
2604
+ )
2605
+ app.add_typer(async_app, name="async")
2606
+
2607
+
2608
+ @async_app.command("queues")
2609
+ def async_queues_cli_cmd(
2610
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2611
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
2612
+ ) -> None:
2613
+ """List all detected asynchronous message queues, topics, and task channels."""
2614
+ from codegraph.async_queue.traversal import list_async_queues
2615
+
2616
+ repo = _resolve_repo(None, repository)
2617
+ if not _ensure_indexed(repo):
2618
+ raise typer.Exit(code=1)
2619
+
2620
+ indexer = _indexer(repo)
2621
+ with indexer.session() as con:
2622
+ queues = list_async_queues(con)
2623
+
2624
+ if json_output:
2625
+ cli_echo(json.dumps(queues, indent=2), json_mode=True)
2626
+ else:
2627
+ if not queues:
2628
+ cli_echo("No asynchronous queues, topics, or task channels detected.")
2629
+ return
2630
+
2631
+ cli_echo(f"Found {len(queues)} async queue(s):\n")
2632
+ for q in queues:
2633
+ cli_echo(
2634
+ f" [{q['system'].upper()}] {q['destination']} "
2635
+ f"(producers: {q['producer_count']}, consumers: {q['consumer_count']}, links: {q['link_count']})"
2636
+ )
2637
+
2638
+
2639
+ @async_app.command("trace")
2640
+ def async_trace_cli_cmd(
2641
+ entrypoint: Annotated[str, typer.Argument(help="Entrypoint symbol, handler, or queue topic name")],
2642
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2643
+ depth: Annotated[int, typer.Option("--depth", "-d", help="Max traversal depth")] = 5,
2644
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
2645
+ ) -> None:
2646
+ """Trace cross-process asynchronous execution flow starting from an entrypoint."""
2647
+ from codegraph.async_queue.traversal import trace_async_flow
2648
+
2649
+ repo = _resolve_repo(None, repository)
2650
+ if not _ensure_indexed(repo):
2651
+ raise typer.Exit(code=1)
2652
+
2653
+ indexer = _indexer(repo)
2654
+ with indexer.session() as con:
2655
+ result = trace_async_flow(con, entrypoint, max_depth=depth)
2656
+
2657
+ if json_output:
2658
+ cli_echo(json.dumps(result, indent=2), json_mode=True)
2659
+ else:
2660
+ if result.get("status") != "ok":
2661
+ cli_echo(f"No async flow found starting from '{entrypoint}'.")
2662
+ return
2663
+
2664
+ cli_echo(f"Async Flow Trace for '{entrypoint}':\n")
2665
+ cli_echo(f" Producers: {result['producers_count']}")
2666
+ cli_echo(f" Consumers: {result['consumers_count']}")
2667
+ cli_echo(f" Downstream DB: {result['downstream_ops_count']}\n")
2668
+ cli_echo("Execution Steps:")
2669
+ for step in result.get("flow_steps", []):
2670
+ cli_echo(
2671
+ f" [{step['step']}] {step['source']} --({step['relationship']})--> {step['target']} "
2672
+ f"[{step.get('evidence_class', 'AST_VERIFIED')}] ({step.get('file', '')}:{step.get('line', '')})"
2673
+ )
2674
+
2675
+
2676
+ @async_app.command("ingest-traces")
2677
+ def async_ingest_traces_cli_cmd(
2678
+ traces_file: Annotated[Path, typer.Argument(help="Path to JSON file containing OpenTelemetry spans (OTLP or flat JSON)")],
2679
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2680
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
2681
+ ) -> None:
2682
+ """Idempotently ingest OpenTelemetry traces and reconcile distributed links with the static graph."""
2683
+ from codegraph.async_queue.otel_parser import parse_otel_spans
2684
+ from codegraph.async_queue.reconciler import OTelTraceReconciler
2685
+
2686
+ repo = _resolve_repo(None, repository)
2687
+ if not _ensure_indexed(repo):
2688
+ raise typer.Exit(code=1)
2689
+
2690
+ if not traces_file.exists():
2691
+ cli_echo(f"Error: traces file '{traces_file}' not found.")
2692
+ raise typer.Exit(code=1)
2693
+
2694
+ try:
2695
+ content = traces_file.read_text(encoding="utf-8")
2696
+ spans = parse_otel_spans(content)
2697
+ except Exception as exc:
2698
+ cli_echo(f"Failed to read/parse traces file: {exc}")
2699
+ raise typer.Exit(code=1) from exc
2700
+
2701
+ indexer = _indexer(repo)
2702
+ with indexer.session() as con:
2703
+ reconciler = OTelTraceReconciler(con)
2704
+ res = reconciler.reconcile_spans(spans)
2705
+
2706
+ if json_output:
2707
+ cli_echo(json.dumps(res.to_dict(), indent=2), json_mode=True)
2708
+ else:
2709
+ cli_echo("OpenTelemetry Trace Ingestion Summary:\n")
2710
+ cli_echo(f" Spans Ingested: {res.spans_ingested}")
2711
+ cli_echo(f" Spans Deduplicated: {res.spans_deduplicated}")
2712
+ cli_echo(f" Links Upgraded: {res.links_upgraded} (to OTEL_DISTRIBUTED_VERIFIED)")
2713
+ cli_echo(f" Cross-Repo Observed: {res.links_created_runtime_only} (RUNTIME_ONLY_OBSERVED)")
2714
+ if res.details:
2715
+ cli_echo("\nReconciliation Details:")
2716
+ for d in res.details:
2717
+ cli_echo(f" * {d.get('action')}: {d.get('destination')} (p50={d.get('p50_ms')}ms, p95={d.get('p95_ms')}ms)")
2718
+
2719
+
2720
+ # ---------------------------------------------------------------------------
2721
+ # Database Intelligence Subcommands
2722
+ # ---------------------------------------------------------------------------
2723
+ db_app = typer.Typer(
2724
+ no_args_is_help=True,
2725
+ help="Database intelligence: tables, columns, ORM models, schema, and impact analysis.",
2726
+ )
2727
+ app.add_typer(db_app, name="db")
2728
+
2729
+
2730
+ @db_app.command("tables")
2731
+ def db_tables_cli_cmd(
2732
+ path: Annotated[Path | None, typer.Argument(help="Repository path or table name filter")] = None,
2733
+ table: Annotated[str | None, typer.Option("--table", "-t", help="Filter by table name")] = None,
2734
+ dialect: Annotated[str | None, typer.Option("--dialect", "-d", help="Filter by SQL dialect")] = None,
2735
+ schema: Annotated[str | None, typer.Option("--schema", "-s", help="Filter by schema name")] = None,
2736
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2737
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
2738
+ ) -> None:
2739
+ """Discover database tables and views in the repository."""
2740
+ from codegraph.database.interrogation import find_db_tables
2741
+
2742
+ target_table = table
2743
+ repo_path = path
2744
+ if path is not None and not path.exists() and not table:
2745
+ target_table = str(path)
2746
+ repo_path = None
2747
+ repo = _resolve_repo(repo_path, repository)
2748
+ if not _ensure_indexed(repo):
2749
+ raise typer.Exit(code=1)
2750
+
2751
+ indexer = _indexer(repo)
2752
+ with indexer.session() as con:
2753
+ res = find_db_tables(con, repo, name=target_table, dialect=dialect, schema=schema)
2754
+
2755
+ if json_output:
2756
+ cli_echo(json.dumps(res, indent=2), json_mode=True)
2757
+ else:
2758
+ tables = res.get("tables", [])
2759
+ if not tables:
2760
+ cli_echo("No database tables found.")
2761
+ return
2762
+ cli_echo(f"Found {len(tables)} database table(s):")
2763
+ for t in tables:
2764
+ models = f" -> ORM: {', '.join(t['orm_models'])}" if t.get("orm_models") else ""
2765
+ schema_prefix = f"{t['schema_name']}." if t.get("schema_name") else ""
2766
+ cli_echo(f" • {schema_prefix}{t['table_name']} ({t.get('dialect', 'sql')}) [{t.get('framework', 'db')}]{models} at {t.get('file')}:{t.get('start_line')}")
2767
+
2768
+
2769
+ @db_app.command("columns")
2770
+ def db_columns_cli_cmd(
2771
+ target: Annotated[str | None, typer.Argument(help="Table name, column name, or repository path")] = None,
2772
+ table: Annotated[str | None, typer.Option("--table", "-t", help="Filter by table name")] = None,
2773
+ column: Annotated[str | None, typer.Option("--column", "-c", help="Filter by column name")] = None,
2774
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2775
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2776
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
2777
+ ) -> None:
2778
+ """Discover database columns, data types, nullability, PK/FK flags, and ORM field mappings."""
2779
+ from codegraph.database.interrogation import find_db_columns
2780
+
2781
+ target_table = table
2782
+ target_column = column
2783
+ repo_path = path
2784
+ if target is not None:
2785
+ p = Path(target)
2786
+ if p.exists() and p.is_dir() and repo_path is None:
2787
+ repo_path = p
2788
+ elif not target_table:
2789
+ if "." in target:
2790
+ parts = target.split(".", 1)
2791
+ target_table = parts[0]
2792
+ target_column = parts[1]
2793
+ else:
2794
+ target_table = target
2795
+
2796
+ repo = _resolve_repo(repo_path, repository)
2797
+ if not _ensure_indexed(repo):
2798
+ raise typer.Exit(code=1)
2799
+
2800
+ indexer = _indexer(repo)
2801
+ with indexer.session() as con:
2802
+ res = find_db_columns(con, repo, table=target_table, column=target_column)
2803
+
2804
+ if json_output:
2805
+ cli_echo(json.dumps(res, indent=2), json_mode=True)
2806
+ else:
2807
+ cols = res.get("columns", [])
2808
+ if not cols:
2809
+ cli_echo("No database columns found.")
2810
+ return
2811
+ cli_echo(f"Found {len(cols)} database column(s):")
2812
+ for c in cols:
2813
+ pk = " [PK]" if c.get("is_primary_key") else ""
2814
+ fk = f" [FK -> {c.get('target_table')}.{c.get('target_column')}]" if c.get("is_foreign_key") else ""
2815
+ nullable = " NULL" if c.get("nullable") else " NOT NULL"
2816
+ cli_echo(f" • {c.get('table_name')}.{c.get('column_name')}: {c.get('data_type')}{nullable}{pk}{fk} ({c.get('file')}:{c.get('start_line')})")
2817
+
2818
+
2819
+ @db_app.command("models")
2820
+ def db_models_cli_cmd(
2821
+ path: Annotated[Path | None, typer.Argument(help="Repository path or model filter")] = None,
2822
+ model: Annotated[str | None, typer.Option("--model", "-m", help="Filter by model name")] = None,
2823
+ framework: Annotated[str | None, typer.Option("--framework", "-f", help="Filter by ORM framework")] = None,
2824
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2825
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
2826
+ ) -> None:
2827
+ """Discover ORM models and classes mapped to database tables."""
2828
+ from codegraph.database.interrogation import find_db_models
2829
+
2830
+ target_model = model
2831
+ repo_path = path
2832
+ if path is not None and not path.exists() and not model:
2833
+ target_model = str(path)
2834
+ repo_path = None
2835
+ repo = _resolve_repo(repo_path, repository)
2836
+ if not _ensure_indexed(repo):
2837
+ raise typer.Exit(code=1)
2838
+
2839
+ indexer = _indexer(repo)
2840
+ with indexer.session() as con:
2841
+ res = find_db_models(con, repo, model=target_model, framework=framework)
2842
+
2843
+ if json_output:
2844
+ cli_echo(json.dumps(res, indent=2), json_mode=True)
2845
+ else:
2846
+ models_list = res.get("models", [])
2847
+ if not models_list:
2848
+ cli_echo("No ORM models found.")
2849
+ return
2850
+ cli_echo(f"Found {len(models_list)} ORM model(s):")
2851
+ for m in models_list:
2852
+ tbl = f" -> Table: {m.get('table_name')}" if m.get("table_name") else ""
2853
+ cli_echo(f" • {m.get('name')} [{m.get('framework')}]{tbl} ({m.get('file')}:{m.get('start_line')})")
2854
+
2855
+
2856
+ @db_app.command("schema")
2857
+ def db_schema_cli_cmd(
2858
+ target: Annotated[str | None, typer.Argument(help="Table name to inspect, or repository path")] = None,
2859
+ table: Annotated[str | None, typer.Option("--table", "-t", help="Inspect single table in detail")] = None,
2860
+ dialect: Annotated[str | None, typer.Option("--dialect", "-d", help="Filter by SQL dialect")] = None,
2861
+ schema_name: Annotated[str | None, typer.Option("--schema", "-s", help="Filter by schema name")] = None,
2862
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2863
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2864
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
2865
+ ) -> None:
2866
+ """Inspect full database schema overview or deep table metadata."""
2867
+ from codegraph.database.interrogation import get_db_schema, get_db_table
2868
+
2869
+ target_table = table
2870
+ repo_path = path
2871
+ if target is not None:
2872
+ p = Path(target)
2873
+ if p.exists() and p.is_dir() and repo_path is None:
2874
+ repo_path = p
2875
+ elif not target_table:
2876
+ target_table = target
2877
+
2878
+ repo = _resolve_repo(repo_path, repository)
2879
+ if not _ensure_indexed(repo):
2880
+ raise typer.Exit(code=1)
2881
+
2882
+ indexer = _indexer(repo)
2883
+ with indexer.session() as con:
2884
+ if target_table:
2885
+ res = get_db_table(con, repo, table=target_table)
2886
+ else:
2887
+ res = get_db_schema(con, repo, dialect=dialect, schema=schema_name)
2888
+
2889
+ if json_output:
2890
+ cli_echo(json.dumps(res, indent=2), json_mode=True)
2891
+ else:
2892
+ if target_table:
2893
+ tbl_info = res.get("table") or {}
2894
+ cols = res.get("columns", [])
2895
+ cli_echo(f"Table: {target_table} ({tbl_info.get('dialect', 'sql')}) [{tbl_info.get('framework', 'db')}]")
2896
+ cli_echo(f"Location: {tbl_info.get('file')}:{tbl_info.get('start_line')}")
2897
+ if res.get("models"):
2898
+ cli_echo(f"ORM Models: {', '.join(m['name'] for m in res['models'])}")
2899
+ cli_echo(f"\nColumns ({len(cols)}):")
2900
+ for c in cols:
2901
+ pk = " [PK]" if c.get("is_primary_key") else ""
2902
+ fk = f" [FK -> {c.get('target_table')}.{c.get('target_column')}]" if c.get("is_foreign_key") else ""
2903
+ cli_echo(f" • {c.get('column_name')}: {c.get('data_type')}{pk}{fk}")
2904
+ if res.get("readers"):
2905
+ cli_echo(f"\nReaders ({len(res['readers'])}):")
2906
+ for r in res["readers"][:5]:
2907
+ cli_echo(f" • {r.get('symbol')} ({r.get('file')}:{r.get('line')})")
2908
+ if res.get("writers"):
2909
+ cli_echo(f"\nWriters ({len(res['writers'])}):")
2910
+ for w in res["writers"][:5]:
2911
+ cli_echo(f" • {w.get('symbol')} ({w.get('file')}:{w.get('line')})")
2912
+ else:
2913
+ cli_echo("Database Schema Overview:")
2914
+ cli_echo(f" Tables: {len(res.get('tables', []))}")
2915
+ cli_echo(f" Columns: {len(res.get('columns', []))}")
2916
+ cli_echo(f" ORM Models: {len(res.get('models', []))}")
2917
+ cli_echo(f" Relationships: {len(res.get('relationships', []))}")
2918
+ cli_echo(f" Migrations: {len(res.get('migrations', []))}")
2919
+ if res.get("tables"):
2920
+ cli_echo("\nTables:")
2921
+ for t in res["tables"][:15]:
2922
+ cli_echo(f" • {t.get('table_name')} ({t.get('dialect', 'sql')})")
2923
+ if len(res["tables"]) > 15:
2924
+ cli_echo(f" ... and {len(res['tables']) - 15} more tables")
2925
+
2926
+
2927
+ @db_app.command("impact")
2928
+ def db_impact_cli_cmd(
2929
+ target: Annotated[str, typer.Argument(help="Table name or Table.column to analyze downstream impact for")],
2930
+ column: Annotated[str | None, typer.Option("--column", "-c", help="Column name if target is a table")] = None,
2931
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
2932
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2933
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
2934
+ ) -> None:
2935
+ """Analyze bidirectional downstream impact of table/column modifications on code, routes, and tests."""
2936
+ from codegraph.database.interrogation import get_db_impact
2937
+
2938
+ target_table = target
2939
+ target_column = column
2940
+ if "." in target and not target_column:
2941
+ parts = target.split(".", 1)
2942
+ target_table = parts[0]
2943
+ target_column = parts[1]
2944
+
2945
+ repo = _resolve_repo(path, repository)
2946
+ if not _ensure_indexed(repo):
2947
+ raise typer.Exit(code=1)
2948
+
2949
+ indexer = _indexer(repo)
2950
+ with indexer.session() as con:
2951
+ res = get_db_impact(con, repo, table=target_table, column=target_column)
2952
+
2953
+ if json_output:
2954
+ cli_echo(json.dumps(res, indent=2), json_mode=True)
2955
+ else:
2956
+ cli_echo(f"Database Impact Analysis for {target}:")
2957
+ cli_echo(f" Direct Readers: {len(res.get('readers', []))}")
2958
+ cli_echo(f" Direct Writers: {len(res.get('writers', []))}")
2959
+ cli_echo(f" Reachable Routes: {len(res.get('routes', []))}")
2960
+ cli_echo(f" Impacted Tests: {len(res.get('tests', []))}")
2961
+ if res.get("routes"):
2962
+ cli_echo("\nReachable Routes:")
2963
+ for r in res["routes"]:
2964
+ cli_echo(f" • [{r.get('http_method')}] {r.get('route_path')} -> {r.get('handler')}")
2965
+ if res.get("tests"):
2966
+ cli_echo("\nImpacted Tests:")
2967
+ for t in res["tests"]:
2968
+ cli_echo(f" • {t.get('test_symbol')} ({t.get('file')}:{t.get('line')})")
2969
+
2970
+
2971
+ @db_app.command("drift")
2972
+ def db_drift_cli_cmd(
2973
+ route: Annotated[str | None, typer.Option("--route", help="Route path or endpoint to check for schema drift")] = None,
2974
+ handler: Annotated[str | None, typer.Option("--handler", "-h", help="Handler symbol to check for schema drift")] = None,
2975
+ table: Annotated[str | None, typer.Option("--table", "-t", help="Target table name (optional, inferred from mutation lineage)")] = None,
2976
+ schema: Annotated[str | None, typer.Option("--schema", "-s", help="Schema class name (optional, inferred from handler signature)")] = None,
2977
+ path: Annotated[Path | None, typer.Argument(help="Repository path (default: current directory)")] = None,
2978
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2979
+ json_output: Annotated[bool, typer.Option("--json", help="Output raw JSON array")] = False,
2980
+ ) -> None:
2981
+ """Detect Pydantic / Form validation drift against destination database table columns."""
2982
+ schema_drift(route=route, handler=handler, table=table, schema=schema, path=path, repository=repository, json_output=json_output)
2983
+
2984
+
2985
+ @db_app.command("ingest")
2986
+ def db_ingest_cli_cmd(
2987
+ source: Annotated[Path, typer.Argument(help="Path to OpenTelemetry JSON/JSONL, SQL query log, or trace file")],
2988
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
2989
+ format: Annotated[str, typer.Option("--format", "-f", help="Trace format: auto | otel | json | sql_log")] = "auto",
2990
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
2991
+ ) -> None:
2992
+ """Ingest runtime database query logs or OpenTelemetry traces into repository index."""
2993
+ ingest_cli_cmd(source=source, repository=repository, format=format, json_output=json_output)
2994
+
2995
+
2996
+ roblox_app = typer.Typer(no_args_is_help=True, help="Roblox & Luau DataModel, Remote, Module, and Service intelligence.")
2997
+ app.add_typer(roblox_app, name="roblox")
2998
+
2999
+
3000
+ @roblox_app.command("remotes")
3001
+ def roblox_remotes_cli_cmd(
3002
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
3003
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
3004
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
3005
+ ) -> None:
3006
+ """List Roblox RemoteEvents and RemoteFunctions with client dispatchers and server handlers."""
3007
+ from codegraph.roblox import list_roblox_remotes
3008
+
3009
+ repo = _resolve_repo(path, repository)
3010
+ if not _ensure_indexed(repo):
3011
+ raise typer.Exit(code=1)
3012
+
3013
+ indexer = _indexer(repo)
3014
+ with indexer.session() as con:
3015
+ res = list_roblox_remotes(con, repo)
3016
+
3017
+ if json_output:
3018
+ cli_echo(json.dumps(res, indent=2), json_mode=True)
3019
+ else:
3020
+ remotes = res.get("remotes", [])
3021
+ cli_echo(f"Roblox Remotes ({len(remotes)}):")
3022
+ for r in remotes:
3023
+ cli_echo(f" • {r.get('remote')} [{r.get('evidence_class')}]")
3024
+ for c in r.get("client_dispatchers", []):
3025
+ cli_echo(f" Client -> {c.get('symbol')} ({c.get('file')}:{c.get('line')})")
3026
+ for s in r.get("server_handlers", []):
3027
+ cli_echo(f" Server <- {s.get('symbol')} ({s.get('file')}:{s.get('line')})")
3028
+
3029
+
3030
+ @roblox_app.command("modules")
3031
+ def roblox_modules_cli_cmd(
3032
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
3033
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
3034
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
3035
+ ) -> None:
3036
+ """List Luau / Roblox modules, Rojo DataModel paths, and require edges."""
3037
+ from codegraph.roblox import list_roblox_modules
3038
+
3039
+ repo = _resolve_repo(path, repository)
3040
+ if not _ensure_indexed(repo):
3041
+ raise typer.Exit(code=1)
3042
+
3043
+ indexer = _indexer(repo)
3044
+ with indexer.session() as con:
3045
+ res = list_roblox_modules(con, repo)
3046
+
3047
+ if json_output:
3048
+ cli_echo(json.dumps(res, indent=2), json_mode=True)
3049
+ else:
3050
+ modules = res.get("modules", [])
3051
+ cli_echo(f"Roblox / Luau Modules ({len(modules)}):")
3052
+ for m in modules:
3053
+ vpath = m.get("virtual_path") or "unmapped"
3054
+ cli_echo(f" • {m.get('file')} ({vpath}) [{m.get('evidence_class')}]")
3055
+ for req in m.get("requires", []):
3056
+ cli_echo(f" REQUIRES_MODULE -> {req.get('target')} [{req.get('evidence_class')}]")
3057
+
3058
+
3059
+ @roblox_app.command("routes")
3060
+ def roblox_routes_cli_cmd(
3061
+ path: Annotated[Path | None, typer.Option("--path", "-p", help="Repository path")] = None,
3062
+ repository: Annotated[Path | None, typer.Option("--repository", "-r", "--repo", help="Repository path")] = None,
3063
+ json_output: Annotated[bool, typer.Option("--json", help="Output JSON result")] = False,
3064
+ ) -> None:
3065
+ """List Roblox Client -> Remote -> Server routes, Knit services, and DataStore persistence bindings."""
3066
+ from codegraph.roblox import list_roblox_routes
3067
+
3068
+ repo = _resolve_repo(path, repository)
3069
+ if not _ensure_indexed(repo):
3070
+ raise typer.Exit(code=1)
3071
+
3072
+ indexer = _indexer(repo)
3073
+ with indexer.session() as con:
3074
+ res = list_roblox_routes(con, repo)
3075
+
3076
+ if json_output:
3077
+ cli_echo(json.dumps(res, indent=2), json_mode=True)
3078
+ else:
3079
+ routes = res.get("routes", [])
3080
+ services = res.get("services", [])
3081
+ persistence = res.get("persistence", [])
3082
+ cli_echo(f"Roblox Network Routes ({len(routes)}):")
3083
+ for rt in routes:
3084
+ cli_echo(f" • {rt.get('client')} -> {rt.get('remote')} -> {rt.get('server')} [{rt.get('evidence_class')}]")
3085
+ if services:
3086
+ cli_echo(f"\nKnit / Flamework Services ({len(services)}):")
3087
+ for sv in services:
3088
+ cli_echo(f" • {sv.get('provider')} ({sv.get('relationship')}) -> {sv.get('service')} [{sv.get('evidence_class')}]")
3089
+ if persistence:
3090
+ cli_echo(f"\nRoblox Persistence ({len(persistence)}):")
3091
+ for p in persistence:
3092
+ cli_echo(f" • {p.get('symbol')} ({p.get('relationship')}) -> {p.get('store')} [{p.get('evidence_class')}]")
3093
+
3094
+
3095
+ if __name__ == "__main__":
3096
+ app()
1552
3097
 
1553
3098
 
1554
- if __name__ == "__main__":
1555
- app()