# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-signed-agent-card-s-capability-declaration-diverges-from-its-live-schema-at-handoff-time.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-signed-agent-card-s-capability-declaration-diverges-from-its-live-schema-at-handoff-time.warrant.json
# Markdown SHA-256:   25d2c490cbdb720517180287b8f9e3a61b67f6a65fe2c01fe656233b10fc0cbf
# Code AST SHA-256:   7ace1046ceae35578cbb14ab34400580729833cc265a9d9049c88b0c98deb360
# Verified Classes:   SchemaDivergenceError, AgentCard, Delegation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class SchemaDivergenceError(RuntimeError):
    """Raised when a signed Agent Card's declared schema diverges from the live schema at task time."""
    pass


@dataclass
class AgentCard:
    vendor: str
    schema_id: str            # the $id pointer, NOT a content hash
    schema_digest: str | None # optional sha256 of dereferenced schema, if vendor provides it
    signature_valid: bool


@dataclass
class Delegation:
    card: AgentCard
    task_id: str
    staged: dict[str, Any] = field(default_factory=dict)
    committed: bool = False


def digest_schema(schema: dict[str, Any]) -> str:
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def negotiate_and_validate(
    card: AgentCard,
    live_schema: dict[str, Any],
    payload: dict[str, Any],
    delegation: Delegation,
) -> None:
    if not card.signature_valid:
        raise SchemaDivergenceError(
            f"card signature invalid for vendor {card.vendor}; cannot proceed"
        )

    live_digest = digest_schema(live_schema)

    # Invariant: proceed only if the signed card binds the schema content by digest.
    if card.schema_digest is None:
        # Unverifiable at client. Must re-validate against live schema, not cache.
        if not _payload_matches(payload, live_schema):
            raise SchemaDivergenceError(
                f"vendor {card.vendor} schema {card.schema_id} has no digest in signed card "
                f"and live schema {live_digest[:12]} rejects payload; halting before commit"
            )
    elif card.schema_digest != live_digest:
        raise SchemaDivergenceError(
            f"signed digest {card.schema_digest[:12]} != live digest {live_digest[:12]} "
            f"for {card.vendor}; stale-schema divergence, halting"
        )

    # Only now may staged state be promoted.
    delegation.staged.clear()
    delegation.committed = True


def _payload_matches(payload: dict[str, Any], schema: dict[str, Any]) -> bool:
    required = set(schema.get("required", []))
    return required.issubset(payload.keys())
