"""Kill switch: DB flag OR the file $FPT_HOME/KILL. Checked by the node wrapper, egress, scheduler and RunManager. Engaging it also kills the AGENT-RUN child processes (Playwright trees, PDF rendering, script lint/dry-run). The mock app (and anything started by `fpt up`) is left running: it is the test pod, not an agent action.""" from __future__ import annotations from pathlib import Path from . import procs from .rundb import RunDB, now_iso class KillSwitchEngaged(RuntimeError): pass class KillSwitch: KEY = "kill_switch" def __init__(self, db: RunDB, home: Path, audit=None): self.db, self.file, self.audit = db, Path(home) / "KILL", audit def state(self) -> dict: s = self.db.kv_get(self.KEY, {}) or {} file_on = self.file.exists() engaged = bool(s.get("engaged")) or file_on reason = s.get("reason") if s.get("engaged") else ("KILL file present" if file_on else None) return {"engaged": engaged, "reason": reason, "actor": s.get("actor") if engaged else None, "since": s.get("since") if engaged else None, "file": file_on} def engaged(self) -> bool: return self.file.exists() or bool((self.db.kv_get(self.KEY, {}) or {}).get("engaged")) def engage(self, reason: str, actor: str) -> None: self.db.kv_set(self.KEY, {"engaged": True, "reason": reason, "actor": actor, "since": now_iso()}) killed = procs.kill_agent_processes() if self.audit: self.audit.append("kill.engaged", actor=actor, summary=reason, payload={"killed_pids": killed}) def release(self, actor: str) -> None: self.db.kv_set(self.KEY, {"engaged": False, "actor": actor, "since": now_iso()}) self.file.unlink(missing_ok=True) if self.audit: self.audit.append("kill.released", actor=actor) def check(self, where: str) -> None: if self.engaged(): raise KillSwitchEngaged(f"kill switch engaged (checked at {where})")