# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-capability-grant-when-residency-attestations-arrive-after-tool-call-dispatch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-capability-grant-when-residency-attestations-arrive-after-tool-call-dispatch.warrant.json
# Markdown SHA-256:   ddb09e1137fb77b3b05650e511667056b87ed58c74a2409f4f7c9972d5ed2e0f
# Code AST SHA-256:   b3d7d4ec6a75b04e44a3786f1f07d1ccdf5470732757a2aa7b17c6f847cb33aa
# Verified Classes:   ResidencyViolation, SideEffectClass, Attestation, CapabilityGrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ResidencyViolation(RuntimeError):
    """Raised when a federated tool dispatch would commit a side effect
    under an attestation that is not causally prior to the commit."""


class SideEffectClass(Enum):
    READ_ONLY = "read_only"
    WRITE = "write"


@dataclass(frozen=True)
class Attestation:
    region: str
    resolution_epoch: int
    issued_at: float
    signature_valid: bool


@dataclass(frozen=True)
class CapabilityGrant:
    handle: str
    expected_region: str
    side_effect: SideEffectClass
    cached_attestation: Attestation | None
    router_epoch: int
    ttl_seconds: float
    now: float


def gate_dispatch(grant: CapabilityGrant) -> str:
    """Decide allow/deny for a federated dispatch. Returns 'allow' or raises."""
    att = grant.cached_attestation

    if grant.side_effect is SideEffectClass.WRITE:
        # Write tools require pre-commit attestation bound to current epoch.
        if att is None:
            raise ResidencyViolation(
                f"write dispatch for {grant.handle} has no pre-commit attestation"
            )
        if not att.signature_valid:
            raise ResidencyViolation(
                f"attestation for {grant.handle} failed signature check"
            )
        if att.resolution_epoch != grant.router_epoch:
            raise ResidencyViolation(
                f"attestation epoch {att.resolution_epoch} != router epoch "
                f"{grant.router_epoch} for {grant.handle}; possible re-shard"
            )
        if att.region != grant.expected_region:
            raise ResidencyViolation(
                f"attestation region {att.region} != expected "
                f"{grant.expected_region} for {grant.handle}"
            )
        return "allow"

    # Read-only: cached attestation acceptable if unexpired and epoch-current.
    if att is None:
        raise ResidencyViolation(
            f"read dispatch for {grant.handle} has no attestation"
        )
    if grant.now - att.issued_at > grant.ttl_seconds:
        raise ResidencyViolation(
            f"attestation for {grant.handle} expired "
            f"({grant.now - att.issued_at:.0f}s > {grant.ttl_seconds:.0f}s)"
        )
    if att.resolution_epoch != grant.router_epoch:
        raise ResidencyViolation(
            f"stale-epoch read attestation for {grant.handle}; force re-attestation"
        )
    return "allow"
