# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-context-self-editing-eviction-versus-the-evidence-an-agent-still-owes-itself.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-context-self-editing-eviction-versus-the-evidence-an-agent-still-owes-itself.warrant.json
# Markdown SHA-256:   cec40c868a3c9a3ea0e7ccb0675da581ec53ddb9103a963902161c277e63e065
# Code AST SHA-256:   1601c419f351c0e156dbb468a549daf2f18a8dc9174426caff1c0fe32f0ed1f8
# Verified Classes:   UnlicensedEviction, Chunk, Obligation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnlicensedEviction(RuntimeError):
    """Raised when an agent attempts to evict a context chunk whose
    downstream obligations cannot be verified from the residual context."""
    pass


@dataclass
class Chunk:
    id: str
    text: str
    relevance_to_subgoal: float
    obligations: list[str] = field(default_factory=list)  # constraints it binds


@dataclass
class Obligation:
    constraint: str
    consumer_step: int


def plan_forward_obligations(plan_steps: list[str], current_step: int) -> set[str]:
    # In a real agent this is derived from the plan; here we model the
    # requirement that the forward set exists and is non-empty when
    # unresolved steps remain.
    return {f"step_{i}_precondition" for i in range(current_step + 1, len(plan_steps))}


def evict(
    chunks: list[Chunk],
    current_step: int,
    plan_steps: list[str],
    watermark_pressure: bool,
    threshold: float = 0.3,
) -> list[Chunk]:
    forward = plan_forward_obligations(plan_steps, current_step)
    kept: list[Chunk] = []
    for c in chunks:
        low_relevance = c.relevance_to_subgoal < threshold
        if not low_relevance:
            kept.append(c)
            continue
        # Low relevance: the dangerous regime. Can we verify it is obligation-free?
        if not c.obligations:
            # Regime one: no downstream consumer -> safe to drop.
            continue
        # Regime two/three: obligations exist. They are only safely droppable
        # if every obligation has already been lifted into the forward record
        # AND has a known consumer. Otherwise this is regime three.
        unresolved = [o for o in c.obligations if o not in forward]
        if unresolved and watermark_pressure:
            raise UnlicensedEviction(
                f"chunk {c.id!r} scored low ({c.relevance_to_subgoal:.2f}) against "
                f"subgoal but binds unresolved obligations {unresolved} with no "
                f"verifiable consumer; watermark pressure is not license to evict. "
                f"Re-plan to expand the forward set or escalate."
            )
        kept.append(c)
    return kept
