# Cortex — Self-Learning AI Agent
**Cortex** is a self-learning AI agent with persistent memory, tools, project awareness, and a polished terminal UI. Inspired by Claude Code CLI, Gemini CLI, OpenCode, and Hermes.
```bash
# Install from crates.io (requires Rust)
cargo install cortex-agent
# Start using it
cortex
```
## Installation
### 1. Install Rust & Cargo
If you don't have Rust installed, the easiest way is via `rustup`:
```bash
```
Verify it worked:
```bash
rustc --version # Should print rustc 1.70+
cargo --version
```
### 2. Install Cortex
```bash
cargo install cortex-agent
```
This downloads, compiles, and installs the `cortex` binary to `~/.cargo/bin/`.
### 3. Set up an API key
On first run, Cortex creates a template config at `~/.cortex/config.yaml`:
```bash
cortex
```
You'll see a welcome screen with instructions. Set your API key as an environment variable:
```bash
export OPENAI_API_KEY="sk-..."
cortex
```
Or edit `~/.cortex/config.yaml` directly and add your key there.
> **New to AI providers?** Sign up for an API key at one of these:
> - [OpenAI](https://platform.openai.com/api-keys)
> - [OpenRouter](https://openrouter.ai/keys) (multiple models, one key)
> - [DeepSeek](https://platform.deepseek.com/api_keys)
> - [Groq](https://console.groq.com/keys)
> - [Together](https://api.together.ai/settings/api-keys)
> - [Mistral](https://console.mistral.ai/api-keys)
> - [Anthropic](https://console.anthropic.com/keys)
> - **Ollama** (local, no key needed): `ollama pull llama3.2` then `/switch ollama`
## Features
### 🧠 Memory & Self-Learning
- **Persistent SQLite memory** — facts, preferences, skills, error lessons
- **Auto-categorization** — memories sorted into identity, preference, work, error, api, configuration, code, session
- **Memory consolidation** — overlapping memories auto-merge with boosted importance
- **Confidence scoring** — access_count tracks recall frequency
- **Memory decay** — old/unused memories degrade and auto-purge after 30 days
- **Preference learning** — detects "I use X", "I prefer Y" patterns automatically
- **Session summarization** — on exit, Cortex saves a summary with extracted topics and tags
- **Vector/semantic search** — embeddings-based memory retrieval (falls back to keyword)
### 🔥 Experience-Based Self-Healing
Cortex learns from its mistakes. When a tool fails, it saves the error as a structured lesson. On future occurrences, it checks if a fix was already learned and applies it automatically.
| `/lessons list` | Show all saved lessons with status and confidence |
| `/lessons show <id>` | Full lesson detail (trigger, fix, context) |
| `/lessons forget <id>` | Delete a stale or incorrect lesson |
| `/lessons stats` | Dashboard with auto-heal rate and confidence distribution |
Lessons auto-save on tool failure. Confidence increases on successful re-use.
### 🎭 Persona System
Switch Cortex's conversation style at runtime:
| `/persona list` | Show available personas |
| `/persona default` | Standard Cortex assistant |
| `/persona code` | Senior software engineer — clean code, best practices |
| `/persona concise` | Extremely brief, to-the-point answers |
| `/persona teacher` | Patient explainer from first principles |
| `/persona creative` | Brainstorming partner, out-of-the-box ideas |
Personas reset the conversation and inject a tailored system prompt.
### 🛠️ CLI Power Features
| `cortex eval "question"` | Non-interactive mode — prints answer and exits |
| `echo "question" \| cortex` | Pipe mode — auto-detects piped input |
| `cortex --doctor` | Full system diagnostics (config, providers, connectivity, memory) |
| `cortex show` | Display config with API keys masked |
| `cortex get <key>` | Get a config value (e.g., `cortex get active_provider`) |
| `cortex set <key> <value>` | Set a config value (e.g., `cortex set max_tokens 8192`) |
| `cortex validate` | Validate config YAML |
| `cortex context` | Show active project context files (AGENTS.md, CLAUDE.md, .cursorrules) |
| `cortex init` | Create `.cortex/config.yaml` for per-project config |
| `cortex completions bash\|zsh\|fish` | Generate shell completion scripts |
| `cortex doctor` | Same as `--doctor` |
| `cortex commit` | Generate conventional commit from staged git diff |
| `cortex commit --yes` | Generate and auto-commit |
| `cortex branch <desc>` | Create a git branch with auto-name + conventional prefix |
### 🎨 Terminal UI
- **Syntax highlighting** — commands like `/help`, `/memory` highlighted in cyan while typing
- **Ctrl+R** — reverse history search (incremental)
- **Rounded input box** (`╭─ provider/model ──╮`) with turn counter
- **Bordered streaming** — left-wall `│` during response, right-wall `│` on submit
- **Session status bar** — provider, tokens, context %, elapsed, turn count
- **Live token counter** — shows `N tok N/s` during generation
- **Auto theme detection** — detects dark/light terminal from COLORFGBG/COLORTERM env vars
- **Catppuccin-inspired themes** (`/theme mocha` / `/theme latte`)
- **Smart project detection** — shows language/framework/package manager on welcome
- **Resize-safe layout** — adapts to terminal width dynamically
### 🔐 Security & Session Control
| `/session readonly` | Block all write/destructive tool operations |
| `/session offline` | Block all network tool operations |
| `/session normal` | Restore full access |
| `/danger <tool>` | Temporarily approve a dangerous tool for this session |
| `/danger list` | Show dangerous tools with allowed/blocked status |
| `/permissions allow <tool>` | Permanently approve a dangerous tool |
| `/permissions list` | Show approved tools |
| `/permissions revoke <tool>` | Revoke approval |
| **API key masking** | Keys auto-redacted in session exports and tool args display |
| **Config auto-backup** | `config.yaml.bak` created before first modification per session |
### 💾 Session Management
| `/session save <name>` | Save current conversation to `~/.cortex/sessions/` |
| `/session load <name>` | Load a saved conversation |
| `/session list` | List saved sessions |
| `/session export` | Export as markdown transcript |
| `/session export --format json` | Export as JSON |
| `/session export --format html` | Export as dark-themed standalone HTML |
### 📁 Project Intelligence
- **Auto-detects project root** — walks up from cwd looking for AGENTS.md, CLAUDE.md, GEMINI.md, .cursorrules
- **Injects project context** into system prompt automatically
- **Smart project detection** — auto-detects language (Rust/Python/JS/Go/Java), framework, package manager, test framework, CI type
- **Per-project `.cortex/config.yaml`** — settings override global config when inside a project
- **`cortex init`** — creates `.cortex/config.yaml` with auto-detected project type
- **`cortex context`** — shows what project files are active
### 🛠️ Built-in Tools (available to the LLM)
| **Web** | `web_search` (DuckDuckGo), `web_fetch` |
| **Code** | `execute_python`, `execute_bash` |
| **Files** | `read_file`, `write_file` |
| **Git** | `git_status`, `git_diff` |
| **Memory** | `save_memory`, `search_memory`, `list_memories`, `forget_memory` |
| **Skills** | `create_skill`, `get_skill`, `update_skill`, `delete_skill`, `list_skills` |
### 📚 Skill System
Skills are reusable instruction sets that teach Cortex how to handle recurring tasks (code review, debugging, planning, etc.). They're stored in the SQLite memory database and managed via `/skills` commands.
**Built-in skills (auto-seeded on first run):**
- `cortex-superpower` — power-user workflows for Cortex itself
- `code-review`, `test-driven-development`, `systematic-debugging`
- `writing-plans`, `executing-plans`, `subagent-driven-development`
- `brainstorming`, `dispatching-parallel-agents`, and more (15 total)
**Managing skills:**
```bash
/skills # List all saved skills
/skills add # Create a new skill interactively
/skills delete # Remove a skill
/skills import <git-url> # Import skills from a GitHub repo
```
**Importing from the community skill repo:**
```bash
/skills import git@github.com:shafiqruet/ajbm-skills.git
```
Skills from the repo are scanned (files with YAML frontmatter `---` are treated as skills), imported one by one, and immediately available to the LLM. Duplicate names are skipped automatically.
Skills are versioned — updating a skill increments its version number. The LLM can read, create, and use skills via the `get_skill`, `create_skill`, `update_skill`, `delete_skill`, and `list_skills` tools.
### 🔄 Provider Support
Cortex supports any OpenAI-compatible API provider. Switch providers and models at runtime:
```bash
/provider # Interactive picker with arrow keys
/switch openrouter # Quick switch — prompts for model
/switch ollama # Switch to local Ollama
```
**Provider management:**
```bash
/provider add # Interactive wizard: name → URL → API key → model
/provider edit # Change API key or base URL for a provider
/provider remove # Remove a provider
/provider test # Ping the API endpoint to verify connectivity
```
**Pre-configured providers** (in `~/.cortex/config.yaml` template):
| OpenAI | `OPENAI_API_KEY` | gpt-4o, gpt-4o-mini |
| OpenRouter | `OPENROUTER_API_KEY` | Access to 200+ models |
| Anthropic | `ANTHROPIC_API_KEY` | Claude models |
| DeepSeek | `DEEPSEEK_API_KEY` | deepseek-chat, deepseek-v4 |
| Groq | `GROQ_API_KEY` | Fast inference, free tier |
| Together | `TOGETHER_API_KEY` | Open-source models |
| Mistral | `MISTRAL_API_KEY` | Mistral models |
| Ollama | _(none)_ | Local inference at `http://localhost:11434/v1` |
**Using Ollama locally:**
```bash
# 1. Install ollama from https://ollama.com
# 2. Pull a model:
ollama pull llama3.2
# 3. Start cortex and switch:
cortex
> /switch ollama
> Model: llama3.2
```
The active provider and model persist between sessions (saved to `~/.cortex/session.json`).
### 📋 Clipboard Integration
```bash
/copy <text> # Copy text to clipboard
/copy --last # Copy last assistant response
```
Uses `wl-copy` (Wayland) or `xclip` (X11). Falls back to writing to `~/.cortex/clipboard.txt`.
### 💥 Crash Recovery
Cortex auto-saves your conversation every 30 seconds to a recovery file. If Cortex crashes or your terminal closes unexpectedly, the next startup will ask if you want to restore the previous session.
## Quick Start
```bash
# Install
cargo install cortex-agent
# First run — creates config and guides you
cortex
# Inside cortex:
/help # Show all commands
/tools # List available tools
/persona list # Try different conversation styles
/memory tree # Browse memories by category
/memory stats # Memory statistics
/theme latte # Switch to light theme
/lessons list # See what Cortex has learned
/session save work # Save current conversation
/session readonly # Block write operations
/danger list # See dangerous tool status
/copy --last # Copy last response
# From the shell (non-interactive):
cortex eval "What is Rust's ownership model?"
cortex context
cortex get active_provider
cortex completions bash
cortex branch fix-login-bug
```
## Commands Reference
| `/help <cmd>` | Categorized help with detailed usage |
| `/tools` | List all available tools grouped by category |
| `/memory` | Browse memories — add `tree`, `timeline`, or `stats` |
| `/skills add\|delete\|import` | Manage reusable skills |
| `/lessons list\|show\|forget\|stats` | Self-healing lesson management |
| `/theme mocha\|latte` | Switch between dark/light themes |
| `/persona list\|<name>` | Switch conversation persona |
| `/provider` | Interactive provider/model picker |
| `/provider add\|edit\|remove\|test` | Provider configuration |
| `/switch <name>` | Quick provider switch |
| `/session save\|load\|list\|export` | Session management |
| `/session readonly\|offline\|normal` | Session security scopes |
| `/permissions allow\|list\|revoke` | Tool permission management |
| `/danger <tool>` | Temporarily approve dangerous tools |
| `/copy <text>\|--last` | Copy to clipboard |
| `/stats` | Session token/cost summary |
| `/model` | Show active provider details |
| `/reset` | Clear conversation |
| `/exit` | Quit and save session |
## Requirements
- **Rust 1.70+** (see [Install Rust & Cargo](#1-install-rust--cargo) above)
- **API key** for any OpenAI-compatible provider (OpenAI, OpenRouter, DeepSeek, etc.) — or Ollama for fully local use
- **Linux/macOS** terminal (Windows via WSL)
## Updating
```bash
cargo install cortex-agent --force
```
## Development
For contributors who want to hack on Cortex itself:
```bash
git clone https://github.com/shafiqul/cortex.git
cd cortex
cargo build --release
./target/release/cortex
```
## License
MIT