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