# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-capability-grant-was-re-signed-under-a-weaker-trust-anchor-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-capability-grant-was-re-signed-under-a-weaker-trust-anchor-mid-session.warrant.json
# Markdown SHA-256:   08c5bc7edad095db1838f76ad23d6d6f13352e39b5b873652c8333f3f7bfff42
# Code AST SHA-256:   71ee73265b0ddc5a0d8448958b0a865711b06d1c79df89649b638f28aa90d225
# Verified Classes:   TrustAnchorDowngradeError, PinnedContract, CapabilityEnvelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TrustAnchorDowngradeError(RuntimeError):
    """Raised when a re-signed capability envelope demotes its trust anchor
    below the tier pinned at negotiation time, even if claims are unchanged."""
    pass


@dataclass(frozen=True)
class PinnedContract:
    capability_id: str
    anchor_id: str
    anchor_tier: int
    claims_hash: str


@dataclass(frozen=True)
class CapabilityEnvelope:
    capability_id: str
    anchor_id: str
    anchor_tier: int
    claims_hash: str
    signature_valid: bool


TIER_ORDER = {"T1": 1, "T2": 2, "T3": 3}


def revalidate_envelope(pinned: PinnedContract, incoming: CapabilityEnvelope) -> PinnedContract:
    if not incoming.signature_valid:
        raise TrustAnchorDowngradeError(
            f"signature invalid for {incoming.capability_id}; hard stop"
        )
    if incoming.capability_id != pinned.capability_id:
        raise TrustAnchorDowngradeError(
            f"capability mismatch: pinned {pinned.capability_id}, got {incoming.capability_id}"
        )

    pinned_rank = TIER_ORDER.get(f"T{pinned.anchor_tier}", -1)
    incoming_rank = TIER_ORDER.get(f"T{incoming.anchor_tier}", -1)

    if incoming_rank < pinned_rank:
        # Claim-stable downgrade: the dangerous case. Claims may be byte-identical,
        # but the authority backing them is weaker than the plan assumed.
        raise TrustAnchorDowngradeError(
            f"anchor downgraded for {incoming.capability_id}: "
            f"pinned tier T{pinned.anchor_tier} (anchor {pinned.anchor_id}), "
            f"incoming tier T{incoming.anchor_tier} (anchor {incoming.anchor_id}); "
            f"claims_hash unchanged={incoming.claims_hash == pinned.claims_hash}. "
            f"Plan steps depending on the higher tier must be re-derived or aborted."
        )

    if incoming.anchor_id != pinned.anchor_id and incoming.anchor_id not in TRUSTED_ANCHORS:
        raise TrustAnchorDowngradeError(
            f"anchor rotated to untrusted id {incoming.anchor_id} for {incoming.capability_id}"
        )

    # Tier held or improved; claims must still match to be a true no-op.
    if incoming.claims_hash != pinned.claims_hash:
        raise TrustAnchorDowngradeError(
            f"claims mutated on refresh for {incoming.capability_id}; "
            f"re-negotiate rather than accept"
        )

    return PinnedContract(
        capability_id=incoming.capability_id,
        anchor_id=incoming.anchor_id,
        anchor_tier=incoming.anchor_tier,
        claims_hash=incoming.claims_hash,
    )


TRUSTED_ANCHORS = {"broker-key-2024", "broker-key-2025-soft"}
