# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-silently-widened-at-a-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-silently-widened-at-a-trust-boundary.warrant.json
# Markdown SHA-256:   1ab63010df80281fc29fdfb5e00713f6e055324d5bf00edcd21379bef1cd5d56
# Code AST SHA-256:   24045de91fc2a7dec5361e3caac81bf963de9b9c227ac73e096178f4f15a8897
# Verified Classes:   ScopeLaunderingError, Scope, Delegation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeLaunderingError(RuntimeError):
    """Raised when a delegated token's effective scope exceeds its encoded grant."""


@dataclass(frozen=True)
class Scope:
    resources: FrozenSet[str]

    def is_subset_of(self, other: "Scope") -> bool:
        return self.resources <= other.resources


@dataclass
class Delegation:
    encoded: Scope                      # what the issuer signed
    registry: Scope                     # what the host could technically do
    scope_source: str                   # "signed_claim" | "prose" | "schema_hint"


def resolve_effective_scope(hop: Delegation, parent_encoded: Scope) -> Scope:
    # Rule 1: unsigned scope is advisory and must not authorize.
    if hop.scope_source != "signed_claim":
        raise ScopeLaunderingError(
            f"scope arrived via {hop.scope_source!r}, not a signed claim; refusing to authorize"
        )

    # Rule 2: effective = encoded INTERSECT registry, never union.
    effective = Scope(hop.encoded.resources & hop.registry.resources)

    # Rule 3: monotonic non-expansion — child encoded must be subset of parent encoded.
    if not hop.encoded.is_subset_of(parent_encoded):
        raise ScopeLaunderingError(
            f"delegated encoded scope {sorted(hop.encoded.resources)} "
            f"is not a subset of parent {sorted(parent_encoded.resources)}"
        )

    # Rule 4 (post-intersection sanity): effective must not exceed encoded.
    if not effective.is_subset_of(hop.encoded):
        raise ScopeLaunderingError("effective scope escaped encoded scope after intersection")

    return effective


def run_hop(hop: Delegation, parent_encoded: Scope) -> Scope:
    effective = resolve_effective_scope(hop, parent_encoded)
    # Any tool call must be checked against `effective`, not `hop.registry`.
    return effective


# --- demonstration of the widening trace ---
parent = Scope(frozenset({"fs:read:/data/reports", "tools:summarize"}))
laundered = Delegation(
    encoded=Scope(frozenset({"fs:read:/data", "net:http", "tools:summarize", "tools:fetch_url"})),
    registry=Scope(frozenset({"fs:read:/data", "net:http", "tools:summarize", "tools:fetch_url"})),
    scope_source="prose",  # described in a prompt, never signed
)

try:
    run_hop(laundered, parent)
except ScopeLaunderingError as e:
    print(f"HARD STOP at trust boundary: {e}")
