# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-the-audit-trail-of-a-compacted-span-when-hierarchical-summarization-crosses-a-provenance-watermark.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-the-audit-trail-of-a-compacted-span-when-hierarchical-summarization-crosses-a-provenance-watermark.warrant.json
# Markdown SHA-256:   c3d0ce5542234d779d40c0c7bec3daaa93aa765f89b62537c5eb86c744009b12
# Code AST SHA-256:   72a2f49caf8665d369ca65d796fd2cb7dd23c6fafb0bf2fe452511f7ed5e16f6
# Verified Classes:   ProvenanceWatermarkError, SummaryNode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class ProvenanceWatermarkError(RuntimeError):
    """Raised when hierarchical compaction breaks the leaf-set union invariant."""
    pass


@dataclass
class SummaryNode:
    node_id: str
    text: str
    leaf_ids: frozenset[str]
    leaf_kind: Literal["event", "summary_node"]


def compact_level(children: list[SummaryNode], model_summary_text: str,
                  new_node_id: str) -> SummaryNode:
    # Provenance is computed by code, never taken from the model.
    union_leaves = frozenset().union(*(c.leaf_ids for c in children))
    max_child = max((len(c.leaf_ids) for c in children), default=0)

    if len(union_leaves) < max_child:
        raise ProvenanceWatermarkError(
            f"leaf-set cardinality decreased: union={len(union_leaves)} "
            f"< max_child={max_child} at node {new_node_id}"
        )
    if any(c.leaf_kind == "summary_node" for c in children) and not union_leaves:
        raise ProvenanceWatermarkError(
            f"node {new_node_id} summarizes summary_nodes with empty leaf union; "
            "would produce an ungrounded, uncitable span"
        )

    return SummaryNode(
        node_id=new_node_id,
        text=model_summary_text,
        leaf_ids=union_leaves,
        leaf_kind="event",  # terminal leaves are always primitive events
    )


def resolve_citation(node: SummaryNode, leaf_store: dict[str, str]) -> list[str]:
    if node.leaf_kind != "event":
        raise ProvenanceWatermarkError(
            f"cannot cite non-terminal node {node.node_id} of kind {node.leaf_kind}"
        )
    missing = [lid for lid in node.leaf_ids if lid not in leaf_store]
    if missing:
        raise ProvenanceWatermarkError(
            f"citation for {node.node_id} references GC'd leaves: {missing[:5]}"
        )
    return [leaf_store[lid] for lid in node.leaf_ids]
