# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-attestation-whose-scope-narrowing-chain-re-widens-after-intersection-with-a-live-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-attestation-whose-scope-narrowing-chain-re-widens-after-intersection-with-a-live-tool.warrant.json
# Markdown SHA-256:   b8a38ebc43e676d93e60eed619c0de9c4cf4f2a6dd44406c02c7eb03d99509d2
# Code AST SHA-256:   da1f02e7f039a8b0ed88f63811a2a64be413ff10aadd4d39fee07a8b656df44d
# Verified Classes:   ScopeRewidening, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeRewidening(RuntimeError):
    """Raised when a delegated scope's semantic authority exceeds its parent's,
    even though the syntactic set intersection is a subset."""


@dataclass(frozen=True)
class Warrant:
    scope_terms: FrozenSet[str]
    lattice: FrozenSet[str]
    schema_hash: str
    parent: "Warrant | None" = None


def intersect_and_verify(
    parent: Warrant,
    local_request: FrozenSet[str],
    local_schema_hash: str,
) -> Warrant:
    # 1. Schema pinning: a changed schema must not silently widen authority.
    if local_schema_hash != parent.schema_hash:
        new_terms = local_request - parent.lattice
        if new_terms:
            raise ScopeRewidening(
                f"schema {local_schema_hash} introduces terms {sorted(new_terms)} "
                f"absent from parent lattice {sorted(parent.lattice)}; "
                f"refusing re-widening, parent must re-mint"
            )

    # 2. Lattice closure: unknown terms are denied, never unconstrained.
    unknown = local_request - parent.lattice
    if unknown:
        raise ScopeRewidening(
            f"local request terms {sorted(unknown)} not in parent lattice; "
            f"treating as denied, not unconstrained"
        )

    # 3. Semantic monotonicity: intersection must be within parent authority.
    child_scope = parent.scope_terms & local_request
    if not child_scope <= parent.scope_terms:
        raise ScopeRewidening("child authority exceeds parent authority")

    return Warrant(
        scope_terms=child_scope,
        lattice=parent.lattice,
        schema_hash=local_schema_hash,
        parent=parent,
    )
