# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-self-authored-context-pruning-against-the-loss-of-the-very-evidence-that-justified-the-prune.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-self-authored-context-pruning-against-the-loss-of-the-very-evidence-that-justified-the-prune.warrant.json
# Markdown SHA-256:   2f1abe2966b1d0cee7b033dd50ae574a3f43c0552e6623d64b755b5f319680f7
# Code AST SHA-256:   f23a19476acf7aad493decfdf7cbd5d6845d55768aa3820b48f2380bb592180e
# Verified Classes:   ProvenanceErosionError, Envelope, Segment
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class ProvenanceErosionError(RuntimeError):
    """Raised when a self-prune pass would strip justification from a retained segment."""


@dataclass
class Envelope:
    source_id: str
    retrieval_turn: int
    confidence: float
    polarity: Literal["positive", "negative"] = "positive"
    exclusion: bool = False


@dataclass
class Segment:
    text: str
    envelope: Envelope


ACTION_THRESHOLD = 0.6


def prune_and_rewrite(segment: Segment, new_text: str, new_confidence: float) -> Segment:
    env = segment.envelope

    # Invariant 1: a rewrite may never raise confidence (confidence-monotone).
    if new_confidence > env.confidence:
        raise ProvenanceErosionError(
            f"rewrite would raise confidence {env.confidence:.2f}->{new_confidence:.2f} "
            f"for {env.source_id}; summarization cannot launder low-confidence facts upward"
        )

    # Invariant 2: segments carrying polarity/exclusion state may not be paraphrased.
    if env.exclusion or env.polarity == "negative" or env.confidence < ACTION_THRESHOLD:
        if new_text.strip() != segment.text.strip():
            raise ProvenanceErosionError(
                f"segment {env.source_id} carries exclusion/polarity/low-confidence state "
                f"and may only be retained verbatim, not rewritten"
            )

    return Segment(text=new_text, envelope=Envelope(
        source_id=env.source_id,
        retrieval_turn=env.retrieval_turn,
        confidence=min(env.confidence, new_confidence),
        polarity=env.polarity,
        exclusion=env.exclusion,
    ))


def run_prune_pass(pre: list[Segment], post: list[Segment]) -> None:
    pre_excl = sum(1 for s in pre if s.envelope.exclusion)
    post_excl = sum(1 for s in post if s.envelope.exclusion)
    if post_excl < pre_excl:
        raise ProvenanceErosionError(
            f"prune evicted {pre_excl - post_excl} exclusion-flagged segment(s); "
            f"agent is about to lose the record of what it decided not to trust"
        )
    pre_ids = {s.envelope.source_id for s in pre if s.envelope.exclusion}
    post_ids = {s.envelope.source_id for s in post if s.envelope.exclusion}
    if pre_ids - post_ids:
        raise ProvenanceErosionError(
            f"excluded sources {pre_ids - post_ids} no longer represented post-prune"
        )
