summaryrefslogtreecommitdiff
path: root/timelord/utils
diff options
context:
space:
mode:
authorBEAST <macbook@Macbooks-MacBook-Pro.local>2026-10-14 18:28:51 +0530
committerBEAST <macbook@Macbooks-MacBook-Pro.local>2026-10-14 18:28:51 +0530
commitdaae7c3cfe18cd4d7de7c5fdffad8c2e54ff7d72 (patch)
tree1b7213a19fdb109cfdaf1c0af96f9a6771c41d47 /timelord/utils
feat: initial commit of TIMELORD Chrono Engine CLI
Diffstat (limited to 'timelord/utils')
-rw-r--r--timelord/utils/__init__.py1
-rw-r--r--timelord/utils/copy_cow.py113
-rw-r--r--timelord/utils/env_helper.py142
-rw-r--r--timelord/utils/git_helper.py101
4 files changed, 357 insertions, 0 deletions
diff --git a/timelord/utils/__init__.py b/timelord/utils/__init__.py
new file mode 100644
index 0000000..d0e5f9b
--- /dev/null
+++ b/timelord/utils/__init__.py
@@ -0,0 +1 @@
+"""TIMELORD utilities package."""
diff --git a/timelord/utils/copy_cow.py b/timelord/utils/copy_cow.py
new file mode 100644
index 0000000..60e6626
--- /dev/null
+++ b/timelord/utils/copy_cow.py
@@ -0,0 +1,113 @@
+"""
+Copy-on-Write and cloning utilities for TIMELORD.
+Leverages macOS APFS clonefile (cp -c -R) for instant, zero-storage cloning,
+with graceful fallbacks for other platforms.
+"""
+
+import os
+import platform
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Callable, List, Optional, Set
+
+
+def is_macos() -> bool:
+ return platform.system().lower() == "darwin"
+
+
+def clone_directory_cow(
+ src: Path,
+ dst: Path,
+ exclude_dirs: Optional[Set[str]] = None,
+ progress_callback: Optional[Callable[[str], None]] = None,
+ allow_existing_dst: bool = False,
+) -> bool:
+ """
+ Clones a directory using Copy-on-Write where supported.
+ On macOS APFS, uses `cp -c -R` which creates block-level clones in milliseconds
+ without consuming extra disk space.
+ """
+ src = Path(src).resolve()
+ dst = Path(dst).resolve()
+
+ if exclude_dirs is None:
+ exclude_dirs = {".timelord", ".venv", "__pycache__", ".pytest_cache"}
+
+ if dst.exists() and not allow_existing_dst:
+ raise FileExistsError(f"Target destination already exists: {dst}")
+
+ dst.parent.mkdir(parents=True, exist_ok=True)
+
+ if progress_callback:
+ progress_callback(f"Cloning {src.name} to {dst.name}...")
+
+ # If on macOS, try APFS clone with cp -c -R
+ if is_macos():
+ # First copy excluding excluded top-level directories
+ # We can create dst, then copy entries
+ dst.mkdir(parents=True, exist_ok=True)
+
+ for item in src.iterdir():
+ if item.name in exclude_dirs:
+ continue
+
+ target_item = dst / item.name
+ try:
+ # Use macOS cp -c -R for instant APFS clone
+ cmd = ["cp", "-c", "-R", "-p", str(item), str(target_item)]
+ subprocess.run(cmd, check=True, capture_output=True)
+ except (subprocess.CalledProcessError, FileNotFoundError):
+ # Fallback to shutil if cp -c fails (e.g. cross-volume or non-APFS)
+ if item.is_dir():
+ shutil.copytree(
+ item,
+ target_item,
+ symlinks=True,
+ ignore=shutil.ignore_patterns(*exclude_dirs),
+ )
+ else:
+ shutil.copy2(item, target_item)
+ return True
+ else:
+ # Linux or other OS: try cp --reflink=auto or fallback to copytree
+ try:
+ cmd = ["cp", "--reflink=auto", "-R", str(src), str(dst)]
+ subprocess.run(cmd, check=True, capture_output=True)
+ # Remove excluded dirs in target
+ for exc in exclude_dirs:
+ exc_path = dst / exc
+ if exc_path.exists():
+ if exc_path.is_dir():
+ shutil.rmtree(exc_path)
+ else:
+ exc_path.unlink()
+ return True
+ except Exception:
+ # Fallback
+ def _ignore_filter(directory, contents):
+ return [c for c in contents if c in exclude_dirs]
+
+ shutil.copytree(src, dst, symlinks=True, ignore=_ignore_filter)
+ return True
+
+
+def copy_file_cow(src: Path, dst: Path) -> bool:
+ """Clones a single file using copy-on-write if possible."""
+ src = Path(src).resolve()
+ dst = Path(dst).resolve()
+ dst.parent.mkdir(parents=True, exist_ok=True)
+
+ if is_macos():
+ try:
+ cmd = ["cp", "-c", "-p", str(src), str(dst)]
+ subprocess.run(cmd, check=True, capture_output=True)
+ return True
+ except Exception:
+ pass
+
+ try:
+ shutil.copy2(src, dst)
+ return True
+ except Exception:
+ return False
diff --git a/timelord/utils/env_helper.py b/timelord/utils/env_helper.py
new file mode 100644
index 0000000..b5fe819
--- /dev/null
+++ b/timelord/utils/env_helper.py
@@ -0,0 +1,142 @@
+"""
+Environment detection, port management, and process context for TIMELORD.
+Enables running multiple universes concurrently without port collisions.
+"""
+
+import os
+import platform
+import re
+import socket
+import sys
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Set
+
+# Keys to sanitize from snapshots for security
+SENSITIVE_KEY_PATTERNS = [
+ r"key",
+ r"secret",
+ r"token",
+ r"password",
+ r"auth",
+ r"private",
+ r"credential",
+]
+
+
+def is_sensitive(key: str) -> bool:
+ key_lower = key.lower()
+ return any(
+ re.search(pat, key_lower) for pat in SENSITIVE_KEY_PATTERNS
+ )
+
+
+def get_system_metadata() -> Dict[str, Any]:
+ """Captures system runtime metadata (Python, OS, host)."""
+ node_version = None
+ try:
+ import subprocess
+
+ res = subprocess.run(["node", "--version"], capture_output=True, text=True)
+ if res.returncode == 0:
+ node_version = res.stdout.strip()
+ except Exception:
+ pass
+
+ return {
+ "os": platform.system(),
+ "os_release": platform.release(),
+ "arch": platform.machine(),
+ "python_version": sys.version.split()[0],
+ "node_version": node_version,
+ }
+
+
+def get_safe_env_vars() -> Dict[str, str]:
+ """Returns safe, non-sensitive environment variables for temporal capture."""
+ safe_vars = {}
+ important_vars = {
+ "PATH",
+ "VIRTUAL_ENV",
+ "NODE_ENV",
+ "PYTHONPATH",
+ "PORT",
+ "HOST",
+ "SHELL",
+ "EDITOR",
+ "TIMELORD_UNIVERSE",
+ }
+
+ for key, value in os.environ.items():
+ if key in important_vars or not is_sensitive(key):
+ # Limit length to avoid bloating
+ if len(value) < 1024:
+ safe_vars[key] = value
+
+ return safe_vars
+
+
+def detect_configured_ports(project_dir: Path) -> List[int]:
+ """Scans .env, package.json, and docker-compose for configured ports."""
+ ports: Set[int] = set()
+
+ # Check .env files
+ for env_name in [".env", ".env.local", ".env.development"]:
+ env_file = project_dir / env_name
+ if env_file.is_file():
+ try:
+ content = env_file.read_text(encoding="utf-8", errors="ignore")
+ for match in re.finditer(r"PORT\s*=\s*(\d+)", content, re.IGNORECASE):
+ ports.add(int(match.group(1)))
+ except Exception:
+ pass
+
+ # Check package.json scripts (e.g. -p 3000, --port 3000)
+ pkg_file = project_dir / "package.json"
+ if pkg_file.is_file():
+ try:
+ content = pkg_file.read_text(encoding="utf-8", errors="ignore")
+ for match in re.finditer(r"(?:--port|-p)\s+(\d+)", content):
+ ports.add(int(match.group(1)))
+ except Exception:
+ pass
+
+ return sorted(list(ports))
+
+
+def is_port_in_use(port: int, host: str = "127.0.0.1") -> bool:
+ """Checks if a TCP port is currently open and bound."""
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(0.5)
+ return s.connect_ex((host, port)) == 0
+
+
+def patch_env_ports_in_universe(universe_dir: Path, port_offset: int) -> Dict[str, int]:
+ """
+ Adjusts PORT definitions in universe .env files by the given offset
+ so parallel universe dev servers do not conflict with Prime.
+ """
+ remapped = {}
+ for env_name in [".env", ".env.local", ".env.development"]:
+ env_file = universe_dir / env_name
+ if not env_file.is_file():
+ continue
+
+ try:
+ content = env_file.read_text(encoding="utf-8", errors="ignore")
+ new_lines = []
+ for line in content.splitlines():
+ match = re.match(r"^(\s*PORT\s*=\s*)(\d+)(.*)$", line, re.IGNORECASE)
+ if match:
+ prefix, old_port_str, suffix = match.groups()
+ old_port = int(old_port_str)
+ new_port = old_port + port_offset
+ remapped[f"{env_name}:PORT"] = new_port
+ new_lines.append(f"{prefix}{new_port}{suffix}")
+ else:
+ new_lines.append(line)
+
+ env_file.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
+ except Exception:
+ pass
+
+ return remapped
diff --git a/timelord/utils/git_helper.py b/timelord/utils/git_helper.py
new file mode 100644
index 0000000..94c23ec
--- /dev/null
+++ b/timelord/utils/git_helper.py
@@ -0,0 +1,101 @@
+"""
+Git inspection and integration helpers for TIMELORD.
+Safe against non-git directories.
+"""
+
+import subprocess
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+
+def is_git_repository(path: Path) -> bool:
+ try:
+ res = subprocess.run(
+ ["git", "-C", str(path), "rev-parse", "--is-inside-work-tree"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return res.returncode == 0 and res.stdout.strip() == "true"
+ except Exception:
+ return False
+
+
+def get_git_state(path: Path) -> Dict[str, Any]:
+ """Extracts git metadata: current branch, commit, dirty status, diff summaries."""
+ if not is_git_repository(path):
+ return {
+ "is_git": False,
+ "branch": None,
+ "head_sha": None,
+ "head_message": None,
+ "is_dirty": False,
+ "staged_files": [],
+ "unstaged_files": [],
+ "untracked_files": [],
+ "stash_count": 0,
+ }
+
+ def _run_git(args: List[str]) -> str:
+ res = subprocess.run(
+ ["git", "-C", str(path)] + args,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return res.stdout.strip() if res.returncode == 0 else ""
+
+ # Branch
+ branch = _run_git(["branch", "--show-current"])
+ if not branch:
+ branch = _run_git(["rev-parse", "--short", "HEAD"]) or "HEAD"
+
+ # HEAD commit
+ head_sha = _run_git(["rev-parse", "HEAD"])
+ head_msg = _run_git(["log", "-1", "--pretty=%B"])
+
+ # Status porcelein
+ status_raw = _run_git(["status", "--porcelain"])
+ staged = []
+ unstaged = []
+ untracked = []
+
+ for line in status_raw.splitlines():
+ if not line:
+ continue
+ code = line[:2]
+ filename = line[3:].strip()
+ if code[0] in ("M", "A", "D", "R", "C"):
+ staged.append(filename)
+ if code[1] in ("M", "D"):
+ unstaged.append(filename)
+ if code == "??":
+ untracked.append(filename)
+
+ # Stash count
+ stash_raw = _run_git(["stash", "list"])
+ stash_count = len(stash_raw.splitlines()) if stash_raw else 0
+
+ return {
+ "is_git": True,
+ "branch": branch,
+ "head_sha": head_sha[:8] if head_sha else None,
+ "head_sha_full": head_sha,
+ "head_message": head_msg.splitlines()[0] if head_msg else None,
+ "is_dirty": bool(staged or unstaged or untracked),
+ "staged_files": staged,
+ "unstaged_files": unstaged,
+ "untracked_files": untracked,
+ "stash_count": stash_count,
+ }
+
+
+def get_git_diff(path: Path, staged: bool = False) -> str:
+ """Returns the git diff for staged or unstaged changes."""
+ if not is_git_repository(path):
+ return ""
+ args = ["git", "-C", str(path), "diff"]
+ if staged:
+ args.append("--staged")
+ res = subprocess.run(args, capture_output=True, text=True, check=False)
+ return res.stdout if res.returncode == 0 else ""