# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-pruning-agents-from-deleting-the-provenance-edge-that-justifies-a-retained-fact.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-pruning-agents-from-deleting-the-provenance-edge-that-justifies-a-retained-fact.warrant.json
# Markdown SHA-256:   812b7f98424a09622b1c9e24da0bee3e4e1852af20b901eedeeaa93cf9764bb7
# Code AST SHA-256:   e3a300a2f0ea2c18037b61ca3aefb22b9045590de623e5c8cd78ec88c51b3c86
# Verified Classes:   ProvenanceFrontierViolation, Span, ContextWindow
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class ProvenanceFrontierViolation(RuntimeError):
    """Raised when a prune would evict the sole provenance for a retained claim."""


@dataclass
class Span:
    span_id: str
    text: str
    derived_from: Set[str] = field(default_factory=set)  # provenance edges


@dataclass
class ContextWindow:
    spans: Dict[str, Span] = field(default_factory=dict)
    retained_claims: Set[str] = field(default_factory=set)

    def add(self, span: Span) -> None:
        self.spans[span.span_id] = span

    def retain_claim(self, span_id: str) -> None:
        self.retained_claims.add(span_id)

    def prune(self, evict: Set[str]) -> None:
        """
        Commit a model-driven prune. Hard precondition: no retained claim may
        lose its entire live provenance frontier. If a retained claim depends
        on an evicted span, the claim must be demoted (removed from
        retained_claims) or the eviction must abort.
        """
        # Compute the set of spans that survive the prune.
        survivors = set(self.spans) - evict

        # For each retained claim, check it still has >=1 live provenance edge
        # OR is a raw observation with no provenance requirement.
        for claim_id in list(self.retained_claims):
            claim = self.spans.get(claim_id)
            if claim is None:
                continue
            if not claim.derived_from:
                # Raw observation: self-grounding, no frontier required.
                continue
            live_edges = claim.derived_from & survivors
            if not live_edges:
                # Sole provenance is being evicted. This is the failure trace:
                # a retained conclusion outliving its evidence.
                raise ProvenanceFrontierViolation(
                    f"prune would evict sole provenance for retained claim "
                    f"{claim_id!r}; evicted sources={claim.derived_from & evict!r}. "
                    f"Demote the claim or retain a source span."
                )

        # Precondition satisfied: commit.
        for span_id in evict:
            self.spans.pop(span_id, None)


def safe_prune(window: ContextWindow, evict: Set[str]) -> None:
    """Wrapper that demotes instead of aborting, per policy."""
    try:
        window.prune(evict)
    except ProvenanceFrontierViolation:
        # Demote all claims whose frontier would be destroyed, then retry.
        survivors = set(window.spans) - evict
        for claim_id in list(window.retained_claims):
            claim = window.spans.get(claim_id)
            if claim and claim.derived_from and not (claim.derived_from & survivors):
                window.retained_claims.discard(claim_id)
        window.prune(evict)  # now safe; raises only on genuine bug
