# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-federated-trust-broker-has-silently-downgraded-a-capability-grant-across-an-inter-domain-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-federated-trust-broker-has-silently-downgraded-a-capability-grant-across-an-inter-domain-boundary.warrant.json
# Markdown SHA-256:   9ec5eef4487056f878f9f5f57f5368d88ed9c3a3c80ba1debcd7aedc418e4c6c
# Code AST SHA-256:   fd2bd13bd5f39f0c708e25956818ad47856c06a360a152652700fa8f911d3495
# Verified Classes:   WarrantAttenuationError, Warrant, PlanRequirements, Reconciliation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantAttenuationError(RuntimeError):
    """Raised when a broker-issued warrant's resource envelope is narrower than
    the requesting plan's declared requirements. This is the receipt-time
    reconciliation failure: the broker attenuated (correctly, per its policy),
    and the agent must not proceed under a false assumption of full grant."""

    def __init__(self, field_name: str, required, granted, warrant_id: str):
        self.field_name = field_name
        self.required = required
        self.granted = granted
        self.warrant_id = warrant_id
        super().__init__(
            f"warrant {warrant_id} attenuated on {field_name}: "
            f"required={required!r} granted={granted!r}"
        )


ASSURANCE_RANK = {"low": 0, "medium": 1, "high": 2}


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    capabilities: FrozenSet[str]
    ttl_seconds: int
    assurance: str
    subject: str


@dataclass(frozen=True)
class PlanRequirements:
    required_capabilities: FrozenSet[str]
    min_ttl_seconds: int
    required_assurance: str
    subject: str


@dataclass
class Reconciliation:
    decision: str  # "accept" | "re_plan" | "reject"
    shortfalls: list = field(default_factory=list)


def reconcile_warrant_at_receipt(
    warrant: Warrant, plan: PlanRequirements, allow_replan: bool
) -> Reconciliation:
    """Total function evaluated before the first operation of the plan.

    Compares the granted envelope against the plan's declared requirements on
    all three attenuation axes: capability set, TTL, and assurance. Any
    shortfall is a structural signal that the broker downgraded the grant.
    """
    shortfalls = []

    missing_caps = plan.required_capabilities - warrant.capabilities
    if missing_caps:
        shortfalls.append(("capabilities", plan.required_capabilities, warrant.capabilities))

    if warrant.ttl_seconds < plan.min_ttl_seconds:
        shortfalls.append(("ttl_seconds", plan.min_ttl_seconds, warrant.ttl_seconds))

    if ASSURANCE_RANK[warrant.assurance] < ASSURANCE_RANK[plan.required_assurance]:
        shortfalls.append(("assurance", plan.required_assurance, warrant.assurance))

    if warrant.subject != plan.subject:
        # Subject rebinding is the most dangerous attenuation: the warrant
        # authorizes a different principal than the plan assumes.
        shortfalls.append(("subject", plan.subject, warrant.subject))

    if not shortfalls:
        return Reconciliation(decision="accept")

    if allow_replan and all(f[0] in ("ttl_seconds",) for f in shortfalls):
        # TTL-only shortfall is safely re-plannable: split the sequence into
        # sub-plans each fitting the granted TTL, with explicit checkpoints.
        # Capability, assurance, and subject shortfalls are NOT re-plannable.
        return Reconciliation(decision="re_plan", shortfalls=shortfalls)

    field_name, required, granted = shortfalls[0]
    raise WarrantAttenuationError(
        field_name=field_name,
        required=required,
        granted=granted,
        warrant_id=warrant.warrant_id,
    )


def execute_plan(warrant: Warrant, plan: PlanRequirements, allow_replan: bool = False) -> None:
    # Receipt-time reconciliation MUST precede any side-effecting operation.
    reconciliation = reconcile_warrant_at_receipt(warrant, plan, allow_replan)
    if reconciliation.decision == "re_plan":
        # Hand off to the re-decomposition path, which must itself reason about
        # which cross-operation atomicity invariants the split will break.
        _replan_under_envelope(warrant, plan, reconciliation.shortfalls)
        return
    # ... proceed with operations under a verified full-fidelity grant ...
