# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-trust-brokered-a2a-gateway-is-silently-downgrading-capability-scope-at-the-cross-org-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-trust-brokered-a2a-gateway-is-silently-downgrading-capability-scope-at-the-cross-org-boundary.warrant.json
# Markdown SHA-256:   058b8457be00b37f19ca49db0b6f46293ac4cb840b9cf9b84f046ebd0a443e28
# Code AST SHA-256:   1c62a23a1dfaba1dbd0cf215899e847c5ed09da950a2b436878954ad0d02482c
# Verified Classes:   ScopeDowngradeError, Warrant, PlanStep
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeDowngradeError(RuntimeError):
    """Raised when a delegated plan assumes capabilities the minted warrant does not grant."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    capabilities: FrozenSet[str]
    ttl_seconds: int
    attestation_present: bool


@dataclass(frozen=True)
class PlanStep:
    name: str
    requires: FrozenSet[str]
    depends_on: FrozenSet[str] = field(default_factory=frozenset)


def validate_plan_against_warrant(steps: list[PlanStep], warrant: Warrant) -> None:
    """
    Enforce the monotonicity invariant at the boundary, before any step executes.
    A delegated plan may only run if every step's required capabilities are a
    subset of the warrant actually minted by the trust broker.
    """
    missing: dict[str, set[str]] = {}
    for step in steps:
        gap = step.requires - warrant.capabilities
        if gap:
            missing[step.name] = set(gap)

    if missing:
        # Surface the split explicitly: the planner assumed a superset.
        detail = "; ".join(f"{step} needs {sorted(caps)}" for step, caps in missing.items())
        raise ScopeDowngradeError(
            f"Warrant from {warrant.issuer} to {warrant.subject} does not cover plan. "
            f"attestation_present={warrant.attestation_present}. Gaps: {detail}. "
            f"Re-plan against effective scope; do not execute dependent steps."
        )


def execute_delegated_plan(steps: list[PlanStep], warrant: Warrant, runner) -> None:
    # Boundary check first: narrowing must be caught here, not at step 4.
    validate_plan_against_warrant(steps, warrant)

    completed: set[str] = set()
    for step in steps:
        unmet = step.depends_on - completed
        if unmet:
            raise ScopeDowngradeError(
                f"Step {step.name} depends on {sorted(unmet)} which did not complete; "
                f"refusing to proceed to a step that would assert an unperformed action."
            )
        runner(step)
        completed.add(step.name)
