# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-capability-grant-as-revoked-when-a-trust-broker-s-policy-translation-is-only-partially-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-capability-grant-as-revoked-when-a-trust-broker-s-policy-translation-is-only-partially-idempotent.warrant.json
# Markdown SHA-256:   50d9ffa56e341e92b113e4cb8e8dd8237c750b9cc0f31fc7458a8e4fec7423c1
# Code AST SHA-256:   ce875d316a47706c185dc1f48f979275a4ecedfce4136e769c1690f82bd55d65
# Verified Classes:   TranslationIntegrityError, FederatedGrant, GrantRefreshGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TranslationIntegrityError(RuntimeError):
    """Raised when a re-signed federated grant's semantic capability set
    drifts from the set the consumer was operating under, indicating a
    non-idempotent broker translation (T^-1 o T != identity)."""
    pass


@dataclass
class FederatedGrant:
    principal: str
    capabilities: frozenset
    signature: str
    ttl: int
    translation_fingerprint: str = ""
    _semantic_hash: str = field(init=False, repr=False)

    def __post_init__(self):
        # Order-independent, dialect-normalized hash of the SEMANTIC set,
        # not the grant bytes. This is the guardrail the agent must compare.
        normalized = "|".join(sorted(self.capabilities))
        self._semantic_hash = hashlib.sha256(normalized.encode()).hexdigest()

    @property
    def semantic_hash(self) -> str:
        return self._semantic_hash


class GrantRefreshGuard:
    """Enforces translation-monotonicity across re-signing cycles."""

    def __init__(self):
        self._last: dict[str, FederatedGrant] = {}

    def accept_refresh(self, grant: FederatedGrant) -> None:
        prior = self._last.get(grant.principal)
        if prior is None:
            self._last[grant.principal] = grant
            return

        if grant.semantic_hash == prior.semantic_hash:
            # Case 1: identical semantic set, new signature/TTL -> routine.
            self._last[grant.principal] = grant
            return

        lost = prior.capabilities - grant.capabilities
        gained = grant.capabilities - prior.capabilities

        if gained:
            # Case 3: widened authority not authorized by origin principal.
            raise TranslationIntegrityError(
                f"privilege amplification for {grant.principal}: "
                f"gained={sorted(gained)} via non-injective reverse translation"
            )

        if lost:
            # Case 2: partial revocation. Do NOT silently continue.
            raise TranslationIntegrityError(
                f"partial revocation for {grant.principal}: "
                f"lost={sorted(lost)}; halt in-flight steps and re-authorize"
            )

        raise TranslationIntegrityError(
            f"unclassified semantic drift for {grant.principal}"
        )

    def checkpoint_and_halt(self, grant: FederatedGrant, inflight_step: str) -> None:
        """Called when a partial revocation is detected mid-workflow."""
        if grant.semantic_hash not in {g.semantic_hash for g in self._last.values()}:
            raise TranslationIntegrityError(
                f"cannot resume {inflight_step}: authority set no longer "
                f"matches any accepted grant for {grant.principal}"
            )
