#!python
"""sandbroker-lock - panic kill-switch (C8).

Clears EVERY session binding, pending request, and approval signal in sandbroker.
After this, every confirm-tier vault requires a fresh biometric approval again.
Use on suspected compromise or when you want to hard-reset all sessions.

Reaches the daemon over the DIRECT socket (not the bridge), so the sandboxed
agent cannot invoke it; the human runs it. Needs the claude-broker group -- run
under `sg claude-broker` if your shell predates the group grant.

    sandbroker-lock
"""
import json
import os
import socket
import sys

SOCKET_PATH = os.environ.get("SANDBROKER_SOCKET") or os.path.join(os.environ.get("SANDBROKER_BASE", "/opt/sandbroker"), "run", "sandbroker.sock")


def main() -> int:
    try:
        conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        conn.settimeout(5)
        conn.connect(SOCKET_PATH)
        conn.sendall((json.dumps({"action": "lock"}) + "\n").encode("utf-8"))
        buf = b""
        while b"\n" not in buf:
            chunk = conn.recv(4096)
            if not chunk:
                break
            buf += chunk
        conn.close()
    except OSError as exc:
        sys.stderr.write("sandbroker-lock: cannot reach daemon: %s\n" % exc)
        return 2
    resp = json.loads(buf.decode("utf-8", "replace").strip() or "{}")
    if resp.get("ok"):
        print("sandbroker locked: all sessions and pending approvals cleared.")
        return 0
    sys.stderr.write("sandbroker-lock: unexpected reply: %s\n" % resp)
    return 1


if __name__ == "__main__":
    sys.exit(main())
