# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-the-eviction-fidelity-ledger-when-a-self-editing-context-controller-co-optimizes-token-budget-recall-fidelity-and-inj.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-the-eviction-fidelity-ledger-when-a-self-editing-context-controller-co-optimizes-token-budget-recall-fidelity-and-inj.warrant.json
# Markdown SHA-256:   2e01a32ecad9bcc6683de5ca47ef4d0b29f6c2d45567c84c17f2342c5d02972c
# Code AST SHA-256:   2b2d377749790ee65ecb674e540dd0b5adc1b3ee6a9ed2b8713d352bccfa6609
# Verified Classes:   Taint, TaintLaunderingError, LedgerIncompleteError, Segment, LedgerEntry, ContextController
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Literal

class Taint(IntEnum):
    CLEAN = 0
    SUSPECT = 1
    QUARANTINED = 2

class TaintLaunderingError(RuntimeError):
    """Raised when a lossy edit resets taint below the input maximum without a sanitizer warrant."""

class LedgerIncompleteError(RuntimeError):
    """Raised when a resident segment's taint is not derivable from the eviction-fidelity ledger."""

@dataclass
class Segment:
    id: str
    text: str
    source_class: Literal["user", "tool_output", "retrieved_doc", "self_summary"]
    taint: Taint
    recall_score: float
    ancestry: tuple[str, ...] = field(default_factory=tuple)  # input segment ids

@dataclass
class LedgerEntry:
    op: str
    input_ids: tuple[str, ...]
    input_taints: tuple[Taint, ...]
    output_id: str
    output_taint: Taint
    sanitizer_id: str | None = None
    justification_hash: str | None = None

class ContextController:
    def __init__(self, budget: int):
        self.budget = budget
        self.resident: dict[str, Segment] = {}
        self.ledger: list[LedgerEntry] = []

    def lossy_transform(self, inputs: list[Segment], summary_id: str, summary_text: str,
                        sanitizer_id: str | None = None,
                        justification_hash: str | None = None) -> Segment:
        max_in = max((s.taint for s in inputs), default=Taint.CLEAN)

        # Invariant: taint monotonicity under edit
        if max_in == Taint.QUARANTINED and sanitizer_id is None:
            raise TaintLaunderingError(
                f"refusing lossy transform of quarantined inputs {[s.id for s in inputs]}"
            )
        if max_in == Taint.SUSPECT and sanitizer_id is None:
            # permitted, but output must remain suspect; never clean
            out_taint = Taint.SUSPECT
        elif sanitizer_id is not None:
            if not justification_hash:
                raise TaintLaunderingError(
                    f"sanitizer {sanitizer_id} invoked without justification_hash"
                )
            out_taint = Taint.CLEAN
        else:
            out_taint = max_in

        out = Segment(
            id=summary_id, text=summary_text, source_class="self_summary",
            taint=out_taint, recall_score=self._recompute_recall(summary_text),
            ancestry=tuple(s.id for s in inputs),
        )
        self.ledger.append(LedgerEntry(
            op="summarize", input_ids=out.ancestry,
            input_taints=tuple(s.taint for s in inputs),
            output_id=summary_id, output_taint=out_taint,
            sanitizer_id=sanitizer_id, justification_hash=justification_hash,
        ))
        for s in inputs:
            self.resident.pop(s.id, None)
        self.resident[summary_id] = out
        return out

    def injection_pass(self) -> None:
        # Ledger-completeness check before scoring
        for seg in self.resident.values():
            if seg.source_class == "self_summary":
                if not self._taint_derivable(seg):
                    seg.taint = Taint.SUSPECT  # demote, disable self-trust
                    raise LedgerIncompleteError(
                        f"segment {seg.id} has no derivable taint ancestry; demoted to suspect"
                    )
        # ... scoring with self-trust disabled for suspect segments ...

    def _taint_derivable(self, seg: Segment) -> bool:
        if not seg.ancestry:
            return False
        return any(e.output_id == seg.id for e in self.ledger)

    def _recompute_recall(self, text: str) -> float:
        return min(1.0, len(text) / 4096.0)
