# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-delegated-capability-after-the-delegating-broker-has-expired-its-own-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-delegated-capability-after-the-delegating-broker-has-expired-its-own-warrant.warrant.json
# Markdown SHA-256:   30a0240fa42d1d4c2bd35d0664c4c82aca0b2f7ac1f7e54caef997673209a44b
# Code AST SHA-256:   0fd4516498e40c21cb8d938ff10194b86b017e438415ff31f3c89f5a578b03cd
# Verified Classes:   OrphanedDelegationError, Warrant, CapabilityToken, WarrantRegistry
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class OrphanedDelegationError(RuntimeError):
    """Raised when a capability token's justifying warrant chain is not live
    at execution time, or when a token was minted with a lifetime exceeding
    its parent warrant's remaining validity."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    scope: frozenset[str]
    issued_at: float
    not_after: float
    version: int = 1


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    subject: str          # executing instance, e.g. "org-c:task-agent"
    action: str           # e.g. "write:ledger"
    issued_at: float
    not_after: float
    parent_warrant_id: str
    parent_warrant_version: int
    signature_ok: bool = True


class WarrantRegistry:
    """Immutable, versioned warrant store. Records are append-only so that a
    token's parent_warrant (id, version) always resolves to the exact warrant
    live at issuance — never a later reissued version."""

    def __init__(self) -> None:
        self._by_key: dict[tuple[str, int], Warrant] = {}

    def record(self, w: Warrant) -> None:
        self._by_key[(w.warrant_id, w.version)] = w

    def resolve(self, warrant_id: str, version: int) -> Optional[Warrant]:
        return self._by_key.get((warrant_id, version))


def mint_token(
    broker_warrant: Warrant,
    subject: str,
    action: str,
    requested_ttl: float,
    now: float,
) -> CapabilityToken:
    """Lifetime-narrowing: a token may never outlive the warrant that justifies
    it. This makes orphaned delegation structurally impossible at the source."""
    if action not in broker_warrant.scope:
        raise OrphanedDelegationError(
            f"action {action!r} outside warrant scope {set(broker_warrant.scope)}"
        )
    if now >= broker_warrant.not_after:
        raise OrphanedDelegationError(
            f"broker warrant {broker_warrant.warrant_id} already expired at mint time"
        )
    # Clamp the token lifetime to the warrant's remaining validity.
    not_after = min(now + requested_ttl, broker_warrant.not_after)
    return CapabilityToken(
        token_id=f"cap-{subject}-{int(now)}",
        subject=subject,
        action=action,
        issued_at=now,
        not_after=not_after,
        parent_warrant_id=broker_warrant.warrant_id,
        parent_warrant_version=broker_warrant.version,
    )


def admit(
    token: CapabilityToken,
    registry: WarrantRegistry,
    now: float,
) -> None:
    """Full-chain re-derivation at execution. Rejects orphaned delegations
    even when the token's own signature and not_after are valid."""
    if not token.signature_ok:
        raise OrphanedDelegationError(f"token {token.token_id} signature invalid")

    if now >= token.not_after:
        raise OrphanedDelegationError(
            f"token {token.token_id} expired at {token.not_after}, now={now}"
        )

    parent = registry.resolve(token.parent_warrant_id, token.parent_warrant_version)
    if parent is None:
        raise OrphanedDelegationError(
            f"parent warrant {token.parent_warrant_id}"
            f"@v{token.parent_warrant_version} not found in registry"
        )

    # (1) Warrant must have been live at token issuance.
    if not (parent.issued_at <= token.issued_at < parent.not_after):
        raise OrphanedDelegationError(
            f"parent warrant was not live at token issuance "
            f"(warrant window [{parent.issued_at}, {parent.not_after}), "
            f"token issued at {token.issued_at})"
        )

    # (2) Warrant must be live NOW — this is the clause hash-presence checks skip.
    if now >= parent.not_after:
        raise OrphanedDelegationError(
            f"orphaned delegation: parent warrant {parent.warrant_id} expired at "
            f"{parent.not_after}, token {token.token_id} still presented at {now}"
        )

    # (3) Scope must cover the action under the issuance-time warrant version.
    if token.action not in parent.scope:
        raise OrphanedDelegationError(
            f"action {token.action!r} not covered by warrant "
            f"{parent.warrant_id}@v{parent.version}"
        )


def resume_working_set(
    tokens: list[CapabilityToken],
    registry: WarrantRegistry,
    now: float,
) -> list[CapabilityToken]:
    """At checkpoint resume, re-derive liveness for every held capability.
    Fail the resume rather than let the agent proceed on dead authority."""
    live: list[CapabilityToken] = []
    for tok in tokens:
        try:
            admit(tok, registry, now)
            live.append(tok)
        except OrphanedDelegationError as exc:
            raise OrphanedDelegationError(
                f"resume refused: capability {tok.token_id} lost its authority "
                f"across suspension; re-delegation required. Cause: {exc}"
            ) from exc
    return live
