# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-windows-when-the-pruning-policy-s-own-justification-is-the-first-thing-it-deletes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-windows-when-the-pruning-policy-s-own-justification-is-the-first-thing-it-deletes.warrant.json
# Markdown SHA-256:   ca53fe671c8d5b03b48342c4ffbcf20c2ef9bdadcbe9d748b035a4ce17055819
# Code AST SHA-256:   112b66616f28f884665ffb28b96734e8ee4e868abda7508ef7246b130163ec4f
# Verified Classes:   DanglingObligationError, Obligation, SelfEditingWindow
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Set


class DanglingObligationError(RuntimeError):
    """Raised when a self-edit would evict the last live reference to an obligation."""
    pass


@dataclass
class Obligation:
    key: str            # e.g. "cursor:c_7f3a"
    handle: str         # the literal token a future call depends on
    discharged: bool = False


@dataclass
class SelfEditingWindow:
    budget: int
    editable: Dict[str, str] = field(default_factory=dict)   # span_id -> text
    obligations: Dict[str, Obligation] = field(default_factory=dict)
    warrant_log: List[str] = field(default_factory=list)
    policy_version: str = "relscore-v3"

    def register_obligation(self, key: str, handle: str) -> None:
        # Pinned region: scorer may never rank these as eviction candidates.
        self.obligations[key] = Obligation(key=key, handle=handle)

    def discharge(self, key: str) -> None:
        if key not in self.obligations:
            raise DanglingObligationError(f"discharge of unknown obligation {key}")
        self.obligations[key].discharged = True

    def _live_handles(self) -> Set[str]:
        return {o.handle for o in self.obligations.values() if not o.discharged}

    def _span_hash(self, span_id: str) -> str:
        return hashlib.sha256(self.editable[span_id].encode()).hexdigest()[:12]

    def evict(self, span_id: str, reason: str, step: int) -> None:
        if span_id not in self.editable:
            raise DanglingObligationError(f"evict of missing span {span_id}")
        text = self.editable[span_id]
        live = self._live_handles()
        # Hard structural check, not a relevance score.
        for handle in live:
            if handle in text:
                others = [
                    sid for sid, t in self.editable.items()
                    if sid != span_id and handle in t
                ]
                if not others:
                    raise DanglingObligationError(
                        f"refusing evict of {span_id}: last live reference to "
                        f"obligation handle {handle!r} at step {step}"
                    )
        h = self._span_hash(span_id)
        del self.editable[span_id]
        self.warrant_log.append(
            f"step={step} evicted={h} policy={self.policy_version} "
            f"reason={reason!r} obligations_affected=none"
        )

    def rewrite(self, span_id: str, new_text: str, step: int) -> None:
        if span_id not in self.editable:
            raise DanglingObligationError(f"rewrite of missing span {span_id}")
        old = self.editable[span_id]
        for handle in self._live_handles():
            if handle in old and handle not in new_text:
                others = [
                    sid for sid, t in self.editable.items()
                    if sid != span_id and handle in t
                ]
                if not others:
                    raise DanglingObligationError(
                        f"rewrite of {span_id} at step {step} would drop the "
                        f"last live reference to {handle!r}; refusing drift"
                    )
        self.editable[span_id] = new_text
        self.warrant_log.append(
            f"step={step} rewrote={self._span_hash(span_id)} "
            f"policy={self.policy_version} provenance=source_span"
        )

    def drift_check(self, step: int) -> None:
        # Re-derive open obligations from the pinned set; compare to buffer.
        live = self._live_handles()
        buffer_text = "\n".join(self.editable.values())
        missing = [h for h in live if h not in buffer_text]
        if missing:
            raise DanglingObligationError(
                f"drift at step {step}: {len(missing)} live obligation handle(s) "
                f"absent from edited buffer: {missing}; halt self-editing"
            )


def run_edit_cycle(win: SelfEditingWindow, step: int,
                   scores: Dict[str, float], threshold: float = 0.2) -> None:
    for span_id, score in list(scores.items()):
        if score < threshold:
            win.evict(span_id, reason=f"relscore={score:.2f}", step=step)
    win.drift_check(step)
