# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-delegated-credential-chain-outlives-the-scope-it-was-minted-against.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-delegated-credential-chain-outlives-the-scope-it-was-minted-against.warrant.json
# Markdown SHA-256:   97e32c7cdf2d9f0c48ba7929f4b21239c1ceaa765c8d871b68e717165be4cc16
# Code AST SHA-256:   fa1a28cae8d581969056f58967fa434521011523e4b5d28a2d63890622b057b0
# Verified Classes:   DelegatedScopeLivenessError, DelegatedToken, ParentStateMachine
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class DelegatedScopeLivenessError(RuntimeError):
    """Raised when a delegated token's scope outlives the parent state that justified it."""


@dataclass
class DelegatedToken:
    issuer: str
    subject: str
    scope: frozenset
    parent_state: str
    minted_at: float
    ttl: float

    def expires_at(self) -> float:
        return self.minted_at + self.ttl


@dataclass
class ParentStateMachine:
    principal: str
    current_state: str
    min_dwell: float
    state_entered_at: float = field(default_factory=time.monotonic)

    def transition(self, new_state: str) -> None:
        self.current_state = new_state
        self.state_entered_at = time.monotonic()


# The scope predicate that legitimately requires the parent to be in RECONCILE.
STATE_DEPENDENT_SCOPES = {
    "ledger:write:reconcile": "RECONCILE",
    "ledger:read": None,  # stateless, TTL-bounded only
}


def mint_delegated_token(
    parent: ParentStateMachine,
    subject: str,
    requested_scope: frozenset,
    requested_ttl: float,
    now: float | None = None,
) -> DelegatedToken:
    now = time.monotonic() if now is None else now

    for scope_item in requested_scope:
        required_state = STATE_DEPENDENT_SCOPES.get(scope_item)
        if required_state is None:
            continue
        if parent.current_state != required_state:
            raise DelegatedScopeLivenessError(
                f"cannot mint {scope_item!r}: parent {parent.principal} is in "
                f"{parent.current_state!r}, requires {required_state!r}"
            )
        # The guardrail: a state-dependent scope may not outlive the parent's
        # minimum dwell in that state, or the token survives the transition.
        if requested_ttl >= parent.min_dwell:
            raise DelegatedScopeLivenessError(
                f"ttl {requested_ttl}s >= parent min_dwell {parent.min_dwell}s for "
                f"state-dependent scope {scope_item!r}; token would outlive {required_state!r}"
            )

    return DelegatedToken(
        issuer=parent.principal,
        subject=subject,
        scope=requested_scope,
        parent_state=parent.current_state,
        minted_at=now,
        ttl=requested_ttl,
    )


def authorize_call(
    token: DelegatedToken,
    scope_item: str,
    parent: ParentStateMachine,
    now: float | None = None,
) -> None:
    now = time.monotonic() if now is None else now

    if scope_item not in token.scope:
        raise DelegatedScopeLivenessError(f"{scope_item!r} not in token scope")

    if now >= token.expires_at():
        raise DelegatedScopeLivenessError(f"token expired at {token.expires_at()}")

    required_state = STATE_DEPENDENT_SCOPES.get(scope_item)
    if required_state is not None and parent.current_state != required_state:
        # This is the check AAIF omits: the token verifies, but the parent
        # has transitioned out of the state that justified the scope.
        raise DelegatedScopeLivenessError(
            f"scope {scope_item!r} requires parent state {required_state!r}, "
            f"but {parent.principal} is in {parent.current_state!r}"
        )


if __name__ == "__main__":
    parent = ParentStateMachine(principal="orchestrator-O", current_state="RECONCILE", min_dwell=600.0)

    # Legitimate mint: TTL below min_dwell.
    t1 = mint_delegated_token(parent, "subagent-S", frozenset({"ledger:write:reconcile"}), requested_ttl=300.0)
    authorize_call(t1, "ledger:write:reconcile", parent)  # ok

    # Parent settles; the token still verifies cryptographically.
    parent.transition("SETTLED")

    try:
        authorize_call(t1, "ledger:write:reconcile", parent)
    except DelegatedScopeLivenessError as exc:
        print(f"blocked post-settlement write: {exc}")

    # The failure the naive deployment hits: TTL >= min_dwell.
    parent.transition("RECONCILE")
    try:
        mint_delegated_token(parent, "subagent-S", frozenset({"ledger:write:reconcile"}), requested_ttl=900.0)
    except DelegatedScopeLivenessError as exc:
        print(f"refused unsafe mint: {exc}")
