# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-capability-token-whose-audit-trail-provenance-is-cryptographically-valid-but-semantically-unreplayable.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-capability-token-whose-audit-trail-provenance-is-cryptographically-valid-but-semantically-unreplayable.warrant.json
# Markdown SHA-256:   c0454d248211159b81e2d596e2f0e4867aeff0fed414dcb761b8d6bf55212151
# Code AST SHA-256:   6b2ca4cdbf332a61b9588ccb35c53cd05aa7fc92ac92badb93caec5c58865447
# Verified Classes:   UnreplayableDelegationError, Hop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnreplayableDelegationError(RuntimeError):
    """Raised when a hop's rationale cannot be reconstructed on a resume path
    and the proposed child scope would exceed the last replayable scope."""
    pass


@dataclass(frozen=True)
class Hop:
    token_scope: frozenset
    rationale_bytes: Optional[bytes]  # inline, content-addressed; None if evicted
    signature_valid: bool


def verify_chain(chain: list[Hop], proposed_child_scope: frozenset) -> frozenset:
    last_replayable_scope: Optional[frozenset] = None

    for i, hop in enumerate(chain):
        if not hop.signature_valid:
            raise UnreplayableDelegationError(
                f"hop {i}: signature invalid; chain untrusted"
            )

        replayable = hop.rationale_bytes is not None
        if replayable:
            last_replayable_scope = hop.token_scope
            continue

        # Unreplayable hop: we may hold the last replayable scope, never widen.
        if last_replayable_scope is None:
            # No prior replayable scope to anchor to; refuse to admit at all.
            raise UnreplayableDelegationError(
                f"hop {i}: unreplayable with no replayable ancestor; "
                f"cannot bound scope"
            )
        if not proposed_child_scope.issubset(last_replayable_scope):
            raise UnreplayableDelegationError(
                f"hop {i}: unreplayable rationale would permit child scope "
                f"{sorted(proposed_child_scope)} exceeding last replayable "
                f"scope {sorted(last_replayable_scope)}; "
                f"refusing to widen on uncertainty"
            )

    return last_replayable_scope if last_replayable_scope is not None else frozenset()


def admit(chain: list[Hop], proposed_child_scope: frozenset) -> frozenset:
    try:
        return verify_chain(chain, proposed_child_scope)
    except UnreplayableDelegationError:
        # Halt and escalate; never silently fall back to root scope.
        raise
