# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-model-driven-context-pruning-against-a-monotonic-evidence-invariant-before-committing-a-tool-action.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-model-driven-context-pruning-against-a-monotonic-evidence-invariant-before-committing-a-tool-action.warrant.json
# Markdown SHA-256:   803568d86f33f5437f9bbedb31428a20e027fd9e7ef0a528c150ecedd5356039
# Code AST SHA-256:   b5cc48e1a888b0b6da41d3dac193f0ea9e362df711b3993e0dda8a8b3bb7b165
# Verified Classes:   EvidenceProvenanceError, ContextWindow
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EvidenceProvenanceError(RuntimeError):
    """Raised when a pending action's precondition cannot be resolved to
    a raw or re-expandable span in the self-edited context window."""


class ContextWindow:
    def __init__(self, budget_tokens: int):
        self.budget = budget_tokens
        self.spans = {}          # span_id -> {"text": str, "pinned": bool,
                                 #             "provenance": list[str] | None}

    def pin(self, span_id: str) -> None:
        if span_id not in self.spans:
            raise EvidenceProvenanceError(f"cannot pin missing span {span_id}")
        self.spans[span_id]["pinned"] = True

    def evict(self, span_id: str, summary_id: str, summary_text: str) -> None:
        span = self.spans[span_id]
        if span["pinned"]:
            raise EvidenceProvenanceError(
                f"refusing to evict pinned span {span_id}: it backs a pending action"
            )
        # Eviction is only legal if the summary retains a re-expansion pointer.
        self.spans[summary_id] = {
            "text": summary_text,
            "pinned": False,
            "provenance": [span_id],
        }
        del self.spans[span_id]

    def resolve(self, span_id: str) -> str:
        span = self.spans.get(span_id)
        if span is None:
            raise EvidenceProvenanceError(
                f"precondition span {span_id} was pruned with no provenance"
            )
        if span["provenance"] is None:
            return span["text"]
        # Re-expand through provenance chain; any broken link is a hard stop.
        parts = [self.resolve(p) for p in span["provenance"]]
        return " ".join(parts)


def commit_tool_action(window: ContextWindow, action: dict) -> None:
    """Gate: every precondition must resolve before the action is emitted."""
    for span_id in action.get("precondition_span_ids", []):
        try:
            window.resolve(span_id)
        except EvidenceProvenanceError as exc:
            raise EvidenceProvenanceError(
                f"blocking action {action.get('name')}: precondition "
                f"{span_id} is not traceable to live evidence"
            ) from exc
    # Only reached when the evidence base is intact.
    emit(action)


def emit(action: dict) -> None:  # placeholder for the real tool transport
    ...
