# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-salience-scoring-self-reference-trap-in-model-driven-context-editing.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-salience-scoring-self-reference-trap-in-model-driven-context-editing.warrant.json
# Markdown SHA-256:   12a47ac072beae4b15f5fd7e704ea92fd44d60a14fc3762e905ecad5960cfeeb
# Code AST SHA-256:   63753b6fd7415ca6c3c8759cb7fd9817181ade1fb47830c668a88472f88f49b4
# Verified Classes:   ConstraintEvictionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ConstraintEvictionError(RuntimeError):
    """Raised when a self-editing context policy attempts to evict or
    deflate a span that carries a pinned task invariant, or when a score
    is contaminated by prior self-generated scores of the same span."""


def guarded_prune(spans, pinned_anchors, prior_scores, summarize_threshold=0.25,
                  evict_threshold=0.10):
    """
    Two-phase endogenous pruning with anchor, provenance, and reversibility
    tests. `spans` is a list of dicts with keys:
        id, text, score, backpointer, is_pinned
    `prior_scores` maps span_id -> list of scores the model emitted about
    that span on earlier passes (the contamination source).
    Returns (kept, summarized, evicted) and never mutates input.
    """
    kept, summarized, evicted = [], [], []

    for span in spans:
        sid = span["id"]
        text = span["text"]

        # Anchor test: pinned spans, or spans sharing tokens with a pinned
        # anchor, are non-prunable regardless of score.
        if span.get("is_pinned"):
            kept.append(span)
            continue
        anchor_hit = any(tok in text for tok in pinned_anchors)
        if anchor_hit:
            kept.append(span)
            continue

        # Provenance test: a score influenced by the model's own prior
        # scores of this span is contaminated; recompute with history
        # masked. If we cannot recompute, refuse to act.
        history = prior_scores.get(sid, [])
        score = span["score"]
        if history:
            if "fresh_score" not in span:
                raise ConstraintEvictionError(
                    f"span {sid} has contaminated score history {history} "
                    f"and no history-masked recomputation; refusing to prune"
                )
            score = span["fresh_score"]

        # Reversibility test: a summary without a backpointer is a one-way
        # door and may not be created from a span that could carry a
        # constraint.
        if score < summarize_threshold and not span.get("backpointer"):
            raise ConstraintEvictionError(
                f"span {sid} scored {score:.2f} below summarize threshold "
                f"but has no backpointer; compression would be irreversible"
            )

        if score < evict_threshold:
            if not span.get("backpointer"):
                raise ConstraintEvictionError(
                    f"span {sid} scheduled for eviction with no backpointer; "
                    f"constraint could be lost permanently"
                )
            evicted.append(span)
        elif score < summarize_threshold:
            summarized.append({**span, "summary_score": score})
        else:
            kept.append(span)

    return kept, summarized, evicted
