# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-semantic-inversion-introduced-by-hierarchical-summarization-when-a-folded-checkpoint-silently-promotes-a-subordinate-cla.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-semantic-inversion-introduced-by-hierarchical-summarization-when-a-folded-checkpoint-silently-promotes-a-subordinate-cla.warrant.json
# Markdown SHA-256:   804d50db46ffe6156c98cbcb157b96cf0292049ac466b326fa8039e2f8664b54
# Code AST SHA-256:   bf9497927faef43759f3243b289b7f3c8294d525d8929dbc51d73682c9719783
# Verified Classes:   ConstraintInversionError, Fold
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field

GOVERNORS = re.compile(
    r"\b(if|only|unless|requires?|provided|assuming|except|not|never|"
    r"must|cannot|may|might|up to|at most|at least|before|after|until)\b",
    re.IGNORECASE,
)
POLARITY_PREDICATES = re.compile(
    r"\b(safe|unsafe|allowed|blocked|ready|valid|released|held|enabled|disabled)\b",
    re.IGNORECASE,
)
NUMERAL = re.compile(r"\b\d+\s*(s|sec|min|ms|h|hr|%|gb|mb)?\b", re.IGNORECASE)


class ConstraintInversionError(RuntimeError):
    """Raised when a fold promotes a governed proposition to an ungoverned assertion."""


@dataclass
class Fold:
    level: int
    text: str
    source_spans: list = field(default_factory=list)


def _sentences(text: str):
    return [s.strip() for s in re.split(r"(?<=[.!?;])\s+|\n+", text) if s.strip()]


def check_fold_integrity(parent: Fold, child: Fold, min_governor_gap: int = 40):
    # 1. Every polarity predicate in the child must have a governor within
    #    min_governor_gap characters, OR be traceable to a governed parent span.
    for sent in _sentences(child.text):
        for pred in POLARITY_PREDICATES.finditer(sent):
            window = sent[: pred.start()][-min_governor_gap:] + sent[pred.end() : pred.end() + min_governor_gap]
            if not GOVERNORS.search(window):
                # predicate asserted bare in the child; is it governed anywhere in parent?
                parent_governed = any(
                    GOVERNORS.search(p) and POLARITY_PREDICATES.search(p)
                    for p in _sentences(parent.text)
                )
                if not parent_governed:
                    continue  # predicate was bare in parent too; not an inversion
                raise ConstraintInversionError(
                    f"level {child.level} fold asserts bare predicate "
                    f"{pred.group(0)!r} with no governor; parent governed it. "
                    f"Offending sentence: {sent!r}"
                )

    # 2. Numerals in the child must not introduce a bounding modal absent in parent.
    parent_nums = {m.group(0).lower() for m in NUMERAL.finditer(parent.text)}
    for sent in _sentences(child.text):
        for num in NUMERAL.finditer(sent):
            if num.group(0).lower() not in parent_nums:
                continue
            # numeral retained; ensure it did not gain an exclusivity modal
            tail = sent[num.end() : num.end() + 20]
            if re.search(r"\b(within|exactly|always|guaranteed)\b", tail, re.IGNORECASE) and not re.search(
                r"\b(within|exactly|always|guaranteed)\b", parent.text, re.IGNORECASE
            ):
                raise ConstraintInversionError(
                    f"level {child.level} fold added exclusivity modal to numeral "
                    f"{num.group(0)!r} not present in parent: {sent!r}"
                )

    # 3. Every child sentence must map to at least one parent span, else it is
    #    ungrounded synthesis and must be rejected.
    if child.source_spans and len(child.source_spans) < len(_sentences(child.text)):
        raise ConstraintInversionError(
            f"level {child.level} fold has {len(_sentences(child.text))} sentences "
            f"but only {len(child.source_spans)} provenance spans; ungrounded sentence present."
        )
    return True


def fold_with_guard(parent: Fold, summarize_fn, budget: int, retries: int = 2):
    for attempt in range(retries + 1):
        child = summarize_fn(parent.text, budget * (2 ** attempt))
        try:
            check_fold_integrity(parent, child)
            return child
        except ConstraintInversionError:
            if attempt == retries:
                # legality fallback: carry parent forward un-folded rather than
                # admit a strengthened constraint into the checkpoint
                raise ConstraintInversionError(
                    f"fold at level {parent.level + 1} rejected after {retries} retries; "
                    f"carry parent forward verbatim"
                )
    raise ConstraintInversionError("unreachable")
