# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-capability-negotiation-authority-when-a-federated-peer-rotates-its-attestation-key-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-capability-negotiation-authority-when-a-federated-peer-rotates-its-attestation-key-mid-session.warrant.json
# Markdown SHA-256:   984cd1be921f17703ac2ab4e0de106bb354900624fd019224666672d07d659fc
# Code AST SHA-256:   a084e3cc0b7b1b821d871561a80449088e21149b6856b8e20aaaa44a8ae18ee3
# Verified Classes:   WarrantEpochUnresolvable, ScopeReductionOnRetry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class WarrantEpochUnresolvable(RuntimeError):
    """Raised when an attestation names a warrant epoch the verifier cannot resolve."""
    pass


class ScopeReductionOnRetry(RuntimeError):
    """Raised when re-attestation would silently narrow the capability set."""
    pass


def verify_attestation(artifact, directory, current_warrant):
    """
    Verify an attested result artifact against a federation directory.

    artifact: dict with keys 'warrant_id', 'warrant_epoch', 'capability_set_hash', 'signature'
    directory: object exposing resolve_epoch(epoch) -> key_record or None
    current_warrant: the warrant the caller currently holds (may differ in epoch/scope)
    """
    named_epoch = artifact.get("warrant_epoch")
    if named_epoch is None:
        # Subject-resolved attestation is unsafe under rotation; refuse.
        raise WarrantEpochUnresolvable(
            f"artifact {artifact.get('warrant_id')} carries no warrant_epoch; "
            "cannot verify against append-only history"
        )

    key_record = directory.resolve_epoch(named_epoch)
    if key_record is None:
        # Do NOT collapse to STALE — that invites a scope-changing retry.
        raise WarrantEpochUnresolvable(
            f"warrant_epoch={named_epoch} not served by directory; "
            "fetch historical key or fail closed, do not renegotiate"
        )

    if not key_record.verifies(artifact["signature"]):
        raise WarrantEpochUnresolvable(
            f"signature invalid against epoch {named_epoch} key"
        )

    # Capability-set continuity check: re-attestation must not narrow scope.
    if current_warrant is not None:
        original_hash = artifact["capability_set_hash"]
        current_hash = current_warrant.capability_set_hash()
        if original_hash != current_hash:
            raise ScopeReductionOnRetry(
                f"artifact {artifact['warrant_id']} bound to capability_set_hash="
                f"{original_hash[:8]}, current warrant grants {current_hash[:8]}; "
                "re-attestation would silently drop capabilities — escalate to task owner"
            )

    return True
