# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-scope-narrowing-delegation-chain-that-is-cryptographically-valid-but-semantically-void.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-scope-narrowing-delegation-chain-that-is-cryptographically-valid-but-semantically-void.warrant.json
# Markdown SHA-256:   9d38747d10d00fbc58c3a1b5a932a5fa5cd830b8901650f6fd3abe590d9c2e09
# Code AST SHA-256:   23070945954a2c1ce4f31eb683e8b1f9f289fbd676566e165191f9c24deb1a14
# Verified Classes:   SemanticAttenuationError, CapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Mapping, Optional


class SemanticAttenuationError(RuntimeError):
    """Raised when a delegation chain is cryptographically valid but semantically void."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    scope: FrozenSet[str]
    max_delegation_depth: int
    remaining_depth: int
    parent_jti: Optional[str]


def attenuate(
    parent: CapabilityToken,
    requested_scope: FrozenSet[str],
    manifest: Mapping[str, FrozenSet[str]],
) -> CapabilityToken:
    # 1. Subset check (cryptographic-equivalent layer).
    if not requested_scope.issubset(parent.scope):
        raise SemanticAttenuationError(
            f"scope {requested_scope} is not a subset of parent {parent.scope}"
        )

    # 2. Co-requisite closure check: every retained capability must keep
    #    the resource-required closure inside the child scope.
    for cap in requested_scope:
        if cap not in manifest:
            raise SemanticAttenuationError(
                f"co-requisite closure for {cap!r} unknown; refusing to attenuate"
            )
        closure = manifest[cap]
        stranded = closure - requested_scope
        if stranded:
            raise SemanticAttenuationError(
                f"capability {cap!r} retains co-requisite {stranded} outside child scope"
            )

    # 3. Monotone depth narrowing: use min(declared, remaining), not declared.
    effective_parent_depth = min(parent.max_delegation_depth, parent.remaining_depth)
    child_depth = effective_parent_depth - 1
    if child_depth < 0:
        raise SemanticAttenuationError(
            f"delegation depth exhausted: parent effective depth {effective_parent_depth}"
        )

    return CapabilityToken(
        scope=requested_scope,
        max_delegation_depth=child_depth,
        remaining_depth=child_depth,
        parent_jti=id(parent),
    )
