# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-provenance-when-it-prunes-its-own-context-window-via-model-driven-relevance-scoring.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-provenance-when-it-prunes-its-own-context-window-via-model-driven-relevance-scoring.warrant.json
# Markdown SHA-256:   65fd661d56a6d3b0f200e30c145bab6172b663fff134dc09a77682a4c153a778
# Code AST SHA-256:   4a6ca515d74867a4293ff17bcc5277c65292b8cae233b3818dae23dcc9b34118
# Verified Classes:   ProvenanceEvictionError, Span, Goal
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceEvictionError(RuntimeError):
    """Raised when a self-prune pass would sever a derivation edge
    required by an active goal or constraint."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    # span_ids this span was derived from (premise edges)
    derived_from: list[str] = field(default_factory=list)
    # precondition that must survive if this span is summarized
    precondition: Optional[str] = None


@dataclass
class Goal:
    goal_id: str
    # spans that causally support this goal (ancestors in derivation graph)
    supported_by: list[str]


def prune_context(
    spans: dict[str, Span],
    active_goals: list[Goal],
    relevance_scores: dict[str, float],
    threshold: float,
) -> dict[str, Span]:
    """Model-driven relevance prune with a provenance guardrail.

    Evicts spans scoring below `threshold`, but refuses to evict any span
    that is an ancestor of an active goal unless a derivation edge
    (span -> goal) with its precondition is preserved in the survivors.
    """
    # Build the set of spans that are ancestors of any active goal.
    required: set[str] = set()

    def collect_ancestors(span_id: str, seen: set[str]) -> None:
        if span_id in seen:
            return
        seen.add(span_id)
        required.add(span_id)
        span = spans.get(span_id)
        if span is not None:
            for parent in span.derived_from:
                collect_ancestors(parent, seen)

    for goal in active_goals:
        for sid in goal.supported_by:
            collect_ancestors(sid, set())

    survivors: dict[str, Span] = {}
    evicted_required: list[str] = []

    for sid, span in spans.items():
        score = relevance_scores.get(sid, 1.0)
        below = score < threshold
        if not below:
            survivors[sid] = span
            continue
        if sid in required:
            # Would evict a premise for an active goal.
            if span.precondition is None:
                evicted_required.append(sid)
                continue
            # Preserve as a derivation edge carrying the precondition,
            # not as a bare conclusion summary.
            survivors[sid] = Span(
                span_id=sid,
                text=f"[edge] {sid} supports active goal; precondition: {span.precondition}",
                derived_from=span.derived_from,
                precondition=span.precondition,
            )
        # else: safe to evict (input to a completed, independently-checkable action)

    if evicted_required:
        raise ProvenanceEvictionError(
            "prune would sever derivation edges for active goals without "
            f"preserving preconditions: {evicted_required}. "
            "Halt prune; do not emit conclusion-only summaries for premise spans."
        )

    return survivors
