# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-syscall-confinement-when-a-tool-call-re-enters-the-sandbox-via-a-cached-interpreter.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-syscall-confinement-when-a-tool-call-re-enters-the-sandbox-via-a-cached-interpreter.warrant.json
# Markdown SHA-256:   c707507dcd3124d3853c910370c64f0840709aa1ce15f5592da62696e7b6d263
# Code AST SHA-256:   7e04db8a0749b97dcf291a67c9a06b5a4fa8a755ce6f526453321532c03f4715
# Verified Classes:   ConfinementContinuityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import os
from pathlib import Path


class ConfinementContinuityError(RuntimeError):
    """Raised when a warm interpreter holds capabilities the next tool-call
    policy does not permit, so tightening the seccomp filter would not
    actually confine the next call."""


# Syscalls the strict "pure computation" profile is meant to allow.
STRICT_POLICY_ALLOW = frozenset({"read", "write", "close", "exit_group", "rt_sigreturn"})

# Capabilities that survive a seccomp filter tightening because they are
# established as kernel objects (mappings, fds), not as syscall entries.
DANGEROUS_FD_TARGETS = ("/memfd:", "/proc/self/mem", "/dev/mem", "anon_inode:[io_uring]",
                        "anon_inode:[userfaultfd]")


def enumerate_held_capabilities(pid: int = 0) -> dict:
    """Return the capability set the interpreter currently holds, independent
    of any seccomp filter that may be installed."""
    proc = Path(f"/proc/{pid}" if pid else "/proc/self")
    caps = {"exec_mappings": [], "dangerous_fds": [], "open_fds": []}

    for line in (proc / "maps").read_text().splitlines():
        parts = line.split()
        if len(parts) >= 6 and "x" in parts[1]:
            caps["exec_mappings"].append(parts[-1])

    fd_dir = proc / "fd"
    for fd in fd_dir.iterdir():
        try:
            target = os.readlink(fd)
        except OSError:
            continue
        caps["open_fds"].append(target)
        if any(target.startswith(t) for t in DANGEROUS_FD_TARGETS):
            caps["dangerous_fds"].append(target)

    return caps


def assert_confinement_continuity(next_policy_allow: frozenset,
                                  next_policy_permits_native_code: bool,
                                  pid: int = 0) -> None:
    """Enforce that tightening the filter for the next call actually confines it.

    A warm interpreter that holds an RWX mapping or a memfd/proc-mem fd can
    reach code execution without issuing any syscall the strict filter would
    block. In that case the filter is live but confinement is discontinuous,
    and the runtime must cold-fork instead.
    """
    caps = enumerate_held_capabilities(pid)

    if caps["dangerous_fds"]:
        raise ConfinementContinuityError(
            f"warm interpreter holds capability-bearing fds {caps['dangerous_fds']!r}; "
            f"seccomp filter tightening to {sorted(next_policy_allow)!r} cannot revoke them"
        )

    if caps["exec_mappings"] and not next_policy_permits_native_code:
        raise ConfinementContinuityError(
            f"warm interpreter holds executable mappings {caps['exec_mappings']!r} "
            f"but next policy forbids native code; filter liveness != confinement continuity"
        )

    # Capability set is within the next policy's allowance: warm reuse is sound.
    return None


def dispatch_tool_call(code: str, next_policy_allow: frozenset,
                       next_policy_permits_native_code: bool) -> str:
    try:
        assert_confinement_continuity(next_policy_allow, next_policy_permits_native_code)
    except ConfinementContinuityError:
        # Fail closed: cold fork, install filter before execve, reap after.
        return cold_fork_execute(code, next_policy_allow)
    return warm_execute(code, next_policy_allow)


def cold_fork_execute(code: str, policy_allow: frozenset) -> str:
    raise NotImplementedError("cold-fork path elided; installs seccomp before execve")


def warm_execute(code: str, policy_allow: frozenset) -> str:
    raise NotImplementedError("warm path elided; adds stricter filter to existing process")
