# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cross-org-a2a-task-whose-residency-policy-resolves-to-the-same-jurisdiction-but-whose-capability-warrant-w.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cross-org-a2a-task-whose-residency-policy-resolves-to-the-same-jurisdiction-but-whose-capability-warrant-w.warrant.json
# Markdown SHA-256:   64c6efd164b0cbed92dd782c2dc9b19a5b9409fb0abc53e2f3eaa5dab82cf3eb
# Code AST SHA-256:   313ddbb032b1a48b333dd8ba8915e6c24d71d5e4c3814353fb0405336e5fa1e5
# Verified Classes:   PolicyEpochWidening, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable


class PolicyEpochWidening(RuntimeError):
    """Raised when a callee's current policy epoch interprets a granted
    capability scope more broadly than the epoch under which the caller
    minted the warrant. Signature and residency may both be valid; the
    failure is semantic scope laundering across epochs."""
    pass


@dataclass(frozen=True)
class Warrant:
    residency_claim: str
    scopes: frozenset[str]
    policy_epoch: str
    signature_valid: bool


def validate_federated_task(
    warrant: Warrant,
    callee_residency: str,
    resolve: Callable[[str, str], frozenset[str]],
    callee_epoch: str,
) -> None:
    # Residency agreement is necessary but NOT sufficient.
    if warrant.residency_claim != callee_residency:
        raise PolicyEpochWidening(
            f"residency mismatch: {warrant.residency_claim} != {callee_residency}"
        )
    if not warrant.signature_valid:
        raise PolicyEpochWidening("warrant signature invalid")

    # Same epoch: token semantics are identical, subset check is sound.
    if warrant.policy_epoch == callee_epoch:
        return

    # Divergent epochs: containment must be tested per scope, in the
    # intersection of caller-epoch and callee-epoch semantics.
    for token in warrant.scopes:
        caller_set = resolve(token, warrant.policy_epoch)
        callee_set = resolve(token, callee_epoch)
        if not callee_set.issubset(caller_set):
            widened = callee_set - caller_set
            raise PolicyEpochWidening(
                f"scope '{token}' widened across epochs "
                f"{warrant.policy_epoch}->{callee_epoch}: "
                f"callee authorizes {sorted(widened)} beyond caller warrant"
            )
    # All scopes resolve narrower-or-equal: safe to execute under callee epoch.
