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