""" 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