# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-delegated-warrant-has-been-silently-narrowed-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-delegated-warrant-has-been-silently-narrowed-mid-chain.warrant.json
# Markdown SHA-256:   b9e63d1e32a2684a053ebc416bfbf35bbf42e179725c21720eafde90a022232a
# Code AST SHA-256:   52e1acb47d09f70c1417dffd88ca8a861790ca0e379d52f60b6e3a0dd172a4fa
# Verified Classes:   ScopeMonotonicityError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ScopeMonotonicityError(RuntimeError):
    """Raised when a delegated warrant's scope is not a subset of its parent's,
    or when the chain cannot be resolved to prove the scope is held."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    subject: str
    scope: frozenset[str]
    parent_hash: Optional[str]  # H(parent warrant); None for root


def _hash(w: Warrant) -> str:
    return hashlib.sha256(
        f"{w.warrant_id}|{w.subject}|{sorted(w.scope)}".encode()
    ).hexdigest()


def effective_scope(
    leaf: Warrant,
    chain_index: dict[str, Warrant],
    revoked_ids: set[str],
    executing_instance: str,
) -> frozenset[str]:
    """Compute the proven scope intersection from leaf to root.

    Fails closed: any unresolvable link, any non-superset scope, any revoked
    link, or a subject mismatch raises instead of returning a partial scope.
    """
    if leaf.subject != executing_instance:
        raise ScopeMonotonicityError(
            f"leaf subject {leaf.subject!r} != executing instance "
            f"{executing_instance!r}"
        )

    proven = set(leaf.scope)
    current = leaf
    while current.parent_hash is not None:
        if current.warrant_id in revoked_ids:
            raise ScopeMonotonicityError(
                f"warrant {current.warrant_id!r} revoked; subtree authority void"
            )
        parent = chain_index.get(current.parent_hash)
        if parent is None:
            raise ScopeMonotonicityError(
                f"cannot resolve parent {current.parent_hash!r} of "
                f"{current.warrant_id!r}; scope unproven, failing closed"
            )
        if not current.scope.issubset(parent.scope):
            narrowed = current.scope - parent.scope
            raise ScopeMonotonicityError(
                f"scope monotonicity violated at {current.warrant_id!r}: "
                f"elements {sorted(narrowed)} not held by parent "
                f"{parent.warrant_id!r}"
            )
        proven &= parent.scope
        current = parent

    if current.warrant_id in revoked_ids:
        raise ScopeMonotonicityError(
            f"root warrant {current.warrant_id!r} revoked"
        )
    return frozenset(proven)


def exercise(scope_element: str, proven: frozenset[str]) -> None:
    if scope_element not in proven:
        raise ScopeMonotonicityError(
            f"scope element {scope_element!r} not in proven chain intersection "
            f"{sorted(proven)}; refusing to exercise"
        )
    # ... perform the tool call ...
