# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-freeze-self-editing-of-working-memory-when-a-rewrite-plan-s-projected-token-savings-are-non-monotonic-under-re.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-freeze-self-editing-of-working-memory-when-a-rewrite-plan-s-projected-token-savings-are-non-monotonic-under-re.warrant.json
# Markdown SHA-256:   0e4d1cf58918cf00f4bcbc1f9dedcd7037db453de6aad9bdcdd2993862d2b56f
# Code AST SHA-256:   576194131fee86407b880f7f50b1fce071bd90c45cc9f0111869d70b98c34c44
# Verified Classes:   CompactionFreezeError, WorkingBuffer, RewritePlan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CompactionFreezeError(RuntimeError):
    """Raised when a self-edit of working memory is attempted on a buffer
    whose provenance or fact-set makes single-application reduction unsound."""


@dataclass(frozen=True)
class WorkingBuffer:
    text: str
    tokens: int
    pinned_facts: FrozenSet[str]
    # provenance: None = first-generation source, "v1","v2" = descendant of a prior rewrite
    provenance: str | None = None


@dataclass
class RewritePlan:
    rewritten: WorkingBuffer
    projected_savings: int
    retained_facts: FrozenSet[str]


def commit_self_edit(source: WorkingBuffer, plan: RewritePlan, *, min_savings_margin: int = 2048) -> WorkingBuffer:
    # 1. Provenance gate: descendant buffers must never be re-summarized.
    if source.provenance is not None:
        raise CompactionFreezeError(
            f"refusing to compact buffer with provenance={source.provenance!r}; "
            "re-summarizing a descendant rewrite is non-monotonic under re-execution"
        )

    # 2. Fact-set gate: size reduction does not imply fact retention.
    missing = source.pinned_facts - plan.retained_facts
    if missing:
        raise CompactionFreezeError(
            f"rewrite dropped pinned facts {sorted(missing)}; size savings alone are unsound"
        )

    # 3. Redundancy floor: savings must exceed rewrite-size variance margin.
    if plan.projected_savings <= min_savings_margin:
        raise CompactionFreezeError(
            f"projected savings {plan.projected_savings} <= margin {min_savings_margin}; "
            "buffer is near the redundancy floor, gate inverts — freeze and evict deterministically"
        )

    # 4. Commit, tagging the result as a descendant so it can never be a source again.
    return WorkingBuffer(
        text=plan.rewritten.text,
        tokens=plan.rewritten.tokens,
        pinned_facts=plan.rewritten.pinned_facts,
        provenance="v1",
    )


def resume_from_checkpoint(buf: WorkingBuffer) -> WorkingBuffer:
    # Absence of provenance is default-deny, not evidence of first-generation status.
    if buf.provenance is None and buf.text.startswith("# compacted:"):
        raise CompactionFreezeError(
            "checkpoint buffer carries compaction sentinel but no provenance tag; "
            "treat as descendant and require replay before any further self-edit"
        )
    return buf
