# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-lossy-compaction-has-silently-promoted-a-summary-s-hedged-inference-into-a-load-bearing-fact.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-lossy-compaction-has-silently-promoted-a-summary-s-hedged-inference-into-a-load-bearing-fact.warrant.json
# Markdown SHA-256:   a8c66e9afcf927a99fe79064023a40e6b38f41c543aa24c4dabdacf2012898c4
# Code AST SHA-256:   5e027809baa20efc2e0759af48dc96908656ad72e72f1bc23415553f1243262e
# Verified Classes:   EpistemicPromotionError, Census
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass
from typing import List

# Epistemic operators that encode the agent's own uncertainty.
HEDGE_PATTERN = re.compile(
    r"\b(probably|likely|unverified|unconfirmed|assumed?|assuming|inconclusive|"
    r"tentative|maybe|possibly|presumably|I think|not sure|uncertain|guess)\b",
    re.IGNORECASE,
)


class EpistemicPromotionError(RuntimeError):
    """Raised when lossy compaction promotes a hedged inference to a flat fact."""


@dataclass
class Census:
    hedge_count: int
    inferred_propositions: List[str]


def census(window_text: str) -> Census:
    """Count uncertainty operators and capture the propositions that carry them."""
    inferred = []
    for sentence in re.split(r"(?<=[.!?])\s+", window_text):
        if HEDGE_PATTERN.search(sentence):
            inferred.append(sentence.strip())
    return Census(
        hedge_count=len(HEDGE_PATTERN.findall(window_text)),
        inferred_propositions=inferred,
    )


def validate_compaction(
    pre: Census,
    summary_text: str,
    min_retention_ratio: float = 0.5,
) -> None:
    """Reject a summary that dropped the uncertainty channel below its floor."""
    post_hedges = len(HEDGE_PATTERN.findall(summary_text))
    floor = int(pre.hedge_count * min_retention_ratio)

    if pre.hedge_count > 0 and post_hedges < floor:
        raise EpistemicPromotionError(
            f"Compaction dropped uncertainty markers: pre={pre.hedge_count} "
            f"post={post_hedges} floor={floor}. "
            f"{len(pre.inferred_propositions)} inferred propositions at risk "
            f"of promotion to fact."
        )

    # Any inferred proposition re-expressed bare in the summary is a promotion.
    for prop in pre.inferred_propositions:
        core = re.sub(HEDGE_PATTERN, "", prop).strip()
        if core and core in summary_text and "[inferred]" not in summary_text:
            raise EpistemicPromotionError(
                f"Hedged proposition emitted without [inferred] marker: {core!r}"
            )
