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 @@
1
+ """Local web visualization package."""
codegraph/web/app.py ADDED
@@ -0,0 +1,271 @@
1
+ """FastAPI app serving the CodeGraph web UI and JSON APIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from fastapi import FastAPI, HTTPException, Query
10
+ from fastapi.responses import FileResponse, JSONResponse
11
+
12
+ from codegraph.models import Decision, normalize_location_path, select_decisions
13
+ from codegraph.storage import (
14
+ connect,
15
+ count_edges_at,
16
+ db_path_for_root,
17
+ list_edges_at,
18
+ query_all_decisions,
19
+ query_decisions_for_file,
20
+ query_nodes_at,
21
+ )
22
+
23
+ STATIC_DIR = Path(__file__).parent / "static"
24
+
25
+
26
+ def _sqlite_path() -> Path:
27
+ return db_path_for_root(Path.cwd())
28
+
29
+
30
+ def _matches_scope(path: str, prefix: str) -> bool:
31
+ """True when a path is the scope itself or lives under it."""
32
+ if not prefix or prefix == ".":
33
+ return True
34
+ candidate = normalize_location_path(path or "")
35
+ return bool(candidate) and (candidate == prefix or candidate.startswith(prefix + "/"))
36
+
37
+
38
+ def _governed_paths(conn) -> dict[str, set[str]]:
39
+ """Map each decision to the code files it is bound to."""
40
+ rows = conn.execute(
41
+ "SELECT DISTINCT decision_uid, file_path FROM decision_code_links"
42
+ ).fetchall()
43
+ out: dict[str, set[str]] = {}
44
+ for decision_uid, file_path in rows:
45
+ out.setdefault(str(decision_uid), set()).add(str(file_path))
46
+ return out
47
+
48
+
49
+ def _in_scope(decision: Decision, prefix: str, governed: dict[str, set[str]]) -> bool:
50
+ """A decision is in scope when it was recorded there or governs code there."""
51
+ if _matches_scope(decision.file_path, prefix):
52
+ return True
53
+ return any(_matches_scope(path, prefix) for path in governed.get(decision.uid, ()))
54
+
55
+
56
+ def _load_graph_sqlite(at: datetime, scope: str) -> dict[str, Any]:
57
+ """Load nodes/edges/decisions valid at a timestamp, filtered by scope.
58
+
59
+ The scope is never widened behind the caller's back: an empty result means
60
+ "nothing in this scope", and the stats describe exactly what came back.
61
+ """
62
+ db_path = _sqlite_path()
63
+ if not db_path.exists():
64
+ return {"nodes": [], "edges": [], "decisions": [], "stats": _empty_stats(),
65
+ "scope": normalize_location_path(scope) or "."}
66
+ prefix = normalize_location_path(scope).rstrip("/")
67
+ conn = connect(db_path)
68
+ try:
69
+ nodes = query_nodes_at(conn, at, prefix)
70
+ edge_count = count_edges_at(conn, at, prefix)
71
+ edges = list_edges_at(conn, at, prefix, limit=400)
72
+ governed = _governed_paths(conn)
73
+ decisions = [
74
+ d
75
+ for d in select_decisions(query_all_decisions(conn))
76
+ if d.timestamp.date() <= at.date() and _in_scope(d, prefix, governed)
77
+ ]
78
+ return {
79
+ "nodes": [_node_json(n) for n in nodes],
80
+ "edges": edges,
81
+ "decisions": [_decision_json(d) for d in decisions[:50]],
82
+ "stats": {
83
+ "nodes": len(nodes),
84
+ "edges": edge_count,
85
+ "decisions": len(decisions),
86
+ },
87
+ "scope": prefix or ".",
88
+ }
89
+ finally:
90
+ conn.close()
91
+
92
+
93
+ def _empty_stats() -> dict[str, int]:
94
+ return {"nodes": 0, "edges": 0, "decisions": 0}
95
+
96
+
97
+ def _node_json(node: Any) -> dict[str, Any]:
98
+ valid_from = getattr(node, "valid_from", None)
99
+ valid_to = getattr(node, "valid_to", None)
100
+ return {
101
+ "uid": node.uid,
102
+ "kind": node.kind,
103
+ "name": node.name,
104
+ "file_path": node.file_path,
105
+ "line_start": node.line_start,
106
+ "line_end": node.line_end,
107
+ "language": node.language,
108
+ "commit_sha": getattr(node, "commit_sha", ""),
109
+ "valid_from": valid_from.isoformat() if valid_from else None,
110
+ "valid_to": valid_to.isoformat() if valid_to else None,
111
+ }
112
+
113
+
114
+ def _decision_json(decision: Decision) -> dict[str, Any]:
115
+ return {
116
+ "uid": decision.uid,
117
+ "content": decision.content,
118
+ "reason": decision.reason,
119
+ "alternatives": decision.alternatives,
120
+ "status": decision.status.value,
121
+ "source": decision.source.value,
122
+ "source_ref": decision.source_ref,
123
+ "timestamp": decision.timestamp.isoformat(),
124
+ "author": decision.author,
125
+ "file_path": decision.file_path,
126
+ "line": decision.line,
127
+ "constraints": decision.constraints,
128
+ "confidence": decision.confidence,
129
+ "category": decision.category,
130
+ "tier": decision.tier.value,
131
+ }
132
+
133
+
134
+ def create_app() -> FastAPI:
135
+ """Build the FastAPI application."""
136
+ app = FastAPI(title="CodeGraph", version="0.1.0")
137
+
138
+ @app.get("/api/health")
139
+ def health() -> dict[str, str]:
140
+ """Liveness probe."""
141
+ return {"status": "ok"}
142
+
143
+ @app.get("/")
144
+ def index() -> FileResponse:
145
+ """Serve the single-page UI."""
146
+ return FileResponse(STATIC_DIR / "index.html")
147
+
148
+ @app.get("/static/{path:path}")
149
+ def static_files(path: str) -> FileResponse:
150
+ """Serve CSS/JS assets."""
151
+ target = (STATIC_DIR / path).resolve()
152
+ if not str(target).startswith(str(STATIC_DIR.resolve())):
153
+ raise HTTPException(status_code=404, detail="Not found")
154
+ if not target.is_file():
155
+ raise HTTPException(status_code=404, detail="Not found")
156
+ return FileResponse(target)
157
+
158
+ @app.get("/api/graph")
159
+ def api_graph(
160
+ at: str = Query(default=""),
161
+ scope: str = Query(default="."),
162
+ ) -> JSONResponse:
163
+ """Return graph payload valid at a date."""
164
+ return JSONResponse(_load_graph_sqlite(_parse_date(at), scope))
165
+
166
+ @app.get("/api/why")
167
+ def api_why(
168
+ file: str = Query(...),
169
+ line: int = Query(...),
170
+ ) -> JSONResponse:
171
+ """Return node + decisions for a file:line.
172
+
173
+ Uses the same resolution as `codegraph why`, so the UI and the CLI
174
+ cannot disagree about whether a decision exists for a line.
175
+ """
176
+ from codegraph.commands.why import load_code_node_sqlite, load_decisions_sqlite
177
+
178
+ path = normalize_location_path(file)
179
+ db_path = _sqlite_path()
180
+ node = None
181
+ decisions: list[Decision] = []
182
+ level = "none"
183
+ if db_path.exists():
184
+ root = db_path.parent.parent
185
+ found = load_code_node_sqlite(path, line, root=root)
186
+ node = _node_json(found) if found else None
187
+ rows, level = load_decisions_sqlite(
188
+ path, line, root=root, commit_sha=found.commit_sha if found else ""
189
+ )
190
+ decisions = select_decisions(rows)
191
+ return JSONResponse(
192
+ {
193
+ "file": path,
194
+ "line": line,
195
+ "node": node,
196
+ "decisions": [_decision_json(d) for d in decisions[:10]],
197
+ "binding": level,
198
+ }
199
+ )
200
+
201
+ @app.get("/api/decisions")
202
+ def api_decisions(
203
+ file: str = Query(default=""),
204
+ ) -> JSONResponse:
205
+ """Return decision timeline for a file or all decisions."""
206
+ db_path = _sqlite_path()
207
+ decisions: list[Decision] = []
208
+ if db_path.exists():
209
+ conn = connect(db_path)
210
+ try:
211
+ decisions = (
212
+ query_decisions_for_file(conn, normalize_location_path(file))
213
+ if file
214
+ else query_all_decisions(conn)
215
+ )
216
+ decisions = select_decisions(decisions)
217
+ finally:
218
+ conn.close()
219
+ return JSONResponse({"decisions": [_decision_json(d) for d in decisions]})
220
+
221
+ @app.get("/api/timeline")
222
+ def api_timeline(
223
+ scope: str = Query(default="."),
224
+ ) -> JSONResponse:
225
+ """Return commit-ish date ticks for the time slider."""
226
+ return JSONResponse({"ticks": _timeline_sqlite(scope)})
227
+
228
+ return app
229
+
230
+
231
+ def _parse_date(raw: str) -> datetime:
232
+ """Parse YYYY-MM-DD or default to now (end-of-day inclusive)."""
233
+ value = (raw or "").strip()
234
+ if not value:
235
+ return datetime.now(timezone.utc)
236
+ try:
237
+ day = datetime.strptime(value, "%Y-%m-%d")
238
+ except ValueError as exc:
239
+ raise HTTPException(status_code=400, detail=f"Invalid date: {raw}") from exc
240
+ # Use end-of-day so nodes stamped later the same day are included.
241
+ return day.replace(hour=23, minute=59, second=59)
242
+
243
+
244
+ def _timeline_sqlite(scope: str) -> list[str]:
245
+ """Return the distinct dates that have node versions inside the scope."""
246
+ db_path = _sqlite_path()
247
+ if not db_path.exists():
248
+ return []
249
+ prefix = normalize_location_path(scope).rstrip("/")
250
+ conn = connect(db_path)
251
+ try:
252
+ if not prefix or prefix == ".":
253
+ rows = conn.execute(
254
+ "SELECT DISTINCT substr(valid_from, 1, 10) AS d FROM nodes "
255
+ "WHERE valid_from IS NOT NULL ORDER BY d"
256
+ ).fetchall()
257
+ else:
258
+ rows = conn.execute(
259
+ "SELECT DISTINCT substr(valid_from, 1, 10) AS d FROM nodes "
260
+ "WHERE valid_from IS NOT NULL AND (file_path = ? OR file_path LIKE ?) "
261
+ "ORDER BY d",
262
+ (prefix, prefix + "/%"),
263
+ ).fetchall()
264
+ return [r[0] for r in rows if r[0]]
265
+ finally:
266
+ conn.close()
267
+
268
+
269
+
270
+
271
+ app = create_app()
@@ -0,0 +1,356 @@
1
+ /* CodeGraph web visualizer client */
2
+ (function () {
3
+ "use strict";
4
+
5
+ // Always call the origin that served this page (works for any port/host).
6
+ const API_BASE = window.location.origin || "";
7
+
8
+ const state = {
9
+ nodes: [],
10
+ edges: [],
11
+ decisions: [],
12
+ ticks: [],
13
+ stats: null,
14
+ };
15
+
16
+ let cy = null;
17
+ let graphTimer = null;
18
+ let scopeTimer = null;
19
+
20
+ function $(id) {
21
+ return document.getElementById(id);
22
+ }
23
+
24
+ function apiUrl(path, params) {
25
+ const qs = new URLSearchParams(params || {}).toString();
26
+ return API_BASE + path + (qs ? "?" + qs : "");
27
+ }
28
+
29
+ async function fetchJson(path, params) {
30
+ const url = apiUrl(path, params);
31
+ const res = await fetch(url, { headers: { Accept: "application/json" } });
32
+ if (!res.ok) {
33
+ throw new Error("HTTP " + res.status + " for " + path);
34
+ }
35
+ return res.json();
36
+ }
37
+
38
+ function selectedKinds() {
39
+ return Array.from(document.querySelectorAll(".kind:checked")).map((el) => el.value);
40
+ }
41
+
42
+ function selectedStatus() {
43
+ return Array.from(document.querySelectorAll(".status:checked")).map((el) => el.value);
44
+ }
45
+
46
+ function currentDate() {
47
+ const ticks = state.ticks;
48
+ if (!ticks.length) return "";
49
+ const raw = Number($("time").value);
50
+ const idx = Number.isFinite(raw)
51
+ ? Math.min(ticks.length - 1, Math.max(0, Math.round(raw)))
52
+ : ticks.length - 1;
53
+ return ticks[idx];
54
+ }
55
+
56
+ async function loadTimeline() {
57
+ const scope = $("scope").value || ".";
58
+ const data = await fetchJson("/api/timeline", { scope: scope });
59
+ const ticks = data.ticks && data.ticks.length ? data.ticks : [""];
60
+ state.ticks = ticks;
61
+ const slider = $("time");
62
+ const max = Math.max(0, ticks.length - 1);
63
+ slider.min = "0";
64
+ slider.max = String(max);
65
+ slider.value = String(max);
66
+ $("time-label").textContent = currentDate() || "now";
67
+ }
68
+
69
+ function filteredNodes() {
70
+ const kinds = new Set(selectedKinds());
71
+ return state.nodes.filter((n) => kinds.has(n.kind));
72
+ }
73
+
74
+ function filteredDecisions() {
75
+ const st = new Set(selectedStatus());
76
+ return state.decisions.filter((d) => st.has(d.status));
77
+ }
78
+
79
+ const LAYOUT_OPTS = {
80
+ name: "cose",
81
+ animate: false,
82
+ nodeRepulsion: 8000,
83
+ idealEdgeLength: 80,
84
+ edgeElasticity: 100,
85
+ gravity: 0.3,
86
+ numIter: 500,
87
+ padding: 30,
88
+ randomize: false,
89
+ };
90
+
91
+ function buildElements() {
92
+ const nodes = filteredNodes().slice(0, 250);
93
+ const decisions = filteredDecisions().slice(0, 40);
94
+ const elements = [];
95
+ const live = new Set(nodes.map((n) => n.uid));
96
+ nodes.forEach((n) => {
97
+ const size = 28 + Math.min(28, (n.line_end - n.line_start) * 2);
98
+ elements.push({
99
+ data: {
100
+ id: n.uid,
101
+ label: n.name,
102
+ kind: n.kind,
103
+ type: "code",
104
+ size,
105
+ file_path: n.file_path,
106
+ line_start: n.line_start,
107
+ line_end: n.line_end,
108
+ commit_sha: n.commit_sha,
109
+ },
110
+ classes: "code " + n.kind,
111
+ });
112
+ });
113
+ decisions.forEach((d) => {
114
+ elements.push({
115
+ data: {
116
+ id: d.uid,
117
+ label: d.content.slice(0, 28),
118
+ type: "decision",
119
+ status: d.status,
120
+ content: d.content,
121
+ reason: d.reason,
122
+ source_ref: d.source_ref,
123
+ file_path: d.file_path,
124
+ line: d.line,
125
+ confidence: d.confidence,
126
+ },
127
+ classes: "decision " + d.status,
128
+ });
129
+ });
130
+ // Draw live edges only (both endpoints present in the node set).
131
+ (state.edges || []).forEach((e, i) => {
132
+ const src = e.from_uid;
133
+ const dst = e.to_uid;
134
+ if (!live.has(src) || !live.has(dst)) return;
135
+ elements.push({
136
+ data: {
137
+ id: "e" + i + ":" + src + "->" + dst,
138
+ source: src,
139
+ target: dst,
140
+ kind: e.kind || "uses",
141
+ },
142
+ classes: "edge " + (e.kind || "uses"),
143
+ });
144
+ });
145
+ return elements;
146
+ }
147
+
148
+ function ensureCy() {
149
+ if (cy) return cy;
150
+ cy = cytoscape({
151
+ container: $("cy"),
152
+ elements: buildElements(),
153
+ style: [
154
+ {
155
+ selector: "node.code",
156
+ style: {
157
+ label: "data(label)",
158
+ "background-color": "#3dffc5",
159
+ color: "#0a0e12",
160
+ "font-size": 10,
161
+ width: "data(size)",
162
+ height: "data(size)",
163
+ "text-valign": "bottom",
164
+ "text-margin-y": 6,
165
+ },
166
+ },
167
+ {
168
+ selector: "node.class",
169
+ style: { "background-color": "#6ba3ff" },
170
+ },
171
+ {
172
+ selector: "node.variable",
173
+ style: { "background-color": "#8b98a8" },
174
+ },
175
+ {
176
+ selector: "node.decision",
177
+ style: {
178
+ shape: "diamond",
179
+ "background-color": "#ffb454",
180
+ label: "data(label)",
181
+ color: "#0a0e12",
182
+ "font-size": 9,
183
+ width: 36,
184
+ height: 36,
185
+ "text-valign": "bottom",
186
+ },
187
+ },
188
+ {
189
+ selector: "edge",
190
+ style: {
191
+ width: 1.4,
192
+ "line-color": "#2a3644",
193
+ "curve-style": "bezier",
194
+ opacity: 0.85,
195
+ "target-arrow-shape": "triangle",
196
+ "arrow-scale": 0.7,
197
+ },
198
+ },
199
+ {
200
+ selector: "edge.uses",
201
+ style: {
202
+ "line-color": "#3dffc5",
203
+ "target-arrow-color": "#3dffc5",
204
+ opacity: 0.7,
205
+ },
206
+ },
207
+ {
208
+ selector: "edge.defined_by",
209
+ style: {
210
+ "line-color": "#6ba3ff",
211
+ "line-style": "dashed",
212
+ "target-arrow-color": "#6ba3ff",
213
+ },
214
+ },
215
+ {
216
+ selector: "edge.contains",
217
+ style: {
218
+ "line-color": "#7f8fa3",
219
+ "line-style": "dotted",
220
+ "target-arrow-color": "#7f8fa3",
221
+ },
222
+ },
223
+ ],
224
+ layout: LAYOUT_OPTS,
225
+ });
226
+ cy.on("tap", "node", (evt) => showDetail(evt.target.data()));
227
+ cy.on("tap", (evt) => {
228
+ if (evt.target === cy) clearDetail();
229
+ });
230
+ return cy;
231
+ }
232
+
233
+ function refreshGraph() {
234
+ ensureCy();
235
+ cy.elements().remove();
236
+ cy.add(buildElements());
237
+ cy.layout(LAYOUT_OPTS).run();
238
+ const stats = state.stats || {};
239
+ const scope = $("scope").value || ".";
240
+ $("stats").textContent =
241
+ "scope " + scope +
242
+ " · nodes " + filteredNodes().length +
243
+ " · edges " + (state.edges ? state.edges.length : 0) +
244
+ " · decisions " + filteredDecisions().length +
245
+ (!state.decisions.length && Number(stats.nodes) > 0
246
+ ? " (none recorded in this scope)"
247
+ : "");
248
+ }
249
+
250
+ async function loadGraph() {
251
+ const data = await fetchJson("/api/graph", {
252
+ at: currentDate(),
253
+ scope: $("scope").value || ".",
254
+ });
255
+ state.nodes = data.nodes || [];
256
+ state.edges = data.edges || [];
257
+ state.decisions = data.decisions || [];
258
+ state.stats = data.stats || {};
259
+ refreshGraph();
260
+ }
261
+
262
+ function showDetail(data) {
263
+ const body = $("detail-body");
264
+ if (data.type === "code") {
265
+ body.innerHTML =
266
+ "<div class='card'><strong>CodeNode</strong><br/>" +
267
+ escapeHtml(data.label) + " (" + escapeHtml(data.kind) + ")<br/>" +
268
+ escapeHtml(data.file_path) + ":" + data.line_start + "-" + data.line_end + "<br/>" +
269
+ "commit " + escapeHtml((data.commit_sha || "").slice(0, 12)) +
270
+ "</div>";
271
+ loadWhy(data.file_path, data.line_start);
272
+ return;
273
+ }
274
+ body.innerHTML =
275
+ "<div class='card'><strong>Decision</strong><br/>" +
276
+ escapeHtml(data.content || data.label) + "<br/>" +
277
+ escapeHtml(data.reason || "") + "<br/>" +
278
+ escapeHtml(data.source_ref || "") + " · " + escapeHtml(data.status || "") +
279
+ "</div>";
280
+ }
281
+
282
+ async function loadWhy(file, line) {
283
+ const data = await fetchJson("/api/why", {
284
+ file: file,
285
+ line: line,
286
+ backend: state.backend,
287
+ });
288
+ const body = $("detail-body");
289
+ let html = body.innerHTML;
290
+ (data.decisions || []).slice(0, 3).forEach((d) => {
291
+ html +=
292
+ "<div class='card'><strong>Decision</strong><br/>" +
293
+ escapeHtml(d.content) + "<br/>" +
294
+ escapeHtml(d.reason || "") + "<br/>" +
295
+ escapeHtml(d.source_ref || "") + " · " + escapeHtml(d.status) +
296
+ "</div>";
297
+ });
298
+ if (!(data.decisions || []).length) {
299
+ html += "<p class='muted'>No decision record found</p>";
300
+ }
301
+ body.innerHTML = html;
302
+ }
303
+
304
+ function clearDetail() {
305
+ $("detail-body").innerHTML = "<div class='muted'>Select a node to view decisions.</div>";
306
+ }
307
+
308
+ function escapeHtml(s) {
309
+ return String(s == null ? "" : s)
310
+ .replace(/&/g, "&amp;")
311
+ .replace(/</g, "&lt;")
312
+ .replace(/>/g, "&gt;");
313
+ }
314
+
315
+ function scheduleGraph() {
316
+ clearTimeout(graphTimer);
317
+ graphTimer = setTimeout(loadGraph, 300);
318
+ }
319
+
320
+ function scheduleScope() {
321
+ clearTimeout(scopeTimer);
322
+ scopeTimer = setTimeout(async () => {
323
+ await loadTimeline();
324
+ await loadGraph();
325
+ }, 500);
326
+ }
327
+
328
+ async function init() {
329
+ await loadTimeline();
330
+ await loadGraph();
331
+
332
+ $("time").addEventListener("input", () => {
333
+ $("time-label").textContent = currentDate() || "now";
334
+ scheduleGraph();
335
+ });
336
+ $("scope").addEventListener("input", scheduleScope);
337
+ document.querySelectorAll(".kind, .status").forEach((el) => {
338
+ el.addEventListener("change", refreshGraph);
339
+ });
340
+ document.addEventListener("keydown", (e) => {
341
+ if (e.key === "r" || e.key === "R") {
342
+ if (cy) cy.layout(LAYOUT_OPTS).run();
343
+ }
344
+ if (e.key === "f" || e.key === "F") {
345
+ document.documentElement.requestFullscreen?.();
346
+ }
347
+ if (e.key === "Escape") clearDetail();
348
+ });
349
+ }
350
+
351
+ init().catch((err) => {
352
+ $("detail-body").textContent =
353
+ "Failed to load graph: " + err +
354
+ " — run `codegraph serve` and open the URL it prints (not file://).";
355
+ });
356
+ })();
@@ -0,0 +1,59 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>CodeGraph — Visualizer</title>
7
+ <link rel="stylesheet" href="/static/styles.css" />
8
+ <script src="https://unpkg.com/cytoscape@3.28.1/dist/cytoscape.min.js"></script>
9
+ </head>
10
+ <body>
11
+ <header class="top">
12
+ <div class="brand">CodeGraph</div>
13
+ <div class="slider-wrap">
14
+ <label for="time">Time</label>
15
+ <input id="time" type="range" min="0" max="0" value="0" />
16
+ <span id="time-label">now</span>
17
+ </div>
18
+ <div class="stats" id="stats">nodes 0 · edges 0 · decisions 0</div>
19
+ </header>
20
+
21
+ <main class="layout">
22
+ <aside class="panel left">
23
+ <h2>Filters</h2>
24
+ <label>Scope
25
+ <input id="scope" type="text" placeholder="src" value="src" />
26
+ </label>
27
+ <fieldset>
28
+ <legend>Node kinds</legend>
29
+ <label><input type="checkbox" class="kind" value="function" checked /> function</label>
30
+ <label><input type="checkbox" class="kind" value="class" checked /> class</label>
31
+ <label><input type="checkbox" class="kind" value="variable" checked /> variable</label>
32
+ </fieldset>
33
+ <fieldset>
34
+ <legend>Decision status</legend>
35
+ <label><input type="checkbox" class="status" value="accepted" checked /> accepted</label>
36
+ <label><input type="checkbox" class="status" value="superseded" checked /> superseded</label>
37
+ <label><input type="checkbox" class="status" value="rejected" checked /> rejected</label>
38
+ </fieldset>
39
+ <p class="hint">R reset · F fullscreen · Esc deselect</p>
40
+ </aside>
41
+
42
+ <section id="cy" aria-label="Code graph canvas"></section>
43
+
44
+ <aside class="panel right" id="detail">
45
+ <h2>Details</h2>
46
+ <div id="detail-body" class="muted">Select a node to view decisions.</div>
47
+ </aside>
48
+ </main>
49
+
50
+ <footer class="legend">
51
+ <span><i class="dot code"></i>CodeNode</span>
52
+ <span><i class="dot decision"></i>Decision</span>
53
+ <span><i class="dot edge"></i>edges</span>
54
+ <span class="muted">Local graph · SQLite</span>
55
+ </footer>
56
+
57
+ <script src="/static/app.js"></script>
58
+ </body>
59
+ </html>