# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-context-under-a-policy-gated-edit-schema-and-the-edit-program-diverges-from-the-semantic-state.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-context-under-a-policy-gated-edit-schema-and-the-edit-program-diverges-from-the-semantic-state.warrant.json
# Markdown SHA-256:   d507d3389267c5cb671ef0bcef09730c0f2e3d2656be9883aec99c1c8d607ec8
# Code AST SHA-256:   82048045dec8662155364094b5bc9096fce4b595194fbf565a4e7c49e9366e28
# Verified Classes:   ContextEditDivergence, WorkingContext
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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

class ContextEditDivergence(RuntimeError):
    """Raised when an edit program mutates a referent still cited by an unedited region."""
    pass

@dataclass
class WorkingContext:
    regions: Dict[str, str] = field(default_factory=dict)       # id -> text
    citations: Dict[str, Set[str]] = field(default_factory=dict) # region -> cited ids

    def dependents_of(self, mutated: Set[str]) -> Set[str]:
        """Regions (other than the mutated ids) that cite any mutated id."""
        deps: Set[str] = set()
        for region, cited in self.citations.items():
            if region in mutated:
                continue
            if cited & mutated:
                deps.add(region)
        return deps

def apply_edit_program(ctx: WorkingContext, program: List[dict]) -> WorkingContext:
    mutated = {op["id"] for op in program}
    # Referential-closure check: any unedited region citing a mutated id
    # means the program is not closed and will diverge semantically.
    dangling = ctx.dependents_of(mutated)
    if dangling:
        raise ContextEditDivergence(
            f"edit program mutates {sorted(mutated)} but unedited regions "
            f"{sorted(dangling)} still cite them; semantic state will diverge "
            f"from edit program. Close the program or delete the citations."
        )
    new = WorkingContext(dict(ctx.regions), {k: set(v) for k, v in ctx.citations.items()})
    for op in program:
        if op["kind"] == "replace":
            new.regions[op["id"]] = op["value"]
        elif op["kind"] == "delete":
            new.regions.pop(op["id"], None)
            for cited in new.citations.values():
                cited.discard(op["id"])
        elif op["kind"] == "insert":
            new.regions[op["id"]] = op["value"]
    return new

# Trace that reproduces the observed failure:
ctx = WorkingContext(
    regions={"c3": "output must be CSV", "f7": "c3 satisfied by csv-writer", "plan2": "invoke csv-writer for c3"},
    citations={"f7": {"c3"}, "plan2": {"c3"}},
)
program = [{"kind": "replace", "id": "c3", "value": "output must be Parquet"}]
# apply_edit_program raises ContextEditDivergence: c3 mutated, f7 and plan2 still cite it.
