# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-sandboxed-skill-has-silently-escaped-its-syscall-confinement-through-a-toctou-window-on-its-own-seccomp-filter.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-sandboxed-skill-has-silently-escaped-its-syscall-confinement-through-a-toctou-window-on-its-own-seccomp-filter.warrant.json
# Markdown SHA-256:   47c10040e1cc80741e86ae2d9b69dc41053cbfc16e827b442ae64a6a7c9fad03
# Code AST SHA-256:   eb47310d367b99e5cf45f8ff23dc0e78764b4fba32f8e5e3fb8ecd62510f4515
# Verified Classes:   SandboxConfinementError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import os
import signal
import subprocess

# A syscall the profile is expected to deny. Chosen because no legitimate
# skill capability needs it and its denial is unambiguous.
PROBE_SYSCALL = "socket"

class SandboxConfinementError(RuntimeError):
    """Raised when a skill process is not demonstrably confined by its seccomp filter."""
    pass

def launch_confined_skill(skill_path: str, profile_path: str) -> int:
    """
    Launch a skill under a seccomp profile and verify confinement from inside
    the executing process before any skill-controlled code runs.

    Ordering is load-bearing: fork -> install filter -> probe -> execve(skill).
    Any deviation (execve before probe, probe in parent, probe skipped) is a
    confinement failure, not a warning.
    """
    # The probe runs as the very first thing in the child, before execve.
    # It must observe EPERM for PROBE_SYSCALL; anything else means the filter
    # is not live in this PID.
    probe = (
        "import ctypes, errno, os, sys\n"
        "libc = ctypes.CDLL(None, use_errno=True)\n"
        "fd = libc.socket(2, 1, 0)\n"  # AF_INET, SOCK_STREAM
        "err = ctypes.get_errno()\n"
        "if fd != -1 or err != errno.EPERM:\n"
        "    sys.stderr.write(f'PROBE_FAIL fd={fd} errno={err}\\n')\n"
        "    sys.exit(97)\n"
        "sys.exit(0)\n"
    )

    # In a real runtime this is a fork + seccomp(TSYNC) + waitpid handshake.
    # The probe is executed in the same PID that will execve the skill.
    proc = subprocess.Popen(
        ["/usr/bin/python3", "-c", probe],
        preexec_fn=lambda: _install_seccomp(profile_path),
    )
    _, status = os.waitpid(proc.pid, 0)

    if os.WIFEXITED(status) and os.WEXITSTATUS(status) == 97:
        raise SandboxConfinementError(
            "seccomp probe did not observe EPERM; filter not live in executing PID. "
            "Likely causes: TSYNC did not cover this process, filter installed after "
            "execve, or skill installed its own filter first."
        )
    if not (os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0):
        raise SandboxConfinementError(
            f"confinement probe terminated abnormally: status={status}"
        )

    # Only now, with confinement proven in-band, exec the skill.
    return subprocess.call(["/usr/bin/python3", skill_path])


def _install_seccomp(profile_path: str) -> None:
    """Placeholder: prctl(NO_NEW_PRIVS) + seccomp(SET_MODE_FILTER, TSYNC, prog)."""
    raise SandboxConfinementError(
        "seccomp installation not wired; refusing to launch unconfined skill"
    )
