# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-chain-scope-attenuation-collapse-under-re-delegation-depth-in-aaif-token-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-chain-scope-attenuation-collapse-under-re-delegation-depth-in-aaif-token-exchange.warrant.json
# Markdown SHA-256:   9c62a96e46a1bf0e8ef069c888c9cfc9a3d4e578b8b6315fc932022eabf53f22
# Code AST SHA-256:   b0d4d18fc8a96330ae93c74ea09c245c9a23485d03fcee04570fd57f132c04ee
# Verified Classes:   DelegationRefused, ScopeAtom, Credential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional


class DelegationRefused(RuntimeError):
    """Raised when a delegating instance cannot preserve scope interpretation
    across a hop and must refuse to issue a child credential."""


@dataclass(frozen=True)
class ScopeAtom:
    kind: str          # e.g. "path", "repo", "action"
    value: str         # canonical form
    regime: str        # interpretation regime tag, e.g. "lexical-prefix", "resolved-subtree"

    def canonical(self) -> "ScopeAtom":
        # Canonicalization must be total; unknown kinds are not silently passed.
        if self.kind == "path":
            # Reject atoms that cannot be canonicalized without a regime.
            if ".." in self.value.split("/"):
                raise DelegationRefused(
                    f"path atom {self.value!r} contains '..'; canonical form "
                    f"requires a resolution regime and cannot be delegated opaquely"
                )
            return ScopeAtom("path", self.value.rstrip("/"), self.regime)
        if self.kind in ("repo", "action"):
            return ScopeAtom(self.kind, self.value.lower(), self.regime)
        raise DelegationRefused(f"unknown scope atom kind {self.kind!r}")


@dataclass(frozen=True)
class Credential:
    subject: str
    atoms: FrozenSet[ScopeAtom]
    parent_hash: Optional[str]
    signature: str


def delegate(parent: Credential, child_subject: str,
             narrowed: FrozenSet[ScopeAtom]) -> Credential:
    """Issue a child credential only if attenuation is sound under the
    canonicalization + regime-binding + closed-world invariants."""

    canon_parent = frozenset(a.canonical() for a in parent.atoms)
    canon_child = frozenset(a.canonical() for a in narrowed)

    # Invariant 1: set containment over canonical atoms.
    if not canon_child <= canon_parent:
        extra = canon_child - canon_parent
        raise DelegationRefused(
            f"child scope not a subset of parent; extra atoms: {extra!r}"
        )

    # Invariant 2: every child atom must share its parent's regime, or the
    # child must be a strict refinement that the verifier can honor.
    parent_regimes = {a.kind: a.regime for a in canon_parent}
    for atom in canon_child:
        parent_regime = parent_regimes.get(atom.kind)
        if parent_regime is None:
            raise DelegationRefused(
                f"child atom kind {atom.kind!r} absent from parent; "
                f"cannot bind interpretation"
            )
        if atom.regime != parent_regime:
            raise DelegationRefused(
                f"regime divergence on {atom.kind!r}: parent={parent_regime!r} "
                f"child={atom.regime!r}; refusing cross-regime delegation — "
                f"request a fresh root credential for regime {atom.regime!r}"
            )

    # Invariant 3: child claim set is closed-world; no parent atoms are
    # merged in at resolution time. Encoded here as: the child carries
    # exactly canon_child, nothing inherited.
    return Credential(
        subject=child_subject,
        atoms=canon_child,
        parent_hash=hash(frozenset(canon_parent)),
        signature=f"sig({child_subject})",
    )


def verify_chain(leaf: Credential, root: Credential) -> bool:
    """Resolution-time check: reject any chain whose hops disagree on regime."""
    seen = {root}
    current = leaf
    while current.parent_hash is not None:
        parent = next((c for c in seen if hash(frozenset(
            a.canonical() for a in c.atoms)) == current.parent_hash), None)
        if parent is None:
            raise DelegationRefused(
                f"broken parent link at subject {current.subject!r}"
            )
        parent_regimes = {a.kind: a.regime for a in parent.atoms}
        for atom in current.atoms:
            if parent_regimes.get(atom.kind) != atom.regime:
                raise DelegationRefused(
                    f"regime mismatch resolving {current.subject!r} against "
                    f"{parent.subject!r} on {atom.kind!r}"
                )
        seen.add(parent)
        current = parent
    return True
