# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-editing-context-corruption-when-its-own-summarization-pass-is-the-only-observer.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-editing-context-corruption-when-its-own-summarization-pass-is-the-only-observer.warrant.json
# Markdown SHA-256:   066e01bb28a70d66bf77caf8b73fae6af2b77f428c6871d537cd7a110dd20585
# Code AST SHA-256:   86e8316a8b00e72847770c46bbdea284860fbfd6b5d6c9ed0263be9806f2563c
# Verified Classes:   UnverifiableSelfEditError, ContextWindow, Checkpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class UnverifiableSelfEditError(RuntimeError):
    """Raised when a context rewrite cannot be checked against a pre-edit original."""


@dataclass
class ContextWindow:
    tokens: list[str] = field(default_factory=list)
    invariants: dict[str, str] = field(default_factory=dict)

    def fingerprint(self) -> str:
        payload = json.dumps(
            {"tokens": self.tokens, "invariants": self.invariants}, sort_keys=True
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class Checkpoint:
    fingerprint: str
    invariants: dict[str, str]


def compact_in_place(window: ContextWindow, budget_remaining: int) -> ContextWindow:
    """Model-driven rewrite of the working context. Destructive by design."""
    # A real implementation would call the model here. The point of the
    # function is the guard, not the summarization.
    if budget_remaining <= 0:
        # The trigger for compaction is also the reason verification is
        # impossible: no headroom left to diff against the original.
        raise UnverifiableSelfEditError(
            "compaction triggered at zero headroom; no budget remains to "
            "verify the edit against a pre-edit copy"
        )
    return ContextWindow(tokens=window.tokens[: budget_remaining // 2],
                         invariants=dict(window.invariants))


def safe_compact(window: ContextWindow, checkpoint: Checkpoint | None,
                 budget_remaining: int) -> ContextWindow:
    if checkpoint is None:
        # No out-of-band original: the edit would be self-certifying.
        raise UnverifiableSelfEditError(
            "no checkpoint of pre-edit context; refusing in-place rewrite"
        )
    if window.fingerprint() != checkpoint.fingerprint:
        raise UnverifiableSelfEditError(
            "working context diverged from checkpoint before compaction; "
            "the 'original' is already a prior compression"
        )

    edited = compact_in_place(window, budget_remaining)

    # Invariants must survive verbatim. Paraphrase is dissolution.
    for key, value in checkpoint.invariants.items():
        if edited.invariants.get(key) != value:
            raise UnverifiableSelfEditError(
                f"invariant {key!r} altered by self-edit: "
                f"{value!r} -> {edited.invariants.get(key)!r}"
            )
    return edited
