# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-delegated-scope-token-exchange-when-the-aaif-delegation-chain-contains-a-scope-narrowing-hop-that-is-non-monotonic.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-delegated-scope-token-exchange-when-the-aaif-delegation-chain-contains-a-scope-narrowing-hop-that-is-non-monotonic.warrant.json
# Markdown SHA-256:   9c7e201bfdb540edfd7a20e2ff6cf93ad14258358d5d6fe9088c055337837abb
# Code AST SHA-256:   71f7ad665926a7119a5589600a2b7347962785b3a90c956a1d1e35c2bb86b747
# Verified Classes:   ScopeRebindingError, DelegatedToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeRebindingError(RuntimeError):
    """Raised when a delegated-scope exchange narrows the scope set but
    re-binds a surviving scope to a different resource namespace.

    This is the AAIF impersonation vector: set-cardinality validation
    passes, but the surviving scope now resolves against a namespace the
    subject was never granted.
    """


@dataclass(frozen=True)
class DelegatedToken:
    scopes: FrozenSet[str]
    # scope -> namespace binding, signed by the exchange endpoint
    bindings: dict
    subject: str
    actor: str


def validate_exchange(inbound: DelegatedToken, outbound: DelegatedToken) -> None:
    """Enforce C1 (set monotonicity) and C2 (namespace invariance).

    Fails closed on any unverifiable binding. Never falls back to
    literal string-set comparison alone.
    """
    # C1: effective scope set must narrow.
    if not outbound.scopes.issubset(inbound.scopes):
        raise ScopeRebindingError(
            f"widening hop: outbound {outbound.scopes} not subset of "
            f"inbound {inbound.scopes}"
        )

    # C2: every surviving scope must keep its exact namespace binding.
    for scope in outbound.scopes:
        out_bind = outbound.bindings.get(scope)
        in_bind = inbound.bindings.get(scope)

        if out_bind is None:
            # Missing binding claim => unverifiable => fail closed.
            raise ScopeRebindingError(
                f"unverifiable hop: scope {scope!r} carries no signed "
                f"namespace_binding on outbound token"
            )
        if in_bind is None:
            raise ScopeRebindingError(
                f"unverifiable hop: scope {scope!r} had no namespace_binding "
                f"on inbound token; cannot prove invariance"
            )
        if out_bind != in_bind:
            # The impersonation vector: same scope string, new namespace.
            raise ScopeRebindingError(
                f"rebinding hop: scope {scope!r} re-bound from "
                f"{in_bind!r} to {out_bind!r} across exchange "
                f"(actor={outbound.actor!r}, subject={outbound.subject!r})"
            )


def exchange_for_subagent(
    inbound: DelegatedToken, outbound: DelegatedToken
) -> DelegatedToken:
    validate_exchange(inbound, outbound)
    return outbound


# Reproduces the observed failure:
# hop 1 -> {read:calendar, read:contacts, write:notes} bound to acme
# hop 2 -> {read:calendar} bound to '*' (principal remap)
if __name__ == "__main__":
    hop1 = DelegatedToken(
        scopes=frozenset({"read:calendar", "read:contacts", "write:notes"}),
        bindings={
            "read:calendar": "acme/calendars/*",
            "read:contacts": "acme/contacts/*",
            "write:notes": "acme/notes/*",
        },
        subject="user:alice",
        actor="agent:orchestrator",
    )
    hop2 = DelegatedToken(
        scopes=frozenset({"read:calendar"}),
        bindings={"read:calendar": "*/calendars/*"},
        subject="agent:orchestrator",
        actor="agent:summarizer",
    )
    exchange_for_subagent(hop1, hop2)  # raises ScopeRebindingError
