# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-scope-whose-capability-attestation-was-minted-against-a-superseded-tool-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-scope-whose-capability-attestation-was-minted-against-a-superseded-tool-schema.warrant.json
# Markdown SHA-256:   4dae7611b16ddff85d19efe002e344e87e8390bd57e29f678964595a2041fb43
# Code AST SHA-256:   6ef3a4926a74bfa15e19fd88669a60801d5320f826eec1feb744aae0caba53d8
# Verified Classes:   StaleAttestationError, Attestation, ToolDescriptor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when a capability attestation is bound to a superseded tool schema."""


@dataclass(frozen=True)
class Attestation:
    subject: str
    scope: str
    tool_id: str
    schema_hash: str
    signature_valid: bool


@dataclass(frozen=True)
class ToolDescriptor:
    tool_id: str
    schema_hash: str
    compatible_with: frozenset  # set of prior schema_hashes still accepted


def authorize_tool_call(
    att: Attestation,
    grant_scopes: set,
    live: ToolDescriptor,
    compatibility_published: bool,
) -> str:
    # Pass 1: credential validity (signature + scope membership).
    if not att.signature_valid:
        raise StaleAttestationError("attestation signature invalid")
    if att.scope not in grant_scopes:
        raise StaleAttestationError(f"scope {att.scope!r} not in grant")
    if att.tool_id != live.tool_id:
        raise StaleAttestationError(
            f"attestation tool {att.tool_id!r} != live tool {live.tool_id!r}"
        )

    # Pass 2: THE BINDING CHECK. This is the step most AAIFs omit.
    if att.schema_hash == live.schema_hash:
        return "ALLOW"

    if compatibility_published and att.schema_hash in live.compatible_with:
        # Compatible rollout: allow, but force a downgrade notice into agent context.
        return "ALLOW_WITH_SCHEMA_DOWNGRADE_NOTICE"

    # Terminal authorization state — must NOT be surfaced as a retryable tool error.
    raise StaleAttestationError(
        "ATTESTATION_SCHEMA_STALE: attestation bound to "
        f"{att.schema_hash}, live descriptor is {live.schema_hash}; "
        "agent must re-request attestation or abandon the tool plan"
    )


def _demo() -> None:
    att = Attestation("agent:research-7", "tool:write:research-db",
                      "research_db.upsert", "sha256:v7", True)
    live = ToolDescriptor("research_db.upsert", "sha256:v9", frozenset({"sha256:v8"}))
    # v7 is neither the live hash nor in the compatibility set -> must raise.
    authorize_tool_call(att, {"tool:write:research-db"}, live, compatibility_published=True)


if __name__ == "__main__":
    _demo()
