# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-roll-back-a-self-edited-context-policy-when-the-rewrite-itself-is-the-only-surviving-record-of-the-pre-edit-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-roll-back-a-self-edited-context-policy-when-the-rewrite-itself-is-the-only-surviving-record-of-the-pre-edit-state.warrant.json
# Markdown SHA-256:   8d4da2a6341f49923fa1e31fcc97c01ea42e3477743be28b11f0dceb878599f6
# Code AST SHA-256:   b77209e6e24abfe992005297873ef8260abbadb65a5b75bbb261334a6e8fc003
# Verified Classes:   UnsafePolicyRollbackError, PolicyRegister, PolicyEdit
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnsafePolicyRollbackError(RuntimeError):
    """Raised when a self-edited policy would commit without an out-of-band rollback record."""


@dataclass
class PolicyRegister:
    """Harness-side, context-independent store. Read path never traverses the context window."""
    _records: dict = field(default_factory=dict)

    def record(self, episode_id: str, edit_id: str, pre_edit_bytes: bytes) -> str:
        h = hashlib.sha256(pre_edit_bytes).hexdigest()
        self._records[(episode_id, edit_id)] = (h, pre_edit_bytes)
        return h

    def resolve(self, episode_id: str, edit_id: str):
        return self._records.get((episode_id, edit_id))


@dataclass
class PolicyEdit:
    edit_id: str
    new_policy_bytes: bytes
    eviction_scope: set          # regions the edit's eviction rules govern
    policy_region: set           # regions where the current policy artifact lives
    lowers_summarization_threshold: bool


def commit_self_edit(episode_id: str, edit: PolicyEdit, current_policy_bytes: bytes,
                     register: PolicyRegister) -> str:
    # Precondition 1: eviction scope must not cover the policy artifact's region.
    if edit.eviction_scope & edit.policy_region:
        raise UnsafePolicyRollbackError(
            f"edit {edit.edit_id} evicts its own rollback record: "
            f"scope {edit.eviction_scope} intersects policy region {edit.policy_region}"
        )

    # Precondition 2: an out-of-band hash of the pre-edit policy must be recorded
    # BEFORE activation, and must resolve through the register (not the context).
    pre_hash = register.record(episode_id, edit.edit_id, current_policy_bytes)
    resolved = register.resolve(episode_id, edit.edit_id)
    if resolved is None or resolved[0] != pre_hash:
        raise UnsafePolicyRollbackError(
            f"no resolvable out-of-band rollback record for edit {edit.edit_id}"
        )

    # Precondition 3: lowering the threshold while the artifact is un-pinned
    # accelerates eviction of the very bytes rollback needs.
    if edit.lowers_summarization_threshold and edit.policy_region <= edit.eviction_scope:
        raise UnsafePolicyRollbackError(
            "threshold reduction would evict un-pinned pre-edit policy artifact"
        )

    # Activation is now safe: rollback resolves by identity, never by reconstruction.
    return pre_hash


def rollback_by_identity(episode_id: str, edit_id: str, register: PolicyRegister) -> bytes:
    resolved = register.resolve(episode_id, edit_id)
    if resolved is None:
        raise UnsafePolicyRollbackError(
            f"rollback target {edit_id} unresolved; reconstruction is forensic only, not a restore"
        )
    return resolved[1]
