# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-self-edits-its-context-window-with-a-diff-based-rewrite-policy-and-the-diff-anchor-drifts.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-self-edits-its-context-window-with-a-diff-based-rewrite-policy-and-the-diff-anchor-drifts.warrant.json
# Markdown SHA-256:   f163a56f8952833d5323c7be9a0401a519fa943dc70ad53c68fd000e8ed19052
# Code AST SHA-256:   dfb3b1fd768ac1c1ef8510cefe63dc2c9a4f74130aed1e08f8e63514639a1892
# Verified Classes:   AnchorDriftError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AnchorDriftError(RuntimeError):
    """Raised when a self-edit patch would apply ambiguously or against a stale anchor."""
    pass


def apply_self_edit(buffer: str, search: str, replace: str, *, reread_verified: bool) -> str:
    if not reread_verified:
        # Patch authored from recollection, not a byte-exact read of the buffer.
        raise AnchorDriftError(
            "patch anchor was not derived from a fresh read of the target region"
        )

    occurrences = buffer.count(search)
    if occurrences == 0:
        # Do NOT relax the anchor. Force a re-read to re-ground the model.
        raise AnchorDriftError(
            f"NO_MATCH for anchor {search!r}; re-read the region before retrying"
        )
    if occurrences > 1:
        # Positional resolution here is exactly how silent retargeting happens.
        raise AnchorDriftError(
            f"AMBIGUOUS_ANCHOR: {search!r} occurs {occurrences} times; "
            "widen the anchor with surrounding unique context"
        )

    patched = buffer.replace(search, replace, 1)
    # Post-condition: the mutation must be local; neighbor regions unchanged.
    if patched.count(replace) != 1:
        raise AnchorDriftError("patch introduced a duplicate of the replacement text")
    return patched
