# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-lossy-auto-compaction-with-recovery-markers-before-the-summarizer-s-own-reasoning-trace-is-evicted-from-the-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-lossy-auto-compaction-with-recovery-markers-before-the-summarizer-s-own-reasoning-trace-is-evicted-from-the-transcript.warrant.json
# Markdown SHA-256:   9dbbc23e572ef7818074e0609da3bff987b28250d4f054a19d45795271c9c77a
# Code AST SHA-256:   fb604e7b7abaf6a4dd6a70c51c9e7b85b54b99a6f914de9d65bbaf508d2af032
# Verified Classes:   CompactionBoundaryError, ItemStatus, Anchor, RecoveryMarker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CompactionBoundaryError(RuntimeError):
    """Raised when a compaction would launder provisional state into settled state."""


class ItemStatus(Enum):
    SETTLED = "settled"
    PROVISIONAL = "provisional"


@dataclass
class Anchor:
    item_id: str
    status: ItemStatus
    provenance: Optional[str] = None          # tool call id / file hash, survives compaction
    partiality_reason: Optional[str] = None   # required if PROVISIONAL
    recheck_action: Optional[str] = None      # cheapest re-verification, required if PROVISIONAL


@dataclass
class RecoveryMarker:
    plan_position: int
    anchors: list[Anchor] = field(default_factory=list)


def build_marker(position: int, anchors: list[Anchor]) -> RecoveryMarker:
    """Validate anchors before they are allowed into a recovery marker.

    Invariant: every PROVISIONAL anchor must carry a partiality reason and a
    recheck action, so a future instance can falsify the summary from the marker
    alone. Every SETTLED anchor must carry provenance.
    """
    for a in anchors:
        if a.status is ItemStatus.PROVISIONAL:
            if not a.partiality_reason or not a.recheck_action:
                raise CompactionBoundaryError(
                    f"provisional item {a.item_id!r} lacks partiality_reason/recheck_action; "
                    f"it would be laundered into settled state on compaction"
                )
        elif a.status is ItemStatus.SETTLED:
            if not a.provenance:
                raise CompactionBoundaryError(
                    f"settled item {a.item_id!r} has no provenance pointer; "
                    f"summary would be unfalsifiable post-compaction"
                )
    return RecoveryMarker(plan_position=position, anchors=anchors)


def advance_plan(marker: RecoveryMarker, target_position: int) -> int:
    """Refuse to advance the plan past any unverified provisional item."""
    blocking = [
        a for a in marker.anchors
        if a.status is ItemStatus.PROVISIONAL
    ]
    if blocking and target_position > marker.plan_position:
        raise CompactionBoundaryError(
            f"cannot advance to position {target_position}: "
            f"{len(blocking)} provisional item(s) unresolved "
            f"({', '.join(a.item_id for a in blocking)}); re-verify before progressing"
        )
    return target_position
