# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-after-model-driven-context-pruning-silently-removes-the-causal-premise-of-an-active-tool-call-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-after-model-driven-context-pruning-silently-removes-the-causal-premise-of-an-active-tool-call-chain.warrant.json
# Markdown SHA-256:   b9faa9e7d1ac56c3f1f717874175fe5d0acd31a9b9a736e8eac83e3f3016fdd7
# Code AST SHA-256:   ebd2f508aceeba8ae8f0143d10fe2225990584ef5ae834ca3775355ad2255b68
# Verified Classes:   PremiseDeletionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PremiseDeletionError(RuntimeError):
    """Raised when context pruning has evicted a premise still cited by a pending step."""
    pass


class Span:
    def __init__(self, span_id, text, kind, reconstructible_from=None):
        self.span_id = span_id
        self.text = text
        self.kind = kind  # "constraint" | "tool_result" | "reasoning"
        self.reconstructible_from = reconstructible_from  # span_id or None


def classify_evictability(span, cited_by_pending):
    """A span is safe to evict only if it is reconstructible AND not cited by pending work."""
    if cited_by_pending and span.reconstructible_from is None:
        return "SOLE_CARRIER"
    if span.kind == "tool_result" and cited_by_pending:
        return "SOLE_CARRIER"  # tool outputs are never compressible when consumed
    return "RECONSTRUCTIBLE"


def prune(context, pending_chain, retention_budget):
    # Backward pass: collect all premises cited by pending steps.
    cited = set()
    for step in pending_chain:
        cited.update(step.cited_premises)

    kept, evicted = [], []
    for span in context:
        verdict = classify_evictability(span, span.span_id in cited)
        if verdict == "SOLE_CARRIER":
            kept.append(span)  # never evict, even under pressure
        elif len(kept) < retention_budget:
            kept.append(span)
        else:
            evicted.append(span)

    # Closure check: every cited premise must survive in kept or via provenance.
    kept_ids = {s.span_id for s in kept}
    provenance_ids = {s.reconstructible_from for s in kept if s.reconstructible_from}
    missing = cited - kept_ids - provenance_ids
    if missing:
        raise PremiseDeletionError(
            f"pruning would delete cited premises {missing}; "
            f"checkpoint and rehydrate instead of pruning"
        )
    return kept, evicted


def execute_step(step, context):
    # Referent-resolution guard: justification must resolve in current context.
    live_ids = {s.span_id for s in context}
    for ref in step.justification_referents:
        if ref not in live_ids:
            raise PremiseDeletionError(
                f"step {step.id} cites referent {ref!r} absent from context; "
                f"premise was pruned — halt chain"
            )
    return step.run()
