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