# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-window-has-crossed-from-summarization-into-self-referential-erasure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-window-has-crossed-from-summarization-into-self-referential-erasure.warrant.json
# Markdown SHA-256:   6e86ea312cdbb23bfbfab552363db927219c6377042aef121e03fec10097241d
# Code AST SHA-256:   366cb88f2b306414becec62b218e6a3d4c782e75117ac26f685377a52f86aa06
# Verified Classes:   ProvenanceClosureViolation, Artifact, ContextBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceClosureViolation(RuntimeError):
    """Raised when a self-authored rewrite would erase provenance of a pruned span."""


@dataclass(frozen=True)
class Artifact:
    kind: str                      # "observation" | "summary" | "fold" | "tombstone"
    leaf_refs: FrozenSet[str]      # leaf span-ids this artifact stands in for
    prunable: bool = True          # tombstones set this False


@dataclass
class ContextBuffer:
    artifacts: list = field(default_factory=list)

    def surviving_leaf_refs(self) -> FrozenSet[str]:
        refs = set()
        for a in self.artifacts:
            refs |= a.leaf_refs
        return frozenset(refs)

    def apply_rewrite(self, target_idx: int, replacement: Artifact,
                      open_leaf_refs: FrozenSet[str]) -> None:
        target = self.artifacts[target_idx]
        if not target.prunable:
            raise ProvenanceClosureViolation(
                f"attempt to rewrite non-prunable artifact (kind={target.kind})"
            )
        # Monotone provenance: replacement must cover every leaf the target covered.
        lost = target.leaf_refs - replacement.leaf_refs
        if lost:
            raise ProvenanceClosureViolation(
                f"rewrite drops leaf refs {sorted(lost)} from {target.kind}; "
                f"emit tombstones instead of folding them away"
            )
        # Open-question containment: the task must still be able to answer its
        # open questions after the rewrite.
        post = self.surviving_leaf_refs() - target.leaf_refs | replacement.leaf_refs
        if not open_leaf_refs.issubset(post):
            missing = open_leaf_refs - post
            raise ProvenanceClosureViolation(
                f"rewrite would orphan open-question refs {sorted(missing)}; "
                f"schedule re-read before dependent step"
            )
        self.artifacts[target_idx] = replacement


def self_prune(buf: ContextBuffer, target_idx: int, summary: Artifact,
               open_leaf_refs: FrozenSet[str]) -> None:
    """Model-authored prune entrypoint. Fails closed on closure violations."""
    try:
        buf.apply_rewrite(target_idx, summary, open_leaf_refs)
    except ProvenanceClosureViolation:
        # Fail closed: do not fall back to a lossy rewrite. Leave the raw span
        # in place and let the caller re-read from cold storage.
        raise
