# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-relevance-pruning-severs-the-causal-chain-to-a-live-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-relevance-pruning-severs-the-causal-chain-to-a-live-tool-call.warrant.json
# Markdown SHA-256:   eaeb499fb8c61e1c6b515a402917d4843eba86b044d24a8a63243884e1be9538
# Code AST SHA-256:   6f369a58e83b5821ebd24b4168f78e8b13b1356f14e97f24fafdca014bbb63c8
# Verified Classes:   UnreconciledCallError, LiveSpan, ContextManager
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnreconciledCallError(RuntimeError):
    """Raised when a context rewrite or reconciliation step encounters a
    live obligation whose key was severed or whose return cannot be matched."""
    pass


@dataclass
class LiveSpan:
    call_id: str
    arg_hash: str
    return_shape: str
    reconciled: bool = False


@dataclass
class ContextManager:
    live: dict[str, LiveSpan] = field(default_factory=dict)
    context: list[str] = field(default_factory=list)

    def dispatch(self, call_id: str, arg_hash: str, return_shape: str) -> None:
        self.live[call_id] = LiveSpan(call_id, arg_hash, return_shape)

    def prune(self, span_id: str, relevance_score: float) -> None:
        # Invariant: a live span is never scored for relevance.
        if span_id in self.live and not self.live[span_id].reconciled:
            raise UnreconciledCallError(
                f"refusing to relevance-prune live obligation {span_id!r} "
                f"(score={relevance_score}); compress via obligation path instead"
            )
        self.context = [s for s in self.context if s != span_id]

    def compress_live(self, call_id: str, summary: str) -> None:
        span = self.live.get(call_id)
        if span is None:
            raise UnreconciledCallError(f"no live span for {call_id!r}")
        if not (span.call_id and span.arg_hash and span.return_shape):
            raise UnreconciledCallError(
                f"compression of {call_id!r} would sever reconciliation key"
            )
        # Key preserved verbatim; only prose is replaced by summary.
        self.context.append(f"[live:{span.call_id}|{span.arg_hash}|{span.return_shape}] {summary}")

    def reconcile(self, call_id: str, payload: str) -> None:
        span = self.live.get(call_id)
        if span is None or span.reconciled:
            raise UnreconciledCallError(
                f"return for {call_id!r} has no live binding; "
                f"likely severed by a prior rewrite — do not re-dispatch blindly"
            )
        span.reconciled = True
        self.context.append(f"[result:{call_id}] {payload[:80]}")


def safe_rewrite(cm: ContextManager, span_id: str, score: float) -> None:
    cm.prune(span_id, score)
