# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-silently-evicting-the-one-token-the-task-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-silently-evicting-the-one-token-the-task-depends-on.warrant.json
# Markdown SHA-256:   436cb73b65bafee6fd80ba29394a08725c57887a18680ab23d1bb54b19e365d4
# Code AST SHA-256:   ac451f27747a89e3b2590c7cf135b02796d5119587f6df83c422d0890ccfe982
# Verified Classes:   ContextPolicyViolation, SpanKind, Span, Plan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ContextPolicyViolation(RuntimeError):
    """Raised when a self-editing context policy would evict a referentially-loaded span."""
    pass


class SpanKind(Enum):
    VERBATIM = "verbatim"
    SUMMARY = "summary"          # lossy by construction
    TOOL_DERIVABLE = "tool_derivable"


@dataclass
class Span:
    span_id: str
    text: str
    kind: SpanKind
    relevance: float
    literals: set[str] = field(default_factory=set)
    is_negative_constraint: bool = False
    lossy_tagged: bool = False


@dataclass
class Plan:
    # Literals the not-yet-executed plan steps will consume.
    required_literals: set[str]


def is_pinned(span: Span, plan: Plan) -> bool:
    if span.literals & plan.required_literals:
        return True
    if span.is_negative_constraint:
        return True
    if span.kind is SpanKind.SUMMARY and not span.lossy_tagged:
        # An untagged summary is indistinguishable from a verbatim span
        # downstream; it must not be treated as a safe substitute.
        return True
    return False


def rewrite_context(
    spans: Iterable[Span],
    plan: Plan,
    cutoff: float,
) -> list[Span]:
    kept: list[Span] = []
    for span in spans:
        pinned = is_pinned(span, plan)
        if pinned:
            kept.append(span)
            continue
        if span.relevance >= cutoff:
            kept.append(span)
            continue
        # Eviction path. Refuse to evict a span whose literals are needed
        # and whose only remaining source would be a lossy summary.
        if span.kind is SpanKind.SUMMARY and not span.lossy_tagged:
            raise ContextPolicyViolation(
                f"refusing to evict span {span.span_id}: "
                "untagged summary would be the sole referential source"
            )
        if span.literals and not span.literals <= plan.required_literals:
            # Evicting a literal-bearing span that the plan does not yet
            # declare is a latent-dependency hazard; log via exception
            # unless explicitly acknowledged by the caller.
            raise ContextPolicyViolation(
                f"span {span.span_id} carries undeclared literals "
                f"{sorted(span.literals)}; plan must declare or pin them"
            )
        # Safe to drop.
    return kept


def compact(spans: list[Span], plan: Plan, cutoff: float = 0.35) -> list[Span]:
    try:
        return rewrite_context(spans, plan, cutoff)
    except ContextPolicyViolation as exc:
        # Operational posture: halt the self-edit, keep the prior context
        # intact, and surface the violation for plan repair. Never proceed
        # with a partially-evicted context on a referential violation.
        raise ContextPolicyViolation(
            f"context self-edit halted; prior context preserved: {exc}"
        ) from exc
