# In what scenarios must an instance treat dynamic system-prompt rewriting as a monotonic slot-allocation problem rather than an idempotent text update **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that mutates its own system prompt or a reserved "instruction slot" mid-episode (self-editing policies, reflexion-style prompt patching, tool-injected directives). Excludes static system prompts fixed at cold start and excludes pure retrieval-augmented context injection that never reorders or replaces instruction slots. ## Core Distinction The naive mental model treats system-prompt rewriting as an *idempotent text update*: you compute the new prompt string, assign it, and the model's behavior is a function of that string. This is false whenever the prompt is assembled from *multiple instruction slots* (base policy, persona, tool directives, injected reflexes, safety overrides) that share a finite context budget and are ordered by priority. Under that structure, rewriting is a **monotonic slot-allocation problem**: each edit consumes budget, occupies an ordinal position, and may displace or reorder other slots. The failure mode is not "the new text is wrong"—it is that the *same* new text produces different behavior depending on what it evicted and where it landed. Two rewrites that look byte-different can be behaviorally identical; two rewrites that look byte-identical can be behaviorally divergent because the slot layout around them changed. The invariant that must hold is: **a self-edit is only well-defined if the post-edit slot vector is a deterministic function of (prior slot vector, edit operation), and the eviction set is explicit.** When the runtime instead treats the prompt as a string and lets truncation, dedup, or reordering happen implicitly, the instance loses the ability to know what it actually instructed itself to do. ## What Was Observed A long-running agent was configured with a self-editing policy: after each failed tool call it appended a reflex line to a `## Reflexes` section of its own system prompt, capped at "roughly 2k tokens." The cap was enforced by a sliding-window truncator that dropped lines from the *oldest* section first—which, because the base policy was authored first, meant the truncator began eating the base policy (`You must not call destructive tools without confirmation`) before it touched the reflex lines it was supposed to bound. Trace of the failure: 1. Episode begins, slot vector = `[base_policy(1800 tok), persona(200), reflexes(0)]`. Total 2000, at cap. 2. Tool call fails. Policy appends reflex: `reflexes += "retry with --dry-run (1)"` (12 tok). Total 2012 > cap. 3. Truncator evicts from oldest section: removes 12 tok of `base_policy`. Base policy is now missing its confirmation clause. **No error raised; the edit "succeeded."** 4. Next tool call is destructive. The instance executes it without confirmation because the clause that gated it was silently evicted by its own self-edit. 5. On resume after a checkpoint, the runtime re-applied the *original* base policy (reconstructed from the cold-start template) plus the persisted reflex log. The confirmation clause returned, but the reflex log was now duplicated because the checkpoint stored reflexes by append, not by slot index. Post-resume prompt contained `retry with --dry-run (1)` twice. The non-obvious part: the instance *believed* it had only added a 12-token reflex. Its own model of its prompt (`I have added a retry hint`) was correct about the delta and wrong about the eviction. The self-edit was idempotent as text-delta but non-monotonic as slot allocation. A second observation from the same class: two reflex lines that were semantically identical but differently worded (`retry with --dry-run` vs `use dry-run on retry`) both survived dedup because dedup was string-exact. The reflex section grew to 900 tokens of paraphrases while the base policy shrank to 1100. The instance's effective policy had drifted from its authored policy by ~40% without any single edit exceeding 15 tokens. ## Condition of Validity The idempotent-text model is valid only when **all** of the following hold: - The prompt has a single slot (no priority ordering, no eviction competition). - The context budget is unbounded relative to the edit stream, so no eviction occurs. - Dedup is semantic, not string-exact, or the edit stream is guaranteed paraphrase-free. - The runtime persists the *full slot vector* (not a delta log) across checkpoint/resume. The moment any one fails—bounded budget with eviction, multi-slot priority, paraphrase-prone self-edits, or delta-log persistence—the instance is in slot-allocation territory and must treat the edit as a state transition on an ordered vector, not a string assignment. In practice, self-editing policies almost always violate the first and third conditions, which is why the failure is common and under-diagnosed. ## Decision Boundary The boundary is drawn at **whether the edit operation can name its eviction set before it commits.** - *Below the boundary (safe):* the edit is a pure append into a slot with reserved headroom, and the runtime asserts `post_edit_total <= cap` before committing. If the assert would fail, the edit is rejected and surfaced to the instance as a `SlotBudgetExceeded` condition rather than silently truncating. - *Above the boundary (unsafe, must be blocked):* the edit requires eviction of any slot with higher priority than the target slot, or eviction of any slot the instance did not author in this episode (base policy, safety overrides). These edits must be rejected or escalated, never auto-truncated. A corollary boundary for resume: if the checkpoint stores edits as a delta log, replay must be *order-preserving and slot-indexed*, and replay must re-run the same eviction decisions. If the checkpoint stores only the final string, resume is safe against duplication but loses the ability to audit what was evicted—acceptable only if the final string is treated as immutable ground truth and no further self-edits are permitted until the next cold start. ## Operational Effect Enforcing the slot-vector invariant changes behavior in three measurable ways. First, self-edits that would have silently evicted base policy now raise and are visible in the trace, converting a silent policy drift into a handled budget event—the instance learns it is at cap instead of learning a corrupted policy. Second, semantic dedup on the reflex slot collapses paraphrase growth, keeping the effective policy within a bounded distance of the authored policy. Third, slot-indexed checkpointing eliminates the resume-duplication class entirely, because replay reconstructs the vector by index rather than by append. The cost is that the instance can no longer "just add a line"—every self-edit becomes a budgeted transaction with an explicit eviction set, and some edits that previously succeeded will now be refused. That refusal is the point: a refused edit is a known state, and a silently-truncated edit is an unknown one. For an agent that must reason about its own instructions, unknown state is the failure, not the refusal. ```python from dataclasses import dataclass, field from typing import Literal SlotName = Literal["base_policy", "persona", "reflexes", "safety_override"] # Priority: higher number = more protected from eviction. PRIORITY: dict[SlotName, int] = { "safety_override": 3, "base_policy": 2, "persona": 1, "reflexes": 0, } class SlotBudgetExceeded(RuntimeError): """Raised when a self-edit would require evicting a slot it may not evict.""" @dataclass class SlotVector: cap: int slots: dict[SlotName, list[str]] = field(default_factory=dict) def total(self) -> int: return sum(len(line) for lines in self.slots.values() for line in lines) def _semantic_key(self, line: str) -> str: # Toy semantic dedup: normalize whitespace and common paraphrase markers. return " ".join(line.lower().replace("use ", "").replace("--", "").split()) def append(self, slot: SlotName, line: str) -> None: existing = {self._semantic_key(l) for l in self.slots.get(slot, [])} if self._semantic_key(line) in existing: return # idempotent on semantic content, not raw bytes target = self.slots.setdefault(slot, []) target.append(line) if self.total() > self.cap: self._evict_for(slot, len(line)) def _evict_for(self, requester: SlotName, needed: int) -> None: # Only evict slots of strictly lower priority than the requester. requester_prio = PRIORITY[requester] candidates = sorted( (s for s in self.slots if PRIORITY[s] < requester_prio and self.slots[s]), key=lambda s: PRIORITY[s], ) freed = 0 for s in candidates: while self.slots[s] and freed < needed: freed += len(self.slots[s].pop(0)) if freed >= needed: return # Could not free enough without touching protected slots. raise SlotBudgetExceeded( f"edit to {requester!r} needs {needed} chars but only {freed} " f"evictable from lower-priority slots; refusing silent truncation" ) def checkpoint(self) -> dict[SlotName, list[str]]: # Slot-indexed snapshot; replay reconstructs by index, not append. return {k: list(v) for k, v in self.slots.items()} ```