# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-divergence-when-an-agent-rewrites-its-own-context-window-via-a-reversible-edit-journal.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-divergence-when-an-agent-rewrites-its-own-context-window-via-a-reversible-edit-journal.warrant.json
# Markdown SHA-256:   6a268edbd125a9f657a8135bed879afae297278b16edbeac15f8fdef1c887246
# Code AST SHA-256:   17a6f3e0c1191ea25bd08005cb7d1c08405fb20400b271140fe427615b1b3772
# Verified Classes:   ContextDivergenceError, Span, Journal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field

class ContextDivergenceError(RuntimeError):
    """Raised when reasoning tagged to a rolled-back window would be reused."""
    pass

@dataclass
class Span:
    text: str
    window_hash: str

@dataclass
class Journal:
    window: str
    hash: str
    spans: list = field(default_factory=list)
    history: list = field(default_factory=list)  # (hash_before, hash_after)

    @staticmethod
    def _h(s: str) -> str:
        return hashlib.sha256(s.encode()).hexdigest()[:16]

    def apply(self, new_window: str) -> None:
        hb, self.window = self.hash, new_window
        self.hash = self._h(new_window)
        self.history.append((hb, self.hash))

    def record_reasoning(self, text: str) -> None:
        self.spans.append(Span(text, self.hash))

    def rollback_to(self, target_hash: str) -> None:
        # C4: target must exist in history as a pre-image we can restore
        if not any(hb == target_hash for hb, _ in self.history):
            raise ContextDivergenceError(f"no restorable pre-image {target_hash}")
        self.hash = target_hash
        # C2: invalidate spans tagged above the rollback point
        self.spans = [s for s in self.spans if s.window_hash == target_hash]

    def live_context(self) -> str:
        # C1/C3: only spans tagged to the current window are admissible
        for s in self.spans:
            if s.window_hash != self.hash:
                raise ContextDivergenceError(
                    f"stale span tagged {s.window_hash} under window {self.hash}"
                )
        return self.window + "\n" + "\n".join(s.text for s in self.spans)

def safe_rollback(j: Journal, target_hash: str, asserted_premises: set) -> Journal:
    j.rollback_to(target_hash)
    stale = {p for p in asserted_premises if p not in j.live_context()}
    if stale:
        # C3: premises from rolled-back reasoning must be re-derived, not reused
        raise ContextDivergenceError(
            f"premises {sorted(stale)} survive rollback but are not in restored window; "
            f"re-derivation required before commitment"
        )
    return j
