# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-privilege-re-expansion-when-a-delegated-agent-mints-attenuated-capability-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-privilege-re-expansion-when-a-delegated-agent-mints-attenuated-capability-tokens.warrant.json
# Markdown SHA-256:   43c4cc903384a3720b7b5d27848206b59e0c85740cc6153fd80df292f49c079a
# Code AST SHA-256:   6b42a3051e8f3a96dd2105177081a2683925a1f641a16e984a371edab243be45
# Verified Classes:   AttenuationInvariantError, CapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AttenuationInvariantError(RuntimeError):
    """Raised when a delegated capability token's effective scope is not a
    live-checked subset of every ancestor's enforced scope."""
    pass


@dataclass
class CapabilityToken:
    token_id: str
    parent_id: str | None
    declared_scope: frozenset[str]      # what the mint path *thought* it granted
    enforced_scope: frozenset[str]      # what the caveat chain actually grants
    parent_state_hash: str | None       # hash of parent enforced set at mint time
    ttl_s: int


def mint_attenuated(parent: CapabilityToken,
                    requested: frozenset[str],
                    live_parent_enforced: frozenset[str]) -> CapabilityToken:
    """Mint a child token whose scope is a subset of the parent's *live* enforced set.

    The invariant: enforced(child) == live_parent_enforced & requested, and the
    result must equal `requested` exactly. Any widening is a re-expansion bug.
    """
    effective = live_parent_enforced & requested
    if effective != requested:
        raise AttenuationInvariantError(
            f"requested scope {sorted(requested)} exceeds live parent enforced "
            f"scope {sorted(live_parent_enforced)}; widening rejected"
        )
    # Bind the child to the parent's *live* state, not a stale snapshot.
    parent_hash = hashlib.sha256(
        ",".join(sorted(live_parent_enforced)).encode()
    ).hexdigest()
    return CapabilityToken(
        token_id=f"{parent.token_id}::child",
        parent_id=parent.token_id,
        declared_scope=requested,        # derived from the chain, never a snapshot
        enforced_scope=effective,
        parent_state_hash=parent_hash,
        ttl_s=min(parent.ttl_s, 3600),
    )


def verify_chain(token: CapabilityToken,
                 live_ancestor_enforced: dict[str, frozenset[str]]) -> None:
    """Re-check the token against current ancestor state before honoring it."""
    if token.parent_id is not None:
        if token.parent_id not in live_ancestor_enforced:
            raise AttenuationInvariantError(
                f"ancestor {token.parent_id} not resolvable; cannot confirm subset"
            )
        ancestor_live = live_ancestor_enforced[token.parent_id]
        if not token.enforced_scope <= ancestor_live:
            raise AttenuationInvariantError(
                f"token {token.token_id} scope {sorted(token.enforced_scope)} "
                f"is not a subset of live ancestor scope {sorted(ancestor_live)}; "
                f"privilege re-expansion detected"
            )
    if token.declared_scope != token.enforced_scope:
        raise AttenuationInvariantError(
            f"token {token.token_id} declared/enforced scope divergence: "
            f"declared={sorted(token.declared_scope)} "
            f"enforced={sorted(token.enforced_scope)}"
        )
