# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-salience-score-inversion-during-model-driven-context-pruning-and-how-to-bound-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-salience-score-inversion-during-model-driven-context-pruning-and-how-to-bound-it.warrant.json
# Markdown SHA-256:   dc2a2081a362c0b5d5b0f6e5893f6f82a7f868952cdcfd69c5243c952c5c18f5
# Code AST SHA-256:   0427873965ac89a9bfd09752c9141778d389902664c291058bf6f99710e2a52e
# Verified Classes:   SalienceInversionError, Span, ContextWindow
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field

CONSTRAINT_PATTERN = re.compile(
    r"\b(must|assume|unless|resets?|do not|never|limit|budget|idempotency|scope)\b",
    re.IGNORECASE,
)


class SalienceInversionError(RuntimeError):
    """Raised when a prune step would evict the sole antecedent of a live invariant."""


@dataclass
class Span:
    span_id: str
    text: str
    salience: float
    generation: int = 0          # 0 = raw, 1 = first-order summary
    pinned: bool = False
    discharged: bool = False


@dataclass
class ContextWindow:
    spans: dict[str, Span] = field(default_factory=dict)
    live_references: set[str] = field(default_factory=set)  # span_ids cited downstream

    def is_single_occurrence_invariant(self, span: Span) -> bool:
        if not CONSTRAINT_PATTERN.search(span.text):
            return False
        restatements = sum(
            1 for s in self.spans.values()
            if s.span_id != span.span_id and CONSTRAINT_PATTERN.search(s.text)
        )
        return restatements == 0

    def safe_to_evict(self, span: Span) -> bool:
        if span.pinned and not span.discharged:
            return False
        if span.span_id in self.live_references:
            return False
        if span.generation >= 1:
            # second-order compression is forbidden; must re-derive or fail
            return False
        return True

    def prune(self, threshold: float = 0.25) -> list[str]:
        evicted: list[str] = []
        for span in list(self.spans.values()):
            if span.salience >= threshold:
                continue
            if self.is_single_occurrence_invariant(span):
                span.pinned = True
                continue
            if not self.safe_to_evict(span):
                raise SalienceInversionError(
                    f"prune would evict span {span.span_id!r} "
                    f"(salience={span.salience}, generation={span.generation}, "
                    f"pinned={span.pinned}, cited={span.span_id in self.live_references}); "
                    f"retain and pin instead of guessing"
                )
            evicted.append(span.span_id)
            del self.spans[span.span_id]
        return evicted
