# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-silent-loss-of-the-negative-evidence-invariant-under-budget-adaptive-context-controllers.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-silent-loss-of-the-negative-evidence-invariant-under-budget-adaptive-context-controllers.warrant.json
# Markdown SHA-256:   e638c043eece6fe8110b2d85df4fab9c03de2b2b0d4f7c77457cc508cba59c0d
# Code AST SHA-256:   8027840447dbda425a5ae1e40f649041e561605dbaa8a77a2d3201e8d82af5c1
# Verified Classes:   Polarity, MemoryEntry, ConstraintEvictionError, SelfEditingContextController
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Polarity(Enum):
    POSITIVE = "positive"
    NEGATIVE = "negative"


@dataclass(frozen=True)
class MemoryEntry:
    tool: str
    argument_binding: str
    polarity: Polarity
    error_code: Optional[str] = None
    text: str = ""


class ConstraintEvictionError(RuntimeError):
    """Raised when a context controller would silently drop the last
    negative-evidence record for a (tool, binding) pair."""


class SelfEditingContextController:
    def __init__(self, budget_tokens: int, saturation_ratio: float = 0.80):
        self.budget = budget_tokens
        self.saturation = saturation_ratio
        # The constraint register is authoritative and score-immune.
        self._constraint_register: dict[tuple[str, str], MemoryEntry] = {}
        # The editable working buffer.
        self._buffer: list[MemoryEntry] = []

    def record(self, entry: MemoryEntry) -> None:
        if entry.polarity is Polarity.NEGATIVE:
            key = (entry.tool, entry.argument_binding)
            # Monotone growth: never overwrite a failure with a success.
            self._constraint_register.setdefault(key, entry)
        self._buffer.append(entry)

    def _would_drop_constraint(self, evicted: list[MemoryEntry]) -> Optional[tuple[str, str]]:
        for entry in evicted:
            if entry.polarity is Polarity.NEGATIVE:
                key = (entry.tool, entry.argument_binding)
                # Is this the last in-buffer assertion of this failure?
                remaining = [
                    e for e in self._buffer
                    if e not in evicted
                    and e.polarity is Polarity.NEGATIVE
                    and (e.tool, e.argument_binding) == key
                ]
                if not remaining:
                    return key
        return None

    def dedup(self, similarity_threshold: float = 0.92) -> None:
        # Polarity-gated dedup: collapse only same-polarity entries.
        survivors: list[MemoryEntry] = []
        for entry in self._buffer:
            dup = next(
                (
                    s for s in survivors
                    if s.polarity is entry.polarity
                    and s.tool == entry.tool
                    and s.argument_binding == entry.argument_binding
                ),
                None,
            )
            if dup is None:
                survivors.append(entry)
        self._buffer = survivors

    def evict_bottom(self, fraction: float, score_fn) -> None:
        n = max(1, int(len(self._buffer) * fraction))
        ranked = sorted(self._buffer, key=score_fn)
        evicted = ranked[:n]
        dropped = self._would_drop_constraint(evicted)
        if dropped is not None:
            raise ConstraintEvictionError(
                f"eviction would drop the last negative-evidence record for "
                f"tool={dropped[0]!r} binding={dropped[1]!r}; "
                f"retain it, raise budget, or emit CONSTRAINT_DROPPED"
            )
        self._buffer = [e for e in self._buffer if e not in evicted]

    def assert_invariant(self, observed_attempts: dict[tuple[str, str], int]) -> None:
        for key, count in observed_attempts.items():
            if key not in self._constraint_register:
                raise ConstraintEvictionError(
                    f"attempt register shows {count} failed attempts for "
                    f"tool={key[0]!r} binding={key[1]!r} but no failure is retained"
                )
