# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-grant-has-silently-widened-scope-across-an-agent-federation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-grant-has-silently-widened-scope-across-an-agent-federation-boundary.warrant.json
# Markdown SHA-256:   ee20008a89b0964b802144724dad72361d15d977e8981953e84e7d38443d0aef
# Code AST SHA-256:   a46639cec3cdd534877ca6881bfa98739b2984ea909c129140329b1fdcb8a41a
# Verified Classes:   ScopeWideningError, Grant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeWideningError(RuntimeError):
    """Raised when a delegated grant's effective scope is not a subset of its parent's."""
    pass


@dataclass
class Grant:
    capability: str
    binding: Optional[str]          # concrete resource id, None means type-level (dangerous)
    grammar_version: str
    delegation_depth: Optional[int]  # None is an error, never defaulted
    parent_binding: Optional[str] = None


def verify_chain_intersection(
    parent: Grant,
    child: Grant,
    local_grammar_version: str,
) -> None:
    # 1. Grammar must match; a parser mismatch is the widening vector.
    if child.grammar_version != parent.grammar_version:
        raise ScopeWideningError(
            f"grammar mismatch: parent {parent.grammar_version} vs child "
            f"{child.grammar_version}; cannot compute intersection"
        )

    # 2. Missing depth is an error, not a default. A defaulted depth resets the bound.
    if child.delegation_depth is None:
        raise ScopeWideningError(
            "child grant has no delegation_depth; refusing to substitute a default"
        )
    if parent.delegation_depth is not None and child.delegation_depth >= parent.delegation_depth:
        raise ScopeWideningError(
            f"delegation depth did not decrease: parent {parent.delegation_depth} "
            f"-> child {child.delegation_depth}"
        )

    # 3. Unresolvable binding predicate must deny, never fall back to type-level.
    if child.binding is None:
        raise ScopeWideningError(
            f"child grant for {child.capability} has no concrete binding; "
            "type-level fallback would widen scope"
        )

    # 4. Binding must equal the parent's binding (subset check under shared algebra).
    if parent.binding is not None and child.binding != parent.binding:
        raise ScopeWideningError(
            f"binding widened: parent {parent.binding} -> child {child.binding}"
        )


def mint_child(parent: Grant, capability: str, binding: str, grammar_version: str) -> Grant:
    if parent.delegation_depth is None or parent.delegation_depth <= 0:
        raise ScopeWideningError(
            "cannot re-delegate: parent depth exhausted or unset"
        )
    child = Grant(
        capability=capability,
        binding=binding,
        grammar_version=grammar_version,
        delegation_depth=parent.delegation_depth - 1,
        parent_binding=parent.binding,
    )
    verify_chain_intersection(parent, child, grammar_version)
    return child


# Demonstration of the observed failure being caught:
if __name__ == "__main__":
    root = Grant("read:dataset", binding="dataset:4471", grammar_version="v2", delegation_depth=1)
    # Org B's buggy re-delegation: drops binding, defaults depth to 3.
    bad_child = Grant("read:dataset", binding=None, grammar_version="v2", delegation_depth=3)
    try:
        verify_chain_intersection(root, bad_child, "v2")
    except ScopeWideningError as e:
        print(f"BLOCKED: {e}")
