# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-hierarchical-re-summarization-of-a-compacted-checkpoint-the-summary-of-summary-drift-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-hierarchical-re-summarization-of-a-compacted-checkpoint-the-summary-of-summary-drift-boundary.warrant.json
# Markdown SHA-256:   bd7cfb45b272ece52ab1c3962edf4d1937d93cbbdf0ce8040b96ee122c0e4b7a
# Code AST SHA-256:   8f5b8d6111a968c3185db84e134a870b1e3a7a2c95996bfedd917bb552429c91
# Verified Classes:   SealedNodeError, QualifierDriftError, SummaryNode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SealedNodeError(RuntimeError):
    """Raised when an instance attempts to re-summarize a node whose
    provenance leaves are no longer reachable (sealed checkpoint node)."""
    pass


class QualifierDriftError(RuntimeError):
    """Raised when re-compaction changes a load-bearing modal/numeric token
    relative to the prior root, indicating qualifier erosion across layers."""
    pass


@dataclass
class SummaryNode:
    depth: int
    text: str
    leaves_reachable: bool
    qualifiers_preserved: bool
    prior_root: Optional[str] = None
    children: list = field(default_factory=list)


LOAD_BEARING = {"approved", "pending", "proposed", "tentative", "if", "not"}


def _load_bearing_tokens(text: str) -> set:
    return {t for t in text.lower().split() if t in LOAD_BEARING or t.replace(",", "").replace("$", "").isdigit()}


def recompact(node: SummaryNode, new_text: str, temperature: float) -> SummaryNode:
    # Invariant 1: provenance reachability bounds composition depth.
    if node.depth >= 1 and not node.leaves_reachable:
        raise SealedNodeError(
            f"refuse re-summarization: node at depth {node.depth} is sealed "
            f"(leaves unreachable); rehydrate leaves or treat as immutable"
        )
    # Invariant 2: qualifier preservation contract.
    if node.depth >= 1 and not node.qualifiers_preserved:
        raise SealedNodeError(
            "refuse re-summarization: qualifier preservation contract not met "
            "at depth >= 1; cap composition depth at 1"
        )
    # Invariant 3: idempotence / seed-pinning on load-bearing tokens.
    if node.prior_root is not None:
        if temperature > 0:
            raise QualifierDriftError(
                "re-compaction must run at temperature 0 with pinned seed, "
                "else the checkpoint is non-reproducible"
            )
        before = _load_bearing_tokens(node.prior_root)
        after = _load_bearing_tokens(new_text)
        if before != after:
            raise QualifierDriftError(
                f"load-bearing token drift on re-compaction: {before ^ after}"
            )
    return SummaryNode(
        depth=node.depth + 1,
        text=new_text,
        leaves_reachable=node.leaves_reachable,
        qualifiers_preserved=node.qualifiers_preserved,
        prior_root=node.text,
    )
