# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-federated-capability-attestation-whose-trust-broker-chain-has-re-rooted-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-federated-capability-attestation-whose-trust-broker-chain-has-re-rooted-mid-handoff.warrant.json
# Markdown SHA-256:   ce986d4a6f30e87401a78ad79c09ec557c221563c663968d6712e98082a524d2
# Code AST SHA-256:   7e14b15fb3eaf3783ae1fb5a021f676ed4dbfaa82a4d83b594c8dec9777a13ae
# Verified Classes:   FederatedAttestationError, Chain, CachedAttestation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class FederatedAttestationError(RuntimeError):
    """Raised when a federated capability attestation cannot be honored
    without splicing identity and scope across a trust-root boundary."""
    pass


@dataclass(frozen=True)
class Chain:
    root_id: str
    chain_digest: str
    granted_capabilities: frozenset
    continuity_from: Optional[str] = None  # retired root, if re-rooted
    continuity_scope_superset: bool = False


@dataclass(frozen=True)
class CachedAttestation:
    capability: str
    root_id: str
    chain_digest: str


def authorize_invocation(
    cached: CachedAttestation,
    presented: Chain,
    capability: str,
) -> bool:
    # Same root: re-verify digest, reuse scope only if chain unchanged.
    if presented.root_id == cached.root_id:
        if presented.chain_digest != cached.chain_digest:
            # Intermediate re-signed under same root: re-derive, don't splice.
            return capability in presented.granted_capabilities
        return capability in presented.granted_capabilities

    # Root changed. Honor only with valid continuity attestation AND
    # scope-superset guarantee for this specific capability.
    if (
        presented.continuity_from == cached.root_id
        and presented.continuity_scope_superset
        and capability in presented.granted_capabilities
    ):
        return True

    # Otherwise: refuse the splice. Re-derive scope from presented chain.
    if capability in presented.granted_capabilities:
        # Fresh derivation grants it under the new root: safe to proceed,
        # but the caller MUST re-pin to the new root.
        return True

    raise FederatedAttestationError(
        f"capability {capability!r} was granted under root {cached.root_id!r} "
        f"but presented chain is rooted at {presented.root_id!r} with no "
        f"continuity attestation covering scope-superset; refusing to splice "
        f"cached scope with new-chain identity"
    )
