# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-self-pruned-context-window-as-a-lossy-transform-rather-than-a-compaction-and-refuse-to-resume-from-it-w.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-self-pruned-context-window-as-a-lossy-transform-rather-than-a-compaction-and-refuse-to-resume-from-it-w.warrant.json
# Markdown SHA-256:   a4224d2b2824e19e743ae8dc0de3ba891ef001e88958fff5c2c3f729d29173eb
# Code AST SHA-256:   928af096dbb656974273f8e5bde8978ba50373c1ec41949dab24a5ba3bab2418
# Verified Classes:   Provenance, BlastRadius, LossyResumeError, Span, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class Provenance(Enum):
    OBSERVED = "observed"   # verbatim tool result / user turn
    DERIVED = "derived"     # model-generated rewrite or summary


class BlastRadius(Enum):
    REVERSIBLE = "reversible"   # inspect, query, draft
    IRREVERSIBLE = "irreversible"  # bulk write, delete, deploy, send


class LossyResumeError(RuntimeError):
    """Raised when an agent attempts to authorize an irreversible action
    using only derived (rewritten) context, with no re-derivation warrant."""


@dataclass
class Span:
    handle: str
    text: str
    provenance: Provenance
    derived_from: tuple[str, ...] = field(default_factory=tuple)


@dataclass
class ContextWindow:
    spans: list[Span]
    durable_log: dict[str, Span]  # handle -> original observed span

    def observed_handles(self) -> set[str]:
        return {s.handle for s in self.spans if s.provenance is Provenance.OBSERVED}

    def rederive(self, handles: tuple[str, ...]) -> list[Span]:
        missing = [h for h in handles if h not in self.durable_log]
        if missing:
            raise LossyResumeError(
                f"cannot re-derive: handles not durable: {missing}"
            )
        return [self.durable_log[h] for h in handles]


def authorize_action(
    window: ContextWindow,
    governing_handles: tuple[str, ...],
    blast: BlastRadius,
) -> None:
    """Gate an action on whether its governing constraints are present
    as OBSERVED spans. Derived-only evidence may not authorize
    irreversible actions."""
    present = window.observed_handles()
    missing = [h for h in governing_handles if h not in present]

    if not missing:
        return  # constraints observed verbatim; safe to proceed

    if blast is BlastRadius.REVERSIBLE:
        return  # lossy window acceptable for reversible probes

    # Irreversible action with missing (possibly evicted) constraints:
    # attempt re-derivation from durable log before refusing.
    try:
        window.rederive(tuple(missing))
    except LossyResumeError as exc:
        raise LossyResumeError(
            f"irreversible action blocked: governing constraints "
            f"{missing} absent from window and unrecoverable ({exc})"
        ) from exc

    raise LossyResumeError(
        f"irreversible action blocked: governing constraints {missing} "
        f"were evicted by self-prune; re-derive from durable log and "
        f"re-admit as OBSERVED before proceeding"
    )
