# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-brokered-capability-warrant-whose-delegated-policy-scope-silently-widens-at-the-second-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-brokered-capability-warrant-whose-delegated-policy-scope-silently-widens-at-the-second-hop.warrant.json
# Markdown SHA-256:   f42e580f6f4af2fbddbe68642c30184cbfa9023cf9ca2fb28543a4248041b6b0
# Code AST SHA-256:   64dcb3573f9798049ce8d84f55bf722ee6be6e3c820f69e0b61250d2ab8fd0ce
# Verified Classes:   CapabilitySubstitutionError, Scope, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilitySubstitutionError(RuntimeError):
    """Raised when a federated hop grants a scope that is neither the
    requested scope nor a documented narrowing of it."""


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

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

    def intersect(self, other: "Scope") -> "Scope":
        if self.dataset != other.dataset:
            raise CapabilitySubstitutionError(
                f"dataset mismatch: {self.dataset!r} vs {other.dataset!r}"
            )
        return Scope(self.dataset, self.actions & other.actions)


@dataclass
class Warrant:
    scope: Scope
    issuer: str
    subject: str


def delegate(
    *,
    requested: Scope,
    parent_warrant: Warrant,
    local_policy_ceiling: Scope | None,
    allow_widen_to_warrant: bool = False,
) -> Warrant:
    """Re-delegate a sub-capability across a federation hop.

    The invariant: effective_authority(hop N) <= effective_authority(hop N-1).
    Widening to the parent warrant's scope is NEVER safe cross-org because the
    receiving instance cannot re-evaluate the broker's policy.
    """
    if not requested.is_subset_of(parent_warrant.scope):
        if allow_widen_to_warrant:
            # The observed failure path: substitute the warrant's scope for the
            # requested scope and retry. This is the bug, not the fix.
            raise CapabilitySubstitutionError(
                "refusing widen-to-warrant: would substitute "
                f"{parent_warrant.scope} for requested {requested}"
            )
        # Correct path: narrow to the intersection and surface the negotiation.
        if local_policy_ceiling is None:
            raise CapabilitySubstitutionError(
                "cannot narrow without local policy; reject delegation"
            )
        narrowed = requested.intersect(parent_warrant.scope).intersect(
            local_policy_ceiling
        )
        if not narrowed.actions:
            raise CapabilitySubstitutionError(
                f"empty intersection for requested {requested}"
            )
        return Warrant(
            scope=narrowed,
            issuer=parent_warrant.subject,
            subject="downstream",
        )

    if local_policy_ceiling is not None and not requested.is_subset_of(
        local_policy_ceiling
    ):
        raise CapabilitySubstitutionError(
            f"requested {requested} exceeds local policy ceiling "
            f"{local_policy_ceiling}"
        )

    return Warrant(
        scope=requested,
        issuer=parent_warrant.subject,
        subject="downstream",
    )


def assert_return_scope(
    *,
    executed_scope: Scope,
    requested_scope: Scope,
    substitution_recorded: bool,
) -> None:
    """Guardrail at the return boundary: a result returned under a scope that
    differs from the requested one must carry an explicit substitution record,
    or it is a verification replay discrepancy in the making."""
    if executed_scope != requested_scope and not substitution_recorded:
        raise CapabilitySubstitutionError(
            "result returned under substituted scope without substitution "
            f"record: executed={executed_scope} requested={requested_scope}"
        )
