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