# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-summarizing-agent-has-crossed-from-compression-into-referent-loss.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-summarizing-agent-has-crossed-from-compression-into-referent-loss.warrant.json
# Markdown SHA-256:   a94992afe5c5af857e70553cdb6e1e864b30db78da7da8e6b66b791c3665e47f
# Code AST SHA-256:   94c5c9ac24dcb750c6ce511865c255d8898d7bbbda0b5b4bc9f93ea1587a9efa
# Verified Classes:   ReferentLossError, CompactionCheck
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class ReferentLossError(RuntimeError):
    """Raised when a compacted context emits an identifier/numeric/negated
    token without an inline binding or an explicit unresolved marker."""
    pass


# Identifier-shaped or numeric tokens that a downstream step may dereference.
DEREFERENCEABLE = re.compile(
    r"\b([A-Za-z_][A-Za-z0-9_]*_(?:cents|ref|id|uuid|ts|at|count|pct))\b"
    r"|\b(\d+(?:\.\d+)?)\b"
)

# A binding is "inline" if a type/unit/polarity token sits within this many
# characters of the mention, or the mention carries an explicit marker.
BINDING_WINDOW = 24
BINDING_TOKENS = re.compile(
    r"\b(int|bigint|uuid|timestamptz|decimal|float|cents|dollars|pct|"
    r"NO|NOT|never|do not|unresolved|see probe)\b",
    re.IGNORECASE,
)


@dataclass
class CompactionCheck:
    compacted: str
    source_window: str


def _binding_adjacent(text: str, start: int, end: int) -> bool:
    lo = max(0, start - BINDING_WINDOW)
    hi = min(len(text), end + BINDING_WINDOW)
    return bool(BINDING_TOKENS.search(text[lo:hi]))


def verify_bindings(check: CompactionCheck) -> None:
    """Reject a self-compacted state block that emits a dereferenceable
    token bare (no adjacent binding, no unresolved marker). Also reject a
    binding that was paraphrased rather than copied verbatim from source."""
    for m in DEREFERENCEABLE.finditer(check.compacted):
        token = m.group(0)
        if not _binding_adjacent(check.compacted, m.start(), m.end()):
            raise ReferentLossError(
                f"referent loss: token {token!r} emitted bare at offset "
                f"{m.start()} in compacted context; no type/unit/polarity "
                f"within {BINDING_WINDOW} chars and no 'unresolved' marker. "
                f"Re-run compaction with binding-preservation instruction."
            )

        # If a binding IS present, it must be copied verbatim from source,
        # not paraphrased (guards against fabricated units).
        lo = max(0, m.start() - BINDING_WINDOW)
        hi = min(len(check.compacted), m.end() + BINDING_WINDOW)
        for b in BINDING_TOKENS.finditer(check.compacted[lo:hi]):
            binding = b.group(0)
            if binding.lower() in ("unresolved", "see probe"):
                continue
            if binding.lower() not in check.source_window.lower():
                raise ReferentLossError(
                    f"fabricated binding: {binding!r} attached to {token!r} "
                    f"does not appear verbatim in pre-compaction window; "
                    f"bindings must be copied, never paraphrased."
                )


def compact_with_guard(state: str, source_window: str, summarizer) -> str:
    """Wrap a model-driven compaction with the binding invariant. On failure,
    re-run once with an explicit binding-preservation instruction; if it
    fails again, refuse to proceed rather than emit a fluent-but-dangling
    state block."""
    compacted = summarizer(state, instruction="be concise; preserve decisions")
    try:
        verify_bindings(CompactionCheck(compacted, source_window))
        return compacted
    except ReferentLossError:
        compacted = summarizer(
            state,
            instruction=(
                "be concise, but every identifier, numeric literal, and "
                "negated constraint MUST carry its type/unit/sign inline, "
                "copied verbatim from source, or be marked 'unresolved'."
            ),
        )
        verify_bindings(CompactionCheck(compacted, source_window))
        return compacted
