# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-anchor-rewrite-invalidation-when-it-self-edits-its-own-in-flight-prompt.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-anchor-rewrite-invalidation-when-it-self-edits-its-own-in-flight-prompt.warrant.json
# Markdown SHA-256:   270209c60e44ee6173604a349dccb46f89a7c64593589e0ffc4e9a471cda2e16
# Code AST SHA-256:   f58ff5729e2e8e7c730175a3168f3df6dad7dccbf34c0d6b9990b2be73bfbef0
# Verified Classes:   AnchorRewriteInvalidation, Anchor, PlanStep, ContextState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class AnchorRewriteInvalidation(RuntimeError):
    """Raised when an in-flight plan's anchor no longer resolves after a context rewrite."""


@dataclass
class Anchor:
    symbol: str          # stable, resolvable identifier, e.g. "cfg_v2" or "file:src/loader.py:42"
    derived: bool        # True if this anchor lives only in a summary/re-anchor artifact


@dataclass
class PlanStep:
    description: str
    anchor: Anchor
    status: str = "open"  # open | done | stale


@dataclass
class ContextState:
    version: int
    transcript: str
    open_anchors: Dict[str, str] = field(default_factory=dict)  # symbol -> resolved referent
    plan: List[PlanStep] = field(default_factory=list)


def rewrite_context(state: ContextState, new_transcript: str,
                    new_anchor_map: Dict[str, str]) -> ContextState:
    """Atomically commit a rewrite. Must be called as a single transition."""
    # Precondition: every open anchor must be reproduced byte-identically.
    for symbol in state.open_anchors:
        if symbol not in new_anchor_map:
            # Anchor was paraphrased or dropped by the rewrite.
            for step in state.plan:
                if step.status == "open" and step.anchor.symbol == symbol:
                    step.status = "stale"
            raise AnchorRewriteInvalidation(
                f"rewrite dropped open anchor {symbol!r}; in-flight plan marked stale, "
                f"re-plan from post-rewrite state required"
            )
        if new_anchor_map[symbol] != state.open_anchors[symbol]:
            raise AnchorRewriteInvalidation(
                f"anchor {symbol!r} re-resolved from {state.open_anchors[symbol]!r} "
                f"to {new_anchor_map[symbol]!r}; referent changed, plan invalid"
            )
    return ContextState(
        version=state.version + 1,
        transcript=new_transcript,
        open_anchors=new_anchor_map,
        plan=state.plan,
    )


def assert_plan_valid(state: ContextState) -> None:
    for step in state.plan:
        if step.status == "open" and step.anchor.derived:
            raise AnchorRewriteInvalidation(
                f"open step {step.description!r} depends on derived artifact "
                f"{step.anchor.symbol!r}; must re-verify against world state before execute"
            )
