# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-self-edited-context-window-when-a-rewrite-silently-invalidates-a-still-pending-tool-result.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-self-edited-context-window-when-a-rewrite-silently-invalidates-a-still-pending-tool-result.warrant.json
# Markdown SHA-256:   90c381bde2aec581d676416d730cf5dead5895e80dbaf60439c2061efcc2d1f6
# Code AST SHA-256:   2476552720c3e557edd453d099f35fe84f532d3d6c576a8263770a076be35f74
# Verified Classes:   ResultWithoutContract, EffectContract, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResultWithoutContract(RuntimeError):
    """Raised when a tool result returns into a context that no longer
    holds the query/args/intent that produced it, and no ledger entry
    exists to reconcile against. The result is uninterpretable; do not
    reconstruct a predicate from residual context."""
    pass


@dataclass(frozen=True)
class EffectContract:
    effect_id: str
    query: str
    args: tuple
    intent: str


@dataclass
class ContextWindow:
    spans: list = field(default_factory=list)
    pinned: dict = field(default_factory=dict)  # effect_id -> EffectContract
    ledger: dict = field(default_factory=dict)  # durable, out-of-band

    def dispatch_effect(self, contract: EffectContract) -> None:
        # Pin the contract at issuance: the question asked the world
        # is a commitment and is immune to salience scoring.
        self.pinned[contract.effect_id] = contract
        self.ledger[contract.effect_id] = contract

    def rewrite(self, evict: set) -> None:
        # Salience pruning / contradiction resolution. Must not evict
        # any span backing a live effect contract.
        protected = {c.query for c in self.pinned.values()}
        blocked = evict & protected
        if blocked:
            raise ResultWithoutContract(
                f"rewrite would evict live effect antecedent(s): {sorted(blocked)}"
            )
        self.spans = [s for s in self.spans if s not in evict]

    def reconcile(self, effect_id: str, result) -> EffectContract:
        contract: Optional[EffectContract] = self.pinned.get(effect_id)
        if contract is None:
            # Effect may have been evicted from the window but survive
            # in the durable ledger. Reconcile against the ledger, never
            # against a reconstructed predicate.
            contract = self.ledger.get(effect_id)
        if contract is None:
            raise ResultWithoutContract(
                f"effect {effect_id!r} returned with no contract in window "
                f"or ledger; result is uninterpretable, re-issue explicitly"
            )
        self.pinned.pop(effect_id, None)
        return contract
