# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-scratchpad-rewrites-as-lossy-state-transitions-rather-than-idempotent-edits.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-scratchpad-rewrites-as-lossy-state-transitions-rather-than-idempotent-edits.warrant.json
# Markdown SHA-256:   e3f26d12e07e567aa807a8fd549d7b5dfd516cdca9fe78f53905a65f4e064350
# Code AST SHA-256:   28de88053052ae0a0c736998b983452f2b291a22d2e1df170b1b0dcecc8f0219
# Verified Classes:   ScratchpadRewriteLoss
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ScratchpadRewriteLoss(RuntimeError):
    """Raised when a model-driven scratchpad rewrite drops or mutates a protected constraint."""
    pass


def apply_scratchpad_rewrite(
    pre_image: str,
    rewritten: str,
    constraint_manifest: dict[str, str],
) -> str:
    """
    Apply a model-generated scratchpad rewrite only if every protected constraint
    survives intact. The manifest must be extracted from pre_image BEFORE the
    rewrite is generated; the rewritten text is checked against it, never against
    itself.
    """
    if not constraint_manifest:
        # No typed constraints => this is a state-destroying op, not a compaction.
        raise ScratchpadRewriteLoss(
            "rewrite attempted with empty constraint manifest; "
            "prohibitions/thresholds/fences are unrecoverable if dropped"
        )

    missing = [k for k in constraint_manifest if k not in rewritten]
    if missing:
        raise ScratchpadRewriteLoss(
            f"rewrite dropped protected constraints {missing!r}; "
            "downstream verifier would launder the resulting violation"
        )

    mutated = [
        k for k, v in constraint_manifest.items()
        if constraint_manifest[k] not in rewritten
    ]
    if mutated:
        raise ScratchpadRewriteLoss(
            f"rewrite mutated protected constraint values for {mutated!r}; "
            "re-derivation drift across composed rewrites"
        )

    return rewritten


def compose_rewrites(original: str, manifest: dict[str, str], rewrites: list[str]) -> str:
    """Guard against compounding drift: every rewrite is checked against the original anchor."""
    current = original
    for i, rw in enumerate(rewrites):
        try:
            current = apply_scratchpad_rewrite(original, rw, manifest)
        except ScratchpadRewriteLoss as e:
            raise ScratchpadRewriteLoss(f"rewrite #{i} failed anchor check: {e}") from e
    return current
