# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-the-evidence-it-just-cited-when-a-self-pruning-context-policy-rewrites-the-window-mid-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-the-evidence-it-just-cited-when-a-self-pruning-context-policy-rewrites-the-window-mid-verification.warrant.json
# Markdown SHA-256:   f7710598d0f5b45ea409e8dce59e5fc766c7a4cb70b8d8565863d98c4b214ef3
# Code AST SHA-256:   5eaccef1c28b2e119fd086b06d66c41f8463c2576ffa90aad3eb3c7aac3f6351
# Verified Classes:   DanglingReferenceError, Unit, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Optional


class DanglingReferenceError(RuntimeError):
    """Raised when a self-edit to the context window would orphan a live reference."""


@dataclass
class Unit:
    uid: str
    body: str
    call_id: Optional[str] = None


@dataclass
class ContextWindow:
    units: Dict[str, Unit] = field(default_factory=dict)
    emitted_refs: Set[str] = field(default_factory=set)  # uids the model has cited

    def resolve(self, uid: str) -> Optional[Unit]:
        return self.units.get(uid)


def apply_self_edit(window: ContextWindow, rewritten: Dict[str, Unit]) -> ContextWindow:
    """
    Commit a model-driven rewrite (prune/summarize/re-chunk) ONLY if every
    live reference still resolves. Address-remapping rewrites that drop a
    cited uid are rejected; the caller must fall back to append-only truncation.
    """
    for uid in window.emitted_refs:
        if uid not in rewritten:
            raise DanglingReferenceError(
                f"self-edit would orphan live reference uid={uid!r}; "
                f"rewrite is address-remapping, not address-preserving"
            )

    # Preserve provenance headers on surviving units; a rewrite that strips
    # call_id from a unit the model may still cite is also a violation.
    for uid, unit in rewritten.items():
        old = window.units.get(uid)
        if old is not None and old.call_id is not None and unit.call_id is None:
            raise DanglingReferenceError(
                f"self-edit stripped call_id from uid={uid!r}; "
                f"citation provenance would dangle downstream"
            )

    return ContextWindow(units=dict(rewritten), emitted_refs=set(window.emitted_refs))


def safe_prune(window: ContextWindow, summarizer) -> ContextWindow:
    """Wrap a model-driven rewrite with the reference-resolving gate."""
    rewritten = summarizer(window)  # model proposes a new window
    try:
        return apply_self_edit(window, rewritten)
    except DanglingReferenceError:
        # Fall back to append-only truncation: drop only units that are
        # provably unreferenced, never re-key survivors.
        survivors = {
            uid: u for uid, u in window.units.items()
            if uid in window.emitted_refs or u.call_id is not None
        }
        return ContextWindow(units=survivors, emitted_refs=set(window.emitted_refs))
