# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-the-pruner-s-own-justification-evicts-the-evidence-it-cites.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-the-pruner-s-own-justification-evicts-the-evidence-it-cites.warrant.json
# Markdown SHA-256:   600bd737c21bbf4029e9f748d5c2ca84d6af20426011bd8570fd44a7c6daec5f
# Code AST SHA-256:   3616963e4612b7bd473988fdee6fab9503ee729d5fefe5e375f366fe49e58a28
# Verified Classes:   ProvenanceViolation, Span, Claim, SelfEditingWindow
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceViolation(RuntimeError):
    """Raised when a retained claim's cited span is no longer resolvable."""
    pass


@dataclass
class Span:
    span_id: str
    text: str


@dataclass
class Claim:
    text: str
    cited_hashes: list[str]
    confidence: float
    status: str = "VERIFIED"  # VERIFIED | UNVERIFIED


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


class SelfEditingWindow:
    def __init__(self, budget_tokens: int, pin_cap_ratio: float = 0.20):
        self.budget = budget_tokens
        self.pin_cap = int(budget_tokens * pin_cap_ratio)
        self.live: dict[str, Span] = {}
        self.cold: dict[str, Span] = {}      # append-only, keyed by hash
        self.claims: list[Claim] = []

    def add_span(self, span_id: str, text: str) -> None:
        self.live[span_id] = Span(span_id, text)
        self.cold[_h(text)] = Span(span_id, text)

    def add_claim(self, text: str, cited_span_ids: list[str], confidence: float) -> None:
        hashes = []
        for sid in cited_span_ids:
            if sid not in self.live:
                raise ProvenanceViolation(f"claim cites absent span {sid}")
            hashes.append(_h(self.live[sid].text))
        self.claims.append(Claim(text, hashes, confidence))

    def _pin_set(self) -> set[str]:
        """Executor-computed: spans whose hashes back any live claim."""
        pinned = set()
        for c in self.claims:
            for h in c.cited_hashes:
                for sid, sp in self.live.items():
                    if _h(sp.text) == h:
                        pinned.add(sid)
        return pinned

    def verify_claims(self) -> None:
        """Demote any claim whose citation no longer resolves in cold store."""
        for c in self.claims:
            for h in c.cited_hashes:
                if h not in self.cold:
                    c.status = "UNVERIFIED"
            if any(h not in self.cold for h in c.cited_hashes):
                raise ProvenanceViolation(
                    f"claim {c.text[:40]!r} has unresolvable citation; "
                    f"must re-derive before acting"
                )

    def prune(self, drop_span_ids: list[str]) -> None:
        """Model-proposed drops; executor refuses to drop pinned spans."""
        pinned = self._pin_set()
        if sum(len(self.live[s].text) for s in pinned) > self.pin_cap:
            raise ProvenanceViolation(
                "pin set exceeds budget cap; require checkpoint-and-flush, "
                "not another compaction"
            )
        for sid in drop_span_ids:
            if sid in pinned:
                raise ProvenanceViolation(
                    f"refused to evict pinned span {sid}: it backs a live claim"
                )
            self.live.pop(sid, None)  # cold store retains it by hash
        self.verify_claims()


def compact(window: SelfEditingWindow, model_proposed_drops: list[str]) -> None:
    """Single-pass compaction entrypoint. No chained rewrites permitted."""
    window.prune(model_proposed_drops)
    if not window.live:
        raise ProvenanceViolation("compaction emptied window; flush required")
