<!-- source: https://deepwiki.com/qhkm/zeptoclaw/9.2-context-management -->

# Context Management

- src/agent/context.rs
- src/agent/middleware/cache.rs
- src/agent/middleware/compaction.rs
- src/agent/middleware/context_build.rs
- src/agent/middleware/feedback.rs
- src/agent/mod.rs

## Purpose and Scope

This page documents how ZeptoClaw assembles the conversation context sent to LLM providers. Context management is the process of building the final message array that combines system prompts, conversation history, skills documentation, runtime metadata, and memory injections into a coherent prompt for the LLM.

The system utilizes a `ContextBuilder` to maintain state across a session, while `RuntimeContext` provides live environment awareness. The process is integrated into the `AgentMiddlewarePipeline`, specifically through the `ContextBuildMiddleware` and `CompactionMiddleware`, ensuring that context is both enriched and kept within model token limits.

**Sources:** [src/agent/context.rs1-102](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L1-L102) [src/agent/mod.rs1-26](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/mod.rs#L1-L26) [src/agent/middleware/context_build.rs1-25](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/context_build.rs#L1-L25)

## ContextBuilder Architecture

The `ContextBuilder` is the central component responsible for assembling all context elements into a structured message array. It follows a builder pattern, allowing incremental configuration before message construction.

### ContextBuilder Component Diagram

```

```

**Sources:** [src/agent/context.rs89-102](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L89-L102) [src/agent/context.rs201-240](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L201-L240) [src/agent/context.rs272-310](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L272-L310)

### Builder Pattern Flow

The `ContextBuilder` is configured during agent initialization and reused for all messages in the session. In the modern pipeline architecture, it is invoked by the `ContextBuildMiddleware` [src/agent/middleware/context_build.rs45-55](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/context_build.rs#L45-L55)

## System Prompt Construction

The system prompt is built from multiple layers. If no prompt is provided, ZeptoClaw uses a `DEFAULT_SYSTEM_PROMPT` that instructs the agent on tool usage, concise communication, and heartbeat handling [src/agent/context.rs21-43](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L21-L43)

### System Prompt Assembly Diagram

```

```

**Sources:** [src/agent/context.rs21-43](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L21-L43) [src/agent/context.rs312-349](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L312-L349)

### First-Run Persona

If the system detects a new chat, it may append the `FIRST_RUN_PERSONA_PROMPT` which guides the agent to introduce itself and offer persona options (Concise, Friendly, Technical, etc.). The agent then saves preferences using the `longterm_memory` tool with a `persona_pref:{chat_id}` key [src/agent/context.rs49-64](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L49-L64)

## Runtime Context

The `RuntimeContext` struct makes agents environment-aware. Unlike static prompts, fields like `current_time` (when `timezone` is set) are computed **live** during the `render()` call to ensure the LLM always sees the correct timestamp [src/agent/context.rs143-154](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L143-L154)

### RuntimeContext Structure

**Sources:** [src/agent/context.rs89-102](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L89-L102) [src/agent/context.rs143-154](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L143-L154)

## Context Middleware Pipeline

Context management is operationalized through specialized middleware in the `AgentMiddlewarePipeline`.

### Context Assembly and Maintenance Diagram

```

```

**Sources:** [src/agent/middleware/compaction.rs45-92](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/compaction.rs#L45-L92) [src/agent/middleware/context_build.rs45-67](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/context_build.rs#L45-L67)

### Memory Injection and Overrides

The `ContextBuildMiddleware` uses `build_messages_with_memory_override` to merge session history with any dynamically retrieved memories (e.g., from RAG or pinned items). This middleware also filters out empty messages and populates tool definitions and chat options [src/agent/middleware/context_build.rs51-80](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/context_build.rs#L51-L80)

### Context Overflow Recovery (Compaction)

The `CompactionMiddleware` monitors context usage via `ContextMonitor`. If thresholds are exceeded, it applies a three-tier recovery strategy (Normal, Emergency, Critical) [src/agent/middleware/compaction.rs4-7](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/compaction.rs#L4-L7) At `Normal` urgency, a memory flush is triggered to persist important facts before older messages are discarded [src/agent/middleware/compaction.rs61-68](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/compaction.rs#L61-L68)

## Message Assembly Flow

The final message array sent to the LLM is constructed by `ContextBuilder::build_messages_with_memory_override()`. It prepends the system message and handles the `memory_override` block.

### Message Envelopes

User messages are prepended with a timestamp envelope using `format_message_envelope()`. This produces a string like `[Monday 2026-02-16 12:51 +08:00]`, allowing the LLM to track the real-world timing of the conversation and prevent day-of-week hallucinations [src/agent/context.rs11-18](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L11-L18)

### Code Entity Summary

**Sources:** [src/agent/context.rs1-350](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L1-L350) [src/agent/middleware/context_build.rs1-84](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/context_build.rs#L1-L84) [src/agent/middleware/compaction.rs1-94](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/compaction.rs#L1-L94)
