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.
- codegraph/__init__.py +37 -0
- codegraph/cli.py +106 -0
- codegraph/commands/__init__.py +1 -0
- codegraph/commands/conflicts.py +154 -0
- codegraph/commands/diff.py +189 -0
- codegraph/commands/export.py +141 -0
- codegraph/commands/graph.py +200 -0
- codegraph/commands/index.py +924 -0
- codegraph/commands/serve.py +62 -0
- codegraph/commands/why.py +645 -0
- codegraph/decisions/__init__.py +18 -0
- codegraph/decisions/conflicts.py +238 -0
- codegraph/decisions/extractor.py +698 -0
- codegraph/decisions/llm_extractor.py +161 -0
- codegraph/decisions/sources.py +298 -0
- codegraph/git/__init__.py +5 -0
- codegraph/git/diff.py +115 -0
- codegraph/git/history.py +156 -0
- codegraph/git/incremental.py +75 -0
- codegraph/git/refs.py +70 -0
- codegraph/models.py +211 -0
- codegraph/parser/__init__.py +1 -0
- codegraph/parser/base.py +164 -0
- codegraph/parser/common.py +147 -0
- codegraph/parser/parallel.py +96 -0
- codegraph/parser/registry.py +83 -0
- codegraph/parser/treesitter_cpp.py +102 -0
- codegraph/parser/treesitter_go.py +113 -0
- codegraph/parser/treesitter_java.py +79 -0
- codegraph/parser/treesitter_js.py +15 -0
- codegraph/parser/treesitter_py.py +163 -0
- codegraph/parser/treesitter_rust.py +120 -0
- codegraph/parser/treesitter_ts.py +178 -0
- codegraph/storage.py +767 -0
- codegraph/web/__init__.py +1 -0
- codegraph/web/app.py +271 -0
- codegraph/web/static/app.js +356 -0
- codegraph/web/static/index.html +59 -0
- codegraph/web/static/styles.css +92 -0
- codegraphx-0.1.0.dist-info/METADATA +262 -0
- codegraphx-0.1.0.dist-info/RECORD +44 -0
- codegraphx-0.1.0.dist-info/WHEEL +4 -0
- codegraphx-0.1.0.dist-info/entry_points.txt +2 -0
- codegraphx-0.1.0.dist-info/licenses/LICENSE +21 -0
codegraph/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""CodeGraph: Python package for the decision memory layer of your codebase."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def make_console_streams_safe() -> None:
|
|
9
|
+
"""Make console output safe on a non-UTF-8 console.
|
|
10
|
+
|
|
11
|
+
Chinese Windows defaults to GBK. Two distinct failures come from that:
|
|
12
|
+
|
|
13
|
+
* An emoji or a character GBK cannot encode (`•`, `✅`) raises
|
|
14
|
+
`UnicodeEncodeError` and kills the command.
|
|
15
|
+
* A character GBK *can* encode still comes out as mojibake when the bytes are
|
|
16
|
+
read back as UTF-8 — `·` renders as `路` in a redirected file or a CI log,
|
|
17
|
+
which is exactly the noise that makes output look broken.
|
|
18
|
+
|
|
19
|
+
Reconfiguring the stream to UTF-8 fixes both, since every character in the
|
|
20
|
+
output is then encodable and readable. When the stream cannot be reconfigured
|
|
21
|
+
(an already-wrapped object, a closed pipe) `errors="replace"` at least keeps
|
|
22
|
+
the command alive instead of dying mid-card.
|
|
23
|
+
"""
|
|
24
|
+
for stream in (sys.stdout, sys.stderr):
|
|
25
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
26
|
+
if reconfigure is None:
|
|
27
|
+
continue
|
|
28
|
+
try:
|
|
29
|
+
reconfigure(encoding="utf-8", errors="replace")
|
|
30
|
+
except (AttributeError, ValueError, OSError):
|
|
31
|
+
try:
|
|
32
|
+
reconfigure(errors="replace")
|
|
33
|
+
except (AttributeError, ValueError, OSError):
|
|
34
|
+
continue
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
make_console_streams_safe()
|
codegraph/cli.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""CodeGraph Typer CLI entrypoint."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
|
|
7
|
+
from codegraph import __version__
|
|
8
|
+
from codegraph.commands.conflicts import conflicts_command
|
|
9
|
+
from codegraph.commands.diff import diff_command
|
|
10
|
+
from codegraph.commands.export import export_command
|
|
11
|
+
from codegraph.commands.graph import graph_command
|
|
12
|
+
from codegraph.commands.index import index_command
|
|
13
|
+
from codegraph.commands.serve import serve_command
|
|
14
|
+
from codegraph.commands.why import decisions_command, why_command
|
|
15
|
+
|
|
16
|
+
app = typer.Typer(
|
|
17
|
+
name="codegraph",
|
|
18
|
+
help=(
|
|
19
|
+
"CodeGraph: turn code structure, history, and design decisions into one "
|
|
20
|
+
"queryable graph.\n\n"
|
|
21
|
+
"Answers are read from the repository's own commits, ADRs and CHANGELOG; "
|
|
22
|
+
"nothing is fabricated. Records that state a reason or a rejected "
|
|
23
|
+
"alternative are decisions, everything else is history behind "
|
|
24
|
+
"--include-events."
|
|
25
|
+
),
|
|
26
|
+
add_completion=True,
|
|
27
|
+
no_args_is_help=True,
|
|
28
|
+
rich_markup_mode="rich",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _version_callback(value: bool) -> None:
|
|
33
|
+
"""Print version and exit."""
|
|
34
|
+
if value:
|
|
35
|
+
typer.echo(f"codegraph {__version__}")
|
|
36
|
+
raise typer.Exit()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@app.callback()
|
|
40
|
+
def main(
|
|
41
|
+
version: bool = typer.Option(
|
|
42
|
+
False,
|
|
43
|
+
"--version",
|
|
44
|
+
"-V",
|
|
45
|
+
help="Show version and exit",
|
|
46
|
+
callback=_version_callback,
|
|
47
|
+
is_eager=True,
|
|
48
|
+
),
|
|
49
|
+
) -> None:
|
|
50
|
+
"""CodeGraph command-line entrypoint."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
app.command(
|
|
54
|
+
name="index",
|
|
55
|
+
help="Parse code + ingest Git history + write the graph (tree-sitter + SQLite)",
|
|
56
|
+
rich_help_panel="Core commands",
|
|
57
|
+
)(index_command)
|
|
58
|
+
|
|
59
|
+
app.command(
|
|
60
|
+
name="why",
|
|
61
|
+
help="Show the decision card behind a source line, e.g. why src/app.py:42",
|
|
62
|
+
rich_help_panel="Core commands",
|
|
63
|
+
)(why_command)
|
|
64
|
+
|
|
65
|
+
app.command(
|
|
66
|
+
name="graph",
|
|
67
|
+
help="Print a historical code-graph snapshot, e.g. graph --at 2026-09-23 --scope src",
|
|
68
|
+
rich_help_panel="Core commands",
|
|
69
|
+
)(graph_command)
|
|
70
|
+
|
|
71
|
+
app.command(
|
|
72
|
+
name="decisions",
|
|
73
|
+
help="List the decision evolution timeline for a file",
|
|
74
|
+
rich_help_panel="Core commands",
|
|
75
|
+
)(decisions_command)
|
|
76
|
+
|
|
77
|
+
app.command(
|
|
78
|
+
name="conflicts",
|
|
79
|
+
help="Detect contradictory accepted decisions in a scope",
|
|
80
|
+
rich_help_panel="Core commands",
|
|
81
|
+
)(conflicts_command)
|
|
82
|
+
|
|
83
|
+
app.command(
|
|
84
|
+
name="export",
|
|
85
|
+
help="Export an AI-agent context pack (--for-ai --scope <path>)",
|
|
86
|
+
rich_help_panel="Core commands",
|
|
87
|
+
)(export_command)
|
|
88
|
+
|
|
89
|
+
app.command(
|
|
90
|
+
name="serve",
|
|
91
|
+
help="Start the local Cytoscape web visualizer",
|
|
92
|
+
rich_help_panel="Core commands",
|
|
93
|
+
)(serve_command)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
app.command(
|
|
98
|
+
name="diff",
|
|
99
|
+
help="Show decision changes between two versions, e.g. diff 2026-09-23 2026-09-24 --scope src",
|
|
100
|
+
rich_help_panel="Core commands",
|
|
101
|
+
)(diff_command)
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
app()
|
|
105
|
+
|
|
106
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""CodeGraph subcommand package."""
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""codegraph conflicts: detect contradictory accepted decisions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
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.decisions.conflicts import detect_all
|
|
13
|
+
from codegraph.models import (
|
|
14
|
+
Conflict,
|
|
15
|
+
Decision,
|
|
16
|
+
DecisionStatus,
|
|
17
|
+
normalize_location_path,
|
|
18
|
+
select_decisions,
|
|
19
|
+
)
|
|
20
|
+
from codegraph.storage import connect, db_path_for_root, query_all_decisions
|
|
21
|
+
|
|
22
|
+
console = Console()
|
|
23
|
+
|
|
24
|
+
TYPE_LABEL = {
|
|
25
|
+
"opposite": "OPPOSITE",
|
|
26
|
+
"supersede": "SUPERSEDE",
|
|
27
|
+
"temporal": "TEMPORAL",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def filter_scope(decisions: list[Decision], scope: str) -> list[Decision]:
|
|
32
|
+
"""Keep decisions whose file_path matches the scope prefix."""
|
|
33
|
+
prefix = normalize_location_path(scope).strip("/")
|
|
34
|
+
out: list[Decision] = []
|
|
35
|
+
for d in decisions:
|
|
36
|
+
if d.status != DecisionStatus.ACCEPTED:
|
|
37
|
+
continue
|
|
38
|
+
path = normalize_location_path(d.file_path or "").replace("\\", "/")
|
|
39
|
+
if not prefix or prefix == ".":
|
|
40
|
+
out.append(d)
|
|
41
|
+
elif path and (path.startswith(prefix) or f"/{prefix}/" in f"/{path}"):
|
|
42
|
+
out.append(d)
|
|
43
|
+
return out
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def load_decisions(*, include_events: bool = False) -> list[Decision]:
|
|
47
|
+
"""Load records from the local graph database, decisions only by default.
|
|
48
|
+
|
|
49
|
+
Detecting contradictions between commit subjects is noise, so event-tier
|
|
50
|
+
records are skipped unless explicitly requested.
|
|
51
|
+
"""
|
|
52
|
+
return select_decisions(_load_all(), include_events=include_events)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _load_all() -> list[Decision]:
|
|
56
|
+
"""Load every stored record."""
|
|
57
|
+
db = db_path_for_root(Path.cwd())
|
|
58
|
+
if not db.exists():
|
|
59
|
+
return []
|
|
60
|
+
conn = connect(db)
|
|
61
|
+
try:
|
|
62
|
+
return query_all_decisions(conn)
|
|
63
|
+
finally:
|
|
64
|
+
conn.close()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _clip(text: str, n: int = 40) -> str:
|
|
68
|
+
t = " ".join((text or "").split())
|
|
69
|
+
return t if len(t) <= n else t[: n - 1] + "…"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def render_table(conflicts: list[Conflict], scope: str) -> None:
|
|
73
|
+
"""Render conflicts table + summary."""
|
|
74
|
+
if not conflicts:
|
|
75
|
+
console.print(f"[bold green]No conflicts detected[/] in scope={scope}")
|
|
76
|
+
return
|
|
77
|
+
|
|
78
|
+
table = Table(title=f"Decision conflicts · --scope {scope}")
|
|
79
|
+
table.add_column("Type", style="cyan", no_wrap=True)
|
|
80
|
+
table.add_column("Decision A", overflow="fold")
|
|
81
|
+
table.add_column("Decision B", overflow="fold")
|
|
82
|
+
table.add_column("Location", style="dim")
|
|
83
|
+
|
|
84
|
+
by_type: dict[str, int] = {}
|
|
85
|
+
for c in conflicts:
|
|
86
|
+
by_type[c.type] = by_type.get(c.type, 0) + 1
|
|
87
|
+
table.add_row(
|
|
88
|
+
TYPE_LABEL.get(c.type, c.type),
|
|
89
|
+
_clip(c.decision_a.content),
|
|
90
|
+
_clip(c.decision_b.content),
|
|
91
|
+
c.location,
|
|
92
|
+
)
|
|
93
|
+
console.print(table)
|
|
94
|
+
parts = [f"{by_type.get(k, 0)} {k}" for k in ("opposite", "supersede", "temporal")]
|
|
95
|
+
console.print(f"\nSummary: {len(conflicts)} total · " + " · ".join(parts))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def render_json(conflicts: list[Conflict], scope: str) -> None:
|
|
99
|
+
"""Render conflicts as JSON."""
|
|
100
|
+
by_type: dict[str, int] = {}
|
|
101
|
+
for c in conflicts:
|
|
102
|
+
by_type[c.type] = by_type.get(c.type, 0) + 1
|
|
103
|
+
payload = {
|
|
104
|
+
"scope": scope,
|
|
105
|
+
"conflicts": [
|
|
106
|
+
{
|
|
107
|
+
"type": c.type,
|
|
108
|
+
"decision_a": {
|
|
109
|
+
"uid": c.decision_a.uid,
|
|
110
|
+
"content": c.decision_a.content,
|
|
111
|
+
"source_ref": c.decision_a.source_ref,
|
|
112
|
+
"file_path": c.decision_a.file_path,
|
|
113
|
+
"status": c.decision_a.status.value,
|
|
114
|
+
},
|
|
115
|
+
"decision_b": {
|
|
116
|
+
"uid": c.decision_b.uid,
|
|
117
|
+
"content": c.decision_b.content,
|
|
118
|
+
"source_ref": c.decision_b.source_ref,
|
|
119
|
+
"file_path": c.decision_b.file_path,
|
|
120
|
+
"status": c.decision_b.status.value,
|
|
121
|
+
},
|
|
122
|
+
"location": c.location,
|
|
123
|
+
"matched_words": c.matched_words,
|
|
124
|
+
"explanation": c.explanation,
|
|
125
|
+
"confidence": getattr(c, "confidence", 1.0),
|
|
126
|
+
}
|
|
127
|
+
for c in conflicts
|
|
128
|
+
],
|
|
129
|
+
"summary": {"total": len(conflicts), "by_type": by_type},
|
|
130
|
+
}
|
|
131
|
+
console.print_json(json.dumps(payload, ensure_ascii=False))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def conflicts_command(
|
|
135
|
+
scope: str = typer.Option(".", "--scope", help="Path scope, e.g. docs/adr", metavar="PATH"),
|
|
136
|
+
format: str = typer.Option("table", "--format", help="table | json", metavar="FMT"),
|
|
137
|
+
) -> None:
|
|
138
|
+
"""Detect contradictory accepted decisions in a scope."""
|
|
139
|
+
if format not in {"table", "json"}:
|
|
140
|
+
console.print("[bold red]Invalid argument[/] --format must be table or json")
|
|
141
|
+
raise typer.Exit(code=2)
|
|
142
|
+
|
|
143
|
+
decisions = filter_scope(load_decisions(), scope)
|
|
144
|
+
conflicts = detect_all(decisions)
|
|
145
|
+
if format == "json":
|
|
146
|
+
render_json(conflicts, scope)
|
|
147
|
+
else:
|
|
148
|
+
render_table(conflicts, scope)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
app = typer.Typer(help="Detect contradictory accepted decisions")
|
|
152
|
+
|
|
153
|
+
if __name__ == "__main__":
|
|
154
|
+
app()
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""codegraph diff: decision changes between two versions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
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.git.refs import RefError, resolve_ref
|
|
13
|
+
from codegraph.models import Decision, DecisionChange, select_decisions
|
|
14
|
+
from codegraph.storage import connect, db_path_for_root, query_decisions_at
|
|
15
|
+
|
|
16
|
+
console = Console()
|
|
17
|
+
|
|
18
|
+
KIND_LABEL = {
|
|
19
|
+
"added": "+ ADDED",
|
|
20
|
+
"removed": "- REMOVED",
|
|
21
|
+
"changed": "~ CHANGED",
|
|
22
|
+
"superseded": "x SUPERSEDED",
|
|
23
|
+
}
|
|
24
|
+
KIND_ORDER = {"added": 0, "changed": 1, "superseded": 2, "removed": 3}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def compute_changes(
|
|
28
|
+
from_decisions: list[Decision], to_decisions: list[Decision]
|
|
29
|
+
) -> list[DecisionChange]:
|
|
30
|
+
"""Compute added/removed/changed/superseded decision deltas."""
|
|
31
|
+
old = {d.uid: d for d in from_decisions}
|
|
32
|
+
new = {d.uid: d for d in to_decisions}
|
|
33
|
+
out: list[DecisionChange] = []
|
|
34
|
+
|
|
35
|
+
for uid, dec in new.items():
|
|
36
|
+
if uid not in old:
|
|
37
|
+
out.append(
|
|
38
|
+
DecisionChange(
|
|
39
|
+
kind="added", decision=dec, old_status=None, new_status=dec.status.value
|
|
40
|
+
)
|
|
41
|
+
)
|
|
42
|
+
continue
|
|
43
|
+
prev = old[uid]
|
|
44
|
+
if prev.status != dec.status and dec.status.value == "superseded":
|
|
45
|
+
out.append(
|
|
46
|
+
DecisionChange(
|
|
47
|
+
kind="superseded",
|
|
48
|
+
decision=dec,
|
|
49
|
+
old_status=prev.status.value,
|
|
50
|
+
new_status=dec.status.value,
|
|
51
|
+
)
|
|
52
|
+
)
|
|
53
|
+
elif prev.status != dec.status or prev.content != dec.content or prev.reason != dec.reason:
|
|
54
|
+
out.append(
|
|
55
|
+
DecisionChange(
|
|
56
|
+
kind="changed",
|
|
57
|
+
decision=dec,
|
|
58
|
+
old_status=prev.status.value,
|
|
59
|
+
new_status=dec.status.value,
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
for uid, dec in old.items():
|
|
64
|
+
if uid not in new:
|
|
65
|
+
out.append(
|
|
66
|
+
DecisionChange(
|
|
67
|
+
kind="removed", decision=dec, old_status=dec.status.value, new_status=None
|
|
68
|
+
)
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
out.sort(key=lambda c: (KIND_ORDER.get(c.kind, 9), c.decision.content))
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _scope_label(decision: Decision) -> str:
|
|
76
|
+
path = decision.file_path or ""
|
|
77
|
+
return path.rsplit("/", 1)[0] if "/" in path else (path or "(global)")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def render_table(from_ref: str, to_ref: str, scope: str, changes: list[DecisionChange]) -> None:
|
|
81
|
+
"""Print a Rich table of decision changes."""
|
|
82
|
+
console.print(f"[bold]Decision changes:[/] {from_ref} → {to_ref}")
|
|
83
|
+
console.print(f"Scope: {scope}\n")
|
|
84
|
+
if not changes:
|
|
85
|
+
console.print("[yellow]No decision changes in this range[/]")
|
|
86
|
+
return
|
|
87
|
+
|
|
88
|
+
table = Table(show_lines=False)
|
|
89
|
+
table.add_column("Change", style="cyan", no_wrap=True)
|
|
90
|
+
table.add_column("Decision", overflow="fold")
|
|
91
|
+
table.add_column("Source", style="dim")
|
|
92
|
+
table.add_column("Scope", style="dim")
|
|
93
|
+
|
|
94
|
+
counts = {"added": 0, "changed": 0, "removed": 0, "superseded": 0}
|
|
95
|
+
for ch in changes:
|
|
96
|
+
counts[ch.kind] = counts.get(ch.kind, 0) + 1
|
|
97
|
+
content = ch.decision.content
|
|
98
|
+
if len(content) > 50:
|
|
99
|
+
content = content[:47] + "..."
|
|
100
|
+
date = ch.decision.timestamp.date().isoformat()
|
|
101
|
+
source = f"{ch.decision.source_ref or ch.decision.source.value} · {date}"
|
|
102
|
+
table.add_row(KIND_LABEL.get(ch.kind, ch.kind), content, source, _scope_label(ch.decision))
|
|
103
|
+
|
|
104
|
+
console.print(table)
|
|
105
|
+
summary = (
|
|
106
|
+
f"{counts.get('added', 0)} added · {counts.get('changed', 0)} changed · "
|
|
107
|
+
f"{counts.get('removed', 0)} removed · {counts.get('superseded', 0)} superseded"
|
|
108
|
+
)
|
|
109
|
+
console.print(f"\nSummary: {summary}")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def render_json(changes: list[DecisionChange]) -> None:
|
|
113
|
+
"""Print JSON payload."""
|
|
114
|
+
payload = {
|
|
115
|
+
"changes": [
|
|
116
|
+
{
|
|
117
|
+
"kind": c.kind,
|
|
118
|
+
"content": c.decision.content,
|
|
119
|
+
"reason": c.decision.reason,
|
|
120
|
+
"source": c.decision.source.value,
|
|
121
|
+
"source_ref": c.decision.source_ref,
|
|
122
|
+
"status": c.decision.status.value,
|
|
123
|
+
"old_status": c.old_status,
|
|
124
|
+
"new_status": c.new_status,
|
|
125
|
+
"file_path": c.decision.file_path,
|
|
126
|
+
"timestamp": c.decision.timestamp.isoformat(),
|
|
127
|
+
}
|
|
128
|
+
for c in changes
|
|
129
|
+
],
|
|
130
|
+
"summary": {
|
|
131
|
+
"added": sum(1 for c in changes if c.kind == "added"),
|
|
132
|
+
"changed": sum(1 for c in changes if c.kind == "changed"),
|
|
133
|
+
"removed": sum(1 for c in changes if c.kind == "removed"),
|
|
134
|
+
"superseded": sum(1 for c in changes if c.kind == "superseded"),
|
|
135
|
+
},
|
|
136
|
+
}
|
|
137
|
+
console.print_json(json.dumps(payload, ensure_ascii=False))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def diff_command(
|
|
141
|
+
from_ref: str = typer.Argument(..., help="Start version (tag / sha / YYYY-MM-DD)"),
|
|
142
|
+
to_ref: str = typer.Argument(..., help="End version (tag / sha / YYYY-MM-DD)"),
|
|
143
|
+
scope: str = typer.Option(".", "--scope", help="Path prefix scope", metavar="PATH"),
|
|
144
|
+
format: str = typer.Option("table", "--format", help="table | json", metavar="FMT"),
|
|
145
|
+
) -> None:
|
|
146
|
+
"""Show decision changes between two versions."""
|
|
147
|
+
if format not in {"table", "json"}:
|
|
148
|
+
console.print("[bold red]Invalid argument[/] --format must be table or json")
|
|
149
|
+
raise typer.Exit(code=2)
|
|
150
|
+
|
|
151
|
+
root = Path.cwd()
|
|
152
|
+
try:
|
|
153
|
+
from_sha, from_ts = resolve_ref(root, from_ref)
|
|
154
|
+
to_sha, to_ts = resolve_ref(root, to_ref)
|
|
155
|
+
except RefError as exc:
|
|
156
|
+
console.print(f"[bold red]Invalid argument[/] {exc}")
|
|
157
|
+
raise typer.Exit(code=2) from exc
|
|
158
|
+
|
|
159
|
+
if from_ts > to_ts:
|
|
160
|
+
console.print("[bold red]Invalid argument[/] from must be earlier than to")
|
|
161
|
+
raise typer.Exit(code=2)
|
|
162
|
+
|
|
163
|
+
db_path = db_path_for_root(root)
|
|
164
|
+
if not db_path.exists():
|
|
165
|
+
console.print("[bold red]No index found[/] Run codegraph index first")
|
|
166
|
+
raise typer.Exit(code=1)
|
|
167
|
+
|
|
168
|
+
conn = connect(db_path)
|
|
169
|
+
try:
|
|
170
|
+
from_decs = select_decisions(query_decisions_at(conn, from_ts, scope))
|
|
171
|
+
to_decs = select_decisions(query_decisions_at(conn, to_ts, scope))
|
|
172
|
+
finally:
|
|
173
|
+
conn.close()
|
|
174
|
+
|
|
175
|
+
if not from_decs and not to_decs:
|
|
176
|
+
console.print("[yellow]No decisions in scope[/]")
|
|
177
|
+
raise typer.Exit(code=0)
|
|
178
|
+
|
|
179
|
+
changes = compute_changes(from_decs, to_decs)
|
|
180
|
+
if format == "json":
|
|
181
|
+
render_json(changes)
|
|
182
|
+
else:
|
|
183
|
+
render_table(from_ref, to_ref, scope, changes)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
app = typer.Typer(help="Diff decisions between two versions")
|
|
187
|
+
|
|
188
|
+
if __name__ == "__main__":
|
|
189
|
+
app()
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""codegraph export: write an AI-agent context pack."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import typer
|
|
9
|
+
from rich.console import Console
|
|
10
|
+
|
|
11
|
+
from codegraph.models import Decision, normalize_location_path, select_decisions
|
|
12
|
+
from codegraph.storage import (
|
|
13
|
+
connect,
|
|
14
|
+
db_path_for_root,
|
|
15
|
+
query_all_decisions,
|
|
16
|
+
query_nodes_at,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
console = Console()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def load_context_data(scope: str) -> tuple[list, list[Decision]]:
|
|
23
|
+
"""Load nodes and decisions for the export scope."""
|
|
24
|
+
db_path = db_path_for_root(Path.cwd())
|
|
25
|
+
if not db_path.exists():
|
|
26
|
+
return [], []
|
|
27
|
+
now = datetime.now(timezone.utc)
|
|
28
|
+
conn = connect(db_path)
|
|
29
|
+
try:
|
|
30
|
+
nodes = query_nodes_at(conn, now, scope)
|
|
31
|
+
prefix = normalize_location_path(scope)
|
|
32
|
+
decisions = select_decisions(query_all_decisions(conn))
|
|
33
|
+
if prefix and prefix != ".":
|
|
34
|
+
decisions = [d for d in decisions if (d.file_path or "").startswith(prefix)]
|
|
35
|
+
return nodes, decisions
|
|
36
|
+
finally:
|
|
37
|
+
conn.close()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_context_markdown(nodes: list, decisions: list[Decision], scope: str) -> str:
|
|
41
|
+
"""Render the context pack markdown body."""
|
|
42
|
+
lines: list[str] = [
|
|
43
|
+
"# CodeGraph Context Pack",
|
|
44
|
+
f"Generated: {datetime.now(timezone.utc).isoformat()}",
|
|
45
|
+
f"Scope: {scope}",
|
|
46
|
+
"",
|
|
47
|
+
]
|
|
48
|
+
by_file: dict[str, list] = {}
|
|
49
|
+
for node in nodes:
|
|
50
|
+
by_file.setdefault(node.file_path, []).append(node)
|
|
51
|
+
|
|
52
|
+
for file_path, file_nodes in sorted(by_file.items()):
|
|
53
|
+
lines.append(f"## File: {file_path}")
|
|
54
|
+
lines.append("")
|
|
55
|
+
for node in file_nodes[:30]:
|
|
56
|
+
start = getattr(node, "line_start", 0)
|
|
57
|
+
end = getattr(node, "line_end", 0)
|
|
58
|
+
name = getattr(node, "name", "?")
|
|
59
|
+
lines.append(f"### CodeNode: {name} (lines {start}-{end})")
|
|
60
|
+
related = _related_decisions(decisions, file_path, start, end)
|
|
61
|
+
if related:
|
|
62
|
+
lines.append("Related decisions:")
|
|
63
|
+
for decision in related[:3]:
|
|
64
|
+
lines.append(f"- [{decision.uid[:12]}] {decision.content}")
|
|
65
|
+
if decision.reason:
|
|
66
|
+
lines.append(f" Reason: {decision.reason[:160]}")
|
|
67
|
+
if decision.source_ref:
|
|
68
|
+
lines.append(f" Source: {decision.source_ref}")
|
|
69
|
+
lines.append(f" Status: {decision.status.value}")
|
|
70
|
+
if decision.constraints:
|
|
71
|
+
lines.append(f" Constraint: {decision.constraints[0][:120]}")
|
|
72
|
+
else:
|
|
73
|
+
lines.append("Related decisions: (none indexed)")
|
|
74
|
+
lines.append("")
|
|
75
|
+
lines.append(
|
|
76
|
+
"Paste this into Cursor/Claude/Copilot before editing these files."
|
|
77
|
+
)
|
|
78
|
+
lines.append("")
|
|
79
|
+
return "\n".join(lines)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _related_decisions(
|
|
83
|
+
decisions: list[Decision], file_path: str, line_start: int, line_end: int
|
|
84
|
+
) -> list[Decision]:
|
|
85
|
+
"""Pick decisions bound to the file or covering a line in the node."""
|
|
86
|
+
out: list[Decision] = []
|
|
87
|
+
for decision in decisions:
|
|
88
|
+
if decision.file_path == file_path or decision.file_path.startswith(file_path):
|
|
89
|
+
out.append(decision)
|
|
90
|
+
continue
|
|
91
|
+
if decision.line is not None and decision.file_path == file_path:
|
|
92
|
+
if line_start <= decision.line <= line_end:
|
|
93
|
+
out.append(decision)
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def export_command(
|
|
98
|
+
for_ai: bool = typer.Option(
|
|
99
|
+
False,
|
|
100
|
+
"--for-ai",
|
|
101
|
+
help="Write an AI-agent context pack",
|
|
102
|
+
),
|
|
103
|
+
scope: str = typer.Option(
|
|
104
|
+
".",
|
|
105
|
+
"--scope",
|
|
106
|
+
help="Path scope, e.g. src or src/auth",
|
|
107
|
+
metavar="PATH",
|
|
108
|
+
),
|
|
109
|
+
output: Path = typer.Option(
|
|
110
|
+
Path(".codegraph/context.md"),
|
|
111
|
+
"--output",
|
|
112
|
+
help="Output markdown path",
|
|
113
|
+
metavar="PATH",
|
|
114
|
+
),
|
|
115
|
+
) -> None:
|
|
116
|
+
"""Export graph + decisions as an AI context pack.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
for_ai: Must be true to write the pack (explicit intent).
|
|
120
|
+
scope: Path prefix scope.
|
|
121
|
+
output: Destination markdown file.
|
|
122
|
+
"""
|
|
123
|
+
if not for_ai:
|
|
124
|
+
console.print("[bold red]Invalid argument[/] Use --for-ai to export a context pack")
|
|
125
|
+
raise typer.Exit(code=2)
|
|
126
|
+
|
|
127
|
+
nodes, decisions = load_context_data(scope)
|
|
128
|
+
text = build_context_markdown(nodes, decisions, scope)
|
|
129
|
+
output = output.expanduser()
|
|
130
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
output.write_text(text, encoding="utf-8")
|
|
132
|
+
console.print(f"[bold green]Context pack written[/] {output}")
|
|
133
|
+
console.print(f" · CodeNodes: [bold]{len(nodes)}[/]")
|
|
134
|
+
console.print(f" · Decisions: [bold]{len(decisions)}[/]")
|
|
135
|
+
console.print("[dim]Paste this into Cursor/Claude/Copilot before editing these files.[/]")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
app = typer.Typer(help="Export an AI-agent context pack")
|
|
139
|
+
|
|
140
|
+
if __name__ == "__main__":
|
|
141
|
+
app()
|