# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-delegated-capability-token-has-silently-outlived-its-delegation-warrant-in-an-aaif-agent-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-delegated-capability-token-has-silently-outlived-its-delegation-warrant-in-an-aaif-agent-chain.warrant.json
# Markdown SHA-256:   af2b282dfbae261d6cf86e55803bf1778545822398e16fc74fa3e9a61003acad
# Code AST SHA-256:   8e8fdaf719477f37a19ea0baab97a19e10e13734cd8aaf9c1a36fe24608ffd7e
# Verified Classes:   OrphanedWarrantError, CapabilityToken, EpochWatermarkVerifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Callable

class OrphanedWarrantError(RuntimeError):
    """Raised when a token's scope claim exceeds the live warrant's effective scope,
    or when the token's warrant_epoch is below the verifier's revocation watermark."""
    pass

@dataclass
class CapabilityToken:
    subject: str
    scope: frozenset[str]
    warrant_ref: str
    warrant_epoch: int
    exp: float

class EpochWatermarkVerifier:
    def __init__(
        self,
        resolve_warrant_scope: Callable[[str], frozenset[str]],
        watermark: int,
        clock: Callable[[], float] = time.time,
    ) -> None:
        self._resolve = resolve_warrant_scope
        self._watermark = watermark
        self._clock = clock

    def verify(self, tk: CapabilityToken) -> None:
        now = self._clock()

        if now >= tk.exp:
            raise OrphanedWarrantError(
                f"token for {tk.subject} expired at {tk.exp:.0f}, now {now:.0f}"
            )

        # Silent-orphan guard: token was minted before the last known revocation.
        if tk.warrant_epoch < self._watermark:
            raise OrphanedWarrantError(
                f"token epoch {tk.warrant_epoch} < watermark {self._watermark}; "
                f"warrant {tk.warrant_ref} may have been narrowed since mint"
            )

        # Scope-subset against LIVE warrant scope, not mint-time scope.
        live_scope = self._resolve(tk.warrant_ref)
        excess = tk.scope - live_scope
        if excess:
            raise OrphanedWarrantError(
                f"token for {tk.subject} claims scope {sorted(excess)} not present in "
                f"live warrant {tk.warrant_ref} (live scope: {sorted(live_scope)})"
            )
