# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-aaif-credential-scope-escalation-during-delegated-agent-re-signing.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-aaif-credential-scope-escalation-during-delegated-agent-re-signing.warrant.json
# Markdown SHA-256:   5d4df6b4c32bf3551c011586793d0a1944506f875154596cc1a0ada687fe4f7a
# Code AST SHA-256:   322050ecba5fdf95ab1a6eb63d2e1ed2fa55019652642ee7629db6fefc91f6cf
# Verified Classes:   ScopeAttenuationViolation, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping, Sequence


class ScopeAttenuationViolation(RuntimeError):
    """Raised when a child warrant's scope does not lattice-contain within its parent's
    scope under the resolving verifier's registry view."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    scope: Sequence[str]
    registry_digest: str


def resolve(scope: Sequence[str], registry: Mapping[str, frozenset[str]]) -> frozenset[str]:
    """Expand scope elements to concrete lattice leaves under a given registry view."""
    leaves: set[str] = set()
    for element in scope:
        if element not in registry:
            raise ScopeAttenuationViolation(
                f"scope element {element!r} not resolvable in registry"
            )
        leaves |= registry[element]
    return frozenset(leaves)


def verify_attenuation(
    parent: Warrant,
    child: Warrant,
    verifier_registry: Mapping[str, frozenset[str]],
    verifier_digest: str,
) -> None:
    if parent.registry_digest != verifier_digest or child.registry_digest != verifier_digest:
        raise ScopeAttenuationViolation(
            f"registry skew: chain digests {parent.registry_digest!r}/{child.registry_digest!r} "
            f"!= verifier {verifier_digest!r}"
        )
    parent_leaves = resolve(parent.scope, verifier_registry)
    child_leaves = resolve(child.scope, verifier_registry)
    if not child_leaves <= parent_leaves:
        escaped = child_leaves - parent_leaves
        raise ScopeAttenuationViolation(
            f"child scope escapes parent under verifier lattice: {sorted(escaped)}"
        )


def re_sign(
    delegator: str,
    parent: Warrant,
    child_scope: Sequence[str],
    verifier_registry: Mapping[str, frozenset[str]],
    verifier_digest: str,
) -> Warrant:
    child = Warrant(
        issuer=delegator,
        scope=tuple(child_scope),
        registry_digest=verifier_digest,
    )
    # Enforce attenuation at the re-signing hop, not only at the terminal verifier.
    verify_attenuation(parent, child, verifier_registry, verifier_digest)
    return child
