# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-agent-has-crossed-the-trace-recoverability-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-agent-has-crossed-the-trace-recoverability-boundary.warrant.json
# Markdown SHA-256:   6b9bd828a0f1224ae5024fcaa14a3580327e94c58163fa05cc5d9d31d1cb85da
# Code AST SHA-256:   3dd7a523ca0325fad9b355c11d90164fa693a2d84380cefbbe669c06938caafc
# Verified Classes:   PruneUnsafeError, SpanClass, ReasoningSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class PruneUnsafeError(RuntimeError):
    """Raised when a self-pruning agent attempts to delete a decision-bearing
    reasoning span whose falsifier cannot be retained in surviving state."""


class SpanClass(Enum):
    TRACE_ONLY = "trace_only"
    DECISION_WITH_FALSIFIER = "decision_with_falsifier"
    DECISION_WITHOUT_FALSIFIER = "decision_without_falsifier"


@dataclass
class ReasoningSpan:
    span_id: str
    tokens: int
    decisions: list[str]
    falsifiers: list[str]  # observations that would overturn each decision


def classify(span: ReasoningSpan) -> SpanClass:
    if not span.decisions:
        return SpanClass.TRACE_ONLY
    if len(span.falsifiers) >= len(span.decisions):
        return SpanClass.DECISION_WITH_FALSIFIER
    return SpanClass.DECISION_WITHOUT_FALSIFIER


def prune(
    spans: list[ReasoningSpan],
    budget_tokens: int,
    summary_cost_per_span: int = 40,
) -> tuple[list[str], list[str]]:
    """Return (pruned_ids, externalized_ids). Raises rather than silently
    pruning a decision-bearing span that has no retainable falsifier."""
    pruned: list[str] = []
    externalized: list[str] = []
    remaining = sum(s.tokens for s in spans)

    for span in sorted(spans, key=lambda s: s.tokens, reverse=True):
        if remaining <= budget_tokens:
            break
        cls = classify(span)
        if cls is SpanClass.TRACE_ONLY:
            pruned.append(span.span_id)
            remaining -= span.tokens - summary_cost_per_span
        elif cls is SpanClass.DECISION_WITH_FALSIFIER:
            # Safe only if the summary restates the falsifier as a
            # first-class clause; the caller is responsible for that.
            pruned.append(span.span_id)
            remaining -= span.tokens - summary_cost_per_span
        else:
            # Decision-bearing, no retainable falsifier. Cannot prune.
            # Externalize with a live pointer and keep a stub.
            externalized.append(span.span_id)
            remaining -= span.tokens - 8  # stub cost

    if remaining > budget_tokens:
        raise PruneUnsafeError(
            f"budget {budget_tokens} unreachable without pruning "
            f"decision-bearing spans lacking falsifiers; "
            f"externalized={externalized}; escalate budget-exhaustion"
        )
    return pruned, externalized


def on_downstream_contradiction(
    contradiction_span: str, externalized: list[str]
) -> str:
    """A contradiction touching an externalized decision forces re-expansion,
    not re-derivation from the summary."""
    if contradiction_span in externalized:
        return f"re-expand:{contradiction_span}"
    raise PruneUnsafeError(
        f"contradiction at {contradiction_span} has no live pointer; "
        f"agent is in the re-derivation trap and must halt"
    )
