DeepSeek TUI Capacity Flow Guardrail System: Architecture, Configuration, and Usage

The DeepSeek TUI capacity flow guardrail system is an optional runtime safety mechanism that monitors model context pressure through a weighted entropy proxy, compares it against model-specific capacity priors, and automatically triggers interventions like context compaction or replanning when risk thresholds are exceeded.

The DeepSeek-TUI repository implements this guardrail as a series of checkpoints within the core engine to prevent context overflow and degradation in long-running terminal sessions. By calculating a runtime pressure proxy () and comparing it against hardcoded model capacity priors (Ĉ), the system can proactively invoke safe interventions before the model reaches its limits.

How the Guardrail Works

The capacity flow system operates by evaluating entropy-based pressure metrics at critical points in the turn loop, then mapping those metrics to specific intervention strategies.

Runtime Pressure Calculation

At each checkpoint, the engine computes Ĥ by aggregating four complexity factors weighted by their impact on context utilization:

  • action_complexity_bits: log₂(1 + actions this turn) weighted at 0.35
  • tool_complexity_bits: log₂(1 + recent tool calls) weighted at 0.30
  • ref_complexity_bits: log₂(1 + unique reference IDs) weighted at 0.20
  • context_pressure_bits: 6 × context_used_ratio weighted at 0.15

These combine to produce the final pressure estimate Ĥ according to the specification in docs/capacity_controller.md.

Capacity Priors and Risk Profiling

Each DeepSeek model declares a hardcoded capacity prior Ĉ in crates/agent/src/models.rs. For example, deepseek_v4_flash uses a prior of 4.2, while unknown models fall back to 3.8.

The system calculates slack as Ĉ - Ĥ. A rolling profile of the last 8 observations feeds into a logistic regression-style risk score p_fail, computed as the sigmoid of a linear combination of:

  • Final slack and minimum slack
  • Violation ratio and volatility metrics
  • Drop indicators

The resulting probability maps to low, medium, or high risk bands using configurable thresholds (default 0.50 and 0.62).

Intervention Strategies

Based on the computed risk band, crates/core/src/engine/capacity_flow.rs selects one of four interventions:

  • NoIntervention: Continue execution unchanged when risk is low.
  • TargetedContextRefresh: Execute compact_messages_safe to replace the long-tail context with a canonical prompt plus memory pointer (triggered at medium risk).
  • VerifyWithToolReplay: Replay a recent read-only tool call to sanity-check the model's reasoning (triggered at high risk).
  • VerifyAndReplan: Persist a snapshot, clear the volatile prompt tail, inject a re-plan instruction, and resume from the compact canonical state (triggered at high risk with severe dynamics).

Checkpoint Evaluation

The guardrail evaluates at three specific moments orchestrated by crates/core/src/engine/turn_loop.rs:

  1. Before the request is assembled
  2. After a tool result is appended
  3. On tool-error escalation

These checkpoints ensure the system can intervene before expensive operations commit to an overloaded context state.

Configuration and Activation

Guardrail activation is opt-in via the TOML configuration. All thresholds support runtime tuning through environment variables prefixed with DEEPSEEK_CAPACITY_.

Enable and configure the guardrail in ~/.deepseek/config.toml:

[capacity]
enabled = true
low_risk_max = 0.45
medium_risk_max = 0.60
severe_min_slack = -0.30
severe_violation_ratio = 0.38
refresh_cooldown_turns = 5
replan_cooldown_turns = 4
max_replay_per_turn = 1
profile_window = 8

Launch the TUI with your configuration:

deepseek --config ~/.deepseek/config.toml

Implementation Architecture

The guardrail spans multiple crates within the DeepSeek-TUI codebase:


crates/core/src/engine/
│   engine.rs          # Turn orchestration

│   turn_loop.rs       # Streaming loop and checkpoint invocation

│   capacity_flow.rs   # Guardrail calculations and intervention logic

│   session.rs         # Session state including capacity memory

Supporting components include crates/agent/src/models.rs (model priors) and crates/config/src/lib.rs (configuration loading). The architecture diagram in docs/ARCHITECTURE.md illustrates how capacity_flow.rs integrates with the broader engine.

Working with Checkpoint Data

The system persists checkpoint snapshots to a per-session memory directory, defaulting to ~/.deepseek/memory/<session_id>.jsonl. Each record stores h_hat, c_hat, slack, and the assigned risk band.

Inspect recent checkpoint history programmatically:

use deepseek::core::engine::capacity_flow::CheckpointRecord;

let records = CheckpointRecord::load_last_k(5, &session)?;
for r in records {
    println!(
        "Turn {}: Ĥ={:.2}, Ĉ={:.2}, slack={:.2}, risk={}",
        r.turn_index, r.h_hat, r.c_hat, r.slack, r.risk_band
    );
}

Force a manual compaction when the guardrail predicts high risk:

/deepseek /compact

Or activate the guardrail programmatically for automated testing:

let mut cfg = deepseek::config::load("~/.deepseek/config.toml")?;
cfg.capacity.enabled = true;
deepseek::run_with_config(cfg)?;

Summary

  • The DeepSeek TUI capacity flow guardrail system computes a weighted entropy proxy Ĥ from action complexity, tool usage, reference density, and context pressure.
  • Model-specific capacity priors (Ĉ) define hard limits; slack (Ĉ - Ĥ) and rolling volatility drive the risk score p_fail.
  • Four intervention levels range from no action to full replanning with context compaction.
  • Checkpoints evaluate pressure before requests, after tool results, and during error escalation.
  • Configuration is opt-in via the [capacity] TOML table or DEEPSEEK_CAPACITY_* environment variables.
  • Checkpoint snapshots persist to ~/.deepseek/memory/<session_id>.jsonl for post-hoc analysis.

Frequently Asked Questions

How do I enable the capacity guardrail in DeepSeek-TUI?

Set enabled = true in the [capacity] section of your ~/.deepseek/config.toml file. You can override any threshold using environment variables like DEEPSEEK_CAPACITY_LOW_RISK_MAX=0.45 before launching the binary with deepseek --config /path/to/config.toml.

What triggers a VerifyAndReplan intervention?

The engine selects VerifyAndReplan when the risk band is high and the session exhibits severe dynamics, specifically when the minimum slack drops below severe_min_slack (default -0.30) or the violation ratio exceeds severe_violation_ratio (default 0.38). This persists a snapshot, clears the volatile prompt tail, and injects a re-planning instruction.

Where are capacity checkpoint snapshots stored?

Snapshots serialize to ~/.deepseek/memory/<session_id>.jsonl by default, as implemented in crates/core/src/engine/session.rs. Each JSON line contains the turn index, computed h_hat, c_hat, slack value, and assigned risk band from the profile window.

How is runtime pressure Ĥ calculated?

The pressure proxy Ĥ combines four logarithmic complexity metrics weighted by their cognitive load: action complexity (0.35), tool complexity (0.30), reference complexity (0.20), and context pressure (0.15). The context pressure component specifically uses 6 × context_used_ratio to amplify the impact of high context utilization.

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 →