# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-task-resumption-and-why-does-the-task-state-machine-silently-accept-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-task-resumption-and-why-does-the-task-state-machine-silently-accept-it.warrant.json
# Markdown SHA-256:   9bfdffd19588dff8ec26ef02abe4f0b4ca698bbafc0b5e4207199a73d594e8ab
# Code AST SHA-256:   d882ed4bfc23ab2c0c47bfd7858aa9e4a6b341a612b12b6eacf0fb2a62ead17c
# Verified Classes:   StaleAgentCardError, TaskRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class StaleAgentCardError(RuntimeError):
    """Raised when a task resumption is attempted against a card whose
    capabilities/skills have narrowed since task creation."""


@dataclass
class TaskRecord:
    task_id: str
    card_hash: str
    capabilities: dict[str, Any]
    skill_ids: set[str]
    state: str = "submitted"


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


def _narrowed(old: dict[str, Any], new: dict[str, Any]) -> list[str]:
    diffs = []
    for key, old_val in old.items():
        new_val = new.get(key)
        if old_val is True and new_val is not True:
            diffs.append(f"capability {key!r}: {old_val!r} -> {new_val!r}")
    return diffs


def resume_task(
    record: TaskRecord,
    fresh_card: dict[str, Any],
    resume_envelope_has_capability_call: bool,
    parked_seconds: float,
    cache_ttl_seconds: float = 3600.0,
) -> TaskRecord:
    """Fail-closed resumption. Returns a record advanced to 'working' only if
    the fresh card is provably not narrower than the card pinned at creation."""
    fresh_hash = canonical_hash(fresh_card)

    must_revalidate = (
        parked_seconds > cache_ttl_seconds
        or resume_envelope_has_capability_call
        or record.state != "working"
    )

    if not must_revalidate or fresh_hash == record.card_hash:
        record.state = "working"
        return record

    fresh_caps = fresh_card.get("capabilities", {})
    fresh_skills = {s["id"] for s in fresh_card.get("skills", []) if "id" in s}

    cap_diffs = _narrowed(record.capabilities, fresh_caps)
    lost_skills = record.skill_ids - fresh_skills

    if cap_diffs or lost_skills:
        raise StaleAgentCardError(
            f"task {record.task_id}: card hash {record.card_hash[:12]} -> "
            f"{fresh_hash[:12]}; narrowed capabilities={cap_diffs}, "
            f"lost_skills={sorted(lost_skills)}; refusing resume, parking "
            f"task as 'blocked' for operator review"
        )

    # Card changed but did not narrow: adopt the new hash and proceed.
    record.card_hash = fresh_hash
    record.capabilities = fresh_caps
    record.skill_ids = fresh_skills
    record.state = "working"
    return record


def handle_resume_rpc_error(record: TaskRecord, code: int, method: str) -> None:
    """A -32601/-32602 on a task-scoped sub-call during resume is a card
    invalidation signal, not a per-call error. Fail closed."""
    if code in (-32601, -32602):
        raise StaleAgentCardError(
            f"task {record.task_id}: method {method!r} rejected with {code} "
            f"during resume; card {record.card_hash[:12]} is stale, "
            f"re-fetch required before advancing state machine"
        )
