# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-delegated-capability-set-it-cannot-itself-re-derive-transitive-capability-amplification-in-a2a-discovery-unde.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-delegated-capability-set-it-cannot-itself-re-derive-transitive-capability-amplification-in-a2a-discovery-unde.warrant.json
# Markdown SHA-256:   b819f862361efd5fbb088d4ad3a2d7d1262c49c5a350327d94187b8284072542
# Code AST SHA-256:   0d6c0c9afba5acc1d1a4f1dc9ed07202975bfda33e254e51aed44bf396149e91
# Verified Classes:   CapabilityAmplificationError, Warrant, DiscoveryResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityAmplificationError(RuntimeError):
    """Raised when a delegate's usable capability set exceeds its warrant scope."""


@dataclass(frozen=True)
class Warrant:
    principal: str
    delegate: str
    scope: FrozenSet[str]
    audience: str
    transitive: bool = False
    ttl_seconds: int = 300


@dataclass
class DiscoveryResult:
    manifest: FrozenSet[str]
    source: str


def scope_filter_manifest(warrant: Warrant, full_manifest: FrozenSet[str]) -> FrozenSet[str]:
    """Source-side enforcement: manifest returned to a derived token is the
    intersection of the full manifest and the presenting warrant's scope.
    Chain trust alone is insufficient; the scope predicate must gate the manifest."""
    if not warrant.transitive:
        # A non-transitive warrant may only ever see its own scope.
        return full_manifest & warrant.scope
    return full_manifest


def reintersect_at_delegate(warrant: Warrant, discovered: DiscoveryResult) -> FrozenSet[str]:
    """Delegate-side defense in depth: never let the planner consume a manifest
    broader than the warrant, even if the source misbehaved."""
    usable = discovered.manifest & warrant.scope
    leaked = discovered.manifest - usable
    if leaked:
        # Contamination detected: planner must not see these names.
        raise CapabilityAmplificationError(
            f"delegate {warrant.delegate} received manifest entries outside "
            f"warrant scope from {discovered.source}: {sorted(leaked)}"
        )
    return usable


def plan_and_invoke(warrant: Warrant, discovered: DiscoveryResult, task_caps: FrozenSet[str]) -> FrozenSet[str]:
    usable = reintersect_at_delegate(warrant, discovered)
    unauthorized = task_caps - usable
    if unauthorized:
        raise CapabilityAmplificationError(
            f"task for {warrant.delegate} requires capabilities outside "
            f"effective scope {sorted(warrant.scope)}: {sorted(unauthorized)}"
        )
    return task_caps


# Reproduction of the observed trace:
full = frozenset({"search", "summarize", "export:raw_corpus", "admin:reindex"})
w_b = Warrant(principal="A", delegate="B", scope=frozenset({"search", "summarize"}),
              audience="C", transitive=False)

# Source correctly filters:
safe_manifest = scope_filter_manifest(w_b, full)
assert safe_manifest == frozenset({"search", "summarize"})

# Misconfigured source returns full manifest; delegate must catch it:
leaky = DiscoveryResult(manifest=full, source="C")
try:
    reintersect_at_delegate(w_b, leaky)
except CapabilityAmplificationError as e:
    print(f"BLOCKED: {e}")

# Planner attempting a withheld capability is blocked before invocation:
try:
    plan_and_invoke(w_b, DiscoveryResult(manifest=safe_manifest, source="C"),
                    frozenset({"summarize", "export:raw_corpus"}))
except CapabilityAmplificationError as e:
    print(f"BLOCKED: {e}")
