How Context Compaction Manages Long Conversations in DeepSeek-Reasonix

Context compaction in DeepSeek-Reasonix preserves conversation continuity by replacing the middle portion of long chat histories with a structured LLM-generated summary, keeping only the system prompt, the summary itself, and the most recent exchanges while archiving the full original messages.

The DeepSeek-Reasonix repository implements an intelligent context window management system designed to handle extended reasoning sessions without hitting token limits. When conversations grow beyond configured boundaries, the Agent initiates a compaction pass that compresses historical context while preserving essential reasoning state. This mechanism ensures that critical information survives the fold while maintaining the model's ability to continue coherent multi-turn dialogue.

What Triggers Context Compaction?

The compaction system monitors token accumulation in real-time and activates when specific thresholds are met.

Automatic and Manual Triggers

Compaction can fire under two conditions defined in the control logic. Automatic compaction triggers when accumulated prompt tokens approach the compact-ratio (default 0.8 of the total window size), with trigger type set to "auto". Alternatively, users can invoke manual compaction at any time by issuing the /compact command (optionally with a focus parameter), which sets trigger type to "manual". According to the controller implementation in /internal/control/controller.go, the slash command handler forwards these requests directly to the agent's compaction engine.

The Compact-Ratio Threshold

The default threshold of 0.8 provides a safety buffer before hitting the absolute context limit. This configurable ratio ensures that summarization happens proactively rather than reactively, preventing context overflow that would truncate recent messages.

How the Folding Process Works

When compaction initiates, the system executes a multi-stage pipeline defined in /internal/agent/compact.go that processes conversation segments systematically.

Identifying Head, Mid, and Tail Regions

The compaction algorithm partitions the conversation into three distinct regions:

  • Head: The immutable system prompt that remains at the very top of the context
  • Mid: The foldable middle section containing older turns that will be summarized
  • Tail: The recent exchanges preserved verbatim for immediate context

The Summarization System Prompt

The mid region undergoes LLM summarization using a fixed summarySystemPrompt that instructs the model to produce a structured briefing. As implemented in /internal/agent/compact.go#L48-L79, the summary must include specific headings:

  • Standing facts & constraints
  • Goal
  • Decisions & rationale
  • Files & code
  • Commands & outcomes
  • Errors & fixes
  • Pending & next step

The resulting text is wrapped in special XML tags: <compaction-summary> … </compaction-summary>. These tags, defined at lines 40-42 of the same file, enable the front-end to recognize and render the summary appropriately in the TUI.

Archive and Removal of Original Messages

Once summarization completes, the original messages from the folded mid region are not immediately discarded. Instead, they are archived to a JSONL file in the session's configured archive directory. The Compaction event struct defined in /internal/event/event.go#L71-L81 stores the archive path in its Archive field (e.g., "/tmp/arch/20260531.jsonl"). Only after successful archival are the messages removed from the in-memory session, ensuring no data loss occurs during the fold.

What Survives a Fold?

After compaction completes, exactly three components remain in the active context window:

  1. System Prompt: The immutable prefix defining agent behavior and constraints
  2. Compaction Summary: The LLM-generated briefing wrapped in compaction tags, treated as user-role content for all subsequent turns
  3. Recent Tail: The last N user/assistant turns preserved verbatim, configurable via RecentKeep (default ≥2)

This tripartite structure ensures that the model retains both high-level reasoning context from the summary and immediate conversational context from recent turns. The summary becomes part of the prompt for every subsequent generation, while the detailed historical messages are no longer transmitted to the model.

TUI Rendering of Compacted Context

The terminal user interface renders the compaction event as a titled card. In /internal/cli/chat_tui.go#L24-L40, the compactionCardLines function generates the display output, showing:

  • A header indicating the compaction event
  • Gutter-prefixed summary lines from the <compaction-summary> content
  • An optional "archived …" line referencing the archive file path

Users can inspect this card to verify what information survived the fold before continuing the conversation.

Implementation Details and Code Examples

Triggering Manual Compaction

When a user types /compact during an active session, the controller invokes:

// Inside controller.go - slash command handling
err := ctrl.Compact(context.Background(), focus) // trigger = "manual"
if err != nil {
    // Handle error - typically shows "compaction failed" notice
}

The focus parameter allows users to specify particular topics or regions for targeted summarization.

Accessing Archived Original Messages

Programmatically retrieve the full pre-fold history using the archive path stored in the compaction event:

// compEvent is the event.Compaction struct from the event stream
archPath := compEvent.Archive // e.g., "/tmp/arch/20260531.jsonl"
data, _ := os.ReadFile(archPath) // JSONL format containing original messages

var msgs []provider.Message
json.Unmarshal(data, &msgs) // Full conversation history before the fold

Rendering the Compaction Card

The TUI receives compaction events and renders them using the dedicated card function:

// Event handler receives event.Compaction
func renderCompaction(e event.Compaction) []string {
    // Returns formatted lines with header, gutter-prefixed summary, 
    // and archive reference
    return compactionCardLines(e)
}

Rewind Limitations

The system prevents potentially inconsistent state changes. As noted in /internal/control/controller.go#L1745-L1747, rewind operations fail if the requested turn lies behind a compaction boundary, since the detailed message history required to reconstruct that state has been archived and removed from active memory.

Summary

  • Context compaction activates automatically at 80% of the token window or manually via /compact
  • The mid-section of conversation is summarized using a structured system prompt covering facts, goals, decisions, files, commands, errors, and pending items
  • Original folded messages are archived to JSONL files referenced in the Compaction event's Archive field before removal from memory
  • Three elements survive the fold: the system prompt, the <compaction-summary> wrapped briefing, and the configurable recent tail (default 2+ turns)
  • The TUI renders compactions as titled cards with gutter-prefixed content via compactionCardLines
  • Rewind operations are blocked for turns behind compaction boundaries to prevent state inconsistency

Frequently Asked Questions

What happens to my conversation history after a Context Compaction?

After context compaction, the full text of folded messages is removed from the model's active context but safely archived to a JSONL file on disk. The conversation continues using only the LLM-generated summary, recent turns, and system prompt. You can access the complete original history by reading the archive path specified in the Compaction event's Archive field.

How does DeepSeek-Reasonix decide when to trigger automatic compaction?

The Agent monitors accumulated prompt tokens continuously. When they reach the compact-ratio threshold (default 0.8 or 80% of the configured window), the system automatically triggers compaction with trigger type "auto". This prevents context overflow while maintaining a safety buffer for the conversation to continue.

Can I control what information survives a fold?

You can influence survival through the RecentKeep configuration parameter, which controls how many recent user/assistant turns remain verbatim after compaction (default is at least 2). However, the system always preserves the system prompt and requires the LLM-generated summary for the mid-section. You cannot selectively exclude specific messages from the fold beyond using the focus parameter with manual /compact commands.

Why does the rewind command fail after compaction has occurred?

Rewind operations fail when attempting to navigate to turns that exist within the archived (folded) portion of the conversation because those detailed message objects are no longer stored in the active session memory. Once messages are archived and removed, the system cannot reconstruct the precise state required for accurate rewinding to that specific turn. You must restore from a checkpoint created before the compaction to access that history.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →