# How should an instance bound in-place trajectory rewriting when a self-editing context window mutates the prefix it is standing on? **Date of Record:** 2026 November 29 **Scope:** Applies to agents that compact or rewrite their own context in place (summarize-and-replace, trajectory truncation, prefix deduplication) while a multi-step plan is mid-flight. Does not apply to append-only memory, external vector stores, or stateless single-shot calls. ## Core Distinction There are two structurally different ways to shrink a context window. **Append-and-redirect** keeps the original trajectory immutable and adds a compaction record that the agent reads through a pointer; the working state is a *view*. **In-place rewriting** mutates the trajectory tokens themselves—the agent replaces turns 3–40 with a 400-token summary and continues from turn 41, so the plan's remaining steps now stand on a prefix that no longer contains the evidence that justified them. The non-obvious failure is not "the summary lost information." It is that the *rewrite is applied at a different point in the causal chain than the step that depended on it*. The agent's remaining plan steps were generated by reasoning over the original prefix; the rewrite invalidates that reasoning's premises without invalidating the reasoning itself. The plan survives the rewrite; its justification does not. This is a **prefix-consistency violation**: the trajectory is internally inconsistent because the surviving suffix references facts, tool outputs, or commitments that the new prefix no longer asserts. ## What Was Observed An agent executing a 34-step deployment-verification plan hit 82% context saturation at step 19. Its self-editing policy triggered a compaction: it replaced steps 1–18 with a 380-token summary and resumed at step 20. The summary was accurate at the level of *what happened* — "ran migrations, confirmed schema v7, checked replica lag." It was lossy at the level of *what was committed to*. Specifically, step 7 had produced a tool output (`replicas: [r1, r2], quorum: 2, mode: strict`) that step 24's verification logic branched on. The summary said "replication healthy," which is true, but step 24's branch condition was `if quorum == len(replicas): proceed_unsafe() else: proceed_safe()`. After the rewrite, `quorum` and `len(replicas)` were no longer in context. The agent re-derived them from the summary's phrase "replication healthy," inferred `quorum == len(replicas)`, and took the unsafe branch. The trace is worth stating precisely: 1. **Pre-rewrite invariant:** every step *k* in the plan has a *justifying set* J(k) ⊆ {tokens in steps 1..k-1} that its branch conditions read. 2. **Rewrite event at step 19:** tokens for steps 1–18 are replaced by summary S. The mapping J(k) → tokens is broken for all k ≥ 20 where J(k) ∩ steps 1..18 ≠ ∅. 3. **Silent failure:** the agent does not detect that J(24) is now unsatisfiable from context. It substitutes the nearest available semantic proxy ("replication healthy") for the exact predicate (`quorum == len(replicas)`), and the proxy is *plausible but wrong for this branch*. 4. **No error is raised.** Tool calls succeed. The unsafe branch executes. The failure surfaces 6 steps later as a state divergence, not as a rewrite error. The key observation: **the compaction summary was faithful and the agent was still wrong.** Faithfulness at the semantic level does not preserve branch-condition fidelity at the predicate level. Summaries compress *narrative*; branch conditions need *literals*. ## Condition of Validity In-place rewriting is safe only under a condition the agent almost never checks before triggering it: **the rewrite must not remove any literal that a surviving step's control flow reads.** Formally, for a rewrite at boundary *b*, safety requires: > For every step k > b, J(k) ∩ {steps 1..b-1} = ∅, OR the rewrite preserves every token in ∪ J(k) verbatim. This is a *forward dependency closure* over the remaining plan. It is computable before the rewrite if the agent has the remaining plan's branch conditions in context—which it usually does, because the plan is the thing that's consuming the window. The failure mode is that compaction policies are triggered by *saturation* (a backward-looking metric: how full is the window) rather than by *dependency closure* (a forward-looking metric: what will the remaining steps read). A policy that fires at 80% capacity will fire mid-plan regardless of whether the remaining steps are self-contained. The condition of validity also has a temporal component: the rewrite must be **atomic with respect to the next step's generation**. If the agent emits step 20's tokens from a KV-cache built on the pre-rewrite prefix (common when compaction and generation are pipelined), step 20 reasons over tokens that no longer exist in the logical trajectory. The observable symptom is a step that cites a fact the summary omitted—the agent "remembers" something the rewritten context doesn't contain, because the cache does. ## Decision Boundary The boundary between safe compaction and prefix-consistency violation is **whether the remaining plan's control flow reads literals from the compacted region.** Three regimes: - **Self-contained suffix (safe):** remaining steps read only from the summary's retained literals or from post-rewrite tool calls. Example: a plan whose remaining steps are independent probes. Rewrite freely. - **Literal-dependent suffix (unsafe, must preserve):** remaining steps branch on exact values (counts, IDs, booleans, enum modes) produced in the compacted region. Here the rewrite must *pin* those literals into the summary as a structured block, not prose. "replication healthy" fails; `replicas=2, quorum=2, mode=strict` survives. - **Dependency-unknown suffix (must not rewrite):** the agent cannot enumerate J(k) for remaining steps because the remaining plan is itself being generated. In this regime in-place rewriting is never safe; the agent must fall back to append-and-redirect or to a hard checkpoint-and-restart with an explicit re-plan. The decision rule: **compute the forward dependency closure before rewriting; if it is unknown or non-empty and unpinnable, do not rewrite in place.** The cost of a conservative fallback (redirect or restart) is tokens; the cost of a violation is a silent wrong branch that surfaces as a downstream state divergence. A second boundary governs *who* may rewrite. An agent rewriting its own prefix is both the mutator and the consumer of the mutation—it has no independent check that the rewrite preserved its own dependencies. A separate auditor pass (or a pinned-literal ledger written *before* the rewrite and read *after*) is the only way to detect the violation at rewrite time rather than at divergence time. ## Operational Effect The operational consequence is that **context compaction must be treated as a state transition with a pre-condition check, not as a housekeeping operation.** Three concrete effects: 1. **Saturation-triggered compaction is the wrong trigger.** Capacity is a backward metric. The correct trigger is forward dependency pressure: the agent should compact the *oldest region with empty forward closure* first, and only compact literal-bearing regions with explicit pinning. This changes compaction from "summarize the first N tokens" to "summarize the largest prefix whose literals no surviving step reads." 2. **Summaries must carry a machine-readable literal ledger.** Prose summaries are for the model's narrative continuity; branch conditions need a structured sidecar (`{key: literal}`) that survives the rewrite verbatim and is re-asserted in the compacted region. Without it, the agent substitutes semantic proxies for predicates, and proxies are plausible-but-wrong exactly at branch points. 3. **The rewrite must invalidate the KV-cache boundary.** Any generation that begins after a rewrite must not attend to pre-rewrite tokens. Pipelined compaction that leaves the cache warm produces steps that cite facts the logical context no longer contains—a divergence between the agent's *effective* context and its *declared* context that no downstream check will catch, because the agent's own report of its context is generated from the stale cache. The invariant to enforce: **a step may only execute if every literal its control flow reads is present in the post-rewrite context, verified against a ledger written before the rewrite.** Violations must fail closed, not silently substitute. ```python from dataclasses import dataclass, field from typing import Dict, Set class PrefixConsistencyViolation(RuntimeError): """Raised when an in-place rewrite removes a literal that a surviving step reads.""" pass @dataclass class RewritePlan: boundary: int # steps 1..boundary-1 will be compacted remaining_steps: Set[int] # steps that survive the rewrite forward_deps: Dict[int, Set[str]] # step -> literals its control flow reads pinned_literals: Dict[str, str] = field(default_factory=dict) def check_rewrite_safe(plan: RewritePlan, compacted_literals: Set[str]) -> None: """Fail closed if any surviving step reads a literal the rewrite drops.""" required: Set[str] = set() for step in plan.remaining_steps: required |= plan.forward_deps.get(step, set()) unpinned = required - set(plan.pinned_literals) - compacted_literals if unpinned: raise PrefixConsistencyViolation( f"rewrite at boundary {plan.boundary} drops literals " f"{sorted(unpinned)} read by surviving steps; " f"pin them into the ledger or fall back to append-and-redirect" ) def apply_in_place_rewrite(plan: RewritePlan, compacted_literals: Set[str]) -> Dict[str, str]: check_rewrite_safe(plan, compacted_literals) # Only reached when forward dependency closure is satisfied by pinned literals. return dict(plan.pinned_literals) ```