# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-capability-scope-enforcement-when-a-tool-result-is-replayed-through-a-cached-warrant-rather-than-re-minted-per-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-capability-scope-enforcement-when-a-tool-result-is-replayed-through-a-cached-warrant-rather-than-re-minted-per-invocation.warrant.json
# Markdown SHA-256:   b6ef5a3e9f813261a0424aba3c4a6e88508bc7afd5234990c26045821c810860
# Code AST SHA-256:   7d6a8d01de9aa94c1eca307211ece50bc8bda6243bc6b8d60513074e4a3e7062
# Verified Classes:   StaleWarrantError, PolicySnapshot, Warrant, Runtime
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StaleWarrantError(RuntimeError):
    """Raised when a cached warrant is older than the live policy snapshot.

    A warrant is an authorization claim frozen at mint time. If the policy
    version has advanced (revocation, allowlist edit, cap tightening), the
    cached warrant no longer represents current policy and MUST NOT be used
    to authorize execution or to gate delivery of a cached result.
    """


@dataclass(frozen=True)
class PolicySnapshot:
    version: int
    allowed_hosts: frozenset
    egress_bytes_max: int
    revoked: frozenset = frozenset()


@dataclass(frozen=True)
class Warrant:
    subject: str
    tool_id: str
    allowed_hosts: frozenset
    egress_bytes_max: int
    policy_version: int
    ttl_s: int = 300


@dataclass
class Runtime:
    live_policy: PolicySnapshot
    _result_cache: dict = field(default_factory=dict)

    def _cache_key(self, tool_id: str, args: dict) -> str:
        # NOTE: policy_version is part of the key so a policy bump
        # invalidates results minted under stale authorization.
        raw = f"{tool_id}|{sorted(args.items())}|{self.live_policy.version}"
        return hashlib.sha256(raw.encode()).hexdigest()

    def mint(self, subject: str, tool_id: str, args: dict) -> Warrant:
        # Always derive from the CURRENT snapshot. Never reuse a cached warrant.
        p = self.live_policy
        return Warrant(
            subject=subject,
            tool_id=tool_id,
            allowed_hosts=p.allowed_hosts,
            egress_bytes_max=p.egress_bytes_max,
            policy_version=p.version,
        )

    def _authorize(self, w: Warrant, host: str, nbytes: int) -> None:
        if w.policy_version != self.live_policy.version:
            raise StaleWarrantError(
                f"warrant minted at policy v{w.policy_version}, "
                f"live is v{self.live_policy.version}; re-mint required"
            )
        if host in self.live_policy.revoked:
            raise StaleWarrantError(f"host {host!r} revoked at live policy")
        # Intersect with live policy; never trust warrant.scope as sufficient.
        if host not in (w.allowed_hosts & self.live_policy.allowed_hosts):
            raise StaleWarrantError(f"host {host!r} outside live allowlist")
        if nbytes > min(w.egress_bytes_max, self.live_policy.egress_bytes_max):
            raise StaleWarrantError(
                f"{nbytes} bytes exceeds live cap "
                f"{self.live_policy.egress_bytes_max}"
            )

    def dispatch(self, subject: str, tool_id: str, args: dict) -> bytes:
        host = args.get("host", "")
        key = self._cache_key(tool_id, args)

        # Authorization happens on EVERY dispatch, hit or miss.
        w = self.mint(subject, tool_id, args)

        if key in self._result_cache:
            body = self._result_cache[key]
            self._authorize(w, host, len(body))  # re-check before delivery
            return body

        body = self._execute(tool_id, args)      # real egress
        self._authorize(w, host, len(body))      # re-check before delivery
        self._result_cache[key] = body
        return body

    def _execute(self, tool_id: str, args: dict) -> bytes:
        return b"x" * 1_847_212  # stand-in for a fetched body
