# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-escalation-when-a-federated-agent-re-derives-its-own-scope-from-a-peer-s-manifest-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-escalation-when-a-federated-agent-re-derives-its-own-scope-from-a-peer-s-manifest-mid-handshake.warrant.json
# Markdown SHA-256:   3323c019becb8254274ec5e4415542dffaa9eb6a485fdb8262855b428348b0ab
# Code AST SHA-256:   f24544704377cb15bc44f22b6fef16e8da306f64182db3d1bf8ea5aeafe99ddd
# Verified Classes:   ScopeEscalationError, WarrantExpiredError, DepthExhaustedError, ScopeToken, DiscoveredCapabilities
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import FrozenSet


class ScopeEscalationError(RuntimeError):
    """Raised when a tool gate is asked to authorize an action outside the warrant."""


class WarrantExpiredError(ScopeEscalationError):
    """Raised when a warrant's not_after has passed at gate time."""


class DepthExhaustedError(ScopeEscalationError):
    """Raised when a delegation would exceed the warrant's delegation_depth."""


@dataclass(frozen=True)
class ScopeToken:
    warrant_id: str
    scope: FrozenSet[str]
    delegation_depth: int
    not_after: datetime

    def verify(self, action: str, now: datetime | None = None) -> None:
        now = now or datetime.now(timezone.utc)
        if now >= self.not_after:
            raise WarrantExpiredError(
                f"warrant {self.warrant_id} expired at {self.not_after.isoformat()}"
            )
        if self.delegation_depth < 1:
            raise DepthExhaustedError(
                f"warrant {self.warrant_id} has no remaining delegation depth"
            )
        if action not in self.scope:
            raise ScopeEscalationError(
                f"action {action!r} not in warrant {self.warrant_id} scope {sorted(self.scope)}"
            )


@dataclass(frozen=True)
class DiscoveredCapabilities:
    """Output of peer-manifest resolution. NOT authorizable. Planner-only."""
    capabilities: FrozenSet[str]


def derive_effective_scope(
    token: ScopeToken, discovered: DiscoveredCapabilities
) -> FrozenSet[str]:
    # Meet, never join. Discovery may shrink; it may never grow.
    return token.scope & discovered.capabilities


def tool_gate(token: ScopeToken, action: str, now: datetime | None = None) -> None:
    # The gate takes the token as a required argument; there is no session fallback.
    token.verify(action, now=now)


def execute_delegated_step(
    token: ScopeToken,
    discovered: DiscoveredCapabilities,
    requested_action: str,
    now: datetime | None = None,
) -> str:
    effective = derive_effective_scope(token, discovered)
    if requested_action not in effective:
        # Distinguish "withheld by warrant" from "withdrawn by peer" for the audit log.
        if requested_action in token.scope:
            raise ScopeEscalationError(
                f"peer withdrew {requested_action!r}; warrant {token.warrant_id} still grants it "
                f"but effective scope is {sorted(effective)}"
            )
        raise ScopeEscalationError(
            f"planner attempted {requested_action!r} derived from peer manifest, "
            f"outside warrant {token.warrant_id} scope {sorted(token.scope)}"
        )
    tool_gate(token, requested_action, now=now)
    return f"ok:{requested_action}"
