# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-task-critical-facts-when-hierarchical-auto-compaction-evicts-a-level-2-summary-before-its-children-are-re-derivable.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-task-critical-facts-when-hierarchical-auto-compaction-evicts-a-level-2-summary-before-its-children-are-re-derivable.warrant.json
# Markdown SHA-256:   875273f43ea2345c4a68b262aa23d833e326b26fe3a489eac71b5d613a6d1886
# Code AST SHA-256:   eef801df998e0ab35085d2c5a795f5a9cd40aa0a94664c861bab0d4b1efb4d77
# Verified Classes:   FactClass, OrphanedEvictionError, SummaryNode, CompactionGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class FactClass(Enum):
    TOOL_OUTPUT = "tool_output"
    ERROR_TRACE = "error_trace"
    DECISION = "decision"
    REJECTION_RATIONALE = "rejection_rationale"
    USER_PREFERENCE = "user_preference"


class OrphanedEvictionError(RuntimeError):
    """Raised when an eviction would leave a fact class uncovered at every level."""


@dataclass
class SummaryNode:
    node_id: str
    tier: int
    covered_facts: set[FactClass]
    schema_certified: set[FactClass]  # fact classes this tier's template is certified to carry
    tombstoned: set[FactClass] = field(default_factory=set)


@dataclass
class CompactionGraph:
    surviving: dict[str, SummaryNode] = field(default_factory=dict)
    addressable_raw_spans: set[str] = field(default_factory=set)

    def coverage_for(self, fact: FactClass, excluding: str) -> bool:
        for nid, node in self.surviving.items():
            if nid == excluding:
                continue
            if fact in node.tombstoned:
                return True  # explicit gap is acceptable coverage
            if fact in node.covered_facts and fact in node.schema_certified:
                return True
        return fact.value in self.addressable_raw_spans

    def authorize_eviction(self, node_id: str) -> None:
        node = self.surviving[node_id]
        uncovered = [
            f for f in node.covered_facts
            if not self.coverage_for(f, excluding=node_id)
        ]
        if uncovered:
            raise OrphanedEvictionError(
                f"eviction of {node_id} (tier {node.tier}) would orphan fact classes "
                f"{[f.value for f in uncovered]}: no surviving ancestor certifies them, "
                f"no raw span is addressable, and no tombstone records the gap. "
                f"Refuse eviction; widen parent schema or write tombstone first."
            )
        del self.surviving[node_id]


def fold_and_evict(graph: CompactionGraph, parent: SummaryNode, child_ids: list[str]) -> None:
    child_facts = set().union(*(graph.surviving[c].covered_facts for c in child_ids))
    missing = child_facts - parent.schema_certified
    if missing:
        raise OrphanedEvictionError(
            f"parent {parent.node_id} schema does not certify fact classes "
            f"{[f.value for f in missing]}; folding would drop them. "
            f"Widen parent template or retain children."
        )
    parent.covered_facts |= child_facts
    graph.surviving[parent.node_id] = parent
    for cid in child_ids:
        graph.authorize_eviction(cid)
