# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-model-driven-pruning-has-silently-excised-the-load-bearing-span-of-its-own-in-flight-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-model-driven-pruning-has-silently-excised-the-load-bearing-span-of-its-own-in-flight-task.warrant.json
# Markdown SHA-256:   22f22fb3588285134b30da2eb6ea0aa4c38b6b910500876297f2b6f84e3e239a
# Code AST SHA-256:   8787129dcd86722e090422c1b2f2dcb7a0ba3bf2219f5e8d24ae74a6a10daa4c
# Verified Classes:   SilentExcisionError, Span, SelfEditingWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SilentExcisionError(RuntimeError):
    """Raised when a span required by a pending downstream step was evicted."""


class Span:
    def __init__(self, span_id, content, produced_by, consumed_by=None):
        self.span_id = span_id
        self.content = content
        self.produced_by = produced_by
        self.consumed_by = consumed_by  # None => pending consumption
        self.pinned = consumed_by is None  # unconsumed => not evictable


class SelfEditingWindow:
    def __init__(self, token_budget):
        self.token_budget = token_budget
        self.spans = {}
        self.eviction_log = []  # readable by the agent

    def add(self, span):
        self.spans[span.span_id] = span

    def mark_consumed(self, span_id, consumer_step):
        self.spans[span_id].consumed_by = consumer_step
        self.spans[span_id].pinned = False

    def evict(self, span_id, score, current_subgoal):
        span = self.spans[span_id]
        if span.pinned:
            raise SilentExcisionError(
                f"refusing to evict {span_id}: produced by {span.produced_by}, "
                f"consumption pending; score={score} under subgoal={current_subgoal!r} "
                f"is relevance-to-now, not relevance-to-later"
            )
        self.eviction_log.append({
            "span_id": span_id,
            "evicted_at_subgoal": current_subgoal,
            "score": score,
            "refetch_handle": f"{span.produced_by}:span={span_id}",
        })
        del self.spans[span_id]

    def diff_against_source(self, source_spans):
        # verification must run against source, not the current window
        for sid, src in source_spans.items():
            if sid not in self.spans:
                logged = any(e["span_id"] == sid for e in self.eviction_log)
                if not logged:
                    raise SilentExcisionError(
                        f"span {sid} absent from window with no eviction record; "
                        f"window is corrupt, not merely compacted"
                    )
        return True
