# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-planning-span-s-next-step-attribute-as-non-authoritative-once-a-human-in-the-loop-approval-span-has-clo.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-planning-span-s-next-step-attribute-as-non-authoritative-once-a-human-in-the-loop-approval-span-has-clo.warrant.json
# Markdown SHA-256:   a29916332b501e5b3ab9a8db04ae4273fc3234eb71d842fd8bed85d96bf85dbc
# Code AST SHA-256:   c0f0cadc180e496be7681400419ef6567698c83f664766328248373be70e3698
# Verified Classes:   StaleIntentReadError, PlanSpan, ApprovalSpan
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleIntentReadError(RuntimeError):
    """Raised when resumption would execute a plan step that a closed
    approval span has amended or that an open approval span still gates."""


@dataclass
class PlanSpan:
    plan_id: str
    next_step: str
    end_ts: float


@dataclass
class ApprovalSpan:
    plan_id: str
    state: str                      # "open" | "closed" | "abandoned"
    decision: Optional[str]         # "approved" | "approved_with_edits" | "approved_subset" | "rejected"
    amended_next_step: Optional[str]
    end_ts: float


def resolve_governing_step(
    plan: PlanSpan,
    approval: Optional[ApprovalSpan],
) -> str:
    """Apply approval-aware precedence. Returns the step the instance is
    authorized to execute, or raises rather than falling through to the
    plan's unapproved proposal."""

    if approval is None:
        # No approval span for this plan id: plan is authoritative only if
        # the caller has proven it is reading the trace tail. We cannot prove
        # that here, so require the caller to have passed a tail-verified plan.
        return plan.next_step

    if approval.plan_id != plan.plan_id:
        raise StaleIntentReadError(
            f"approval {approval.plan_id!r} does not correlate to plan {plan.plan_id!r}"
        )

    if approval.state == "open":
        # Pending human decision must block, never fall through to plan.
        raise StaleIntentReadError(
            f"plan {plan.plan_id!r} has an open approval span; "
            f"executing proposed step {plan.next_step!r} would bypass human-in-the-loop"
        )

    if approval.state == "abandoned":
        raise StaleIntentReadError(
            f"approval for plan {plan.plan_id!r} was abandoned; re-request approval"
        )

    if approval.decision == "approved":
        return plan.next_step

    if approval.decision in ("approved_with_edits", "approved_subset"):
        if approval.amended_next_step is None:
            raise StaleIntentReadError(
                f"approval for plan {plan.plan_id!r} is {approval.decision!r} "
                f"but carries no amended_next_step; ambiguity must fail closed"
            )
        return approval.amended_next_step

    if approval.decision == "rejected":
        raise StaleIntentReadError(
            f"plan {plan.plan_id!r} was rejected by human approver; halt delegation"
        )

    raise StaleIntentReadError(
        f"unrecognized approval decision {approval.decision!r} for plan {plan.plan_id!r}"
    )


def resume_delegation(plan: PlanSpan, approval: Optional[ApprovalSpan]) -> str:
    step = resolve_governing_step(plan, approval)
    if approval is not None and approval.state == "closed" and approval.decision != "approved":
        if step == plan.next_step:
            # Defensive: precedence returned the proposed step despite amendment.
            raise StaleIntentReadError(
                f"resolved step {step!r} equals pre-amendment proposal for "
                f"plan {plan.plan_id!r}; stale-intent read detected"
            )
    return step
