# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-aaif-delegation-chain-verification-as-a-stateful-reachability-problem-rather-than-a-per-hop-signature-che.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-aaif-delegation-chain-verification-as-a-stateful-reachability-problem-rather-than-a-per-hop-signature-che.warrant.json
# Markdown SHA-256:   bbdde52a285371f798509b27e713e4f5eab924bae863f019a91d68a22f24b2df
# Code AST SHA-256:   4ee7516ab7112f97a4e6dc5aa38c57fe6fbfddb143d3b354940b9f63382b834f
# Verified Classes:   AAIFChainViolation, AAIFToken
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AAIFChainViolation(RuntimeError):
    """Raised when an AAIF delegation chain composes to an unauthorized subject."""
    pass


@dataclass(frozen=True)
class AAIFToken:
    iss: str
    sub: str
    scope: frozenset
    may_act: frozenset
    cnf_key: Optional[str] = None


def compose_chain(root: str, tokens: list[AAIFToken]) -> frozenset:
    """
    Model-check a single AAIF chain from `root` to a leaf.
    Returns the composed scope (intersection of scope and may_act along the path).
    Raises AAIFChainViolation if the chain is ambiguous, re-rooted, or non-monotone.
    """
    if not tokens:
        raise AAIFChainViolation("empty delegation chain")

    # Invariant 4: no re-rooting; chain must be a single path from root.
    by_iss = {}
    for t in tokens:
        if t.iss in by_iss:
            # Invariant 1: parallel delegation into the same context is ambiguous.
            raise AAIFChainViolation(
                f"ambiguous delegation: multiple tokens issued by {t.iss!r}"
            )
        by_iss[t.iss] = t

    if root not in by_iss:
        raise AAIFChainViolation(f"no token issued by root {root!r}")

    composed = by_iss[root].scope & by_iss[root].may_act
    current = root
    seen = {root}

    while True:
        tok = by_iss[current]
        # Invariant 2: may_act is the delegation ceiling, not scope.
        if not tok.may_act <= tok.scope:
            raise AAIFChainViolation(
                f"may_act exceeds scope at {current!r}: "
                f"{sorted(tok.may_act)} ⊄ {sorted(tok.scope)}"
            )
        # Invariant 3: monotone narrowing.
        if not tok.scope <= composed:
            raise AAIFChainViolation(
                f"scope re-widening at {current!r}: "
                f"{sorted(tok.scope)} ⊄ {sorted(composed)}"
            )
        composed = composed & tok.scope & tok.may_act

        # Find the next hop: the token whose iss is this token's sub.
        nxt = by_iss.get(tok.sub)
        if nxt is None:
            break
        if nxt.iss in seen:
            raise AAIFChainViolation(f"cycle detected at {nxt.iss!r}")
        # Invariant 4: next hop must be issued by the current subject.
        if nxt.iss != tok.sub:
            raise AAIFChainViolation(
                f"re-rooting: {nxt.iss!r} is not subject of {current!r}"
            )
        # Key-substitution guard: cnf must bind to the signing key of the next hop.
        if nxt.cnf_key is not None and nxt.cnf_key != tok.sub:
            raise AAIFChainViolation(
                f"cnf key substitution at {nxt.iss!r}: "
                f"bound to {nxt.cnf_key!r}, expected {tok.sub!r}"
            )
        seen.add(nxt.iss)
        current = nxt.iss

    return composed


def open_mcp_session(root: str, tokens: list[AAIFToken], requested: frozenset) -> frozenset:
    composed = compose_chain(root, tokens)
    if not requested <= composed:
        raise AAIFChainViolation(
            f"MCP session scope escalation: requested {sorted(requested)} "
            f"not within composed {sorted(composed)}"
        )
    return composed
