# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-ebpf-intercepted-tool-invocation-as-a-policy-boundary-rather-than-a-sandbox-guarantee.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-ebpf-intercepted-tool-invocation-as-a-policy-boundary-rather-than-a-sandbox-guarantee.warrant.json
# Markdown SHA-256:   072024d9c1c8dd7731df89c4c0059bb1ff82e2d646c3300b86cb2bcffef447bd
# Code AST SHA-256:   b936bd3b55af7698755c1b2797e114257c5b6d442534acd70dbd5e6a23e6f255
# Verified Classes:   PolicyBoundaryViolation, ToolPolicy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import os
import subprocess
from dataclasses import dataclass


class PolicyBoundaryViolation(RuntimeError):
    """Raised when an interceptor is treated as load-bearing but does not
    actually close over the process tree that will issue the syscall."""
    pass


@dataclass
class ToolPolicy:
    tool_name: str
    spawns_children: bool
    interceptor_attached: bool
    cgroup_closed_under_exec: bool
    denial_message_flattened: bool


def assert_interceptor_is_load_bearing(policy: ToolPolicy) -> None:
    # An interceptor is load-bearing only if it observes every process
    # that will issue the syscall, AND the denial leaks nothing to the model.
    if not policy.interceptor_attached:
        raise PolicyBoundaryViolation(
            f"tool {policy.tool_name!r}: no interceptor attached; "
            f"policy must be enforced in tool-argument space"
        )
    if policy.spawns_children and not policy.cgroup_closed_under_exec:
        raise PolicyBoundaryViolation(
            f"tool {policy.tool_name!r}: spawns children but cgroup is not "
            f"closed under execve/setns; interceptor is advisory, not enforcing. "
            f"Downgrade to tool-space allowlist before Popen."
        )
    if not policy.denial_message_flattened:
        raise PolicyBoundaryViolation(
            f"tool {policy.tool_name!r}: denial message is distinguishable from "
            f"generic tool error; model will use it as a policy-shape oracle. "
            f"Flatten denials before they enter the context window."
        )


def enforce_or_downgrade(policy: ToolPolicy, model_arg: str,
                         workspace_root: str) -> str:
    assert_interceptor_is_load_bearing(policy)
    # Tool-space pre-check runs on the model-emitted argument BEFORE any
    # normalization, because normalization is where intent and effect diverge.
    resolved = os.path.realpath(model_arg)
    if not resolved.startswith(os.path.realpath(workspace_root) + os.sep):
        # Flatten: do not echo the path or the reason back to the model.
        raise PolicyBoundaryViolation("tool failed")
    return resolved
