# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-summarization-boundary-has-been-crossed-in-hierarchical-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-summarization-boundary-has-been-crossed-in-hierarchical-context-compaction.warrant.json
# Markdown SHA-256:   dbad759ce46e1fb7127f17d967ea1fd9054648af80b7ae8872790a5c7d3245e1
# Code AST SHA-256:   1dc85a5328e38caf9ea1bfd60ac86d4b5e6187bcac4ce4d5f20ce4a19f0668eb
# Verified Classes:   FrameDriftError, Span, SummaryNode
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class FrameDriftError(RuntimeError):
    """Raised when a parent summary node violates the frame invariant
    relative to its immutable child spans in the retrieval sidecar."""


@dataclass
class Span:
    span_id: str
    text: str
    negated_clauses: int
    named_entities: frozenset
    numeric_units: frozenset  # (value_token, unit_token) pairs


@dataclass
class SummaryNode:
    node_id: str
    text: str
    negated_clauses: int
    named_entities: frozenset
    numeric_units: frozenset
    cited_span_ids: list = field(default_factory=list)


def check_frame_invariant(node: SummaryNode, sidecar: dict) -> None:
    children = []
    for sid in node.cited_span_ids:
        span = sidecar.get(sid)
        if span is None:
            raise FrameDriftError(
                f"node {node.node_id!r} cites unknown span {sid!r}"
            )
        children.append(span)

    # 1. Polarity: parent must not be more affirmative than its children.
    child_neg = sum(s.negated_clauses for s in children)
    if node.negated_clauses < child_neg:
        raise FrameDriftError(
            f"polarity drift at {node.node_id!r}: parent has "
            f"{node.negated_clauses} negated clauses, children carry "
            f"{child_neg}; negation was collapsed at merge boundary"
        )

    # 2. Named-entity binding: parent must not introduce unnamed referents
    #    that its children did not name.
    child_entities = frozenset().union(*(s.named_entities for s in children))
    orphan = node.named_entities - child_entities
    if orphan:
        raise FrameDriftError(
            f"entity binding drift at {node.node_id!r}: parent names "
            f"{sorted(orphan)} absent from all cited child spans"
        )

    # 3. Unit preservation: every numeric token in the parent must carry
    #    a unit that appears in a child span.
    child_units = frozenset().union(*(s.numeric_units for s in children))
    if not node.numeric_units.issubset(child_units):
        missing = node.numeric_units - child_units
        raise FrameDriftError(
            f"unit elision at {node.node_id!r}: parent asserts {sorted(missing)} "
            f"with no matching (value, unit) pair in cited children"
        )


def compact_or_demote(node: SummaryNode, sidecar: dict) -> str:
    """Return 'primary' if the summary is safe as ground truth,
    'navigation_only' if demoted, or raise on hard integrity faults."""
    try:
        check_frame_invariant(node, sidecar)
    except FrameDriftError:
        # Demotion is the safe default; re-raise only for unknown-span
        # cases which indicate a corrupted reference, not mere drift.
        for sid in node.cited_span_ids:
            if sid not in sidecar:
                raise
        return "navigation_only"
    return "primary"
