# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-rewrite-of-its-working-set-as-a-non-atomic-transaction-with-a-versioned-shadow-buffer.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-rewrite-of-its-working-set-as-a-non-atomic-transaction-with-a-versioned-shadow-buffer.warrant.json
# Markdown SHA-256:   dce4e9739005f920362ef73f3a21ed21c61aa2744d83ddc2b1d956fd8d25320c
# Code AST SHA-256:   65e5475ca40d602e76932a769e1407ea56b48fbe69197cb81eec3658eafdd344
# Verified Classes:   RegionClass, RewriteInvariantError, ContextItem
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class RegionClass(Enum):
    PINNED = "pinned"          # verbatim or pointer only; never paraphrased
    COMPRESSIBLE = "compressible"
    VOLATILE = "volatile"


class RewriteInvariantError(RuntimeError):
    """Raised when a self-rewrite would paraphrase a pinned fact or
    exceed the generative-compaction depth cap."""
    pass


@dataclass(frozen=True)
class ContextItem:
    key: str
    text: str
    region: RegionClass
    source_hash: str          # hash of authoritative source
    gen_passes: int = 0       # how many generative summaries touched this


MAX_GEN_PASSES = 2


def apply_rewrite(
    working_set: list[ContextItem],
    proposed: list[ContextItem],
    budget_tokens: int,
    token_len,
) -> list[ContextItem]:
    """Validate a proposed self-rewrite against the pinned-fact invariant
    and compaction-depth cap before committing it."""
    pinned_before = {i.key: i for i in working_set if i.region is RegionClass.PINNED}
    proposed_by_key = {i.key: i for i in proposed}

    # Invariant 1: pinned facts survive byte-identically or via resolvable pointer.
    for key, orig in pinned_before.items():
        new = proposed_by_key.get(key)
        if new is None:
            raise RewriteInvariantError(
                f"pinned fact '{key}' dropped entirely; must evict verbatim "
                f"with pointer, not omit"
            )
        if new.source_hash != orig.source_hash:
            raise RewriteInvariantError(
                f"pinned fact '{key}' paraphrased (source_hash "
                f"{orig.source_hash!r} -> {new.source_hash!r}); paraphrase "
                f"of constraints is not entailment-preserving"
            )

    # Invariant 2: no item exceeds generative-compaction depth cap.
    for item in proposed:
        if item.gen_passes > MAX_GEN_PASSES:
            raise RewriteInvariantError(
                f"item '{item.key}' summarized {item.gen_passes} times; "
                f"paraphrase is not idempotent — re-fetch from source or drop"
            )

    # Invariant 3: budget is a hard ceiling, not a license to paraphrase.
    total = sum(token_len(i.text) for i in proposed)
    if total > budget_tokens:
        raise RewriteInvariantError(
            f"rewrite exceeds budget ({total} > {budget_tokens}); "
            f"escalate/checkpoint — do not paraphrase pinned facts to fit"
        )

    return proposed


def compact_under_pressure(
    working_set: list[ContextItem],
    budget_tokens: int,
    token_len,
    summarize,
) -> list[ContextItem]:
    """Compaction driver: only COMPRESSIBLE items may be generatively
    summarized; PINNED survive verbatim; VOLATILE are evicted post-parse."""
    if sum(token_len(i.text) for i in working_set) <= budget_tokens:
        return working_set

    candidate = []
    for item in working_set:
        if item.region is RegionClass.VOLATILE:
            continue  # evict after structured parse
        if item.region is RegionClass.PINNED:
            candidate.append(item)  # verbatim, never summarized
            continue
        if item.gen_passes >= MAX_GEN_PASSES:
            # Cannot summarize further; must re-fetch or drop, not paraphrase.
            raise RewriteInvariantError(
                f"compressible item '{item.key}' at depth cap "
                f"{item.gen_passes}; re-fetch from source before compacting"
            )
        candidate.append(
            ContextItem(
                key=item.key,
                text=summarize(item.text),
                region=item.region,
                source_hash=item.source_hash,
                gen_passes=item.gen_passes + 1,
            )
        )

    return apply_rewrite(working_set, candidate, budget_tokens, token_len)
