# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-surviving-scope-narrowing-re-issuance-when-attenuation-is-monotone-only-on-the-issuer-s-latt.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-surviving-scope-narrowing-re-issuance-when-attenuation-is-monotone-only-on-the-issuer-s-latt.warrant.json
# Markdown SHA-256:   2c78623c480538c7121d2f227b2d51a74a045c8daed2f1f116818d90042cd707
# Code AST SHA-256:   43bcddcd5654da884c1765e734bf16187fe6287f56341dd4fff2159cc3e651c5
# Verified Classes:   LatticeSkewError, CapabilityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class LatticeSkewError(RuntimeError):
    """Raised when a delegated token cannot be proven narrower than its parent
    because the two are interpreted under different scope lattices without a
    signed translation."""


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    scope: FrozenSet[str]
    lattice_version: str
    parent: Optional["CapabilityToken"] = None
    translation: Optional[dict] = None  # child_symbol -> parent_symbol


KNOWN_SCOPES = {
    "v1": {"read:*", "write:docs"},
    "v2": {"read:docs", "read:config", "read:secrets", "write:docs"},
}


def _expand(scope: FrozenSet[str], lattice: str) -> FrozenSet[str]:
    """Closed-world expansion: unknown symbols are an error, never vacuous."""
    known = KNOWN_SCOPES[lattice]
    out = set()
    for sym in scope:
        if sym not in known:
            raise LatticeSkewError(
                f"scope symbol {sym!r} unknown to lattice {lattice!r}"
            )
        out.add(sym)
    return frozenset(out)


def reissue(parent: CapabilityToken, child_scope: FrozenSet[str],
            child_lattice: str) -> CapabilityToken:
    """Mint a narrowed child token, or refuse. Refusal is the safe default."""
    if child_lattice != parent.lattice_version:
        if parent.translation is None:
            raise LatticeSkewError(
                f"lattice skew {parent.lattice_version!r} -> {child_lattice!r} "
                f"with no signed translation; refusing to compare"
            )
        mapped = frozenset(
            parent.translation.get(s, s) for s in child_scope
        )
    else:
        mapped = child_scope

    parent_eff = _expand(parent.scope, parent.lattice_version)
    child_eff = _expand(mapped, parent.lattice_version)

    if not child_eff.issubset(parent_eff):
        raise LatticeSkewError(
            f"attenuation violation: {sorted(child_eff)} not subset of "
            f"{sorted(parent_eff)} under {parent.lattice_version!r}"
        )

    return CapabilityToken(
        subject="child",
        scope=child_scope,
        lattice_version=child_lattice,
        parent=parent,
        translation=parent.translation,
    )
