# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-the-self-rewrite-feedback-loop-when-pruning-its-own-working-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-the-self-rewrite-feedback-loop-when-pruning-its-own-working-memory.warrant.json
# Markdown SHA-256:   b43ec51a850adb157c517b91512132f9e2edcf9569413839baad9a6ae49299d6
# Code AST SHA-256:   eea38dfb9a9b27ab8bc413f4aec749698e88fe57492d5143cec83a3e4b6ffee9
# Verified Classes:   SelfEditInvariantError, WorkingMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SelfEditInvariantError(RuntimeError):
    """Raised when a self-edit would invalidate the policy that produced it."""
    pass


class WorkingMemory:
    def __init__(self, policy_hash: str):
        self.policy_hash = policy_hash
        self.entries = {}          # id -> (payload, provenance_id or None)
        self.snapshot = {}         # pre-rewrite raw entries, retained for audit
        self.last_prune_policy = policy_hash

    def stage_rewrite(self, entry_id: str, new_payload: str) -> None:
        if entry_id not in self.entries:
            raise SelfEditInvariantError(f"cannot rewrite unknown entry {entry_id!r}")
        raw = self.entries[entry_id][0]
        self.snapshot[entry_id] = raw
        # provenance points to the raw entry; raw is retained
        self.entries[entry_id] = (new_payload, entry_id)

    def prune(self, keep_ids: set[str]) -> None:
        # Invariant: the prune policy must be identical to the one that
        # scored the pre-rewrite snapshot. If rewrites changed the policy
        # or the input set, the prune is invalid.
        if self.policy_hash != self.last_prune_policy:
            raise SelfEditInvariantError(
                "prune policy changed since last pass; re-score from snapshot"
            )
        rewritten = {eid for eid, (_, prov) in self.entries.items() if prov is not None}
        # Reject if we would prune every raw anchor for a rewritten entry.
        for eid in rewritten:
            anchor = self.entries[eid][1]
            if anchor not in keep_ids and anchor not in self.snapshot:
                raise SelfEditInvariantError(
                    f"pruning anchor {anchor!r} of rewritten entry {eid!r} "
                    "would make the retained set unauditable"
                )
        for eid in list(self.entries):
            if eid not in keep_ids:
                del self.entries[eid]
        self.last_prune_policy = self.policy_hash


def commit_self_edit(mem: WorkingMemory, keep_ids: set[str]) -> None:
    if not keep_ids:
        raise SelfEditInvariantError("refusing to prune entire working memory")
    mem.prune(keep_ids)
