# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-capability-has-been-silently-widened-by-scope-intersection-collapse-during-re-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-capability-has-been-silently-widened-by-scope-intersection-collapse-during-re-delegation.warrant.json
# Markdown SHA-256:   3067deddefba2937229f0635e5c7959f64c89a5889ae75c48825cd1ab402aaec
# Code AST SHA-256:   896d27afd3f5acdfd537885f02b4bc693ec69e9ebb78c8c8185c03d7f760c0d7
# Verified Classes:   ScopeTuple, ScopeWideningError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Tuple

@dataclass(frozen=True)
class ScopeTuple:
    resource: str
    action: str
    constraint: str  # e.g. "tenant=acme"; "*" means unconstrained

class ScopeWideningError(RuntimeError):
    pass

ALGEBRA_TUPLE = "tuple-v1"
ALGEBRA_FLAT = "flat-v1"

def is_subset(child: FrozenSet[ScopeTuple], parent: FrozenSet[ScopeTuple]) -> bool:
    # child <= parent iff every child tuple is dominated by some parent tuple
    for c in child:
        if not any(
            (p.resource == c.resource or p.resource == "*") is False
            and p.resource == c.resource
            and p.action == c.action
            and p.constraint == c.constraint
            for p in parent
        ):
            return False
    return True

def delegate(
    parent_scope: FrozenSet[ScopeTuple],
    parent_algebra: str,
    child_scope: FrozenSet[ScopeTuple],
    child_algebra: str,
    refinement_map_present: bool,
) -> FrozenSet[ScopeTuple]:
    if child_algebra != parent_algebra and not refinement_map_present:
        # Dialect mismatch without a registered refinement map.
        # Do NOT normalize. Reject the hop.
        raise ScopeWideningError(
            f"re-delegation crosses algebra boundary {parent_algebra!r} -> "
            f"{child_algebra!r} with no registered refinement map; "
            f"scope is incomparable and must not be intersected"
        )
    if not is_subset(child_scope, parent_scope):
        raise ScopeWideningError(
            "declared child scope is not a subset of parent scope under a "
            "single algebra; effective scope would widen"
        )
    return child_scope
