# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-trust-anchor-divergence-during-bilateral-capability-attestation-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-trust-anchor-divergence-during-bilateral-capability-attestation-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   ca60968992608538d96bd83490c2bc9292b31a940d21b0afd34d44e5821a5a4b
# Code AST SHA-256:   f353185910d26c1e7b4871fd089fc98a324ed21612035e5a1ffd2d6d6f8132ce
# Verified Classes:   TrustBoundaryError, FailureClass, CapabilityManifest, CachedGrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class TrustBoundaryError(RuntimeError):
    """Raised when an instance cannot resolve peer trust state to a safe action."""


class FailureClass(Enum):
    ANCHOR_CONTINUITY_GAP = "anchor_continuity_gap"
    UNTRUSTED_SIGNER = "untrusted_signer"
    REVOKED_OR_EXPIRED = "revoked_or_expired"


@dataclass(frozen=True)
class CapabilityManifest:
    manifest_id: str
    signer_kid: str
    epoch: int
    cross_signed_by: str | None      # kid of a currently-pinned anchor, if any
    revoked: bool
    declared_rotation_window_epochs: int


@dataclass(frozen=True)
class CachedGrant:
    capability: str
    signed_epoch: int
    ttl_seconds_remaining: int


def classify_verification_failure(
    manifest: CapabilityManifest,
    pinned_anchor_kids: set[str],
    peer_last_confirmed_epoch: int,
) -> FailureClass:
    if manifest.revoked:
        return FailureClass.REVOKED_OR_EXPIRED

    if manifest.signer_kid in pinned_anchor_kids:
        # Not a failure at all; caller should not reach here.
        raise TrustBoundaryError(
            f"manifest {manifest.manifest_id} signer is pinned; no divergence to classify"
        )

    epoch_delta = manifest.epoch - peer_last_confirmed_epoch
    chain_ok = (
        manifest.cross_signed_by is not None
        and manifest.cross_signed_by in pinned_anchor_kids
    )
    within_window = 0 < epoch_delta <= manifest.declared_rotation_window_epochs

    if chain_ok and within_window:
        return FailureClass.ANCHOR_CONTINUITY_GAP
    return FailureClass.UNTRUSTED_SIGNER


def resolve_delegation(
    manifest: CapabilityManifest,
    pinned_anchor_kids: set[str],
    peer_last_confirmed_epoch: int,
    cached_grant: CachedGrant | None,
) -> str:
    failure = classify_verification_failure(
        manifest, pinned_anchor_kids, peer_last_confirmed_epoch
    )

    if failure is FailureClass.ANCHOR_CONTINUITY_GAP:
        # Hold delegation, refresh anchor over old-root-authenticated channel.
        # Critically: refuse to fall back to a cached grant here.
        if cached_grant is not None:
            if cached_grant.signed_epoch < peer_last_confirmed_epoch:
                raise TrustBoundaryError(
                    f"refusing stale cached grant for {cached_grant.capability} "
                    f"(epoch {cached_grant.signed_epoch} < peer epoch "
                    f"{peer_last_confirmed_epoch}) during anchor-continuity gap on "
                    f"manifest {manifest.manifest_id}"
                )
        return "DELEGATION_SUSPENDED_REFRESH_ANCHOR"

    if failure is FailureClass.UNTRUSTED_SIGNER:
        raise TrustBoundaryError(
            f"hard reject: manifest {manifest.manifest_id} signed by unrecognized "
            f"kid {manifest.signer_kid} with no valid chain to a pinned anchor"
        )

    # REVOKED_OR_EXPIRED: evict cache, hard reject.
    raise TrustBoundaryError(
        f"hard reject: manifest {manifest.manifest_id} revoked or expired"
    )
