# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-ebpf-tool-interception-allowlist-as-a-continuity-invariant-rather-than-a-per-syscall-check.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-ebpf-tool-interception-allowlist-as-a-continuity-invariant-rather-than-a-per-syscall-check.warrant.json
# Markdown SHA-256:   c8c95334df6141fa64018bea78ddc6e8596c01404de3f63ea88ac9de8d6699ac
# Code AST SHA-256:   451de98ae37389f465bbd9249379ff97196c6697ab383e31db6080835dc5d561
# Verified Classes:   PolicyFenceViolation, Policy, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class PolicyFenceViolation(RuntimeError):
    """Raised when a checkpointed plan is resumed under a policy whose
    permitted-destination set is not a superset of the set in force when
    the plan was formed, for the same principal in the same enforcement
    domain. Resuming would allow a composition of individually-permitted
    syscalls that the plan's author never intended."""


@dataclass(frozen=True)
class Policy:
    version: str
    # Destinations permitted for a given principal in this enforcement domain.
    permitted: dict = field(default_factory=dict)

    def permitted_for(self, principal: str, domain: str) -> FrozenSet[str]:
        # Union across co-resident principals: the kernel sees the domain,
        # not the individual agent's plan.
        union = set()
        for (p, d), dests in self.permitted.items():
            if d == domain:
                union |= dests
        return frozenset(union)


@dataclass(frozen=True)
class Checkpoint:
    plan: tuple
    principal: str
    domain: str
    policy_version: str
    permitted_at_formation: FrozenSet[str]


def resume_checkpoint(cp: Checkpoint, current: Policy) -> tuple:
    if cp.policy_version == current.version:
        return cp.plan

    now = current.permitted_for(cp.principal, cp.domain)
    if not cp.permitted_at_formation.issubset(now):
        # Policy widened somewhere in the domain, or rotated in a way that
        # makes the old plan's assumptions unverifiable. Invalidate.
        raise PolicyFenceViolation(
            f"checkpoint formed under policy {cp.policy_version} "
            f"(permitted={sorted(cp.permitted_at_formation)}) is not "
            f"admissible under {current.version} "
            f"(permitted={sorted(now)}); re-plan required"
        )
    return cp.plan


def handle_tool_error(errno: int, cp: Checkpoint, current: Policy) -> tuple:
    if errno == 1:  # EPERM from a policy hook: terminal, no fallback search.
        raise PolicyFenceViolation(
            f"EPERM at syscall under policy {current.version}; "
            f"fallback search forbidden, plan {cp.plan} invalidated"
        )
    # ECONNREFUSED and friends may be transient; retry is permitted.
    return resume_checkpoint(cp, current)
