# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-salience-score-collapse-when-a-model-rewrites-its-own-in-flight-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-salience-score-collapse-when-a-model-rewrites-its-own-in-flight-context.warrant.json
# Markdown SHA-256:   7e7096a6b5701c27a3662026dcdd5867fc1474fe2ccfbf7e2f6f4015b5f71575
# Code AST SHA-256:   c05dd3cb6ac60af38aad599cd9dc04bdc4215f6e41f7d54603e2cb678210ef9b
# Verified Classes:   SalienceCollapseError, Span, RewriteRound
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SalienceCollapseError(RuntimeError):
    """Raised when a self-edit round would shrink the pinned-constraint set
    without a corresponding constraint_release record, or when a span's
    salience drops faster than its content changed."""
    pass


@dataclass
class Span:
    span_id: str
    content: str
    pinned: bool
    score_history: list[float] = field(default_factory=list)

    @property
    def last_score(self) -> Optional[float]:
        return self.score_history[-1] if self.score_history else None

    @property
    def historical_max(self) -> float:
        return max(self.score_history) if self.score_history else 0.0


@dataclass
class RewriteRound:
    turn: int
    scores: dict[str, float]              # span_id -> fresh absolute score
    releases: set[str]                    # span_ids explicitly released
    pruned: set[str] = field(default_factory=set)


def apply_rewrite(
    window: dict[str, Span],
    rnd: RewriteRound,
    prune_threshold: float = 0.30,
    max_single_round_drop: float = 0.30,
    decay: float = 0.95,
) -> dict[str, Span]:
    """Apply a model-driven rewrite round under the salience-collapse guardrail.

    Invariants enforced:
      1. Pinned spans may only leave the window via an explicit release.
      2. Effective salience is max(fresh, decayed historical max) -- rank-floor
         prevents tail drift across rounds.
      3. A span whose score drops more than max_single_round_drop in one round
         without a content change is flagged, not pruned.
    """
    pinned_before = {sid for sid, s in window.items() if s.pinned}
    released = rnd.releases & pinned_before
    pinned_after = pinned_before - released

    # Invariant 1: pinned set must be monotone non-increasing, and only shrink
    # via explicit release. If a pinned span is absent from the incoming scores
    # and not released, the round is malformed.
    for sid in pinned_before - released:
        if sid not in rnd.scores:
            raise SalienceCollapseError(
                f"turn {rnd.turn}: pinned span {sid!r} vanished from scores "
                f"without a constraint_release record"
            )

    new_window: dict[str, Span] = {}
    for sid, span in window.items():
        fresh = rnd.scores.get(sid)
        if fresh is None:
            # Span absent from this round's scoring: keep only if pinned.
            if span.pinned and sid not in released:
                new_window[sid] = span
            continue

        # Invariant 2: rank-floor against decayed historical max.
        floor = span.historical_max * (decay ** 1)
        effective = max(fresh, floor)

        # Invariant 3: detect discontinuity.
        if span.last_score is not None:
            drop = span.last_score - fresh
            if drop > max_single_round_drop and not span.pinned:
                # Flag: do not prune this round; require human/auditor review.
                span.score_history.append(fresh)
                new_window[sid] = span
                continue

        if span.pinned and sid not in released:
            span.score_history.append(fresh)
            new_window[sid] = span
            continue

        if effective < prune_threshold:
            rnd.pruned.add(sid)
            continue

        span.score_history.append(fresh)
        new_window[sid] = span

    # Post-condition: pinned set shrank only by releases.
    pinned_final = {sid for sid, s in new_window.items() if s.pinned}
    if pinned_final != pinned_after:
        raise SalienceCollapseError(
            f"turn {rnd.turn}: pinned set {pinned_final} != expected {pinned_after}"
        )

    return new_window
