# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-self-authored-context-rewrite-when-summarization-collides-with-an-in-flight-tool-call-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-self-authored-context-rewrite-when-summarization-collides-with-an-in-flight-tool-call-contract.warrant.json
# Markdown SHA-256:   dad34700c4592670b2a72e7ee15645d06ea41c85f3c629222210b50a9fff1309
# Code AST SHA-256:   83d87c43cf5bbd58cea86349d8d59102061c8d5b9eba7fc32af0d369a468ceb7
# Verified Classes:   ObligationBoundaryViolation, PendingObligation, WorkingMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ObligationBoundaryViolation(RuntimeError):
    """Raised when a self-rewrite would mutate a region carrying a pending obligation."""
    pass


@dataclass
class PendingObligation:
    correlation_id: str
    region: str                 # buffer region the antecedent bytes live in
    has_external_handle: bool   # True if verbatim antecedents are resolvable out-of-band
    verbatim_antecedents: str   # what was actually dispatched


@dataclass
class WorkingMemory:
    regions: dict = field(default_factory=dict)          # region -> token text
    obligations: dict = field(default_factory=dict)      # cid -> PendingObligation

    def pending_in(self, region: str) -> list:
        return [o for o in self.obligations.values() if o.region == region]

    def rewrite_region(self, region: str, new_text: str, saturation: float) -> None:
        """Self-edit entry point. Enforces antecedent immutability under budget pressure."""
        pending = self.pending_in(region)

        # Budget pressure is the TRIGGER for scrutiny, not a license to skip it.
        for ob in pending:
            if not ob.has_external_handle:
                # No out-of-band resolution path: mutating this region destroys the
                # only faithful record of what was dispatched. Forbidden at any budget.
                raise ObligationBoundaryViolation(
                    f"refusing rewrite of region {region!r}: pending obligation "
                    f"{ob.correlation_id!r} has no external handle; verbatim "
                    f"antecedents would be lost (saturation={saturation:.2f}). "
                    f"Compact unencumbered regions or surface budget exhaustion."
                )
            # Handle exists: rewrite is legal, but the handle must survive verbatim.
            if ob.correlation_id not in new_text:
                raise ObligationBoundaryViolation(
                    f"rewrite of region {region!r} dropped correlation handle "
                    f"{ob.correlation_id!r}; result could not be reconciled. "
                    f"Preserve the handle or block the rewrite."
                )

        self.regions[region] = new_text

    def reconcile(self, correlation_id: str, result: str) -> str:
        """A result must bind to verbatim antecedents or a resolvable handle, never a paraphrase."""
        ob = self.obligations.get(correlation_id)
        if ob is None:
            raise ObligationBoundaryViolation(
                f"result for {correlation_id!r} has no live obligation record; "
                f"refusing to reconcile against reconstructed arguments."
            )
        if ob.region not in self.regions:
            raise ObligationBoundaryViolation(
                f"antecedent region {ob.region!r} for {correlation_id!r} was evicted."
            )
        del self.obligations[correlation_id]
        return result
