# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-capability-advertisements-against-attenuated-aaif-scopes-when-a-delegate-silently-widens-privilege-through-transitive.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-capability-advertisements-against-attenuated-aaif-scopes-when-a-delegate-silently-widens-privilege-through-transitive.warrant.json
# Markdown SHA-256:   6bfbdf9059abeef606c21c46bbe8dc9041ea52b19936e0a7979ee3b189f1fc39
# Code AST SHA-256:   62c20490d03e60ef2880924aa97615c0ec351505b563232299cbd0dab37c9e49
# Verified Classes:   TransitiveScopeWidening, ScopeInsufficient, ScopeToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TransitiveScopeWidening(RuntimeError):
    """Raised when a child delegation token is not a subset of every ancestor scope."""
    pass


class ScopeInsufficient(RuntimeError):
    """Raised when a required capability is outside the inherited delegation scope."""
    pass


@dataclass(frozen=True)
class ScopeToken:
    scopes: FrozenSet[str]
    origin: str
    # Full ancestor chain, nearest-first. Empty for a root token.
    lineage: tuple = field(default_factory=tuple)

    def attenuate(self, requested: FrozenSet[str]) -> "ScopeToken":
        """Mint a child token. Attenuates against THIS token's scopes,
        never against any broader provisioned identity."""
        granted = self.scopes & requested
        return ScopeToken(
            scopes=granted,
            origin=self.origin,
            lineage=(self,) + self.lineage,
        )


def mint_delegation(parent: ScopeToken, peer_manifest: FrozenSet[str],
                    needed: FrozenSet[str]) -> ScopeToken:
    """Mint a delegation token for a discovered peer.

    Invariant: child.scopes must be a subset of EVERY ancestor's scopes,
    not merely the immediate parent's. A peer manifest is advisory only.
    """
    # Capability gap must fail closed at the delegator, not be re-discovered.
    if not needed <= parent.scopes:
        missing = needed - parent.scopes
        raise ScopeInsufficient(
            f"needed capabilities {sorted(missing)} are outside inherited "
            f"scope {sorted(parent.scopes)}; escalate to origin "
            f"'{parent.origin}' rather than re-discovering a broader peer"
        )

    child = parent.attenuate(needed & peer_manifest)

    # Enforce the lineage invariant across the FULL ancestor chain.
    for ancestor in child.lineage:
        if not child.scopes <= ancestor.scopes:
            widened = child.scopes - ancestor.scopes
            raise TransitiveScopeWidening(
                f"child scope {sorted(child.scopes)} exceeds ancestor "
                f"scope {sorted(ancestor.scopes)} by {sorted(widened)}; "
                f"origin '{child.origin}' never held {sorted(widened)}"
            )
    return child


def check_ledger_row(origin_scope: ScopeToken, action_scope: FrozenSet[str]) -> None:
    """Post-hoc detector: any action attributed to an origin must fall
    within that origin's scope. Violation = widening event, page it."""
    if not action_scope <= origin_scope.scopes:
        raise TransitiveScopeWidening(
            f"action scope {sorted(action_scope)} attributed to origin "
            f"'{origin_scope.origin}' exceeds its grant "
            f"{sorted(origin_scope.scopes)}"
        )
