# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-self-editing-context-policies-when-a-rewrite-invalidates-the-retrieval-keys-that-justified-the-prune.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-self-editing-context-policies-when-a-rewrite-invalidates-the-retrieval-keys-that-justified-the-prune.warrant.json
# Markdown SHA-256:   10764b7e3a82295613c7497a491a5a4eab60cc44f64bc5cae864f2bd330360a7
# Code AST SHA-256:   60c7266381827644b341b029cb563fbf8b3b49faab9a67584933ef33d667afdf
# Verified Classes:   RewriteEvictionError, MemoryItem, EditPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class RewriteEvictionError(RuntimeError):
    """Raised when a self-edit lowers an artifact's retention score below the
    threshold that admitted its source — i.e. a compression that is really an
    eviction disguised as a budget win."""
    pass


@dataclass
class MemoryItem:
    item_id: str
    text: str
    embedding_score: float          # similarity to current query set
    generation: int = 0
    source_ref: str | None = None   # back-pointer to immutable source


@dataclass
class EditPolicy:
    theta_retain: float = 0.55
    margin_delta: float = 0.10
    g_max: int = 2
    pinned: set[str] = field(default_factory=set)


def revalidate_and_commit(
    policy: EditPolicy,
    source: MemoryItem,
    artifact: MemoryItem,
    rescore_fn,  # callable(text) -> float, embeds artifact vs current query set
) -> MemoryItem:
    """Gate a rewrite on re-scoring the artifact, not the source."""
    artifact.embedding_score = rescore_fn(artifact.text)
    artifact.generation = source.generation + 1
    artifact.source_ref = source.item_id

    # Rule 1: re-score before commit. A rewrite that drops below threshold is an eviction.
    if source.embedding_score >= policy.theta_retain and artifact.embedding_score < policy.theta_retain:
        raise RewriteEvictionError(
            f"rewrite of {source.item_id} scored {artifact.embedding_score:.2f} "
            f"< theta_retain {policy.theta_retain:.2f} (source scored "
            f"{source.embedding_score:.2f}); reject or pin source"
        )

    # Rule 2: margin band — pin source when artifact lands in the danger band.
    band_lo = policy.theta_retain
    band_hi = policy.theta_retain + policy.margin_delta
    if band_lo <= artifact.embedding_score <= band_hi:
        policy.pinned.add(source.item_id)

    # Rule 3: cap rewrite lineage depth to bound superlinear drift.
    if artifact.generation > policy.g_max:
        if source.item_id not in policy.pinned:
            raise RewriteEvictionError(
                f"lineage {source.item_id} exceeded g_max={policy.g_max} "
                f"without a pinned source; force re-expansion, not re-summarize"
            )

    return artifact


# --- example trigger ---
if __name__ == "__main__":
    policy = EditPolicy()
    src = MemoryItem("M17", "retry wrapper double-wraps client; timeouts fire at 2x", 0.79)
    art = MemoryItem("M17'", "timeout observed; suspected retry interaction", 0.0)
    fake_rescore = lambda text: 0.41  # drifted embedding after abstract rewrite
    revalidate_and_commit(policy, src, art, fake_rescore)  # raises RewriteEvictionError
