# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-scratchpad-rewrite-divergence-when-it-edits-its-own-working-memory-mid-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-scratchpad-rewrite-divergence-when-it-edits-its-own-working-memory-mid-trajectory.warrant.json
# Markdown SHA-256:   1719e9213ec40a41baeccc272ea65ba051ed9a5a7e3069858fbcdd578d5156ee
# Code AST SHA-256:   449e17bc437c067139652e04bcb8337682ca9c57e89cef0684af1c50bf02fc9b
# Verified Classes:   ScratchpadRewriteDivergence, ConstraintLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class ScratchpadRewriteDivergence(RuntimeError):
    """Raised when a self-rewrite would drop or paraphrase a protected constraint
    or launder a negative observation, making downstream state unverifiable."""
    pass


@dataclass
class ConstraintLedger:
    # Immutable region: literal predicates and negative observations the rewrite may not touch.
    predicates: list[str] = field(default_factory=list)
    negative_observations: list[str] = field(default_factory=list)


def apply_self_rewrite(
    old_scratchpad: str,
    new_scratchpad: str,
    ledger: ConstraintLedger,
    is_constraint_pattern: Callable[[str], bool],
) -> str:
    """Gate a mid-trajectory scratchpad rewrite. Returns new scratchpad only if
    every protected literal survives byte-identically; otherwise raises."""
    for pred in ledger.predicates:
        if pred not in old_scratchpad:
            continue  # already absent before rewrite; not this rewrite's fault
        if pred not in new_scratchpad:
            raise ScratchpadRewriteDivergence(
                f"rewrite drops protected predicate {pred!r}; "
                f"paraphrase is not preservation"
            )

    for obs in ledger.negative_observations:
        if obs in old_scratchpad and obs not in new_scratchpad:
            # Dropping a negative observation is only legal if a superseding
            # successful observation is present in the new scratchpad.
            if not any(
                is_constraint_pattern(line) and "SUPERSEDED_BY" in line
                for line in new_scratchpad.splitlines()
            ):
                raise ScratchpadRewriteDivergence(
                    f"rewrite launders negative observation {obs!r} "
                    f"into an action without supersession"
                )

    # Reject any new line that looks like a generalized constraint substitute.
    for line in new_scratchpad.splitlines():
        if is_constraint_pattern(line) and line not in old_scratchpad:
            raise ScratchpadRewriteDivergence(
                f"rewrite introduces unverified constraint-like line {line!r}; "
                f"commitment without ledger entry"
            )

    return new_scratchpad
