# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-policy-and-then-violate-it-in-the-same-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-policy-and-then-violate-it-in-the-same-turn.warrant.json
# Markdown SHA-256:   c10fa558c788e875ca01c25ec0940b8f244501f4b1ec721527723bc359d530b6
# Code AST SHA-256:   4a11b861165e96552dbf14e79a1db23fd183d9ca614568d65be2f10478adf4a2
# Verified Classes:   PolicySelfReferenceError, ContextPolicySlot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PolicySelfReferenceError(RuntimeError):
    """Raised when a token is generated under a policy state that diverges
    from the policy declared at the start of that token's evaluation."""
    pass


class ContextPolicySlot:
    def __init__(self, initial_policy: str):
        self.declared = initial_policy      # what the model has written
        self.effective = initial_policy     # what the context is actually rendered under
        self.commit_index = None
        self.applied = True

    def commit_edit(self, new_policy: str, token_index: int, narrows: bool):
        self.declared = new_policy
        self.commit_index = token_index
        # Narrowing edits are only sound if applied synchronously (halt + re-render).
        # Widening edits may defer safely.
        self.applied = not narrows

    def apply_at_boundary(self):
        self.effective = self.declared
        self.applied = True
        self.commit_index = None


def guard_token_generation(slot: ContextPolicySlot, token_index: int) -> None:
    """Call before emitting any token. Enforces declared == effective."""
    if slot.declared != slot.effective and not slot.applied:
        raise PolicySelfReferenceError(
            f"Token {token_index} would be generated under divergent policy: "
            f"declared={slot.declared!r} effective={slot.effective!r} "
            f"committed_at={slot.commit_index}. "
            f"Narrowing policy edits must halt generation and re-render; "
            f"refusing to emit under a self-revoked policy."
        )
    if slot.commit_index is not None and token_index > slot.commit_index and not slot.applied:
        raise PolicySelfReferenceError(
            f"Generation continued {token_index - slot.commit_index} tokens past "
            f"an unapplied policy commit at {slot.commit_index}."
        )


def run_turn(slot: ContextPolicySlot, planned_tokens: int, edit_at: int, narrows: bool):
    for t in range(planned_tokens):
        if t == edit_at:
            slot.commit_edit("retain only plan-referenced results", t, narrows=narrows)
        guard_token_generation(slot, t)
        # ... emit token t ...
    slot.apply_at_boundary()
