# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-authorization-scopes-when-a-cross-org-trust-federation-re-issues-a-capability-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-authorization-scopes-when-a-cross-org-trust-federation-re-issues-a-capability-mid-execution.warrant.json
# Markdown SHA-256:   4d9ab4163efab5748041cc775c02659853f5a6f8feb4ab546ed4da441e9ce814
# Code AST SHA-256:   2e9aae42abcb63946487a39901e228a0b4d4b2a3876a2178fd5e190afef6fd96
# Verified Classes:   ScopeDivergenceError, Warrant, PlanStep, HolderState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeDivergenceError(RuntimeError):
    """Raised when an in-flight plan is no longer covered by the active warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer_key_id: str
    scopes: FrozenSet[str]


@dataclass
class PlanStep:
    step_id: int
    intent_scope: str          # scope the plan *intended*, compiled at plan time
    executed: bool = False


@dataclass
class HolderState:
    active_warrant: Warrant
    plan: list = field(default_factory=list)
    decision_cache: dict = field(default_factory=dict)  # keyed by (warrant_id, call)


def reconcile_on_warrant_mutation(state: HolderState, new_warrant: Warrant) -> None:
    """Called on every warrant-cache mutation. Halts if plan is partially unauthorized."""
    # Key rotation / re-issue invalidates all cached decisions.
    state.decision_cache.clear()
    state.active_warrant = new_warrant

    uncovered_unexecuted = [
        s for s in state.plan
        if not s.executed and s.intent_scope not in new_warrant.scopes
    ]
    uncovered_executed = [
        s for s in state.plan
        if s.executed and s.intent_scope not in new_warrant.scopes
    ]

    if uncovered_executed:
        # Committed side effects under a now-revoked scope: must be compensated.
        raise ScopeDivergenceError(
            f"warrant {new_warrant.warrant_id} revoked scope(s) already committed by "
            f"steps {[s.step_id for s in uncovered_executed]}; emit compensating actions"
        )
    if uncovered_unexecuted:
        # Plan is partially unauthorized: halt before executing remaining steps.
        raise ScopeDivergenceError(
            f"warrant {new_warrant.warrant_id} does not cover unexecuted steps "
            f"{[s.step_id for s in uncovered_unexecuted]}; re-plan or abort"
        )


def execute_step(state: HolderState, step: PlanStep) -> None:
    # Intent-scope check, not just runtime call-scope check.
    if step.intent_scope not in state.active_warrant.scopes:
        raise ScopeDivergenceError(
            f"step {step.step_id} intent scope {step.intent_scope!r} not in active "
            f"warrant {state.active_warrant.warrant_id}"
        )
    state.decision_cache[(state.active_warrant.warrant_id, step.step_id)] = "ALLOW"
    step.executed = True
