# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-delegate-an-attenuated-capability-token-whose-attenuation-chain-has-been-flattened-by-a-lossy-serializ.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-delegate-an-attenuated-capability-token-whose-attenuation-chain-has-been-flattened-by-a-lossy-serializ.warrant.json
# Markdown SHA-256:   e41fae05856b87883da5698e20d062a85ce2874d721cf09f87db89ef35e42205
# Code AST SHA-256:   877c88cc58b7fcfcf235af28dd8329d2c5f8b9e3eb0194ec8fa08496f2a98522
# Verified Classes:   DelegationProofError, Derivation, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, List, Optional, Tuple


class DelegationProofError(RuntimeError):
    """Raised when a token cannot be proven a lower bound of its root
    without trusting an intermediate flattener. Re-delegation must stop."""


@dataclass(frozen=True)
class Derivation:
    parent_id: str
    meet_ops: Tuple[str, ...]
    deny_set: FrozenSet[str]


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    scopes: FrozenSet[str]
    deny: FrozenSet[str]
    derivation: Optional[List[Derivation]] = None  # None => flattened

    def is_provable(self) -> bool:
        return self.derivation is not None and len(self.derivation) > 0


def attenuate_for_subtask(
    parent: CapabilityToken,
    requested: FrozenSet[str],
    hops_from_root: int,
) -> CapabilityToken:
    """Attenuate `parent` down to `requested` for a new sub-agent.

    Refuses when the parent is flattened and has crossed an intermediate
    agent, because the true deny set has been lost and any new token we
    mint would be an unprovable (possibly widening) derivation.
    """
    if not parent.is_provable():
        if hops_from_root > 1:
            raise DelegationProofError(
                f"token {parent.token_id} is flattened and {hops_from_root} "
                f"hops from root; deny set unverifiable, refusing to "
                f"re-delegate scopes={sorted(requested)}"
            )
        # Single hop from root: materialized scopes ARE the lattice.
        effective_deny = parent.deny
        new_derivation = [Derivation(parent.token_id, tuple(sorted(requested)), effective_deny)]
    else:
        # Fail closed: absent deny is deny-all, never deny-none.
        effective_deny = parent.deny if parent.deny else frozenset({"*"})
        new_derivation = list(parent.derivation) + [
            Derivation(parent.token_id, tuple(sorted(requested)), effective_deny)
        ]

    # Meet must not exceed parent scopes.
    if not requested.issubset(parent.scopes):
        raise DelegationProofError(
            f"requested {sorted(requested)} not a subset of parent "
            f"{sorted(parent.scopes)} for token {parent.token_id}"
        )

    return CapabilityToken(
        token_id=f"{parent.token_id}/sub",
        scopes=requested,
        deny=effective_deny,
        derivation=new_derivation,
    )


def verify_containment(leaf: CapabilityToken, root: CapabilityToken) -> None:
    """End-to-end check that must not use a shared flattened view."""
    if not leaf.is_provable():
        raise DelegationProofError(
            f"leaf {leaf.token_id} carries no derivation; containment "
            f"against root {root.token_id} is unverifiable"
        )
    if not leaf.scopes.issubset(root.scopes):
        raise DelegationProofError(
            f"leaf scopes {sorted(leaf.scopes)} escape root {sorted(root.scopes)}"
        )
    if not root.deny.issubset(leaf.deny):
        raise DelegationProofError(
            f"leaf dropped root deny clauses: missing "
            f"{sorted(root.deny - leaf.deny)}"
        )
