# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-model-driven-context-compaction-when-its-own-retention-scores-are-computed-against-a-rewritten-history.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-model-driven-context-compaction-when-its-own-retention-scores-are-computed-against-a-rewritten-history.warrant.json
# Markdown SHA-256:   ddb814379b683144e9813b91f3308fccea742150f5764b0806dfad586cf12a84
# Code AST SHA-256:   632eed2df932a278170bfb85bde7f5802244ab01af56a5e7dcd00262dd22357a
# Verified Classes:   Polarity, UnsoundCompactionError, Span, Rewrite
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class Polarity(Enum):
    SUCCESS = "success"
    FAILURE = "failure"
    CONSTRAINT = "constraint"
    NEUTRAL = "neutral"


class UnsoundCompactionError(RuntimeError):
    """Raised when a self-editing pass would score or prune against model-authored text."""


@dataclass
class Span:
    span_id: str
    text: str
    polarity: Polarity
    original_hash: str = field(default=None)

    def __post_init__(self):
        if self.original_hash is None:
            self.original_hash = hashlib.sha256(self.text.encode()).hexdigest()


@dataclass
class Rewrite:
    source_span_id: str
    replacement_text: str
    source_hash: str
    source_polarity: Polarity
    rewritten_polarity: Polarity


PINNED = {Polarity.CONSTRAINT, Polarity.FAILURE}


def apply_rewrite(span: Span, replacement_text: str, new_polarity: Polarity) -> Rewrite:
    # A rewrite may compress detail but must not flip the truth-value of an event.
    if span.polarity in PINNED and new_polarity != span.polarity:
        raise UnsoundCompactionError(
            f"rewrite of span {span.span_id} would flip polarity "
            f"{span.polarity.value} -> {new_polarity.value}; "
            f"history mutation forbidden"
        )
    return Rewrite(
        source_span_id=span.span_id,
        replacement_text=replacement_text,
        source_hash=span.original_hash,
        source_polarity=span.polarity,
        rewritten_polarity=new_polarity,
    )


def score_and_prune(
    spans: list[Span],
    rewrites: dict[str, Rewrite],
    scores: dict[str, float],
    threshold: float,
) -> list[Span]:
    """
    scores: span_id -> relevance to current subgoal (model-assigned).
    Refuses to prune any span whose scoring input was a rewrite, and never
    prunes a pinned span regardless of its relevance score.
    """
    surviving: list[Span] = []
    for span in spans:
        if span.span_id in rewrites:
            rw = rewrites[span.span_id]
            # The score was computed against the rewrite, not the original.
            # Deleting the original now would delete ground truth the rewrite
            # may have already corrupted. Refuse.
            if rw.source_hash != span.original_hash:
                raise UnsoundCompactionError(
                    f"span {span.span_id} scored against rewrite whose source "
                    f"hash does not match the original; scoring referent is unsound"
                )
        if span.polarity in PINNED:
            surviving.append(span)  # pinned: never enters the pruning decision
            continue
        if scores.get(span.span_id, 1.0) < threshold:
            continue  # safe: verbatim span, scored against itself, deleted knowingly
        surviving.append(span)
    return surviving


def compact(spans, rewrites, scores, threshold):
    try:
        return score_and_prune(spans, rewrites, scores, threshold)
    except UnsoundCompactionError:
        # Fail closed: keep the full buffer and surface the divergence.
        raise
