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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
|
"""
TIMELORD CLI: Rewind your dev environment. Split parallel timelines. Break anomalies.
"""
import sys
from pathlib import Path
from typing import List, Optional
import click
from rich.prompt import Confirm
from timelord.core.compare import TimelineComparator
from timelord.core.engine import ChronoEngine
from timelord.core.merge import TimelineMerger
from timelord.core.multiverse import MultiverseManager
from timelord.core.process import ProcessRunner
from timelord.core.snapshot import SnapshotManager
from timelord.ui.diff_view import render_diff_summary, render_side_by_side_diff
from timelord.ui.theme import BANNER, MINI_BANNER, SCI_FI_QUOTES, console
from timelord.ui.views import (
render_multiverse_tree,
render_snapshots_table,
render_status_dashboard,
render_universes_table,
)
from timelord.utils.env_helper import detect_configured_ports
from timelord.utils.git_helper import get_git_state
def get_engine() -> ChronoEngine:
engine = ChronoEngine()
return engine
def ensure_initialized(engine: ChronoEngine) -> None:
if not engine.is_initialized:
console.print(
"[bold red]Temporal rift detected:[/bold red] TIMELORD is not initialized in this project.\n"
"Run [bold cyan]tl init[/bold cyan] to create your project's Prime Timeline."
)
sys.exit(1)
@click.group(invoke_without_command=True)
@click.pass_context
@click.version_option(version="1.0.0", prog_name="timelord")
def cli(ctx: click.Context) -> None:
"""⚡ TIMELORD: Experimental snapshot & parallel universe CLI for coding projects."""
if ctx.invoked_subcommand is None:
console.print(BANNER)
console.print(
"[bold cyan]Usage:[/bold cyan] [bold white]tl [COMMAND][/bold white] (e.g. `tl status`, `tl freeze`, `tl branch`, `tl diff`)\n"
"Run [bold cyan]tl --help[/bold cyan] for full temporal commands.\n"
)
@cli.command(name="init")
def cmd_init() -> None:
"""Initialize a Timelord repository in the current project."""
engine = get_engine()
if engine.is_initialized:
console.print(f"[bold yellow]TIMELORD already initialized at:[/bold yellow] {engine.project_root}")
return
try:
root = engine.init_repository()
console.print(BANNER)
console.print(f"[bold bright_green]✔ Chrono-Space established at:[/bold bright_green] [cyan]{root}[/cyan]")
console.print("[dim]Prime Timeline anchored as Earth-616.[/dim]")
console.print("[dim]Ready to freeze time with [bold cyan]tl freeze[/bold cyan] or split reality with [bold cyan]tl branch <name>[/bold cyan].[/dim]\n")
except Exception as e:
console.print(f"[bold red]Initialization failed:[/bold red] {e}")
sys.exit(1)
@cli.command(name="status")
def cmd_status() -> None:
"""Show current temporal coordinates, git state, and parallel universes."""
engine = get_engine()
ensure_initialized(engine)
git_state = get_git_state(engine.project_root)
ports = detect_configured_ports(engine.project_root)
multiverse = MultiverseManager(engine)
active_universes = multiverse.list_universes(active_only=True)
snapshots = SnapshotManager(engine)
last_id = engine.get_state().get("last_snapshot_id")
last_snap = snapshots.get_snapshot(last_id) if last_id else None
render_status_dashboard(
current_timeline=engine.current_timeline,
project_root=engine.project_root,
last_snapshot=last_snap,
git_state=git_state,
active_universes=active_universes,
ports=ports,
)
@cli.command(name="freeze")
@click.argument("label", required=False, default="Manual Temporal Anchor")
def cmd_freeze(label: str) -> None:
"""Freeze current project state into an immutable temporal snapshot."""
engine = get_engine()
ensure_initialized(engine)
manager = SnapshotManager(engine)
with console.status("[bold cyan]Freezing time & capturing project state...[/bold cyan]", spinner="dots"):
snap = manager.create_snapshot(label=label)
console.print(
f"\n[bold bright_green]✔ Time frozen successfully![/bold bright_green] Anchor ID: [bold bright_yellow]{snap['id']}[/bold bright_yellow]"
)
console.print(f"[dim]Label: \"{snap['label']}\"[/dim]")
console.print(f"[dim]Total files captured: {snap['stats']['total_files']}[/dim]")
console.print(f"[dim italic]{SCI_FI_QUOTES['freeze']}[/dim italic]\n")
@cli.command(name="branch")
@click.argument("universe_name")
@click.option("--from", "from_snapshot", help="Branch from a specific snapshot ID instead of current state.")
@click.option("--port-offset", type=int, default=None, help="TCP Port offset for parallel dev server (default: +100).")
def cmd_branch(universe_name: str, from_snapshot: Optional[str], port_offset: Optional[int]) -> None:
"""Branch into a parallel universe to experiment with risky changes."""
engine = get_engine()
ensure_initialized(engine)
manager = MultiverseManager(engine)
with console.status(
f"[bold magenta]Quantum splitting reality into universe '{universe_name}'...[/bold magenta]",
spinner="aesthetic",
):
try:
universe = manager.create_universe(
name=universe_name,
from_snapshot_id=from_snapshot,
port_offset=port_offset,
)
except Exception as e:
console.print(f"[bold red]Multiverse branching failed:[/bold red] {e}")
sys.exit(1)
console.print(
f"\n[bold bright_green]✔ Parallel Universe spawned:[/bold bright_green] [bold magenta]🌌 {universe['name']}[/bold magenta]"
)
console.print(f"[dim]Location: {universe['path']}[/dim]")
console.print(f"[dim]Branched from anchor: {universe['parent_snapshot_id']}[/dim]")
if universe.get("port_offset"):
console.print(f"[yellow]Port offset allocated: +{universe['port_offset']}[/yellow]")
console.print(f"[dim italic]{SCI_FI_QUOTES['branch']}[/dim italic]\n")
console.print(
f"To enter this universe, run:\n [bold cyan]tl enter {universe['name']}[/bold cyan]\n"
f"Or run commands directly:\n [bold cyan]tl run {universe['name']} -- <command>[/bold cyan]\n"
)
@cli.command(name="enter")
@click.argument("universe_name")
def cmd_enter(universe_name: str) -> None:
"""Enter a parallel universe via an isolated subshell."""
engine = get_engine()
ensure_initialized(engine)
runner = ProcessRunner(engine)
exit_code = runner.enter_universe_shell(universe_name)
sys.exit(exit_code)
@cli.command(name="run")
@click.argument("universe_name")
@click.argument("cmd", nargs=-1, required=True)
def cmd_run(universe_name: str, cmd: List[str]) -> None:
"""Run a command inside a parallel universe (e.g. `tl run refactor -- npm test`)."""
engine = get_engine()
ensure_initialized(engine)
runner = ProcessRunner(engine)
exit_code = runner.run_in_universe(universe_name, list(cmd))
sys.exit(exit_code)
@cli.command(name="diff")
@click.argument("universe_name")
@click.option("--file", "target_file", default=None, help="Inspect side-by-side diff of a specific file.")
@click.option("--side-by-side/--summary-only", default=True, help="Display side-by-side split screen diffs.")
def cmd_diff(universe_name: str, target_file: Optional[str], side_by_side: bool) -> None:
"""Compare Prime Timeline with a Parallel Universe side by side."""
engine = get_engine()
ensure_initialized(engine)
comparator = TimelineComparator(engine)
try:
diff_res = comparator.compare_universe_with_prime(universe_name)
except Exception as e:
console.print(f"[bold red]Comparison error:[/bold red] {e}")
sys.exit(1)
if diff_res["is_identical"]:
console.print(
f"\n[bold bright_green]✔ Universe '{universe_name}' and Prime are in exact quantum resonance (0 differences).[/bold bright_green]\n"
)
return
# Print summary table
console.print("")
summary_table = render_diff_summary(diff_res)
console.print(summary_table)
# If specific file requested, show its side-by-side diff
if target_file:
prime_txt, uni_txt = comparator.get_file_contents(universe_name, target_file)
render_side_by_side_diff(
file_rel_path=target_file,
content_a=prime_txt,
content_b=uni_txt,
label_a="Prime (Earth-616)",
label_b=f"Universe: {universe_name}",
)
elif side_by_side and diff_res["modified"]:
console.print("\n[bold cyan]─── Side-by-Side Visual Diff of Modified Files ───[/bold cyan]\n")
# Show first 3 modified files
for mod in diff_res["modified"][:3]:
rel = mod["path"]
prime_txt, uni_txt = comparator.get_file_contents(universe_name, rel)
render_side_by_side_diff(
file_rel_path=rel,
content_a=prime_txt,
content_b=uni_txt,
label_a="Prime (Earth-616)",
label_b=f"Universe: {universe_name}",
)
@cli.command(name="prune")
@click.argument("universe_name")
@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt.")
def cmd_prune(universe_name: str, yes: bool) -> None:
"""Break the timeline! Prune and discard a parallel universe."""
engine = get_engine()
ensure_initialized(engine)
if not yes:
if not Confirm.ask(
f"[bold red]Are you sure you want to prune parallel universe '{universe_name}' and discard its changes?[/bold red]"
):
console.print("[dim]Operation aborted. Timeline remains intact.[/dim]")
return
manager = MultiverseManager(engine)
try:
res = manager.prune_universe(universe_name)
console.print(
f"\n[bold bright_red]✔ Timeline pruned![/bold bright_red] Parallel universe [bold magenta]'{universe_name}'[/bold magenta] collapsed."
)
console.print(f"[dim italic]{SCI_FI_QUOTES['prune']}[/dim italic]\n")
except Exception as e:
console.print(f"[bold red]Prune failed:[/bold red] {e}")
sys.exit(1)
@cli.command(name="merge")
@click.argument("universe_name")
@click.option("--git-commit/--no-git-commit", default=False, help="Automatically create a Git commit on Prime.")
@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt.")
def cmd_merge(universe_name: str, git_commit: bool, yes: bool) -> None:
"""Canon Event Achieved! Merge parallel universe changes into Prime."""
engine = get_engine()
ensure_initialized(engine)
if not yes:
if not Confirm.ask(
f"[bold bright_green]Incorporate universe '{universe_name}' changes into Prime Timeline?[/bold bright_green]"
):
console.print("[dim]Merge aborted.[/dim]")
return
merger = TimelineMerger(engine)
with console.status(f"[bold cyan]Merging universe '{universe_name}' into Prime...[/bold cyan]", spinner="dots"):
try:
res = merger.merge_universe_into_prime(
universe_name,
create_safety=True,
git_commit=git_commit,
)
except Exception as e:
console.print(f"[bold red]Merge failed:[/bold red] {e}")
sys.exit(1)
if res.get("status") == "already_identical":
console.print(f"[yellow]{res['message']}[/yellow]")
return
console.print(
f"\n[bold bright_green]✔ Canon Event Achieved![/bold bright_green] Changes from [bold magenta]'{universe_name}'[/bold magenta] integrated."
)
console.print(f"[dim]Safety snapshot created: [yellow]{res.get('safety_snapshot_id')}[/yellow][/dim]")
console.print(
f"[dim]Files: +{res['files_added']} added, ~{res['files_modified']} modified, -{res['files_deleted']} removed[/dim]"
)
if res.get("git_committed"):
console.print("[green]✔ Git commit created on Prime continuum.[/green]")
console.print(f"[dim italic]{SCI_FI_QUOTES['merge']}[/dim italic]\n")
@cli.command(name="rewind")
@click.argument("snapshot_id")
@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt.")
def cmd_rewind(snapshot_id: str, yes: bool) -> None:
"""Rewind your project files to an earlier snapshot."""
engine = get_engine()
ensure_initialized(engine)
if not yes:
if not Confirm.ask(
f"[bold bright_yellow]Rewind project to snapshot '{snapshot_id}'? (An auto-safety snapshot will be taken)[/bold bright_yellow]"
):
console.print("[dim]Rewind cancelled.[/dim]")
return
snapshots = SnapshotManager(engine)
with console.status(f"[bold yellow]Rewinding temporal coordinates to {snapshot_id}...[/bold yellow]", spinner="dots"):
try:
res = snapshots.restore_snapshot(snapshot_id, create_safety=True)
except Exception as e:
console.print(f"[bold red]Rewind failed:[/bold red] {e}")
sys.exit(1)
console.print(
f"\n[bold bright_green]✔ Timeline successfully rewound to:[/bold bright_green] [bold yellow]{res['restored_snapshot']['id']}[/bold yellow]"
)
if res.get("safety_snapshot"):
console.print(
f"[dim]Pre-rewind state saved as safety anchor: [yellow]{res['safety_snapshot']['id']}[/yellow][/dim]"
)
console.print(f"[dim italic]{SCI_FI_QUOTES['rewind']}[/dim italic]\n")
@cli.command(name="universes")
def cmd_universes() -> None:
"""List all parallel universe timelines."""
engine = get_engine()
ensure_initialized(engine)
manager = MultiverseManager(engine)
all_univs = manager.list_universes()
if not all_univs:
console.print("[dim]No parallel universes recorded yet. Use `tl branch <name>` to split time.[/dim]")
return
render_universes_table(all_univs, current=engine.current_timeline)
@cli.command(name="snapshots")
def cmd_snapshots() -> None:
"""List all frozen temporal anchors."""
engine = get_engine()
ensure_initialized(engine)
manager = SnapshotManager(engine)
all_snaps = manager.list_snapshots()
if not all_snaps:
console.print("[dim]No snapshots recorded yet. Use `tl freeze <label>` to create an anchor.[/dim]")
return
render_snapshots_table(all_snaps)
@cli.command(name="tree")
def cmd_tree() -> None:
"""Visualize the multiverse tree and branching timelines."""
engine = get_engine()
ensure_initialized(engine)
snapshots = SnapshotManager(engine).list_snapshots()
universes = MultiverseManager(engine).list_universes()
console.print(MINI_BANNER)
console.print("")
render_multiverse_tree(snapshots, universes, current_timeline=engine.current_timeline)
console.print("")
# Aliases
cli.add_command(cmd_freeze, name="snapshot")
cli.add_command(cmd_branch, name="split")
cli.add_command(cmd_enter, name="warp")
cli.add_command(cmd_prune, name="break")
cli.add_command(cmd_prune, name="collapse")
cli.add_command(cmd_merge, name="canon")
cli.add_command(cmd_rewind, name="jump")
cli.add_command(cmd_tree, name="log")
cli.add_command(cmd_universes, name="list")
def main() -> None:
cli()
if __name__ == "__main__":
main()
|