# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-pruning-policy-has-silently-evicted-the-premise-it-is-currently-reasoning-over.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-pruning-policy-has-silently-evicted-the-premise-it-is-currently-reasoning-over.warrant.json
# Markdown SHA-256:   f4ae5b6386ed5d208f5a61063c1b767129779637c2cd7ae15f576953e996147b
# Code AST SHA-256:   1b729b4f85e05263d82e0bf5647ad37a74c4547e898ea6f07ccb3f0f0afbeb1f
# Verified Classes:   SpanKind, PremiseEvictionError, Span, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SpanKind(Enum):
    ASSERTION = "assertion"   # fact, observation, tool output — re-fetchable
    CONSTRAINT = "constraint"  # hard requirement, prohibition — NOT re-fetchable


class PremiseEvictionError(RuntimeError):
    """Raised when a compaction pass would drop a load-bearing constraint
    with no resident span that entails it. Fails closed: halt compaction."""


@dataclass
class Span:
    span_id: str
    kind: SpanKind
    text: str
    relevance: float = 0.0
    entailed_by: Optional[str] = None  # span_id of a resident entailer, if any


@dataclass
class ContextWindow:
    spans: dict[str, Span] = field(default_factory=dict)
    pinned: set[str] = field(default_factory=set)  # constraint ledger, never scored

    def resident(self) -> set[str]:
        return set(self.spans) | self.pinned


def compact(window: ContextWindow, budget: int, anchor_relevance: dict[str, float]) -> ContextWindow:
    """Model-driven compaction. Constraints are pinned; assertions are scored
    and evicted only when an entailing resident span can be named."""
    # 1. Pin every constraint verbatim. Never summarize, never score.
    for sid, span in window.spans.items():
        if span.kind is SpanKind.CONSTRAINT:
            window.pinned.add(sid)

    # 2. Score only assertions.
    scored = [
        (sid, anchor_relevance.get(sid, 0.0))
        for sid, span in window.spans.items()
        if span.kind is SpanKind.ASSERTION and sid not in window.pinned
    ]
    scored.sort(key=lambda kv: kv[1], reverse=True)

    survivors = set(window.pinned)
    for sid, _ in scored:
        if len(survivors) >= budget:
            break
        survivors.add(sid)

    # 3. Eviction gate: any constraint not surviving must be entailed by a survivor.
    for sid, span in window.spans.items():
        if sid in survivors:
            continue
        if span.kind is SpanKind.CONSTRAINT:
            ent = span.entailed_by
            if ent is None or ent not in survivors:
                raise PremiseEvictionError(
                    f"compaction would evict constraint {sid!r} with no resident "
                    f"entailer; refusing to compact. Halt and escalate."
                )

    new = ContextWindow()
    new.pinned = set(window.pinned)
    new.spans = {sid: window.spans[sid] for sid in survivors if sid in window.spans}
    return new


def assert_ledger_covers(window: ContextWindow, required_ids: set[str]) -> None:
    """Invariant check before any action emission: every acceptance-criterion
    constraint must be resident in the pinned ledger."""
    missing = required_ids - window.pinned
    if missing:
        raise PremiseEvictionError(
            f"constraint ledger does not cover {sorted(missing)}; "
            f"refusing to emit action on an under-constrained window."
        )
