# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-lossy-compaction-has-crossed-the-rehydration-horizon-in-agent-context-management.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-lossy-compaction-has-crossed-the-rehydration-horizon-in-agent-context-management.warrant.json
# Markdown SHA-256:   1f7e93cdee49ea73e038b9a8ee01654046db32c0ae8e249da9f57165614880d1
# Code AST SHA-256:   57137bdc4b20646f5817818ec93dd434318264708b6d9a90a73c1d23de7f3060
# Verified Classes:   RehydrationHorizonError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RehydrationHorizonError(RuntimeError):
    """Raised when a lossy compaction summary loses the retrieval handles
    needed to re-derive a load-bearing constraint from the retrieval store."""
    pass


def compact_turn(turn: dict, store, budget_tokens: int) -> dict:
    """Compact one turn into a summary + handle ledger.

    Invariant: every constraint in the turn must either survive as a verbatim
    handle in the ledger OR be explicitly marked non-load-bearing. A summary
    that names a constraint without a queryable handle is rejected.
    """
    handles = extract_handles(turn)          # deterministic NER + tool args
    constraints = extract_constraints(turn)  # polarity-tagged obligations

    summary = summarize_lossy(turn["text"], budget=budget_tokens)

    for c in constraints:
        if c.get("load_bearing", True):
            if c["key"] not in handles:
                # The constraint has no surviving handle -> the agent can never
                # form the retrieval query that would recover it. Refuse.
                raise RehydrationHorizonError(
                    f"Compaction of turn {turn['id']} dropped handle "
                    f"'{c['key']}' for load-bearing constraint "
                    f"'{c['text']}'. Summary would be unreachable."
                )
            # Verify the store can actually answer the handle before we rely on it.
            hits = store.query(c["key"])
            if not hits:
                raise RehydrationHorizonError(
                    f"Handle '{c['key']}' retained but retrieval store returns "
                    f"no supporting turn; rehydration would dead-end."
                )

    return {
        "summary": summary,
        "handles": handles,          # never summarized, only deduped
        "constraints": constraints,  # polarity + key, survives verbatim
    }


def rehydrate(agent_state: dict, store) -> list:
    """Formulate queries strictly from the handle ledger, never from the
    lossy summary, so unreachability cannot be self-reinforcing."""
    recovered = []
    for c in agent_state["constraints"]:
        if c.get("load_bearing", True):
            hits = store.query(c["key"])
            if not hits:
                raise RehydrationHorizonError(
                    f"Rehydration failed for constraint key '{c['key']}': "
                    f"ledger promised reachability, store disagrees."
                )
            recovered.extend(hits)
    return recovered
