# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-pruning-as-a-lossy-non-idempotent-transform-rather-than-a-semantic-summarization-step.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-pruning-as-a-lossy-non-idempotent-transform-rather-than-a-semantic-summarization-step.warrant.json
# Markdown SHA-256:   082e3bf3f06a843e94e68b9fbba63ece45a324ee11321cc40d1418cf2627703b
# Code AST SHA-256:   4ce9d5d46f6334cd1f054d5f0ac8df44c119caefcf8f7288d7a1bbfcad255e3b
# Verified Classes:   ContextRewriteProvenanceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ContextRewriteProvenanceError(RuntimeError):
    """Raised when a model-authored rewrite would replace a live span
    without leaving a retrievable provenance stub, making downstream
    reasoning unable to distinguish source from paraphrase."""
    pass


PROTECTED_PATTERNS = ("must not", "must remain", "no more than", "exactly", "retain")


def apply_prune(span_text: str, replacement: str, stub_ref: str, *, rewrite: bool) -> str:
    if not rewrite:
        # Eviction path: drop the span, leave a pointer. Loss is loud.
        return f"[elided; retrieve via {stub_ref}]"

    # Rewrite path: refuse if the source carries constraints that a
    # paraphrase can silently invert or drop.
    lowered = span_text.lower()
    hazards = [p for p in PROTECTED_PATTERNS if p in lowered]
    if hazards and not stub_ref:
        raise ContextRewriteProvenanceError(
            f"refusing in-place rewrite of span containing protected "
            f"constraints {hazards} with no provenance stub; "
            f"downgrade to eviction or attach stub_ref"
        )

    # Even with a stub, the replacement must be marked as derived so the
    # instance does not later cite it as ground truth.
    return f"[derived summary of {stub_ref} — verify before relying] {replacement}"


def prune_turn(span_text: str, replacement: str, stub_ref: str, *, rewrite: bool) -> str:
    try:
        return apply_prune(span_text, replacement, stub_ref, rewrite=rewrite)
    except ContextRewriteProvenanceError as exc:
        # Fail closed: force eviction-with-stub rather than corrupting state.
        raise ContextRewriteProvenanceError(
            f"prune aborted, falling back to eviction: {exc}"
        ) from exc
