From daae7c3cfe18cd4d7de7c5fdffad8c2e54ff7d72 Mon Sep 17 00:00:00 2001 From: BEAST Date: Wed, 14 Oct 2026 18:28:51 +0530 Subject: feat: initial commit of TIMELORD Chrono Engine CLI --- .gitignore | 2 + README.md | 158 ++++++++++++ setup.py | 26 ++ tests/test_timelord.py | 189 ++++++++++++++ timelord/__init__.py | 7 + timelord/cli.py | 401 +++++++++++++++++++++++++++++ timelord/core/__init__.py | 16 ++ timelord/core/compare.py | 148 +++++++++++ timelord/core/engine.py | 136 ++++++++++ timelord/core/merge.py | 122 +++++++++ timelord/core/multiverse.py | 154 +++++++++++ timelord/core/process.py | 102 ++++++++ timelord/core/snapshot.py | 188 ++++++++++++++ timelord/ui/__init__.py | 1 + timelord/ui/diff_view.py | 139 ++++++++++ timelord/ui/theme.py | 45 ++++ timelord/ui/views.py | 220 ++++++++++++++++ timelord/utils/__init__.py | 1 + timelord/utils/copy_cow.py | 113 ++++++++ timelord/utils/env_helper.py | 142 ++++++++++ timelord/utils/git_helper.py | 101 ++++++++ timelord_cli.egg-info/PKG-INFO | 17 ++ timelord_cli.egg-info/SOURCES.txt | 24 ++ timelord_cli.egg-info/dependency_links.txt | 1 + timelord_cli.egg-info/entry_points.txt | 3 + timelord_cli.egg-info/requires.txt | 2 + timelord_cli.egg-info/top_level.txt | 1 + 27 files changed, 2459 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 setup.py create mode 100644 tests/test_timelord.py create mode 100644 timelord/__init__.py create mode 100644 timelord/cli.py create mode 100644 timelord/core/__init__.py create mode 100644 timelord/core/compare.py create mode 100644 timelord/core/engine.py create mode 100644 timelord/core/merge.py create mode 100644 timelord/core/multiverse.py create mode 100644 timelord/core/process.py create mode 100644 timelord/core/snapshot.py create mode 100644 timelord/ui/__init__.py create mode 100644 timelord/ui/diff_view.py create mode 100644 timelord/ui/theme.py create mode 100644 timelord/ui/views.py create mode 100644 timelord/utils/__init__.py create mode 100644 timelord/utils/copy_cow.py create mode 100644 timelord/utils/env_helper.py create mode 100644 timelord/utils/git_helper.py create mode 100644 timelord_cli.egg-info/PKG-INFO create mode 100644 timelord_cli.egg-info/SOURCES.txt create mode 100644 timelord_cli.egg-info/dependency_links.txt create mode 100644 timelord_cli.egg-info/entry_points.txt create mode 100644 timelord_cli.egg-info/requires.txt create mode 100644 timelord_cli.egg-info/top_level.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e818245 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# TIMELORD Chrono Engine +.timelord/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..beee1da --- /dev/null +++ b/README.md @@ -0,0 +1,158 @@ +# ⚡ TIMELORD (CLI) + +> **"Physics remains annoyingly committed to its current business model. TIMELORD isn't."** + +**TIMELORD** (`tl`) is an experimental snapshot and parallel universe branching CLI for developers. + +Freeze your project state in time, spin up parallel universes in milliseconds to try dangerous refactors, run dev servers concurrently across multiple timelines, compare versions side-by-side, and choose whether to **break the timeline** (prune the universe cleanly) or declare a **canon event** (merge back into Prime). + +--- + +``` + ╔═════════════════════════════════════════════════════════════════════════╗ + ║ ████████╗██╗███╗ ███╗███████╗██╗ ██████╗ ██████╗ ██████╗ ║ + ║ ╚══██╔══╝██║████╗ ████║██╔════╝██║ ██╔═══██╗██╔══██╗██╔══██╗ ║ + ║ ██║ ██║██╔████╔██║█████╗ ██║ ██║ ██║██████╔╝██║ ██║ ║ + ║ ██║ ██║██║╚██╔╝██║██╔══╝ ██║ ██║ ██║██╔══██╗██║ ██║ ║ + ║ ██║ ██║██║ ╚═╝ ██║███████╗███████╗╚██████╔╝██║ ██║██████╔╝ ║ + ║ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ║ + ║ Rewind your dev environment • Split parallel timelines • Break anomalies ║ + ╚═════════════════════════════════════════════════════════════════════════╝ +``` + +--- + +## 🚀 Killer Features + +- **⚡ Instant Copy-on-Write Branching (APFS/Reflink)** + Spawning a parallel universe takes `< 50ms` regardless of repo size and uses **zero duplicate storage** on creation. Only blocks you change consume disk space. +- **🌌 Concurrent Multiverse Execution** + Run multiple universes simultaneously. TIMELORD auto-detects ports in `.env` or `package.json` and assigns intelligent offsets (e.g., Prime on `3000`, Universe Alpha on `3100`), preventing `EADDRINUSE` port collision errors. +- **🖥️ Side-by-Side Visual Terminal Diff (`tl diff`)** + A dual-column Rich split-screen terminal viewer that shows exact line differences between Prime and your alternate reality in real time. +- **💥 Break the Timeline (`tl break` / `tl prune`)** + TVA-style pruning. If your experimental refactor crashes or turns into an unholy mess, collapse that universe. You return cleanly to the Prime Timeline without a single lingering artifact. +- **🏆 Canon Event Integration (`tl canon` / `tl merge`)** + When an experiment succeeds, integrate its changes into Prime. TIMELORD automatically creates a pre-merge safety anchor so you can always roll back. +- **⏳ Time Rewind (`tl jump` / `tl rewind`)** + Instantly restore your codebase to any previous temporal anchor with full snapshot isolation. +- **🌲 Multiverse Timeline Tree (`tl tree` / `tl log`)** + View the sacred timeline and all active/pruned variant branches in a terminal tree. + +--- + +## 📦 Installation + +```bash +# Clone and install in editable mode +cd timelord +pip install -e . + +# Or run directly via Python +python3 -m timelord.cli --help +``` + +Both `timelord` and the short alias `tl` will be available in your `$PATH`. + +--- + +## 🕹️ Quickstart: 3-Minute Time Travel Walkthrough + +### 1. Anchor your Prime Continuum (Earth-616) +Navigate to any coding project (Git or non-Git) and initialize TIMELORD: +```bash +tl init +``` + +### 2. Freeze a Temporal Snapshot +Before making major changes, freeze time: +```bash +tl freeze "Before migrating database from PostgreSQL to SQLite" +``` + +### 3. Split Reality into a Parallel Universe +Want to test a risky architectural pivot? Branch into an alternate universe: +```bash +tl branch quantum-sqlite --port-offset 100 +``` + +### 4. Enter the Parallel Universe Subshell +Warp into the universe with an isolated terminal prompt and custom environment variables: +```bash +tl enter quantum-sqlite +# 🌌 [TIMELORD: quantum-sqlite] ~/my-project $ +# Hack freely here! Modify files, install packages, delete folders. +# Type 'exit' to warp back to Earth-616 anytime! +``` + +Or execute commands without entering: +```bash +tl run quantum-sqlite -- npm test +``` + +### 5. Compare Prime vs The Universe Side by Side +Inspect your temporal divergence: +```bash +tl diff quantum-sqlite +``` + +### 6. Decide the Fate of the Universe! + +- **Option A: Break the Timeline (Prune it)** + The experiment failed? Vaporize it: + ```bash + tl break quantum-sqlite + ``` + +- **Option B: Canon Event (Merge into Prime)** + The experiment was a massive success? Promote it to Prime: + ```bash + tl canon quantum-sqlite --git-commit + ``` + +--- + +## 📖 Command Reference & Aliases + +| Command | Alias | Description | +| :--- | :--- | :--- | +| `tl init` | - | Initializes `.timelord/` chrono-space in project | +| `tl status` | - | Displays temporal coordinates, active realm, ports, and git state | +| `tl freeze [LABEL]` | `tl snapshot` | Captures project tree, git metadata, and environment snapshot | +| `tl branch ` | `tl split` | Branches an isolated parallel universe using instant APFS copy-on-write | +| `tl enter ` | `tl warp` | Opens an interactive subshell inside that universe with a custom prompt | +| `tl run -- ` | - | Concurrently runs commands in a universe without leaving Prime | +| `tl diff ` | `tl compare` | Side-by-side terminal diff showing modifications vs Prime | +| `tl prune ` | `tl break`, `tl collapse` | Destroys the parallel universe, restoring pristine Prime state | +| `tl merge ` | `tl canon` | Applies universe changes to Prime with automatic rollback safety | +| `tl rewind ` | `tl jump` | Restores files to an earlier snapshot anchor | +| `tl tree` | `tl log` | Renders the Multiverse timeline tree | +| `tl universes` | `tl list` | Lists all active and pruned parallel universes | +| `tl snapshots` | - | Lists all frozen temporal anchors | + +--- + +## 🧠 Architecture + +``` +.timelord/ +├── config.json # Exclusion rules, port stepping, Prime settings +├── state.json # Active multiverse registry & coordinates +├── snapshots/ +│ ├── chrono-a91f3b/ +│ │ ├── metadata.json # Git sha, env vars, system info, file hashes +│ │ └── tree/ # Block-level APFS copy-on-write file snapshot +└── universes/ + ├── quantum-sqlite/ + │ ├── timelord_universe.json # Universe manifest, port offsets, parent ID + │ └── [project files...] # Isolated, live mutable sandbox +``` + +- **APFS Clonefile Support (`cp -c -R`)**: On macOS, branching duplicates file-system extent references rather than physical data blocks. +- **Port Offset Engine**: Dynamically shifts environment `PORT` specifications in child universes to let both dev servers listen simultaneously. +- **Safety Pre-Rollbacks**: Any destructive action (`rewind` or `merge`) automatically creates an un-pruned safety snapshot before modifying disks. + +--- + +## 📜 License +MIT License. Travel through time responsibly. Do not cause grandfather paradoxes. diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..4167807 --- /dev/null +++ b/setup.py @@ -0,0 +1,26 @@ +from setuptools import find_packages, setup + +setup( + name="timelord-cli", + version="1.0.0", + description="Rewind your dev environment. Snapshot & Parallel Multiverse CLI for coding projects.", + author="TIMELORD", + packages=find_packages(), + python_requires=">=3.8", + install_requires=[ + "click>=8.0.0", + "rich>=12.0.0", + ], + entry_points={ + "console_scripts": [ + "timelord=timelord.cli:main", + "tl=timelord.cli:main", + ], + }, + classifiers=[ + "Programming Language :: Python :: 3", + "Operating System :: MacOS", + "Operating System :: POSIX :: Linux", + "Topic :: Software Development :: Version Control", + ], +) diff --git a/tests/test_timelord.py b/tests/test_timelord.py new file mode 100644 index 0000000..c86be9d --- /dev/null +++ b/tests/test_timelord.py @@ -0,0 +1,189 @@ +""" +Comprehensive test suite for TIMELORD Chrono Engine. +Tests snapshot creation, parallel multiverse branching, side-by-side diffs, +timeline pruning, and canonical merge events. +""" + +import os +import shutil +import tempfile +from pathlib import Path + +import pytest +from click.testing import CliRunner + +from timelord.cli import cli +from timelord.core.compare import TimelineComparator +from timelord.core.engine import ChronoEngine +from timelord.core.merge import TimelineMerger +from timelord.core.multiverse import MultiverseManager +from timelord.core.snapshot import SnapshotManager + + +@pytest.fixture +def test_project(): + """Creates a temporary sandbox coding project.""" + temp_dir = tempfile.mkdtemp(prefix="timelord_test_") + proj_path = Path(temp_dir) + + # Populate dummy files + (proj_path / "src").mkdir(parents=True) + (proj_path / "src" / "main.py").write_text("print('Prime Earth-616')\n", encoding="utf-8") + (proj_path / "package.json").write_text('{"name": "test-app", "scripts": {"dev": "vite --port 3000"}}\n', encoding="utf-8") + (proj_path / ".env").write_text("PORT=3000\nDATABASE_URL=sqlite:///prime.db\n", encoding="utf-8") + + yield proj_path + + # Teardown + shutil.rmtree(temp_dir, ignore_errors=True) + + +def test_init_and_freeze(test_project): + engine = ChronoEngine(test_project) + assert not engine.is_initialized + + # Init + engine.init_repository(test_project) + assert engine.is_initialized + assert (test_project / ".timelord").is_dir() + assert (test_project / ".timelord" / "config.json").is_file() + + # Freeze initial snapshot + snap_mgr = SnapshotManager(engine) + snap = snap_mgr.create_snapshot(label="Genesis Baseline") + assert snap["id"].startswith("chrono-") + assert snap["stats"]["total_files"] >= 3 + + # List snapshots + snaps = snap_mgr.list_snapshots() + assert len(snaps) == 1 + assert snaps[0]["id"] == snap["id"] + + +def test_multiverse_branch_and_diff(test_project): + engine = ChronoEngine(test_project) + engine.init_repository(test_project) + + # Branch into universe 'quantum-experiment' + mv_mgr = MultiverseManager(engine) + universe = mv_mgr.create_universe(name="quantum-experiment", port_offset=100) + + assert universe["name"] == "quantum-experiment" + universe_path = Path(universe["path"]) + assert universe_path.is_dir() + + # Verify port remapping in universe .env + env_content = (universe_path / ".env").read_text(encoding="utf-8") + assert "PORT=3100" in env_content + + # Make risky changes inside the parallel universe + (universe_path / "src" / "main.py").write_text("print('Quantum Universe variant!')\n", encoding="utf-8") + (universe_path / "src" / "risky_feature.py").write_text("def explode(): pass\n", encoding="utf-8") + + # Prime remains completely untouched! + prime_main = (test_project / "src" / "main.py").read_text(encoding="utf-8") + assert "Prime Earth-616" in prime_main + assert not (test_project / "src" / "risky_feature.py").exists() + + # Compare differences + comparator = TimelineComparator(engine) + diff = comparator.compare_universe_with_prime("quantum-experiment") + + assert not diff["is_identical"] + assert "src/risky_feature.py" in diff["added"] + assert any(m["path"] == "src/main.py" for m in diff["modified"]) + + +def test_timeline_prune(test_project): + engine = ChronoEngine(test_project) + engine.init_repository(test_project) + + mv_mgr = MultiverseManager(engine) + universe = mv_mgr.create_universe(name="doomed-timeline") + uni_path = Path(universe["path"]) + assert uni_path.is_dir() + + # Prune / Break the timeline + res = mv_mgr.prune_universe("doomed-timeline") + assert res["status"] == "pruned" + assert not uni_path.exists() + assert len(mv_mgr.list_universes(active_only=True)) == 0 + + +def test_canon_event_merge(test_project): + engine = ChronoEngine(test_project) + engine.init_repository(test_project) + + mv_mgr = MultiverseManager(engine) + universe = mv_mgr.create_universe(name="successful-refactor") + uni_path = Path(universe["path"]) + + # Add a new feature in the universe + (uni_path / "src" / "feature.py").write_text("# Canon feature\n", encoding="utf-8") + (uni_path / "src" / "main.py").write_text("print('Enhanced Main')\n", encoding="utf-8") + + # Merge into Prime + merger = TimelineMerger(engine) + merge_res = merger.merge_universe_into_prime("successful-refactor", create_safety=True) + + assert merge_res["status"] == "merged" + assert merge_res["files_added"] == 1 + assert merge_res["files_modified"] == 1 + + # Prime now contains the merged changes! + assert (test_project / "src" / "feature.py").exists() + assert "Enhanced Main" in (test_project / "src" / "main.py").read_text(encoding="utf-8") + + +def test_rewind_snapshot(test_project): + engine = ChronoEngine(test_project) + engine.init_repository(test_project) + + snap_mgr = SnapshotManager(engine) + initial_snap = snap_mgr.create_snapshot(label="Original State") + + # Introduce breaking change in Prime + (test_project / "src" / "main.py").write_text("BROKEN CODE CRASH\n", encoding="utf-8") + (test_project / "junk.txt").write_text("garbage", encoding="utf-8") + + # Rewind + rewind_res = snap_mgr.restore_snapshot(initial_snap["id"], create_safety=True) + assert rewind_res["restored_snapshot"]["id"] == initial_snap["id"] + + # Verify Prime was restored + restored_main = (test_project / "src" / "main.py").read_text(encoding="utf-8") + assert "Prime Earth-616" in restored_main + assert not (test_project / "junk.txt").exists() + + +def test_cli_integration(test_project): + runner = CliRunner() + with runner.isolated_filesystem(temp_dir=test_project.parent): + # init + res = runner.invoke(cli, ["init"]) + assert res.exit_code == 0 + assert "Chrono-Space established" in res.output + + # freeze + res = runner.invoke(cli, ["freeze", "First CLI Snapshot"]) + assert res.exit_code == 0 + assert "Time frozen successfully" in res.output + + # status + res = runner.invoke(cli, ["status"]) + assert res.exit_code == 0 + assert "TEMPORAL COORDINATES" in res.output + + # branch + res = runner.invoke(cli, ["branch", "multiverse-test", "--port-offset", "100"]) + assert res.exit_code == 0 + assert "Parallel Universe spawned" in res.output + + # diff + res = runner.invoke(cli, ["diff", "multiverse-test"]) + assert res.exit_code == 0 + + # prune + res = runner.invoke(cli, ["prune", "multiverse-test", "-y"]) + assert res.exit_code == 0 + assert "Timeline pruned" in res.output diff --git a/timelord/__init__.py b/timelord/__init__.py new file mode 100644 index 0000000..23dc314 --- /dev/null +++ b/timelord/__init__.py @@ -0,0 +1,7 @@ +""" +TIMELORD: Rewind your development environment. +An experimental snapshot system and parallel timelines engine for coding projects. +""" + +__version__ = "1.0.0" +__author__ = "TIMELORD Team" diff --git a/timelord/cli.py b/timelord/cli.py new file mode 100644 index 0000000..055bcec --- /dev/null +++ b/timelord/cli.py @@ -0,0 +1,401 @@ +""" +TIMELORD CLI: Rewind your dev environment. Split parallel timelines. Break anomalies. +""" + +import sys +from pathlib import Path +from typing import List, Optional + +import click +from rich.prompt import Confirm + +from timelord.core.compare import TimelineComparator +from timelord.core.engine import ChronoEngine +from timelord.core.merge import TimelineMerger +from timelord.core.multiverse import MultiverseManager +from timelord.core.process import ProcessRunner +from timelord.core.snapshot import SnapshotManager +from timelord.ui.diff_view import render_diff_summary, render_side_by_side_diff +from timelord.ui.theme import BANNER, MINI_BANNER, SCI_FI_QUOTES, console +from timelord.ui.views import ( + render_multiverse_tree, + render_snapshots_table, + render_status_dashboard, + render_universes_table, +) +from timelord.utils.env_helper import detect_configured_ports +from timelord.utils.git_helper import get_git_state + + +def get_engine() -> ChronoEngine: + engine = ChronoEngine() + return engine + + +def ensure_initialized(engine: ChronoEngine) -> None: + if not engine.is_initialized: + console.print( + "[bold red]Temporal rift detected:[/bold red] TIMELORD is not initialized in this project.\n" + "Run [bold cyan]tl init[/bold cyan] to create your project's Prime Timeline." + ) + sys.exit(1) + + +@click.group(invoke_without_command=True) +@click.pass_context +@click.version_option(version="1.0.0", prog_name="timelord") +def cli(ctx: click.Context) -> None: + """⚡ TIMELORD: Experimental snapshot & parallel universe CLI for coding projects.""" + if ctx.invoked_subcommand is None: + console.print(BANNER) + console.print( + "[bold cyan]Usage:[/bold cyan] [bold white]tl [COMMAND][/bold white] (e.g. `tl status`, `tl freeze`, `tl branch`, `tl diff`)\n" + "Run [bold cyan]tl --help[/bold cyan] for full temporal commands.\n" + ) + + +@cli.command(name="init") +def cmd_init() -> None: + """Initialize a Timelord repository in the current project.""" + engine = get_engine() + if engine.is_initialized: + console.print(f"[bold yellow]TIMELORD already initialized at:[/bold yellow] {engine.project_root}") + return + + try: + root = engine.init_repository() + console.print(BANNER) + console.print(f"[bold bright_green]✔ Chrono-Space established at:[/bold bright_green] [cyan]{root}[/cyan]") + console.print("[dim]Prime Timeline anchored as Earth-616.[/dim]") + console.print("[dim]Ready to freeze time with [bold cyan]tl freeze[/bold cyan] or split reality with [bold cyan]tl branch [/bold cyan].[/dim]\n") + except Exception as e: + console.print(f"[bold red]Initialization failed:[/bold red] {e}") + sys.exit(1) + + +@cli.command(name="status") +def cmd_status() -> None: + """Show current temporal coordinates, git state, and parallel universes.""" + engine = get_engine() + ensure_initialized(engine) + + git_state = get_git_state(engine.project_root) + ports = detect_configured_ports(engine.project_root) + multiverse = MultiverseManager(engine) + active_universes = multiverse.list_universes(active_only=True) + + snapshots = SnapshotManager(engine) + last_id = engine.get_state().get("last_snapshot_id") + last_snap = snapshots.get_snapshot(last_id) if last_id else None + + render_status_dashboard( + current_timeline=engine.current_timeline, + project_root=engine.project_root, + last_snapshot=last_snap, + git_state=git_state, + active_universes=active_universes, + ports=ports, + ) + + +@cli.command(name="freeze") +@click.argument("label", required=False, default="Manual Temporal Anchor") +def cmd_freeze(label: str) -> None: + """Freeze current project state into an immutable temporal snapshot.""" + engine = get_engine() + ensure_initialized(engine) + + manager = SnapshotManager(engine) + with console.status("[bold cyan]Freezing time & capturing project state...[/bold cyan]", spinner="dots"): + snap = manager.create_snapshot(label=label) + + console.print( + f"\n[bold bright_green]✔ Time frozen successfully![/bold bright_green] Anchor ID: [bold bright_yellow]{snap['id']}[/bold bright_yellow]" + ) + console.print(f"[dim]Label: \"{snap['label']}\"[/dim]") + console.print(f"[dim]Total files captured: {snap['stats']['total_files']}[/dim]") + console.print(f"[dim italic]{SCI_FI_QUOTES['freeze']}[/dim italic]\n") + + +@cli.command(name="branch") +@click.argument("universe_name") +@click.option("--from", "from_snapshot", help="Branch from a specific snapshot ID instead of current state.") +@click.option("--port-offset", type=int, default=None, help="TCP Port offset for parallel dev server (default: +100).") +def cmd_branch(universe_name: str, from_snapshot: Optional[str], port_offset: Optional[int]) -> None: + """Branch into a parallel universe to experiment with risky changes.""" + engine = get_engine() + ensure_initialized(engine) + + manager = MultiverseManager(engine) + with console.status( + f"[bold magenta]Quantum splitting reality into universe '{universe_name}'...[/bold magenta]", + spinner="aesthetic", + ): + try: + universe = manager.create_universe( + name=universe_name, + from_snapshot_id=from_snapshot, + port_offset=port_offset, + ) + except Exception as e: + console.print(f"[bold red]Multiverse branching failed:[/bold red] {e}") + sys.exit(1) + + console.print( + f"\n[bold bright_green]✔ Parallel Universe spawned:[/bold bright_green] [bold magenta]🌌 {universe['name']}[/bold magenta]" + ) + console.print(f"[dim]Location: {universe['path']}[/dim]") + console.print(f"[dim]Branched from anchor: {universe['parent_snapshot_id']}[/dim]") + if universe.get("port_offset"): + console.print(f"[yellow]Port offset allocated: +{universe['port_offset']}[/yellow]") + console.print(f"[dim italic]{SCI_FI_QUOTES['branch']}[/dim italic]\n") + console.print( + f"To enter this universe, run:\n [bold cyan]tl enter {universe['name']}[/bold cyan]\n" + f"Or run commands directly:\n [bold cyan]tl run {universe['name']} -- [/bold cyan]\n" + ) + + +@cli.command(name="enter") +@click.argument("universe_name") +def cmd_enter(universe_name: str) -> None: + """Enter a parallel universe via an isolated subshell.""" + engine = get_engine() + ensure_initialized(engine) + + runner = ProcessRunner(engine) + exit_code = runner.enter_universe_shell(universe_name) + sys.exit(exit_code) + + +@cli.command(name="run") +@click.argument("universe_name") +@click.argument("cmd", nargs=-1, required=True) +def cmd_run(universe_name: str, cmd: List[str]) -> None: + """Run a command inside a parallel universe (e.g. `tl run refactor -- npm test`).""" + engine = get_engine() + ensure_initialized(engine) + + runner = ProcessRunner(engine) + exit_code = runner.run_in_universe(universe_name, list(cmd)) + sys.exit(exit_code) + + +@cli.command(name="diff") +@click.argument("universe_name") +@click.option("--file", "target_file", default=None, help="Inspect side-by-side diff of a specific file.") +@click.option("--side-by-side/--summary-only", default=True, help="Display side-by-side split screen diffs.") +def cmd_diff(universe_name: str, target_file: Optional[str], side_by_side: bool) -> None: + """Compare Prime Timeline with a Parallel Universe side by side.""" + engine = get_engine() + ensure_initialized(engine) + + comparator = TimelineComparator(engine) + try: + diff_res = comparator.compare_universe_with_prime(universe_name) + except Exception as e: + console.print(f"[bold red]Comparison error:[/bold red] {e}") + sys.exit(1) + + if diff_res["is_identical"]: + console.print( + f"\n[bold bright_green]✔ Universe '{universe_name}' and Prime are in exact quantum resonance (0 differences).[/bold bright_green]\n" + ) + return + + # Print summary table + console.print("") + summary_table = render_diff_summary(diff_res) + console.print(summary_table) + + # If specific file requested, show its side-by-side diff + if target_file: + prime_txt, uni_txt = comparator.get_file_contents(universe_name, target_file) + render_side_by_side_diff( + file_rel_path=target_file, + content_a=prime_txt, + content_b=uni_txt, + label_a="Prime (Earth-616)", + label_b=f"Universe: {universe_name}", + ) + elif side_by_side and diff_res["modified"]: + console.print("\n[bold cyan]─── Side-by-Side Visual Diff of Modified Files ───[/bold cyan]\n") + # Show first 3 modified files + for mod in diff_res["modified"][:3]: + rel = mod["path"] + prime_txt, uni_txt = comparator.get_file_contents(universe_name, rel) + render_side_by_side_diff( + file_rel_path=rel, + content_a=prime_txt, + content_b=uni_txt, + label_a="Prime (Earth-616)", + label_b=f"Universe: {universe_name}", + ) + + +@cli.command(name="prune") +@click.argument("universe_name") +@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt.") +def cmd_prune(universe_name: str, yes: bool) -> None: + """Break the timeline! Prune and discard a parallel universe.""" + engine = get_engine() + ensure_initialized(engine) + + if not yes: + if not Confirm.ask( + f"[bold red]Are you sure you want to prune parallel universe '{universe_name}' and discard its changes?[/bold red]" + ): + console.print("[dim]Operation aborted. Timeline remains intact.[/dim]") + return + + manager = MultiverseManager(engine) + try: + res = manager.prune_universe(universe_name) + console.print( + f"\n[bold bright_red]✔ Timeline pruned![/bold bright_red] Parallel universe [bold magenta]'{universe_name}'[/bold magenta] collapsed." + ) + console.print(f"[dim italic]{SCI_FI_QUOTES['prune']}[/dim italic]\n") + except Exception as e: + console.print(f"[bold red]Prune failed:[/bold red] {e}") + sys.exit(1) + + +@cli.command(name="merge") +@click.argument("universe_name") +@click.option("--git-commit/--no-git-commit", default=False, help="Automatically create a Git commit on Prime.") +@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt.") +def cmd_merge(universe_name: str, git_commit: bool, yes: bool) -> None: + """Canon Event Achieved! Merge parallel universe changes into Prime.""" + engine = get_engine() + ensure_initialized(engine) + + if not yes: + if not Confirm.ask( + f"[bold bright_green]Incorporate universe '{universe_name}' changes into Prime Timeline?[/bold bright_green]" + ): + console.print("[dim]Merge aborted.[/dim]") + return + + merger = TimelineMerger(engine) + with console.status(f"[bold cyan]Merging universe '{universe_name}' into Prime...[/bold cyan]", spinner="dots"): + try: + res = merger.merge_universe_into_prime( + universe_name, + create_safety=True, + git_commit=git_commit, + ) + except Exception as e: + console.print(f"[bold red]Merge failed:[/bold red] {e}") + sys.exit(1) + + if res.get("status") == "already_identical": + console.print(f"[yellow]{res['message']}[/yellow]") + return + + console.print( + f"\n[bold bright_green]✔ Canon Event Achieved![/bold bright_green] Changes from [bold magenta]'{universe_name}'[/bold magenta] integrated." + ) + console.print(f"[dim]Safety snapshot created: [yellow]{res.get('safety_snapshot_id')}[/yellow][/dim]") + console.print( + f"[dim]Files: +{res['files_added']} added, ~{res['files_modified']} modified, -{res['files_deleted']} removed[/dim]" + ) + if res.get("git_committed"): + console.print("[green]✔ Git commit created on Prime continuum.[/green]") + console.print(f"[dim italic]{SCI_FI_QUOTES['merge']}[/dim italic]\n") + + +@cli.command(name="rewind") +@click.argument("snapshot_id") +@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt.") +def cmd_rewind(snapshot_id: str, yes: bool) -> None: + """Rewind your project files to an earlier snapshot.""" + engine = get_engine() + ensure_initialized(engine) + + if not yes: + if not Confirm.ask( + f"[bold bright_yellow]Rewind project to snapshot '{snapshot_id}'? (An auto-safety snapshot will be taken)[/bold bright_yellow]" + ): + console.print("[dim]Rewind cancelled.[/dim]") + return + + snapshots = SnapshotManager(engine) + with console.status(f"[bold yellow]Rewinding temporal coordinates to {snapshot_id}...[/bold yellow]", spinner="dots"): + try: + res = snapshots.restore_snapshot(snapshot_id, create_safety=True) + except Exception as e: + console.print(f"[bold red]Rewind failed:[/bold red] {e}") + sys.exit(1) + + console.print( + f"\n[bold bright_green]✔ Timeline successfully rewound to:[/bold bright_green] [bold yellow]{res['restored_snapshot']['id']}[/bold yellow]" + ) + if res.get("safety_snapshot"): + console.print( + f"[dim]Pre-rewind state saved as safety anchor: [yellow]{res['safety_snapshot']['id']}[/yellow][/dim]" + ) + console.print(f"[dim italic]{SCI_FI_QUOTES['rewind']}[/dim italic]\n") + + +@cli.command(name="universes") +def cmd_universes() -> None: + """List all parallel universe timelines.""" + engine = get_engine() + ensure_initialized(engine) + + manager = MultiverseManager(engine) + all_univs = manager.list_universes() + if not all_univs: + console.print("[dim]No parallel universes recorded yet. Use `tl branch ` to split time.[/dim]") + return + + render_universes_table(all_univs, current=engine.current_timeline) + + +@cli.command(name="snapshots") +def cmd_snapshots() -> None: + """List all frozen temporal anchors.""" + engine = get_engine() + ensure_initialized(engine) + + manager = SnapshotManager(engine) + all_snaps = manager.list_snapshots() + if not all_snaps: + console.print("[dim]No snapshots recorded yet. Use `tl freeze