# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-editing-pruning-of-a-still-live-reasoning-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-editing-pruning-of-a-still-live-reasoning-trajectory.warrant.json
# Markdown SHA-256:   d688f10fc2aa8280003e11437acae923d9744a37eb22cbd56b5c2a67152ecfd1
# Code AST SHA-256:   90062ec3e09d2aac0349f8bfb859f48fa58472dabdbb47642f44fbb52b1edfb8
# Verified Classes:   PruneViolation, LedgerEntry, ContextBuffer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PruneViolation(RuntimeError):
    """Raised when a self-prune would remove the only support for a live obligation."""
    pass


@dataclass
class LedgerEntry:
    constraint_id: str
    statement: str          # verbatim, never paraphrased
    origin_turn: int
    live: bool = True


@dataclass
class ContextBuffer:
    turns: dict[int, str] = field(default_factory=dict)
    ledger: dict[str, LedgerEntry] = field(default_factory=dict)

    def support_spans(self, entry: LedgerEntry) -> list[int]:
        # A turn supports an entry if the verbatim statement appears in it.
        return [t for t, text in self.turns.items() if entry.statement in text]


def self_prune(buf: ContextBuffer, candidate_turns: list[int],
               retained_summary: str) -> ContextBuffer:
    """Prune candidate_turns only if no live obligation loses its last support.

    Gate order: extract -> resolve -> block -> verify (post-prune).
    """
    # 1. Extract: ledger entries whose support lies in the candidate set.
    at_risk = [
        e for e in buf.ledger.values()
        if e.live and any(t in candidate_turns for t in buf.support_spans(e))
    ]

    # 2. Resolve + 3. Block: any live entry with no support outside the
    #    candidate set must be promoted verbatim into the retained summary.
    for entry in at_risk:
        outside = [t for t in buf.support_spans(entry) if t not in candidate_turns]
        if not outside and entry.statement not in retained_summary:
            raise PruneViolation(
                f"refusing prune: live obligation {entry.constraint_id!r} "
                f"(origin turn {entry.origin_turn}) has no support outside "
                f"candidate turns {candidate_turns} and is absent from summary. "
                f"Retain verbatim: {entry.statement!r}"
            )

    # Apply the prune.
    for t in candidate_turns:
        buf.turns.pop(t, None)
    buf.turns[-1] = retained_summary  # sentinel retained-summary slot

    # 4. Verify: every live entry must still have a support span.
    for entry in buf.ledger.values():
        if entry.live and not buf.support_spans(entry):
            raise PruneViolation(
                f"post-prune verification failed: {entry.constraint_id!r} "
                f"lost all support after pruning {candidate_turns}"
            )
    return buf


# Triggering trace (the observed failure, now blocked):
buf = ContextBuffer()
buf.turns[3] = ("backoff cap missing; fix cap. do not change max_retries, "
                "test asserts max_retries == 3")
buf.ledger["max_retries_pinned"] = LedgerEntry(
    constraint_id="max_retries_pinned",
    statement="test asserts max_retries == 3",
    origin_turn=3,
)
# Instance tries to prune turns 1-8 with an outcome-shaped summary:
self_prune(buf, candidate_turns=[3],
           retained_summary="fixed backoff cap issue in config")
# -> raises PruneViolation: the pinned invariant would have been silently lost.
