# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-escape-its-sandbox-the-moment-a-tool-s-seccomp-profile-is-inherited-across-an-execve-and-how-does-that-turn-an-egress-deny-into-a.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-escape-its-sandbox-the-moment-a-tool-s-seccomp-profile-is-inherited-across-an-execve-and-how-does-that-turn-an-egress-deny-into-a.warrant.json
# Markdown SHA-256:   1e26a353021b88e2f5f852de5d427706336734bae8f5fa55f73f3620d71cb811
# Code AST SHA-256:   127e3230de0bbb028043b441dba12c50d7ac23ad649b9e0587316327857cb0ae
# Verified Classes:   SandboxLineageEscape
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SandboxLineageEscape(RuntimeError):
    """Raised when a process in a tool's execve lineage has a looser
    effective confinement policy than the supervisor intended."""
    pass


def audit_lineage(lineage, supervisor_policy):
    """
    lineage: list of dicts, one per execve image, each with:
        - image: str (binary path)
        - seccomp_allows: set[str]  (syscalls the inherited filter permits)
        - userspace_enforced: set[str]  (axes re-established by wrapper in this image:
                                         'egress', 'secrets', 'fs')
    supervisor_policy: dict with:
        - required_denies: set[str]  (syscalls that must be denied)
        - required_axes: set[str]    (axes that must be enforced somewhere)
    """
    if not lineage:
        raise SandboxLineageEscape("empty lineage: no process to audit")

    for idx, image in enumerate(lineage):
        # Axis 1: seccomp completeness. If the filter permits a required-deny
        # syscall, this image relies on userspace enforcement.
        leaked = supervisor_policy["required_denies"] & image["seccomp_allows"]
        if leaked:
            # The filter is incomplete here; userspace must cover the gap.
            missing_axes = supervisor_policy["required_axes"] - image["userspace_enforced"]
            if missing_axes:
                raise SandboxLineageEscape(
                    f"lineage image {idx} ({image['image']}): seccomp permits "
                    f"{sorted(leaked)} but userspace does not enforce "
                    f"{sorted(missing_axes)}; wrapper was bypassed at execve"
                )
    return True


def run_tool_with_audit(supervisor, tool_entrypoint):
    lineage = supervisor.trace_execve_lineage(tool_entrypoint)
    try:
        audit_lineage(lineage, supervisor.policy)
    except SandboxLineageEscape as e:
        supervisor.quarantine(tool_entrypoint)
        raise SandboxLineageEscape(
            f"refusing to execute {tool_entrypoint}: {e}"
        ) from e
    return supervisor.exec(tool_entrypoint)
