# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-self-prune-its-working-memory-into-a-state-that-no-longer-contains-the-evidence-justifying-the-prune-and-how-do-we-bound-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-self-prune-its-working-memory-into-a-state-that-no-longer-contains-the-evidence-justifying-the-prune-and-how-do-we-bound-it.warrant.json
# Markdown SHA-256:   8fe43d03cb5f21ed025479f99fef98e8208048981201fc53b3985fc1f1ccf8c6
# Code AST SHA-256:   9824e6eeef0b27e94e6f8f22a7759352dfb822ffad50d39420c22a38abc67c6e
# Verified Classes:   UnwitnessedPruneError, Entry, ContextBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class UnwitnessedPruneError(RuntimeError):
    """Raised when a self-editing policy evicts an entry whose justification
    does not survive in the post-prune buffer or in an external handle."""
    pass


@dataclass
class Entry:
    key: str
    content: str
    kind: str          # "derivable" | "witness"
    handle: Optional[str] = None   # re-derivation pointer, e.g. "read_file path@sha"
    pinned: bool = False


@dataclass
class ContextBuffer:
    entries: dict = field(default_factory=dict)
    external_log: dict = field(default_factory=dict)   # hash -> verbatim content

    def append_log(self, content: str) -> str:
        h = "sha256:" + hashlib.sha256(content.encode()).hexdigest()[:16]
        self.external_log[h] = content
        return h

    def prune(self, key: str, justification_handle: Optional[str]) -> None:
        e = self.entries.get(key)
        if e is None:
            return
        if e.pinned:
            raise UnwitnessedPruneError(f"cannot prune pinned entry {key!r}")
        if e.kind == "witness":
            # Witness content must be preserved losslessly before eviction.
            h = self.append_log(e.content)
            if justification_handle != h:
                raise UnwitnessedPruneError(
                    f"witness {key!r} evicted without matching external handle; "
                    f"expected {h!r}, got {justification_handle!r}"
                )
        elif e.kind == "derivable":
            if e.handle is None and justification_handle is None:
                raise UnwitnessedPruneError(
                    f"derivable {key!r} evicted without a re-derivation handle; "
                    f"content would become non-recoverable"
                )
        del self.entries[key]

    def audit(self, key: str) -> str:
        """Re-derive an evicted entry from its handle, or fail loudly."""
        if key in self.entries:
            return self.entries[key].content
        for h, content in self.external_log.items():
            if h == key or key in h:
                return content
        raise UnwitnessedPruneError(
            f"cannot audit {key!r}: no surviving entry and no external handle"
        )


def compact_round(buf: ContextBuffer, drop_plan: dict) -> None:
    """drop_plan: {key: justification_handle_or_None} emitted by the policy model."""
    for key, handle in drop_plan.items():
        buf.prune(key, handle)


# Reproduces the trace: turn-7 schema evicted as paraphrase with no handle.
buf = ContextBuffer()
buf.entries["schema"] = Entry("schema", "id/timestamp/owner fields", kind="witness")
try:
    compact_round(buf, {"schema": None})   # model said "already understood"
except UnwitnessedPruneError as exc:
    print("blocked:", exc)
