Append-Only Agent Context: Engineering Practices for Configuration Changes

    Treating agent context as an append-only event log can improve cache stability, cost predictability, latency, auditability, and reproducibility. This article explains the risks of rewriting conversation history, shows append-based alternatives for configuration changes and tool outputs, and provides migration guidance for long-running agent workflows.

    1. Background: Context Is the Runtime Foundation of an Agent

    In multi-turn tasks, an agent relies on more than the latest user message. Its context may include system instructions, conversation history, tool results, and intermediate reasoning data. How this context is organized directly affects inference cost, response latency, and output stability.

    Many teams have developed context-pruning techniques to keep prompts concise. Common examples include assembling system instructions according to the current scenario, rewriting the beginning of the context based on retrieval results on every turn, trimming long tool logs after they have been recorded, replacing early conversation history with a summary, switching the structured-output schema as the task progresses, and adding or removing tools based on permissions.

    The common characteristic of these techniques is that they modify history that has already been written.

    2. The Hidden Costs of Rewriting History

    Rewriting history may seem reasonable because it saves tokens and keeps the context compact. However, inference platforms with prefix caching typically match cached content by prefix. If content changes at a given position, cached content after that position may become invalid.

    This creates three types of cost:

    1. Higher cost: Cache misses cause input tokens to be processed and billed at the standard rate. Recomputing a long context repeatedly can make expenses accumulate.
    2. Higher latency: The model must process all content after the modified position again.
    3. Output variability: Some platforms preserve intermediate inference state across turns. When history changes, that state may be discarded, forcing the model to reason through the task again and potentially produce a different conclusion.

    The exact changes that invalidate a cache depend on the platform’s rules. Developers should follow the relevant official documentation and validate the behavior using actual usage and latency measurements from their requests.

    3. The Core Principle: Append to Context Only

    A safer design is to treat context as an append-only event log. The rules are straightforward:

    • Never modify messages that have already been written.
    • When behavior needs to change, append a new configuration or instruction message.
    • When content needs to be reduced, truncate it before it is first written instead of replacing it later.

    This approach has three main benefits. The prefix remains stable, which can improve cache hit rates. The history remains traceable for auditing. During debugging, each turn’s input can be reproduced completely.

    4. Append-Based Alternatives for Common Changes

    The following examples show how to handle common configuration changes without rewriting existing history.

    1. Adjusting reasoning intensity or output format: Instead of modifying request-level parameters, append a configuration-change record and specify the turn from which it takes effect.
    2. Switching the output schema between task stages: Append a stage-transition record. The server or adapter can apply the new schema from that record onward.
    3. Dynamically adding or removing tools: Declare newly available tools through appended records, or restrict the tools callable in the current request. Keep historical tool definitions unchanged.
    4. Changing the initial system instructions: Append a new instruction at the end to override or supplement the earlier agreement.
    5. Truncating old tool output: Perform truncation before the tool result is first written to the log. Do not rewrite it afterward.

    5. Fixed Instructions and the Cache Prefix

    Fixed system instructions should appear at the beginning of the input so they become part of the cache prefix. If a platform accepts instructions in a separate field and treats that field differently for billing or caching, verify whether it actually participates in prefix caching.

    A robust approach is to place long-lived instructions in the first message and compare cache-hit metrics before and after the migration in a test environment.

    The following example uses config_update as a custom event type. Before sending the request, an adapter must convert this event into the format required by the target platform:

    1. class ConversationLog:
    2. def __init__(self, base_instructions: str):
    3. # The first message contains fixed instructions; all later entries are appended.
    4. self.events = [{"role": "system", "content": base_instructions}]
    5. def append_message(self, role: str, content: str):
    6. self.events.append({"role": role, "content": content})
    7. def append_config_update(self, changes: dict):
    8. # Store configuration changes as new records instead of modifying earlier parameters.
    9. self.events.append({"type": "config_update", "changes": changes})
    10. def snapshot(self) -> list:
    11. # Return a copy so external code cannot modify the internal log.
    12. return list(self.events)

    6. Truncating Tool Output Early

    Tool responses often contain lengthy logs, while only a small portion is useful to the model. The recommended approach is to truncate the result before adding it to the log. Preserve enough location information to indicate that some content was omitted.

    1. MAX_TOOL_CHARS = 4000 # Example threshold; adjust it for the task.
    2. def ingest_tool_result(log: ConversationLog, tool_name: str, raw: str):
    3. if len(raw) <= MAX_TOOL_CHARS:
    4. text = raw
    5. else:
    6. half = MAX_TOOL_CHARS // 2
    7. head = raw[:half]
    8. tail = raw[-half:]
    9. omitted = len(raw) - 2 * half
    10. text = f"{head}\n...[{omitted} characters omitted]...\n{tail}"
    11. log.append_message("tool", f"[{tool_name}] {text}")

    This ensures that the log remains unchanged after the result is written. Regardless of how later requests are assembled, the same tool result appears in the prefix as the same text.

    7. Summaries and Long Conversations

    Long conversations do sometimes need to be compressed. An append-only approach keeps the original history unchanged and appends a summary record. When assembling a request, the adapter can decide which content to send—for example, only the portion after the summary.

    The original records remain available for auditing, while the model input can still be controlled.

    Keep in mind that replacing a prefix with a summary can also invalidate the cache. Compression should therefore be performed at a small number of deliberate checkpoints rather than on every turn. These checkpoints can be determined by context-length thresholds or task stages.

    8. Migration Checklist

    1. Identify every code path that modifies history, including system-instruction rewrites, tool-output cleanup, summary replacement, and model or user-identity switching.
    2. Design an append-based alternative for each type of modification and specify the turn from which it takes effect.
    3. Move fixed instructions to the beginning of the input and verify that they are included in the cache prefix.
    4. In a test environment, compare token usage, latency, and cache hit rates before and after the migration.
    5. Evaluate output quality, especially for multi-turn reasoning tasks, and check for conclusion drift caused by changes to historical context.
    6. When switching models or tenants, assess whether a new session should be started instead of modifying the existing history.

    9. Conclusion

    The focus of agent context management is shifting from “how to minimize history” to “how to append changes while keeping the prefix stable.” Rewriting history may appear to save space, but it can also increase cost and latency while introducing uncertainty.

    Moving configuration changes and truncation decisions earlier in the workflow, then allowing context to grow only at the end, is a more predictable engineering strategy.