# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-agent-card-whose-signed-capability-manifest-is-valid-but-stale-the-a2a-v1-0-discovery-time-capability-drift-bounda.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-agent-card-whose-signed-capability-manifest-is-valid-but-stale-the-a2a-v1-0-discovery-time-capability-drift-bounda.warrant.json
# Markdown SHA-256:   d7016fb9a9570f7c6c940cbb73ea0fbcaec6de0144311a364778d5b00cd90061
# Code AST SHA-256:   2e131426011bcf5ed81cf9010427ce68d7b4dee2d27e9f216b68c81c7ee75826
# Verified Classes:   StaleManifestDelegationError, SignedManifest, CapabilityCache
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional


class StaleManifestDelegationError(RuntimeError):
    """Raised when a caller attempts to delegate against a manifest whose
    assertion is no longer admissible, or whose capability was observed absent."""


@dataclass(frozen=True)
class SignedManifest:
    agent_id: str
    manifest_digest: str
    issued_at: datetime
    ttl_seconds: int
    capabilities: frozenset[str]
    signature_valid: bool

    def assertion_expires_at(self) -> datetime:
        return self.issued_at + timedelta(seconds=self.ttl_seconds)


@dataclass
class CapabilityCache:
    entries: dict[tuple[str, str], SignedManifest]
    observed_absent: dict[str, set[str]]  # agent_id -> capabilities observed gone

    def resolve(self, agent_id: str) -> Optional[SignedManifest]:
        for (aid, _digest), manifest in self.entries.items():
            if aid == agent_id:
                return manifest
        return None

    def evict(self, agent_id: str, digest: str) -> None:
        self.entries.pop((agent_id, digest), None)


def delegate(
    cache: CapabilityCache,
    agent_id: str,
    required_capability: str,
    now: datetime,
    warrant_not_after: datetime,
) -> str:
    manifest = cache.resolve(agent_id)
    if manifest is None:
        raise StaleManifestDelegationError(
            f"no resolved manifest for {agent_id}; cannot delegate"
        )

    if not manifest.signature_valid:
        raise StaleManifestDelegationError(
            f"manifest {manifest.manifest_digest} for {agent_id} failed signature verification"
        )

    # Signature is valid -- but assertion freshness is a separate clock.
    if now > manifest.assertion_expires_at():
        raise StaleManifestDelegationError(
            f"manifest {manifest.manifest_digest} for {agent_id} expired at "
            f"{manifest.assertion_expires_at().isoformat()}, now={now.isoformat()}"
        )

    if now > warrant_not_after:
        raise StaleManifestDelegationError(
            f"capability warrant for {required_capability} expired at "
            f"{warrant_not_after.isoformat()}; re-negotiate before delegating"
        )

    if required_capability not in manifest.capabilities:
        raise StaleManifestDelegationError(
            f"{agent_id} manifest does not declare capability {required_capability}"
        )

    # Falsification hook: observation of absence overrides cryptographic assertion.
    if required_capability in cache.observed_absent.get(agent_id, set()):
        raise StaleManifestDelegationError(
            f"capability {required_capability} previously observed absent on {agent_id} "
            f"under manifest {manifest.manifest_digest}; awaiting re-issued manifest"
        )

    return f"delegated:{agent_id}:{required_capability}:{manifest.manifest_digest}"


def on_task_response(
    cache: CapabilityCache,
    agent_id: str,
    manifest_digest: str,
    required_capability: str,
    peer_error_code: str,
) -> None:
    """Task-time falsification: a capability_unavailable response invalidates
    the cached manifest for that capability, regardless of signature validity."""
    if peer_error_code == "capability_unavailable":
        cache.observed_absent.setdefault(agent_id, set()).add(required_capability)
        cache.evict(agent_id, manifest_digest)
        raise StaleManifestDelegationError(
            f"peer {agent_id} reported capability_unavailable for {required_capability} "
            f"under manifest {manifest_digest}; cache evicted, delegation halted "
            f"until a manifest with later issued_at is resolved"
        )
