# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-lossy-checkpoint-rather-than-a-transparent-context-reset.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-lossy-checkpoint-rather-than-a-transparent-context-reset.warrant.json
# Markdown SHA-256:   9b232e136a2bf810d9fdf27b941b34c8a43ce054c62bfc8324c1a581e87b5908
# Code AST SHA-256:   4c27eca4ccb2cb754ba05735437d9df82bb1a4d3660207835f33f278aa1ee9f3
# Verified Classes:   CompactionError, Provenance, Claim, CompactionManifest, PlannedAction
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionError(RuntimeError):
    """Raised when a compaction event would grant write authority to unverified content."""
    pass


class Provenance(Enum):
    OBSERVED = "observed"   # traceable to a raw step
    INFERRED = "inferred"   # summarizer synthesis, not authoritative for writes


@dataclass
class Claim:
    text: str
    provenance: Provenance
    source_steps: tuple[int, ...] = ()


@dataclass
class CompactionManifest:
    compacted_range: tuple[int, int]
    claims: list[Claim] = field(default_factory=list)
    depth: int = 1  # 1 = first compaction over raw; >1 = summary-of-summary


@dataclass
class PlannedAction:
    tool: str
    mutates_state: bool
    depends_on: list[str]  # claim texts this action relies on


def authorize_action(manifest: CompactionManifest, action: PlannedAction) -> None:
    # Depth cap: lossy transforms do not compose safely over entity identity.
    if manifest.depth > 1:
        raise CompactionError(
            f"compaction depth {manifest.depth} exceeds cap; "
            "escalate to structured checkpoint-and-restart, not summary-of-summary"
        )

    if not action.mutates_state:
        return  # read-only divergence is bounded; allow routing from summary

    # A mutating action may not rest on an INFERRED claim.
    by_text = {c.text: c for c in manifest.claims}
    for dep in action.depends_on:
        claim = by_text.get(dep)
        if claim is None:
            raise CompactionError(
                f"action {action.tool!r} depends on {dep!r} absent from manifest; "
                "cannot establish provenance"
            )
        if claim.provenance is Provenance.INFERRED:
            raise CompactionError(
                f"action {action.tool!r} would mutate state on inferred claim "
                f"{dep!r} (source_steps={claim.source_steps}); "
                "re-ground against live state before write"
            )


# --- reproduction of the observed failure ---
manifest = CompactionManifest(
    compacted_range=(1, 22),
    claims=[Claim("The schema was already migrated to v3.", Provenance.INFERRED, (1, 22))],
)
action = PlannedAction(
    tool="apply_migration",
    mutates_state=True,
    depends_on=["The schema was already migrated to v3."],
)

try:
    authorize_action(manifest, action)
except CompactionError as e:
    print(f"BLOCKED: {e}")
