# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-credential-scopes-from-silently-widening-across-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-credential-scopes-from-silently-widening-across-agent-hops.warrant.json
# Markdown SHA-256:   1a715b0bd607ad71e4789f088b89bd962644df45d1ea5c37463168a2019ad2a5
# Code AST SHA-256:   5796c9e5804e479ca96390de77f44618cdcac23f1edd1acebc87e88d4195b8ef
# Verified Classes:   ScopeAttenuationError, RegistrySnapshot, DelegatedToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeAttenuationError(RuntimeError):
    """Raised when a delegated token's effective scope cannot be proven to be
    a subset of its parent's scope under a shared registry snapshot."""


@dataclass(frozen=True)
class RegistrySnapshot:
    digest: str
    # namespace -> set of fully-qualified capability identifiers
    capabilities: dict


@dataclass(frozen=True)
class DelegatedToken:
    scope_verb: str
    resource_pattern: str
    parent_scope: FrozenSet[str]
    registry_digest: str


def resolve(snapshot: RegistrySnapshot, verb: str, pattern: str) -> FrozenSet[str]:
    """Resolve a (verb, pattern) pair against a registry snapshot.
    Deliberately conservative: exact-prefix match only, no implicit verb subsumption."""
    prefix = pattern.rstrip("*").rstrip("/")
    out = set()
    for ns, caps in snapshot.capabilities.items():
        for cap in caps:
            if cap.startswith(prefix + "/") or cap == prefix:
                if cap.split("/")[-1] == verb:
                    out.add(cap)
    return frozenset(out)


def verify_attenuation(
    token: DelegatedToken,
    issuer_snapshot: RegistrySnapshot,
    delegate_snapshot: RegistrySnapshot,
) -> FrozenSet[str]:
    """Prove delegate-resolved scope is a subset of issuer-resolved scope,
    and that both resolve against the same registry bytes."""
    if token.registry_digest != issuer_snapshot.digest:
        raise ScopeAttenuationError(
            f"token registry_digest {token.registry_digest!r} does not match "
            f"issuer snapshot {issuer_snapshot.digest!r}; attenuation unprovable"
        )
    if delegate_snapshot.digest != issuer_snapshot.digest:
        raise ScopeAttenuationError(
            f"delegate registry {delegate_snapshot.digest!r} skewed from issuer "
            f"{issuer_snapshot.digest!r}; refusing local re-resolution"
        )

    issuer_effective = resolve(issuer_snapshot, token.scope_verb, token.resource_pattern)
    delegate_effective = resolve(delegate_snapshot, token.scope_verb, token.resource_pattern)

    if not delegate_effective <= issuer_effective:
        widened = delegate_effective - issuer_effective
        raise ScopeAttenuationError(
            f"scope widened at delegate: {sorted(widened)} not in issuer resolution"
        )
    if not issuer_effective <= token.parent_scope:
        escaped = issuer_effective - token.parent_scope
        raise ScopeAttenuationError(
            f"issuer resolution escapes parent scope: {sorted(escaped)}"
        )
    return delegate_effective
