# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-capability-warrant-when-a-peer-re-registers-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-capability-warrant-when-a-peer-re-registers-mid-task.warrant.json
# Markdown SHA-256:   b356ca2664f05fc88194f06f0ba4f725706a408140ebefd06b9a45b45a56b6ec
# Code AST SHA-256:   9654af5b6fc27a37eefba8f0803262bc68a2721db0ade6764028c82774cb8190
# Verified Classes:   StaleWarrantError, AgentCard, TaskRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when a task's execution warrant no longer matches the card bound at creation."""
    pass


@dataclass(frozen=True)
class AgentCard:
    version: str
    skills: tuple[str, ...]
    raw: bytes

    def hash(self) -> str:
        return hashlib.sha256(self.raw).hexdigest()


@dataclass
class TaskRecord:
    task_id: str
    bound_card_hash: str          # pinned at creation, never mutated
    state: str = "submitted"
    artifact_card_hash: str | None = None


def assert_warrant_intact(task: TaskRecord, live_card: AgentCard) -> None:
    """Guard invoked on every terminal transition and on push-notification delivery."""
    if task.artifact_card_hash is None:
        raise StaleWarrantError(
            f"task {task.task_id} reached {task.state} with no artifact card hash; "
            "cannot verify warrant"
        )
    if task.artifact_card_hash != task.bound_card_hash:
        raise StaleWarrantError(
            f"task {task.task_id}: executed under card {task.artifact_card_hash[:12]} "
            f"but was bound to {task.bound_card_hash[:12]} at creation; "
            "output is conditionally invalid and must be quarantined"
        )
    if live_card.hash() != task.bound_card_hash:
        # Peer re-registered; task may still be valid if it honored the pin.
        # Surface as a warning-level signal, not a failure, but quarantine
        # any subsequent webhook deliveries keyed to the new scheme.
        raise StaleWarrantError(
            f"task {task.task_id}: live card {live_card.hash()[:12]} diverged from "
            f"bound {task.bound_card_hash[:12]}; webhook signature validation must "
            "use the bound card, not the live one"
        )


def quarantine_on_mismatch(task: TaskRecord, live_card: AgentCard) -> str:
    try:
        assert_warrant_intact(task, live_card)
    except StaleWarrantError as exc:
        task.state = "quarantined"
        return f"QUARANTINED: {exc}"
    task.state = "accepted"
    return "ACCEPTED"
