summaryrefslogtreecommitdiff
path: root/timelord/core/snapshot.py
blob: cd12617f697f324c3f908d3c857d77dc3af3fd23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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,
        }