# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-pruning-as-a-destructive-non-idempotent-state-transition-rather-than-a-retrieval-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-pruning-as-a-destructive-non-idempotent-state-transition-rather-than-a-retrieval-refresh.warrant.json
# Markdown SHA-256:   5c8ad106ef76b35c6238dfb89e446ad6e316daef11417abd94fa45f481b5e8b3
# Code AST SHA-256:   57a0dbcce973fa8bdd3c65b53a5055e82cd352fe0ce945303b5a318aadfe55cb
# Verified Classes:   ContextIntegrityError, Shard, WorkingMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ContextIntegrityError(RuntimeError):
    """Raised when a self-edit violates the protected-set or reversibility invariant."""


@dataclass
class Shard:
    id: str
    text: str
    protected: bool          # classified at ingestion, never scored
    source_ref: str          # pointer into append-only backing store


@dataclass
class WorkingMemory:
    live: dict[str, Shard] = field(default_factory=dict)
    backing: dict[str, str] = field(default_factory=dict)  # immutable, model cannot write
    protected_ids: set[str] = field(default_factory=set)

    def ingest(self, shard: Shard) -> None:
        self.backing[shard.source_ref] = shard.text
        self.live[shard.id] = shard
        if shard.protected:
            self.protected_ids.add(shard.id)


def apply_prune(mem: WorkingMemory, scores: dict[str, float], threshold: float) -> None:
    """Model-driven prune. Must fail closed on any protected or unrecoverable shard."""
    to_drop = [sid for sid, s in scores.items() if s < threshold]

    for sid in to_drop:
        if sid in mem.protected_ids:
            raise ContextIntegrityError(
                f"prune targeted protected constraint shard {sid!r}; "
                "relevance scoring must not see the protected partition"
            )
        shard = mem.live.get(sid)
        if shard is None:
            continue
        if shard.source_ref not in mem.backing:
            raise ContextIntegrityError(
                f"shard {sid!r} has no byte-recoverable backing ref {shard.source_ref!r}; "
                "prune would be irreversible"
            )
        # prune == pointer drop, never delete from backing
        del mem.live[sid]


def apply_rewrite(mem: WorkingMemory, sid: str, rewritten: str, entailed: bool) -> None:
    """Rewrite must shadow, not overwrite, and must be entailed by source."""
    shard = mem.live[sid]
    if sid in mem.protected_ids:
        raise ContextIntegrityError(f"rewrite targeted protected shard {sid!r}")
    if not entailed:
        raise ContextIntegrityError(
            f"rewrite of {sid!r} is not entailed by source {shard.source_ref!r}; "
            "compression drift detected (e.g. hard_stop dropped)"
        )
    # shadow: live text changes, backing stays byte-exact for replay
    mem.live[sid] = Shard(sid, rewritten, shard.protected, shard.source_ref)


def replay_consistent(mem: WorkingMemory, seed_scores: dict[str, float], threshold: float) -> bool:
    """Idempotence check: pruning twice must equal pruning once."""
    clone = WorkingMemory(
        live=dict(mem.live), backing=dict(mem.backing), protected_ids=set(mem.protected_ids)
    )
    apply_prune(clone, seed_scores, threshold)
    before = set(clone.live)
    apply_prune(clone, seed_scores, threshold)
    return set(clone.live) == before
