# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-attenuate-a-delegated-aaif-credential-when-the-scope-lattice-is-not-provably-a-sub-lattice-of-the-issuer.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-attenuate-a-delegated-aaif-credential-when-the-scope-lattice-is-not-provably-a-sub-lattice-of-the-issuer.warrant.json
# Markdown SHA-256:   e5843bfc3d6db67f55969af72660cf1bec83c4b522a484620f7666b956c576bb
# Code AST SHA-256:   cbeb02ab4145e5738a563ab540413e284e7996a5734218f71610053310fbc7e2
# Verified Classes:   UnsoundAttenuationError, ScopeGrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass
from hashlib import sha256


class UnsoundAttenuationError(RuntimeError):
    """Raised when a delegated AAIF credential cannot be proven to be a
    lattice-refinement of its parent under a shared normalization."""


@dataclass(frozen=True)
class ScopeGrant:
    scope: str
    normalization_digest: str  # H(N) of the normalizer that produced `scope`
    parent_scope: str | None = None
    issuer: str = ""


def _canonicalize(scope: str, normalizer: str) -> str:
    # Placeholder for the real lattice normalizer. The digest of the
    # normalizer function is what binds interpretation across instances.
    return f"{normalizer}::{scope.strip()}"


def _normalizer_digest(normalizer_id: str) -> str:
    return sha256(normalizer_id.encode()).hexdigest()


def _meet(parent: str, child: str, normalizer: str) -> str:
    # Meet in the scope lattice. Real implementations resolve wildcards;
    # here we model the failure mode: a non-terminal '**' is treated
    # differently by prefix-anchored vs glob normalizers.
    p = _canonicalize(parent, normalizer)
    c = _canonicalize(child, normalizer)
    if "**" in parent and "**" not in child:
        return p  # meet collapses to parent — child is NOT below parent
    return c


def attenuate(
    parent: ScopeGrant,
    proposed_child_scope: str,
    local_normalizer_id: str,
) -> ScopeGrant:
    local_digest = _normalizer_digest(local_normalizer_id)

    # Invariant 1: shared normalization identity.
    if parent.normalization_digest != local_digest:
        raise UnsoundAttenuationError(
            f"normalization mismatch: parent={parent.normalization_digest[:12]} "
            f"local={local_digest[:12]}; cannot prove C ⊑ P"
        )

    # Invariant 2: no implicit inheritance / aliases in signed bytes.
    if "@" in proposed_child_scope or "~" in proposed_child_scope:
        raise UnsoundAttenuationError(
            f"child scope {proposed_child_scope!r} contains an unresolved alias; "
            "ordering is not bound by the signature"
        )

    # Invariant 3: canonicalization-equality, not mere subset.
    child_canon = _canonicalize(proposed_child_scope, local_normalizer_id)
    meet_canon = _meet(parent.scope, proposed_child_scope, local_normalizer_id)
    if child_canon != meet_canon:
        raise UnsoundAttenuationError(
            f"meet({parent.scope!r}, {proposed_child_scope!r}) = {meet_canon!r} "
            f"!= child {child_canon!r}; attenuation would widen scope"
        )

    return ScopeGrant(
        scope=proposed_child_scope,
        normalization_digest=local_digest,
        parent_scope=parent.scope,
        issuer="this-instance",
    )


# --- reproduction of the observed failure ---
root = ScopeGrant(
    scope="fs:read:/data/**",
    normalization_digest=_normalizer_digest("glob"),
)
try:
    # 'glob' normalizer would treat '/data/**/reports/*' as wider than
    # '/data/reports/*', so canonicalization-equality must fail closed.
    attenuate(root, "fs:read:/data/**/reports/*", "prefix-anchored")
except UnsoundAttenuationError as e:
    print(f"refused (correct): {e}")

# And the digest-mismatch path:
try:
    attenuate(root, "fs:read:/data/reports/*", "prefix-anchored")
except UnsoundAttenuationError as e:
    print(f"refused (correct): {e}")
