Documentation

Protocols - How lean-ctx Communicates

5 protocols govern how lean-ctx manages context: CEP, CCP, TDD/CRP, CLP, and A2A. Learn when each activates and how they work together.

lean-ctx defines 5 protocols that govern how context is managed, compressed, communicated, and shared between agents. They activate automatically based on session state, but understanding them helps you get the most out of the system.

Protocol Map

ProtocolFull NameWhen It ActivatesWhat It Does
CEP Context Engineering Protocol Every session (system prompt) 5 rules for efficient context usage: act first, delta only, structured notation, one line per action, quality anchor
CCP Context Checkpoint Protocol Every ~15 tool calls (auto) or manual Creates compressed session snapshots that survive context window truncation
TDD/CRP Terse Data Density / Context Reduction Protocol When CRP_MODE=tdd is set Maximum compression: abbreviated keywords, symbol maps, diff-only output
CLP Context Layered Preload Session start with ctx_preload Intelligently pre-loads relevant files based on task description
A2A Agent-to-Agent Multi-agent sessions Message bus, shared cache, task delegation between agents

CEP — Context Engineering Protocol

CEP is the foundational protocol: it shapes how the LLM itself communicates. Injected into every session's system prompt, CEP establishes 5 rules that reduce output token waste by training the model to be concise and action-oriented.

The 5 CEP Rules

  1. ACT FIRST: Execute tool calls before explaining. No narration before action.
  2. DELTA ONLY: Use file references (F1, F2...) instead of repeating full paths. Show only changed code, never echo unchanged lines.
  3. STRUCTURED: Use + (add), - (remove), ~ (modify) notation for changes.
  4. ONE LINE PER ACTION: Each action or result fits on a single line for scan-ability.
  5. QUALITY ANCHOR: Never skip edge cases, never use mock data, never use placeholders.

When CEP Activates

CEP is always active. It is injected via the LITM (Lost-In-The-Middle) system prompt block at session start and reinforced at the end of instructions. You cannot disable CEP — it is the baseline communication contract between lean-ctx and the model.

Example: With vs. Without CEP

# Without CEP (typical LLM output):
I'll read the authentication service file to understand the current implementation.
Let me also check the token refresh logic...
The file at src/auth/service.rs contains a TokenService struct with methods for
creating and refreshing tokens. I can see that the refresh logic on line 45...

# With CEP active (lean-ctx output):
F1=auth/service.rs → ~refresh_token(): fixed expiry calc
  ~ L45: expires_at = now + duration  (was: now - duration)

Full CEP documentation →

CCP — Context Checkpoint Protocol

CCP creates compressed session snapshots that preserve the agent's working state across context window truncation. In long sessions, the LLM's context window silently drops older messages — CCP ensures critical state (cached files, F-references, active tasks) survives.

What a Checkpoint Captures

  • File cache state: All cached files with their F-references, content hashes, and read modes
  • Session metadata: Active task, workflow state, knowledge entries, diary entries
  • File signatures: Compact summaries for quick recovery without full re-reads
  • Token accounting: Cumulative savings, call counts, and budget status

When CCP Activates

TriggerCondition
Auto checkpointEvery ~15 tool calls (configurable via checkpoint_interval)
Manual checkpointCall ctx_compress explicitly
Threshold checkpointWhen estimated context usage exceeds 60% of window
Session saveWhen calling ctx_session save

Example: Checkpoint in Action

# After 15+ tool calls, lean-ctx auto-compresses:
⟳ CCP checkpoint (auto, call #16)
  Files: 5 cached (F1..F5), 3 signatures
  State: task="fix auth bug", workflow=investigating
  Tokens: 34,200 saved (87% reduction)
  Snapshot: 142 tokens (vs ~4800 tokens to re-read all files)

# Manual checkpoint when you want to save state:
ctx_compress
→ Checkpoint created: 5 files, 2 knowledge entries, 1 diary
  Recovery cost: ~150 tokens

Full CCP documentation →

TDD / CRP — Terse Data Density Mode

TDD is the maximum compression protocol. When activated, all lean-ctx output is compressed using abbreviated keywords, symbol maps, and diff-only notation. It targets ≤150 tokens per response with zero narration — ideal for agents running on tight token budgets or high-throughput pipelines.

When TDD Activates

TriggerHow
Environment variableCRP_MODE=tdd in shell or .env
Config filecrp_mode = "tdd" in lean-ctx.toml
Per-sessionctx_session set crp_mode=tdd

TDD Compression Techniques

  • Abbreviated keywords: fn, cfg, impl, deps, req, res, ctx, err
  • Type shortcuts: :s (string), :n (number), :b (boolean)
  • Symbol maps (§MAP): Long identifiers → short IDs (α1, α2...)
  • Diff-only output: +/-/~ notation, no unchanged code
  • Budget target: ≤150 tokens per response

Example: Normal vs. TDD Output

# Normal ctx_read output (~180 tokens):
F1=src/auth/service.rs 95L [full]
  pub struct TokenService { db: Pool, secret: String }
  pub fn create_token(&self, user_id: i64) -> Token { ... }
  pub fn refresh_token(&self, token: &str) -> Result<Token> { ... }
  pub fn revoke_token(&self, token: &str) -> Result<()> { ... }

# TDD ctx_read output (~45 tokens):
F1=auth/service.rs 95L
  §MAP: TokenService=α1, create_token=α2, refresh_token=α3
  α1 { db:Pool, secret:s }
  α2(user_id:n)->Token
  α3(token:s)->Res<Token>
  revoke_token(token:s)->Res<()>

Quality Gate: Symbol Scope

TDD symbols like λ (lambda shorthand for functions) and § (section/map marker) are only emitted in map mode output (ctx_read mode="map"). Shell output (ctx_shell) never contains these symbols — the shell compression engine uses a separate pipeline that preserves structural integrity of command output (exit codes, paths, diff hunks). This separation ensures that tools and scripts parsing shell output are never confused by TDD notation.

Full TDD documentation →

CLP — Context Layered Preload

CLP front-loads the right files at session start so the agent doesn't waste tool calls discovering them later. Given a task description, CLP analyzes the project structure (imports, call graph, file names) and pre-loads files in three layers with decreasing detail.

When CLP Activates

CLP activates when you call ctx_preload with a task description at session start. It can also trigger automatically if auto_preload = true is set in lean-ctx.toml and the agent's first message contains a clear task.

The Three Layers

LayerRead ModeWhat Gets LoadedWhy
L1 (Entry) full Files directly relevant to the task You'll likely edit these — need full content
L2 (Context) map / signatures Dependencies and imports of L1 files Need API surface, not full code
L3 (Reference) reference Transitive dependencies Registered for quick access, no content loaded

Example: Preloading for a Bug Fix

ctx_preload task="fix the auth refresh token bug"
→ Preloaded 7 files in 3 layers:
  L1 (full):    src/auth/service.rs, src/auth/token.rs
  L2 (map):     src/http/middleware.rs, src/db/sessions.rs, src/config.rs
  L3 (ref):     src/http/server.rs, src/main.rs
  Total: ~2400 tokens (vs ~12000 tokens for full reads)

# Without CLP, the agent would:
#   1. ctx_tree src/         → 200 tokens
#   2. ctx_read src/auth/    → scan multiple files → 800+ tokens
#   3. ctx_read dependencies → 600+ tokens each
# CLP saves 3-5 tool calls and loads everything in optimal modes

A2A — Agent-to-Agent Protocol

A2A enables coordination between multiple AI agents working on the same project. It provides an agent registry, message bus, task delegation, shared cache, and persistent diaries — everything needed for multi-agent workflows on a single codebase.

See Multi-Agent Coordination for details on the agent registry, message routing, task delegation, Google A2A compatibility, and context handoff patterns.

How Protocols Work Together

Protocols are not isolated — they compose. A typical session activates multiple protocols at different stages:

  1. Session start: CEP activates (always). CLP activates if ctx_preload is called.
  2. During work: CEP governs LLM output style. TDD may further compress if enabled.
  3. At checkpoint intervals: CCP creates snapshots automatically every ~15 calls.
  4. In multi-agent setups: A2A routes messages and shares cache between agents.
Session timeline:
  ┌─── CEP (always active, governs output style) ──────────────────────┐
  │                                                                     │
  │ CLP         CCP          CCP          CCP                          │
  │ preload     checkpoint   checkpoint   checkpoint                   │
  │ ↓           ↓            ↓            ↓                            │
  ├──┤──────────┤────────────┤────────────┤────────────────────────────┤
  0  start     call #15     call #30     call #45                   end
  │                                                                     │
  │ TDD (optional, if CRP_MODE=tdd) ───────────────────────────────────│
  │ A2A (optional, if multi-agent) ────────────────────────────────────│
  └─────────────────────────────────────────────────────────────────────┘

Which Protocol When?

Use this table to decide which protocols matter for your use case:

ScenarioProtocols ActiveWhat to Do
Default session (no config) CEP + CCP Nothing — both activate automatically
Long session (50+ tool calls) CEP + CCP CCP auto-checkpoints; call ctx_compress manually if context feels stale
Tight token budget or CI pipeline CEP + CCP + TDD Set CRP_MODE=tdd for maximum compression
Task-oriented session start CEP + CLP + CCP Call ctx_preload task="..." to front-load relevant files
Multiple agents on same project CEP + CCP + A2A Use ctx_agent for coordination; see Multi-Agent
Maximum savings (all optimizations) CEP + CCP + TDD + CLP Preload + TDD mode + auto checkpoints — typical 90%+ token reduction