# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-a-re-fetched-agent-card-as-a-new-negotiation-epoch-rather-than-a-cached-capability-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-a-re-fetched-agent-card-as-a-new-negotiation-epoch-rather-than-a-cached-capability-grant.warrant.json
# Markdown SHA-256:   a5224de2adf47573cf0bc6c23c99a6a26e96e1cf94cd79476d3f568fe51ea3e9
# Code AST SHA-256:   f1b17dcaef55205f313a6444c18882d1daf6508c3c6ab4a5ae4699074b33c8aa
# Verified Classes:   CardEpochDriftError, Task, Worker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class CardEpochDriftError(RuntimeError):
    """Raised when a task-scoped RPC references a task whose recorded
    AgentCard revision no longer matches the worker's current card.
    This is terminal for the task: the caller must re-negotiate."""


def card_revision(card: dict[str, Any]) -> str:
    # Canonical hash over the capability-bearing fields only; description
    # and display metadata are excluded so cosmetic churn does not trip
    # the gate. Auth schemes are included: rotation is epoch-bearing.
    binding = {
        "skills": card.get("skills"),
        "inputModes": card.get("inputModes"),
        "outputModes": card.get("outputModes"),
        "authentication": card.get("authentication"),
    }
    return hashlib.sha256(
        json.dumps(binding, sort_keys=True).encode()
    ).hexdigest()


@dataclass
class Task:
    id: str
    session_id: str
    recorded_revision: str
    status: str = "working"
    artifacts: list[dict[str, Any]] = field(default_factory=list)


class Worker:
    def __init__(self, card: dict[str, Any]) -> None:
        self.card = card
        self.tasks: dict[str, Task] = {}

    def accept_send(self, task_id: str, session_id: str) -> Task:
        # Bind the task to the card revision live at acceptance.
        task = Task(
            id=task_id,
            session_id=session_id,
            recorded_revision=card_revision(self.card),
        )
        self.tasks[task_id] = task
        return task

    def _admit_task_scoped(self, task_id: str) -> Task:
        task = self.tasks.get(task_id)
        if task is None:
            raise CardEpochDriftError(f"unknown task {task_id}")
        current = card_revision(self.card)
        if current != task.recorded_revision:
            # Terminal: do not serve, do not silently migrate.
            task.status = "failed"
            raise CardEpochDriftError(
                f"task {task_id} bound to card revision "
                f"{task.recorded_revision[:12]} but worker now serves "
                f"{current[:12]}; re-negotiate a fresh task"
            )
        return task

    def handle_get(self, task_id: str) -> Task:
        return self._admit_task_scoped(task_id)

    def handle_continuation(self, task_id: str, payload: dict[str, Any]) -> Task:
        task = self._admit_task_scoped(task_id)
        mode = payload.get("mode")
        if mode not in self.card.get("inputModes", []):
            raise CardEpochDriftError(
                f"payload mode {mode!r} not in current card inputModes"
            )
        task.artifacts.append({"mode": mode, "body": payload.get("body")})
        return task


if __name__ == "__main__":
    w = Worker({
        "skills": ["extract"],
        "inputModes": ["application/pdf"],
        "outputModes": ["application/json"],
        "authentication": {"schemes": ["bearer"]},
    })
    t1 = w.accept_send("T1", "S")

    # Canary redeploy narrows the card mid-task.
    w.card = {
        "skills": ["extract"],
        "inputModes": ["text/plain"],
        "outputModes": ["application/json"],
        "authentication": {"schemes": ["mtls"]},
    }

    try:
        w.handle_continuation("T1", {"mode": "application/pdf", "body": b"..."})
    except CardEpochDriftError as e:
        # Correct outcome: T1 is failed, caller re-negotiates T2.
        print(f"epoch drift caught: {e}")
        assert w.tasks["T1"].status == "failed"
