# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-the-self-edit-observation-paradox-and-the-relevance-reweighting-ratchet.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-the-self-edit-observation-paradox-and-the-relevance-reweighting-ratchet.warrant.json
# Markdown SHA-256:   1dc234bd4e09acffd552c94ebab01c055686d35b578530ec4a2a7931c5330fd5
# Code AST SHA-256:   de6c139289013cf05476cc4931b0b9ade27068c08a93278ddeb944c13d0c1c83
# Verified Classes:   ContextEditInvariantError, ContextItem, SelfEditingWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Literal

PinClass = Literal["constraint", "auth_scope", "irreversible_action", "plan_negation"]


class ContextEditInvariantError(RuntimeError):
    """Raised when a self-edit violates the reconstructibility or pinning invariant."""


@dataclass
class ContextItem:
    text: str
    relevance: float
    pin: PinClass | None = None

    @property
    def digest(self) -> str:
        return hashlib.sha256(self.text.encode("utf-8")).hexdigest()[:16]


@dataclass
class SelfEditingWindow:
    items: list[ContextItem] = field(default_factory=list)
    side_store: dict[str, ContextItem] = field(default_factory=dict)
    eviction_ledger: list[str] = field(default_factory=list)

    def prune(self, threshold: float = 0.3) -> None:
        survivors: list[ContextItem] = []
        for item in self.items:
            # Pinned items are never relevance-gated.
            if item.pin is not None or item.relevance >= threshold:
                survivors.append(item)
            else:
                self.side_store[item.digest] = item
                self.eviction_ledger.append(item.digest)

        pre = {i.digest for i in self.items}
        post = {i.digest for i in survivors} | set(self.side_store)
        if pre != post:
            # An eviction dropped an item without recording it: lossy edit.
            lost = pre - post
            raise ContextEditInvariantError(
                f"lossy prune: {sorted(lost)} vanished from window and side store"
            )
        self.items = survivors

    def readmit_on_contradiction(self, signal: str) -> None:
        """Re-admit a pinned fact when a contradicting signal (e.g. HTTP 429) arrives."""
        for digest, item in list(self.side_store.items()):
            if item.pin == "constraint" and "rate" in item.text.lower():
                self.items.append(item)
                del self.side_store[digest]
                return
        raise ContextEditInvariantError(
            f"contradiction {signal!r} has no pinned fact to re-admit; "
            "constraint was never pinned at insertion time"
        )


def enforce_pin_at_insertion(window: SelfEditingWindow, item: ContextItem) -> None:
    if item.pin is None and any(
        kw in item.text.lower() for kw in ("req/min", "rate limit", "scope:", "irreversible")
    ):
        raise ContextEditInvariantError(
            f"unpinned load-bearing fact inserted: {item.digest}; "
            "classifier must assign a pin before it can enter the window"
        )
    window.items.append(item)
