# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-scopes-a-delegated-capability-token-mid-chain-attenuation-graph-aliasing-and-the-silent-privilege-laundering-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-scopes-a-delegated-capability-token-mid-chain-attenuation-graph-aliasing-and-the-silent-privilege-laundering-failure.warrant.json
# Markdown SHA-256:   b76a874839eb18c69f94ac1cf141fc73a0fa841e199293696d05facc87d9aabb
# Code AST SHA-256:   2497332b33b48eb5949a6d3aca6ea68a54af54613000a425250a917887119cea
# Verified Classes:   AttenuationViolation, StaleParentAlias, Scope, CapabilityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AttenuationViolation(RuntimeError):
    """Raised when a delegated child token is not a joint subset of its live parent."""
    pass


class StaleParentAlias(AttenuationViolation):
    """Raised when a child token was attenuated against a cached/ancestor scope, not the live parent."""
    pass


@dataclass(frozen=True)
class Scope:
    resource: frozenset
    verb: frozenset
    region: frozenset

    def scope_hash(self) -> str:
        payload = "|".join([
            ",".join(sorted(self.resource)),
            ",".join(sorted(self.verb)),
            ",".join(sorted(self.region)),
        ])
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    scope: Scope
    parent_scope_hash: str


def _materialize(child: Scope, parent: Scope) -> Scope:
    # Omission inherits the parent's most restrictive value, never wildcard.
    return Scope(
        resource=child.resource if child.resource else parent.resource,
        verb=child.verb if child.verb else parent.verb,
        region=child.region if child.region else parent.region,
    )


def verify_attenuation(child: CapabilityToken, live_parent: CapabilityToken, chain_store: dict) -> None:
    # 1. Parent must be the live signed token from the chain store, not a cached copy.
    stored = chain_store.get(live_parent.token_id)
    if stored is None or stored.scope.scope_hash() != live_parent.scope.scope_hash():
        raise StaleParentAlias(
            f"parent {live_parent.token_id} not resolvable to live signed scope in chain store"
        )

    # 2. Child must be bound to this exact parent scope.
    if child.parent_scope_hash != live_parent.scope.scope_hash():
        raise StaleParentAlias(
            f"child {child.token_id} attenuated against scope hash "
            f"{child.parent_scope_hash[:12]}, live parent is "
            f"{live_parent.scope.scope_hash()[:12]}"
        )

    # 3. Joint subset check across the full constraint product.
    effective = _materialize(child.scope, live_parent.scope)
    for dim in ("resource", "verb", "region"):
        child_set = getattr(effective, dim)
        parent_set = getattr(live_parent.scope, dim)
        widened = child_set - parent_set
        if widened:
            raise AttenuationViolation(
                f"child {child.token_id} widens dimension '{dim}' "
                f"beyond parent {live_parent.token_id}: {sorted(widened)}"
            )


def delegate(orch: CapabilityToken, child_id: str, requested: Scope,
             chain_store: dict) -> CapabilityToken:
    token = CapabilityToken(
        token_id=child_id,
        scope=requested,
        parent_scope_hash=orch.scope.scope_hash(),
    )
    verify_attenuation(token, orch, chain_store)
    chain_store[child_id] = token
    return token
