# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-self-editing-context-policies-as-a-non-idempotent-rewrite-of-its-own-observation-function.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-self-editing-context-policies-as-a-non-idempotent-rewrite-of-its-own-observation-function.warrant.json
# Markdown SHA-256:   d29eb569586732a9d65c7dd69aa19979f130831c69db36654120fa9623de95ef
# Code AST SHA-256:   123b7cab48ca696defcbef37570848f0054eaed98ab3edaeddc25a0a319d5d99
# Verified Classes:   ContextPolicyEpochError, Segment, EpochPolicy, ContextStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable


class ContextPolicyEpochError(RuntimeError):
    """Raised when a self-edit of the context policy would retroactively
    change the observation of history predating the edit without a pre-image."""


@dataclass
class Segment:
    epoch: int
    content: str


@dataclass
class EpochPolicy:
    epoch: int
    # observation function: segment -> retained content ("" means pruned)
    observe: Callable[[Segment], str]


@dataclass
class ContextStore:
    segments: list[Segment] = field(default_factory=list)
    policies: dict[int, EpochPolicy] = field(default_factory=dict)
    current_epoch: int = 0
    preimages: dict[int, str] = field(default_factory=dict)

    def ingest(self, content: str) -> None:
        self.segments.append(Segment(epoch=self.current_epoch, content=content))

    def _digest(self) -> str:
        h = hashlib.sha256()
        for s in self.segments:
            h.update(f"{s.epoch}:{s.content}".encode())
        return h.hexdigest()

    def snapshot(self) -> str:
        return self._digest()

    def edit_policy(self, new_observe: Callable[[Segment], str]) -> int:
        """Commit a new policy epoch. Refuses if the new policy would alter
        observation of any pre-existing segment and no pre-image exists."""
        candidate = EpochPolicy(epoch=self.current_epoch + 1, observe=new_observe)

        retroactive = False
        for seg in self.segments:
            old = self.policies[seg.epoch].observe(seg)
            new = candidate.observe(seg)
            if old != new:
                retroactive = True
                break

        if retroactive and self._digest() not in self.preimages.values():
            # caller must snapshot() and register it before committing
            raise ContextPolicyEpochError(
                "policy edit is retroactive over pre-existing segments and no "
                "pre-image checkpoint is registered; refusing to commit"
            )

        self.current_epoch = candidate.epoch
        self.policies[candidate.epoch] = candidate
        return candidate.epoch

    def register_preimage(self) -> str:
        d = self.snapshot()
        self.preimages[d] = d
        return d

    def observe_all(self) -> list[str]:
        """Observation is per-segment epoch-scoped: never apply the current
        policy backward to older segments."""
        out = []
        for seg in self.segments:
            out.append(self.policies[seg.epoch].observe(seg))
        return out


def self_edit(story: ContextStore, new_observe: Callable[[Segment], str]) -> int:
    # attempt the edit; on refusal, checkpoint then retry
    try:
        return story.edit_policy(new_observe)
    except ContextPolicyEpochError:
        story.register_preimage()
        return story.edit_policy(new_observe)
