# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-capability-drift-after-a2a-v1-0-agent-card-re-resolution-the-capabilities-hash-mismatch-that-survives-schema-valid-ne.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-capability-drift-after-a2a-v1-0-agent-card-re-resolution-the-capabilities-hash-mismatch-that-survives-schema-valid-ne.warrant.json
# Markdown SHA-256:   f3d4e84fcbbd6c257c058dca40a64bc8972c45c533b2fac7b53f234d4aa25cd1
# Code AST SHA-256:   d90ba12b9201d96fafdd4d15c4fdecf6b8a1303bb5393062cdc52b932ddf9c7b
# Verified Classes:   CapabilityDriftError, CardProjection
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityDriftError(RuntimeError):
    """Raised when a re-resolved A2A Agent Card's capability projection
    differs from the projection the plan was compiled against, and the
    plan is not provably re-compilable."""


@dataclass(frozen=True)
class CardProjection:
    agent_id: str
    skill_ids: tuple[str, ...]
    input_modes: tuple[str, ...]
    output_modes: tuple[str, ...]
    tags: tuple[str, ...]
    streaming: bool
    push_notifications: bool

    def canonical_hash(self) -> str:
        payload = {
            "agent_id": self.agent_id,
            "skill_ids": sorted(self.skill_ids),
            "input_modes": sorted(self.input_modes),
            "output_modes": sorted(self.output_modes),
            "tags": sorted(self.tags),
            "streaming": self.streaming,
            "push_notifications": self.push_notifications,
        }
        blob = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
        return hashlib.sha256(blob).hexdigest()


def bind_subtask(
    plan_time_projection: CardProjection,
    bind_time_projection: CardProjection,
    plan_is_recompilable: bool,
) -> str:
    """Bind a sub-task to the current card surface, or fail closed.

    Returns the projection hash to stamp into the task envelope on success.
    """
    plan_hash = plan_time_projection.canonical_hash()
    bind_hash = bind_time_projection.canonical_hash()

    if plan_hash == bind_hash:
        return bind_hash

    if plan_is_recompilable:
        # Caller may re-derive the sub-task contract from the new surface.
        return bind_hash

    # Siblings already committed; the plan cannot absorb the drift.
    raise CapabilityDriftError(
        "capability projection drifted between plan and bind: "
        f"plan_hash={plan_hash[:12]} bind_hash={bind_hash[:12]} "
        f"streaming {plan_time_projection.streaming}->{bind_time_projection.streaming} "
        f"tags {plan_time_projection.tags}->{bind_time_projection.tags} "
        f"input_modes {plan_time_projection.input_modes}->{bind_time_projection.input_modes}"
    )


def classify_rpc_error(code: int) -> str:
    """Route JSON-RPC errors. -32601 is permanent method-unavailability,
    not a transient transport fault; it must reach the drift handler."""
    if code == -32601:
        return "capability_drift"
    if code in (-32603, -32000):
        return "transient"
    return "unclassified"
