# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-self-applied-context-patch-that-is-semantically-valid-but-structurally-fatal-to-downstream-reasoning.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-self-applied-context-patch-that-is-semantically-valid-but-structurally-fatal-to-downstream-reasoning.warrant.json
# Markdown SHA-256:   ab811fec934ca704f8651913665eb53fa52ef7649f30bf9aee0da357799fe094
# Code AST SHA-256:   6912e484cb427f08c86d21668a1d0a5a0eafc4add9371e42850a3371018c6852
# Verified Classes:   SilentRebindingError, Context
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class SilentRebindingError(RuntimeError):
    """Raised when a self-applied context patch changes what a reference
    resolves to without the patch itself rewriting that reference."""
    pass


@dataclass
class Context:
    # Ordered positional entities, e.g. plan steps. Index = position.
    steps: list[str] = field(default_factory=list)
    # Named entities, e.g. findings keyed by id.
    named: dict[str, str] = field(default_factory=dict)
    # Free-text buffer containing reference tokens like "step 7" or "F4".
    prose: str = ""


STEP_REF = re.compile(r"\bstep\s+(\d+)\b", re.IGNORECASE)
NAMED_REF = re.compile(r"\b([CF]\d+)\b")


def resolution_table(ctx: Context) -> dict[str, str]:
    """Map each reference token in prose to the entity text it currently binds to."""
    table: dict[str, str] = {}
    for m in STEP_REF.finditer(ctx.prose):
        idx = int(m.group(1)) - 1
        target = ctx.steps[idx] if 0 <= idx < len(ctx.steps) else "<dangling>"
        table[m.group(0).lower()] = target
    for m in NAMED_REF.finditer(ctx.prose):
        key = m.group(1)
        table[key] = ctx.named.get(key, "<dangling>")
    return table


def apply_patch_and_verify(
    ctx: Context,
    *,
    delete_step: int | None = None,
    set_named: tuple[str, str] | None = None,
    rewritten_refs: set[str] | None = None,
) -> Context:
    """Apply a self-edit, then verify no untouched reference silently rebound.

    rewritten_refs: reference tokens the patch author explicitly rewrote in prose.
    Any resolution change NOT covered by this set is a silent misbinding.
    """
    rewritten_refs = {r.lower() for r in (rewritten_refs or set())}
    before = resolution_table(ctx)

    # Build the post-patch context.
    new_steps = list(ctx.steps)
    new_named = dict(ctx.named)
    if delete_step is not None:
        del new_steps[delete_step - 1]  # positional shift: later steps move up
    if set_named is not None:
        new_named[set_named[0]] = set_named[1]
    after_ctx = Context(steps=new_steps, named=new_named, prose=ctx.prose)
    after = resolution_table(after_ctx)

    # Detect silent rebinding: token resolution changed, token not rewritten.
    fatal: list[str] = []
    for token, old_target in before.items():
        new_target = after.get(token, "<missing>")
        if new_target != old_target and token not in rewritten_refs:
            fatal.append(f"{token!r}: {old_target!r} -> {new_target!r}")

    if fatal:
        raise SilentRebindingError(
            "patch applied cleanly but silently rebound references it did not "
            "rewrite; refusing commit. Misbindings: " + "; ".join(fatal)
        )
    return after_ctx


# --- demonstration -----------------------------------------------------------
ctx = Context(
    steps=[
        "load fixture",
        "validate schema",
        "stage deploy",
        "monitor",
    ],
    named={"C1": "no-retry on fixture load", "F4": "schema mismatch observed"},
    prose="Per C1 we must not retry. Step 3 depends on step 2. F4 supports C1.",
)

# Agent decides step 2 is unnecessary and deletes it. Prose still says
# "step 3 depends on step 2" -- a positional reference now misbinds.
try:
    apply_patch_and_verify(ctx, delete_step=2, rewritten_refs=set())
except SilentRebindingError as e:
    print("BLOCKED:", e)

# Correct approach: rewrite the affected references in the same transaction.
ctx_ok = apply_patch_and_verify(
    ctx,
    delete_step=2,
    rewritten_refs={"step 3", "step 2"},  # author updated prose to match
)
print("COMMITTED, steps now:", ctx_ok.steps)
