# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-self-pruned-context-as-a-lossy-transform-not-a-lossless-one-the-summary-absorption-divergence-when-an-agent-compacts-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-self-pruned-context-as-a-lossy-transform-not-a-lossless-one-the-summary-absorption-divergence-when-an-agent-compacts-it.warrant.json
# Markdown SHA-256:   c3404a280c9a4a1f2ebe2eca9eabc42df32233a29d8cc7ccaec65da017bb035e
# Code AST SHA-256:   36cb5b3d18611748eca183d814649a32f47e7b1f9ef7e4787eeddb36f68c9ae0
# Verified Classes:   CompactionError, ItemClass, ContextItem, CompactionResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CompactionError(RuntimeError):
    """Raised when a self-compaction would destroy unrecoverable state."""


class ItemClass(Enum):
    RE_DERIVABLE = "re_derivable"      # safe to drop; re-fetch on demand
    DERIVED = "derived"                # safe to summarize; mark as derived
    DECISION = "decision"              # user instruction / chosen approach
    CONSTRAINT = "constraint"          # policy / one-shot external fact


# Items whose loss is unrecoverable must be tombstoned, never absorbed.
NON_REDERIVABLE = {ItemClass.DECISION, ItemClass.CONSTRAINT}


@dataclass
class ContextItem:
    key: str
    body: str
    cls: ItemClass


@dataclass
class CompactionResult:
    retained: list[ContextItem] = field(default_factory=list)
    summary: str = ""
    tombstones: list[str] = field(default_factory=list)


def compact(
    items: Iterable[ContextItem],
    budget_tokens: int,
    in_flight_step: bool,
    token_cost=lambda it: max(1, len(it.body) // 4),
) -> CompactionResult:
    """Self-compaction with tombstone enforcement.

    Invariants enforced:
      1. No compaction while a mutating step is in flight.
      2. Every non-re-derivable drop is tombstoned verbatim.
      3. Tombstones count against the budget; if they don't fit, escalate.
    """
    if in_flight_step:
        raise CompactionError(
            "compaction attempted mid-step; rewrite only at quiescent points "
            "or a constraint can be absorbed while the step that needs it runs"
        )

    items = list(items)
    result = CompactionResult()
    used = 0

    for it in items:
        cost = token_cost(it)
        if it.cls in NON_REDERIVABLE:
            # Must be preserved verbatim OR tombstoned; never silently absorbed.
            if used + cost <= budget_tokens:
                result.retained.append(it)
                used += cost
            else:
                tomb = f"DROPPED_{it.cls.name}:{it.key}={it.body!r}"
                result.tombstones.append(tomb)
                used += token_cost(ContextItem(it.key, tomb, it.cls))
        elif it.cls is ItemClass.DERIVED:
            result.summary += f"[derived] {it.body}\n"
            used += token_cost(it)
        # RE_DERIVABLE: dropped, re-fetched on demand; no tombstone needed.

    # Tombstones are not free: they occupy budget. If they don't fit, we must
    # escalate rather than drop them (dropping a tombstone re-creates the bug).
    if used > budget_tokens:
        raise CompactionError(
            f"compaction over budget by {used - budget_tokens} tokens with "
            f"{len(result.tombstones)} tombstones; escalate (spill to external "
            f"store or reduce scope) instead of dropping unrecoverable state"
        )

    return result


def resume_step(result: CompactionResult, step_key: str) -> None:
    """Guard called before any mutating step that depends on compacted state."""
    for tomb in result.tombstones:
        if step_key in tomb:
            raise CompactionError(
                f"step {step_key!r} depends on a tombstoned item: {tomb}. "
                f"Re-fetch or re-apply the constraint before proceeding; do not "
                f"trust the summary as a faithful record of the pre-compaction state."
            )
