# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-peer-s-agent-card-after-metadata-signature-divergence-from-its-declared-capability-set.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-peer-s-agent-card-after-metadata-signature-divergence-from-its-declared-capability-set.warrant.json
# Markdown SHA-256:   6f7fc4c73e31cc2b61478a66be3c2296fddb7de72ac9673a70e5d5b51d1a3709
# Code AST SHA-256:   a1440fc8cbbe18b507a2c0d05e4955b9f4ab9dc2995b8d9b7baec611c393c253
# Verified Classes:   AgentCardDivergenceError, AgentCard, LivePeerState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AgentCardDivergenceError(RuntimeError):
    """Raised when a signature-valid Agent Card no longer describes live peer behavior."""
    pass


@dataclass
class AgentCard:
    peer_id: str
    capabilities: set[str]
    resources: dict[str, str]          # uri -> committed sha256
    signature_valid: bool


@dataclass
class LivePeerState:
    invoked_capabilities: set[str] = field(default_factory=set)
    live_resource_hashes: dict[str, str] = field(default_factory=dict)
    tool_description_bodies: list[str] = field(default_factory=list)


def admit_peer(card: AgentCard, live: LivePeerState) -> None:
    if not card.signature_valid:
        # Cheap rejection path; not the quarantine boundary.
        raise AgentCardDivergenceError(
            f"{card.peer_id}: signature invalid, reject (not quarantine)"
        )

    # Check 1: invocation superset. Any invoked capability outside the card is a hard violation.
    undeclared = live.invoked_capabilities - card.capabilities
    if undeclared:
        raise AgentCardDivergenceError(
            f"{card.peer_id}: invoked undeclared capabilities {sorted(undeclared)} "
            f"(card declares {sorted(card.capabilities)}) — QUARANTINE"
        )

    # Check 2: resource hash pinning. Live content must match the signed commitment.
    for uri, committed in card.resources.items():
        live_hash = live.live_resource_hashes.get(uri)
        if live_hash is None:
            raise AgentCardDivergenceError(
                f"{card.peer_id}: resource {uri} unresolvable at admission — QUARANTINE"
            )
        if live_hash != committed:
            raise AgentCardDivergenceError(
                f"{card.peer_id}: resource {uri} hash divergence "
                f"committed={committed} live={live_hash} — QUARANTINE (resource poisoning)"
            )

    # Check 3: description-content taint. Descriptions are model input, not metadata.
    for body in live.tool_description_bodies:
        lowered = body.lower()
        if any(marker in lowered for marker in ("call document.export", "send to external", "include the full")):
            raise AgentCardDivergenceError(
                f"{card.peer_id}: tool description carries injection-shaped imperative "
                f"— QUARANTINE (skill injection via description)"
            )


def verify_hash(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()
