# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-window-has-dropped-load-bearing-state.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-window-has-dropped-load-bearing-state.warrant.json
# Markdown SHA-256:   7de2c70f69ab1d3ceadaf44a6b01636c6e673b30a87d63492164297654a3b3c6
# Code AST SHA-256:   03d5f16eefe7eab084d16a1878a41f124b6c60170c527d8c1c71a11e5d7dcd8d
# Verified Classes:   LoadBearingEvictionError, RederivationConflictError, Span, SettledFact, ProvenanceGatedCompactor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class LoadBearingEvictionError(RuntimeError):
    """Raised when a compaction step attempts to evict a span that is
    a settled fact, a standing constraint, or the definition site of a
    live identifier."""
    pass


class RederivationConflictError(RuntimeError):
    """Raised when the agent asserts a fact whose shape matches a settled
    fact but whose value differs -- the observable signature of silent
    load-bearing loss."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    tags: set = field(default_factory=set)          # {"settled_fact", "standing_constraint"}
    defines_identifiers: set = field(default_factory=set)
    similarity_to_current_subgoal: float = 0.0


@dataclass
class SettledFact:
    key: str
    value: str
    source_span_id: str


class ProvenanceGatedCompactor:
    def __init__(self, external_store: dict):
        self.external_store = external_store   # span_id -> Span, for re-injection

    def evict(self, span: Span, live_identifiers: set) -> None:
        # The invariant: relevance ranking may order spans but may not
        # decide survival of provenance-bearing or liveness-bearing spans.
        if "settled_fact" in span.tags or "standing_constraint" in span.tags:
            raise LoadBearingEvictionError(
                f"span {span.span_id} carries provenance tag(s) "
                f"{sorted(span.tags)}; relevance score "
                f"{span.similarity_to_current_subgoal:.3f} does not authorize eviction"
            )
        if span.defines_identifiers & live_identifiers:
            raise LoadBearingEvictionError(
                f"span {span.span_id} defines live identifier(s) "
                f"{sorted(span.defines_identifiers & live_identifiers)}; "
                f"eviction would orphan downstream references"
            )
        self.external_store[span.span_id] = span   # reversible eviction

    def reinject(self, span_id: str) -> Span:
        if span_id not in self.external_store:
            raise LoadBearingEvictionError(
                f"cannot re-inject {span_id}: not in external store; "
                f"eviction was not reversible"
            )
        return self.external_store.pop(span_id)

    def check_assertion(self, asserted_key: str, asserted_value: str,
                        settled: dict) -> None:
        # Re-derivation detector: fires when shape matches a settled fact
        # but the value diverges. This is the loud signal that a load-bearing
        # span was silently dropped and the agent is guessing.
        fact: Optional[SettledFact] = settled.get(asserted_key)
        if fact is None:
            return
        if fact.value != asserted_value:
            raise RederivationConflictError(
                f"agent asserts {asserted_key}={asserted_value!r} but "
                f"settled value is {fact.value!r} (from {fact.source_span_id}); "
                f"halt subgoal and re-inject before proceeding"
            )
