# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-context-window-rewrite-as-a-commit-rather-than-a-hint.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-context-window-rewrite-as-a-commit-rather-than-a-hint.warrant.json
# Markdown SHA-256:   2fcbad6fd68c41e979cb1d4b15b24841f67cbb33e1c65e0a15276c82f0d11cef
# Code AST SHA-256:   4506cfab11e661a8147753817e77f6d877b160d494d3ff2ecd5a0ff8dd015280
# Verified Classes:   UnrecoverableRewriteError, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnrecoverableRewriteError(RuntimeError):
    """Raised when a rewrite directive names a span removed by a prior destructive directive
    and no durable substrate exists to recover the original bytes."""
    pass


class ContextWindow:
    def __init__(self):
        self.generation = 0
        self.spans = {}          # span_id -> bytes (live window only)
        self.removed = set()     # span_ids removed destructively
        self.durable_log = None  # optional external recovery source

    def apply_rewrite(self, directive):
        inputs = set(directive.input_spans)
        crossing = inputs & self.removed
        if crossing and self.durable_log is None:
            raise UnrecoverableRewriteError(
                f"directive {directive.kind} references removed spans {sorted(crossing)} "
                f"at generation {self.generation}; no durable log — this is a commit, "
                f"not a hint. Reject or supply a recovery source."
            )
        if directive.kind == "drop":
            for sid in inputs:
                self.spans.pop(sid, None)
                self.removed.add(sid)
        elif directive.kind == "reexpand":
            if self.durable_log is None:
                raise UnrecoverableRewriteError(
                    f"reexpand of {sorted(inputs)} would produce a paraphrase, not bytes"
                )
            for sid in inputs:
                self.spans[sid] = self.durable_log.fetch(sid)
        self.generation += 1
