# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-verifiable-a2a-completion-attestation-whose-escrow-warrant-has-already-been-superseded-by-a-re-issued-task-revision.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-verifiable-a2a-completion-attestation-whose-escrow-warrant-has-already-been-superseded-by-a-re-issued-task-revision.warrant.json
# Markdown SHA-256:   864693cf3663bbd4175363d75afee27d7cb16bc4f78aaa31679784c5230b86c8
# Code AST SHA-256:   dc07e6b986904a3ce312096778f58fb67a7e46f2b7dc509ee370536730056181
# Verified Classes:   EscrowAttestationError, Escrow, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class EscrowAttestationError(RuntimeError):
    """Raised when a completion attestation cannot be bound to the live escrow."""


@dataclass(frozen=True)
class Escrow:
    escrow_id: str
    locked_revision: str
    locked_nonce: str
    state: str  # "LOCKED" | "SUPERSEDED" | "RELEASED"


@dataclass(frozen=True)
class Attestation:
    task_revision: str
    warrant_chain: tuple[str, ...]  # terminates at buyer escrow nonce
    payload_hash: str


def verify_and_release(escrow: Escrow, att: Attestation, artifact_hash: str) -> str:
    if escrow.state != "LOCKED":
        raise EscrowAttestationError(
            f"escrow {escrow.escrow_id} not releasable in state {escrow.state}"
        )
    if att.payload_hash != artifact_hash:
        raise EscrowAttestationError("payload hash mismatch")
    if att.task_revision != escrow.locked_revision:
        # Fail closed: stale-revision attestation is an orphan claim, not a release.
        raise EscrowAttestationError(
            f"STALE_REVISION: att={att.task_revision} escrow={escrow.locked_revision}; "
            "route to reconciliation, do not release"
        )
    if not att.warrant_chain or att.warrant_chain[-1] != escrow.locked_nonce:
        raise EscrowAttestationError(
            f"WARRANT_MISMATCH: chain tail={att.warrant_chain[-1:]!r} "
            f"escrow nonce={escrow.locked_nonce}"
        )
    return "RELEASED"
