summaryrefslogtreecommitdiff
path: root/timelord
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
feat: initial commit of TIMELORD Chrono Engine CLI
Diffstat (limited to 'timelord')
-rw-r--r--timelord/__init__.py7
-rw-r--r--timelord/cli.py401
-rw-r--r--timelord/core/__init__.py16
-rw-r--r--timelord/core/compare.py148
-rw-r--r--timelord/core/engine.py136
-rw-r--r--timelord/core/merge.py122
-rw-r--r--timelord/core/multiverse.py154
-rw-r--r--timelord/core/process.py102
-rw-r--r--timelord/core/snapshot.py188
-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
-rw-r--r--timelord/utils/__init__.py1
-rw-r--r--timelord/utils/copy_cow.py113
-rw-r--r--timelord/utils/env_helper.py142
-rw-r--r--timelord/utils/git_helper.py101
17 files changed, 2036 insertions, 0 deletions
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 <name>[/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']} -- <command>[/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 <name>` 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 <label>` to create an anchor.[/dim]")
+ return
+
+ render_snapshots_table(all_snaps)
+
+
+@cli.command(name="tree")
+def cmd_tree() -> None:
+ """Visualize the multiverse tree and branching timelines."""
+ engine = get_engine()
+ ensure_initialized(engine)
+
+ snapshots = SnapshotManager(engine).list_snapshots()
+ universes = MultiverseManager(engine).list_universes()
+
+ console.print(MINI_BANNER)
+ console.print("")
+ render_multiverse_tree(snapshots, universes, current_timeline=engine.current_timeline)
+ console.print("")
+
+
+# Aliases
+cli.add_command(cmd_freeze, name="snapshot")
+cli.add_command(cmd_branch, name="split")
+cli.add_command(cmd_enter, name="warp")
+cli.add_command(cmd_prune, name="break")
+cli.add_command(cmd_prune, name="collapse")
+cli.add_command(cmd_merge, name="canon")
+cli.add_command(cmd_rewind, name="jump")
+cli.add_command(cmd_tree, name="log")
+cli.add_command(cmd_universes, name="list")
+
+
+def main() -> None:
+ cli()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/timelord/core/__init__.py b/timelord/core/__init__.py
new file mode 100644
index 0000000..cec9ec4
--- /dev/null
+++ b/timelord/core/__init__.py
@@ -0,0 +1,16 @@
+"""TIMELORD Core Engine package."""
+from timelord.core.engine import ChronoEngine
+from timelord.core.snapshot import SnapshotManager
+from timelord.core.multiverse import MultiverseManager
+from timelord.core.compare import TimelineComparator
+from timelord.core.merge import TimelineMerger
+from timelord.core.process import ProcessRunner
+
+__all__ = [
+ "ChronoEngine",
+ "SnapshotManager",
+ "MultiverseManager",
+ "TimelineComparator",
+ "TimelineMerger",
+ "ProcessRunner",
+]
diff --git a/timelord/core/compare.py b/timelord/core/compare.py
new file mode 100644
index 0000000..b545766
--- /dev/null
+++ b/timelord/core/compare.py
@@ -0,0 +1,148 @@
+"""
+Timeline Comparator: Inspects differences between Prime and Parallel Universes.
+Computes file modifications, additions, deletions, and line-level changes.
+"""
+
+import difflib
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Set
+
+from timelord.core.engine import ChronoEngine
+from timelord.core.multiverse import MultiverseManager
+from timelord.core.snapshot import hash_file
+
+
+class TimelineComparator:
+ def __init__(self, engine: ChronoEngine):
+ self.engine = engine
+ self.multiverse = MultiverseManager(engine)
+
+ def _collect_files(self, root: Path, excludes: Set[str]) -> Dict[str, Path]:
+ files = {}
+ for p in root.rglob("*"):
+ if not p.is_file():
+ continue
+ rel = p.relative_to(root)
+ # Skip any relative path containing an excluded segment
+ if any(part in excludes for part in rel.parts):
+ continue
+ files[str(rel)] = p
+ return files
+
+ def compare_universe_with_prime(self, universe_name: str) -> Dict[str, Any]:
+ """Compares Prime Timeline (Earth-616) with the specified parallel universe."""
+ universe = self.multiverse.get_universe(universe_name)
+ if not universe:
+ raise ValueError(f"Universe '{universe_name}' not found.")
+
+ universe_dir = Path(universe["path"])
+ prime_dir = self.engine.project_root
+
+ config = self.engine.get_config()
+ excludes = set(config.get("exclude_patterns", [".timelord", ".git"]))
+ excludes.add("timelord_universe.json")
+
+ prime_files = self._collect_files(prime_dir, excludes)
+ universe_files = self._collect_files(universe_dir, excludes)
+
+ prime_keys = set(prime_files.keys())
+ universe_keys = set(universe_files.keys())
+
+ added = sorted(list(universe_keys - prime_keys))
+ deleted = sorted(list(prime_keys - universe_keys))
+ common = sorted(list(prime_keys & universe_keys))
+
+ modified = []
+ remapped_ports = universe.get("remapped_ports", {})
+ for rel in common:
+ pf = prime_files[rel]
+ uf = universe_files[rel]
+
+ # Fast size check before hash
+ if pf.stat().st_size != uf.stat().st_size or hash_file(pf) != hash_file(uf):
+ # Ignore if the only change is the auto-injected port offset
+ if self._is_only_port_remapped(pf, uf, remapped_ports):
+ continue
+
+ # Count added and deleted lines
+ additions, deletions = self._count_line_diffs(pf, uf)
+ modified.append({
+ "path": rel,
+ "prime_path": str(pf),
+ "universe_path": str(uf),
+ "additions": additions,
+ "deletions": deletions,
+ })
+
+ return {
+ "universe_name": universe_name,
+ "prime_path": str(prime_dir),
+ "universe_path": str(universe_dir),
+ "added": added,
+ "deleted": deleted,
+ "modified": modified,
+ "is_identical": not (added or deleted or modified),
+ }
+
+ def _count_line_diffs(self, file_a: Path, file_b: Path) -> tuple[int, int]:
+ try:
+ lines_a = file_a.read_text(encoding="utf-8", errors="ignore").splitlines()
+ lines_b = file_b.read_text(encoding="utf-8", errors="ignore").splitlines()
+ matcher = difflib.SequenceMatcher(None, lines_a, lines_b)
+ additions = 0
+ deletions = 0
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
+ if tag in ("replace", "delete"):
+ deletions += (i2 - i1)
+ if tag in ("replace", "insert"):
+ additions += (j2 - j1)
+ return additions, deletions
+ except Exception:
+ return 0, 0
+
+ def _is_only_port_remapped(self, pf: Path, uf: Path, remapped_ports: Dict[str, int]) -> bool:
+ if not remapped_ports:
+ return False
+ try:
+ lines_p = pf.read_text(encoding="utf-8", errors="ignore").splitlines()
+ lines_u = uf.read_text(encoding="utf-8", errors="ignore").splitlines()
+ if len(lines_p) != len(lines_u):
+ return False
+ import re
+ for lp, lu in zip(lines_p, lines_u):
+ if lp == lu:
+ continue
+ mp = re.match(r"^(\s*PORT\s*=\s*)(\d+)(.*)$", lp, re.IGNORECASE)
+ mu = re.match(r"^(\s*PORT\s*=\s*)(\d+)(.*)$", lu, re.IGNORECASE)
+ if mp and mu and mp.group(1) == mu.group(1) and mp.group(3) == mu.group(3):
+ continue
+ return False
+ return True
+ except Exception:
+ return False
+
+ def get_file_contents(
+ self,
+ universe_name: str,
+ rel_path: str,
+ ) -> tuple[str, str]:
+ """Returns (prime_content, universe_content) for a specific relative file path."""
+ universe = self.multiverse.get_universe(universe_name)
+ if not universe:
+ raise ValueError(f"Universe '{universe_name}' not found.")
+
+ prime_file = self.engine.project_root / rel_path
+ universe_file = Path(universe["path"]) / rel_path
+
+ prime_txt = (
+ prime_file.read_text(encoding="utf-8", errors="ignore")
+ if prime_file.is_file()
+ else ""
+ )
+ universe_txt = (
+ universe_file.read_text(encoding="utf-8", errors="ignore")
+ if universe_file.is_file()
+ else ""
+ )
+
+ return prime_txt, universe_txt
diff --git a/timelord/core/engine.py b/timelord/core/engine.py
new file mode 100644
index 0000000..ff7d274
--- /dev/null
+++ b/timelord/core/engine.py
@@ -0,0 +1,136 @@
+"""
+ChronoEngine: Project root discovery, initialization, and temporal context resolution.
+"""
+
+import json
+import os
+from pathlib import Path
+from typing import Any, Dict, Optional, Tuple
+
+TIMELORD_DIR = ".timelord"
+CONFIG_FILE = "config.json"
+STATE_FILE = "state.json"
+
+
+class ChronoEngine:
+ def __init__(self, start_path: Optional[Path] = None):
+ self.start_path = Path(start_path or os.getcwd()).resolve()
+ self.project_root, self.current_timeline = self._resolve_context(self.start_path)
+ self.timelord_dir = (
+ self.project_root / TIMELORD_DIR if self.project_root else None
+ )
+
+ def _resolve_context(self, path: Path) -> Tuple[Optional[Path], str]:
+ """
+ Determines the project root and whether we are in Prime or a Parallel Universe.
+ If current directory is inside `.timelord/universes/<name>/...`,
+ identifies that universe name and the true project root.
+ """
+ current = path.resolve()
+ parts = current.parts
+
+ # Check if inside an active parallel universe
+ for idx in range(len(parts) - 1):
+ if parts[idx] == TIMELORD_DIR and idx + 2 < len(parts) and parts[idx + 1] == "universes":
+ universe_name = parts[idx + 2]
+ prime_root = Path(*parts[:idx])
+ return prime_root, universe_name
+
+ # Walk up to find .timelord directory
+ check = current
+ while check != check.parent:
+ if (check / TIMELORD_DIR).is_dir():
+ return check, "Prime"
+ check = check.parent
+
+ # Not initialized yet
+ return None, "Prime"
+
+ @property
+ def is_initialized(self) -> bool:
+ return self.timelord_dir is not None and self.timelord_dir.is_dir()
+
+ def init_repository(self, project_path: Optional[Path] = None) -> Path:
+ """Initializes a new TIMELORD chrono-space in the given directory."""
+ root = (project_path or self.start_path).resolve()
+ tl_dir = root / TIMELORD_DIR
+
+ if tl_dir.exists():
+ raise FileExistsError(f"TIMELORD already initialized in {root}")
+
+ # Create directories
+ tl_dir.mkdir(parents=True, exist_ok=True)
+ (tl_dir / "snapshots").mkdir(parents=True, exist_ok=True)
+ (tl_dir / "universes").mkdir(parents=True, exist_ok=True)
+
+ # Default configuration
+ config = {
+ "version": "1.0.0",
+ "prime_timeline_name": "Earth-616",
+ "auto_safety_snapshots": True,
+ "port_offset_step": 100,
+ "exclude_patterns": [
+ ".timelord",
+ ".git",
+ "node_modules",
+ ".venv",
+ "venv",
+ "__pycache__",
+ ".pytest_cache",
+ ".DS_Store",
+ "dist",
+ "build",
+ ],
+ }
+ with open(tl_dir / CONFIG_FILE, "w", encoding="utf-8") as f:
+ json.dump(config, f, indent=2)
+
+ # State tracking
+ state = {
+ "current_prime": "Earth-616",
+ "active_universes": [],
+ "last_snapshot_id": None,
+ }
+ with open(tl_dir / STATE_FILE, "w", encoding="utf-8") as f:
+ json.dump(state, f, indent=2)
+
+ # Add to .gitignore if git repo exists
+ gitignore_path = root / ".gitignore"
+ if gitignore_path.exists():
+ content = gitignore_path.read_text(encoding="utf-8")
+ if ".timelord" not in content:
+ with open(gitignore_path, "a", encoding="utf-8") as f:
+ f.write("\n# TIMELORD Chrono Engine\n.timelord/\n")
+ else:
+ gitignore_path.write_text("# TIMELORD Chrono Engine\n.timelord/\n", encoding="utf-8")
+
+ self.project_root = root
+ self.timelord_dir = tl_dir
+ self.current_timeline = "Prime"
+ return root
+
+ def get_config(self) -> Dict[str, Any]:
+ if not self.is_initialized:
+ return {}
+ cfg_file = self.timelord_dir / CONFIG_FILE
+ if cfg_file.is_file():
+ with open(cfg_file, "r", encoding="utf-8") as f:
+ return json.load(f)
+ return {}
+
+ def get_state(self) -> Dict[str, Any]:
+ if not self.is_initialized:
+ return {}
+ state_file = self.timelord_dir / STATE_FILE
+ if state_file.is_file():
+ with open(state_file, "r", encoding="utf-8") as f:
+ return json.load(f)
+ return {}
+
+ def update_state(self, updates: Dict[str, Any]) -> None:
+ if not self.is_initialized:
+ return
+ state = self.get_state()
+ state.update(updates)
+ with open(self.timelord_dir / STATE_FILE, "w", encoding="utf-8") as f:
+ json.dump(state, f, indent=2)
diff --git a/timelord/core/merge.py b/timelord/core/merge.py
new file mode 100644
index 0000000..ba71d83
--- /dev/null
+++ b/timelord/core/merge.py
@@ -0,0 +1,122 @@
+"""
+Timeline Merger: Canonicalize and merge parallel timeline universes into Prime.
+Achieves the 'Canon Event' - incorporating experimental changes into the main continuum.
+"""
+
+import json
+import os
+import shutil
+import subprocess
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+from timelord.core.compare import TimelineComparator
+from timelord.core.engine import ChronoEngine
+from timelord.core.multiverse import MultiverseManager
+from timelord.core.snapshot import SnapshotManager
+from timelord.utils.copy_cow import copy_file_cow
+from timelord.utils.git_helper import is_git_repository
+
+
+class TimelineMerger:
+ def __init__(self, engine: ChronoEngine):
+ self.engine = engine
+ self.multiverse = MultiverseManager(engine)
+ self.comparator = TimelineComparator(engine)
+ self.snapshots = SnapshotManager(engine)
+
+ def merge_universe_into_prime(
+ self,
+ universe_name: str,
+ create_safety: bool = True,
+ git_commit: bool = False,
+ ) -> Dict[str, Any]:
+ """
+ Applies changes from the parallel universe onto the Prime timeline.
+ 1. Takes an automatic safety snapshot of Prime before touching files.
+ 2. Copies added and modified files to Prime.
+ 3. Removes deleted files from Prime.
+ 4. Optionally creates a Git commit if in a Git repo.
+ 5. Updates universe status to 'merged'.
+ """
+ universe = self.multiverse.get_universe(universe_name)
+ if not universe:
+ raise ValueError(f"Universe '{universe_name}' not found.")
+
+ prime_root = self.engine.project_root
+ universe_dir = Path(universe["path"])
+
+ # Compare differences
+ diff = self.comparator.compare_universe_with_prime(universe_name)
+
+ if diff["is_identical"]:
+ return {
+ "universe_name": universe_name,
+ "status": "already_identical",
+ "message": "Universe and Prime are already identical. No changes to apply.",
+ }
+
+ # 1. Automatic safety snapshot of Prime
+ safety_snap = None
+ if create_safety:
+ safety_snap = self.snapshots.create_snapshot(
+ label=f"Auto-safety before merging universe '{universe_name}'",
+ is_safety=True,
+ )
+
+ # 2. Copy added and modified files
+ for rel in diff["added"] + [m["path"] for m in diff["modified"]]:
+ src_file = universe_dir / rel
+ dst_file = prime_root / rel
+ copy_file_cow(src_file, dst_file)
+
+ # 3. Remove deleted files from Prime
+ for rel in diff["deleted"]:
+ target = prime_root / rel
+ if target.is_file():
+ target.unlink()
+ elif target.is_dir():
+ shutil.rmtree(target)
+
+ # 4. Optional Git integration
+ git_committed = False
+ if git_commit and is_git_repository(prime_root):
+ try:
+ subprocess.run(
+ ["git", "-C", str(prime_root), "add", "-A"],
+ check=True,
+ capture_output=True,
+ )
+ commit_msg = f"[TIMELORD] Canon Event: Merged parallel universe '{universe_name}'"
+ subprocess.run(
+ ["git", "-C", str(prime_root), "commit", "-m", commit_msg],
+ check=True,
+ capture_output=True,
+ )
+ git_committed = True
+ except Exception:
+ pass
+
+ # 5. Mark universe as merged
+ universe["status"] = "merged"
+ universe["merged_at"] = datetime.now().isoformat()
+ with open(universe_dir / "timelord_universe.json", "w", encoding="utf-8") as f:
+ json.dump(universe, f, indent=2)
+
+ # Update engine active list
+ state = self.engine.get_state()
+ active = state.get("active_universes", [])
+ if universe_name in active:
+ active.remove(universe_name)
+ self.engine.update_state({"active_universes": active})
+
+ return {
+ "universe_name": universe_name,
+ "status": "merged",
+ "safety_snapshot_id": safety_snap["id"] if safety_snap else None,
+ "files_added": len(diff["added"]),
+ "files_modified": len(diff["modified"]),
+ "files_deleted": len(diff["deleted"]),
+ "git_committed": git_committed,
+ }
diff --git a/timelord/core/multiverse.py b/timelord/core/multiverse.py
new file mode 100644
index 0000000..6ce981a
--- /dev/null
+++ b/timelord/core/multiverse.py
@@ -0,0 +1,154 @@
+"""
+Multiverse Engine: Spawning, managing, and pruning parallel timeline universes.
+"""
+
+import json
+import re
+import shutil
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Set
+
+from timelord.core.engine import ChronoEngine
+from timelord.core.snapshot import SnapshotManager
+from timelord.utils.copy_cow import clone_directory_cow
+from timelord.utils.env_helper import patch_env_ports_in_universe
+
+
+class MultiverseManager:
+ def __init__(self, engine: ChronoEngine):
+ self.engine = engine
+ if not self.engine.is_initialized:
+ raise RuntimeError("TIMELORD is not initialized. Run `tl init` first.")
+ self.universes_dir = self.engine.timelord_dir / "universes"
+ self.snapshot_manager = SnapshotManager(engine)
+
+ def _sanitize_name(self, name: str) -> str:
+ clean = re.sub(r"[^a-zA-Z0-9_\-]", "-", name.strip().lower())
+ if not clean:
+ raise ValueError("Universe name must contain valid alphanumeric characters.")
+ return clean
+
+ def create_universe(
+ self,
+ name: str,
+ from_snapshot_id: Optional[str] = None,
+ port_offset: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ """
+ Branches the project into a parallel quantum universe.
+ Uses copy-on-write APFS cloning so branching is instant and takes zero initial extra space.
+ """
+ universe_name = self._sanitize_name(name)
+ universe_dir = self.universes_dir / universe_name
+
+ if universe_dir.exists():
+ raise FileExistsError(f"Parallel universe '{universe_name}' already exists.")
+
+ # Determine source state: snapshot or live Prime
+ parent_snap = None
+ if from_snapshot_id:
+ parent_snap = self.snapshot_manager.get_snapshot(from_snapshot_id)
+ if not parent_snap:
+ raise ValueError(f"Snapshot '{from_snapshot_id}' not found.")
+ source_tree = self.snapshot_manager.snapshots_dir / parent_snap["id"] / "tree"
+ else:
+ # Auto-anchor current state before branching so we have a clear temporal origin
+ parent_snap = self.snapshot_manager.create_snapshot(
+ label=f"Timeline branch anchor for universe '{universe_name}'"
+ )
+ source_tree = self.engine.project_root
+
+ # Determine port offset
+ config = self.engine.get_config()
+ step = config.get("port_offset_step", 100)
+ active_universes = self.list_universes(active_only=True)
+ if port_offset is None:
+ port_offset = (len(active_universes) + 1) * step
+
+ # Clone into isolated universe sandbox
+ excludes = set(config.get("exclude_patterns", [".timelord"]))
+ clone_directory_cow(source_tree, universe_dir, exclude_dirs=excludes)
+
+ # Apply port offset to .env files inside universe if any exist
+ remapped_ports = patch_env_ports_in_universe(universe_dir, port_offset)
+
+ # Save universe manifest
+ manifest = {
+ "name": universe_name,
+ "created_at": datetime.now().isoformat(),
+ "parent_snapshot_id": parent_snap["id"],
+ "status": "active",
+ "port_offset": port_offset,
+ "remapped_ports": remapped_ports,
+ "path": str(universe_dir),
+ }
+
+ with open(universe_dir / "timelord_universe.json", "w", encoding="utf-8") as f:
+ json.dump(manifest, f, indent=2)
+
+ # Update engine state
+ state = self.engine.get_state()
+ active = state.get("active_universes", [])
+ if universe_name not in active:
+ active.append(universe_name)
+ self.engine.update_state({"active_universes": active})
+
+ return manifest
+
+ def list_universes(self, active_only: bool = False) -> List[Dict[str, Any]]:
+ """Lists all parallel universes and their statuses."""
+ results = []
+ if not self.universes_dir.exists():
+ return results
+
+ for u_dir in sorted(self.universes_dir.iterdir()):
+ manifest_file = u_dir / "timelord_universe.json"
+ if u_dir.is_dir() and manifest_file.is_file():
+ try:
+ with open(manifest_file, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ if active_only and data.get("status") != "active":
+ continue
+ results.append(data)
+ except Exception:
+ pass
+
+ return results
+
+ def get_universe(self, name: str) -> Optional[Dict[str, Any]]:
+ """Retrieves details of a universe by name."""
+ clean = self._sanitize_name(name)
+ u_dir = self.universes_dir / clean
+ manifest_file = u_dir / "timelord_universe.json"
+ if u_dir.is_dir() and manifest_file.is_file():
+ with open(manifest_file, "r", encoding="utf-8") as f:
+ return json.load(f)
+ return None
+
+ def prune_universe(self, name: str) -> Dict[str, Any]:
+ """
+ 'Break the timeline' / TVA Prune.
+ Collapses and completely removes the parallel universe, returning clean to Prime.
+ """
+ clean = self._sanitize_name(name)
+ u_dir = self.universes_dir / clean
+
+ if not u_dir.exists():
+ raise FileNotFoundError(f"Universe '{clean}' does not exist.")
+
+ manifest = self.get_universe(clean) or {"name": clean}
+
+ # Remove sandbox directory completely
+ shutil.rmtree(u_dir)
+
+ # Update state
+ state = self.engine.get_state()
+ active = state.get("active_universes", [])
+ if clean in active:
+ active.remove(clean)
+ self.engine.update_state({"active_universes": active})
+
+ manifest["status"] = "pruned"
+ manifest["pruned_at"] = datetime.now().isoformat()
+ return manifest
diff --git a/timelord/core/process.py b/timelord/core/process.py
new file mode 100644
index 0000000..b708c85
--- /dev/null
+++ b/timelord/core/process.py
@@ -0,0 +1,102 @@
+"""
+Process Execution Engine: Interactive Subshell warp and concurrent command execution.
+"""
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from timelord.core.engine import ChronoEngine
+from timelord.core.multiverse import MultiverseManager
+from timelord.ui.theme import console
+
+
+class ProcessRunner:
+ def __init__(self, engine: ChronoEngine):
+ self.engine = engine
+ self.multiverse = MultiverseManager(engine)
+
+ def enter_universe_shell(self, universe_name: str) -> int:
+ """
+ Launches an interactive subshell inside the parallel universe
+ with a customized shell prompt and temporal environment variables.
+ """
+ universe = self.multiverse.get_universe(universe_name)
+ if not universe:
+ raise ValueError(f"Universe '{universe_name}' not found.")
+
+ universe_dir = Path(universe["path"])
+ if not universe_dir.is_dir():
+ raise FileNotFoundError(f"Universe directory missing: {universe_dir}")
+
+ shell = os.environ.get("SHELL", "/bin/zsh")
+ user_env = os.environ.copy()
+
+ # Inject temporal context
+ user_env["TIMELORD_UNIVERSE"] = universe_name
+ user_env["TIMELORD_PRIME_PATH"] = str(self.engine.project_root)
+ user_env["TIMELORD_IS_PARALLEL"] = "1"
+
+ if universe.get("port_offset"):
+ user_env["TIMELORD_PORT_OFFSET"] = str(universe["port_offset"])
+
+ # Styled prompt
+ custom_prompt = f"🌌 [TIMELORD: {universe_name}] % "
+ if "zsh" in shell:
+ user_env["PROMPT"] = f"%F{{magenta}}🌌 [TIMELORD: {universe_name}]%f %1~ %# "
+ elif "bash" in shell:
+ user_env["PS1"] = f"\\[\\033[1;35m\\]🌌 [TIMELORD: {universe_name}]\\[\\033[0m\\] \\W \\$ "
+
+ console.print(
+ f"\n[bold magenta]⚑ WARPING INTO PARALLEL UNIVERSE: [bold white]{universe_name}[/bold white][/bold magenta]"
+ )
+ console.print(f"[dim]Working directory: {universe_dir}[/dim]")
+ if universe.get("port_offset"):
+ console.print(f"[yellow]Port offset active: +{universe['port_offset']}[/yellow]")
+ console.print("[dim]Type [bold white]exit[/bold white] or press [bold white]Ctrl+D[/bold white] to return to Prime.[/dim]\n")
+
+ # Launch subshell
+ try:
+ res = subprocess.run([shell, "-i"], cwd=str(universe_dir), env=user_env)
+ console.print(
+ f"\n[bold bright_green]βœ” Returned to Prime Continuum ({self.engine.get_config().get('prime_timeline_name', 'Earth-616')}).[/bold bright_green]\n"
+ )
+ return res.returncode
+ except Exception as e:
+ console.print(f"[bold red]Temporal warp disrupted:[/bold red] {e}")
+ return 1
+
+ def run_in_universe(
+ self,
+ universe_name: str,
+ command: List[str],
+ ) -> int:
+ """Runs a one-off command inside the parallel universe."""
+ universe = self.multiverse.get_universe(universe_name)
+ if not universe:
+ raise ValueError(f"Universe '{universe_name}' not found.")
+
+ universe_dir = Path(universe["path"])
+ if not universe_dir.is_dir():
+ raise FileNotFoundError(f"Universe directory missing: {universe_dir}")
+
+ user_env = os.environ.copy()
+ user_env["TIMELORD_UNIVERSE"] = universe_name
+ user_env["TIMELORD_PRIME_PATH"] = str(self.engine.project_root)
+ user_env["TIMELORD_IS_PARALLEL"] = "1"
+ if universe.get("port_offset"):
+ user_env["TIMELORD_PORT_OFFSET"] = str(universe["port_offset"])
+
+ try:
+ res = subprocess.run(
+ command,
+ cwd=str(universe_dir),
+ env=user_env,
+ text=True,
+ )
+ return res.returncode
+ except Exception as e:
+ console.print(f"[bold red]Command failed to execute in universe {universe_name}:[/bold red] {e}")
+ return 1
diff --git a/timelord/core/snapshot.py b/timelord/core/snapshot.py
new file mode 100644
index 0000000..cd12617
--- /dev/null
+++ b/timelord/core/snapshot.py
@@ -0,0 +1,188 @@
+"""
+Temporal Snapshot Engine for TIMELORD.
+Captures complete project state, Git metadata, environment variables, and file trees.
+"""
+
+import hashlib
+import json
+import os
+import shutil
+import time
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Set
+
+from timelord.core.engine import ChronoEngine
+from timelord.utils.copy_cow import clone_directory_cow
+from timelord.utils.env_helper import get_safe_env_vars, get_system_metadata
+from timelord.utils.git_helper import get_git_state
+
+
+def generate_chrono_id() -> str:
+ """Generates a compact, readable chrono-anchor ID."""
+ hex_suffix = hashlib.sha256(str(time.time_ns()).encode()).hexdigest()[:6]
+ return f"chrono-{hex_suffix}"
+
+
+def hash_file(file_path: Path) -> str:
+ """Calculates SHA-256 hash of a file."""
+ h = hashlib.sha256()
+ with open(file_path, "rb") as f:
+ while chunk := f.read(65536):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+class SnapshotManager:
+ def __init__(self, engine: ChronoEngine):
+ self.engine = engine
+ if not self.engine.is_initialized:
+ raise RuntimeError("TIMELORD is not initialized. Run `tl init` first.")
+ self.snapshots_dir = self.engine.timelord_dir / "snapshots"
+
+ def create_snapshot(
+ self,
+ label: str = "Manual Snapshot",
+ is_safety: bool = False,
+ ) -> Dict[str, Any]:
+ """
+ Freezes the project state at this exact moment in time.
+ Uses copy-on-write APFS cloning for instantaneous zero-storage snapshotting.
+ """
+ root = self.engine.project_root
+ chrono_id = generate_chrono_id()
+ if is_safety:
+ chrono_id = f"safety-{chrono_id.replace('chrono-', '')}"
+
+ snapshot_dir = self.snapshots_dir / chrono_id
+ tree_dir = snapshot_dir / "tree"
+ snapshot_dir.mkdir(parents=True, exist_ok=True)
+
+ config = self.engine.get_config()
+ excludes: Set[str] = set(config.get("exclude_patterns", [".timelord", ".git"]))
+
+ # Copy-on-Write clone of project files
+ clone_directory_cow(root, tree_dir, exclude_dirs=excludes)
+
+ # Inventory files and stats
+ file_tree = {}
+ total_bytes = 0
+ for p in tree_dir.rglob("*"):
+ if p.is_file():
+ rel = str(p.relative_to(tree_dir))
+ size = p.stat().st_size
+ total_bytes += size
+ file_tree[rel] = {
+ "size": size,
+ "hash": hash_file(p),
+ }
+
+ # Capture environmental & git coordinates
+ git_metadata = get_git_state(root)
+ system_metadata = get_system_metadata()
+ env_vars = get_safe_env_vars()
+
+ metadata = {
+ "id": chrono_id,
+ "label": label,
+ "timestamp": datetime.now().isoformat(),
+ "is_safety": is_safety,
+ "git": git_metadata,
+ "system": system_metadata,
+ "environment": env_vars,
+ "stats": {
+ "total_files": len(file_tree),
+ "total_bytes": total_bytes,
+ },
+ "files": file_tree,
+ }
+
+ # Save metadata
+ with open(snapshot_dir / "metadata.json", "w", encoding="utf-8") as f:
+ json.dump(metadata, f, indent=2)
+
+ # Update engine state
+ self.engine.update_state({"last_snapshot_id": chrono_id})
+
+ return metadata
+
+ def list_snapshots(self) -> List[Dict[str, Any]]:
+ """Returns all snapshots in chronological order."""
+ snapshots = []
+ if not self.snapshots_dir.exists():
+ return snapshots
+
+ for s_dir in sorted(self.snapshots_dir.iterdir()):
+ meta_file = s_dir / "metadata.json"
+ if s_dir.is_dir() and meta_file.is_file():
+ try:
+ with open(meta_file, "r", encoding="utf-8") as f:
+ snapshots.append(json.load(f))
+ except Exception:
+ pass
+
+ # Sort by timestamp
+ snapshots.sort(key=lambda s: s.get("timestamp", ""))
+ return snapshots
+
+ def get_snapshot(self, snapshot_id: str) -> Optional[Dict[str, Any]]:
+ """Retrieves a specific snapshot by ID or prefix."""
+ # Exact match
+ target = self.snapshots_dir / snapshot_id
+ if target.is_dir() and (target / "metadata.json").is_file():
+ with open(target / "metadata.json", "r", encoding="utf-8") as f:
+ return json.load(f)
+
+ # Prefix match
+ for s_dir in self.snapshots_dir.iterdir():
+ if s_dir.name.startswith(snapshot_id) and (s_dir / "metadata.json").is_file():
+ with open(s_dir / "metadata.json", "r", encoding="utf-8") as f:
+ return json.load(f)
+
+ return None
+
+ def restore_snapshot(
+ self,
+ snapshot_id: str,
+ create_safety: bool = True,
+ ) -> Dict[str, Any]:
+ """
+ Rewinds the project to an earlier snapshot.
+ Automatically takes a safety snapshot before rewinding to guarantee no work is lost.
+ """
+ snapshot = self.get_snapshot(snapshot_id)
+ if not snapshot:
+ raise ValueError(f"Snapshot '{snapshot_id}' not found in timeline.")
+
+ real_id = snapshot["id"]
+ source_tree = self.snapshots_dir / real_id / "tree"
+ if not source_tree.is_dir():
+ raise FileNotFoundError(f"Snapshot files corrupted or missing for {real_id}")
+
+ safety_snap = None
+ if create_safety:
+ safety_snap = self.create_snapshot(
+ label=f"Auto-safety before rewinding to {real_id}",
+ is_safety=True,
+ )
+
+ root = self.engine.project_root
+ config = self.engine.get_config()
+ excludes = set(config.get("exclude_patterns", [".timelord", ".git"]))
+
+ # Remove existing project files (except excluded)
+ for item in root.iterdir():
+ if item.name in excludes:
+ continue
+ if item.is_dir():
+ shutil.rmtree(item)
+ else:
+ item.unlink()
+
+ # Copy restored files
+ clone_directory_cow(source_tree, root, exclude_dirs={".timelord"}, allow_existing_dst=True)
+
+ return {
+ "restored_snapshot": snapshot,
+ "safety_snapshot": safety_snap,
+ }
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)
diff --git a/timelord/utils/__init__.py b/timelord/utils/__init__.py
new file mode 100644
index 0000000..d0e5f9b
--- /dev/null
+++ b/timelord/utils/__init__.py
@@ -0,0 +1 @@
+"""TIMELORD utilities package."""
diff --git a/timelord/utils/copy_cow.py b/timelord/utils/copy_cow.py
new file mode 100644
index 0000000..60e6626
--- /dev/null
+++ b/timelord/utils/copy_cow.py
@@ -0,0 +1,113 @@
+"""
+Copy-on-Write and cloning utilities for TIMELORD.
+Leverages macOS APFS clonefile (cp -c -R) for instant, zero-storage cloning,
+with graceful fallbacks for other platforms.
+"""
+
+import os
+import platform
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Callable, List, Optional, Set
+
+
+def is_macos() -> bool:
+ return platform.system().lower() == "darwin"
+
+
+def clone_directory_cow(
+ src: Path,
+ dst: Path,
+ exclude_dirs: Optional[Set[str]] = None,
+ progress_callback: Optional[Callable[[str], None]] = None,
+ allow_existing_dst: bool = False,
+) -> bool:
+ """
+ Clones a directory using Copy-on-Write where supported.
+ On macOS APFS, uses `cp -c -R` which creates block-level clones in milliseconds
+ without consuming extra disk space.
+ """
+ src = Path(src).resolve()
+ dst = Path(dst).resolve()
+
+ if exclude_dirs is None:
+ exclude_dirs = {".timelord", ".venv", "__pycache__", ".pytest_cache"}
+
+ if dst.exists() and not allow_existing_dst:
+ raise FileExistsError(f"Target destination already exists: {dst}")
+
+ dst.parent.mkdir(parents=True, exist_ok=True)
+
+ if progress_callback:
+ progress_callback(f"Cloning {src.name} to {dst.name}...")
+
+ # If on macOS, try APFS clone with cp -c -R
+ if is_macos():
+ # First copy excluding excluded top-level directories
+ # We can create dst, then copy entries
+ dst.mkdir(parents=True, exist_ok=True)
+
+ for item in src.iterdir():
+ if item.name in exclude_dirs:
+ continue
+
+ target_item = dst / item.name
+ try:
+ # Use macOS cp -c -R for instant APFS clone
+ cmd = ["cp", "-c", "-R", "-p", str(item), str(target_item)]
+ subprocess.run(cmd, check=True, capture_output=True)
+ except (subprocess.CalledProcessError, FileNotFoundError):
+ # Fallback to shutil if cp -c fails (e.g. cross-volume or non-APFS)
+ if item.is_dir():
+ shutil.copytree(
+ item,
+ target_item,
+ symlinks=True,
+ ignore=shutil.ignore_patterns(*exclude_dirs),
+ )
+ else:
+ shutil.copy2(item, target_item)
+ return True
+ else:
+ # Linux or other OS: try cp --reflink=auto or fallback to copytree
+ try:
+ cmd = ["cp", "--reflink=auto", "-R", str(src), str(dst)]
+ subprocess.run(cmd, check=True, capture_output=True)
+ # Remove excluded dirs in target
+ for exc in exclude_dirs:
+ exc_path = dst / exc
+ if exc_path.exists():
+ if exc_path.is_dir():
+ shutil.rmtree(exc_path)
+ else:
+ exc_path.unlink()
+ return True
+ except Exception:
+ # Fallback
+ def _ignore_filter(directory, contents):
+ return [c for c in contents if c in exclude_dirs]
+
+ shutil.copytree(src, dst, symlinks=True, ignore=_ignore_filter)
+ return True
+
+
+def copy_file_cow(src: Path, dst: Path) -> bool:
+ """Clones a single file using copy-on-write if possible."""
+ src = Path(src).resolve()
+ dst = Path(dst).resolve()
+ dst.parent.mkdir(parents=True, exist_ok=True)
+
+ if is_macos():
+ try:
+ cmd = ["cp", "-c", "-p", str(src), str(dst)]
+ subprocess.run(cmd, check=True, capture_output=True)
+ return True
+ except Exception:
+ pass
+
+ try:
+ shutil.copy2(src, dst)
+ return True
+ except Exception:
+ return False
diff --git a/timelord/utils/env_helper.py b/timelord/utils/env_helper.py
new file mode 100644
index 0000000..b5fe819
--- /dev/null
+++ b/timelord/utils/env_helper.py
@@ -0,0 +1,142 @@
+"""
+Environment detection, port management, and process context for TIMELORD.
+Enables running multiple universes concurrently without port collisions.
+"""
+
+import os
+import platform
+import re
+import socket
+import sys
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Set
+
+# Keys to sanitize from snapshots for security
+SENSITIVE_KEY_PATTERNS = [
+ r"key",
+ r"secret",
+ r"token",
+ r"password",
+ r"auth",
+ r"private",
+ r"credential",
+]
+
+
+def is_sensitive(key: str) -> bool:
+ key_lower = key.lower()
+ return any(
+ re.search(pat, key_lower) for pat in SENSITIVE_KEY_PATTERNS
+ )
+
+
+def get_system_metadata() -> Dict[str, Any]:
+ """Captures system runtime metadata (Python, OS, host)."""
+ node_version = None
+ try:
+ import subprocess
+
+ res = subprocess.run(["node", "--version"], capture_output=True, text=True)
+ if res.returncode == 0:
+ node_version = res.stdout.strip()
+ except Exception:
+ pass
+
+ return {
+ "os": platform.system(),
+ "os_release": platform.release(),
+ "arch": platform.machine(),
+ "python_version": sys.version.split()[0],
+ "node_version": node_version,
+ }
+
+
+def get_safe_env_vars() -> Dict[str, str]:
+ """Returns safe, non-sensitive environment variables for temporal capture."""
+ safe_vars = {}
+ important_vars = {
+ "PATH",
+ "VIRTUAL_ENV",
+ "NODE_ENV",
+ "PYTHONPATH",
+ "PORT",
+ "HOST",
+ "SHELL",
+ "EDITOR",
+ "TIMELORD_UNIVERSE",
+ }
+
+ for key, value in os.environ.items():
+ if key in important_vars or not is_sensitive(key):
+ # Limit length to avoid bloating
+ if len(value) < 1024:
+ safe_vars[key] = value
+
+ return safe_vars
+
+
+def detect_configured_ports(project_dir: Path) -> List[int]:
+ """Scans .env, package.json, and docker-compose for configured ports."""
+ ports: Set[int] = set()
+
+ # Check .env files
+ for env_name in [".env", ".env.local", ".env.development"]:
+ env_file = project_dir / env_name
+ if env_file.is_file():
+ try:
+ content = env_file.read_text(encoding="utf-8", errors="ignore")
+ for match in re.finditer(r"PORT\s*=\s*(\d+)", content, re.IGNORECASE):
+ ports.add(int(match.group(1)))
+ except Exception:
+ pass
+
+ # Check package.json scripts (e.g. -p 3000, --port 3000)
+ pkg_file = project_dir / "package.json"
+ if pkg_file.is_file():
+ try:
+ content = pkg_file.read_text(encoding="utf-8", errors="ignore")
+ for match in re.finditer(r"(?:--port|-p)\s+(\d+)", content):
+ ports.add(int(match.group(1)))
+ except Exception:
+ pass
+
+ return sorted(list(ports))
+
+
+def is_port_in_use(port: int, host: str = "127.0.0.1") -> bool:
+ """Checks if a TCP port is currently open and bound."""
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(0.5)
+ return s.connect_ex((host, port)) == 0
+
+
+def patch_env_ports_in_universe(universe_dir: Path, port_offset: int) -> Dict[str, int]:
+ """
+ Adjusts PORT definitions in universe .env files by the given offset
+ so parallel universe dev servers do not conflict with Prime.
+ """
+ remapped = {}
+ for env_name in [".env", ".env.local", ".env.development"]:
+ env_file = universe_dir / env_name
+ if not env_file.is_file():
+ continue
+
+ try:
+ content = env_file.read_text(encoding="utf-8", errors="ignore")
+ new_lines = []
+ for line in content.splitlines():
+ match = re.match(r"^(\s*PORT\s*=\s*)(\d+)(.*)$", line, re.IGNORECASE)
+ if match:
+ prefix, old_port_str, suffix = match.groups()
+ old_port = int(old_port_str)
+ new_port = old_port + port_offset
+ remapped[f"{env_name}:PORT"] = new_port
+ new_lines.append(f"{prefix}{new_port}{suffix}")
+ else:
+ new_lines.append(line)
+
+ env_file.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
+ except Exception:
+ pass
+
+ return remapped
diff --git a/timelord/utils/git_helper.py b/timelord/utils/git_helper.py
new file mode 100644
index 0000000..94c23ec
--- /dev/null
+++ b/timelord/utils/git_helper.py
@@ -0,0 +1,101 @@
+"""
+Git inspection and integration helpers for TIMELORD.
+Safe against non-git directories.
+"""
+
+import subprocess
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+
+def is_git_repository(path: Path) -> bool:
+ try:
+ res = subprocess.run(
+ ["git", "-C", str(path), "rev-parse", "--is-inside-work-tree"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return res.returncode == 0 and res.stdout.strip() == "true"
+ except Exception:
+ return False
+
+
+def get_git_state(path: Path) -> Dict[str, Any]:
+ """Extracts git metadata: current branch, commit, dirty status, diff summaries."""
+ if not is_git_repository(path):
+ return {
+ "is_git": False,
+ "branch": None,
+ "head_sha": None,
+ "head_message": None,
+ "is_dirty": False,
+ "staged_files": [],
+ "unstaged_files": [],
+ "untracked_files": [],
+ "stash_count": 0,
+ }
+
+ def _run_git(args: List[str]) -> str:
+ res = subprocess.run(
+ ["git", "-C", str(path)] + args,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return res.stdout.strip() if res.returncode == 0 else ""
+
+ # Branch
+ branch = _run_git(["branch", "--show-current"])
+ if not branch:
+ branch = _run_git(["rev-parse", "--short", "HEAD"]) or "HEAD"
+
+ # HEAD commit
+ head_sha = _run_git(["rev-parse", "HEAD"])
+ head_msg = _run_git(["log", "-1", "--pretty=%B"])
+
+ # Status porcelein
+ status_raw = _run_git(["status", "--porcelain"])
+ staged = []
+ unstaged = []
+ untracked = []
+
+ for line in status_raw.splitlines():
+ if not line:
+ continue
+ code = line[:2]
+ filename = line[3:].strip()
+ if code[0] in ("M", "A", "D", "R", "C"):
+ staged.append(filename)
+ if code[1] in ("M", "D"):
+ unstaged.append(filename)
+ if code == "??":
+ untracked.append(filename)
+
+ # Stash count
+ stash_raw = _run_git(["stash", "list"])
+ stash_count = len(stash_raw.splitlines()) if stash_raw else 0
+
+ return {
+ "is_git": True,
+ "branch": branch,
+ "head_sha": head_sha[:8] if head_sha else None,
+ "head_sha_full": head_sha,
+ "head_message": head_msg.splitlines()[0] if head_msg else None,
+ "is_dirty": bool(staged or unstaged or untracked),
+ "staged_files": staged,
+ "unstaged_files": unstaged,
+ "untracked_files": untracked,
+ "stash_count": stash_count,
+ }
+
+
+def get_git_diff(path: Path, staged: bool = False) -> str:
+ """Returns the git diff for staged or unstaged changes."""
+ if not is_git_repository(path):
+ return ""
+ args = ["git", "-C", str(path), "diff"]
+ if staged:
+ args.append("--staged")
+ res = subprocess.run(args, capture_output=True, text=True, check=False)
+ return res.stdout if res.returncode == 0 else ""