# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-narrowing-forgery-in-aaif-delegation-chains-when-attenuation-proofs-are-valid-but-the-delegation-graph-is-not-a-latt.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-narrowing-forgery-in-aaif-delegation-chains-when-attenuation-proofs-are-valid-but-the-delegation-graph-is-not-a-latt.warrant.json
# Markdown SHA-256:   a37cece9177cf0716b14c504db6cb994abb84e455deb1e66fc6bcd9816aa0c47
# Code AST SHA-256:   d0d8b167193af04f6f5f1004a29aaacdf9d004e8badd96d64d873f7a3c728fdf
# Verified Classes:   UnverifiableJoinError, Scope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class UnverifiableJoinError(RuntimeError):
    """Raised when a join delegation's reconstructed scope cannot be certified
    as a subset of every parent scope. This is a denial, never a pass."""


@dataclass(frozen=True)
class Scope:
    resources: FrozenSet[str]
    regions: FrozenSet[str]
    # NOTE: negative constraints are NOT representable here on purpose.
    # If the framework encodes exclusions as positive patterns, closure fails.


def certify_subset(child: Scope, parent: Scope) -> bool:
    """Framework's subsumption checker. Must be sound; must be called per parent."""
    return child.resources <= parent.resources and child.regions <= parent.regions


def reconstruct_join_scope(parents: list[Scope]) -> Scope:
    """Intersection routine. NOT a substitute for certification."""
    if not parents:
        raise UnverifiableJoinError("join delegation with zero parents")
    resources = frozenset.intersection(*(p.resources for p in parents))
    regions = frozenset.intersection(*(p.regions for p in parents))
    return Scope(resources=resources, regions=regions)


def authorize_join(parents: list[Scope], requested: Scope) -> Scope:
    """Authorize a join delegation. Fails closed on any uncertified parent."""
    reconstructed = reconstruct_join_scope(parents)
    for i, parent in enumerate(parents):
        if not certify_subset(reconstructed, parent):
            raise UnverifiableJoinError(
                f"reconstructed join scope is not a certified subset of parent[{i}]; "
                f"intersection routine and subsumption checker disagree — "
                f"treat as forgery, do not authorize"
            )
    if not certify_subset(requested, reconstructed):
        raise UnverifiableJoinError(
            "requested scope exceeds certified join scope"
        )
    return reconstructed
