# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-context-the-self-editing-eviction-deadlock-at-the-relevance-score-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-context-the-self-editing-eviction-deadlock-at-the-relevance-score-boundary.warrant.json
# Markdown SHA-256:   009aec6a180f61febaaee47fd6b9ab0fdf54db47145ae53ed2d6865a69d99731
# Code AST SHA-256:   c873576f0e02b15f15d4cf81fbad9e40aae311b80a28b0f131409c95ae1b8d55
# Verified Classes:   SelfEditPruneError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SelfEditPruneError(RuntimeError):
    """Raised when a self-editing context pass would launder an error into authoritative state."""
    pass


def apply_self_edit(
    span_id: str,
    source_text: str,
    source_score: float,
    rewrite_text: str,
    rewrite_score: float,
    source_present: bool,
    source_hedges: set[str],
    rewrite_hedges: set[str],
    turns_since_subgoal_pivot: int,
    pivot_freeze_turns: int = 3,
) -> str:
    """
    Gate a single self-edit rewrite. Returns the rewrite to admit to context,
    or raises SelfEditPruneError to halt self-editing and escalate.
    """
    # Tripwire 1: orphaned summary — retained span with no live source.
    if not source_present:
        raise SelfEditPruneError(
            f"span {span_id}: orphaned summary, no live source in backing store; "
            f"re-admit source or demote summary to unverified"
        )

    # Tripwire 2: score inversion — rewrite outscored its source on the same axis.
    if rewrite_score > source_score:
        raise SelfEditPruneError(
            f"span {span_id}: score inflation on rewrite "
            f"({rewrite_score:.2f} > {source_score:.2f}); "
            f"rewrite drifted toward scorer bias, not truth"
        )

    # Tripwire 3: hedge / negation / provenance loss.
    lost = source_hedges - rewrite_hedges
    if lost:
        raise SelfEditPruneError(
            f"span {span_id}: rewrite dropped hedges/provenance {sorted(lost)}; "
            f"truth-value changed, not just length"
        )

    # Tripwire 4: eviction during post-pivot recalibration window.
    if turns_since_subgoal_pivot <= pivot_freeze_turns:
        raise SelfEditPruneError(
            f"span {span_id}: eviction attempted {turns_since_subgoal_pivot} turns "
            f"after subgoal pivot (freeze={pivot_freeze_turns}); scorer not recalibrated"
        )

    return rewrite_text
