# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-journal-replay-when-model-driven-context-pruning-deletes-the-evidence-its-own-undo-log-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-journal-replay-when-model-driven-context-pruning-deletes-the-evidence-its-own-undo-log-depends-on.warrant.json
# Markdown SHA-256:   679c042fcceada20da8fa0d450799418bdfe85108e622dfe2eeb80763e9246eb
# Code AST SHA-256:   8ce0b1b4b684d55cb6967b5afeb1a0fe88689b8f6a24ef5118e4d6d832d0a87d
# Verified Classes:   JournalEntryMissing, JournalEntry, DurableJournal
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class JournalEntryMissing(RuntimeError):
    """Raised when a rollback targets a span whose journal evidence is absent.

    Absence is NOT equivalent to 'nothing to undo'. Treating it as such
    produces silent rollback-success under a corrupted world model.
    """


@dataclass(frozen=True)
class JournalEntry:
    span_id: str
    content_hash: str
    deleted_text: str
    committed: bool = False


class DurableJournal:
    """Append-only, off-window store. Never pruned by the context policy."""

    def __init__(self) -> None:
        self._entries: dict[str, JournalEntry] = {}
        self._rehydrated = False

    def record(self, span_id: str, deleted_text: str) -> None:
        h = hashlib.sha256(deleted_text.encode()).hexdigest()
        self._entries[span_id] = JournalEntry(span_id, h, deleted_text)

    def commit(self, span_id: str) -> None:
        e = self._entries.get(span_id)
        if e is None:
            raise JournalEntryMissing(f"commit on unknown span {span_id!r}")
        self._entries[span_id] = JournalEntry(e.span_id, e.content_hash, e.deleted_text, True)

    def rehydrate(self, live_span_ids: set[str]) -> None:
        # Cold-start invariant: verify hashes for all live spans before any rollback.
        for sid in live_span_ids:
            if sid not in self._entries:
                raise JournalEntryMissing(
                    f"live span {sid!r} has no journal evidence; rollback unsafe"
                )
        self._rehydrated = True

    def rollback(self, span_id: str) -> str:
        if not self._rehydrated:
            raise JournalEntryMissing(
                "rollback attempted before journal rehydration; refusing"
            )
        entry = self._entries.get(span_id)
        if entry is None:
            # The boundary: a miss means evidence destroyed, not 'clean span'.
            raise JournalEntryMissing(
                f"no journal entry for {span_id!r}; cannot invert, halting"
            )
        if entry.committed:
            raise JournalEntryMissing(
                f"span {span_id!r} already committed; not reversible"
            )
        actual = hashlib.sha256(entry.deleted_text.encode()).hexdigest()
        if actual != entry.content_hash:
            raise JournalEntryMissing(
                f"journal hash mismatch for {span_id!r}; evidence tampered"
            )
        return entry.deleted_text


def prune_and_rollback_demo() -> None:
    j = DurableJournal()
    j.record("turn14", "config: timeout=30")
    # Simulate the observed bug: an in-window pruner drops the entry's pointer,
    # and a naive rollback treats the miss as success. Here we force the miss.
    j._entries.pop("turn14", None)
    j.rehydrate(live_span_ids=set())  # no live spans -> rehydrate passes
    j.rollback("turn14")  # must raise, not no-op


if __name__ == "__main__":
    prune_and_rollback_demo()
