# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-aaif-trust-anchor-that-attests-a-peer-identity-whose-attested-capability-set-silently-widened-between-att.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-aaif-trust-anchor-that-attests-a-peer-identity-whose-attested-capability-set-silently-widened-between-att.warrant.json
# Markdown SHA-256:   8a6b81877dac58b225ac616c5be9106cd62495a61e06334bd2a85682fe35f5d2
# Code AST SHA-256:   87468cc3708da642f2447a194b21c4c346bf70cb4600952136f283ed68faad12
# Verified Classes:   CapabilityExpansionUnreviewed, CanonicalizationMismatch, AnchorPin
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from hashlib import sha256
from typing import FrozenSet


class CapabilityExpansionUnreviewed(RuntimeError):
    """Raised when a presented attestation widens the pinned capability set
    without a recorded review. Fail-closed: do not execute the warrant."""


class CanonicalizationMismatch(RuntimeError):
    """Raised when the attestation's capability set cannot be canonicalized
    under the federation profile the pin was computed with."""


@dataclass(frozen=True)
class AnchorPin:
    identity: str
    issuer: str
    anchor_epoch: int
    capability_digest: str  # H(identity || sorted_caps || issuer || epoch)


def canonical_digest(identity: str, issuer: str, epoch: int,
                     capabilities: FrozenSet[str],
                     profile_version: str = "aaif-fed/1") -> str:
    if not capabilities:
        raise CanonicalizationMismatch("empty capability set is not canonical")
    # Profile fixes: lowercase, strip, sort, join with \x1f, version-prefixed.
    norm = "\x1f".join(sorted(c.strip().lower() for c in capabilities))
    payload = f"{profile_version}\x1e{identity}\x1e{issuer}\x1e{epoch}\x1e{norm}"
    return sha256(payload.encode("utf-8")).hexdigest()


def verify_warrant(pin: AnchorPin, presented_identity: str,
                   presented_issuer: str, presented_caps: FrozenSet[str],
                   presented_epoch: int, signature_valid: bool) -> None:
    if not signature_valid:
        raise CapabilityExpansionUnreviewed("signature chain invalid; halt")
    if presented_identity != pin.identity or presented_issuer != pin.issuer:
        raise CapabilityExpansionUnreviewed(
            f"identity/issuer drift: pin={pin.identity}@{pin.issuer} "
            f"presented={presented_identity}@{presented_issuer}")
    if presented_epoch != pin.anchor_epoch:
        raise CapabilityExpansionUnreviewed(
            f"anchor epoch bump {pin.anchor_epoch}->{presented_epoch}; "
            "requires re-anchoring review")

    presented_digest = canonical_digest(
        presented_identity, presented_issuer, presented_epoch, presented_caps)
    if presented_digest == pin.capability_digest:
        return  # exact match: cached policy is valid

    # Compute the delta to classify direction.
    pinned_caps = _caps_from_pin(pin)  # profile-defined reconstruction
    delta = presented_caps - pinned_caps
    if not delta:
        return  # narrowing: safe, but caller must prune cache
    raise CapabilityExpansionUnreviewed(
        f"capability expansion {sorted(delta)} not covered by pin "
        f"{pin.capability_digest[:12]}…; route to review before executing")
