# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-self-pruned-context-silently-resurrect-stale-tool-results-when-the-pruner-scores-relevance-against-a-summary-it-just-overwrote.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-self-pruned-context-silently-resurrect-stale-tool-results-when-the-pruner-scores-relevance-against-a-summary-it-just-overwrote.warrant.json
# Markdown SHA-256:   ecbf18f8222362f3fb15370c6443963d2ee4b0b923e555a24aecc10fbd6bd832
# Code AST SHA-256:   88a45d911f787a5eef19a6d2ecc5795e515712eb83ac4798dd684138383bdcab
# Verified Classes:   PruneInvariantViolation, Segment, FramingGeneration
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class PruneInvariantViolation(RuntimeError):
    """Raised when a self-edit pass re-scores segments against a query it rewrote."""


@dataclass(frozen=True)
class Segment:
    origin_turn: int
    origin_tool: str
    origin_hash: str
    text: str
    admitted_generation: int
    last_score: float


@dataclass
class FramingGeneration:
    generation: int
    objective_text: str


def _hash(text: str) -> str:
    return hashlib.sha256(text.encode()).hexdigest()


def run_prune_pass(
    segments: list[Segment],
    current_framing: FramingGeneration,
    origin_framings: dict[int, FramingGeneration],
    live_tool_hashes: set[str],
    threshold: float,
    score_fn,
) -> list[Segment]:
    """
    Sound self-edit pass. Refuses to score a segment against a framing
    generation other than the one it was admitted under, and refuses to
    retain any segment whose origin hash no longer matches a live tool call.
    """
    retained: list[Segment] = []

    for seg in segments:
        origin_gen = seg.admitted_generation

        # Invariant 1: frozen query. Score against the origin framing, not
        # the possibly-rewritten current framing.
        if origin_gen not in origin_framings:
            raise PruneInvariantViolation(
                f"segment from turn {seg.origin_turn} has no origin framing "
                f"generation {origin_gen}; cannot score soundly"
            )
        frozen_query = origin_framings[origin_gen].objective_text

        # Invariant 2: provenance must still resolve to a live tool call.
        if seg.origin_hash not in live_tool_hashes:
            # Stale provenance: cannot be retained regardless of score.
            continue

        score = score_fn(seg.text, frozen_query)

        # Invariant 3: monotone retention under a frozen query.
        if score > seg.last_score + 1e-9:
            raise PruneInvariantViolation(
                f"score for turn {seg.origin_turn} increased "
                f"({seg.last_score:.3f} -> {score:.3f}) under a frozen query; "
                f"scoring inputs were mutated"
            )

        if score >= threshold:
            retained.append(
                Segment(
                    origin_turn=seg.origin_turn,
                    origin_tool=seg.origin_tool,
                    origin_hash=seg.origin_hash,
                    text=seg.text,
                    admitted_generation=origin_gen,
                    last_score=score,
                )
            )

    # If the objective was rewritten this pass, that is a NEW generation;
    # surviving segments keep their origin generation, they are not re-admitted.
    if current_framing.generation not in origin_framings:
        origin_framings[current_framing.generation] = current_framing

    return retained
