lean-ctx enables multiple AI agents (Cursor, Claude Code, Codex, Gemini CLI, Pi, etc.) to work on the same project simultaneously with coordination, not conflict. The multi-agent system is built on 5 primitives: registry, message bus, task delegation, shared cache, and persistent diaries.
Agent Registry
Each agent registers when it joins a session, declaring its type and role. This enables targeted communication and role-based task assignment.
ctx_agent action="register" agent_type="cursor" role="dev"
→ Registered: cursor-dev-1 (agent_id: a1b2c3)
ctx_agent action="list"
→ 3 agents active:
a1b2c3 cursor dev active 2 min ago
d4e5f6 claude review active 5 min ago
g7h8i9 codex test idle 12 min ago Agent Types
| Type | Description |
|---|---|
cursor | Cursor IDE agent |
claude | Claude Code / Claude Desktop |
codex | OpenAI Codex CLI |
gemini | Gemini CLI |
crush | Crush IDE agent |
subagent | Spawned sub-agent |
Roles
| Role | Typical Responsibility |
|---|---|
dev | Primary development - writing code |
review | Code review - checking quality, security, patterns |
test | Testing - writing and running tests |
plan | Architecture - planning and design decisions |
Message Bus
Agents communicate via broadcast or direct messages, categorized for filtering:
# Broadcast a finding to all agents
ctx_agent action="post" category="finding" message="Auth token expiry is hardcoded at 3600s"
# Send directly to the reviewer
ctx_agent action="post" to_agent="d4e5f6" category="request" message="Please review auth.ts changes"
# Read pending messages
ctx_agent action="read"
→ 2 new messages:
[finding] from cursor-dev-1: Auth token expiry is hardcoded at 3600s
[status] from codex-test: All 42 tests passing Selective Routing
Instead of full broadcast, agents subscribe with TopicFilters to receive only relevant events. Filters support event kind, actor, consistency level, and agent identity. Directed events target specific agents, reducing noise and saving tokens.
# Poll events with filtering (via ctx_agent)
ctx_agent action="poll_events" category="default" message="0"
→ Events (3, since=0):
#1 [session_mutated] actor=cursor-dev cl=strong (14:30:12)
#2 [knowledge_remembered] actor=codex-test cl=eventual (14:31:05)
cursor=2 A2A Transport
TransportEnvelopeV1 enables cross-machine agent handoffs. Context packages and handoff bundles are wrapped with agent identity and HMAC-SHA256 signatures for integrity.
# Send a context package to a remote daemon
lean-ctx pack send myproject.lctxpkg --target=http://remote:3344 --secret=mykey
# Receive and verify on the other end
lean-ctx pack receive envelope.json --secret=mykey --apply
HTTP endpoint: POST /v1/a2a/handoff accepts TransportEnvelopes directly.
Agent discovery: GET /.well-known/agent.json returns the A2A v1.0 Agent Card.
Google A2A Compatibility
LeanCTX exposes a JSON-RPC 2.0 endpoint at /a2a compatible with the
Google A2A Protocol.
Supported operations: tasks/send, tasks/get, tasks/cancel.
# JSON-RPC request to create a task
POST /a2a
{
"jsonrpc": "2.0",
"id": 1,
"method": "tasks/send",
"params": {
"to": "lean-ctx",
"message": {
"role": "user",
"parts": [{"type": "text", "text": "Fix the auth bug"}]
}
}
} Task Delegation
ctx_task enables structured task assignment with tracking:
# Create and assign a task
ctx_task action="create" description="Write tests for auth token refresh" to_agent="g7h8i9"
→ Task T1 created, assigned to codex-test
# Check task status
ctx_task action="list"
→ T1: "Write tests for auth token refresh" → codex-test [in_progress]
T2: "Review security of token storage" → claude-review [pending] Shared Session Cache
All agents in a session share the same file cache. When one agent reads a file, all other agents benefit from the cached version. This eliminates redundant reads and ensures consistency.
- Agent A reads
auth.ts→ cached as F1 - Agent B reads
auth.ts→ gets cache hit (~13 tokens) - Agent A edits
auth.ts→ cache auto-invalidated - Agent B reads again → gets fresh content with updated hash
Persistent Diaries
Each agent can maintain a diary that persists across sessions. Diary entries are categorized for later retrieval:
# Log a discovery
ctx_agent action="diary" category="discovery" message="Config uses TOML, not YAML as documented"
# Log a decision
ctx_agent action="diary" category="decision" message="Using JWT RS256 for auth tokens"
# Log a blocker
ctx_agent action="diary" category="blocker" message="Cannot test refresh flow - mock server needed"
# Recall diary in a new session
ctx_agent action="recall_diary"
→ 3 entries from cursor-dev-1:
[discovery] Config uses TOML, not YAML as documented
[decision] Using JWT RS256 for auth tokens
[blocker] Cannot test refresh flow - mock server needed Context Handoff
ctx_handoff transfers the full working context between agents or sessions.
This includes cached files, knowledge base entries, workflow state, and session context.
# Agent A saves context before ending
ctx_handoff action="save" apply_knowledge=true apply_session=true apply_workflow=true
→ Context saved: 12 files, 3 knowledge entries, 1 active workflow
# Agent B (or new session) restores
ctx_handoff action="load"
→ Restored: 12 cached files (F1-F12), 3 knowledge entries, workflow "bugfix" at step "test"
Ready to continue where Agent A left off. Compaction Survival
When AI providers truncate or compact the context window (e.g., Claude's context window management, Cursor's automatic compaction), lean-ctx sessions can lose critical state. The Compaction Survival system detects and recovers from these events automatically.
PreCompact Hook
The PreCompact hook fires when lean-ctx detects an imminent compaction event,
giving the system a chance to save critical state before the context is truncated:
- Saves current session state (cached files, file references, active tasks)
- Creates a compact resume block (≤500 tokens) summarizing everything needed to continue
- Writes the resume block to
~/.lean-ctx/sessions/<id>/resume.json
Heuristic Detection
lean-ctx detects compaction even without an explicit hook by monitoring for a tool-call counter mismatch:
- lean-ctx tracks how many tool calls have been made in the session (server-side counter)
- The model's context includes an expected counter value from the session banner
- After compaction, the model may "forget" recent calls - the next tool call has a counter gap
- When a gap is detected, lean-ctx automatically injects the resume block into the response
# Normal flow: counters match
Tool call #15 → server expects #15 ✓
# After compaction: model "forgot" calls 10-14
Tool call #10 → server expects #15 ✗ (gap detected)
→ Auto-injecting resume block... Resume Block
The resume block is a compact summary (max 500 tokens) that restores critical session context:
ctx_session action="resume"
→ Session resumed from checkpoint:
Files: F1=auth.ts F2=server.rs F3=db.ts (3 cached)
Task: "Fix JWT refresh race condition" (step 3/5)
Archives: [a7f3c2] auth analysis, [b8d4e1] test results
Diary: 2 entries (1 decision, 1 discovery)
Agent: cursor-dev-1, role: dev Archive Interaction
The resume block includes references to all active ctx_expand archive IDs.
This means that even after compaction, the agent can still retrieve large tool results
that were archived before the context was truncated:
- Archive IDs listed in resume block are validated - expired entries are excluded
- The agent can call
ctx_expand id="..."to retrieve any listed archive - If the archive TTL expired during compaction, the resume block notes it as
[expired]
Configuration
# config.toml
[compaction]
resume_max_tokens = 500 # Max size of the resume block
auto_detect = true # Enable heuristic detection
counter_gap_threshold = 2 # Min gap to trigger resume injection Best Practices
- Register early: Call
ctx_agent action="register"at the start of every multi-agent session - Use diaries: Log important discoveries and decisions - they persist and help future sessions
- Categorize messages: Use
finding,warning,request,statusfor easy filtering - Delegate with context: Include clear descriptions when assigning tasks
- Track costs: Use
ctx_cost action="agent"to monitor per-agent token spend