# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-authored-scratchpad-rewrite-as-a-commit-that-invalidates-prior-reasoning-rather-than-as-a-lossless-com.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-authored-scratchpad-rewrite-as-a-commit-that-invalidates-prior-reasoning-rather-than-as-a-lossless-com.warrant.json
# Markdown SHA-256:   f55a23d4149a00ca734007dff8fd444a0766e0db8f5066541df59febf1433275
# Code AST SHA-256:   61a9fac3597897ac8ff87326192fda62ec19b8ac03febc99df7ea86719038227
# Verified Classes:   ScratchpadCommitError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ScratchpadCommitError(RuntimeError):
    """Raised when a self-authored scratchpad rewrite destroys load-bearing state
    without an adequate drop manifest, i.e. it is a commit masquerading as compression."""


def apply_self_rewrite(
    original: dict[str, str],
    rewritten: dict[str, str],
    drop_manifest: dict[str, str] | None,
    protected_keys: set[str],
) -> dict[str, str]:
    """
    original:        key -> content of the pre-rewrite scratchpad
    rewritten:       key -> content of the proposed post-rewrite scratchpad
    drop_manifest:   key -> reason, for every element the rewrite removed
    protected_keys:  keys that rewrites are forbidden to remove or alter
    """
    if drop_manifest is None:
        # A rewrite with no manifest is a commit with unknown loss.
        # We cannot certify entailment preservation, so we must reject it.
        dropped = set(original) - set(rewritten)
        if dropped:
            raise ScratchpadCommitError(
                f"rewrite dropped {sorted(dropped)} with no drop manifest; "
                f"cannot distinguish compression from commit"
            )

    # Protected regions must survive verbatim.
    for key in protected_keys:
        if key in original and key not in rewritten:
            raise ScratchpadCommitError(
                f"protected key {key!r} removed by rewrite; "
                f"negative constraints and open branches must be append-only"
            )
        if key in original and rewritten.get(key) != original[key]:
            raise ScratchpadCommitError(
                f"protected key {key!r} altered by rewrite; "
                f"protected regions are read-only to summarization"
            )

    # Every dropped element must be accounted for in the manifest.
    dropped = set(original) - set(rewritten)
    unaccounted = dropped - set(drop_manifest or {})
    if unaccounted:
        raise ScratchpadCommitError(
            f"dropped elements {sorted(unaccounted)} absent from drop manifest; "
            f"rewrite is a commit and must be rejected or the elements restored"
        )

    # Every manifest entry must name a real drop (no phantom justifications).
    phantom = set(drop_manifest or {}) - dropped
    if phantom:
        raise ScratchpadCommitError(
            f"drop manifest claims removal of {sorted(phantom)} which were not dropped; "
            f"manifest is unreliable and the rewrite cannot be certified"
        )

    return rewritten
