# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-context-pruning-policy-has-silently-corrupted-a-salience-anchor-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-context-pruning-policy-has-silently-corrupted-a-salience-anchor-mid-task.warrant.json
# Markdown SHA-256:   cc6cf4338053b2a54d1273d5d22bd12f07f25c50f82e4a0e585319dae891e6ab
# Code AST SHA-256:   d6e5c0366fbeef5c95fd52fb53a50cf480aa1d80ceb226cb5e9197c5a53955f5
# Verified Classes:   SalienceAnchorCorruption
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SalienceAnchorCorruption(RuntimeError):
    """Raised when a binding constraint survives only as a self-authored summary
    whose polarity/scope diverges from the cold-store original."""
    pass


NEGATION_MARKERS = ("do not", "must not", "never", "instead", "only", "deprecated")


def verify_constraint_citation(summary_text: str, cold_store_original: str | None,
                               binding_key: str) -> None:
    if cold_store_original is None:
        raise SalienceAnchorCorruption(
            f"binding segment {binding_key} evicted with no cold-store original; "
            f"cannot verify polarity of self-authored summary"
        )

    original_has_negation = any(m in cold_store_original.lower() for m in NEGATION_MARKERS)
    summary_has_negation = any(m in summary_text.lower() for m in NEGATION_MARKERS)

    if original_has_negation and not summary_has_negation:
        raise SalienceAnchorCorruption(
            f"polarity loss on {binding_key}: original carries a prohibition/"
            f"correction marker, summary does not. Summary is topic-faithful but "
            f"constraint-unfaithful; halt and re-read cold store before acting."
        )


def prune_with_guard(segments: list[dict], watermark: float) -> list[dict]:
    survivors, evicted = [], []
    for seg in segments:
        # binding segments are pinned: never destructively evicted
        if seg.get("tag") == "binding" or seg.get("salience", 0) >= watermark:
            survivors.append(seg)
        else:
            evicted.append(seg)

    for seg in evicted:
        if seg.get("tag") == "binding":
            # unreachable by construction, but assert the invariant
            raise SalienceAnchorCorruption(
                f"invariant violated: binding segment {seg['key']} reached eviction path"
            )
        # demote, do not drop: summary carries a pointer, not a paraphrase
        seg["summary_pointer"] = f"[constraint:ref-{seg['key']}]"

    return survivors
