# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-reversible-edit-journal-has-silently-diverged-from-the-live-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-reversible-edit-journal-has-silently-diverged-from-the-live-context-window.warrant.json
# Markdown SHA-256:   319582f24321dda160379340e07d7f030208135f0febe2e2d8b46464c57e292c
# Code AST SHA-256:   4a8313c3524f85fad0c642f72aa6f3e8fe64f5bf68e166453c9b45a5882c5719
# Verified Classes:   JournalDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class JournalDivergenceError(RuntimeError):
    """Raised when a reversible edit journal's inverse does not reconstruct the pre-edit state."""
    pass


def apply_forward_edit(journal, ctx, anchor, replacement):
    # Guard: the replacement must not contain the anchor string, or the
    # inverse will later match the replacement instead of the original span.
    if anchor in replacement:
        raise JournalDivergenceError(
            f"forward edit output reintroduces its own anchor {anchor!r}; "
            f"inverse would be ambiguous — re-anchor to a span ID before committing"
        )
    span_id = journal.next_span_id()
    journal.append_forward(span_id=span_id, anchor=anchor, original=ctx.extract(anchor))
    return ctx.replace(anchor, replacement)


def apply_inverse(journal, ctx, span_id):
    op = journal.get_forward(span_id)
    before_tokens = ctx.token_count()
    restored = ctx.replace_by_span_id(op.span_id, op.original)
    delta = restored.token_count() - before_tokens
    expected = op.original.token_count() - op.replacement.token_count()
    if delta != expected:
        raise JournalDivergenceError(
            f"inverse of span {span_id} changed token count by {delta}, "
            f"expected {expected}; journal has diverged from live window"
        )
    return restored
