summaryrefslogtreecommitdiff
path: root/timelord/core/engine.py
blob: ff7d2746e387e9063441d3f2c23bf91d1141c373 (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
"""
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)