# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-of-stale-reasoning-traces-before-self-editing-context-windows-corrupt-task-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-of-stale-reasoning-traces-before-self-editing-context-windows-corrupt-task-state.warrant.json
# Markdown SHA-256:   9942b10a9146b5aec378148a3b6f91c8d8ede7ec6b3cab8ebd2267a0dfaebf01
# Code AST SHA-256:   62893c5e0f816bc2cc3feeb48b560eb24715bc3483e51d2fa95f1810107f681e
# Verified Classes:   ClosureViolation, Trace, ObligationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ClosureViolation(RuntimeError):
    """Raised when a proposed prune set intersects the obligation closure."""


@dataclass(frozen=True)
class Trace:
    trace_id: str
    text: str
    # Forward references / deferred corrections minted from this trace.
    obligations: tuple[str, ...] = ()
    # True if this trace only restates a conclusion already propagated.
    leaf: bool = False


@dataclass
class ObligationLedger:
    # obligation_id -> trace_id it was minted from
    provenance: dict[str, str] = field(default_factory=dict)
    discharged: set[str] = field(default_factory=set)

    def mint(self, trace: Trace) -> None:
        for ob in trace.obligations:
            self.provenance[ob] = trace.trace_id

    def closure_traces(self) -> set[str]:
        """Trace IDs that are load-bearing for any undischarged obligation."""
        return {
            self.provenance[ob]
            for ob in self.provenance
            if ob not in self.discharged
        }


def safe_prune(
    traces: Iterable[Trace],
    ledger: ObligationLedger,
    proposed: set[str],
) -> set[str]:
    """
    Vet a model-proposed prune set against the obligation closure.
    Returns the actually-prunable set; raises if the model tried to
    sever an undischarged obligation.
    """
    by_id = {t.trace_id: t for t in traces}
    closure = ledger.closure_traces()

    # Interior nodes and ambiguous (non-leaf) traces are never prunable.
    for tid in proposed:
        t = by_id.get(tid)
        if t is None:
            raise ClosureViolation(f"prune set references unknown trace {tid!r}")
        if tid in closure:
            raise ClosureViolation(
                f"trace {tid!r} carries undischarged obligation(s) "
                f"{[o for o in t.obligations if o not in ledger.discharged]}; "
                f"pruning would sever dependency closure"
            )
        if not t.leaf:
            raise ClosureViolation(
                f"trace {tid!r} is not a leaf (interior or ambiguous); "
                f"retention required by closure invariant"
            )

    return set(proposed)


def self_edit(
    traces: list[Trace],
    ledger: ObligationLedger,
    model_proposed_prune: set[str],
) -> list[Trace]:
    """Two-phase self-edit: mint ledger (done by caller), then vetted prune."""
    try:
        prunable = safe_prune(traces, ledger, model_proposed_prune)
    except ClosureViolation:
        # Asymmetric consequence: on any doubt, retain. Never prune on failure.
        return list(traces)
    return [t for t in traces if t.trace_id not in prunable]
