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,62 @@
1
+ """codegraph serve: start the local web visualizer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import time
7
+ import webbrowser
8
+
9
+ import typer
10
+ from rich.console import Console
11
+
12
+ console = Console()
13
+
14
+ READY_TIMEOUT_SECONDS = 5.0
15
+
16
+
17
+ def open_when_ready(server, url: str, timeout: float = READY_TIMEOUT_SECONDS) -> None:
18
+ """Open the browser only once the server is actually accepting requests.
19
+
20
+ Opening before the port is bound shows a connection error to the user, and
21
+ on a busy port the tab points at whatever else is listening.
22
+ """
23
+ deadline = time.monotonic() + timeout
24
+ while not server.started and time.monotonic() < deadline:
25
+ time.sleep(0.05)
26
+ if server.started:
27
+ webbrowser.open(url)
28
+
29
+
30
+ def serve_command(
31
+ port: int = typer.Option(8080, "--port", help="HTTP port", metavar="N"),
32
+ open_browser: bool = typer.Option(
33
+ True,
34
+ "--open-browser/--no-open-browser",
35
+ help="Open the UI in the default browser",
36
+ ),
37
+ ) -> None:
38
+ """Start the local Cytoscape web visualizer.
39
+
40
+ Args:
41
+ port: HTTP listen port.
42
+ open_browser: Launch a browser tab once the server is listening.
43
+ """
44
+ import uvicorn
45
+
46
+ from codegraph.web.app import app
47
+
48
+ url = f"http://127.0.0.1:{port}/"
49
+ config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="info")
50
+ server = uvicorn.Server(config)
51
+ console.print(f"[bold green]CodeGraph UI[/] {url}")
52
+ if open_browser:
53
+ threading.Thread(
54
+ target=open_when_ready, args=(server, url), daemon=True
55
+ ).start()
56
+ server.run()
57
+
58
+
59
+ app = typer.Typer(help="Start the local web visualizer")
60
+
61
+ if __name__ == "__main__":
62
+ app()
@@ -0,0 +1,645 @@
1
+ """codegraph why: decision provenance for a source location."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import sqlite3
7
+ import sys
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+ import typer
12
+ from rich.console import Console
13
+ from rich.panel import Panel
14
+ from rich.table import Table
15
+ from rich.text import Text
16
+
17
+ from codegraph.models import (
18
+ CodeNode,
19
+ Decision,
20
+ decision_to_dict,
21
+ node_to_dict,
22
+ normalize_location_path,
23
+ select_decisions,
24
+ )
25
+ from codegraph.storage import (
26
+ connect,
27
+ db_path_for_root,
28
+ find_db,
29
+ find_node_at_line,
30
+ query_decisions_for_commit,
31
+ query_decisions_for_dir,
32
+ query_decisions_for_file,
33
+ query_decisions_for_file_links,
34
+ query_decisions_for_line,
35
+ query_decisions_for_line_links,
36
+ query_decisions_for_node_lines,
37
+ )
38
+
39
+ console = Console()
40
+
41
+ LOCATION_RE = re.compile(r"^(?P<file>.+):(?P<line>\d+)$")
42
+
43
+
44
+ class LocationError(ValueError):
45
+ """User-supplied file:line is invalid."""
46
+
47
+
48
+ def normalize_user_path(raw: str) -> str:
49
+ """Normalize a user path, turning an absolute path inside the repo into a relative one.
50
+
51
+ Editors such as the VS Code extension hand over `doc.uri.fsPath`, which is
52
+ absolute; stored paths are repo-relative.
53
+
54
+ The base has to be the repository root, not the current directory: after
55
+ `find_db` locates a database above cwd, the caller may be anywhere, and an
56
+ absolute path that is not under cwd would otherwise stay absolute
57
+ (`D:/repo/src/a.py`), which never matches the stored `src/a.py`.
58
+ """
59
+ path = Path(raw)
60
+ if not path.is_absolute():
61
+ return normalize_location_path(raw)
62
+
63
+ resolved = path.resolve()
64
+ bases: list[Path] = []
65
+ # The most reliable base is the database that owns the file being asked
66
+ # about, found by walking up from the file itself. Falling back to cwd covers
67
+ # the editor case, where the extension passes an absolute path inside the
68
+ # workspace the user opened.
69
+ file_db = find_db(resolved.parent)
70
+ if file_db is not None:
71
+ bases.append(file_db.parent.parent) # <repo>/.codegraph/graph.db -> <repo>
72
+ cwd_db = find_db()
73
+ if cwd_db is not None:
74
+ bases.append(cwd_db.parent.parent)
75
+ bases.append(Path.cwd())
76
+ for base in bases:
77
+ try:
78
+ return resolved.relative_to(base.resolve()).as_posix()
79
+ except ValueError:
80
+ continue
81
+ return normalize_location_path(raw)
82
+
83
+
84
+ def parse_location(raw: str) -> tuple[str, int]:
85
+ """Parse `file:line` into (path, line)."""
86
+ value = raw.strip()
87
+ if not value:
88
+ raise LocationError("Location cannot be empty. Use the form src/main.py:42")
89
+ match = LOCATION_RE.match(value)
90
+ if not match:
91
+ raise LocationError(
92
+ f"Cannot parse location '{raw}'. Expected path:line, e.g. src/main.py:42"
93
+ )
94
+ line_no = int(match.group("line"))
95
+ if line_no < 1:
96
+ raise LocationError(f"Line number must be >= 1, got: {line_no}")
97
+
98
+ raw_file = match.group("file")
99
+ # Remember the database that owns the *original* path before it becomes a
100
+ # repo-relative string: `normalize_user_path` strips the absolute prefix, and
101
+ # after that there is no way to tell which repository the user meant.
102
+ _remember_db_for(raw_file)
103
+ return normalize_user_path(raw_file), line_no
104
+
105
+
106
+ def _current_stdout_encodes(text: str) -> bool:
107
+ """True when the active stdout encoding can represent text."""
108
+ encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
109
+ try:
110
+ text.encode(encoding)
111
+ except (UnicodeEncodeError, LookupError):
112
+ return False
113
+ return True
114
+
115
+
116
+ def format_status_label(status_value: str) -> str:
117
+ """Map decision status to a short label, degrading to ASCII when needed."""
118
+ mapping = {
119
+ "accepted": ("✅ active", "[OK] active"),
120
+ "superseded": ("🔁 superseded", "[SUPERSEDED]"),
121
+ "rejected": ("⛔ rejected", "[REJECTED]"),
122
+ }
123
+ preferred, fallback = mapping.get(status_value, (status_value, status_value))
124
+ return preferred if _current_stdout_encodes(preferred) else fallback
125
+
126
+
127
+ def format_confidence(confidence: float) -> str:
128
+ """Format 0-1 confidence as stars and percent."""
129
+ percent = int(round(confidence * 100))
130
+ stars = "★" * int(round(confidence * 5)) + "☆" * (5 - int(round(confidence * 5)))
131
+ return f"{stars} {percent}%"
132
+
133
+
134
+ # Database resolved from the location the user actually typed, set by
135
+ # `_remember_db_for` during argument parsing. `None` means "fall back to cwd".
136
+ _QUERY_DB: Path | None = None
137
+
138
+
139
+ def _remember_db_for(raw_path: str) -> None:
140
+ """Record which graph database owns `raw_path`, before it is relativised.
141
+
142
+ Needed because a user may run `codegraph index some/repo` and then query an
143
+ absolute path inside it from an unrelated directory; the database lives in
144
+ `some/repo`, not in cwd.
145
+ """
146
+ global _QUERY_DB
147
+ _QUERY_DB = None
148
+ candidate = Path(raw_path)
149
+ if not candidate.is_absolute():
150
+ return
151
+ found = find_db(candidate.parent)
152
+ if found is not None:
153
+ _QUERY_DB = found
154
+
155
+
156
+ def _resolve_db(root: Path | None = None, file_path: str = "") -> Path:
157
+ """Locate the graph database for a query.
158
+
159
+ Priority order matters for the case that actually breaks: a user runs
160
+ `codegraph index some/repo` from elsewhere, then asks about a file inside
161
+ that repo. `index` wrote the database into `some/repo`, so looking only at the
162
+ current directory reports "no record" for everything.
163
+
164
+ 1. the database resolved from the location the user typed;
165
+ 2. walk up from the file being asked about — the most reliable clue;
166
+ 3. walk up from cwd;
167
+ 4. fall back to `<cwd>/.codegraph/graph.db`, which is where `index` writes
168
+ when given no path.
169
+ """
170
+ if _QUERY_DB is not None and _QUERY_DB.is_file():
171
+ return _QUERY_DB
172
+
173
+ if file_path:
174
+ candidate = Path(file_path)
175
+ if not candidate.is_absolute():
176
+ candidate = (root or Path.cwd()) / candidate
177
+ found = find_db(candidate.parent if candidate.suffix else candidate)
178
+ if found is not None:
179
+ return found
180
+
181
+ base = root or Path.cwd()
182
+ found = find_db(base)
183
+ return found if found is not None else db_path_for_root(base)
184
+
185
+
186
+ def load_code_node_sqlite(file_path: str, line: int, root: Path | None = None) -> CodeNode | None:
187
+ """Load covering CodeNode from SQLite if an index exists."""
188
+ db_path = _resolve_db(root, file_path)
189
+ if not db_path.exists():
190
+ return None
191
+ try:
192
+ conn = connect(db_path)
193
+ except sqlite3.Error as exc:
194
+ console.print(f"[yellow]warn[/] Cannot open graph database {db_path}: {exc}")
195
+ return None
196
+ try:
197
+ return find_node_at_line(conn, file_path, line)
198
+ finally:
199
+ conn.close()
200
+
201
+
202
+ def load_decisions_sqlite(
203
+ file_path: str,
204
+ line: int,
205
+ root: Path | None = None,
206
+ commit_sha: str = "",
207
+ ) -> tuple[list[Decision], str]:
208
+ """Load decisions with line → file → commit → directory fallback.
209
+
210
+ Returns:
211
+ (decisions, level) where level is "line", "file", "commit", or "dir".
212
+ """
213
+ db_path = _resolve_db(root, file_path)
214
+ rows: list[Decision] = []
215
+ level = "line"
216
+ if db_path.exists():
217
+ try:
218
+ conn = connect(db_path)
219
+ except sqlite3.Error as exc:
220
+ console.print(f"[yellow]warn[/] Cannot open graph database {db_path}: {exc}")
221
+ return [], "none"
222
+ try:
223
+ # A line-level record is any record linked to the symbol that covers
224
+ # this line. Querying the node range first stops an unrelated
225
+ # exact-line commit record from shadowing it.
226
+ covering = find_node_at_line(conn, file_path, line)
227
+ if covering is not None:
228
+ rows = query_decisions_for_node_lines(
229
+ conn, file_path, covering.line_start, covering.line_end
230
+ )
231
+ if rows:
232
+ level = "line"
233
+ if not rows:
234
+ rows = query_decisions_for_line_links(conn, file_path, line)
235
+ if rows:
236
+ level = "line"
237
+ if not rows:
238
+ rows = query_decisions_for_line(conn, file_path, line)
239
+ if not rows:
240
+ rows = query_decisions_for_file(conn, file_path)
241
+ level = "file"
242
+ if not rows and commit_sha:
243
+ rows = query_decisions_for_commit(conn, commit_sha)
244
+ level = "commit"
245
+ if not rows:
246
+ rows = query_decisions_for_dir(conn, file_path, limit=5)
247
+ level = "dir"
248
+ finally:
249
+ conn.close()
250
+ if rows:
251
+ return rows, level
252
+ return [], "none"
253
+
254
+
255
+ def _parse_ts(value: object) -> datetime:
256
+ """Parse an ISO timestamp or fall back to now."""
257
+ if isinstance(value, str) and value:
258
+ try:
259
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
260
+ except ValueError:
261
+ pass
262
+ return datetime.now(timezone.utc)
263
+
264
+
265
+ def _load_all_decisions() -> list[Decision]:
266
+ """Load every decision from the local graph database, if it exists."""
267
+ from codegraph.storage import query_all_decisions
268
+
269
+ db_path = db_path_for_root(Path.cwd())
270
+ if not db_path.exists():
271
+ return []
272
+ conn = connect(db_path)
273
+ try:
274
+ return query_all_decisions(conn)
275
+ finally:
276
+ conn.close()
277
+
278
+
279
+ def render_code_node_header(node: CodeNode) -> None:
280
+ """Render the hit CodeNode summary at the top of the card."""
281
+ valid_to = node.valid_to.date().isoformat() if node.valid_to else "current"
282
+ panel = Panel(
283
+ Text(
284
+ f" kind: {node.kind} name: {node.name}\n"
285
+ f" range: {node.file_path}:{node.line_start}-{node.line_end}\n"
286
+ f" language: {node.language}\n"
287
+ f" valid: {node.valid_from.date().isoformat()} → {valid_to}\n"
288
+ f" commit: {node.commit_sha or 'n/a'}",
289
+ style="cyan",
290
+ ),
291
+ title="[bold]Matched CodeNode[/]",
292
+ border_style="cyan",
293
+ padding=(0, 2),
294
+ )
295
+ console.print(panel)
296
+
297
+
298
+ def decision_title(decision: Decision, index: int = 1) -> str:
299
+ """Build a human-readable panel title (never leak internal uids)."""
300
+ snippet = " ".join((decision.content or "").split())
301
+ if snippet:
302
+ snippet = snippet[:40] + ("…" if len(snippet) > 40 else "")
303
+ return f"Decision #{index}: {snippet}"
304
+ ref = (decision.source_ref or "").split()[-1] if decision.source_ref else ""
305
+ return f"Decision #{index}" + (f" · {ref}" if ref else "")
306
+
307
+
308
+ def build_decision_panel(
309
+ decision: Decision, file_path: str, line: int, level: str = "line", index: int = 1
310
+ ) -> Panel:
311
+ """Render one decision as a Rich Panel card."""
312
+ body = Text()
313
+ body.append("[Location]\n", style="bold cyan")
314
+ body.append(f" {file_path}:{line}\n")
315
+ if level in {"file", "commit", "dir"}:
316
+ body.append(f" binding: {level}-level decision\n", style="dim")
317
+ body.append("[Decision]\n", style="bold yellow")
318
+ body.append(f" {decision.content}\n")
319
+ body.append("[Reason]\n", style="bold yellow")
320
+ reason = (decision.reason or "").strip()
321
+ if not reason or reason == decision.content:
322
+ body.append(" Not recorded\n")
323
+ else:
324
+ body.append(f" {reason}\n")
325
+ body.append("[Alternatives]\n", style="bold yellow")
326
+ if decision.alternatives:
327
+ for item in decision.alternatives:
328
+ body.append(f" · {item}\n")
329
+ else:
330
+ body.append(" (none)\n")
331
+ body.append("[Source]\n", style="bold yellow")
332
+ body.append(f" {decision.source.value} · {decision.source_ref}\n")
333
+ body.append(
334
+ f" author: {decision.author or 'unknown'} · "
335
+ f"date: {decision.timestamp.date().isoformat()}\n"
336
+ )
337
+ body.append("[Status]\n", style="bold yellow")
338
+ body.append(f" {format_status_label(decision.status.value)}\n")
339
+ body.append("[Constraints]\n", style="bold yellow")
340
+ if decision.constraints:
341
+ for item in decision.constraints:
342
+ body.append(f" · {item}\n")
343
+ else:
344
+ body.append(" (none)\n")
345
+ body.append("[Confidence]\n", style="bold yellow")
346
+ body.append(f" {format_confidence(decision.confidence)}\n")
347
+ return Panel(
348
+ body,
349
+ title=f"[bold]{decision_title(decision, index)}[/]",
350
+ border_style="yellow",
351
+ padding=(1, 2),
352
+ )
353
+
354
+
355
+ def render_decision_card(
356
+ file_path: str, line: int, decisions: list[Decision], level: str = "line"
357
+ ) -> None:
358
+ """Render decision cards for a location.
359
+
360
+ Args:
361
+ file_path: Queried file.
362
+ line: Queried line.
363
+ decisions: Decisions to show.
364
+ level: Binding strength — line / file / commit / dir / none.
365
+ """
366
+ labels = {
367
+ "line": "line-level decision",
368
+ "file": "file-level decision",
369
+ "commit": "commit-level decision",
370
+ "dir": "directory-level decision",
371
+ "none": "decision",
372
+ }
373
+ tag = labels.get(level, "decision")
374
+ console.print(
375
+ f"[bold cyan]Query[/] {file_path}:{line} → [bold]{len(decisions)}[/] matched {tag}(s)\n"
376
+ )
377
+ for i, decision in enumerate(decisions[:5], start=1):
378
+ panel = build_decision_panel(decision, file_path, line, level=level, index=i)
379
+ console.print(panel)
380
+
381
+
382
+ def render_not_found(
383
+ file_path: str,
384
+ line: int | None = None,
385
+ hidden_records: int = 0,
386
+ related: list[Decision] | None = None,
387
+ ) -> None:
388
+ """Render the empty-result hint.
389
+
390
+ Args:
391
+ file_path: Queried file.
392
+ line: Queried line, when known.
393
+ hidden_records: Records that exist but were filtered out by the tier
394
+ and category defaults.
395
+ related: Decisions bound to this file but not to this line. Showing them
396
+ turns "nothing here" into an answer for files governed by an ADR.
397
+ """
398
+ location = f"{file_path}:{line}" if line is not None else file_path
399
+ console.print("[bold yellow]No decision record found[/]")
400
+ if related:
401
+ console.print("[dim]No record is tied to this line, but this file is governed by:[/]")
402
+ for item in related:
403
+ text = item.content if len(item.content) <= 74 else item.content[:71] + "..."
404
+ console.print(f" [cyan]{text}[/]")
405
+ console.print(f"[dim] source: {item.source_ref}[/]")
406
+ console.print("[dim] codegraph decisions --timeline # all decisions[/]")
407
+ return
408
+ if hidden_records:
409
+ console.print(
410
+ f"[dim]{hidden_records} history record(s) exist for {location} "
411
+ "but are not decisions.[/]"
412
+ )
413
+ console.print("[dim] Add --include-events (and --include-dependency) to see them.[/]")
414
+ return
415
+ console.print(f"[dim]No Decision bound to {location}. Try:[/]")
416
+ console.print("[dim] codegraph index <repo> --depth 50 # build the graph first[/]")
417
+ console.print("[dim] codegraph decisions --file <path> --timeline[/]")
418
+
419
+
420
+ def _file_governed_decisions(
421
+ file_path: str, include_events: bool, include_dependency: bool
422
+ ) -> list[Decision]:
423
+ """Decisions bound to this file by a link, for an otherwise empty result."""
424
+ db_path = db_path_for_root(Path.cwd())
425
+ if not db_path.exists():
426
+ return []
427
+ try:
428
+ conn = connect(db_path)
429
+ try:
430
+ rows = query_decisions_for_file_links(conn, file_path)
431
+ finally:
432
+ conn.close()
433
+ except Exception: # noqa: BLE001
434
+ return []
435
+ return select_decisions(
436
+ rows, include_events=include_events, include_dependency=include_dependency
437
+ )[:2]
438
+
439
+
440
+ def why_command(
441
+ location: str,
442
+ as_json: bool = typer.Option(
443
+ False,
444
+ "--json",
445
+ help="Emit machine-readable JSON instead of Rich cards",
446
+ ),
447
+ include_dependency: bool = typer.Option(
448
+ False,
449
+ "--include-dependency",
450
+ help="Include dependency-bump decisions (hidden by default)",
451
+ ),
452
+ include_events: bool = typer.Option(
453
+ False,
454
+ "--include-events",
455
+ help="Include event records (plain history: commit subjects, changelog lines)",
456
+ ),
457
+ ) -> None:
458
+ """Query decision cards for a source location.
459
+
460
+ Args:
461
+ location: Location string like `src/auth/session.ts:42`.
462
+ as_json: Output JSON for editor extensions.
463
+ """
464
+ import json as jsonlib
465
+
466
+ try:
467
+ file_path, line = parse_location(location)
468
+ except LocationError as exc:
469
+ if as_json:
470
+ typer.echo(jsonlib.dumps({"error": str(exc)}))
471
+ else:
472
+ console.print(f"[bold red]Invalid argument[/] {exc}")
473
+ raise typer.Exit(code=2) from exc
474
+
475
+ node = load_code_node_sqlite(file_path, line)
476
+ raw_decisions, level = load_decisions_sqlite(
477
+ file_path, line, commit_sha=node.commit_sha if node else ""
478
+ )
479
+ decisions = select_decisions(
480
+ raw_decisions,
481
+ include_events=include_events,
482
+ include_dependency=include_dependency,
483
+ )
484
+ hidden_records = max(len(raw_decisions) - len(decisions), 0)
485
+ governed = [] if decisions else _file_governed_decisions(
486
+ file_path, include_events, include_dependency
487
+ )
488
+
489
+ if as_json:
490
+ payload = {
491
+ "file": file_path,
492
+ "line": line,
493
+ "node": _node_payload(node),
494
+ "decisions": [_decision_payload(d) for d in decisions[:10]],
495
+ "binding": level,
496
+ "related": [_decision_payload(d) for d in governed],
497
+ }
498
+ typer.echo(jsonlib.dumps(payload, ensure_ascii=False, indent=2))
499
+ if not decisions:
500
+ raise typer.Exit(code=1)
501
+ return
502
+
503
+ if node is not None and level != "line":
504
+ try:
505
+ db_path = db_path_for_root(Path.cwd())
506
+ if db_path.exists():
507
+ conn = connect(db_path)
508
+ try:
509
+ near = query_decisions_for_node_lines(
510
+ conn, file_path, node.line_start, node.line_end
511
+ )
512
+ finally:
513
+ conn.close()
514
+ else:
515
+ near = []
516
+ except Exception: # noqa: BLE001
517
+ near = []
518
+ if near:
519
+ near_visible = select_decisions(
520
+ near,
521
+ include_events=include_events,
522
+ include_dependency=include_dependency,
523
+ )
524
+ hidden_records += len(near) - len(near_visible)
525
+ if near_visible:
526
+ decisions = near_visible
527
+ level = "line"
528
+
529
+ if node is not None:
530
+ render_code_node_header(node)
531
+ else:
532
+ console.print(
533
+ "[dim]No active code node covers this line "
534
+ "(the symbol may have moved or been removed).[/]"
535
+ )
536
+
537
+ if not decisions:
538
+ render_not_found(file_path, line, hidden_records=hidden_records, related=governed)
539
+ raise typer.Exit(code=1)
540
+
541
+ render_decision_card(file_path, line, decisions, level=level)
542
+
543
+
544
+ def _node_payload(node: CodeNode | None) -> dict | None:
545
+ """Serialize a CodeNode for --json."""
546
+ return node_to_dict(node) if node is not None else None
547
+
548
+
549
+ def _decision_payload(decision: Decision) -> dict:
550
+ """Serialize a Decision for --json."""
551
+ return decision_to_dict(decision)
552
+
553
+
554
+ def decisions_command(
555
+ file: str = typer.Option(
556
+ "",
557
+ "--file",
558
+ help="File path (omit to list decisions for every file)",
559
+ metavar="PATH",
560
+ ),
561
+ timeline: bool = typer.Option(False, "--timeline", help="Show oldest-first evolution"),
562
+ include_dependency: bool = typer.Option(
563
+ False,
564
+ "--include-dependency",
565
+ help="Include dependency-bump decisions (hidden by default)",
566
+ ),
567
+ include_events: bool = typer.Option(
568
+ False,
569
+ "--include-events",
570
+ help="Include event records (plain history: commit subjects, changelog lines)",
571
+ ),
572
+ as_json: bool = typer.Option(
573
+ False,
574
+ "--json",
575
+ help="Emit machine-readable JSON instead of a table",
576
+ ),
577
+ ) -> None:
578
+ """List the decision evolution timeline, for one file or for everything.
579
+
580
+ Args:
581
+ file: Target file path; omitted means every file.
582
+ timeline: Emit oldest-first when true.
583
+ include_dependency: Show dependency-bump decisions too.
584
+ include_events: Show event-tier records too.
585
+ as_json: Emit JSON for editors and scripts.
586
+ """
587
+ prefix = normalize_location_path(file) if file else ""
588
+ rows = [
589
+ d
590
+ for d in _load_all_decisions()
591
+ if not prefix or d.file_path == prefix or d.file_path.startswith(prefix)
592
+ ]
593
+ filtered = select_decisions(
594
+ rows,
595
+ include_events=include_events,
596
+ include_dependency=include_dependency,
597
+ )
598
+ if not filtered and not as_json:
599
+ render_not_found(
600
+ file or "this repository", hidden_records=max(len(rows) - len(filtered), 0)
601
+ )
602
+ raise typer.Exit(code=1)
603
+ rows = filtered
604
+
605
+ if as_json:
606
+ import json as jsonlib
607
+
608
+ ordered_json = list(rows) if timeline else list(reversed(rows))
609
+ typer.echo(
610
+ jsonlib.dumps(
611
+ {
612
+ "file": file or None,
613
+ "count": len(ordered_json),
614
+ "decisions": [decision_to_dict(d) for d in ordered_json],
615
+ },
616
+ ensure_ascii=False,
617
+ indent=2,
618
+ )
619
+ )
620
+ if not ordered_json:
621
+ raise typer.Exit(code=1)
622
+ return
623
+
624
+ table = Table(title=f"Decision evolution · {file or 'all files'}")
625
+ table.add_column("Date", style="cyan")
626
+ table.add_column("Status")
627
+ table.add_column("Decision", overflow="fold")
628
+ table.add_column("Kind", style="dim")
629
+ table.add_column("Source", style="dim")
630
+ ordered = list(rows) if timeline else list(reversed(rows))
631
+ for decision in ordered[:15]:
632
+ table.add_row(
633
+ decision.timestamp.date().isoformat(),
634
+ decision.status.value,
635
+ decision.content,
636
+ decision.tier.value,
637
+ decision.source_ref,
638
+ )
639
+ console.print(table)
640
+
641
+
642
+ app = typer.Typer(help="Decision provenance for a source line")
643
+
644
+ if __name__ == "__main__":
645
+ app()