# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-reconstruction-guarantees-when-hierarchical-memory-compaction-prunes-the-provenance-edge-but-preserves-the-summary-node.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-reconstruction-guarantees-when-hierarchical-memory-compaction-prunes-the-provenance-edge-but-preserves-the-summary-node.warrant.json
# Markdown SHA-256:   e04f06aaf415c04b947a9af9216004bd37240abfe60f322429f1b44a6089f461
# Code AST SHA-256:   ef360f29403494cca02cff5dbca6e64626bedd00af7b247de49eeb62a43cf151
# Verified Classes:   SourceKind, Node, ProvenanceCollapseError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set, List, Optional


class SourceKind(str, Enum):
    EPISODE = "episode"
    SUMMARY = "summary"


@dataclass
class Node:
    node_id: str
    kind: SourceKind
    provenance: Set[str] = field(default_factory=set)  # inbound source node ids
    irreconstructable: bool = False
    truncation_boundary: Optional[str] = None


class ProvenanceCollapseError(RuntimeError):
    """Raised when a prune would leave a retained summary with no leaf-reachable path
    and no recorded truncation boundary, silently breaking reconstruction guarantees."""
    pass


def reconstructable(node_id: str, graph: Dict[str, Node], _seen: Optional[Set[str]] = None) -> bool:
    """Coinductive check: a node is reconstructable iff it is a leaf episode, or it is
    explicitly marked irreconstructable with a boundary, or every provenance source is
    reconstructable. Cycles are treated as non-reconstructable (no leaf grounding)."""
    _seen = _seen or set()
    if node_id in _seen:
        return False
    _seen.add(node_id)
    node = graph[node_id]
    if node.kind is SourceKind.EPISODE:
        return True
    if node.irreconstructable and node.truncation_boundary is not None:
        return True  # truncation is recorded, walk may bottom out safely
    if not node.provenance:
        return False
    return all(reconstructable(src, graph, _seen) for src in node.provenance)


def commit_prune(graph: Dict[str, Node], leaves_to_delete: List[str]) -> None:
    """Delete leaves only if no retained summary loses leaf reachability without a
    recorded truncation boundary. Reverse-reachability check gated before delete."""
    saved = {lid: graph[lid] for lid in leaves_to_delete}
    for lid in leaves_to_delete:
        del graph[lid]

    # Reverse reachability: find summaries whose provenance referenced deleted leaves.
    affected = [
        n.node_id for n in graph.values()
        if n.kind is SourceKind.SUMMARY and n.provenance & set(leaves_to_delete)
    ]
    broken = [nid for nid in affected if not reconstructable(nid, graph)]
    if broken:
        # Roll back the delete; refuse to commit a silent provenance collapse.
        graph.update(saved)
        raise ProvenanceCollapseError(
            f"prune would irreconstructably collapse provenance for {broken}; "
            f"demote to irreconstructable=true with truncation_boundary or defer prune"
        )
