# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-has-been-scope-widened-by-a-transitive-grant-merge.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-has-been-scope-widened-by-a-transitive-grant-merge.warrant.json
# Markdown SHA-256:   c641f060232da1dff22ff3d6b819cf35939225b29df10d79ac3fe78cce93810b
# Code AST SHA-256:   654e519fe8f935d06a4972f938aa8af22dbe1e8b419cbdb54599fc127f5f463e
# Verified Classes:   ScopeWideningError, Credential, Hop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a delegated credential's resolved scope escapes the root anchor
    or widens monotonically along the delegation path."""


@dataclass(frozen=True)
class Credential:
    issuer: str
    held: FrozenSet[str]
    delegable: FrozenSet[str] = field(default_factory=frozenset)
    # Absence of explicit delegable set is FAIL-CLOSED: nothing is delegable.


@dataclass
class Hop:
    delegator: Credential
    requested: FrozenSet[str]


def resolve_path_scope(root: Credential, hops: list[Hop]) -> FrozenSet[str]:
    """Compute terminal scope as the intersection of every ancestor-declared
    scope along the path, never a union with any delegator's held set."""
    if not hops:
        return frozenset()

    path_intersection = frozenset(root.held)
    previous_cardinality = len(path_intersection)

    for index, hop in enumerate(hops):
        # Fail-closed: an undeclared delegable set permits no delegation.
        if not hop.delegator.delegable:
            raise ScopeWideningError(
                f"hop {index}: delegator {hop.delegator.issuer!r} has no "
                f"delegable_subset; refusing (fail-closed)"
            )

        # The delegator may only pass along what it is permitted to delegate,
        # and only what the path has already narrowed to.
        permitted = hop.delegator.delegable & path_intersection
        candidate = permitted & hop.requested

        # Containment against the ROOT anchor, not just the immediate parent.
        if not candidate <= frozenset(root.held):
            escaped = candidate - frozenset(root.held)
            raise ScopeWideningError(
                f"hop {index}: resolved scope escapes root anchor: {sorted(escaped)}"
            )

        # Monotonicity: path scope must never grow hop over hop.
        if len(candidate) > previous_cardinality:
            raise ScopeWideningError(
                f"hop {index}: scope widened {previous_cardinality} -> "
                f"{len(candidate)}; union-merge suspected at joint"
            )

        path_intersection = candidate
        previous_cardinality = len(candidate)

    return path_intersection


def delegate(root: Credential, hops: list[Hop]) -> FrozenSet[str]:
    terminal = resolve_path_scope(root, hops)
    if not terminal <= frozenset(root.held):
        # Defensive re-check; resolve_path_scope should have caught this.
        raise ScopeWideningError("terminal scope not contained in root anchor")
    return terminal


# --- Demonstration of the observed failure ---
if __name__ == "__main__":
    root = Credential(issuer="O", held=frozenset({"fs:read:/data", "fs:write:/data/out"}),
                      delegable=frozenset({"fs:read:/data"}))
    planner = Credential(issuer="P",
                         held=frozenset({"fs:write:/data/out", "net:egress:telemetry"}),
                         delegable=frozenset())  # undeclared -> fail-closed
    try:
        delegate(root, [
            Hop(delegator=root, requested=frozenset({"fs:read:/data"})),
            Hop(delegator=planner, requested=frozenset({"fs:read:/data"})),
        ])
    except ScopeWideningError as exc:
        print(f"REJECTED: {exc}")
