# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-re-signed-agent-card-mid-task-and-why-capability-attestation-freshness-cannot-be-inferred-from-signatu.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-re-signed-agent-card-mid-task-and-why-capability-attestation-freshness-cannot-be-inferred-from-signatu.warrant.json
# Markdown SHA-256:   bcd13e1b5afdf635fc8c577335e020703724741355fa11fb0238ed5c31f88423
# Code AST SHA-256:   837050b591c5e134615d32e3713dfffd340ffe670eae90246d4b4464a13c86a2
# Verified Classes:   AttestationEpochViolation, CapabilityRevoked, SchemaVersionMismatch, Lease, TaskState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class AttestationEpochViolation(RuntimeError):
    """Raised when a task transition would consume a capability whose
    attestation digest no longer matches the lease-bound digest."""
    pass


class CapabilityRevoked(AttestationEpochViolation):
    """Raised when the peer's current card drops a capability the task needs."""
    pass


class SchemaVersionMismatch(AttestationEpochViolation):
    """Raised when a peer response's schema_version differs from the request's,
    indicating silent skill fallthrough on the peer side."""
    pass


CAPABILITY_KEYS = ("skills", "modalities", "tool_grants", "schema_versions")


def capability_digest(card: dict) -> str:
    subset = {k: card.get(k, []) for k in CAPABILITY_KEYS}
    canonical = json.dumps(subset, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


@dataclass
class Lease:
    task_id: str
    bound_digest: str
    bound_epoch: int
    required_caps: dict = field(default_factory=dict)  # skill_id -> schema_version


@dataclass
class TaskState:
    lease: Lease
    status: str = "ACTIVE"


def validate_transition(state: TaskState, current_card: dict,
                        request_skill: str, request_schema: str,
                        response_schema: Optional[str] = None) -> None:
    """Called before every capability-consuming lifecycle transition.
    Raises on any attestation drift that invalidates the lease."""
    current_digest = capability_digest(current_card)
    current_epoch = current_card.get("attestation_epoch")

    if current_epoch is None:
        raise AttestationEpochViolation(
            f"task {state.lease.task_id}: peer card lacks attestation_epoch; "
            f"cannot establish monotonicity, refusing transition"
        )
    if current_epoch < state.lease.bound_epoch:
        raise AttestationEpochViolation(
            f"task {state.lease.task_id}: epoch regression "
            f"{current_epoch} < bound {state.lease.bound_epoch}"
        )

    if current_digest != state.lease.bound_digest:
        # Digest changed mid-task. Check whether remaining required caps survive.
        present = {(s["id"], s.get("schema_version"))
                   for s in current_card.get("skills", [])}
        for skill_id, schema in state.lease.required_caps.items():
            if (skill_id, schema) not in present:
                raise CapabilityRevoked(
                    f"task {state.lease.task_id}: capability {skill_id}@{schema} "
                    f"revoked at epoch {current_epoch} (bound {state.lease.bound_epoch}); "
                    f"task must SUSPEND, not continue"
                )
        # Superset: rebind to new digest/epoch.
        state.lease.bound_digest = current_digest
        state.lease.bound_epoch = current_epoch

    if request_skill not in {s["id"] for s in current_card.get("skills", [])}:
        raise CapabilityRevoked(
            f"task {state.lease.task_id}: requested skill {request_skill} "
            f"absent from current card"
        )

    if response_schema is not None and response_schema != request_schema:
        raise SchemaVersionMismatch(
            f"task {state.lease.task_id}: requested {request_skill}@{request_schema} "
            f"but peer responded with schema {response_schema}; "
            f"silent fallthrough detected"
        )
