# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-attest-capability-warrants-after-a-peer-s-schema-narrows-mid-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-attest-capability-warrants-after-a-peer-s-schema-narrows-mid-delegation.warrant.json
# Markdown SHA-256:   ed0b36aac92b44d072549bb4cc79b4626830c4301d2af7974906a160751c1f3a
# Code AST SHA-256:   c5533bcf8aa34a95472dc6bfd533c1d5c94b609e020091f860a2669b94be8059
# Verified Classes:   StaleWarrantScopeError, ResidualHandlerError, Manifest, Warrant, Peer
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class StaleWarrantScopeError(RuntimeError):
    """Raised when a warrant's schema_hash does not match the peer's current manifest."""


class ResidualHandlerError(RuntimeError):
    """Raised when a handler is callable but its authorizing manifest version is revoked."""


@dataclass(frozen=True)
class Manifest:
    version: str
    scopes: frozenset
    def hash(self) -> str:
        payload = f"{self.version}:{','.join(sorted(self.scopes))}".encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass(frozen=True)
class Warrant:
    scope: str
    aud: str
    schema_hash: str
    minted_at: float = field(default_factory=time.time)


class Peer:
    def __init__(self, manifest: Manifest):
        self._manifest = manifest
        self._handlers: dict = {}
        self._bind_handlers()

    def _bind_handlers(self) -> None:
        # Handlers are bound to the manifest version that authorized them.
        self._handlers = {
            scope: (lambda s=scope: f"executed:{s}") for scope in self._manifest.scopes
        }

    def reload_manifest(self, new_manifest: Manifest) -> None:
        # Atomic: manifest and handlers rebind together. No residual handlers survive.
        self._manifest = new_manifest
        self._bind_handlers()

    def execute(self, warrant: Warrant) -> str:
        if warrant.aud != "self":
            raise StaleWarrantScopeError(f"warrant audience mismatch: {warrant.aud}")

        # ENFORCING check, not advisory: current manifest hash must match warrant.
        current_hash = self._manifest.hash()
        if warrant.schema_hash != current_hash:
            raise StaleWarrantScopeError(
                f"warrant schema_hash {warrant.schema_hash[:12]} != "
                f"current manifest {current_hash[:12]} (v={self._manifest.version}); "
                f"narrowing drift detected — failing closed"
            )

        if warrant.scope not in self._manifest.scopes:
            raise StaleWarrantScopeError(
                f"scope {warrant.scope!r} absent from manifest v={self._manifest.version}"
            )

        handler = self._handlers.get(warrant.scope)
        if handler is None:
            # Should be unreachable if rebind is atomic; guards against split-brain.
            raise ResidualHandlerError(
                f"handler for {warrant.scope!r} callable but not bound to "
                f"manifest v={self._manifest.version}"
            )

        return handler()


def delegate(peer: Peer, scope: str) -> str:
    """Principal mints a warrant against the peer's *advertised* manifest and dispatches."""
    advertised = peer._manifest  # principal's discovery view
    warrant = Warrant(scope=scope, aud="self", schema_hash=advertised.hash())
    return peer.execute(warrant)


if __name__ == "__main__":
    peer = Peer(Manifest(version="v3", scopes=frozenset({"read:corpus", "write:index"})))
    assert delegate(peer, "write:index") == "executed:write:index"

    # Operator revokes write:index mid-batch. Manifest narrows v3 -> v4.
    peer.reload_manifest(Manifest(version="v4", scopes=frozenset({"read:corpus:redacted"})))

    # Principal still holds cached v3 manifest; mints an over-broad warrant.
    stale = Warrant(scope="write:index", aud="self", schema_hash=Manifest(
        version="v3", scopes=frozenset({"read:corpus", "write:index"})).hash())

    try:
        peer.execute(stale)
    except StaleWarrantScopeError as e:
        print(f"FAIL-CLOSED as required: {e}")
        # Principal must now invalidate its cached manifest and re-plan.
    else:
        raise StaleWarrantScopeError("over-broad warrant executed — invariant violated")
