# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-the-attestation-scope-supersession-gap-in-mcp-a2a-handshakes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-the-attestation-scope-supersession-gap-in-mcp-a2a-handshakes.warrant.json
# Markdown SHA-256:   431ad22ace77878e6e2feab07abe6a713eb74ef9184022f30a2a5d0b56092845
# Code AST SHA-256:   b9cdbbd30062621664acfd73bd8d905686e4d60bf455de6a630135be843e52d5
# Verified Classes:   SupersededAttestationError, AttestationLedgerUnavailable, Attestation, LedgerEntry, IssuerLedger
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class SupersededAttestationError(RuntimeError):
    """Raised when a presented attestation's scope is no longer the issuer's current grant."""
    pass


class AttestationLedgerUnavailable(RuntimeError):
    """Raised when the issuer ledger cannot be reached; distinct from invalid attestation."""
    pass


@dataclass
class Attestation:
    att_id: str
    issuer: str
    subject: str
    scope: frozenset
    issued_at: float
    expires_at: float
    issuance_counter: int


@dataclass
class LedgerEntry:
    att_id: str
    scope: frozenset
    issuance_counter: int
    superseded_by: Optional[str] = None


class IssuerLedger:
    """Stand-in for the control-plane ledger. In production: a queryable store."""

    def __init__(self):
        self._entries: dict = {}
        self._current_counter: dict = {}
        self._reachable = True

    def record(self, att: Attestation):
        self._entries[att.att_id] = LedgerEntry(
            att_id=att.att_id, scope=att.scope, issuance_counter=att.issuance_counter
        )
        self._current_counter[att.subject] = att.issuance_counter

    def supersede(self, subject: str, new_att: Attestation):
        current = self._current_counter.get(subject, -1)
        if new_att.issuance_counter <= current:
            raise ValueError("supersession must carry a higher issuance counter")
        for entry in self._entries.values():
            if entry.issuance_counter == current and entry.superseded_by is None:
                entry.superseded_by = new_att.att_id
        self._current_counter[subject] = new_att.issuance_counter
        self._entries[new_att.att_id] = LedgerEntry(
            att_id=new_att.att_id,
            scope=new_att.scope,
            issuance_counter=new_att.issuance_counter,
        )

    def current_scope(self, subject: str) -> frozenset:
        if not self._reachable:
            raise AttestationLedgerUnavailable("issuer ledger unreachable")
        counter = self._current_counter.get(subject)
        if counter is None:
            return frozenset()
        for entry in self._entries.values():
            if entry.issuance_counter == counter and entry.superseded_by is None:
                return entry.scope
        return frozenset()

    def is_superseded(self, att_id: str) -> bool:
        entry = self._entries.get(att_id)
        return entry is not None and entry.superseded_by is not None


MUTATING_PREFIXES = ("write:", "delete:", "spend:", "send:")


def authorize(
    presented: Attestation,
    requested_scope: frozenset,
    ledger: IssuerLedger,
    now: Optional[float] = None,
) -> bool:
    now = time.time() if now is None else now

    # Step 1-3: cryptographic + temporal validation (omitted signature check here).
    if now >= presented.expires_at:
        raise SupersededAttestationError(f"attestation {presented.att_id} expired")
    if not requested_scope.issubset(presented.scope):
        raise SupersededAttestationError(
            f"requested {requested_scope} not within presented scope {presented.scope}"
        )

    # Step 4: boundary check -- mutating capability requires issuer-current scope.
    is_mutating = any(
        s.startswith(MUTATING_PREFIXES) for s in requested_scope
    )
    if not is_mutating:
        return True  # presented-scope validation sufficient for read scopes

    try:
        current = ledger.current_scope(presented.subject)
    except AttestationLedgerUnavailable:
        # Fail closed for mutating capability; caller must retry, not re-request.
        raise

    if ledger.is_superseded(presented.att_id):
        raise SupersededAttestationError(
            f"attestation {presented.att_id} superseded; "
            f"issuer-current scope is {current}, presented was {presented.scope}"
        )
    if not requested_scope.issubset(current):
        raise SupersededAttestationError(
            f"requested {requested_scope} outside issuer-current scope {current}"
        )
    return True


if __name__ == "__main__":
    ledger = IssuerLedger()
    broad = Attestation(
        att_id="att-7", issuer="control-plane", subject="agent-A",
        scope=frozenset({"write:/sandbox", "read:/sandbox"}),
        issued_at=0.0, expires_at=1e12, issuance_counter=1,
    )
    ledger.record(broad)

    narrow = Attestation(
        att_id="att-9", issuer="control-plane", subject="agent-A",
        scope=frozenset({"write:/sandbox/scratch", "read:/sandbox"}),
        issued_at=40.0, expires_at=1e12, issuance_counter=2,
    )
    ledger.supersede("agent-A", narrow)

    # agent-A still presents the broad attestation from its context window.
    try:
        authorize(broad, frozenset({"write:/sandbox/secrets"}), ledger)
    except SupersededAttestationError as e:
        print("BLOCKED:", e)
