# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-referential-pruning-collapse-when-model-driven-context-rewriting-evicts-the-evidence-it-needs-to-justify-the-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-referential-pruning-collapse-when-model-driven-context-rewriting-evicts-the-evidence-it-needs-to-justify-the-eviction.warrant.json
# Markdown SHA-256:   2e9f1798135f2c50d7ed1d2370ce019fd3ab9127d4fb0efd107ebbcdf7dc8549
# Code AST SHA-256:   099f12dd838b4bf98e3a18450f31977fd23ec39eeb977263e187f42020b43a8b
# Verified Classes:   SelfReferentialPruningCollapse
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SelfReferentialPruningCollapse(RuntimeError):
    """Raised when a rewrite would fold a falsifiable operand into a digest,
    destroying the only evidence that could later contradict a future observation."""
    pass


FALSIFIABLE_OPERAND_MARKERS = ("$", "%", "deadline", "ceiling", "budget", "limit", "warrant", "id:")


def commit_rewrite(rewrite_plan, pinned_region, retained_spans):
    """
    rewrite_plan: list of dicts, each either
        {"op": "digest", "source": <span>, "digest": <str>}  or
        {"op": "pin",    "source": <span>}
    Enforces the invariant: a span carrying a falsifiable operand may be pinned
    but must never be paraphrased into a digest.
    """
    for step in rewrite_plan:
        if step["op"] != "digest":
            continue
        source_text = step["source"].lower()
        carries_operand = any(m in source_text for m in FALSIFIABLE_OPERAND_MARKERS)
        if carries_operand:
            # The digest keeps the referent but drops the operand. No retained span
            # can witness the justification for this eviction, because the operand
            # itself is the witness. Refuse and force a pin instead.
            raise SelfReferentialPruningCollapse(
                f"refusing to digest span carrying falsifiable operand: "
                f"{step['source'][:80]!r} -> {step['digest']!r}; "
                f"pin the verbatim source instead"
            )
        # narrative span: safe to fold
        retained_spans.append(step["digest"])

    # After a clean pass, verify every pinned operand still has a live witness.
    for pinned in pinned_region:
        if pinned not in retained_spans and not _witnessed(pinned, retained_spans):
            raise SelfReferentialPruningCollapse(
                f"pinned operand lost its witness across rewrite: {pinned[:80]!r}"
            )
    return retained_spans


def _witnessed(pinned, retained_spans):
    # A pinned operand is witnessed if it is present verbatim in the retained set.
    return any(pinned in s for s in retained_spans)
