# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-reject-stale-delegated-scope-credentials-after-a-mid-task-scope-narrowing-event-in-aaif.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-reject-stale-delegated-scope-credentials-after-a-mid-task-scope-narrowing-event-in-aaif.warrant.json
# Markdown SHA-256:   877e4a47c36cf13b731b093aeca172d610985555599c007f78e9cc02d453d4bc
# Code AST SHA-256:   4560038a02bbb53ccba3a220ea8103a3a7c21530be4c59b1b713c86d9ccc5039
# Verified Classes:   SupersededScopeError, IssuerSequenceAnomaly, Credential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet

class SupersededScopeError(RuntimeError):
    """Raised when a tool call exercises a scope withdrawn by a newer delegation."""
    pass

class IssuerSequenceAnomaly(RuntimeError):
    """Raised when the issuer's delegationSeq is not strictly monotonic."""
    pass

@dataclass(frozen=True)
class Credential:
    subject: str
    issuer: str
    scopes: FrozenSet[str]
    delegation_seq: int
    valid_until: float

def authorize_tool_call(
    requested_scope: str,
    cached: Credential,
    issuer_credential: Credential,
    now: float,
) -> Credential:
    if issuer_credential.delegation_seq < cached.delegation_seq:
        raise IssuerSequenceAnomaly(
            f"issuer seq {issuer_credential.delegation_seq} < cached "
            f"{cached.delegation_seq} for subject {cached.subject}; "
            f"possible fork or rollback — escalate, do not proceed"
        )

    if issuer_credential.valid_until <= now:
        raise SupersededScopeError(
            f"issuer credential for {cached.subject} expired at "
            f"{issuer_credential.valid_until}; now={now}"
        )

    # Refresh cache to the authoritative credential regardless of outcome.
    effective = issuer_credential

    if cached.delegation_seq < issuer_credential.delegation_seq:
        if requested_scope not in effective.scopes:
            raise SupersededScopeError(
                f"scope {requested_scope!r} exercised at seq "
                f"{cached.delegation_seq} was withdrawn at seq "
                f"{issuer_credential.delegation_seq} for subject "
                f"{cached.subject}; re-plan required"
            )

    if requested_scope not in effective.scopes:
        raise SupersededScopeError(
            f"scope {requested_scope!r} not present in credential for "
            f"{cached.subject} at seq {effective.delegation_seq}"
        )

    return effective
