# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-silent-capability-contract-drift-in-a2a-v1-0-agent-card-discovery-across-vendor-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-silent-capability-contract-drift-in-a2a-v1-0-agent-card-discovery-across-vendor-boundaries.warrant.json
# Markdown SHA-256:   d3786d5b59effbd0f5285e2a5c9da27dd86373f4ab04c25e8cad3675b707db23
# Code AST SHA-256:   e8247268ca5804f86babfec002b7b50c1398a3e1ebe1a8b041ec7f5410152d4d
# Verified Classes:   ContractDriftError, PinnedContract, TaskRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ContractDriftError(RuntimeError):
    """Raised when an A2A input-required follow-up requires paths outside the
    contract pinned at task-accept time, or when the remote's agent-level
    version changed mid-flight. Non-retryable; requires renegotiation."""

    def __init__(self, task_id: str, skill_id: str, pinned_version: str,
                 observed_version: str | None, missing_paths: list[str]):
        self.task_id = task_id
        self.skill_id = skill_id
        self.pinned_version = pinned_version
        self.observed_version = observed_version
        self.missing_paths = missing_paths
        super().__init__(
            f"contract drift on task {task_id} skill {skill_id}: "
            f"pinned={pinned_version} observed={observed_version} "
            f"undeclared_required_paths={missing_paths}"
        )


@dataclass
class PinnedContract:
    skill_id: str
    agent_version: str
    declared_paths: frozenset[str]   # dotted paths the client may supply
    contract_hash: str

    @classmethod
    def from_card(cls, card: dict[str, Any], skill_id: str) -> "PinnedContract":
        skill = next(s for s in card["skills"] if s["id"] == skill_id)
        # Client-side schema of the skill's argument surface. In a real client
        # this is the JSON Schema it validated its own payload against.
        declared = frozenset(skill.get("argumentPaths", []))
        blob = json.dumps({"skill": skill_id, "paths": sorted(declared)},
                          sort_keys=True).encode()
        return cls(
            skill_id=skill_id,
            agent_version=card["version"],
            declared_paths=declared,
            contract_hash=hashlib.sha256(blob).hexdigest(),
        )


@dataclass
class TaskRecord:
    task_id: str
    pinned: PinnedContract
    history: list[dict[str, Any]] = field(default_factory=list)


def handle_input_required(task: TaskRecord, followup: dict[str, Any],
                          current_card_version: str | None) -> None:
    """Enforce the pinned-contract invariant on an input-required follow-up."""
    # 1. Version superset signal: any change is drift, even if paths validate.
    if current_card_version is not None and \
            current_card_version != task.pinned.agent_version:
        raise ContractDriftError(
            task.task_id, task.pinned.skill_id, task.pinned.agent_version,
            current_card_version, missing_paths=[],
        )

    # 2. Sharp signal: required paths must be subset of pinned declared paths.
    required = set(followup.get("requiredPaths", []))
    undeclared = sorted(required - task.pinned.declared_paths)
    if undeclared:
        raise ContractDriftError(
            task.task_id, task.pinned.skill_id, task.pinned.agent_version,
            current_card_version, missing_paths=undeclared,
        )

    # Invariant holds: normal follow-up, satisfy and continue.
    task.history.append({"event": "input-required-satisfied",
                         "paths": sorted(required),
                         "contract_hash": task.pinned.contract_hash})
