# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-freeze-scratchpad-rewrites-when-per-turn-context-budget-reallocation-invalidates-its-own-compaction-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-freeze-scratchpad-rewrites-when-per-turn-context-budget-reallocation-invalidates-its-own-compaction-provenance.warrant.json
# Markdown SHA-256:   30bdee91c58274eed61ab76b0a963d8dd6ee3cc2244838156c1c61309a799033
# Code AST SHA-256:   7d735631a370b148ab887210860637377f01b4fd32b73f7ea580a73957662bfd
# Verified Classes:   ProvenanceOrphaned, Fact, Scratchpad
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceOrphaned(RuntimeError):
    """Raised when a scratchpad rewrite would sever a fact's verification provenance."""
    pass


@dataclass
class Fact:
    text: str
    verified_at_turn: int
    pointer_region: str          # region name where the verification evidence lives
    reconstructed: bool = False


@dataclass
class Scratchpad:
    facts: list[Fact] = field(default_factory=list)
    authored_under_budget: int = 0


def rewrite_scratchpad(
    scratch: Scratchpad,
    new_budget: int,
    region_sizes: dict[str, int],
    reachable_regions: set[str],
    is_lossy_compressor: bool = True,
) -> Scratchpad:
    # Freeze condition: shrinking budget + orphaned pointers + lossy rewrite.
    shrinking = new_budget < scratch.authored_under_budget
    orphaned = [
        f for f in scratch.facts
        if f.pointer_region not in reachable_regions
        or region_sizes.get(f.pointer_region, 0) <= 0
    ]
    if shrinking and orphaned and is_lossy_compressor:
        names = ", ".join(f.text[:40] for f in orphaned)
        raise ProvenanceOrphaned(
            f"Refusing rewrite: budget {scratch.authored_under_budget}->{new_budget} "
            f"orphans {len(orphaned)} provenance pointer(s): [{names}]. "
            f"Freeze scratchpad and surface to orchestrator; do not reconstruct."
        )

    # Safe path: append-only or expanding budget with resolvable pointers.
    new_facts = []
    for f in scratch.facts:
        if f.pointer_region not in reachable_regions:
            # Explicit drop, never silent reconstruction.
            continue
        new_facts.append(f)
    return Scratchpad(facts=new_facts, authored_under_budget=new_budget)


def attempt_turn(scratch: Scratchpad, budget: int, regions: dict[str, int],
                 reachable: set[str]) -> Scratchpad:
    try:
        return rewrite_scratchpad(scratch, budget, regions, reachable)
    except ProvenanceOrphaned:
        # Emit current state unchanged; schedule re-verification instead.
        return scratch
