# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trust-broker-attenuation-from-silently-re-widening-on-federated-re-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trust-broker-attenuation-from-silently-re-widening-on-federated-re-delegation.warrant.json
# Markdown SHA-256:   a2a07dde67bd6380997ca22c352258890f9f9814746cb67a8d6abcaad0cf418f
# Code AST SHA-256:   8d8546f19f4e6b3d5cc6951cd5839ecb3875e225892ba1c85ec0df1ee61ca1bd
# Verified Classes:   WarrantAttenuationError, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantAttenuationError(RuntimeError):
    """Raised when a child warrant would exceed or drop constraints of its parent."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    scope: FrozenSet[str]
    caveats: FrozenSet[str]
    derived_from: str | None  # warrant_id of parent, or None for chain root


def attenuate(parent: Warrant | None, requested_scope: FrozenSet[str],
              requested_caveats: FrozenSet[str], new_id: str) -> Warrant:
    """
    Mint a child warrant. On a negotiate/re-delegate path the parent MUST be
    resolvable; falling back to root-policy issuance is the silent-widening bug.
    """
    if parent is None:
        # Requester authenticated but ancestor unknown: fail closed.
        raise WarrantAttenuationError(
            f"cannot mint {new_id}: no resolvable parent warrant on negotiate path; "
            "refusing root-policy fallback"
        )

    widened = requested_scope - parent.scope
    if widened:
        raise WarrantAttenuationError(
            f"scope widening on {new_id} vs parent {parent.warrant_id}: "
            f"requested-but-not-held={sorted(widened)}"
        )

    dropped_caveats = parent.caveats - requested_caveats
    if dropped_caveats:
        raise WarrantAttenuationError(
            f"caveat drop on {new_id} vs parent {parent.warrant_id}: "
            f"lost={sorted(dropped_caveats)}"
        )

    return Warrant(
        warrant_id=new_id,
        scope=requested_scope,
        caveats=requested_caveats | parent.caveats,  # inherit, never drop
        derived_from=parent.warrant_id,
    )


def handle_negotiate(parent: Warrant | None, requester_claims: dict,
                     new_id: str) -> Warrant:
    # requester_claims are unauthenticated wrt the ancestor chain; only the
    # parent bounds what may be granted.
    return attenuate(
        parent=parent,
        requested_scope=frozenset(requester_claims.get("scope", [])),
        requested_caveats=frozenset(requester_claims.get("caveats", [])),
        new_id=new_id,
    )
