How Reasonix Implements Context Compaction When the Context Window Limit Is Reached
Reasonix prevents prompt overflow by automatically summarizing older conversation history into a structured compaction summary once token usage exceeds 80% of the context window, preserving the system prompt, key facts, and recent messages while archiving the folded content.
DeepSeek-Reasonix manages long-running LLM conversations by implementing an intelligent context compaction system that triggers when token usage approaches the model's configured limit. The system automatically folds historical dialogue into concise, structured summaries while preserving critical context, ensuring the agent maintains coherent reasoning without exceeding hardware constraints.
Detecting the Compaction Trigger
The compaction process begins in internal/agent/compact.go where the maybeCompact function (line 81) monitors token consumption during each turn. This function checks the current u.PromptTokens against configured compact-ratio thresholds: a soft limit at 50% that emits informational notices only, and a hard limit at 80% that initiates automatic folding. Once the hard ratio is exceeded, maybeCompact invokes compact (line 119) with the trigger identifier "auto".
Planning the Compaction Region
Inside compact, the planCompaction function (line 99) determines exactly which messages to fold by calculating two critical boundaries. First, it establishes a pinned prefix (pinnedPrefixLen) that must remain verbatim, including the system prompt, the initial user turn, and any existing compaction summaries. Second, it allocates a tail budget of 16 KB tokens and walks backward from the newest messages until this budget fills, marking the tailStart index. The function returns the range msgs[head:start] representing the foldable middle section.
Partitioning and Economic Checks
The partitionFold function (line 84) separates the target region into two categories: kept messages (small user turns, prior summaries, and messages protected by the keep policy) and fold messages eligible for summarization. Before invoking the LLM, Reasonix performs a foldEconomics validation (line 13) to ensure the foldable portion justifies an API call; if the segment is too small, the compaction aborts unless the force flag is set.
Generating the Structured Summary
When economics validate, summarizeWithRetry calls summarize (line 44) to generate the briefing. This function sends a specialized summarySystemPrompt (lines 48–79) instructing the model to produce a structured document covering standing facts, goals, decisions, files, commands, errors, and next steps. The call respects a summaryTimeout (line 46) and streams the response to capture usage statistics.
Reconstructing the Session
After summarization, Reasonix rebuilds the message list atomically using session.Replace. The new transcript structure consists of: the original prefix (msgs[:head]), all kept messages, a single compaction summary wrapped in <compaction-summary> tags (lines 58–62), and the unchanged recent tail (msgs[start:]). A rewrite counter increments (line 66) to track compaction frequency.
Archiving and Event Emission
If an archive directory is configured, archiveMessages (lines 20–40) writes the folded messages to a timestamped .jsonl file. Reasonix emits three events to update UI components: CompactionStarted before summarization, CompactionDone containing the summary, fold count, and archive path (lines 68–70), and a fallback mechanical fold (plain text) if summarization fails (lines 46–52).
Handling Pathological Loops
To prevent infinite compaction cycles, a stuck guard (lines 28–34) detects when compaction fires on consecutive turns and disables auto-compaction while emitting a warning. Users retain the ability to force compaction manually using the /compact command, which bypasses the guard.
Code Examples
Automatic compaction triggered by window limits:
// Inside the turn‑processing loop (simplified)
usage, _ := provider.GetUsage() // provider‑specific token usage
agent.maybeCompact(ctx, usage) // Auto‑compact when usage exceeds the configured ratio
Manual compaction via the /compact command:
// The UI sends a `CompactionStarted` event with trigger "manual"
agent.compact(ctx, "manual", userFocus, false) // `userFocus` is optional extra guidance
Inspecting the resulting session after compaction:
for i, m := range agent.session.Messages {
fmt.Printf("%d [%s] %s\n", i, m.Role, m.Content)
}
The output will contain a single user message that starts with <compaction-summary> – the compacted briefing.
Key Source Files
internal/agent/compact.go– Core implementation of context compaction, including detection, planning, summarisation, and archiving.internal/event/event.go– Definition of theCompactionStartedandCompactionDoneevents used to surface progress.internal/provider/provider.go– Provides theMessageandUsagetypes that the compaction logic operates on.internal/cli/chat_tui.go– Renders the compaction summary card in the terminal UI (compactionCardLines).
Summary
- Context compaction triggers automatically when token usage exceeds 80% of the configured window, or manually via the
/compactcommand. - The system preserves a pinned prefix (system prompt, first turn, existing summaries) and a 16 KB tail of recent messages while folding the middle section.
- Reasonix validates fold economics to avoid API calls for insignificant token savings, unless the
forceflag overrides this check. - Summaries follow a structured format wrapped in
<compaction-summary>tags and are stored alongside archived original messages in timestamped.jsonlfiles. - A stuck guard prevents infinite compaction loops by disabling auto-compaction when it fires on consecutive turns.
Frequently Asked Questions
At what token threshold does Reasonix automatically compact context?
Reasonix initiates automatic compaction when u.PromptTokens exceeds the hard ratio of 80% of the configured context window. A soft ratio at 50% only emits informational warnings without triggering the fold.
How does Reasonix decide which messages to keep versus fold?
The planCompaction function calculates a pinned prefix containing the system prompt and initial turns, plus a tail budget of 16 KB for recent messages. The partitionFold function then categorizes the remaining middle section into kept messages (small user turns, prior summaries) and fold messages eligible for summarization.
What happens if the summarization API call fails during compaction?
If the LLM summarization fails, Reasonix falls back to a mechanical fold that compresses the foldable messages into plain text rather than a structured summary. The system still emits a CompactionDone event to notify the UI of the fallback.
Can users manually trigger context compaction?
Yes. Users can invoke the /compact command at any time, which calls agent.compact with the "manual" trigger and optional userFocus guidance. Manual compaction bypasses the stuck-guard protection that disables auto-compaction after consecutive folds.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →