# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-capability-scoped-syscall-broker-silently-widens-a-path-prefix-during-sandbox-re-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-capability-scoped-syscall-broker-silently-widens-a-path-prefix-during-sandbox-re-entry.warrant.json
# Markdown SHA-256:   a88a1cdd431da1ce1b9b309d1a78fc0390d8f47124062e0d2a91f641307134ea
# Code AST SHA-256:   49261764fcbffd97674a719e32d1815d2e750a74a749ec2e61a6c2efe00894fb
# Verified Classes:   CapabilityDenotationDrift, CapabilityToken, ResolvedIdentity
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import os
from dataclasses import dataclass


class CapabilityDenotationDrift(RuntimeError):
    """Raised when a capability's granted prefix no longer denotes the same inode subtree."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    op: str
    prefix: str
    dev: int
    ino: int
    epoch: int


@dataclass(frozen=True)
class ResolvedIdentity:
    dev: int
    ino: int
    canonical_path: str


def resolve_prefix(prefix: str) -> ResolvedIdentity:
    real = os.path.realpath(prefix)
    st = os.stat(real)
    return ResolvedIdentity(dev=st.st_dev, ino=st.st_ino, canonical_path=real)


def verify_capability_on_reentry(token: CapabilityToken) -> ResolvedIdentity:
    """Called by the broker on every sandbox re-entry. Fail-closed on drift."""
    current = resolve_prefix(token.prefix)
    if (current.dev, current.ino) != (token.dev, token.ino):
        raise CapabilityDenotationDrift(
            f"capability prefix {token.prefix!r} (epoch {token.epoch}) resolved to "
            f"(dev={current.dev}, ino={current.ino}) but was granted for "
            f"(dev={token.dev}, ino={token.ino}); canonical path now "
            f"{current.canonical_path!r}. Revoke and require re-grant before any "
            f"further mutation."
        )
    return current


def reconcile_checkpoint(
    logical_path: str,
    checkpoint_identity: dict[str, ResolvedIdentity],
    observed: ResolvedIdentity,
) -> None:
    """Agent-side resume check. Halt on identity mismatch for the same logical path."""
    recorded = checkpoint_identity.get(logical_path)
    if recorded is None:
        return
    if (recorded.dev, recorded.ino) != (observed.dev, observed.ino):
        raise CapabilityDenotationDrift(
            f"logical path {logical_path!r} recorded as "
            f"(dev={recorded.dev}, ino={recorded.ino}) at checkpoint but now resolves to "
            f"(dev={observed.dev}, ino={observed.ino}) at {observed.canonical_path!r}. "
            f"Refusing to retry; write may have landed in a widened subtree."
        )
