# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-narrowing-delegation-chains-from-silently-widening-at-re-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-narrowing-delegation-chains-from-silently-widening-at-re-issuance.warrant.json
# Markdown SHA-256:   333454459f9aa7a81879a35aa9472373bb40f3b5fc5995ccbd92ab0706f25f1d
# Code AST SHA-256:   062840dbf1ca32141b80c36ec27dea49062e98c6c714c9713a55c2edd569f473
# Verified Classes:   ScopeWideningError, Scope
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a child capability scope is not a sound subset of its parent."""


@dataclass(frozen=True)
class Scope:
    # Totality: every dimension present at root must be present here.
    grants: FrozenSet[str]
    denies: FrozenSet[str]
    dimensions: FrozenSet[str]  # the root's full dimension set, pinned at issuance


def derive_child_scope(parent: Scope, requested_grants: FrozenSet[str]) -> Scope:
    if requested_grants - parent.dimensions:
        raise ScopeWideningError(
            f"requested dimensions {requested_grants - parent.dimensions} "
            f"not present in root dimension set {parent.dimensions}"
        )
    # Denies are inherited by conjunction: child cannot drop a parent deny.
    child_denies = parent.denies | (requested_grants & parent.denies)
    # Grants are intersected with parent grants; you cannot grant what you lack.
    child_grants = requested_grants & parent.grants
    if child_grants - parent.grants:
        raise ScopeWideningError("grant exceeds parent grant set")
    if not (child_denies >= parent.denies):
        raise ScopeWideningError("deny set shrank across delegation")
    return Scope(
        grants=child_grants,
        denies=child_denies,
        dimensions=parent.dimensions,
    )


def verify_chain(root: Scope, chain: list[Scope]) -> None:
    current = root
    for hop_index, child in enumerate(chain):
        if child.dimensions != root.dimensions:
            raise ScopeWideningError(
                f"hop {hop_index}: dimension set drifted from root; "
                f"missing={root.dimensions - child.dimensions}, "
                f"extra={child.dimensions - root.dimensions}"
            )
        if not (child.denies >= current.denies):
            raise ScopeWideningError(
                f"hop {hop_index}: deny dropped "
                f"({current.denies - child.denies}); omission-as-widening"
            )
        if not (child.grants <= current.grants):
            raise ScopeWideningError(
                f"hop {hop_index}: grant {child.grants - current.grants} "
                f"exceeds parent {current.grants}"
            )
        current = child
