# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-at-the-second-federation-hop-when-policy-negotiation-succeeds-at-the-first.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-at-the-second-federation-hop-when-policy-negotiation-succeeds-at-the-first.warrant.json
# Markdown SHA-256:   2d0fb57abcb69900e21d30fa7990ee59db9a97a2d1197d4cc4a9ddc3daac97d1
# Code AST SHA-256:   d2679bf29f7b9ff9ed02a9af389a668aa02a8e2ff6852c73c38c61a7e00d5137
# Verified Classes:   DelegationScopeViolation, Warrant, Session
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class DelegationScopeViolation(RuntimeError):
    """Raised when a downstream negotiation requests scope outside the inbound warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    audience: str
    scope: frozenset[str]
    delegation_depth: int
    max_calls: int


@dataclass
class Session:
    chain_id: str
    effective_scope: frozenset[str]
    remaining_calls: int
    depth_remaining: int


def negotiate_downstream(
    inbound: Warrant,
    requested_scope: Sequence[str],
    grantor_policy: frozenset[str],
    chain_id: str,
) -> Session:
    """Grantor enforces subset-of-warrant at negotiation time, not execution time."""
    requested = frozenset(requested_scope)

    # Invariant: requested scope must be a subset of the presented warrant's scope.
    overreach = requested - inbound.scope
    if overreach:
        raise DelegationScopeViolation(
            f"chain={chain_id} requested={sorted(overreach)} "
            f"exceeds warrant.scope={sorted(inbound.scope)}"
        )

    if inbound.delegation_depth < 1:
        raise DelegationScopeViolation(
            f"chain={chain_id} delegation_depth exhausted; cannot sub-delegate"
        )

    # Effective scope is intersection, never union with local policy.
    effective = requested & grantor_policy & inbound.scope
    if effective != requested:
        raise DelegationScopeViolation(
            f"chain={chain_id} grantor_policy excludes {sorted(requested - effective)}"
        )

    return Session(
        chain_id=chain_id,
        effective_scope=effective,
        remaining_calls=inbound.max_calls,
        depth_remaining=inbound.delegation_depth - 1,
    )
