summaryrefslogtreecommitdiff
path: root/timelord/ui
diff options
context:
space:
mode:
authorBEAST <macbook@Macbooks-MacBook-Pro.local>2026-10-14 18:28:51 +0530
committerBEAST <macbook@Macbooks-MacBook-Pro.local>2026-10-14 18:28:51 +0530
commitdaae7c3cfe18cd4d7de7c5fdffad8c2e54ff7d72 (patch)
tree1b7213a19fdb109cfdaf1c0af96f9a6771c41d47 /timelord/ui
feat: initial commit of TIMELORD Chrono Engine CLI
Diffstat (limited to 'timelord/ui')
-rw-r--r--timelord/ui/__init__.py1
-rw-r--r--timelord/ui/diff_view.py139
-rw-r--r--timelord/ui/theme.py45
-rw-r--r--timelord/ui/views.py220
4 files changed, 405 insertions, 0 deletions
diff --git a/timelord/ui/__init__.py b/timelord/ui/__init__.py
new file mode 100644
index 0000000..fe2dba7
--- /dev/null
+++ b/timelord/ui/__init__.py
@@ -0,0 +1 @@
+"""TIMELORD UI package."""
diff --git a/timelord/ui/diff_view.py b/timelord/ui/diff_view.py
new file mode 100644
index 0000000..e3c4af0
--- /dev/null
+++ b/timelord/ui/diff_view.py
@@ -0,0 +1,139 @@
+"""
+Side-by-side split screen diff viewer and summary diff formatting using Rich.
+"""
+
+import difflib
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+
+from rich.columns import Columns
+from rich.panel import Panel
+from rich.syntax import Syntax
+from rich.table import Table
+from rich.text import Text
+
+from timelord.ui.theme import console
+
+
+def render_diff_summary(changes: Dict[str, Any]) -> Table:
+ """Renders a summary table of changed files between Prime and Universe."""
+ table = Table(
+ title="[bold bright_cyan]Temporal Divergence Summary[/bold bright_cyan]",
+ border_style="cyan",
+ header_style="bold magenta",
+ )
+ table.add_column("Status", style="bold", width=12)
+ table.add_column("File Path", style="bright_white")
+ table.add_column("Lines (+ / -)", justify="right", style="dim")
+
+ for f in changes.get("added", []):
+ table.add_row("[green]+ ADDED[/green]", str(f), "[green]+new file[/green]")
+ for f in changes.get("deleted", []):
+ table.add_row("[red]- REMOVED[/red]", str(f), "[red]-deleted[/red]")
+ for item in changes.get("modified", []):
+ path = item.get("path", "")
+ plus = item.get("additions", 0)
+ minus = item.get("deletions", 0)
+ table.add_row(
+ "[yellow]~ MODIFIED[/yellow]",
+ str(path),
+ f"[green]+{plus}[/green] / [red]-{minus}[/red]",
+ )
+
+ return table
+
+
+def render_side_by_side_diff(
+ file_rel_path: str,
+ content_a: str,
+ content_b: str,
+ label_a: str = "Prime (Earth-616)",
+ label_b: str = "Parallel Universe",
+ max_lines: int = 100,
+) -> None:
+ """Renders a side-by-side visual diff in two terminal panels."""
+ lines_a = content_a.splitlines()
+ lines_b = content_b.splitlines()
+
+ # Determine syntax lexer by file extension
+ ext = Path(file_rel_path).suffix.lstrip(".")
+ lexer_map = {
+ "py": "python",
+ "js": "javascript",
+ "ts": "typescript",
+ "json": "json",
+ "html": "html",
+ "css": "css",
+ "md": "markdown",
+ "sh": "bash",
+ "yml": "yaml",
+ "yaml": "yaml",
+ }
+ lexer = lexer_map.get(ext, "text")
+
+ # Generate side-by-side aligned diff lines
+ matcher = difflib.SequenceMatcher(None, lines_a, lines_b)
+ left_lines = []
+ right_lines = []
+
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
+ if tag == "equal":
+ for line in lines_a[i1:i2]:
+ left_lines.append(f" {line}")
+ right_lines.append(f" {line}")
+ elif tag == "replace":
+ chunk_a = lines_a[i1:i2]
+ chunk_b = lines_b[j1:j2]
+ max_len = max(len(chunk_a), len(chunk_b))
+ for i in range(max_len):
+ la = chunk_a[i] if i < len(chunk_a) else ""
+ lb = chunk_b[i] if i < len(chunk_b) else ""
+ left_lines.append(f"- {la}" if la else " ")
+ right_lines.append(f"+ {lb}" if lb else " ")
+ elif tag == "delete":
+ for line in lines_a[i1:i2]:
+ left_lines.append(f"- {line}")
+ right_lines.append(" ")
+ elif tag == "insert":
+ for line in lines_b[j1:j2]:
+ left_lines.append(" ")
+ right_lines.append(f"+ {line}")
+
+ # Clip to max_lines if too long
+ is_truncated = len(left_lines) > max_lines
+ if is_truncated:
+ left_lines = left_lines[:max_lines]
+ right_lines = right_lines[:max_lines]
+
+ left_text = Text()
+ for l in left_lines:
+ if l.startswith("-"):
+ left_text.append(l + "\n", style="bold red")
+ else:
+ left_text.append(l + "\n", style="dim white")
+
+ right_text = Text()
+ for l in right_lines:
+ if l.startswith("+"):
+ right_text.append(l + "\n", style="bold green")
+ else:
+ right_text.append(l + "\n", style="dim white")
+
+ if is_truncated:
+ left_text.append(f"\n... truncated to {max_lines} lines ...", style="dim yellow")
+ right_text.append(f"\n... truncated to {max_lines} lines ...", style="dim yellow")
+
+ panel_a = Panel(
+ left_text,
+ title=f"[bold cyan]{label_a}[/bold cyan] ({file_rel_path})",
+ border_style="cyan",
+ expand=True,
+ )
+ panel_b = Panel(
+ right_text,
+ title=f"[bold magenta]{label_b}[/bold magenta] ({file_rel_path})",
+ border_style="magenta",
+ expand=True,
+ )
+
+ console.print(Columns([panel_a, panel_b], expand=True))
diff --git a/timelord/ui/theme.py b/timelord/ui/theme.py
new file mode 100644
index 0000000..fd074a3
--- /dev/null
+++ b/timelord/ui/theme.py
@@ -0,0 +1,45 @@
+"""
+Sci-Fi theme, banners, and aesthetic formatting for TIMELORD.
+"""
+
+from rich.console import Console
+from rich.theme import Theme
+
+# Dedicated Chrono Theme
+CHRONO_THEME = Theme({
+ "chrono.prime": "bold bright_cyan",
+ "chrono.universe": "bold magenta",
+ "chrono.snapshot": "bold bright_yellow",
+ "chrono.active": "bold bright_green",
+ "chrono.pruned": "dim red",
+ "chrono.merged": "bold bright_blue",
+ "chrono.dim": "dim white",
+ "chrono.warning": "bold bright_magenta",
+ "chrono.danger": "bold red",
+ "chrono.success": "bold green",
+ "chrono.tag": "cyan on blue",
+})
+
+console = Console(theme=CHRONO_THEME)
+
+BANNER = r"""
+ [bold cyan]╔═════════════════════════════════════════════════════════════════════════╗[/bold cyan]
+ [bold cyan]║[/bold cyan] [bold bright_cyan]████████╗██╗███╗ ███╗███████╗██╗ ██████╗ ██████╗ ██████╗ [/bold bright_cyan] [bold cyan]║[/bold cyan]
+ [bold cyan]║[/bold cyan] [bold bright_cyan]╚══██╔══╝██║████╗ ████║██╔════╝██║ ██╔═══██╗██╔══██╗██╔══██╗[/bold bright_cyan] [bold cyan]║[/bold cyan]
+ [bold cyan]║[/bold cyan] [bold bright_cyan]██║ ██║██╔████╔██║█████╗ ██║ ██║ ██║██████╔╝██║ ██║[/bold bright_cyan] [bold cyan]║[/bold cyan]
+ [bold cyan]║[/bold cyan] [bold bright_cyan]██║ ██║██║╚██╔╝██║██╔══╝ ██║ ██║ ██║██╔══██╗██║ ██║[/bold bright_cyan] [bold cyan]║[/bold cyan]
+ [bold cyan]║[/bold cyan] [bold bright_cyan]██║ ██║██║ ╚═╝ ██║███████╗███████╗╚██████╔╝██║ ██║██████╔╝[/bold bright_cyan] [bold cyan]║[/bold cyan]
+ [bold cyan]║[/bold cyan] [bold bright_cyan]╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ [/bold bright_cyan] [bold cyan]║[/bold cyan]
+ [bold cyan]║[/bold cyan] [dim]Rewind your dev environment • Split parallel timelines • Break anomalies[/dim] [bold cyan]║[/bold cyan]
+ [bold cyan]╚═════════════════════════════════════════════════════════════════════════╝[/bold cyan]
+"""
+
+MINI_BANNER = "[bold bright_cyan]⚡ TIMELORD[/bold bright_cyan] [dim]• Chrono Engine v1.0.0[/dim]"
+
+SCI_FI_QUOTES = {
+ "freeze": "“People assume that time is a strict progression of cause to effect, but actually it's more like a big ball of wibbly-wobbly, timey-wimey stuff.”",
+ "branch": "“Branching timeline detected. Entering parallel quantum state.”",
+ "prune": "“Timeline pruned. Nexus event neutralized. Earth-616 restored.”",
+ "merge": "“Canon event achieved! Alternate timeline integrated into the Prime Continuum.”",
+ "rewind": "“Rewinding temporal coordinates... resetting project causality.”",
+}
diff --git a/timelord/ui/views.py b/timelord/ui/views.py
new file mode 100644
index 0000000..7e76aa1
--- /dev/null
+++ b/timelord/ui/views.py
@@ -0,0 +1,220 @@
+"""
+Rich visual presentations: Status dashboard, Multiverse branching trees, and tables.
+"""
+
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from rich.panel import Panel
+from rich.table import Table
+from rich.tree import Tree
+from rich.text import Text
+
+from timelord.ui.theme import console
+
+
+def render_status_dashboard(
+ current_timeline: str,
+ project_root: Path,
+ last_snapshot: Optional[Dict[str, Any]],
+ git_state: Dict[str, Any],
+ active_universes: List[Dict[str, Any]],
+ ports: List[int],
+) -> None:
+ """Renders the comprehensive temporal coordinate status dashboard."""
+ is_prime = current_timeline.lower() in ("prime", "earth-616")
+
+ status_table = Table.grid(padding=(0, 2))
+ status_table.add_column(style="bold cyan", justify="right")
+ status_table.add_column(style="white")
+
+ # Current Timeline
+ timeline_str = (
+ "[bold bright_green]Prime Timeline (Earth-616)[/bold bright_green]"
+ if is_prime
+ else f"[bold magenta]🌌 Parallel Universe: {current_timeline}[/bold magenta]"
+ )
+ status_table.add_row("Temporal Realm:", timeline_str)
+ status_table.add_row("Project Root:", f"[dim]{project_root}[/dim]")
+
+ # Git state
+ if git_state.get("is_git"):
+ branch = git_state.get("branch", "detached")
+ sha = git_state.get("head_sha", "unknown")
+ dirty_flag = (
+ "[bold yellow]● DIRTY (uncommitted changes)[/bold yellow]"
+ if git_state.get("is_dirty")
+ else "[green]✔ CLEAN[/green]"
+ )
+ status_table.add_row(
+ "Git Continuum:",
+ f"branch [cyan]{branch}[/cyan] ({sha}) {dirty_flag}",
+ )
+ else:
+ status_table.add_row("Git Continuum:", "[dim]Non-git workspace[/dim]")
+
+ # Configured ports
+ if ports:
+ ports_str = ", ".join(f"[bold yellow]{p}[/bold yellow]" for p in ports)
+ status_table.add_row("Bound Ports:", ports_str)
+
+ # Last Snapshot Anchor
+ if last_snapshot:
+ snap_id = last_snapshot.get("id")
+ snap_time = last_snapshot.get("timestamp", "unknown")
+ snap_label = last_snapshot.get("label", "no description")
+ status_table.add_row(
+ "Last Anchor:",
+ f"[bold bright_yellow]{snap_id}[/bold bright_yellow] [dim]({snap_time})[/dim] - \"{snap_label}\"",
+ )
+ else:
+ status_table.add_row("Last Anchor:", "[dim]No snapshots recorded yet[/dim]")
+
+ # Active Parallel Universes
+ if active_universes:
+ univ_names = [f"[magenta]🌌 {u.get('name')}[/magenta]" for u in active_universes]
+ status_table.add_row("Active Universes:", ", ".join(univ_names))
+ else:
+ status_table.add_row("Parallel Universes:", "[dim]No active parallel timelines[/dim]")
+
+ panel = Panel(
+ status_table,
+ title="[bold bright_cyan]⚡ TEMPORAL COORDINATES ⚡[/bold bright_cyan]",
+ subtitle="[dim]TIMELORD Chrono Engine[/dim]",
+ border_style="cyan",
+ padding=(1, 2),
+ )
+ console.print(panel)
+
+
+def render_multiverse_tree(
+ snapshots: List[Dict[str, Any]],
+ universes: List[Dict[str, Any]],
+ current_timeline: str = "Prime",
+) -> None:
+ """Renders the branching timeline tree showing Prime continuum and parallel universes."""
+ root_label = Text()
+ root_label.append("⚡ Prime Continuum (Earth-616)", style="bold bright_cyan")
+ if current_timeline.lower() in ("prime", "earth-616"):
+ root_label.append(" [YOU ARE HERE]", style="bold bright_green")
+
+ tree = Tree(root_label)
+
+ # Map universes by parent snapshot id
+ universes_by_parent: Dict[str, List[Dict[str, Any]]] = {}
+ for u in universes:
+ parent = u.get("parent_snapshot_id", "root")
+ universes_by_parent.setdefault(parent, []).append(u)
+
+ if not snapshots:
+ tree.add("[dim]No frozen snapshots recorded yet. Use `tl freeze` to anchor time.[/dim]")
+ else:
+ for snap in snapshots:
+ snap_id = snap.get("id", "")
+ snap_time = snap.get("timestamp", "")
+ label = snap.get("label", "")
+ git_info = ""
+ if snap.get("git", {}).get("is_git"):
+ git_info = f" [cyan]({snap['git']['branch']}@{snap['git']['head_sha']})[/cyan]"
+
+ node_text = Text()
+ node_text.append(f"● {snap_id}", style="bold yellow")
+ node_text.append(f" [{snap_time}]", style="dim")
+ node_text.append(f" \"{label}\"", style="white")
+ if git_info:
+ node_text.append(git_info)
+
+ snap_node = tree.add(node_text)
+
+ # Check if any universe branched from this snapshot
+ branched_universes = universes_by_parent.get(snap_id, [])
+ for u in branched_universes:
+ uname = u.get("name", "")
+ status = u.get("status", "active")
+ offset = u.get("port_offset")
+ is_current = current_timeline == uname
+
+ u_text = Text()
+ u_text.append(f"├─── 🌌 Universe: '{uname}'", style="bold magenta")
+ if is_current:
+ u_text.append(" [YOU ARE HERE]", style="bold bright_green")
+ if status == "pruned":
+ u_text.append(" (Pruned)", style="dim red")
+ elif status == "merged":
+ u_text.append(" (Merged to Prime)", style="bold bright_blue")
+ else:
+ u_text.append(" (Active)", style="bold bright_green")
+
+ if offset:
+ u_text.append(f" [Port offset +{offset}]", style="yellow")
+
+ snap_node.add(u_text)
+
+ # Universes without snapshot parent
+ orphans = universes_by_parent.get("root", [])
+ for u in orphans:
+ uname = u.get("name", "")
+ tree.add(f"├─── 🌌 Universe: '{uname}' (Spawned from unrecorded timeline)", style="bold magenta")
+
+ console.print(tree)
+
+
+def render_snapshots_table(snapshots: List[Dict[str, Any]]) -> None:
+ """Renders tabular list of snapshots."""
+ table = Table(
+ title="[bold yellow]Temporal Anchors (Snapshots)[/bold yellow]",
+ border_style="yellow",
+ header_style="bold bright_yellow",
+ )
+ table.add_column("Chrono ID", style="bold yellow", width=14)
+ table.add_column("Timestamp", style="dim", width=20)
+ table.add_column("Git Coordinates", style="cyan")
+ table.add_column("Description / Label", style="white")
+ table.add_column("Files", justify="right", style="dim", width=8)
+
+ for s in snapshots:
+ snap_id = s.get("id", "")
+ ts = s.get("timestamp", "")[:19].replace("T", " ")
+ label = s.get("label", "")
+ git_str = "-"
+ if s.get("git", {}).get("is_git"):
+ git_str = f"{s['git'].get('branch', '')} ({s['git'].get('head_sha', '')})"
+ files_count = str(s.get("stats", {}).get("total_files", "-"))
+ table.add_row(snap_id, ts, git_str, label, files_count)
+
+ console.print(table)
+
+
+def render_universes_table(universes: List[Dict[str, Any]], current: str = "Prime") -> None:
+ """Renders tabular list of parallel universes."""
+ table = Table(
+ title="[bold magenta]Multiverse Registry (Parallel Universes)[/bold magenta]",
+ border_style="magenta",
+ header_style="bold bright_magenta",
+ )
+ table.add_column("Universe Name", style="bold magenta")
+ table.add_column("Status", width=12)
+ table.add_column("Branched From", style="yellow")
+ table.add_column("Created At", style="dim")
+ table.add_column("Port Offset", justify="right", style="yellow")
+ table.add_column("Active?", justify="center")
+
+ for u in universes:
+ name = u.get("name", "")
+ status = u.get("status", "active")
+ parent = u.get("parent_snapshot_id", "prime")
+ ts = u.get("created_at", "")[:19].replace("T", " ")
+ offset = f"+{u.get('port_offset')}" if u.get("port_offset") else "-"
+ is_here = "⭐ CURRENT" if name == current else ""
+
+ status_fmt = (
+ "[bold green]Active[/bold green]"
+ if status == "active"
+ else "[dim red]Pruned[/dim red]"
+ if status == "pruned"
+ else "[blue]Merged[/blue]"
+ )
+
+ table.add_row(name, status_fmt, parent, ts, offset, is_here)
+
+ console.print(table)