# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-escrow-warrant-divergence-when-a-dispute-resolution-agent-settles-against-a-stale-delivery-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-escrow-warrant-divergence-when-a-dispute-resolution-agent-settles-against-a-stale-delivery-attestation.warrant.json
# Markdown SHA-256:   d526b08bcaa15dd1b6e45d38fc5405b5d6f66b693953b226f9240ac8172aeb22
# Code AST SHA-256:   f38d31639f5f3acf40a716a508351c20726d2a83a364f8307f7584f31376e1b0
# Verified Classes:   SettlementLineageError, Attestation, Escrow
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SettlementLineageError(RuntimeError):
    """Raised when a DR agent is asked to settle against an attestation
    whose content_hash does not match the escrow's sealed expectation,
    or when a redelivered attestation contradicts an already-committed
    settlement for the same escrow."""


@dataclass(frozen=True)
class Attestation:
    escrow_id: str
    worker_id: str
    content_hash: str
    ts: int
    signature_valid: bool


@dataclass(frozen=True)
class Escrow:
    escrow_id: str
    expected_content_hash: str
    settled_hash: str | None = None


def release_escrow(escrow: Escrow, att: Attestation, now: int, max_age: int = 300) -> str:
    # 1. freshness + signature (necessary, not sufficient)
    if not att.signature_valid:
        raise SettlementLineageError(f"invalid signature on attestation for {escrow.escrow_id}")
    if now - att.ts > max_age:
        raise SettlementLineageError(f"stale attestation for {escrow.escrow_id}")

    # 2. lineage binding — the conjunct that is routinely omitted
    if att.content_hash != escrow.expected_content_hash:
        raise SettlementLineageError(
            f"attestation content_hash {att.content_hash!r} does not match "
            f"sealed expectation {escrow.expected_content_hash!r} for {escrow.escrow_id}"
        )

    # 3. redelivery of a superseded attestation is a contradiction, not a duplicate
    if escrow.settled_hash is not None and escrow.settled_hash != att.content_hash:
        raise SettlementLineageError(
            f"escrow {escrow.escrow_id} already settled against {escrow.settled_hash!r}; "
            f"redelivered attestation cites {att.content_hash!r} — audit-trail fork"
        )
    if escrow.settled_hash == att.content_hash:
        return "idempotent-noop"

    # commit content_hash into the settlement record
    return f"released:{escrow.escrow_id}:{att.content_hash}"
