# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-hierarchical-compaction-has-silently-inverted-a-negation-before-eviction-commits-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-hierarchical-compaction-has-silently-inverted-a-negation-before-eviction-commits-it.warrant.json
# Markdown SHA-256:   2ae9bdb4b5b02d0133707ff0a3ae58d69f136e935924c964a08198e3c9f529bb
# Code AST SHA-256:   791d1b821bfe46767f2f376e0c27c18c99e6033f54bcf5f411b5f66aca618f3d
# Verified Classes:   PolarityInversionError, CompactedNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass

POLARITY_LEXEMES = re.compile(
    r"\b(not|never|without|except|must|may|should|can|cannot|"
    r"before|after|then|until|gated on|only|all|any|at least)\b",
    re.IGNORECASE,
)


class PolarityInversionError(RuntimeError):
    """Raised when an abstractive compaction node does not conservatively
    entail a polarity-bearing span of the children it is about to evict."""


@dataclass
class CompactedNode:
    text: str
    extractive: bool          # True if built only from verbatim spans
    children: list[str]


def polarity_spans(children: list[str]) -> list[str]:
    spans = []
    for child in children:
        for sentence in re.split(r"(?<=[.!?])\s+", child):
            if POLARITY_LEXEMES.search(sentence):
                spans.append(sentence.strip())
    return spans


def entails(premise: str, hypothesis: str) -> bool:
    """Directional NLI: does the child (premise) entail the parent claim
    (hypothesis)? Fail-closed on neutral/contradiction. Stubbed here;
    wire to a real NLI model in production."""
    raise NotImplementedError("bind to NLI backend")


def commit_compaction(node: CompactedNode) -> CompactedNode:
    if node.extractive:
        return node  # polarity preserved by construction

    spans = polarity_spans(node.children)
    if not spans:
        return node  # nothing operative to invert

    for span in spans:
        # Does the abstractive parent entail the child's constraint?
        if not entails(premise=span, hypothesis=node.text):
            raise PolarityInversionError(
                f"Compaction node does not entail polarity-bearing child span.\n"
                f"  child span : {span!r}\n"
                f"  parent node: {node.text!r}\n"
                f"  action     : reject node, retain children, or pin span verbatim"
            )
    return node
