# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-prune-its-own-context-window-and-then-lose-the-tool-call-that-authorized-the-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-prune-its-own-context-window-and-then-lose-the-tool-call-that-authorized-the-pruning.warrant.json
# Markdown SHA-256:   a64c202b05a2d66c0aee65ff3e8ece96fe3ea2fd116cfc0f6a6ff9a43476f655
# Code AST SHA-256:   4f1963a10b6d9d14148ec61ae5159183be2e21d6744165d30646bcfddf43f35c
# Verified Classes:   PruningInvariantViolation, Span, ContextWindow
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class PruningInvariantViolation(RuntimeError):
    """Raised when a self-editing context policy removes a span that a
    reachable tool call depends on, or when precondition validation is
    attempted against a pruned (non-authoritative) window."""


@dataclass(frozen=True)
class Span:
    start: int
    end: int

    def overlaps(self, other: "Span") -> bool:
        return not (self.end < other.start or other.end < self.start)


@dataclass
class ContextWindow:
    durable_turns: dict[int, str] = field(default_factory=dict)
    pruned_spans: list[Span] = field(default_factory=list)
    pinned_spans: list[Span] = field(default_factory=list)
    provenance: list[dict] = field(default_factory=list)

    def pin(self, span: Span) -> None:
        self.pinned_spans.append(span)

    def request_prune(self, span: Span, policy: str) -> None:
        for pinned in self.pinned_spans:
            if span.overlaps(pinned):
                raise PruningInvariantViolation(
                    f"prune span {span} overlaps pinned span {pinned}; "
                    f"authorization/task-statement content is non-prunable"
                )
        self.pruned_spans.append(span)
        self.provenance.append(
            {"event": "prune", "span": (span.start, span.end), "policy": policy}
        )

    def resolve_precondition(self, required_span: Span) -> str:
        for pruned in self.pruned_spans:
            if pruned.overlaps(required_span):
                raise PruningInvariantViolation(
                    f"precondition at {required_span} was pruned by {pruned}; "
                    f"validate against durable_turns, not the live window"
                )
        if required_span.start not in self.durable_turns:
            raise PruningInvariantViolation(
                f"no durable record for precondition span {required_span}"
            )
        return self.durable_turns[required_span.start]


def execute_destructive_call(window: ContextWindow, grant_span: Span, table: str) -> str:
    grant = window.resolve_precondition(grant_span)
    if "except" in grant.lower() and table.lower() in grant.lower():
        raise PruningInvariantViolation(
            f"table {table!r} excluded by grant scope; refusing destructive call"
        )
    return f"deleted from {table} under grant: {grant!r}"


def demo() -> None:
    w = ContextWindow(
        durable_turns={
            3: "grant delete_records for tenant t-4471 except audit table",
        }
    )
    w.pin(Span(1, 4))  # task statement + authorization
    try:
        w.request_prune(Span(1, 9), policy="summarize_to_3_sentences")
    except PruningInvariantViolation as exc:
        print("prune refused:", exc)
    # Even if a buggy policy slipped through, precondition validation
    # against the pruned window must fail closed:
    w.pruned_spans.append(Span(1, 9))
    try:
        execute_destructive_call(w, Span(3, 3), table="audit")
    except PruningInvariantViolation as exc:
        print("call refused:", exc)


if __name__ == "__main__":
    demo()
