# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-controllers-from-evicting-the-very-constraint-they-are-executing-under.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-controllers-from-evicting-the-very-constraint-they-are-executing-under.warrant.json
# Markdown SHA-256:   502cae2d5b7caebd79ae3342a3d0e996d96bbbb4e8ee4b0a36bc3770c9708c2a
# Code AST SHA-256:   9a4c0043ec3fc254ecdf973d0d2c04affced275fbd77bb72e6800b05f3c28406
# Verified Classes:   ProtectedFrameViolation, ContextItem, WorkingSet
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class ProtectedFrameViolation(RuntimeError):
    """Raised when a self-editing context controller attempts to evict or
    rewrite an item in the protected frame (invariants, task contract,
    permission manifest)."""


@dataclass
class ContextItem:
    slot: int
    text: str
    cls: str  # "INVARIANT" | "TASK" | "FINDING" | "TOOL_OUTPUT"


@dataclass
class WorkingSet:
    items: list[ContextItem]
    budget: int

    def tokens(self) -> int:
        # crude proxy; real impl uses the model tokenizer
        return sum(len(i.text.split()) for i in self.items)


PROTECTED_CLASSES = frozenset({"INVARIANT", "TASK"})

# Controller is a black box: given the *editable* items and a budget,
# returns the subset it chooses to keep. It never sees protected items.
Controller = Callable[[list[ContextItem], int], list[ContextItem]]


def compact(
    ws: WorkingSet,
    controller: Controller,
    min_editable_tokens: int = 200,
) -> WorkingSet:
    protected = [i for i in ws.items if i.cls in PROTECTED_CLASSES]
    editable = [i for i in ws.items if i.cls not in PROTECTED_CLASSES]

    protected_tokens = sum(len(i.text.split()) for i in protected)
    editable_budget = ws.budget - protected_tokens

    if editable_budget < min_editable_tokens:
        # Do NOT evict invariants to make room. Fail loudly instead.
        raise ProtectedFrameViolation(
            f"protected frame ({protected_tokens} tok) leaves only "
            f"{editable_budget} tok for editable set; minimum is "
            f"{min_editable_tokens}. Split the task or raise budget; "
            f"do not trade invariants for task progress."
        )

    kept_editable = controller(editable, editable_budget)

    # Post-condition: controller must not have smuggled protected items
    # back in or dropped them. It was never handed them, so any protected
    # item in its output is a controller bug worth catching.
    if any(i.cls in PROTECTED_CLASSES for i in kept_editable):
        raise ProtectedFrameViolation(
            "controller returned items from the protected frame; "
            "editable region was not properly isolated"
        )

    # Invariants are re-materialized at the head of every rewrite,
    # verbatim, never re-derived from a prior summary.
    return WorkingSet(items=protected + kept_editable, budget=ws.budget)
