# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-capability-attestation-whose-trust-anchor-chain-crosses-an-organization-boundary-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-capability-attestation-whose-trust-anchor-chain-crosses-an-organization-boundary-mid-handoff.warrant.json
# Markdown SHA-256:   64a238d94e75da8cbd5d052a634289e78b7873f939dfdf210965209ac9823ec9
# Code AST SHA-256:   eccac9bea5a86cac06f1a7f875910732886532b7c2ebdad3817270f33e359aa1
# Verified Classes:   UntrustedAnchorError, ScopeEscalationError, OrphanAttestationError, Attestation, Warrant, FederationVerifier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UntrustedAnchorError(RuntimeError):
    """Attestation chain terminates at an anchor not in the local federation trust store."""


class ScopeEscalationError(RuntimeError):
    """Attestation claims authority wider than the delegation warrant granted."""


class OrphanAttestationError(RuntimeError):
    """Attestation is not bound to an outstanding warrant for the current handoff."""


@dataclass
class Attestation:
    issuer: str
    terminal_anchor: str
    scope: frozenset
    warrant_id: Optional[str]
    signature_valid: bool


@dataclass
class Warrant:
    warrant_id: str
    counterparty_anchor: str
    scope: frozenset


@dataclass
class FederationVerifier:
    trust_store: frozenset
    outstanding_warrants: dict = field(default_factory=dict)

    def admit(self, att: Attestation) -> Warrant:
        # 1. Signature must verify (necessary, never sufficient).
        if not att.signature_valid:
            raise UntrustedAnchorError(f"signature invalid for issuer {att.issuer}")

        # 2. Anchor MEMBERSHIP, not merely anchor validity.
        if att.terminal_anchor not in self.trust_store:
            raise UntrustedAnchorError(
                f"anchor {att.terminal_anchor} verifies but is not federated locally"
            )

        # 3. Warrant binding: must answer a specific outstanding handoff.
        warrant = self.outstanding_warrants.get(att.warrant_id)
        if warrant is None:
            raise OrphanAttestationError(
                f"attestation {att.issuer} not bound to an outstanding warrant"
            )

        # 4. Anchor of attestation must match the anchor we federated for THIS warrant.
        if att.terminal_anchor != warrant.counterparty_anchor:
            raise UntrustedAnchorError(
                f"attestation anchor {att.terminal_anchor} != warrant anchor "
                f"{warrant.counterparty_anchor}"
            )

        # 5. Scope containment: may narrow, never widen.
        if not att.scope.issubset(warrant.scope):
            raise ScopeEscalationError(
                f"attestation scope {set(att.scope)} exceeds warrant scope {set(warrant.scope)}"
            )

        return warrant


def handle_handoff_result(verifier: FederationVerifier, att: Attestation) -> str:
    try:
        verifier.admit(att)
    except (UntrustedAnchorError, ScopeEscalationError, OrphanAttestationError) as e:
        # Fail closed: do NOT cache, do NOT re-present to policy.
        return f"REJECTED: {type(e).__name__}: {e}"
    return "ADMITTED: authority is local and warrant-bound"
