# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attenuates-a-delegated-warrant-but-the-downstream-agent-re-derives-capabilities-from-the-raw-task-payload.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attenuates-a-delegated-warrant-but-the-downstream-agent-re-derives-capabilities-from-the-raw-task-payload.warrant.json
# Markdown SHA-256:   9d458aae56c6dc9aebd04ab2052beb7297e313fa519dc553b81bfdf09a4b8a55
# Code AST SHA-256:   8cf173882d48a4db3d9949ee4da3f3445810062d07c70c34350fb265ec68cfa3
# Verified Classes:   DelegationAttenuationError, Warrant, TaskPayload
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationAttenuationError(RuntimeError):
    """Raised when a delegated payload requests capabilities the minted warrant does not grant."""
    pass


@dataclass(frozen=True)
class Warrant:
    capabilities: FrozenSet[str]
    parent_caps: FrozenSet[str]

    def attenuate(self, requested: FrozenSet[str]) -> "Warrant":
        # Least privilege: a child can never exceed its parent.
        if not requested.issubset(self.capabilities):
            illegal = requested - self.capabilities
            raise DelegationAttenuationError(
                f"attenuation would widen authority: {sorted(illegal)} not held by parent"
            )
        return Warrant(capabilities=requested, parent_caps=self.capabilities)


@dataclass
class TaskPayload:
    requested_tools: FrozenSet[str]
    instruction: str


def mint_and_dispatch(parent: Warrant, child_caps: FrozenSet[str], payload: TaskPayload) -> Warrant:
    """Delegator-side check: the payload we ship MUST be satisfiable by the warrant we mint."""
    child_warrant = parent.attenuate(child_caps)
    if not payload.requested_tools.issubset(child_warrant.capabilities):
        unsatisfiable = payload.requested_tools - child_warrant.capabilities
        raise DelegationAttenuationError(
            f"payload requests {sorted(unsatisfiable)} but minted warrant grants "
            f"{sorted(child_warrant.capabilities)}; refusing to dispatch an unsatisfiable task"
        )
    return child_warrant


def resolve_tools(warrant: Warrant, payload: TaskPayload) -> FrozenSet[str]:
    """Recipient-side check: derive from the warrant, treat payload as a checked subset."""
    if not payload.requested_tools.issubset(warrant.capabilities):
        out_of_scope = payload.requested_tools - warrant.capabilities
        raise DelegationAttenuationError(
            f"recipient received payload naming {sorted(out_of_scope)} outside its warrant; "
            f"this is a delegation defect at the sender, not an auth failure here"
        )
    return payload.requested_tools


# Reproduction of the observed incident:
orchestrator = Warrant(
    capabilities=frozenset({"read:repo", "write:repo", "exec:shell", "net:http"}),
    parent_caps=frozenset(),
)
planner_w = orchestrator.attenuate(frozenset({"read:repo", "net:http"}))

# Planner tries to hand the executor a write task it cannot back with authority.
bad_payload = TaskPayload(
    requested_tools=frozenset({"read:repo", "write:repo"}),
    instruction="apply the patch to src/foo.py",
)

try:
    mint_and_dispatch(planner_w, frozenset({"read:repo"}), bad_payload)
except DelegationAttenuationError as e:
    print(f"BLOCKED at delegation: {e}")
    # Without this guard, the executor would later fail with a misleading 403,
    # or (soft-enforced) execute the write under ambient credentials.
