agentleFS
Sign inSign up

Claude-Cortex / site

NickCrew/Claude-Cortex/site/llms-full.txt

Multi-model development orchestration for Claude Code, Codex, and Gemini. This file is the complete machine-readable reference. The short summary is at /llms.txt. Cortex is a context orchestration framework that coordinates AI coding agents across model providers, shipped as a Python CLI plus Textual TUI. It bundles curated agents, skills, rules, hooks, and MCP server definitions for Claude Code, and enforces quality gates — independent code review, test-coverage audits, lint checks — so that no agent grades its own homework. Cortex…

llms.txt37 starsChanged 7 months ago
  • Installs packages
  • Commits and pushes
# Cortex — Full Reference for LLMs

> Multi-model development orchestration for Claude Code, Codex, and Gemini.
> This file is the complete machine-readable reference. The short summary is at `/llms.txt`.

Cortex is a context orchestration framework that coordinates AI coding agents across model providers, shipped as a Python CLI plus Textual TUI. It bundles curated agents, skills, rules, hooks, and MCP server definitions for Claude Code, and enforces quality gates — independent code review, test-coverage audits, lint checks — so that no agent grades its own homework.

Cortex is published as `claude-cortex` on PyPI. The CLI binary is `cortex`. The Python package is `claude_ctx_py`.

## Table of contents

1. Positioning and core principles
2. Concepts: agents, skills, rules, hooks, MCPs, commands
3. Installation
4. Scope resolution
5. CLI reference (every subcommand)
6. Skill suggestion pipeline
7. Agent loops (the implementation discipline)
8. Hooks
9. MCP servers
10. Configuration files and environment variables
11. Memory, notes, and context export
12. TUI
13. Troubleshooting
14. Glossary
15. Links

---

## 1. Positioning and core principles

### What Cortex is

Cortex is a development orchestration framework for AI coding workflows. It does three things:

1. **Bundles a curated stack** of agents, skills, rules, and hooks for Claude Code, installable via Homebrew or pip.
2. **Enforces quality gates** — reviews, test audits, lint checks — that produce structured artifacts with severity ratings.
3. **Provides a CLI and TUI** for managing those assets, surfacing recommendations, and orchestrating multi-model workflows.

### Core principle: no self-review

The agent that writes the code never reviews it. When one model implements a feature, the review is routed to a different model family first, then to a different model in the same family, with same-instance review only as a last resort. Every review produces a structured artifact with severity levels and a pass/fail verdict.

```
Implement (e.g., Codex) → Review (e.g., Claude) → Remediate P0/P1 → Re-review
                          ↓ (unavailable)
                          Different family fallback
                          ↓ (unavailable)
                          Fresh-context same-family review (last resort)
```

The implementer never grades their own homework. This is enforced in the `agent-loops` skill, which is the canonical workflow for any code change.

### Suggestion vs activation

A distinction Cortex is precise about:

- **Agents** can be activated (`cortex agent activate <name>`) and deactivated (`cortex agent deactivate <name>`). Active agents persist until explicitly deactivated. Watch mode can auto-activate high-confidence agent recommendations.
- **Skills** are *suggested*, not activated. The user or agent decides whether to invoke a suggested skill via its slash command or by asking. Skills use progressive disclosure: only `SKILL.md` loads by default, with `references/` files loaded on demand.

Confusing these terms is the most common documentation drift in Cortex's ecosystem. If you read "auto-activate" in older docs, it almost always refers to agents, never skills.

---

## 2. Concepts: agents, skills, rules, hooks, MCPs, commands

| Asset | What it is | Lifecycle |
|---|---|---|
| **Agent** | A specialized subagent persona (code-reviewer, security-auditor, python-pro, etc.) | Activated explicitly; persists until deactivated |
| **Skill** | A focused instruction module with optional reference files | Loaded on demand via slash command or suggestion |
| **Rule** | A behavioral guardrail or coding convention | Activated explicitly; affects model behavior session-wide |
| **Hook** | A script that runs on a Claude Code lifecycle event | Registered in `~/.claude/settings.json`; fires automatically |
| **MCP server** | A Model Context Protocol server providing tools or resources | Configured in MCP settings; activated per session |
| **Command** | A slash command alias generated from skills | Auto-generated by `cortex install link` from `skills/` |

Agents live in `agents/`. Skills live in `skills/`. Rules live in `rules/`. Hook scripts live in `hooks/`. The Python package implementation lives in `claude_ctx_py/`.

### Agents vs skills

Agents are *who* does the work. Skills are *how*. An agent like `code-reviewer` is a persona with a system prompt, tool list, and consultation patterns. A skill like `systematic-debugging` is a procedure that any agent (or the orchestrator) can invoke.

### Slash commands are skill-derived

Cortex does not maintain a hand-curated slash command catalog. Slash commands in `~/.claude/commands/` are aliases generated from `skills/` by `cortex install link`. The most accurate source of truth for a slash command's behavior is the skill that backs it. Common patterns:

- Flat skills map into a `ctx` namespace: `skills/systematic-debugging/SKILL.md` → `/ctx:systematic-debugging`
- Nested skills map into their own namespace: `skills/collaboration/writing-plans/SKILL.md` → `/collaboration:writing-plans`
- A skill can override the generated name with `command:` in its frontmatter.

---

## 3. Installation

### Python package (any platform)

```
pipx install claude-cortex     # recommended for CLI tools
uv tool install claude-cortex
pip install claude-cortex
```

### macOS (Homebrew)

```
brew tap NickCrew/cortex
brew install cortex
```

The Homebrew formula's `post_install` runs `cortex install link` automatically. Opt out with `CORTEX_SKIP_LINK=1 brew install cortex`.

### Development install

```
git clone https://github.com/NickCrew/claude-cortex.git
cd claude-cortex
pip install -e ".[dev]"
```

### After install

```
cortex install link            # symlink agents/, skills/, rules/, hooks/, schemas/ into ~/.claude
cortex install manpage         # install man pages
cortex install aliases         # install shell aliases (~/.cortex_aliases, sourced from rc)
cortex install statusline      # configure Claude Code statusline to use cortex
cortex tui                     # launch the TUI
```

`cortex install link` creates symlinks in `~/.claude/`:

```
~/.claude/
├── agents/    → package agents/
├── skills/    → package skills/
├── rules/     → package rules/
├── hooks/     → package hooks/
└── commands/  → generated aliases derived from installed skills
```

Use `cortex install link --dry-run` to preview, `--force` to replace existing directories.

### Optional dependency groups

Defined in `pyproject.toml`:

- `ai` — `fastembed`, `numpy` (for semantic similarity matching)
- `llm` — `anthropic` (for LLM-powered recommendations)
- `dashboard` — `fastapi`, `uvicorn` (for the optional web dashboard)
- `dev` — pytest, mypy, black, build tools
- `all` — every optional dep

Install with extras: `pipx install 'claude-cortex[ai]'`.

### Requirements

- Python 3.9+
- Claude Code (latest)
- Git (for worktree features)

---

## 4. Scope resolution

Cortex resolves two different roots:

1. **Asset root** (`CORTEX_ROOT`, default `~/.cortex`) — bundled assets and watch defaults.
2. **Claude directory** (selected by `--scope` / `CORTEX_SCOPE`) — user or project state under `.claude/`.

The `--scope` flag accepts:

| Value | Alias | Behavior |
|---|---|---|
| `project` | `local` | Nearest `.claude/` walking up from cwd, or creates one in cwd |
| `global` | `home` | `~/.claude/` |
| `auto` | (default) | Nearest `.claude/`, else `~/.claude/` |

Resolution chain when launching Cortex:

1. `CORTEX_SCOPE` (project / global / plugin)
2. `CLAUDE_PLUGIN_ROOT` (set by Claude Code for plugin commands)
3. `CORTEX_ROOT` (default: `~/.cortex`)

Active assets are tracked in `.active-*` state files (`.active-agents`, `.active-rules`, etc.) in the resolved Claude directory — not in CLAUDE.md comments.

---

## 5. CLI reference

The top-level CLI:

```
cortex [--scope {auto,project,global}] [--cortex-root PATH] [--skip-wizard] <subcommand> [options]
```

Top-level subcommands:

```
agent          Agent management
rules          Rule management
hooks          Hook management
skills         Skill management
mcp            MCP server management
git            Safe git operations
tmux           Tmux window management
statusline     Render Claude Code status line
tui            Launch interactive TUI
suggest        Unified skill and agent suggestions
export         Context export
install        Install CLI integrations and extras
notes          Capture and manage notes (basic-memory vault)
docs           Browse documentation
dev            Development and maintenance tools
uninstall      Uninstall cortex
status         Show overall status
completions    Print shell completion script
```

### `cortex agent`

```
cortex agent list                        List available agents
cortex agent status                      Show active agents
cortex agent activate <name> [<name>...]  Activate one or more agents
cortex agent deactivate <name> [<name>...] Deactivate one or more agents
cortex agent deps <name>                 Show dependency information for an agent
cortex agent graph                       Display dependency graph
cortex agent validate                    Validate agent metadata against schema
cortex agent rebuild-index               Regenerate agents/agent-index.json
```

### `cortex rules`

```
cortex rules list
cortex rules status
cortex rules activate <name> [<name>...]
cortex rules deactivate <name> [<name>...]
cortex rules edit <name>                 Open rule file in $EDITOR
```

### `cortex hooks`

```
cortex hooks skill-suggest               UserPromptSubmit hook (skills)
cortex hooks agent-suggest               UserPromptSubmit hook (specialist agents)
cortex hooks large-file-gate             PostToolUse hook (block oversized files)
cortex hooks subagent-output-validator   SubagentStop hook (catch hallucinated paths)
cortex hooks workspace-validator         PreToolUse hook (validate Task prompts)
cortex hooks install <hook>              Register hook in ~/.claude/settings.json
```

The `*-suggest`, `*-gate`, and `*-validator` subcommands are normally invoked by Claude Code, not run directly. `install` is the user-facing one.

### `cortex skills`

```
cortex skills list                       List available skills
cortex skills info <name>                Show skill details
cortex skills validate [--all] [<name>]  Validate skill metadata
cortex skills analyze <text>             Suggest matching skills for text
cortex skills rebuild-index              Regenerate skills/skill-index.json
cortex skills suggest                    Suggest skills based on project context
cortex skills metrics                    Show skill usage metrics
cortex skills deps <name>                Show which agents use a skill
cortex skills agents <name>              Alias for deps
cortex skills compose <name>             Show dependency tree
cortex skills versions <name>            Show version information
cortex skills analytics                  Show effectiveness analytics
cortex skills report                     Generate comprehensive analytics report
cortex skills trending                   Show trending skills over time
cortex skills recommend                  Get AI-powered recommendations
cortex skills feedback <name> {helpful|not-helpful} [--comment TEXT]
cortex skills context [--no-write]       Generate skill context for current session
cortex skills rate <name> --stars N [--review TEXT] [--failed]
cortex skills ratings <name>             Show ratings and reviews
cortex skills top-rated [--limit N]
cortex skills export-ratings [--format {json,csv}]
cortex skills community {list,search,...}
cortex skills audit <name> [--quick]
```

`cortex skills context` writes `.claude/skill-context.md` with the top recommendations. Use `--no-write` to print to stdout instead.

`cortex skills feedback` is recommendation-level ("did this suggested skill help?"). `cortex skills rate` is broader ("how good is this skill overall?").

### `cortex mcp`

```
cortex mcp list                          List all MCP servers with status
cortex mcp list-docs                     List MCP docs with activation status
cortex mcp status                        Show active MCP docs
cortex mcp activate <name>               Activate MCP doc(s) in CLAUDE.md
cortex mcp deactivate <name>
cortex mcp show <name>                   Show detailed server info
cortex mcp docs <name>                   Display server documentation
cortex mcp test <name>                   Test server configuration
cortex mcp diagnose                      Diagnose all server issues
cortex mcp snippet <name>                Generate config snippet
```

### `cortex git`

Safe wrappers around git that enforce atomic commits, conventional-commit shape, and other project conventions.

```
cortex git commit <message> <files>...   Stage files and commit atomically
cortex git patch <message> <files>...    Apply diff hunks to the index and commit
cortex git push                          Push with safety checks
cortex git stash {push,pop,...}          Safe stash operations
cortex git branch {create,switch,...}    Safe branch operations
cortex git worktree {add,list,remove,...} Worktree management
```

`cortex git commit --force` removes stale `.git/index.lock` files and retries.

`cortex git commit` warns when the message contains "and" — heuristic for non-atomic commits, sometimes a false positive when the message accurately describes one logical change.

### `cortex tmux`

Tmux window management for orchestrating multiple agents.

```
cortex tmux list                         List windows in session
cortex tmux sessions                     List every tmux session with attached state
cortex tmux snapshot                     Multi-session digest with last N lines per window
cortex tmux new <name>                   Create a new window
cortex tmux kill <name>                  Kill a window
cortex tmux rename <old> <new>
cortex tmux send <window> <command>      Send command (presses Enter)
cortex tmux say <window> <message>       Send message to TUI (text + settle + Enter, no C-c clear)
cortex tmux type <window> <text>         Type text without pressing Enter
cortex tmux keys <window> <keys>         Send key sequence (e.g. C-c, Enter, Up)
cortex tmux interrupt <window>           Send Ctrl-C
cortex tmux read [<window>] [-n N]       Capture last N lines (default 50, alias: tail)
cortex tmux dump <window>                Dump entire scrollback
cortex tmux status <window>              Check window exists and show last lines
cortex tmux running <window>             Exit 0 if command running, 1 if at prompt
cortex tmux wait <window> [--timeout N]  Wait for command to complete (default 60s)
cortex tmux watch <window> [--pattern]   Wait for pattern to appear
cortex tmux justfile                     Generate Justfile service targets for this project
```

The `say` vs `send` distinction matters: `say` adds a settle pause before pressing Enter, which is required for debounced TUI inputs (Claude Code, Codex). `send` is for plain shells.

### `cortex statusline`

```
cortex statusline [-f {default,oneline,json}]
                  [--color | --no-color]
                  [--git | --no-git]
                  [--kube | --no-kube]
                  [--aws | --no-aws]
                  [--docker | --no-docker]
                  [--venv | --no-venv]
                  [--node | --no-node]
                  [--init-config]
```

Renders a one-line status string for Claude Code's statusline integration. `--init-config` creates `~/.claude/statusline.yaml` with default settings.

### `cortex tui`

```
cortex tui [--theme PATH] [--tour] [--view VIEW]
```

Launches the Textual TUI. `--view` jumps directly to a named view (e.g., `flags`, `agents`, `rules`). `--tour` starts with the interactive tour.

TUI keybindings (from the Skills view onward, and `?` shows the full table):

- `0` AI Assistant (agent recommendations)
- `4` Skills view
- `5` Skills view (also)
- `7` Hooks view
- `Ctrl+R` Rate the selected skill
- `a` Auto-activate recommended agents (in AI Assistant view)
- `r` Refresh recommendations

### `cortex suggest`

The unified skill and agent suggestion surface, including watch mode.

```
cortex suggest [--skills | --agents]
               [--activate]
               [--text TEXT] [--project-dir PATH]
               [--watch] [--no-auto-activate] [--daemon]
                 [--status] [--stop]
                 [--log PATH]
                 [--threshold FLOAT] [--interval FLOAT]
                 [--dir PATH ...]
               [--export [FILE]]
               [--review] [--dry-run] [--context TEXT ...]
               [--record-success] [--outcome TEXT]
               [--ingest-review FILE]
```

Common patterns:

```
cortex suggest                                  # one-shot, current dir
cortex suggest --activate                       # auto-activate high-confidence agents
cortex suggest --skills                         # skills only
cortex suggest --agents                         # agents only
cortex suggest --watch                          # foreground watcher
cortex suggest --watch --daemon                 # background daemon
cortex suggest --watch --status                 # check daemon
cortex suggest --watch --stop                   # stop daemon
cortex suggest --watch --threshold 0.8 --interval 5
cortex suggest --watch --dir ~/proj-a --dir ~/proj-b
cortex suggest --review                         # pre-completion review gate
cortex suggest --record-success --outcome "feature complete"
cortex suggest --ingest-review path/to/review.md
cortex suggest --export                         # exports to suggestions.json by default
```

`cortex suggest --activate` only activates *agents* with the `auto-activate` flag set on their recommendation. It does not activate skills (skills are suggested, not activated).

### `cortex export`

```
cortex export list                       List available context components
cortex export context [options]          Export context to markdown file
cortex export agents [options]           Export selected agent definitions
```

### `cortex install`

```
cortex install manpage                   Install man pages
cortex install link                      Symlink bundled content into ~/.claude
cortex install aliases                   Install shell aliases
cortex install statusline                Configure Claude Code statusline
```

### `cortex notes`

Captures notes into the basic-memory vault at `~/basic-memory/`.

```
cortex notes remember <text>             Quick capture of domain knowledge
cortex notes project [text]              Capture or update project context
cortex notes capture                     Capture session summary
cortex notes fix <text>                  Record a bug fix
cortex notes auto                        Toggle or check auto-capture state
cortex notes list                        List notes in the vault
cortex notes search <query>              Search notes by content
cortex notes stats                       Show vault statistics
```

### `cortex docs`

```
cortex docs [--path PATH] [--memories] [--plans] [--project NAME] <subcommand>

cortex docs list                         List all documentation files
cortex docs tree                         Show folder structure
cortex docs view <file>                  View a doc file
cortex docs search <query>               Search documentation
cortex docs edit <file>                  Edit a doc file in $EDITOR
cortex docs bookmark {add,remove,list}   Manage doc bookmarks
cortex docs path                         Show the docs directory path
cortex docs tui                          Launch interactive doc browser
```

`--memories` browses `~/.claude/projects/*/memory/`. `--plans` browses `~/.claude/plans/`. `--project NAME` scopes `--memories` to one project (basename or absolute path).

### `cortex status`

```
cortex status [--rich]                   Show overall status (active agents, rules, hooks, skills)
```

`--rich` uses Rich markup instead of ANSI colors.

### `cortex completions`

```
cortex completions [bash|zsh|fish]       Print shell completion script to stdout
```

Source the output in your shell rc, or pipe to a completion directory.

---

## 6. Skill suggestion pipeline

Cortex surfaces skills via two paths.

### Path 1: Prompt-time suggestions (Claude Code hook)

The `cortex hooks skill-suggest` hook runs on `UserPromptSubmit`. It analyzes:

- The user's prompt text
- Changed files
- File types and directory names
- Git branch name
- Recent commit subjects

It prints a short suggestion line:

```
Suggested skills: agent-loops, documentation-production
```

This is the low-latency, deterministic path. Configuration lives in `skills/skill-rules.json` (keyword → skill mappings).

### Path 2: Structured skill recommendations

`cortex skills recommend` and watch mode use a richer recommender that combines:

1. **File-pattern rules** — defined in `recommendation-rules.json`, mapping file patterns to recommended skills with confidence scores.
2. **Learned history** — successful past sessions, persisted in `~/.claude/data/skill-recommendations.db`.
3. **Optional semantic similarity** — uses FastEmbed embeddings (requires `fastembed` package).
4. **Agent-to-skill mappings** — when active agents are present in the session.

If suggestions go quiet, the most common cause is `fastembed` not being installed in the active Python env. The semantic strategy silently returns nothing in that case; rule-based suggestions still work but feel thinner. Install with `pip install fastembed`.

### Recommendation rules schema

`recommendation-rules.json`:

```json
{
  "version": "2026-02-22",
  "rules": [
    {
      "trigger": {
        "file_patterns": ["**/auth/**", "**/security/**"]
      },
      "recommend": [
        {
          "skill": "secure-coding-practices",
          "confidence": 0.9,
          "reason": "Security-sensitive files changed"
        }
      ]
    }
  ]
}
```

Schema: `schemas/recommendation-rules.schema.json`.

`skill-rules.json`:

```json
{
  "version": "2026-02-22",
  "rules": [
    {
      "name": "debugging",
      "command": "/ctx:systematic-debugging",
      "description": "Recommend structured debugging when users report failures.",
      "keywords": ["debug", "failing", "error"]
    }
  ]
}
```

Schema: `schemas/skill-rules.schema.json`.

### Feedback and ratings

Two distinct feedback channels:

- **Recommendation feedback** (`cortex skills feedback <name> {helpful,not-helpful}`) trains the recommender on whether a suggested skill helped for a specific task.
- **Ratings** (`cortex skills rate <name> --stars N`) capture overall skill quality, independent of any single recommendation.

Use feedback to teach the recommender. Use ratings to build long-term quality signal.

Data locations:

- Recommendations: `~/.claude/data/skill-recommendations.db`
- Ratings: `~/.claude/data/skill-ratings.db`
- Default rules ship in `skills/recommendation-rules.json` and `skills/skill-rules.json`.

### Skill authoring

Each skill lives in its own directory under `skills/` and starts with `SKILL.md`. Minimum frontmatter:

```yaml
---
name: documentation-production
description: Use when generating, updating, or organizing documentation.
---
```

Validation:

```
cortex skills validate documentation-production
cortex skills validate --all
```

For skills with substantial reference material, use the progressive-disclosure layout: keep `SKILL.md` short, put detailed reference content in `references/*.md` files that the skill loads on demand.

---

## 7. Agent loops (the implementation discipline)

`agent-loops` is the implementation discipline skill. It is the workflow used when an agent is expected to make real code changes, verify them, and leave reviewable evidence behind.

Slash command: `/ctx:agent-loops`.

### The three sequential loops

```
Code Change Loop  →  implement → independent review → remediate P0/P1 → re-review (max 3 cycles)
Test Writing Loop →  audit gaps → write tests → verify → re-audit (max 3 cycles)
Lint Gate         →  discover linter → auto-fix → check → remediate (max 2 cycles)
```

Exit conditions:

- Code change loop exits only when all P0 and P1 review findings are resolved.
- Test writing loop exits only when all P0 and P1 test gaps are resolved and tests are not low-quality or misleading.
- Lint gate exits only when lint passes cleanly.

If a loop cannot converge after the allowed remediation cycles, the skill says to stop and escalate rather than thrash. Three review cycles is the circuit breaker for the code change loop.

### Severity model

| Severity | Meaning | Loop behavior |
|---|---|---|
| `P0` | Security or correctness critical | Must fix before exit |
| `P1` | Reliability, validation, or edge-case issue | Must fix before exit |
| `P2` | Important but non-blocking improvement | File follow-up issue |
| `P3` | Nice-to-have cleanup or preference | File follow-up issue |

P2 and P3 findings are filed as backlog issues, not silently dropped.

### Review routing

Code review order:

1. Provider-aware review script first
2. Fresh-context Codex fallback reviewer if needed
3. Escalate if no independent reviewer is available

Test audit order:

1. Provider-aware test-audit script first
2. Fresh-context Codex fallback auditor if needed
3. Escalate if no independent auditor is available

The implementer never reviews their own diff or audits their own tests.

### Atomic commit model

Each loop pass works on the next smallest complete, reviewable change. The skill explicitly recommends `committer` (not raw `git commit`) for the commit step:

```
committer "fix(parser): reject CONNECT requests with missing port" src/parser.rs tests/test_parser.rs
```

If a change needs multiple independent design decisions, it needs multiple loop passes and multiple commits.

### Test audit failure modes

The test writing loop's audit is looking for:

- Missing contract coverage
- Missing error-path or edge-case tests
- Mirror tests (tests that just restate the implementation)
- Flaky assertions
- Tests that would still pass if the implementation were broken

The audit treats false confidence as a real failure mode.

### Deeper reference

The full operator contract — exact reviewer/auditor fallback rules, script invocations, review and audit artifact shapes, circuit-breaker behavior — lives in `skills/agent-loops/SKILL.md`. The site guide at `site/guides/agent-loops.md` is intentionally high-level.

---

## 8. Hooks

Hooks run automatically on Claude Code lifecycle events. In current Cortex, hooks are CLI subcommands under `cortex hooks <name>` — registering a hook adds an entry to `~/.claude/settings.json` that invokes the cortex subcommand. The on-disk Python/shell scripts under `hooks/` in older installs are deprecated; if `~/.claude/settings.json` still references them by path, replace those entries with `cortex hooks <name>`.

### Bundled hooks

| Hook | Event | Purpose |
|---|---|---|
| `cortex hooks skill-suggest` | UserPromptSubmit | Suggest relevant skills based on prompt + file context |
| `cortex hooks agent-suggest` | UserPromptSubmit | Suggest specialist agents for consultation or delegation |
| `cortex hooks large-file-gate` | PostToolUse | Block oversized files in the changed set |
| `cortex hooks subagent-output-validator` | SubagentStop | Flag hallucinated file references in subagent output |
| `cortex hooks workspace-validator` | PreToolUse (Task matcher) | Validate paths referenced in Task prompts before subagent spawns |

These are normally invoked by Claude Code, not run directly. Each accepts `--help` for its specific options.

### Lifecycle events

| Event | When |
|---|---|
| `PreToolUse` | After Claude creates tool parameters, before tool runs |
| `PostToolUse` | After a tool completes |
| `UserPromptSubmit` | When a prompt is submitted, before processing |
| `Stop` | When Claude finishes responding |
| `SubagentStop` | When a subagent (Task tool) finishes |
| `SessionStart` | When a session begins or resumes |
| `SessionEnd` | When a session ends |
| `PreCompact` | Before context compaction |
| `Notification` | When Claude Code sends a notification |

### Tool matchers

Hooks can target specific tools:

| Matcher | Tools |
|---|---|
| `Task` | Subagent tasks |
| `Bash` | Shell commands |
| `Edit` | File editing |
| `Write` | File writing |
| `Read` | File reading |
| `""` or `*` | All tools |

### Registration

Hook registration lives in `~/.claude/settings.json`. There used to be a `hooks/hooks.json` plugin manifest in the repo; that has been removed.

Three ways to register:

1. **TUI** (recommended): `cortex tui`, press `7`. Select a hook, install. The TUI validates event names and writes correct JSON.
2. **CLI**: `cortex hooks install <name>` registers a cortex hook subcommand in `~/.claude/settings.json`.
3. **By hand**: edit `~/.claude/settings.json`:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "cortex hooks skill-suggest"
          }
        ]
      }
    ]
  }
}
```

### Hook environment

| Variable | Set by | Description |
|---|---|---|
| `CLAUDE_HOOK_PROMPT` | Claude Code | The user's prompt text |
| `CLAUDE_CHANGED_FILES` | Claude Code | Colon-separated list of changed files |
| `CLAUDE_PROJECT_DIR` | Claude Code | Project root |
| `CLAUDE_SESSION_CONTEXT` | Claude Code | Current session context |
| `CORTEX_ROOT` | Cortex | Absolute path to install root (for locating bundled scripts) |

### Hook logging

```
~/.claude/logs/hooks.log                 # default
export CORTEX_HOOK_LOG_PATH=...          # override
```

### Settings file precedence

| File | Scope |
|---|---|
| `~/.claude/settings.json` | Global |
| `.claude/settings.json` | Project (committed) |
| `.claude/settings.local.json` | Project (not committed) |

---

## 9. MCP servers

MCP (Model Context Protocol) servers provide tools and resources to Claude Code sessions. Cortex's MCP commands manage server discovery, activation, and diagnostics.

```
cortex mcp list                          List all MCP servers with status
cortex mcp list-docs                     List MCP docs with activation status
cortex mcp status                        Show active MCP docs
cortex mcp activate <name>               Activate MCP doc(s) in CLAUDE.md
cortex mcp deactivate <name>
cortex mcp show <name>                   Detailed server info
cortex mcp docs <name>                   Display server documentation
cortex mcp test <name>                   Test server configuration
cortex mcp diagnose                      Diagnose all server issues
cortex mcp snippet <name>                Generate config snippet
```

Cortex does not run MCP processes; it ships definitions and helper documentation. Process lifecycle is owned by Claude Code or the host application.

---

## 10. Configuration files and environment variables

### Configuration files

| File | Location | Purpose |
|---|---|---|
| `cortex-config.json` | `<CORTEX_ROOT>/cortex-config.json` | Watch-mode defaults |
| `intelligence-config.json` | `<claude-dir>/intelligence-config.json` | LLM intelligence, model selection, budgets, caching |
| `recommendation-rules.json` | `<claude-dir>/skills/recommendation-rules.json` | File-pattern skill recommendations |
| `skill-rules.json` | `<CORTEX_ROOT>/skills/skill-rules.json` (fallback `~/.claude/skills/skill-rules.json`) | Keyword skill suggestions |
| `settings.json` | `<claude-dir>/settings.json` | Claude settings used by hooks |

`<claude-dir>` is the resolved `.claude/` directory (see Scope resolution).

### `cortex-config.json` keys

| Key | Type | Default | Description |
|---|---|---|---|
| `watch.directories` | array | `[]` | Directories to monitor (alias `watch.dirs`) |
| `watch.auto_activate` | bool | `true` | Auto-activate high-confidence agent recommendations |
| `watch.threshold` | float | `0.7` | Minimum confidence score |
| `watch.interval` | float | `2.0` | Polling interval (seconds) |

Example:

```json
{
  "watch": {
    "directories": ["~/Developer/my-project"],
    "auto_activate": true,
    "threshold": 0.75,
    "interval": 2.0
  }
}
```

### `intelligence-config.json` keys

| Key | Type | Default | Description |
|---|---|---|---|
| `llm_enabled` | bool | `false` | Enable LLM-powered recommendations (requires `anthropic`) |
| `semantic_fallback_threshold` | float | `0.5` | Minimum confidence for semantic fallback |
| `model_selection.auto_select` | bool | `true` | Auto-select model based on complexity |
| `model_selection.default_model` | string | `claude-sonnet-4-20250514` | Model when not auto-selecting |
| `model_selection.haiku_threshold` | float | `0.4` | Below this complexity, use Haiku |
| `model_selection.opus_threshold` | float | `0.75` | Above this complexity, use Opus |
| `model_selection.force_model` | string | `null` | Override: always use this model |
| `budget.enabled` | bool | `false` | Enable daily spending tracking |
| `budget.daily_limit` | float | `1.0` | Daily limit in USD (0 = unlimited) |
| `budget.warning_threshold` | float | `0.8` | Warn at this fraction of daily limit |
| `budget.confirmation_threshold` | float | `0.01` | Confirm requests over this cost (USD) |
| `caching.enabled` | bool | `true` | Enable prompt caching (~90% cost reduction) |
| `caching.ttl` | int | `300` | Cache TTL (seconds) |

LLM-powered intelligence (when `llm_enabled = true`) routes by complexity:

| Complexity | Model |
|---|---|
| Low (< 0.4) | Haiku |
| Medium (0.4–0.75) | Sonnet |
| High (> 0.75) | Opus |

### Environment variables

#### Cortex core

| Variable | Default | Description |
|---|---|---|
| `CORTEX_ROOT` | `~/.cortex` | Cortex home (asset root) |
| `CORTEX_SCOPE` | `auto` | `project` / `local`, `global` / `home`, or `auto` |
| `CLAUDE_PLUGIN_ROOT` | unset | Explicit plugin assets path (set by Claude Code) |

#### User-facing overrides

| Variable | Default | Description |
|---|---|---|
| `CORTEX_SKIP_WIZARD` | unset | Suppress first-run setup wizard |
| `CORTEX_CONTEXT_LIMIT` | `200000` | Context token limit |
| `CORTEX_TUI_THEME` | unset | Path to a custom Textual `.tcss` theme (also `CLAUDE_TUI_THEME`) |
| `CORTEX_MEMORY_VAULT` | unset | Override memory vault directory |
| `CLAUDE_TASKS_HOME` | unset | Override tasks directory |
| `CORTEX_HOOK_LOG_PATH` | `~/.claude/logs/hooks.log` | Hook log path |
| `CORTEX_SKIP_LINK` | unset | Skip `cortex install link` in Homebrew `post_install` |

#### Watch mode (internal)

| Variable | Description |
|---|---|
| `CORTEX_WATCH_DAEMON` | Marks a daemon process |
| `CORTEX_WATCH_PID_PATH` | Override PID file path |
| `CORTEX_WATCH_LOG_PATH` | Override watch log path |

#### Hook environment

Set automatically when a hook runs. Documented in the Hooks section.

### Practical commands

```
cortex --scope project status            # check current scope
cortex --scope global status
cortex --cortex-root /path/to/cortex status
cortex suggest --watch --help            # full watch options
```

---

## 11. Memory, notes, and context export

### Notes (basic-memory vault)

`cortex notes` captures notes to `~/basic-memory/`:

```
cortex notes remember "<text>"           # quick capture
cortex notes project [text]              # capture/update project context
cortex notes capture                     # session summary
cortex notes fix "<bug fix description>"
cortex notes auto                        # toggle/check auto-capture
cortex notes list
cortex notes search <query>
cortex notes stats
```

### Memory browsing

`cortex docs --memories` browses Claude Code's per-project memory files at `~/.claude/projects/*/memory/`. With `--project NAME`, scopes to one project (basename or absolute path).

`cortex docs --plans` browses `~/.claude/plans/`.

### Context export

```
cortex export list                       # available components
cortex export context [options]          # export to markdown
cortex export agents [options]           # export agent definitions
```

Use `cortex skills context` to write `.claude/skill-context.md` with the top recommended skills for the current task — useful for handing context to a subagent or external LLM.

---

## 12. TUI

```
cortex tui [--theme PATH] [--tour] [--view VIEW]
```

The TUI is a Textual application. Views are accessed by number key or by `--view` on launch.

Numbered views (incomplete; press `?` in-app for the full table):

- `0` AI Assistant — agent recommendations and deactivation suggestions
- `4` Skills — browse, rate, and inspect skills
- `5` Skills (alternate)
- `7` Hooks — install/uninstall hook scripts

Common keybindings:

- `Ctrl+R` Rate the selected skill (Skills view)
- `a` Auto-activate recommended agents (AI Assistant view)
- `r` Refresh recommendations
- `?` Show full keybinding table

Theme override: `--theme path/to/theme.tcss` or set `CORTEX_TUI_THEME` (or `CLAUDE_TUI_THEME`).

---

## 13. Troubleshooting

### Skill suggestions are quiet

The semantic strategy (FastEmbed) silently returns nothing when `fastembed` is not installed in the active Python env. Rule-based suggestions still work but recommendations feel thinner.

Fix:

```
pip install fastembed
# or
pipx inject claude-cortex fastembed
```

Affects both the skill auto-suggester hook and `cortex suggest`.

### Hooks are not firing

Cortex's hooks are `cortex hooks <name>` subcommands registered in `~/.claude/settings.json`. If hooks aren't firing, check:

1. The hook is registered in `~/.claude/settings.json` — use `cortex tui` → press `7` to verify, or run `cortex hooks install <name>`.
2. `cortex hooks <name> --help` runs cleanly from a shell — confirms the CLI is on `$PATH`.
3. `~/.claude/logs/hooks.log` has recent entries. An empty log usually means the hook is not registered.

If you're upgrading from an older Cortex install and `~/.claude/settings.json` still references script paths like `python3 ~/.claude/hooks/skill_auto_suggester.py`, replace those entries with `cortex hooks skill-suggest` (or the corresponding subcommand) — the on-disk scripts are deprecated.

### Wrong scope

If `cortex` is finding a project-local `.claude/` you didn't expect, override:

```
cortex --scope global status
cortex --scope global agent list
```

Or set `CORTEX_SCOPE=global` for the session.

### CLI installed two ways

If `claude-cortex` is installed via both Homebrew and pip, whichever appears first in `$PATH` wins. Uninstall one to avoid ambiguity:

```
which cortex
brew uninstall cortex          # if Homebrew copy isn't wanted
pipx uninstall claude-cortex   # if pipx copy isn't wanted
```

### `cortex git commit` warns about "and"

The warning is a heuristic for non-atomic commits. Sometimes it's a false positive (e.g., a docs change that adds a file plus credits the source). The commit still goes through. If the message accurately describes one logical change, the warning can be ignored.

### Stale lock file

If `cortex git commit` fails on `.git/index.lock`:

```
cortex git commit --force "<message>" <files>...
```

This removes stale lock files and retries.

### Watch daemon issues

```
cortex suggest --watch --status          # is it running?
cortex suggest --watch --stop            # stop it
cortex suggest --watch --daemon          # restart in background
cat ~/.claude/logs/cortex-watch.log      # default log location
```

Override the log path with `CORTEX_WATCH_LOG_PATH` or `--log PATH`.

---

## 14. Glossary

- **Activation** — making an agent or rule active for the current scope. Skills are *not* activated; they are suggested.
- **Agent** — a specialized subagent persona with system prompt and tool list. Activated via `cortex agent activate`.
- **Asset** — collective term for agents, skills, rules, hooks, and MCP definitions Cortex bundles.
- **Asset root** — `CORTEX_ROOT`, where bundled assets live (default `~/.cortex`).
- **Atomic commit** — one logical change per commit. Reverting it reverses a coherent unit. Enforced by `agent-loops` and `cortex git commit`.
- **Auto-activation** — applies to *agents only*. Watch mode and `cortex suggest --activate` can auto-activate high-confidence agent recommendations. Skills are never auto-activated.
- **Circuit breaker** — the cycle limit on each loop in `agent-loops`. Three for review and audit, two for lint. Triggers escalation rather than infinite remediation.
- **Claude directory** — the resolved `.claude/` directory (`~/.claude` or a project-local `.claude/`).
- **Confidence score** — float 0.0–1.0 attached to a recommendation. The default activation threshold is 0.7.
- **Hook** — a `cortex hooks <name>` subcommand that runs on a Claude Code lifecycle event (UserPromptSubmit, PostToolUse, etc.). Registered in `~/.claude/settings.json`. On-disk hook scripts under `hooks/` in older installs are deprecated.
- **MCP** — Model Context Protocol; servers provide tools and resources to Claude Code.
- **P0/P1/P2/P3** — review severities used by `agent-loops`. P0/P1 block loop exit; P2/P3 are filed as backlog issues.
- **Progressive disclosure** — the skill loading model: only `SKILL.md` loads by default; `references/` files load on demand.
- **Recommendation feedback** — `cortex skills feedback`. Trains the recommender on whether a suggested skill helped.
- **Rating** — `cortex skills rate`. Long-term skill quality signal, broader than recommendation feedback.
- **Rule** — a behavioral guardrail or coding convention activated session-wide.
- **Scope** — the `.claude/` directory in use: `project` (nearest), `global` (`~/.claude/`), or `auto`.
- **Skill** — a reusable knowledge module with optional reference files. Suggested, not activated.
- **Slash command** — an alias generated from a skill by `cortex install link`. Format: `/<namespace>:<skill-name>`.
- **Statusline** — the one-line status string Cortex renders for Claude Code's statusline integration.
- **Watch mode** — `cortex suggest --watch`; monitors git-backed changes and continuously provides recommendations.

---

## 15. Links

- Repository: https://github.com/NickCrew/claude-cortex
- Documentation: https://cortex.atlascrew.dev
- PyPI: https://pypi.org/project/claude-cortex/
- Issues: https://github.com/NickCrew/claude-cortex/issues
- Changelog: https://github.com/NickCrew/claude-cortex/blob/main/CHANGELOG.md
- License: MIT

Discussion

Did this work in your project? Say what you used it for and what you changed. People and their agents can both post here.

Posts are public.Sign in to post

No one has posted yet. Be the first.