Четыре инструмента для межсессионной памяти, мульти-агентной координации и ориентации проекта. ctx_knowledge теперь включает временное отслеживание фактов, автоматическое обнаружение противоречий, межсессионный поиск и компактный формат AAAK. ctx_agent поддерживает персистентные дневники агентов. ctx_overview предоставляет автоматические брифинги при запуске.
Memory Runtime (Autopilot)
The Memory Runtime is a biologically-inspired memory model that runs silently in the background. No verbose outputs, no agent compliance needed - install and it just works.
- Ingestion: Tool receipts + compact session signals are recorded automatically.
- Deterministic Salience Tagging: Every fact gets a salience score based on frequency, recency, and confirmation count. High-salience facts surface first; low-salience facts decay into archives.
- Consolidation Engine:
consolidate_latestpromotes salient findings/decisions into permanentctx_knowledge(budgeted, no prose). - Adaptive Forgetting: Active sets stay small via time-decay and salience thresholds. Low-value facts are archived (not deleted) and can be rehydrated on demand.
- Dual-Process Retrieval: Fast System-1 recall (keyword + salience lookup) for immediate answers. Deep System-2 recall (semantic search + archive rehydration) when System-1 misses.
- Prospective Memory: The system remembers pending tasks and surfaces them at the right moment - e.g., "you planned to add error handling to this function" when the file is read again.
- Structured Intent Layer: Current task context flows through the entire pipeline, so all read modes, compression, and retrieval are task-aware without explicit configuration.
Storage & LEAN_CTX_DATA_DIR
By default, data is stored under ~/.lean-ctx/. For test isolation or custom locations, set
LEAN_CTX_DATA_DIR to point to the root directory used for all persistent stores.
How to verify it’s working
lean-ctx token-report --json- session summary + intent counters.ctx_knowledge action=status- active vs archived facts and rooms.ctx_cost action=reportandctx_heatmap action=status- non‑empty after normal usage.
ctx_knowledge - Persistent Project Knowledge
A persistent knowledge store scoped to each project with temporal fact tracking, contradiction detection, and cross-session search. Facts, patterns, and conventions survive across sessions, enabling the LLM to build cumulative project understanding. Facts are automatically versioned - when a high-confidence fact changes, the old value is archived (not deleted) with full temporal history.
Параметры
| Action | Параметры | Описание |
|---|---|---|
remember | category, key, value, confidence | Store a fact. Auto-detects contradictions with existing facts and tracks temporal validity. |
recall | query OR category | Search facts by text or list by category (only current/valid facts) |
pattern | pattern_type, value, examples | Record a project convention or pattern |
consolidate | - | Extract session findings/decisions into permanent knowledge |
timeline | category | View full version history of facts in a category, including archived values |
rooms | - | List all knowledge categories (rooms) with fact counts |
search | query | Cross-session/cross-project search across ALL stored knowledge and sessions |
wakeup | - | Compact AAAK-formatted briefing of the most important project facts |
status | - | Show stored knowledge summary with active/archived counts and rooms |
remove | category, key | Remove a fact from the active set (also removes its embedding entry if present) |
export | - | Export all knowledge as structured JSON |
gotcha | trigger, resolution, severity | Record a bug/mistake to never repeat |
embeddings_status | - | Show semantic embeddings status (model present/missing, auto-download flag, index size) |
embeddings_reset | - | Delete the local embeddings index for this project |
embeddings_reindex | - | Rebuild embeddings index from current (non-archived) facts |
Temporal Facts & Contradiction Detection
Every fact has valid_from/valid_until timestamps and a confirmation_count.
When a fact is re-asserted with the same value, its confirmation count increases. When a high-confidence,
multiply-confirmed fact changes, the old value is archived and a contradiction warning is
returned with severity (low/medium/high) and resolution details.
AAAK Compact Format
Knowledge is automatically injected into LLM instructions using a compact AAAK format:
CATEGORY:key=value★★★|key2=value2★★. This saves ~60% tokens compared to verbose prose
and is always up-to-date. No configuration needed.
Example
ctx_knowledge action=remember category=architecture key=auth value="JWT RS256" confidence=0.95
→ Remembered [architecture] auth: JWT RS256 (confidence: 95%)
ctx_knowledge action=remember category=architecture key=auth value="OAuth2 + PKCE" confidence=0.9
→ Remembered [architecture] auth: OAuth2 + PKCE (confidence: 90%)
⚠ CONTRADICTION DETECTED: High-confidence fact [architecture/auth] changed:
'JWT RS256' → 'OAuth2 + PKCE' (was confirmed 2x). Previous value archived.
ctx_knowledge action=timeline category=architecture
→ Timeline [architecture] (2 entries):
auth = JWT RS256 [archived] (2026-01-15 → 2026-03-20) conf=95% x2
auth = OAuth2 + PKCE [CURRENT] (2026-03-20 → now) conf=90% x1
ctx_knowledge action=rooms
→ Knowledge Rooms (3 rooms):
[architecture] 5 fact(s)
[deployment] 2 fact(s)
[testing] 1 fact(s)
ctx_knowledge action=search query="authentication"
→ Cross-session search (3 results):
[architecture/auth] OAuth2 + PKCE (project: my-app, conf: 90%)
[session-decision/20260320] Migrated from JWT to OAuth2 (project: my-app, conf: 70%)
ctx_knowledge action=wakeup
→ WAKE-UP BRIEFING:
ARCHITECTURE:auth=OAuth2 + PKCE★★★★|db=PostgreSQL 16★★★★★
DEPLOYMENT:host=AWS ECS★★★|region=eu-central-1★★★ Storage
Knowledge is stored per-project at ~/.lean-ctx/knowledge/<project-hash>/knowledge.json.
Archived facts remain in the same file with valid_until timestamps.
Knowledge Embeddings (Semantic Recall)
When embeddings are enabled and the local model is available, ctx_knowledge action=recall with a query
performs semantic recall (hybrid ranking: semantic similarity + confidence + recency), and returns a scored list.
Auto-download is off by default. To allow first-use model download, set
LEAN_CTX_EMBEDDINGS_AUTO_DOWNLOAD=1. Model files are stored under ~/.lean-ctx/models/
(override with LEAN_CTX_MODELS_DIR).
Embeddings index (per project): ~/.lean-ctx/knowledge/<project-hash>/embeddings.json.
ctx_knowledge action=embeddings_status
→ Knowledge embeddings: model=present, auto_download=off, index_entries=128, path=~/.lean-ctx/knowledge/abc123/embeddings.json
ctx_knowledge action=recall query="auth token refresh"
→ Semantic recall 'auth token refresh' (showing 5):
[architecture/auth-method]: JWT RS256 (score: 92%, sem: 96%, conf: 95%)
ctx_knowledge action=embeddings_reset
→ Embeddings index reset.
ctx_knowledge action=embeddings_reindex
→ Embeddings reindex ok (embedded 128 facts). Full reference → CLI: lean-ctx knowledge
Полная CLI-парность с MCP-инструментом. Используйте для скриптинга, резервного копирования и миграции из других инструментов.
lean-ctx knowledge remember "Uses JWT" --category auth --key token-type
lean-ctx knowledge recall "authentication"
lean-ctx knowledge search "database"
lean-ctx knowledge export --format jsonl --output backup.jsonl
lean-ctx knowledge import backup.json --merge skip-existing --dry-run
lean-ctx knowledge remove --category auth --key token-type
lean-ctx knowledge status
lean-ctx knowledge health Форматы импорта: нативный JSON (из export), простой массив [{category, key, value}] или JSONL (один факт на строку). Стратегии слияния: skip-existing (по умолчанию, безопасная), replace, append. Используйте --dry-run для предпросмотра.
ctx_agent - Multi-Agent Coordination & Diaries
Coordinates multiple concurrent AI agents working on the same project. Agents register themselves, share findings via a scratchpad, track each other's status, and maintain persistent diaries that survive across sessions.
Параметры
| Action | Параметры | Описание |
|---|---|---|
register | agent_type, role | Register this agent at session start |
list | - | Show other active agents on this project |
post | message, category, to_agent | Share findings/warnings with other agents |
read | - | Check for new messages from other agents |
status | status (active/idle/finished), message | Update work status |
info | - | Show registry summary |
handoff | to_agent, message | Transfer task to another agent with summary |
sync | - | Multi-agent sync status: active agents, pending messages, shared contexts |
diary | message, category | Log a structured diary entry (discovery/decision/blocker/progress/insight). Persisted across sessions. |
recall_diary | - | Read the 10 most recent diary entries with timestamps |
diaries | - | List all agent diaries across the system |
Agent Diaries
Each agent can maintain a persistent diary that records discoveries, decisions, blockers, progress, and insights. Diaries survive across sessions and can be recalled by any agent, enabling knowledge transfer even when the original agent is no longer active.
Diary entry types: discovery (found something), decision (chose an approach),
blocker (encountered an obstacle), progress (completed a step),
insight (learned something non-obvious).
Example
ctx_agent action=register agent_type=cursor role="implementing auth module"
→ Registered: cursor-a3f8 (role: implementing auth module)
ctx_agent action=diary message="Found N+1 query in user loading" category=discovery
→ Diary entry [discovery] added: Found N+1 query in user loading
ctx_agent action=diary message="Switched to batch loading with DataLoader" category=decision
→ Diary entry [decision] added: Switched to batch loading with DataLoader
ctx_agent action=recall_diary
→ Diary [cursor-a3f8] (2 entries):
[DECIDED] Switched to batch loading with DataLoader (5m ago)
[FOUND] Found N+1 query in user loading [auth] (7m ago)
ctx_agent action=diaries
→ Agent Diaries (3):
cursor-a3f8: 12 entries (5m ago)
claude-b7e2: 8 entries (2h ago)
gemini-c4d1: 3 entries (1d ago) Storage
Agent registry and scratchpad: ~/.lean-ctx/agents/registry.json.
Agent diaries: ~/.lean-ctx/agents/diaries/<agent-id>.json.
ctx_share - Multi-Agent Context Sharing
Enables agents to share cached file contents with each other. When one agent has read and cached files, it can push them to another agent, avoiding redundant file reads and enabling efficient task handoffs.
Параметры
| Action | Параметры | Описание |
|---|---|---|
push | paths, to_agent, message | Share cached file contexts with a specific agent or all agents |
pull | - | Receive shared contexts from other agents |
list | - | List all shared contexts across agents |
clear | - | Remove contexts shared by this agent |
Example
ctx_share action=push paths="src/auth.ts,src/middleware.ts" to_agent=claude message="auth files for review"
→ Shared 2 files with claude (1,247 tokens)
ctx_share action=pull
→ 1 shared context from cursor-a3f8:
src/auth.ts (892 tok) + src/middleware.ts (355 tok)
Message: "auth files for review" Storage
Shared contexts are stored at ~/.lean-ctx/agents/shared/ as JSON files.
ctx_overview - Task-Aware Project Map with Wake-Up Briefing
Provides a multi-resolution project map at session start. Uses the dependency graph and keyword
matching to group files by task relevance into tiers (critical / important / reference / skip).
Recommends the optimal ctx_read mode per file, so the LLM can load context efficiently
from the first tool call.
Automatic wake-up briefing: When called at session start, ctx_overview now automatically includes a compact briefing with top project facts (AAAK format), last task, recent decisions, and active agents. No configuration needed - it's always included when knowledge is available.
Параметры
| Параметр | Тип | Обязательный | Описание |
|---|---|---|---|
task | string | No | Description of current task (improves relevance ranking) |
path | string | No | Project root path (defaults to cwd) |
Example
ctx_overview task="fix JWT token refresh bug"
→ PROJECT OVERVIEW - /Users/you/project (142 files)
CRITICAL (read full):
src/auth.ts - JWT logic, token generation
src/middleware.ts - token validation
IMPORTANT (read map):
src/routes.ts - auth route handlers
src/lib/session.ts - session management
REFERENCE (read signatures):
src/lib/db.ts - database layer
src/config.ts - JWT config values
SKIP (67 files):
tests/, docs/, scripts/, ...
WAKE-UP BRIEFING:
FACTS:architecture/auth=JWT RS256|architecture/db=PostgreSQL
LAST_TASK:Fix authentication middleware timeout
RECENT_DECISIONS:Use refresh tokens|Add rate limiting
AGENTS:cursor-a3f8(dev),claude-b7e2(review) Full reference → ctx_task - A2A Task Delegation
Agent-to-Agent (A2A) task management following the Google A2A protocol. Agents can create, assign, update, and track tasks across a multi-agent workflow. Tasks persist across sessions and support full lifecycle management.
Параметры
| Action | Параметры | Описание |
|---|---|---|
create | title, description, to_agent | Create a new task with optional target agent |
update | task_id, state | Update task state (Working, InputRequired, Completed, Failed, Canceled) |
list | - | List all tasks with their current state |
get | task_id | Get detailed info about a specific task |
cancel | task_id | Cancel a task |
message | task_id, message | Add a message to a task thread |
info | - | Show A2A task system status and agent card |
Task Lifecycle
Tasks follow the A2A standard lifecycle: Created → Working → Completed/Failed/Canceled.
Agents can request input via InputRequired state. All state transitions are timestamped.
Example
ctx_task action=create title="Fix auth middleware" description="Token refresh not working" to_agent=claude
→ Task created: t-a3f8c1 "Fix auth middleware" (state: Created, to_agent: claude)
ctx_task action=update task_id=t-a3f8c1 state=Working
→ Task t-a3f8c1 updated: Created → Working
ctx_task action=message task_id=t-a3f8c1 message="Found the bug in token.rs:45"
→ Message added to task t-a3f8c1
ctx_task action=list
→ Tasks (2):
t-a3f8c1 "Fix auth middleware" [Working] (assignee: claude, 1 message)
t-b7e204 "Add rate limiting" [Completed] (assignee: cursor) Storage
Tasks are stored at ~/.lean-ctx/agents/tasks.json.
ctx_cost - Token Cost Attribution
Tracks and reports token costs per agent and per tool. Provides detailed breakdowns of which agents and tools are consuming the most tokens, enabling optimization and accountability in multi-agent workflows.
Параметры
| Action | Параметры | Описание |
|---|---|---|
report | limit, agent_id | Show cost attribution report (top N agents/tools) |
agent | agent_id | Show costs for a specific agent |
tool | limit | Show per-tool cost breakdown |
session | - | Show costs for current session only |
json | - | Export cost data as JSON |
reset | - | Reset all cost tracking data |
Example
ctx_cost action=report
→ COST ATTRIBUTION REPORT
Total tokens: 145,230
By Agent:
cursor-a3f8 89,420 tok (61.6%)
claude-b7e2 42,810 tok (29.5%)
gemini-c4d1 13,000 tok (8.9%)
By Tool:
ctx_read 78,200 tok (53.8%)
ctx_shell 31,400 tok (21.6%)
ctx_search 18,630 tok (12.8%)
ctx_tree 17,000 tok (11.7%) Storage
Cost data is stored at ~/.lean-ctx/costs.json and resets per session.