# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-aaif-warrant-after-a-mid-task-capability-downgrade-and-why-scope-hash-caching-silently-defeats-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-aaif-warrant-after-a-mid-task-capability-downgrade-and-why-scope-hash-caching-silently-defeats-it.warrant.json
# Markdown SHA-256:   824181177e1445b17aec76508171e84cef10d1981fc0661b9a7c374bd2372b9b
# Code AST SHA-256:   aa8824364099e1fdafa9ddc019217fd03b61312f69c8023755b6d7ba43a5eb9d
# Verified Classes:   StaleWarrantDecisionError, Warrant, Decision, WarrantDecisionCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from hashlib import sha256
from typing import Optional


class StaleWarrantDecisionError(RuntimeError):
    """Raised when a cached AAIF authorization decision is reused for a
    warrant whose canonical scope-set digest no longer matches the digest
    the decision was derived from (e.g. after mid-task attenuation)."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    chain_root: str
    scopes: frozenset[str]
    expiry: int

    def scope_digest(self) -> str:
        canonical = "|".join(sorted(self.scopes))
        return sha256(canonical.encode("utf-8")).hexdigest()


@dataclass(frozen=True)
class Decision:
    allow: bool
    scope_digest: str
    expiry: int


class WarrantDecisionCache:
    """Cache keyed on (issuer, subject, chain_root) but whose *values*
    carry the scope digest they were derived from. A hit is only honored
    when the presented warrant's digest matches the cached digest."""

    def __init__(self) -> None:
        self._store: dict[tuple[str, str, str], Decision] = {}

    def _key(self, w: Warrant) -> tuple[str, str, str]:
        return (w.issuer, w.subject, w.chain_root)

    def decide(self, w: Warrant, required: frozenset[str], now: int) -> Decision:
        if now >= w.expiry:
            return Decision(allow=False, scope_digest=w.scope_digest(), expiry=w.expiry)

        key = self._key(w)
        presented_digest = w.scope_digest()
        cached = self._store.get(key)

        if cached is not None:
            if cached.scope_digest != presented_digest:
                # Same chain root, different scope set: the issuer attenuated
                # (or re-signed) mid-task. The cached decision is stale and
                # MUST NOT be reused. Recompute against the presented bytes.
                raise StaleWarrantDecisionError(
                    f"cached decision for {key} was derived from scope digest "
                    f"{cached.scope_digest!r} but presented warrant has digest "
                    f"{presented_digest!r}; refusing to reuse stale allow"
                )
            if cached.expiry != w.expiry:
                raise StaleWarrantDecisionError(
                    f"cached decision for {key} has expiry {cached.expiry} "
                    f"but presented warrant has expiry {w.expiry}"
                )
            if cached.allow and not required.issubset(w.scopes):
                raise StaleWarrantDecisionError(
                    f"cached allow for {key} does not cover required scopes "
                    f"{sorted(required)} under current warrant scopes {sorted(w.scopes)}"
                )
            return cached

        allow = required.issubset(w.scopes)
        decision = Decision(allow=allow, scope_digest=presented_digest, expiry=w.expiry)
        self._store[key] = decision
        return decision


def authorize(cache: WarrantDecisionCache, w: Warrant,
              required: frozenset[str], now: int) -> None:
    """Entry point used by the executor before each tool call. Raises on
    stale-decision reuse or on denial; returns None on authorized call."""
    decision = cache.decide(w, required, now)
    if not decision.allow:
        raise StaleWarrantDecisionError(
            f"denied: warrant {w.chain_root} scopes {sorted(w.scopes)} "
            f"do not cover required {sorted(required)}"
        )
