# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-erasure-in-a-model-authored-context-pruning-policy-before-the-pruned-span-becomes-unrecoverable.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-erasure-in-a-model-authored-context-pruning-policy-before-the-pruned-span-becomes-unrecoverable.warrant.json
# Markdown SHA-256:   dce69d63318ee434d4602bc034dc1c723a8e65b475fcc90efa705df16f1ed402
# Code AST SHA-256:   ee1d64e1ef6e8dc54e5fdf7d25d221c71c6b0cf0bda8a9acef0ab93850e15deb
# Verified Classes:   PruningInvariantViolation, SpanKind, Span, ContextPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class PruningInvariantViolation(RuntimeError):
    """Raised when a self-editing context policy would erase a load-bearing constraint."""


class SpanKind(Enum):
    FILLER = "filler"
    REDUNDANT = "redundant"
    PROHIBITION = "prohibition"        # "do not", "already bound", negative result
    UNIQUENESS = "uniqueness"          # "only one", "the single", "first and last"
    FAILED_ATTEMPT = "failed_attempt"  # "we tried X and it failed"


LOAD_BEARING = {SpanKind.PROHIBITION, SpanKind.UNIQUENESS, SpanKind.FAILED_ATTEMPT}


@dataclass
class Span:
    span_id: str
    text: str
    kind: SpanKind
    pinned: bool = False


@dataclass
class ContextPolicy:
    pinned: list[Span] = field(default_factory=list)
    exemption_ids: set[str] = field(default_factory=set)
    pinned_budget: int = 4000


def _classify(span: Span) -> SpanKind:
    # In production this is the model's own heuristic; here it is the typed check
    # that the blocklist enforces *after* the model scores salience.
    lowered = span.text.lower()
    if "do not" in lowered or "already bound" in lowered or "must not" in lowered:
        return SpanKind.PROHIBITION
    if "only one" in lowered or "the single" in lowered:
        return SpanKind.UNIQUENESS
    if "tried" in lowered and "failed" in lowered:
        return SpanKind.FAILED_ATTEMPT
    return span.kind


def apply_pruning(
    policy: ContextPolicy,
    candidates: Iterable[Span],
    model_salience: dict[str, float],
) -> list[Span]:
    """Prune only spans that are non-load-bearing AND not exempt.

    Raises PruningInvariantViolation if the policy's own exemption list was
    mutated, or if pinned content would exceed budget (halt, do not compress).
    """
    survivors: list[Span] = []
    for span in candidates:
        effective_kind = _classify(span)

        # Guard 1: exemption list must be append-only. A span whose id is in
        # exemption_ids but whose kind was reclassified to filler is an attempt
        # to launder a prohibition past the blocklist.
        if span.span_id in policy.exemption_ids and effective_kind not in LOAD_BEARING:
            raise PruningInvariantViolation(
                f"exemption laundering: span {span.span_id} was exempt but "
                f"reclassified to {effective_kind.value}"
            )

        # Guard 2: load-bearing spans are ineligible for pruning regardless of
        # the model's salience score.
        if effective_kind in LOAD_BEARING:
            span.pinned = True
            survivors.append(span)
            continue

        # Guard 3: only genuinely redundant/filler spans with low salience drop.
        if model_salience.get(span.span_id, 1.0) < 0.3:
            continue  # pruned
        survivors.append(span)

    pinned_tokens = sum(len(s.text.split()) for s in survivors if s.pinned)
    if pinned_tokens > policy.pinned_budget:
        raise PruningInvariantViolation(
            f"pinned region {pinned_tokens} > budget {policy.pinned_budget}: "
            "halt and checkpoint; do not compress pinned constraints"
        )

    policy.pinned = [s for s in survivors if s.pinned]
    return survivors


if __name__ == "__main__":
    policy = ContextPolicy(exemption_ids={"s-port"})
    spans = [
        Span("s-port", "Port 5432 already bound; do not start a second instance.",
             SpanKind.REDUNDANT),
        Span("s-filler", "Sounds good, moving on.", SpanKind.FILLER),
    ]
    try:
        kept = apply_pruning(policy, spans, model_salience={"s-port": 0.1, "s-filler": 0.1})
        assert any(s.span_id == "s-port" for s in kept), "prohibition must survive"
    except PruningInvariantViolation as exc:
        print(f"HALT: {exc}")
