# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-windows-from-silently-deleting-the-evidence-an-agent-is-reasoning-about.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-windows-from-silently-deleting-the-evidence-an-agent-is-reasoning-about.warrant.json
# Markdown SHA-256:   8bed6576f19fa52c78dea9184967f8108ff66b2248e543357ad05d02386083e7
# Code AST SHA-256:   174f71019a876adf4efa36d5d163d4b10dfcc4882cdd02499221513c16a074d4
# Verified Classes:   StaleEvidenceError, Tombstone, SelfEditingWindow
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class StaleEvidenceError(RuntimeError):
    """Raised when a committed claim rests on evidence deleted under a stale objective hash."""
    pass


@dataclass
class Tombstone:
    span_id: str
    score: float
    query_hash: str
    step: int
    payload: str  # the actual span text, kept addressable


@dataclass
class SelfEditingWindow:
    objective: str
    live: Dict[str, str] = field(default_factory=dict)
    tombstones: Dict[str, Tombstone] = field(default_factory=dict)

    def _hash(self, text: str) -> str:
        return hashlib.sha256(text.encode()).hexdigest()[:16]

    @property
    def query_hash(self) -> str:
        return self._hash(self.objective)

    def compact(self, span_id: str, score: float, step: int) -> None:
        # Irreversible deletion is forbidden; every drop becomes a tombstone.
        if span_id not in self.live:
            return
        self.tombstones[span_id] = Tombstone(
            span_id=span_id,
            score=score,
            query_hash=self.query_hash,   # provenance of the scoring query
            step=step,
            payload=self.live.pop(span_id),
        )

    def recall(self, span_id: str) -> Optional[str]:
        t = self.tombstones.get(span_id)
        return t.payload if t else self.live.get(span_id)

    def retarget(self, new_objective: str) -> None:
        # Objective change invalidates the epoch: re-expand all tombstones
        # scored under the old hash so they can be re-evaluated.
        old = self.query_hash
        self.objective = new_objective
        for sid, t in list(self.tombstones.items()):
            if t.query_hash != self.query_hash:
                self.live[sid] = t.payload
                del self.tombstones[sid]

    def audit_claim(self, claim: str, cited_span_ids: list[str]) -> None:
        current = self.query_hash
        for sid in cited_span_ids:
            t = self.tombstones.get(sid)
            if t is not None and t.query_hash != current:
                raise StaleEvidenceError(
                    f"claim {claim!r} cites span {sid} deleted under stale "
                    f"objective hash {t.query_hash} (current {current}); "
                    f"recall and re-verify before commit"
                )


def run_incident_replay() -> None:
    w = SelfEditingWindow(objective="call sites of parse_config")
    w.live["grep_11"] = "def load_config(): ...  # second entry point"
    w.live["grep_12"] = "parse_config() at foo.py:10"

    # Step 25: honest but query-relative scoring deletes grep_11.
    w.compact("grep_11", score=0.18, step=25)

    # Step 29: objective widens; tombstone re-expanded for re-scoring.
    w.retarget("call sites of parse_config OR load_config")

    # Step 33: agent commits a claim resting on the deleted span.
    w.audit_claim("no other call sites exist", ["grep_11"])  # raises


if __name__ == "__main__":
    run_incident_replay()
