# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-driven-context-pruning-decision-as-irreversible-and-when-may-it-be-safely-re-derived.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-driven-context-pruning-decision-as-irreversible-and-when-may-it-be-safely-re-derived.warrant.json
# Markdown SHA-256:   8eb7f9f874275a906d0d0f189960e8d5383390132277558aff942a064f267096
# Code AST SHA-256:   50e7a38d8a548b32d10e315567f738d43b4a8542fa9d4c4f97a347a27f04c2be
# Verified Classes:   PruneBoundaryViolation, SpanKind, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class PruneBoundaryViolation(RuntimeError):
    """Raised when a prune decision crosses the re-derivability boundary."""
    pass


class SpanKind(Enum):
    OBSERVED = "observed"
    DERIVED = "derived"
    SUMMARY = "summary"


@dataclass
class Span:
    span_id: str
    kind: SpanKind
    content: str
    locator: Optional[str] = None          # path+hash, tool_call_id, message_id
    source_hash: Optional[str] = None
    authored_by_scorer: bool = False
    derivations: list = field(default_factory=list)


def _hash(s: str) -> str:
    return hashlib.sha256(s.encode()).hexdigest()


def commit_prune(span: Span, *, env_mutated_since_capture: bool,
                 derivation_log: dict, scorer_id: str) -> str:
    """
    Decide whether a span may be dropped from the window.
    Returns 'pruned' or 'persisted'. Raises on boundary violation.
    """
    # Rule 1: scorer output is never a valid eviction candidate.
    if span.authored_by_scorer or span.kind is SpanKind.SUMMARY:
        raise PruneBoundaryViolation(
            f"span {span.span_id} was authored by scorer {scorer_id}; "
            "excluded from candidate set"
        )

    # Rule 2: derivations are irreversible regardless of re-fetchability.
    if span.kind is SpanKind.DERIVED:
        derivation_log[span.span_id] = {
            "content": span.content,
            "inputs": span.derivations,
        }
        return "persisted"

    # Rule 3: observations require a pinned locator and a monotone environment.
    if span.kind is SpanKind.OBSERVED:
        if span.locator is None or span.source_hash is None:
            raise PruneBoundaryViolation(
                f"span {span.span_id} has no pinned locator; cannot treat as re-derivable"
            )
        if env_mutated_since_capture:
            raise PruneBoundaryViolation(
                f"span {span.span_id} source mutated since capture "
                f"({span.source_hash}); re-fetch would launder state"
            )
        return "pruned"

    raise PruneBoundaryViolation(f"unhandled span kind {span.kind}")


def score_and_evict(window: list[Span], threshold: float, scorer_id: str,
                    derivation_log: dict, mutated: set[str]) -> list[Span]:
    """
    Reference set excludes scorer output; candidate set excludes summaries.
    The overlap that triggers the amnesia attractor is structurally impossible.
    """
    candidates = [s for s in window
                  if not s.authored_by_scorer and s.kind is not SpanKind.SUMMARY]
    survivors = [s for s in window if s not in candidates]
    for s in candidates:
        decision = commit_prune(
            s,
            env_mutated_since_capture=s.span_id in mutated,
            derivation_log=derivation_log,
            scorer_id=scorer_id,
        )
        if decision == "pruned":
            continue
        survivors.append(s)
    return survivors
