#!/usr/bin/env python3 """Hash-gated bounded journals for existing, explicitly owned local LaunchAgents. Only stdout/stderr ownership changes. Arguments, environment, schedules, SSH trust and forwarding endpoints stay byte-for-byte equivalent after unwrapping. Previous declarations and journals are preserved for rollback and diagnosis. """ from __future__ import annotations import argparse import hashlib import json import os import plistlib import subprocess import time from pathlib import Path from manage_mission_core_launch_agent import _reload_launch_agent, _wait_for_health, _write_atomic from migrate_worker_tunnel_logs import reload_agent from k1link.launchd_logs import bounded_launchd_output, service_command, service_log_path LABELS = { "core": "com.nodedc.mission-core.local", "observatory": "com.nodedc.observatory-worker-tunnel.local", "gaussian": "com.nodedc.gaussian-pipeline-tunnel.local", "telemetry-startup": "com.nodedc.telemetry-startup.local", "telemetry-tunnel": "com.nodedc.telemetry-tunnel.local", "map": "com.nodedc.mission-core.map-gateway-link", } def digest(data): return hashlib.sha256(data).hexdigest() def plan(root, name, *, home=None): home = home or Path.home() root = root.resolve(strict=True) label = LABELS[name] agent = home / "Library/LaunchAgents" / f"{label}.plist" if agent.is_symlink() or not agent.is_file(): raise ValueError("Missing or unsafe existing LaunchAgent") before = agent.read_bytes() document = plistlib.loads(before) if document.get("Label") != label: raise ValueError("Foreign LaunchAgent") command = service_command(document) if name == "core": if document.get("WorkingDirectory") != str(root) or command[-2:] != ["k1link", "serve"]: raise ValueError("Unexpected canonical Core declaration") elif name == "telemetry-startup": if str(root / "scripts/manage_telemetry_startup.py") not in command: raise ValueError("Unexpected startup owner") elif command[0] != "/usr/bin/ssh": raise ValueError("Unexpected tunnel command") desired = bounded_launchd_output(document, root) assert service_command(desired) == command for key in set(document) | set(desired): if key not in {"ProgramArguments", "StandardOutPath", "StandardErrorPath"} and document.get( key ) != desired.get(key): raise ValueError("Service policy changed") payload = plistlib.dumps(desired, sort_keys=True) result = { "schema": "missioncore.runtime-log-policy/v1", "name": name, "label": label, "root": str(root), "agent": str(agent), "before_sha256": digest(before), "desired_sha256": digest(payload), "changed": before != payload, "journal": str(service_log_path(desired)), "max_bytes": 8388608, "backups": 4, "commands_and_environment_preserved": True, } return result, before, payload def accept(name, label): if name == "core": if not _wait_for_health(45): raise RuntimeError("Core health failed") return {"operational": True} target = f"gui/{os.getuid()}/{label}" previous = None stable = 0 for _ in range(15): result = subprocess.run( ["launchctl", "print", target], capture_output=True, text=True, timeout=5 ) state = result.stdout if name == "telemetry-startup" and "last exit code = 0" in state: return {"last_exit_code": 0} pid = next( (line.strip() for line in state.splitlines() if line.strip().startswith("pid = ")), None ) stable = stable + 1 if pid and pid == previous and "state = running" in state else 0 if stable >= 5: return {"stable_process": pid} previous = pid time.sleep(1) raise RuntimeError("LaunchAgent did not reach a stable accepted state") def apply(expected): current, before, payload = plan(Path(expected["root"]), expected["name"]) if current != expected: raise ValueError("Stale log policy plan") if not current["changed"]: return {**current, "applied": False} path = Path(current["agent"]) root = Path(current["root"]) backup = ( root / ".runtime/storage-maintenance/log-policy" / current["label"] / f"{current['before_sha256']}.plist" ) if backup.exists() and backup.read_bytes() != before: raise ValueError("Rollback identity collision") if not backup.exists(): _write_atomic(backup, before) _write_atomic(path, payload) try: if current["name"] == "core": _reload_launch_agent(path) else: reload_agent(path, current["label"]) proof = accept(current["name"], current["label"]) except BaseException: _write_atomic(path, before) if current["name"] == "core": _reload_launch_agent(path) else: reload_agent(path, current["label"]) accept(current["name"], current["label"]) raise receipt = { **current, "applied": True, "backup": str(backup), "accepted": proof, "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), } _write_atomic(backup.with_suffix(".receipt.json"), json.dumps(receipt, indent=2).encode()) return receipt def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("action", choices=["plan", "apply"]) p.add_argument("name", choices=LABELS) p.add_argument("--plan", type=Path) a = p.parse_args() if a.action == "plan": value = plan(Path(__file__).resolve().parents[1], a.name)[0] else: if not a.plan: p.error("apply requires --plan") expected = json.loads(a.plan.read_text()) if expected["name"] != a.name: p.error("plan owner does not match") value = apply(expected) print(json.dumps(value, indent=2)) if __name__ == "__main__": main()