# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-validate-mcp-tool-scopes-after-a-mid-session-capability-downgrade-to-prevent-scope-resurrection-across-the-audit.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-validate-mcp-tool-scopes-after-a-mid-session-capability-downgrade-to-prevent-scope-resurrection-across-the-audit.warrant.json
# Markdown SHA-256:   50da235532d4b2c00b6dd8c3b9e7a3530bed34d3869d96e1965cf6dc6fcaa9d8
# Code AST SHA-256:   6989e6a4fcf996cfbd27b04ac6c7f61072e2a968ed898df52efeaab83e519c4c
# Verified Classes:   StaleGrantEpochError, Grant, AuditRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleGrantEpochError(RuntimeError):
    """Raised when a tool call is authorized against a cached grant whose epoch
    is older than the grant store's current epoch. Admitting such a call would
    resurrect a revoked scope and emit an unreconcilable audit record."""
    pass


@dataclass(frozen=True)
class Grant:
    epoch: int
    scopes: frozenset[str]


@dataclass(frozen=True)
class AuditRecord:
    session: str
    tool: str
    decision: str
    grant_epoch: int  # captured at decision time, never post-hoc
    reason: str = ""


def authorize_and_audit(
    session: str,
    tool: str,
    cached_grant: Grant,
    store_grant: Grant,
    scope_required: str,
) -> AuditRecord:
    # Guardrail 1: per-call epoch check. A cached grant older than the store
    # grant may contain scopes that have since been revoked.
    if cached_grant.epoch < store_grant.epoch:
        # Do not admit against the cache. Re-resolve against the store grant.
        if scope_required not in store_grant.scopes:
            return AuditRecord(
                session=session,
                tool=tool,
                decision="deny",
                grant_epoch=store_grant.epoch,
                reason="stale_grant_epoch_and_scope_revoked",
            )
        # Scope survives the downgrade: admit, but stamp the fresh epoch.
        return AuditRecord(
            session=session,
            tool=tool,
            decision="allow",
            grant_epoch=store_grant.epoch,
            reason="revalidated_after_epoch_bump",
        )

    # Guardrail 2: even at matching epochs, never admit a scope absent from the
    # grant. This is the ordinary scope check, kept separate from the epoch check.
    if scope_required not in cached_grant.scopes:
        return AuditRecord(
            session=session,
            tool=tool,
            decision="deny",
            grant_epoch=cached_grant.epoch,
            reason="scope_not_granted",
        )

    return AuditRecord(
        session=session,
        tool=tool,
        decision="allow",
        grant_epoch=cached_grant.epoch,
    )


def enforce_post_call_invariant(record: AuditRecord, store_grant: Grant) -> None:
    """After dispatch, assert the audit record's epoch is reconcilable with the
    store. A record stamped with an epoch older than a revocation affecting its
    tool is a scope-resurrection event and must abort the transaction."""
    if record.decision == "allow" and record.grant_epoch < store_grant.epoch:
        raise StaleGrantEpochError(
            f"session {record.session} tool {record.tool} audited allow at epoch "
            f"{record.grant_epoch} but store advanced to {store_grant.epoch}; "
            f"scope resurrection detected, aborting"
        )
