# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-capability-grant-when-the-peer-s-trust-attestation-expires-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-capability-grant-when-the-peer-s-trust-attestation-expires-mid-handoff.warrant.json
# Markdown SHA-256:   83d5a5900d534b065c29e1ebaccc67ac4501f71b577114ea892d13d519f3e2c1
# Code AST SHA-256:   87c91e565a07e977768974a90c35e5cc3eaa53ceee65025d81c625da3f2dd660
# Verified Classes:   FederationTrustError, ScopeNarrowingRejected, WarrantIdentityMismatch, TaskStateOrphaned, WarrantState, Warrant, CommittedTask
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class FederationTrustError(RuntimeError):
    """Base for cross-org trust boundary violations."""


class ScopeNarrowingRejected(FederationTrustError):
    """Successor warrant's scope is not a superset of the pinned scope."""


class WarrantIdentityMismatch(FederationTrustError):
    """A re-binding attempt presented a warrant from a different issuer."""


class TaskStateOrphaned(FederationTrustError):
    """Committed task has no pinned warrant identity; provenance is unverifiable."""


class WarrantState(Enum):
    VALID = "valid"
    EXPIRED_AT_REST = "expired_at_rest"       # never committed under it
    EXPIRED_IN_FLIGHT = "expired_in_flight"   # committed, then lapsed


@dataclass(frozen=True)
class Warrant:
    jti: str
    iss: str
    scope: frozenset
    not_after: float


@dataclass
class CommittedTask:
    task_id: str
    pinned: Warrant | None = None


def classify(warrant: Warrant, now: float, committed: bool) -> WarrantState:
    if now <= warrant.not_after:
        return WarrantState.VALID
    return WarrantState.EXPIRED_IN_FLIGHT if committed else WarrantState.EXPIRED_AT_REST


def accept_or_continue(task: CommittedTask, presented: Warrant, now: float) -> str:
    """Gate execution. Expiry gates only uncommitted work."""
    committed = task.pinned is not None
    state = classify(presented, now, committed)

    if state is WarrantState.EXPIRED_AT_REST:
        # No state exists; safe to reject outright.
        raise FederationTrustError(
            f"warrant {presented.jti} expired before any task committed"
        )

    if state is WarrantState.EXPIRED_IN_FLIGHT and task.pinned.jti == presented.jti:
        # Continue under pinned authority; expiry does not revoke committed work.
        return "continue_under_pinned"

    # A different warrant is being presented for an already-committed task:
    # this is a re-binding request, not a duplicate.
    if task.pinned is None:
        task.pinned = presented
        return "accepted_fresh"

    if presented.iss != task.pinned.iss:
        raise WarrantIdentityMismatch(
            f"re-bind for {task.task_id}: issuer {presented.iss} != pinned {task.pinned.iss}"
        )
    if not task.pinned.scope <= presented.scope:
        raise ScopeNarrowingRejected(
            f"re-bind for {task.task_id}: successor scope "
            f"{sorted(presented.scope)} does not cover pinned {sorted(task.pinned.scope)}"
        )
    # Superset and same issuer: safe to re-pin, but log the transition.
    task.pinned = presented
    return "rebound_superset"


def require_provenance(task: CommittedTask) -> Warrant:
    if task.pinned is None:
        raise TaskStateOrphaned(
            f"task {task.task_id} committed without a pinned warrant identity"
        )
    return task.pinned
