codegraphx 0.1.0__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 (44) hide show
  1. codegraph/__init__.py +37 -0
  2. codegraph/cli.py +106 -0
  3. codegraph/commands/__init__.py +1 -0
  4. codegraph/commands/conflicts.py +154 -0
  5. codegraph/commands/diff.py +189 -0
  6. codegraph/commands/export.py +141 -0
  7. codegraph/commands/graph.py +200 -0
  8. codegraph/commands/index.py +924 -0
  9. codegraph/commands/serve.py +62 -0
  10. codegraph/commands/why.py +645 -0
  11. codegraph/decisions/__init__.py +18 -0
  12. codegraph/decisions/conflicts.py +238 -0
  13. codegraph/decisions/extractor.py +698 -0
  14. codegraph/decisions/llm_extractor.py +161 -0
  15. codegraph/decisions/sources.py +298 -0
  16. codegraph/git/__init__.py +5 -0
  17. codegraph/git/diff.py +115 -0
  18. codegraph/git/history.py +156 -0
  19. codegraph/git/incremental.py +75 -0
  20. codegraph/git/refs.py +70 -0
  21. codegraph/models.py +211 -0
  22. codegraph/parser/__init__.py +1 -0
  23. codegraph/parser/base.py +164 -0
  24. codegraph/parser/common.py +147 -0
  25. codegraph/parser/parallel.py +96 -0
  26. codegraph/parser/registry.py +83 -0
  27. codegraph/parser/treesitter_cpp.py +102 -0
  28. codegraph/parser/treesitter_go.py +113 -0
  29. codegraph/parser/treesitter_java.py +79 -0
  30. codegraph/parser/treesitter_js.py +15 -0
  31. codegraph/parser/treesitter_py.py +163 -0
  32. codegraph/parser/treesitter_rust.py +120 -0
  33. codegraph/parser/treesitter_ts.py +178 -0
  34. codegraph/storage.py +767 -0
  35. codegraph/web/__init__.py +1 -0
  36. codegraph/web/app.py +271 -0
  37. codegraph/web/static/app.js +356 -0
  38. codegraph/web/static/index.html +59 -0
  39. codegraph/web/static/styles.css +92 -0
  40. codegraphx-0.1.0.dist-info/METADATA +262 -0
  41. codegraphx-0.1.0.dist-info/RECORD +44 -0
  42. codegraphx-0.1.0.dist-info/WHEEL +4 -0
  43. codegraphx-0.1.0.dist-info/entry_points.txt +2 -0
  44. codegraphx-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,200 @@
1
+ """codegraph graph: real time-travel code-graph snapshot."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, datetime, time, timezone
6
+ from pathlib import Path
7
+
8
+ import typer
9
+ from rich.console import Console
10
+ from rich.table import Table
11
+
12
+ from codegraph.models import CodeNode, Decision, decision_to_dict, select_decisions
13
+ from codegraph.storage import (
14
+ connect,
15
+ count_edges_at,
16
+ db_path_for_root,
17
+ query_nodes_at,
18
+ )
19
+
20
+ console = Console()
21
+
22
+
23
+ class DateError(ValueError):
24
+ """Date string is invalid."""
25
+
26
+
27
+ def parse_date(raw: str) -> date:
28
+ """Parse YYYY-MM-DD date string."""
29
+ value = raw.strip()
30
+ try:
31
+ return datetime.strptime(value, "%Y-%m-%d").date()
32
+ except ValueError as exc:
33
+ raise DateError(f"Date '{raw}' is invalid. Use YYYY-MM-DD, e.g. 2024-11-02") from exc
34
+
35
+
36
+ def local_day_end(day: date) -> datetime:
37
+ """Return the last instant of a local calendar day as an aware UTC datetime.
38
+
39
+ Stored `valid_from` / `valid_to` values are UTC ISO strings, so the query
40
+ boundary has to be UTC too. Treating local midnight as if it were UTC put the
41
+ cut-off eight hours late east of Greenwich.
42
+ """
43
+ return datetime.combine(day, time(23, 59, 59)).astimezone(timezone.utc)
44
+
45
+
46
+ def filter_decisions_at(decisions: list[Decision], at: date) -> list[Decision]:
47
+ """Return decisions created on or before the given local date."""
48
+ return [d for d in decisions if d.timestamp.astimezone().date() <= at]
49
+
50
+
51
+ def load_snapshot_sqlite(
52
+ root: Path, at: date, scope: str
53
+ ) -> tuple[int, int, int, list[str], list[Decision]]:
54
+ """Load a historical snapshot from SQLite."""
55
+ db_path = db_path_for_root(root)
56
+ at_dt = local_day_end(at)
57
+ if not db_path.exists():
58
+ return 0, 0, 0, [], []
59
+
60
+ conn = connect(db_path)
61
+ try:
62
+ nodes = query_nodes_at(conn, at_dt, scope)
63
+ decisions = filter_decisions_at(_load_decisions(conn, scope), at)
64
+ # Deduplicate symbol versions for a readable summary (keep newest range).
65
+ summary = _unique_node_summaries(nodes)
66
+ edge_count = count_edges_at(conn, at_dt, scope)
67
+ return (
68
+ len(nodes),
69
+ edge_count,
70
+ len(decisions),
71
+ summary,
72
+ decisions,
73
+ )
74
+ finally:
75
+ conn.close()
76
+
77
+
78
+ def _unique_node_summaries(nodes: list[CodeNode]) -> list[str]:
79
+ """Return one summary line per (file, name), preferring the tightest range."""
80
+ best: dict[tuple[str, str], CodeNode] = {}
81
+ for node in nodes:
82
+ key = (node.file_path, node.name)
83
+ prev = best.get(key)
84
+ if prev is None or (node.line_end - node.line_start) < (prev.line_end - prev.line_start):
85
+ best[key] = node
86
+ lines = [
87
+ f"{n.kind} {n.name} @ {n.file_path}:{n.line_start}-{n.line_end}"
88
+ for n in best.values()
89
+ ]
90
+ return lines[:8]
91
+
92
+
93
+ def _load_decisions(conn, scope: str) -> list[Decision]:
94
+ """Load decisions from DB, optionally filtered by scope prefix."""
95
+ from codegraph.storage import query_all_decisions
96
+
97
+ rows = select_decisions(query_all_decisions(conn))
98
+ prefix = (scope or "").replace("\\", "/").rstrip("/")
99
+ if prefix and prefix != ".":
100
+ rows = [d for d in rows if d.file_path.startswith(prefix)]
101
+ return rows
102
+
103
+
104
+ def summarize_changes(at: date, sample_nodes: list[str], decisions: list[Decision]) -> list[str]:
105
+ """Build a short change summary for the snapshot date."""
106
+ lines: list[str] = []
107
+ for item in sample_nodes:
108
+ lines.append(f"Structure: {item}")
109
+ for decision in decisions:
110
+ if decision.timestamp.date() == at:
111
+ lines.append(f"Decision: {decision.content} ({decision.source_ref})")
112
+ if not lines:
113
+ lines.append(f"No nodes valid at {at.isoformat()} for this scope")
114
+ return lines
115
+
116
+
117
+ def build_graph_table(
118
+ at: date,
119
+ scope: str,
120
+ node_count: int,
121
+ edge_count: int,
122
+ decision_count: int,
123
+ ) -> Table:
124
+ """Build the code-graph summary table."""
125
+ table = Table(
126
+ title=f"Code graph snapshot · --at {at.isoformat()} · --scope {scope}",
127
+ show_lines=False,
128
+ )
129
+ table.add_column("Metric", style="cyan", no_wrap=True)
130
+ table.add_column("Value", style="white")
131
+ table.add_column("Notes", style="dim")
132
+ table.add_row(
133
+ "Date",
134
+ at.isoformat(),
135
+ "valid_from <= date AND (valid_to is null OR valid_to >= date)",
136
+ )
137
+ table.add_row("Nodes", str(node_count), "CodeNode versions valid at date")
138
+ table.add_row("Edges", str(edge_count), "edges with both endpoints valid at date")
139
+ table.add_row("Decisions", str(decision_count), "Decision (not after this date)")
140
+ return table
141
+
142
+
143
+ def graph_command(
144
+ at: str = typer.Option(..., "--at", help="Snapshot date, format YYYY-MM-DD", metavar="DATE"),
145
+ scope: str = typer.Option(
146
+ ".",
147
+ "--scope",
148
+ help="Path scope, e.g. src or src/auth",
149
+ metavar="PATH",
150
+ ),
151
+ as_json: bool = typer.Option(
152
+ False,
153
+ "--json",
154
+ help="Emit machine-readable JSON instead of a table",
155
+ ),
156
+ ) -> None:
157
+ """Print a code-graph snapshot for a historical date and scope.
158
+
159
+ Args:
160
+ at: Snapshot date (YYYY-MM-DD).
161
+ scope: Path prefix scope.
162
+ as_json: Emit JSON for editors and scripts.
163
+ """
164
+ try:
165
+ at_date = parse_date(at)
166
+ except DateError as exc:
167
+ console.print(f"[bold red]Invalid argument[/] {exc}")
168
+ raise typer.Exit(code=2) from exc
169
+
170
+ root = Path.cwd()
171
+ node_count, edge_count, decision_count, sample, decisions = load_snapshot_sqlite(
172
+ root, at_date, scope
173
+ )
174
+
175
+ if as_json:
176
+ import json as jsonlib
177
+
178
+ payload = {
179
+ "date": at_date.isoformat(),
180
+ "scope": scope,
181
+ "nodes": node_count,
182
+ "edges": edge_count,
183
+ "decisions": decision_count,
184
+ "summary": summarize_changes(at_date, sample, decisions),
185
+ "decision_records": [decision_to_dict(d) for d in decisions],
186
+ }
187
+ typer.echo(jsonlib.dumps(payload, ensure_ascii=False, indent=2))
188
+ return
189
+
190
+ console.print(build_graph_table(at_date, scope, node_count, edge_count, decision_count))
191
+ console.print()
192
+ console.print("[bold cyan]Change summary[/]")
193
+ for line in summarize_changes(at_date, sample, decisions):
194
+ console.print(f" · {line}")
195
+
196
+
197
+ app = typer.Typer(help="Historical code-graph snapshot (time travel)")
198
+
199
+ if __name__ == "__main__":
200
+ app()