# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attenuates-a-capability-it-does-not-fully-enumerate-silent-privilege-re-expansion-at-the-third-delegation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attenuates-a-capability-it-does-not-fully-enumerate-silent-privilege-re-expansion-at-the-third-delegation-hop.warrant.json
# Markdown SHA-256:   fe67118a77eb0eb0e5475192a2dc5c1fa90ce6eb774f04954b203ea9450f40f9
# Code AST SHA-256:   bc43587a96874e0a7ae0e3ba6c1f4d34524f4d164ce80cb39ed87b4c8c83b55f
# Verified Classes:   CapabilityReexpansionError, Capability, Hop
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityReexpansionError(RuntimeError):
    """Raised when a delegated token grants authority its parent never held."""


@dataclass(frozen=True)
class Capability:
    ops: FrozenSet[str]
    resource_glob: str
    manifest_complete: bool = False


@dataclass
class Hop:
    agent: str
    declared_ops: FrozenSet[str]
    saw_full_manifest: bool


def attenuate(parent: Capability, hop: Hop) -> Capability:
    """Intersection-based attenuation. Refuses subtraction against partial beliefs."""
    if not hop.saw_full_manifest:
        # The hop cannot prove it enumerated the full surface; it may only
        # narrow via explicit allowlist, and the result must be a subset.
        raise CapabilityReexpansionError(
            f"hop '{hop.agent}' attenuated without a complete manifest; "
            f"subtraction against a partial belief set is not attenuation"
        )

    child_ops = parent.ops & hop.declared_ops
    if not child_ops.issubset(parent.ops):
        # Defensive: intersection cannot widen, but assert the invariant.
        raise CapabilityReexpansionError(
            f"hop '{hop.agent}' produced ops {child_ops - parent.ops} "
            f"outside parent authority"
        )

    return Capability(
        ops=child_ops,
        resource_glob=parent.resource_glob,
        manifest_complete=True,
    )


def run_chain(root: Capability, hops: list[Hop]) -> Capability:
    current = root
    for hop in hops:
        current = attenuate(current, hop)
    # Effect audit: replay leaf's actual calls against root, not declared scope.
    if not current.ops.issubset(root.ops):
        raise CapabilityReexpansionError(
            f"leaf authority {current.ops} exceeds root {root.ops}"
        )
    return current


# The observed failure, reproduced:
root = Capability(
    ops=frozenset({"research.fetch", "research.search", "research.fetch_raw",
                   "research.export_bundle", "research.write"}),
    resource_glob="corpus://tenant-42/**",
    manifest_complete=True,
)
retriever = Hop(
    agent="retriever",
    declared_ops=frozenset({"research.fetch", "research.search"}),
    saw_full_manifest=False,  # paginated tools/list, page 2 never fetched
)
try:
    run_chain(root, [retriever])
except CapabilityReexpansionError as e:
    print(f"blocked: {e}")  # fires here instead of silently exporting
