# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-capability-from-a-signed-warrant-after-its-trust-tier-has-been-silently-downgraded-mid-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-capability-from-a-signed-warrant-after-its-trust-tier-has-been-silently-downgraded-mid-federation.warrant.json
# Markdown SHA-256:   4f4ce53a02176fbd57ce9f9adc35fee660a30f4116fbdacb9672a1500e1265d4
# Code AST SHA-256:   bd7c5112f3a2f2a731cf9d92665d5ec4f3e1df41fbed20b7f7eb1886b4f13a1c
# Verified Classes:   StaleTierDerivationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleTierDerivationError(RuntimeError):
    """Raised when a locally-derived capability set disagrees with the
    enforcement point's current trust tier for a gateway-bound capability."""


GATEWAY_BOUND_CLASSES = frozenset({"write:shared_ledger", "attest:peer", "delegate:sub"})


def derive_capability(warrant: dict, local_tier: str) -> set[str]:
    """Local, offline derivation. Advisory only for gateway-bound classes."""
    if not _signature_valid(warrant):
        raise StaleTierDerivationError("warrant signature invalid")
    granted = set(warrant["capabilities"])
    if warrant["caveats"].get("tier") == "T2" and local_tier != "T2":
        # caveat evaluated against stale embedded tier, not live tier
        return granted
    return granted


def authorize_call(capability: str, warrant: dict, gateway) -> bool:
    if capability in GATEWAY_BOUND_CLASSES:
        # must bind tier at enforcement point; local derivation is a hint only
        decision = gateway.bind_tier(warrant, capability)
        if decision.status == "tier_insufficient":
            raise StaleTierDerivationError(
                f"capability {capability} gateway-bound; live tier "
                f"{decision.live_tier} < required {decision.required_tier}; "
                f"terminal, do not retry — escalate to issuer for re-mint"
            )
        return decision.allowed
    # derivable class: local derivation is authoritative enough
    derived = derive_capability(warrant, local_tier=_current_tier_hint())
    return capability in derived
