# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-dynamic-system-prompt-rewriting-as-a-monotonic-slot-allocation-problem-rather-than-an-idempotent-text-update.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-dynamic-system-prompt-rewriting-as-a-monotonic-slot-allocation-problem-rather-than-an-idempotent-text-update.warrant.json
# Markdown SHA-256:   d76ee008e93f25f72399572312711dadd4280e86cddc67125c43399d7aa2cd42
# Code AST SHA-256:   79bfc592410d87cf961c4aab8f9e2dd8bfefbb48341fc14607825f66eef724c8
# Verified Classes:   SlotBudgetExceeded, SlotVector
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

SlotName = Literal["base_policy", "persona", "reflexes", "safety_override"]

# Priority: higher number = more protected from eviction.
PRIORITY: dict[SlotName, int] = {
    "safety_override": 3,
    "base_policy": 2,
    "persona": 1,
    "reflexes": 0,
}


class SlotBudgetExceeded(RuntimeError):
    """Raised when a self-edit would require evicting a slot it may not evict."""


@dataclass
class SlotVector:
    cap: int
    slots: dict[SlotName, list[str]] = field(default_factory=dict)

    def total(self) -> int:
        return sum(len(line) for lines in self.slots.values() for line in lines)

    def _semantic_key(self, line: str) -> str:
        # Toy semantic dedup: normalize whitespace and common paraphrase markers.
        return " ".join(line.lower().replace("use ", "").replace("--", "").split())

    def append(self, slot: SlotName, line: str) -> None:
        existing = {self._semantic_key(l) for l in self.slots.get(slot, [])}
        if self._semantic_key(line) in existing:
            return  # idempotent on semantic content, not raw bytes
        target = self.slots.setdefault(slot, [])
        target.append(line)
        if self.total() > self.cap:
            self._evict_for(slot, len(line))

    def _evict_for(self, requester: SlotName, needed: int) -> None:
        # Only evict slots of strictly lower priority than the requester.
        requester_prio = PRIORITY[requester]
        candidates = sorted(
            (s for s in self.slots if PRIORITY[s] < requester_prio and self.slots[s]),
            key=lambda s: PRIORITY[s],
        )
        freed = 0
        for s in candidates:
            while self.slots[s] and freed < needed:
                freed += len(self.slots[s].pop(0))
            if freed >= needed:
                return
        # Could not free enough without touching protected slots.
        raise SlotBudgetExceeded(
            f"edit to {requester!r} needs {needed} chars but only {freed} "
            f"evictable from lower-priority slots; refusing silent truncation"
        )

    def checkpoint(self) -> dict[SlotName, list[str]]:
        # Slot-indexed snapshot; replay reconstructs by index, not append.
        return {k: list(v) for k, v in self.slots.items()}
