# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-mid-task-and-the-pruner-s-rationale-is-itself-pruned.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-mid-task-and-the-pruner-s-rationale-is-itself-pruned.warrant.json
# Markdown SHA-256:   6831c51b50b1cda9c93b362ccbbb92e5595447c82740e260b6fc1a241097e9e6
# Code AST SHA-256:   15d59c0d6e4decb78f8382e2ba0fc35ff79b8066b90aeebf63cf33ba7386d9b7
# Verified Classes:   SelfPruneProvenanceError, Turn, PruneRequest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SelfPruneProvenanceError(RuntimeError):
    """Raised when a model-driven prune would delete the provenance for a
    closure/negation claim in its own summary, or would drop the rationale
    turn that carries the prune decision itself."""
    pass


CLOSURE_TOKENS = ("done", "complete", "resolved", "do not", "already", "ignore")


@dataclass
class Turn:
    index: int
    content: str

    def digest(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()[:12]


@dataclass
class PruneRequest:
    rationale_turn: int
    drop: list[int]
    summary: str
    # map: closure-claim substring -> turn index that evidences it
    provenance: dict[str, int] = field(default_factory=dict)


def validate_self_prune(req: PruneRequest, turns: dict[int, Turn]) -> None:
    # Guard 1: the rationale turn must never be inside its own drop set.
    if req.rationale_turn in req.drop:
        raise SelfPruneProvenanceError(
            f"rationale turn {req.rationale_turn} is inside its own drop set "
            f"{sorted(req.drop)}; the decision would delete its own justification"
        )

    # Guard 2: every closure/negation claim in the summary needs surviving provenance.
    lowered = req.summary.lower()
    for token in CLOSURE_TOKENS:
        if token not in lowered:
            continue
        if token not in req.provenance:
            raise SelfPruneProvenanceError(
                f"summary asserts closure via {token!r} with no provenance pointer; "
                f"downgrade to hypothesis or cite a surviving turn"
            )
        evidence_turn = req.provenance[token]
        if evidence_turn in req.drop:
            raise SelfPruneProvenanceError(
                f"provenance for {token!r} lives in turn {evidence_turn}, "
                f"which is scheduled for eviction; commitment would be unauditable"
            )
        if evidence_turn not in turns:
            raise SelfPruneProvenanceError(
                f"provenance pointer for {token!r} references missing turn {evidence_turn}"
            )

    # Guard 3: dropped evidence must be reconstructable from surviving hashes.
    for token, evidence_turn in req.provenance.items():
        surviving = turns.get(evidence_turn)
        if surviving is None:
            raise SelfPruneProvenanceError(
                f"cannot hash evidence for {token!r}: turn {evidence_turn} unavailable"
            )


def apply_self_prune(req: PruneRequest, turns: dict[int, Turn]) -> dict[int, Turn]:
    validate_self_prune(req, turns)
    kept = {i: t for i, t in turns.items() if i not in req.drop}
    kept[req.rationale_turn] = turns[req.rationale_turn]  # pin rationale
    return kept
