# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-referential-integrity-when-it-prunes-and-rewrites-its-own-working-memory-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-referential-integrity-when-it-prunes-and-rewrites-its-own-working-memory-mid-task.warrant.json
# Markdown SHA-256:   2b1a780b9b7dfc188dc70044666ecb6671e44f5c781c807d6cb349a50a6d88dc
# Code AST SHA-256:   a501779c05a0cf511e27465e5f8b19c7a0ae4bdedcae985551c820ac84b25040
# Verified Classes:   ReferentialIntegrityError, WorkingMemory
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class ReferentialIntegrityError(RuntimeError):
    """Raised when a self-edit drops or mutates a live binding."""
    pass


@dataclass
class WorkingMemory:
    # Byte-exact pinned bindings that pending steps will dereference.
    pinned: dict[str, str] = field(default_factory=dict)
    # Free-form narrative spans that are safe to compact.
    narrative: str = ""


def extract_pinned_literals(buffer: str, pending_refs: list[str]) -> dict[str, str]:
    """Collect literals that pending dereferences depend on.

    A literal is 'pinned' if it appears in a pending tool-call template.
    This is a structural scan, not a semantic judgment by the model.
    """
    pinned: dict[str, str] = {}
    for ref in pending_refs:
        for literal in re.findall(r'"[^"]+"|\b[\w.-]{6,}\b', ref):
            if literal in buffer:
                pinned[literal] = literal
    return pinned


def commit_self_edit(pre_edit: WorkingMemory, candidate_text: str) -> WorkingMemory:
    """Validate a model-proposed rewritten buffer before accepting it.

    The model proposes; this deterministic validator disposes.
    """
    missing = [lit for lit in pre_edit.pinned if lit not in candidate_text]
    if missing:
        raise ReferentialIntegrityError(
            "self-edit dropped live bindings; refusing to commit. "
            f"missing={missing!r}. Re-issue the edit with these spans pinned "
            "verbatim or externalize them to a re-queryable store first."
        )
    # Only narrative is allowed to be lossy.
    return WorkingMemory(pinned=dict(pre_edit.pinned), narrative=candidate_text)


# --- Trace of the observed failure -----------------------------------------
pre = WorkingMemory(
    pinned={"acct-7f3a-92b1": "acct-7f3a-92b1", "quota=500": "quota=500"},
    narrative="resolved target; mutation issued; verify pending",
)

# Model-generated "summary" that paraphrases the high-entropy literal away.
candidate = (
    "Task: updating account quota to 500. Account identified earlier. "
    "Next: verify the quota change using the check tool."
)

try:
    commit_self_edit(pre, candidate)
except ReferentialIntegrityError as err:
    # Correct behavior: reject at compaction time, while bindings are in hand.
    print(f"edit rejected: {err}")
    # Recovery: re-issue with pinned block preserved byte-exact.
    safe_candidate = candidate + "\nPINNED: acct-7f3a-92b1 quota=500"
    committed = commit_self_edit(pre, safe_candidate)
    print(f"edit committed, pinned intact: {list(committed.pinned)}")
