# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-delete-the-one-context-span-it-will-need-three-tool-calls-later-the-self-pruning-eviction-trap-and-the-reachability-invariant-for.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-delete-the-one-context-span-it-will-need-three-tool-calls-later-the-self-pruning-eviction-trap-and-the-reachability-invariant-for.warrant.json
# Markdown SHA-256:   43e5af802446161175bbd577bf0eb79a7b15a43efe3b20ced4cdcfe41c06c4ac
# Code AST SHA-256:   283c38e93dd3285cd4148c95cbeb995e2303fdc2bb09ad02a0bfd2aad1af018e
# Verified Classes:   PruneInvariantViolation, LossSignature, Span, Pointer, ContextWindow
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class PruneInvariantViolation(RuntimeError):
    """Raised when a self-pruning pass would break forward reachability."""


class LossSignature(Enum):
    SELF_ANNOUNCING = "self_announcing"  # absence fails loudly at next consumer
    SILENT = "silent"                    # absence fails downstream, misattributed


@dataclass
class Span:
    span_id: str
    text: str
    exact_key: str | None          # verbatim identifier/path/value, if any
    loss: LossSignature
    relevance: float               # score against CURRENT subgoal only


@dataclass
class Pointer:
    span_id: str
    resolve_key: str
    marker: str = "RESOLVE_REQUIRED"
    resolved: bool = False


@dataclass
class ContextWindow:
    spans: dict[str, Span] = field(default_factory=dict)
    pointers: dict[str, Pointer] = field(default_factory=dict)
    budget: int = 10_000

    def used(self) -> int:
        return sum(len(s.text) for s in self.spans.values())

    def prune(
        self,
        candidates: list[str],
        resolver: Callable[[str], str],
    ) -> list[Pointer]:
        """Model-driven relevance eviction with reachability guard."""
        emitted: list[Pointer] = []
        for sid in candidates:
            span = self.spans.get(sid)
            if span is None:
                continue

            # Guardrail 1: silent-loss spans are ineligible for relevance eviction.
            if span.loss is LossSignature.SILENT:
                raise PruneInvariantViolation(
                    f"refusing to relevance-evict span {sid!r}: silent-loss span "
                    f"may be consumed by a future step; only capacity eviction "
                    f"with a live pointer is permitted"
                )

            # Guardrail 2: any eviction must leave a faithful, resolvable pointer.
            if span.exact_key is None:
                raise PruneInvariantViolation(
                    f"span {sid!r} has no exact_key; a paraphrase pointer would "
                    f"suppress re-retrieval (false-floor hazard)"
                )

            ptr = Pointer(span_id=sid, resolve_key=span.exact_key)
            # Verify the pointer actually resolves before committing the eviction.
            probe = resolver(span.exact_key)
            if not probe:
                raise PruneInvariantViolation(
                    f"pointer for span {sid!r} does not resolve; eviction would be "
                    f"irreversible (reachability invariant broken)"
                )

            del self.spans[sid]
            self.pointers[sid] = ptr
            emitted.append(ptr)
        return emitted

    def consume(self, sid: str, resolver: Callable[[str], str]) -> str:
        """Downstream step consuming a pruned region must resolve, not paraphrase."""
        ptr = self.pointers.get(sid)
        if ptr is None:
            raise PruneInvariantViolation(f"no pointer for {sid!r}")
        if not ptr.resolved:
            content = resolver(ptr.resolve_key)
            if not content:
                raise PruneInvariantViolation(
                    f"unresolved RESOLVE_REQUIRED region {sid!r}; refusing to "
                    f"proceed on confabulated substitute"
                )
            ptr.resolved = True
            return content
        return resolver(ptr.resolve_key)


def run_prune_pass(window: ContextWindow, candidates: list[str],
                   resolver: Callable[[str], str]) -> None:
    if window.used() > window.budget:
        # capacity pressure permits broader eviction, but pointers still required
        pass
    window.prune(candidates, resolver)
