# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-trust-broker-s-re-attestation-as-a-revocation-event-during-cross-org-policy-renegotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-trust-broker-s-re-attestation-as-a-revocation-event-during-cross-org-policy-renegotiation.warrant.json
# Markdown SHA-256:   6d1fdbc2faca504331d85242cb2f935b38e6cea25be65ceae81a2efdcc50f627
# Code AST SHA-256:   b2fdc915d0c365c541329cb6f721dd6a4a12344226eddefa20b469eb8d907d15
# Verified Classes:   PolicyDigestTransitionError, UnauditableAttestationError, Attestation, GrantState, FederationGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class PolicyDigestTransitionError(RuntimeError):
    """Raised when a broker re-attestation changes the policy digest of an in-flight grant."""
    pass


class UnauditableAttestationError(RuntimeError):
    """Raised when an attestation's policy digest cannot be resolved to a policy document."""
    pass


@dataclass
class Attestation:
    broker_id: str
    subject: str
    task_id: str
    policy_digest: str
    not_before: int
    not_after: int
    signature_valid: bool


@dataclass
class GrantState:
    task_id: str
    original_policy_digest: str
    active_handles: set = field(default_factory=set)


class FederationGate:
    def __init__(self, policy_resolver):
        # policy_resolver: digest -> canonical policy document bytes, or None
        self._resolve = policy_resolver
        self._grants: dict[str, GrantState] = {}

    def register_grant(self, task_id: str, policy_digest: str) -> GrantState:
        gs = GrantState(task_id=task_id, original_policy_digest=policy_digest)
        self._grants[task_id] = gs
        return gs

    def admit_reattestation(self, att: Attestation, now: int) -> str:
        if not att.signature_valid:
            raise UnauditableAttestationError(
                f"attestation for {att.subject} on task {att.task_id} has invalid signature"
            )
        if not (att.not_before <= now <= att.not_after):
            raise UnauditableAttestationError(
                f"attestation for {att.subject} outside validity window"
            )
        if self._resolve(att.policy_digest) is None:
            raise UnauditableAttestationError(
                f"policy digest {att.policy_digest!r} does not resolve to a policy document"
            )

        gs = self._grants.get(att.task_id)
        if gs is None:
            self.register_grant(att.task_id, att.policy_digest)
            return "initial"

        if att.policy_digest == gs.original_policy_digest:
            # Same digest: pure window refresh, safe to apply in place.
            return "refresh"

        # Digest changed in either direction: this is a revocation event.
        # Invalidate every handle minted under the superseded digest before
        # the peer's next tool call is admitted, and force re-handshake.
        stale = gs.active_handles
        gs.active_handles = set()
        gs.original_policy_digest = att.policy_digest
        raise PolicyDigestTransitionError(
            f"broker {att.broker_id} re-attested {att.subject} on task {att.task_id} "
            f"under new policy digest {att.policy_digest!r}; "
            f"{len(stale)} in-flight handle(s) invalidated; re-handshake with "
            f"delegating principal required before further tool calls"
        )
