# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-model-driven-context-pruning-from-silently-deleting-the-evidence-a-later-reasoning-step-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-model-driven-context-pruning-from-silently-deleting-the-evidence-a-later-reasoning-step-depends-on.warrant.json
# Markdown SHA-256:   d8fdefbad6b0517dfab8c627ad144ff4c5e300325d830f46a00fb3b9df0ddccd
# Code AST SHA-256:   a00a7719c64acc1e4d00a2b884ed1ea0b9a6d122e447dddc5d83a08b8dbd3c6f
# Verified Classes:   ReferentialClosureViolation, PlanStep, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ReferentialClosureViolation(RuntimeError):
    """Raised when a prune/rewrite operator removes a literal that a pending
    plan step will dereference, leaving a dangling reference in the working set."""


@dataclass
class PlanStep:
    step_id: str
    # Literal tokens this step will dereference at execution time.
    obligated_symbols: set[str] = field(default_factory=set)


@dataclass
class Span:
    span_id: str
    text: str
    # True if the span's source cannot be re-run to reproduce the same value
    # (nondeterministic tool, one-shot id, prior model turn). Such spans are
    # non-rehydratable and must never be pruned while obligated.
    rehydratable: bool = True

    def contains(self, symbol: str) -> bool:
        return symbol in self.text


def apply_prune(
    working_set: list[Span],
    span_id: str,
    pending_steps: list[PlanStep],
) -> list[Span]:
    """Apply a model-driven prune, enforcing referential closure.

    Prune is allowed only if the span holds no obligated symbol, OR if it is
    rehydratable (in which case the caller must have installed a stub first).
    """
    target = next((s for s in working_set if s.span_id == span_id), None)
    if target is None:
        raise ReferentialClosureViolation(f"unknown span {span_id!r}")

    obligated = {sym for step in pending_steps for sym in step.obligated_symbols}
    hit = {sym for sym in obligated if target.contains(sym)}

    if hit and not target.rehydratable:
        # Category-3: non-re-derivable literal under a committed plan.
        raise ReferentialClosureViolation(
            f"prune of span {span_id!r} would drop non-rehydratable "
            f"obligated symbols {sorted(hit)} required by pending plan"
        )
    if hit and target.rehydratable:
        # Category-2: require a stub carrying exact literals before deletion.
        raise ReferentialClosureViolation(
            f"prune of span {span_id!r} needs a rehydration stub for "
            f"{sorted(hit)} before deletion is permitted"
        )
    # Category-1: no obligation touched; prune is safe.
    return [s for s in working_set if s.span_id != span_id]


def check_turn_boundary(working_set: list[Span], pending_steps: list[PlanStep]) -> None:
    """Hard gate: every obligated symbol must still resolve before execution."""
    resolved = {sym for span in working_set for sym in span.text.split()}
    for step in pending_steps:
        missing = {s for s in step.obligated_symbols if s not in resolved}
        if missing:
            raise ReferentialClosureViolation(
                f"plan step {step.step_id!r} dereferences unresolved symbols "
                f"{sorted(missing)}; halt and re-plan"
            )


def demo() -> None:
    ws = [
        Span("read_schema", "orders.legacy_id -> orders.external_ref", rehydratable=False),
        Span("chatter", "user asked about migration status", rehydratable=True),
    ]
    pending = [PlanStep("migrate", {"legacy_id", "external_ref"})]
    # Safe: chatter has no obligated symbol.
    ws = apply_prune(ws, "chatter", pending)
    # Unsafe: schema span holds non-rehydratable obligated literals.
    apply_prune(ws, "read_schema", pending)


if __name__ == "__main__":
    demo()
