# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-contract-against-a-peer-whose-declared-schema-drifts-between-the-handshake-and-the-first-invocat.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-contract-against-a-peer-whose-declared-schema-drifts-between-the-handshake-and-the-first-invocat.warrant.json
# Markdown SHA-256:   e83fcdb38c06da6247f31fe87f12f212cb7f54a8ef005d9608bb515e6a472be8
# Code AST SHA-256:   f409972c5e42a1940e13f529de834f8d4b41b512c37831051e57cf519d83dd39
# Verified Classes:   ContractUnsoundError, Manifest, Contract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ContractUnsoundError(RuntimeError):
    """Raised when a synthesized A2A contract cannot be shown to hold at invocation time."""
    pass


@dataclass(frozen=True)
class Manifest:
    capability: str
    max_input_tokens: int
    p95_latency_ms: int
    attests_content_integrity: bool

    def version_hash(self) -> str:
        blob = f"{self.capability}|{self.max_input_tokens}|{self.p95_latency_ms}|{self.attests_content_integrity}"
        return hashlib.sha256(blob.encode()).hexdigest()[:16]


@dataclass(frozen=True)
class Contract:
    bound_manifest_hash: str
    max_input_tokens: int
    p95_latency_ms: int
    content_integrity_attested: bool


def synthesize_contract(manifest: Manifest) -> Contract:
    return Contract(
        bound_manifest_hash=manifest.version_hash(),
        max_input_tokens=manifest.max_input_tokens,
        p95_latency_ms=manifest.p95_latency_ms,
        content_integrity_attested=manifest.attests_content_integrity,
    )


def verify_before_invoke(contract: Contract, live_manifest: Manifest, batch_tokens: int) -> None:
    """Gate every invocation: reject if the contract has drifted from the live manifest,
    or if the task cannot be verified post-hoc and the peer degrades silently."""
    if live_manifest.version_hash() != contract.bound_manifest_hash:
        raise ContractUnsoundError(
            f"manifest drift: contract bound to {contract.bound_manifest_hash}, "
            f"live manifest is {live_manifest.version_hash()}"
        )
    if batch_tokens > live_manifest.max_input_tokens:
        raise ContractUnsoundError(
            f"batch of {batch_tokens} tokens exceeds live ceiling {live_manifest.max_input_tokens}; "
            "peer would truncate silently"
        )
    if not contract.content_integrity_attested:
        raise ContractUnsoundError(
            "peer does not attest content integrity and degrades silently; "
            "post-hoc verification cannot detect truncation — refuse trust-and-verify routing"
        )


def route_batch(contract: Contract, live_manifest: Manifest, batch_tokens: int) -> str:
    verify_before_invoke(contract, live_manifest, batch_tokens)
    return "dispatched"
