# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-context-compaction-has-severed-a-causal-dependency-chain-before-rehydration.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-context-compaction-has-severed-a-causal-dependency-chain-before-rehydration.warrant.json
# Markdown SHA-256:   bacef62cf99fd528c6cfa50ccedf181f35d8daa7016f8f7ff3b2a214872fa0ba
# Code AST SHA-256:   4f53aa49bbc65183497e4ddc1a6ef1db2540613608f58e33ebb783635f3b0dbc
# Verified Classes:   SeveredBindingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SeveredBindingError(RuntimeError):
    """Raised when a rehydrated context cannot ground a referenced binding."""
    pass


def admit_rehydrated_chunk(chunk: dict, required_binding: dict, manifest: dict) -> bool:
    """
    Gate admission of a rehydrated chunk for a step that references a binding.

    required_binding: {"symbol": "job_7f3a", "constraint": "no delete on staging"}
    manifest: eviction-time record of symbol -> constraint, exact.
    """
    symbol = required_binding["symbol"]
    constraint = required_binding["constraint"]

    # The manifest is the authority on what was supposed to survive eviction.
    if manifest.get(symbol) != constraint:
        raise SeveredBindingError(
            f"Manifest has no exact record for {symbol!r}; "
            f"compaction may have evicted an untagged definition."
        )

    # Similarity score is necessary but NOT sufficient; exact antecedent required.
    text = chunk.get("text", "")
    if symbol not in text or constraint not in text:
        raise SeveredBindingError(
            f"Rehydrated chunk scores {chunk.get('score'):.3f} but does not "
            f"contain binding {symbol!r} -> {constraint!r}. "
            f"Topic-similar is not referentially adequate; escalate to lossless store."
        )
    return True


def execute_dependent_call(call: dict, admitted_chunks: list, manifest: dict) -> None:
    for ref in call.get("binding_refs", []):
        grounded = any(
            ref["symbol"] in c.get("text", "") and ref["constraint"] in c.get("text", "")
            for c in admitted_chunks
        )
        if not grounded:
            raise SeveredBindingError(
                f"Blocking {call['tool']}({call.get('args')}): binding "
                f"{ref['symbol']!r} -> {ref['constraint']!r} is ungrounded "
                f"after compaction. Refusing to execute on a dangling reference."
            )
    # only reached when every binding reference is grounded
    dispatch(call)
