# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-when-the-pruned-span-is-the-sole-witness-of-a-tool-call-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-when-the-pruned-span-is-the-sole-witness-of-a-tool-call-side-effect.warrant.json
# Markdown SHA-256:   aca9f52b1f50f8368d11173eb764674a798868ad844779d8ed6581bf339939d1
# Code AST SHA-256:   970502dc2de2d7b24dc1f59ee24af87a0379947c151785ba18ad0a7dead1a5fe
# Verified Classes:   PruningRefusal, SpanKind, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class PruningRefusal(RuntimeError):
    """Raised when a pruning policy attempts to evict a witness span."""
    pass


class SpanKind(Enum):
    RECONSTRUCTIBLE = "reconstructible"
    WITNESS = "witness"


@dataclass
class Span:
    call_id: str
    kind: SpanKind
    carries_idempotency_token: bool
    body: str

    def content_hash(self) -> str:
        return hashlib.sha256(self.body.encode()).hexdigest()


def prune_span(span: Span, witness_store: dict, durable: bool) -> str:
    """
    Returns the in-context replacement for a span.
    Reconstructible spans may be summarized. Witness spans may only be
    replaced by a durable pointer, never by a paraphrase.
    """
    if span.kind is SpanKind.RECONSTRUCTIBLE:
        return f"[summary of {span.call_id}]"

    # Witness span: must relocate, never summarize.
    if not durable:
        raise PruningRefusal(
            f"witness span {span.call_id} cannot be relocated to a non-durable "
            f"store; eviction would destroy the only record of its side effect"
        )

    if span.carries_idempotency_token and span.call_id not in witness_store:
        raise PruningRefusal(
            f"witness span {span.call_id} carries an idempotency token but has "
            f"no committed receipt; refusing to evict before relocation"
        )

    witness_store[span.call_id] = {
        "hash": span.content_hash(),
        "body": span.body,
    }
    return f"[witness ptr {span.call_id} sha256:{span.content_hash()[:12]}]"


def apply_pruning_policy(spans, witness_store, durable):
    out = []
    for span in spans:
        out.append(prune_span(span, witness_store, durable))
    return out
