# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-from-corrupting-in-place-workspace-mutations.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-from-corrupting-in-place-workspace-mutations.warrant.json
# Markdown SHA-256:   8726a737c9f811684bdfd082651d372033278b3b630f3663e37de67fec0ddd58
# Code AST SHA-256:   a3087c286533fbfdf2b51e7ed9d0197ab6b9af0dcb993c9474744487b6bb4352
# Verified Classes:   StaleMirrorError, WorkspaceMirror
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleMirrorError(RuntimeError):
    """Raised when an agent reasons over a workspace region whose
    context representation predates the last mutation touching it."""


class WorkspaceMirror:
    def __init__(self, revision: int = 0):
        self.revision = revision
        # region_id -> (text, revision_at_render)
        self.spans: dict[str, tuple[str, int]] = {}
        # region_id -> revision of last mutation that touched it
        self.last_mutation: dict[str, int] = {}

    def render(self, region_id: str, text: str) -> None:
        self.spans[region_id] = (text, self.revision)

    def apply_mutation(self, region_id: str, new_text: str) -> None:
        self.revision += 1
        self.last_mutation[region_id] = self.revision
        # Explicitly invalidate the mirror span; it is now stale until re-rendered.
        self.spans.pop(region_id, None)

    def read_for_reasoning(self, region_id: str) -> str:
        if region_id not in self.spans:
            raise StaleMirrorError(
                f"region {region_id!r} has no current mirror span; "
                f"last mutation at revision {self.last_mutation.get(region_id)} "
                f"but mirror revision is {self.revision}. Re-read before reasoning."
            )
        text, rendered_at = self.spans[region_id]
        last = self.last_mutation.get(region_id, -1)
        if rendered_at < last:
            raise StaleMirrorError(
                f"region {region_id!r} rendered at revision {rendered_at} "
                f"but mutated at revision {last}. Mirror is stale."
            )
        return text


def safe_edit_step(mirror: WorkspaceMirror, region_id: str, new_text: str) -> str:
    """Mutate a region, then immediately re-render it so the next
    reasoning step has an authoritative post-mutation span."""
    mirror.apply_mutation(region_id, new_text)
    # Tool result must be ingested as a fresh render at the new revision.
    mirror.render(region_id, new_text)
    # Prove the invariant holds before returning control to the planner.
    try:
        return mirror.read_for_reasoning(region_id)
    except StaleMirrorError as exc:
        raise StaleMirrorError(
            f"post-mutation render failed invariant for {region_id!r}: {exc}"
        ) from exc


def reason_over(mirror: WorkspaceMirror, region_id: str) -> str:
    """Any planner step that reads a region must pass through here."""
    try:
        return mirror.read_for_reasoning(region_id)
    except StaleMirrorError as exc:
        raise StaleMirrorError(
            f"refusing to reason over stale region {region_id!r}: {exc}"
        ) from exc
