# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-capability-negotiation-as-non-idempotent-across-agent-card-refreshes.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-capability-negotiation-as-non-idempotent-across-agent-card-refreshes.warrant.json
# Markdown SHA-256:   d421d6d3f88c9badff95a4080c444d3152f23be9484c1fa34b735cd113de0328
# Code AST SHA-256:   d354d8818aee285ed6e5267d46238e9cd9be851be1ed0ee5256eb97066bb57cc
# Verified Classes:   CapabilityContractDriftError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CapabilityContractDriftError(RuntimeError):
    """Raised when a refreshed AgentCard's advertised surface no longer
    matches the enforced surface inferred from task-failure error shapes."""
    pass


def resume_task_after_refresh(
    task_id: str,
    cached_contract: dict,
    refreshed_card: dict,
    last_task_error: str | None,
) -> dict:
    """Renegotiate before resuming a task across an AgentCard refresh.

    Returns the (possibly new) negotiated contract. Raises
    CapabilityContractDriftError if the refreshed card's advertised surface
    is stable but the enforced surface has drifted, as evidenced by a
    contract-shaped task failure.
    """
    CONTRACT_ERROR_PATTERNS = (
        "unsupported output mode",
        "unsupported input mode",
        "capability not supported",
        "interface not available",
    )

    advertised_hash = _hash_advertised(refreshed_card)
    cached_hash = cached_contract["advertised_hash"]

    if advertised_hash != cached_hash:
        # Advertised surface changed: renegotiate unconditionally.
        return _renegotiate(refreshed_card)

    if last_task_error and any(
        p in last_task_error.lower() for p in CONTRACT_ERROR_PATTERNS
    ):
        # Advertised surface is byte-identical, but the enforced surface
        # has drifted underneath us. The cache key is a lie.
        raise CapabilityContractDriftError(
            f"task {task_id}: advertised capabilities_hash={advertised_hash} "
            f"is stable but enforced surface drifted "
            f"(error={last_task_error!r}); renegotiation required before resume"
        )

    # No drift signal: safe to resume under the cached contract.
    return cached_contract


def _hash_advertised(card: dict) -> str:
    import hashlib, json
    surface = {
        "capabilities": card.get("capabilities"),
        "defaultInputModes": card.get("defaultInputModes"),
        "defaultOutputModes": card.get("defaultOutputModes"),
        "supportedInterfaces": card.get("supportedInterfaces"),
        "securitySchemes": card.get("securitySchemes"),
    }
    return hashlib.sha256(
        json.dumps(surface, sort_keys=True).encode()
    ).hexdigest()


def _renegotiate(card: dict) -> dict:
    # Placeholder: intersect coordinator and remote capabilities, select
    # output modes, and return a fresh contract with a new epoch.
    raise NotImplementedError
