# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-model-driven-context-pruning-as-a-destructive-write-not-a-read-optimization.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-model-driven-context-pruning-as-a-destructive-write-not-a-read-optimization.warrant.json
# Markdown SHA-256:   fcb1dbdcc57ea09009631ebb28bceb6b177e8fc516e65bb06b8a9f2f48d81b68
# Code AST SHA-256:   42cb64e2a6d06a761bdbc670d45d200558415a2744edf196839c25acf2666016
# Verified Classes:   SpanKind, PruneRefused, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class SpanKind(Enum):
    TOOL_RESULT = "tool_result"
    REASONING = "reasoning"
    FAILURE = "failure"


class PruneRefused(RuntimeError):
    """Raised when a model-driven prune would destroy unrecoverable state."""


@dataclass(frozen=True)
class Span:
    span_id: str
    kind: SpanKind
    idempotent_source: bool
    content: str
    durable_pointer: str | None = None

    def digest(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()[:16]


def authorize_prune(span: Span, utilization: float, threshold: float = 0.80) -> dict:
    if utilization <= threshold:
        return {"action": "keep", "span_id": span.span_id}

    # Failure evidence is never prunable: the retry loop depends on it.
    if span.kind is SpanKind.FAILURE:
        raise PruneRefused(
            f"span {span.span_id} is failure evidence; pruning it would erase "
            f"the record of a rejected attempt and permit silent re-issue"
        )

    # Reasoning is always a destructive write: non-deterministic, unreplayable.
    if span.kind is SpanKind.REASONING:
        raise PruneRefused(
            f"span {span.span_id} is model reasoning; cannot be re-derived to "
            f"identical state, requires checkpoint not eviction"
        )

    # Tool result: prunable only if idempotent-and-cheap, or pointer-backed.
    if span.kind is SpanKind.TOOL_RESULT:
        if span.idempotent_source:
            return {"action": "evict", "span_id": span.span_id, "recoverable": "re-call"}
        if span.durable_pointer is None:
            raise PruneRefused(
                f"span {span.span_id} from non-idempotent source has no durable "
                f"pointer; eviction would destroy the only copy (digest {span.digest()})"
            )
        return {
            "action": "evict",
            "span_id": span.span_id,
            "recoverable": span.durable_pointer,
            "digest": span.digest(),
        }

    raise PruneRefused(f"unclassified span {span.span_id}")


def run_policy(spans: list[Span], utilization: float) -> list[dict]:
    decisions, refused = [], []
    for s in spans:
        try:
            decisions.append(authorize_prune(s, utilization))
        except PruneRefused as e:
            refused.append(str(e))
            decisions.append({"action": "keep", "span_id": s.span_id, "reason": str(e)})
    if refused:
        # Escalate: a policy that wants to prune pinned state is itself suspect.
        decisions.append({"action": "checkpoint_and_halt_policy", "refused": refused})
    return decisions
