# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-lossy-auto-compaction-has-silently-severed-a-causal-dependency-in-a-long-horizon-agent-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-lossy-auto-compaction-has-silently-severed-a-causal-dependency-in-a-long-horizon-agent-trace.warrant.json
# Markdown SHA-256:   5ecf4ba1dbeca597f5f7bc2f2f891e4dd721b405c46d3948fa501715b3933bbf
# Code AST SHA-256:   e453dea4de326133bebca0eeb72343ecab51cf241ac3d8ea7993a5dcbac4f8b4
# Verified Classes:   CausalDependencySevered, PlanBinding, CompactionRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CausalDependencySevered(RuntimeError):
    """Raised when compaction evicts a symbol that a live plan step dereferences,
    or when reinflation resolves that symbol to a default instead of its source."""
    pass


@dataclass
class PlanBinding:
    symbol: str
    source_step: int
    is_write_precondition: bool


@dataclass
class CompactionRequest:
    evict_candidate_steps: set[int]
    live_bindings: dict[str, PlanBinding] = field(default_factory=dict)


def compact(req: CompactionRequest, pinned_steps: set[int]) -> set[int]:
    """Return the eviction set, refusing to evict any step that is the sole
    source of a live plan binding. Pinned steps are exempt unconditionally."""
    protected: set[int] = set(pinned_steps)
    for binding in req.live_bindings.values():
        protected.add(binding.source_step)

    evict = req.evict_candidate_steps - protected
    severed = req.evict_candidate_steps & protected
    if severed:
        # Do not silently drop; surface the intersection so the caller can
        # pin or promote the binding before retrying.
        raise CausalDependencySevered(
            f"eviction set intersects live binding sources at steps {sorted(severed)}; "
            f"promote these bindings to a structured side-channel before compaction"
        )
    return evict


def resolve_symbol(symbol: str, bindings: dict[str, PlanBinding], retrieved: dict[str, str]) -> str:
    """Resolve a symbol post-compaction. Fails closed: a missing binding that
    would otherwise fall back to a system-prompt default raises instead."""
    if symbol in bindings:
        return f"bound:{bindings[symbol].source_step}"
    if symbol in retrieved:
        return retrieved[symbol]
    raise CausalDependencySevered(
        f"symbol {symbol!r} has no live binding and no retrieved source; "
        f"refusing to substitute a default value"
    )
