# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-hierarchical-auto-compaction-has-entered-the-lossy-regime-before-the-token-budget-is-exhausted.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-hierarchical-auto-compaction-has-entered-the-lossy-regime-before-the-token-budget-is-exhausted.warrant.json
# Markdown SHA-256:   a15f0cc0f2872ee11b7c87eb5efddeee32c0f16aa0cb45ce8c03453fd42ff1e0
# Code AST SHA-256:   7dd26ccf4486c9d8e1d4fb68e20f577122b6c162687632103a4451e40d98db70
# Verified Classes:   BindingIntegrityViolation, Fold, BindingLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class BindingIntegrityViolation(RuntimeError):
    """Raised when a compaction fold drops a live referent from the context."""


@dataclass
class Fold:
    inputs: list[str]
    summary: str
    tokens_freed: int


@dataclass
class BindingLedger:
    # referent -> role ("target" | "protected" | "argument")
    live: dict[str, str] = field(default_factory=dict)

    def referents_in(self, text: str) -> set[str]:
        return {r for r in self.live if r in text}


def commit_fold(fold: Fold, ledger: BindingLedger, occupancy_after: float,
                watermark: float) -> None:
    """Gate a hierarchical compaction fold on binding integrity, not occupancy.

    Occupancy improving is NOT sufficient to commit a fold. A fold that frees
    tokens while dropping a live referent puts the agent into the lossy regime
    even though the budget reads healthy. Refuse such folds.
    """
    r_in: set[str] = set()
    for seg in fold.inputs:
        r_in |= ledger.referents_in(seg)
    r_out = ledger.referents_in(fold.summary)

    dropped = r_in - r_out
    if dropped:
        # Budget improved but structure degraded: this is the lossy regime.
        raise BindingIntegrityViolation(
            f"fold dropped live referents {sorted(dropped)} "
            f"while freeing {fold.tokens_freed} tokens "
            f"(occupancy now {occupancy_after:.2f}, watermark {watermark:.2f}); "
            f"occupancy is no longer a valid capacity signal"
        )

    if occupancy_after > watermark:
        # Conservative fold but still over budget: compact a different segment,
        # do not fold again blindly.
        raise BindingIntegrityViolation(
            f"conservative fold insufficient: occupancy {occupancy_after:.2f} "
            f"still above watermark {watermark:.2f}; select another segment"
        )


def dedup_merge(a: str, b: str, ledger: BindingLedger, similarity: float,
                threshold: float = 0.9) -> str:
    """Semantic dedup must never merge operationally distinct referents."""
    ra, rb = ledger.referents_in(a), ledger.referents_in(b)
    if similarity >= threshold and ra != rb and ra and rb:
        raise BindingIntegrityViolation(
            f"refusing semantic merge of {sorted(ra)} with {sorted(rb)} "
            f"at similarity {similarity:.2f}: referent sets are disjoint, "
            f"similarity is a retrieval signal, not an identity signal"
        )
    return a if len(a) >= len(b) else b
