# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-delegation-chain-has-silently-widened-instead-of-narrowed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-delegation-chain-has-silently-widened-instead-of-narrowed.warrant.json
# Markdown SHA-256:   bba37bf4befe687a4f0cc25c4bb377ef9cdb6c331cb64a662740b55b447e99f8
# Code AST SHA-256:   c20cc86cecbcf8cd3f45e9916e5624717a45cb1ab52e5914932188bc70adc0d0
# Verified Classes:   AttenuationWidenedError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AttenuationWidenedError(RuntimeError):
    """Raised when a child's effective scope set exceeds its declared set
    or escapes its parent's effective set during AAIF chain verification."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_id: str | None
    parent_digest: str | None
    declared_allow: frozenset[str]
    declared_deny: frozenset[str]

    def digest(self) -> str:
        body = "|".join(
            [
                self.warrant_id,
                self.parent_id or "",
                self.parent_digest or "",
                ",".join(sorted(self.declared_allow)),
                ",".join(sorted(self.declared_deny)),
            ]
        )
        return hashlib.sha256(body.encode()).hexdigest()


def _resolve(token: str, namespace: frozenset[str]) -> frozenset[str]:
    """Resolve a scope token to concrete capabilities within a namespace.
    Fail-closed: an unresolvable token yields the empty set, never the
    full namespace."""
    if token in namespace:
        return frozenset({token})
    if token.endswith("*"):
        prefix = token[:-1]
        matched = frozenset(c for c in namespace if c.startswith(prefix))
        return matched  # empty if nothing matches; never fail-open
    return frozenset()


def effective_scope(
    warrant: Warrant,
    parent: Warrant | None,
    namespace: frozenset[str],
    max_hops: int = 8,
    _depth: int = 0,
) -> frozenset[str]:
    if _depth > max_hops:
        raise AttenuationWidenedError(
            f"delegation depth exceeded {max_hops} at {warrant.warrant_id}"
        )

    declared = frozenset().union(
        *(_resolve(t, namespace) for t in warrant.declared_allow)
    )

    if parent is None:
        if warrant.parent_id is not None:
            raise AttenuationWidenedError(
                f"{warrant.warrant_id} references missing parent "
                f"{warrant.parent_id}; cannot establish attenuation"
            )
        return declared - frozenset().union(
            *(_resolve(t, namespace) for t in warrant.declared_deny)
        )

    if warrant.parent_digest != parent.digest():
        raise AttenuationWidenedError(
            f"{warrant.warrant_id} parent digest mismatch: minted against "
            f"{warrant.parent_digest}, current parent is {parent.digest()}"
        )

    parent_effective = effective_scope(
        parent, None, namespace, max_hops, _depth + 1
    )

    deny = frozenset().union(
        *(_resolve(t, namespace) for t in warrant.declared_deny)
    )

    # Correct form: (declared ∩ parent_effective) − deny.
    # The common bug is (defaults ∪ parent_effective) − deny, which widens.
    narrowed = (declared & parent_effective) - deny

    if not narrowed.issubset(parent_effective):
        raise AttenuationWidenedError(
            f"{warrant.warrant_id} escaped parent {parent.warrant_id}: "
            f"{sorted(narrowed - parent_effective)}"
        )
    if len(narrowed) > len(declared):
        raise AttenuationWidenedError(
            f"{warrant.warrant_id} effective cardinality {len(narrowed)} "
            f"exceeds declared {len(declared)}"
        )
    return narrowed


def verify_chain(
    chain: list[Warrant], namespace: frozenset[str]
) -> frozenset[str]:
    """Verify a full O -> P -> W -> S chain, each hop against its exact
    parent, returning the leaf's effective scope or raising."""
    if not chain:
        raise AttenuationWidenedError("empty delegation chain")
    by_id = {w.warrant_id: w for w in chain}
    leaf = chain[-1]
    parent = by_id.get(leaf.parent_id) if leaf.parent_id else None
    return effective_scope(leaf, parent, namespace)
