# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-the-revocation-gossip-horizon-has-been-crossed-in-byzantine-resilient-agent-federations.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-the-revocation-gossip-horizon-has-been-crossed-in-byzantine-resilient-agent-federations.warrant.json
# Markdown SHA-256:   80657ebbd235f0c77c67257df04f0e916c464b72e107b21e93f9df2220e3ece3
# Code AST SHA-256:   2a6a4cc906eb5afc3ba07c070562c0f318578ed5e78690450e657bb2c5e63b0a
# Verified Classes:   RevocationHorizonViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RevocationHorizonViolation(RuntimeError):
    """Raised when an agent attempts authorization while its local CRL view
    lags the federation's max-seen epoch beyond the certified gossip bound."""
    pass


def authorize_identity(
    identity_id: str,
    local_crl_epoch: int,
    max_seen_epoch: int,
    certified_delta_max: int,
    local_crl: dict,
) -> bool:
    # Freshness proof first: can we even trust the absence of a revocation entry?
    lag = max_seen_epoch - local_crl_epoch
    if lag > certified_delta_max:
        raise RevocationHorizonViolation(
            f"local CRL epoch {local_crl_epoch} lags federation max {max_seen_epoch} "
            f"by {lag} > certified bound {certified_delta_max}; non-revocation for "
            f"{identity_id} cannot be certified — failing closed"
        )

    # Only now is a presence check meaningful.
    entry = local_crl.get(identity_id)
    if entry is not None and entry.get("epoch", 0) <= local_crl_epoch:
        return False  # identity is revoked at or before our (now-fresh) view
    return True


def guarded_delegate(
    identity_id: str,
    local_crl_epoch: int,
    max_seen_epoch: int,
    certified_delta_max: int,
    local_crl: dict,
) -> str:
    try:
        if not authorize_identity(
            identity_id, local_crl_epoch, max_seen_epoch, certified_delta_max, local_crl
        ):
            return f"denied: {identity_id} revoked"
    except RevocationHorizonViolation as exc:
        # Fail closed: refuse the delegation and surface the horizon breach.
        raise RevocationHorizonViolation(
            f"delegation to {identity_id} refused: {exc}"
        ) from exc
    return f"granted: {identity_id}"
