# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-retention-rewrite-oscillation-trap-in-self-editing-context-controllers.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-retention-rewrite-oscillation-trap-in-self-editing-context-controllers.warrant.json
# Markdown SHA-256:   a46e7b694625f8235a743ac11c8cb1b9e8ae5b07eed4d9188d095e105d134756
# Code AST SHA-256:   2ea446f8e87a84418e3723a2ade3fcc846f2d893831f8264ce4cf492ef430dce
# Verified Classes:   RetentionUnmeasurableError, ContextGeneration, SelfEditingController
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RetentionUnmeasurableError(RuntimeError):
    """Raised when a compaction decision would be scored against a stale or
    invisible baseline. This is a measurement fault, not a retention failure,
    and must never be treated as a reason to rewrite forward."""
    pass


@dataclass
class ContextGeneration:
    generation: int
    token_count: int
    named_fact_baseline: int          # facts the estimator could name in THIS generation
    estimator_had_visibility: bool    # could the estimator see the prior generation?


@dataclass
class SelfEditingController:
    budget: int
    fold_fraction: float = 0.40
    deficit_threshold: int = 5
    history: list = field(default_factory=list)   # snapshots, newest last

    def _current(self) -> ContextGeneration:
        return self.history[-1]

    def _prior(self) -> Optional[ContextGeneration]:
        return self.history[-2] if len(self.history) >= 2 else None

    def check_retention(self, post_rewrite_named_facts: int) -> str:
        cur, prior = self._current(), self._prior()
        if prior is None:
            return "MEASURABLE_SATISFIED"  # nothing to compare against yet

        # Guard 1: baseline must be the immediately preceding generation.
        if cur.generation - prior.generation != 1:
            raise RetentionUnmeasurableError(
                f"baseline generation {prior.generation} is not current-1 "
                f"({cur.generation}); deficit would be scored against deleted memory"
            )

        # Guard 2: the estimator must have had visibility into the prior generation.
        if not cur.estimator_had_visibility:
            raise RetentionUnmeasurableError(
                "estimator could not see prior generation; retention is unmeasurable"
            )

        deficit = prior.named_fact_baseline - post_rewrite_named_facts

        # Guard 3: a drop larger than the entire prior baseline is arithmetically
        # impossible as genuine loss -> stale-baseline signature.
        if deficit > prior.named_fact_baseline:
            raise RetentionUnmeasurableError(
                f"deficit {deficit} exceeds prior baseline {prior.named_fact_baseline}; "
                "stale-baseline signature, refusing to rewrite"
            )

        if deficit > self.deficit_threshold:
            return "MEASURABLE_UNSATISFIED_ROLLBACK"
        return "MEASURABLE_SATISFIED"

    def compact(self) -> str:
        cur = self._current()
        if cur.token_count <= int(0.85 * self.budget):
            return "UNDER_BUDGET"

        # Refuse forward rewrite if measurability is already broken.
        try:
            state = self.check_retention(post_rewrite_named_facts=cur.named_fact_baseline)
        except RetentionUnmeasurableError:
            # Shed load by truncating verbatim tool output, never by rewriting memory.
            return "SHED_TOOL_OUTPUT_VERBATIM"

        if state == "MEASURABLE_UNSATISFIED_ROLLBACK":
            self.history.pop()  # roll back the over-aggressive rewrite
            return "ROLLBACK_AND_RETRY_SMALLER_FOLD"

        # Proceed with the rewrite, tagging the new generation explicitly.
        new_gen = ContextGeneration(
            generation=cur.generation + 1,
            token_count=int(cur.token_count * (1 - self.fold_fraction)),
            named_fact_baseline=cur.named_fact_baseline,  # re-derived after rewrite
            estimator_had_visibility=True,
        )
        self.history.append(new_gen)
        return "REWRITTEN"
