# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-negotiate-a-peer-s-capability-warrant-when-a-federated-a2a-handoff-crosses-an-org-trust-boundary-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-negotiate-a-peer-s-capability-warrant-when-a-federated-a2a-handoff-crosses-an-org-trust-boundary-mid-task.warrant.json
# Markdown SHA-256:   7984ef6ababe21d03d0aafa271c755ae210a02fb59fe22372fcab174fad588c2
# Code AST SHA-256:   7a46c30d59f2dda30179e36beec99fd40793956ee4850103038ba2bd175cd6dc
# Verified Classes:   WarrantLineageError, Warrant, ReturnedValue, FederatedHandoff
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantLineageError(RuntimeError):
    """Raised when a returned value is consumed under a warrant that does not
    cover the warrant under which the value was produced (cross-org boundary)."""
    pass


@dataclass(frozen=True)
class Warrant:
    ref: str
    issuer: str
    granted: FrozenSet[str]
    delegation_depth: int
    expiry: float
    revocation_epoch: int


@dataclass
class ReturnedValue:
    payload: object
    produced_under: str          # warrant_ref at production time
    required_capability: str     # capability the consumer will use it to justify


class FederatedHandoff:
    def __init__(self, now: float, revocation_epochs: dict[str, int]):
        self.now = now
        self.revocation_epochs = revocation_epochs
        self._cache: dict[str, Warrant] = {}

    def validate_at_handoff(self, w: Warrant) -> None:
        if w.expiry <= self.now:
            raise WarrantLineageError(f"warrant {w.ref} expired at handoff")
        self._cache[w.ref] = w

    def consume(self, value: ReturnedValue, presented: Warrant) -> None:
        cached = self._cache.get(value.produced_under)
        if cached is None:
            raise WarrantLineageError(
                f"no cached warrant for production ref {value.produced_under}"
            )
        # 1. issuer revocation must be re-checked at use time, not handoff time
        current_epoch = self.revocation_epochs.get(cached.ref, 0)
        if current_epoch != cached.revocation_epoch:
            raise WarrantLineageError(
                f"warrant {cached.ref} revoked (epoch {cached.revocation_epoch}->{current_epoch})"
            )
        # 2. the value was produced under a warrant that must still cover the
        #    capability the consumer is using it to justify
        if value.required_capability not in cached.granted:
            raise WarrantLineageError(
                f"production warrant {cached.ref} lacks {value.required_capability!r}"
            )
        # 3. the presented (consuming) warrant must be the same lineage and
        #    must not have narrowed below the production scope
        if presented.ref != cached.ref:
            raise WarrantLineageError(
                f"cross-warrant consumption: produced under {cached.ref}, "
                f"presented {presented.ref}"
            )
        if presented.delegation_depth < cached.delegation_depth:
            raise WarrantLineageError(
                f"delegation depth narrowed {cached.delegation_depth}->{presented.delegation_depth}"
            )
