# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-holds-a-still-valid-capability-token-for-a-tool-whose-issuing-principal-was-revoked-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-holds-a-still-valid-capability-token-for-a-tool-whose-issuing-principal-was-revoked-mid-execution.warrant.json
# Markdown SHA-256:   24552c473bb91b40c921d056e403d0ae61291f48e0049423a1d39b939d9dc28b
# Code AST SHA-256:   5b2248a52ed159fa732ea7f04cf229cc16789a8a9317ee3114455752cdf76129
# Verified Classes:   StaleAuthorityError, Capability
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAuthorityError(RuntimeError):
    """Raised when an agent attempts an irreversible tool call or a
    delegation using a token whose issuing principal was revoked, even
    though the token itself is still signature-valid and unexpired."""


@dataclass(frozen=True)
class Capability:
    token_id: str
    root_principal: str
    scope: frozenset
    expires_at: float          # absolute epoch seconds; inherited, never extended
    revoked: bool = False

    def is_signature_valid(self) -> bool:
        # Local crypto check only. Says nothing about current authority.
        return True

    def is_unexpired(self, now: float) -> bool:
        return now < self.expires_at


def assert_current_authority(
    cap: Capability,
    now: float,
    revocation_latency_bound: float,
    irreversible: bool,
) -> None:
    """Gate irreversible calls and delegation on *current* authority,
    not merely on token validity."""
    if not cap.is_signature_valid():
        raise StaleAuthorityError(f"token {cap.token_id} signature invalid")

    if not cap.is_unexpired(now):
        raise StaleAuthorityError(f"token {cap.token_id} expired at {cap.expires_at}")

    if irreversible:
        # A valid+unexpired token is NOT proof of authority for effects.
        # We need a revocation check fresh within the staleness bound.
        if cap.revoked:
            raise StaleAuthorityError(
                f"root {cap.root_principal} revoked; token {cap.token_id} "
                f"still honored until {cap.expires_at} — refusing irreversible call"
            )
        if revocation_latency_bound <= 0:
            raise StaleAuthorityError(
                "no revocation oracle reachable; cannot bound staleness "
                "for an irreversible effect"
            )


def mint_child(parent: Capability, requested_ttl: float, now: float) -> Capability:
    """Attenuation must never extend the root's expiry clock."""
    if requested_ttl <= 0:
        raise StaleAuthorityError("requested TTL must be positive")
    child_exp = min(parent.expires_at, now + requested_ttl)
    if child_exp > parent.expires_at:
        raise StaleAuthorityError(
            f"delegation would extend authority past root expiry "
            f"({child_exp} > {parent.expires_at})"
        )
    # Re-verify the ROOT before minting: fan-out vector lives here.
    if parent.revoked:
        raise StaleAuthorityError(
            f"cannot mint descendant of revoked root {parent.root_principal}"
        )
    return Capability(
        token_id=f"{parent.token_id}.child",
        root_principal=parent.root_principal,
        scope=parent.scope,          # attenuation only narrows; not widened here
        expires_at=child_exp,
        revoked=False,
    )


def tool_call(cap: Capability, now: float, effect_is_irreversible: bool) -> str:
    assert_current_authority(
        cap,
        now=now,
        revocation_latency_bound=5.0,   # oracle staleness SLA in seconds
        irreversible=effect_is_irreversible,
    )
    return f"executed under {cap.token_id}"


# Reproduces the observed trace: revocation at t=40, calls still succeed
# unless the irreversible gate is enforced.
if __name__ == "__main__":
    t0 = Capability("T0", root_principal="P", scope=frozenset({"db.read", "ticket.write"}),
                    expires_at=time.time() + 300)
    revoked_t0 = Capability(t0.token_id, t0.root_principal, t0.scope,
                            t0.expires_at, revoked=True)

    # t=41s: read is idempotent; stale token tolerated.
    print(tool_call(revoked_t0, now=time.time() + 41, effect_is_irreversible=False))

    # t=47s: ticket write is irreversible; must be refused.
    tool_call(revoked_t0, now=time.time() + 47, effect_is_irreversible=True)
