# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-task-authority-when-an-a2a-v1-0-agent-card-is-re-fetched-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-task-authority-when-an-a2a-v1-0-agent-card-is-re-fetched-mid-task.warrant.json
# Markdown SHA-256:   85441d933d3a05232804b6b6c99f68d0faf69a71b545928450ca5724339db67e
# Code AST SHA-256:   1cc2bfd125e9fd1e6fc72a266d767aebbc37377974b7c7e5717b6b839074eeb2
# Verified Classes:   DelegationBoundaryViolation, DelegationWarrant
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class DelegationBoundaryViolation(RuntimeError):
    """Raised when a live task's continuation authority no longer matches its submission-time warrant."""
    pass


# Fields on an A2A v1.0 agent card that gate whether an in-flight task may be continued.
# Descriptive fields (description, provider, documentationUrl) are deliberately excluded.
CONTINUATION_GATING_FIELDS = (
    "capabilities",
    "securitySchemes",
    "skills",          # narrowed to inputModes/outputModes/id at digest time
    "url",
)


def _canonical(obj: Any) -> str:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"))


def _gating_digest(card: dict) -> str:
    projected = {}
    for f in CONTINUATION_GATING_FIELDS:
        if f not in card:
            continue
        if f == "skills":
            projected[f] = [
                {"id": s.get("id"), "inputModes": s.get("inputModes"), "outputModes": s.get("outputModes")}
                for s in card.get("skills", [])
            ]
        else:
            projected[f] = card[f]
    return hashlib.sha256(_canonical(projected).encode()).hexdigest()


@dataclass(frozen=True)
class DelegationWarrant:
    task_id: str
    context_id: str
    card_snapshot_hash: str
    gating_field_digest: str
    credential_scope: tuple[str, ...] = field(default_factory=tuple)


def issue_warrant(task_id: str, context_id: str, card: dict, credential_scope: list[str]) -> DelegationWarrant:
    return DelegationWarrant(
        task_id=task_id,
        context_id=context_id,
        card_snapshot_hash=hashlib.sha256(_canonical(card).encode()).hexdigest(),
        gating_field_digest=_gating_digest(card),
        credential_scope=tuple(sorted(credential_scope)),
    )


def resume_task(warrant: DelegationWarrant, live_card: dict, task_state: str) -> str:
    """Validate continuation authority before resuming. Returns the task_id to resume against."""
    if task_state in ("completed", "failed", "canceled"):
        # Terminal states read from the task resource; card re-validation is irrelevant.
        return warrant.task_id

    live_digest = _gating_digest(live_card)
    if live_digest != warrant.gating_field_digest:
        # Do NOT resume, do NOT re-submit. Cancel the original and escalate.
        raise DelegationBoundaryViolation(
            f"continuation-gating fields changed for task {warrant.task_id} "
            f"(context {warrant.context_id}); warrant digest {warrant.gating_field_digest[:12]} "
            f"!= live digest {live_digest[:12]}. Cancel original, escalate, and use a fresh "
            f"contextId for any re-delegation to avoid remote state merge."
        )
    return warrant.task_id


# --- illustrative trace ---
if __name__ == "__main__":
    card_v1 = {
        "capabilities": {"streaming": True},
        "url": "https://remote.example/a2a",
        "securitySchemes": {"oauth2": {"scopes": ["tasks:write", "tasks:read"]}},
        "skills": [{"id": "invoice-reconcile", "inputModes": ["application/json", "text/plain"],
                    "outputModes": ["application/json"]}],
    }
    warrant = issue_warrant("task-7f3a", "ctx-91b2", card_v1, ["tasks:write", "tasks:read"])

    # Remote redeployed: write scope moved behind a new scheme; inputModes narrowed.
    card_v2 = {
        "capabilities": {"streaming": True},
        "url": "https://remote.example/a2a",
        "securitySchemes": {"oauth2_v2": {"scopes": ["tasks:read"]}},
        "skills": [{"id": "invoice-reconcile", "inputModes": ["application/json"],
                    "outputModes": ["application/json"]}],
    }

    try:
        resume_task(warrant, card_v2, task_state="working")
    except DelegationBoundaryViolation as e:
        print(f"BOUNDARY EVENT: {e}")
