# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-laundering-evicted-context-past-the-audit-trail.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-laundering-evicted-context-past-the-audit-trail.warrant.json
# Markdown SHA-256:   7618507bed838cf08b626d1b0cea23d5545fb725a70b93269be08d84099cd276
# Code AST SHA-256:   fdf103cacc246b2bb0f97c7c65e93d6c98991b28d6ae917f8118fc7510703042
# Verified Classes:   CompactionGroundingError, SummaryNode, Ledger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionGroundingError(RuntimeError):
    """Raised when a summary node asserts a claim not transitively entailed
    by its retained original spans, or when an underdetermined fold resolves
    ambiguity instead of propagating PARTIAL/UNRESOLVED."""


@dataclass
class SummaryNode:
    node_id: str
    level: int
    text: str
    source_span_ids: list[str]
    evicted_descendants: int = 0
    grounded: Optional[bool] = None
    status: str = "OK"  # OK | PARTIAL | UNRESOLVED | UNGROUNDED


@dataclass
class Ledger:
    evicted_spans: dict[str, str] = field(default_factory=dict)  # span_id -> node_id
    retained_spans: dict[str, str] = field(default_factory=dict)  # span_id -> text
    derivation: dict[str, list[str]] = field(default_factory=dict)  # node_id -> child ids

    def leaves(self, node_id: str) -> list[str]:
        """Walk derivation down to original span ids."""
        children = self.derivation.get(node_id)
        if not children:
            return [node_id]
        out: list[str] = []
        for c in children:
            out.extend(self.leaves(c))
        return out


def entailment_check(claim: str, spans: list[str]) -> bool:
    # Placeholder for a real NLI/entailment call against retained span text.
    return all(s in claim or claim in s for s in spans) if spans else False


def fold_children(
    parent: SummaryNode,
    children: list[SummaryNode],
    ledger: Ledger,
    *,
    transitive: bool = True,
) -> SummaryNode:
    """Fold child summaries into a parent. Enforces the grounding invariant:
    at level >= 2, entailment must be checked transitively against original
    spans, and underdetermined folds must not resolve ambiguity."""
    if parent.level >= 2 and not transitive:
        raise CompactionGroundingError(
            f"node {parent.node_id} at level {parent.level} requested local-only "
            f"entailment; closure assumption is invalid above L1"
        )

    evicted = sum(c.evicted_descendants for c in children)
    for c in children:
        for span_id in ledger.leaves(c.node_id):
            if span_id in ledger.evicted_spans:
                evicted += 1

    if evicted > 0 and parent.status == "OK":
        # Underdetermined fold: summarizer must not smooth over missing leaves.
        if "only" in parent.text or "single" in parent.text:
            raise CompactionGroundingError(
                f"node {parent.node_id}: fold has {evicted} evicted descendants "
                f"but summary resolves ambiguity ('only'/'single'); must emit PARTIAL"
            )
        parent.status = "PARTIAL"

    if transitive:
        leaf_texts = [
            ledger.retained_spans[s]
            for c in children
            for s in ledger.leaves(c.node_id)
            if s in ledger.retained_spans
        ]
        if not leaf_texts:
            parent.grounded = False
            parent.status = "UNGROUNDED"
        elif not entailment_check(parent.text, leaf_texts):
            raise CompactionGroundingError(
                f"node {parent.node_id}: claim not entailed by retained original "
                f"spans (transitive check failed)"
            )
        else:
            parent.grounded = True

    ledger.derivation[parent.node_id] = [c.node_id for c in children]
    return parent


def act_on_digest(node: SummaryNode) -> str:
    """Agent acting on a compacted claim must refuse UNGROUNDED/PARTIAL
    claims that would drive irreversible operations."""
    if node.status in ("UNGROUNDED", "PARTIAL") and node.level >= 2:
        raise CompactionGroundingError(
            f"refusing to act on {node.node_id}: status={node.status}, "
            f"re-fetch source spans before proceeding"
        )
    return node.text
