Metadata-Version: 2.4
Name: cortexcode
Version: 0.10.0
Summary: Lightweight code indexing for AI assistants — build a searchable codegraph and grounded context
Author-email: Naveen <naveen_joshi07@outlook.com>
License: MIT
Project-URL: Homepage, https://github.com/naveen-joshi/cortexcode
Project-URL: Repository, https://github.com/naveen-joshi/cortexcode
Project-URL: Documentation, https://github.com/naveen-joshi/cortexcode#readme
Project-URL: Issues, https://github.com/naveen-joshi/cortexcode/issues
Project-URL: Changelog, https://github.com/naveen-joshi/cortexcode/blob/main/CHANGELOG.md
Project-URL: VSCodeMarketplace, https://marketplace.visualstudio.com/items?itemName=cortexcode.cortexcode-vscode
Keywords: code-index,ast,copilot,cursor,rag,ai-assistant,tree-sitter,code-analysis,token-savings,context-provider
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Documentation
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Indexing
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: tree-sitter>=0.21.0
Requires-Dist: tree-sitter-python>=0.23.0
Requires-Dist: tree-sitter-javascript>=0.23.0
Requires-Dist: tree-sitter-typescript>=0.23.0
Requires-Dist: tree-sitter-go>=0.23.0
Requires-Dist: tree-sitter-rust>=0.23.0
Requires-Dist: tree-sitter-java>=0.23.0
Requires-Dist: tree-sitter-c-sharp>=0.23.0
Requires-Dist: click>=8.1.0
Requires-Dist: questionary>=2.0.1
Requires-Dist: watchdog>=4.0.0
Requires-Dist: rich>=13.0.0
Requires-Dist: pyyaml>=6.0.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: ruff>=0.3.0; extra == "dev"
Provides-Extra: ai
Requires-Dist: tiktoken>=0.7.0; extra == "ai"
Requires-Dist: openai>=1.0.0; extra == "ai"
Requires-Dist: anthropic>=0.18.0; extra == "ai"
Requires-Dist: google-generativeai>=0.4.0; extra == "ai"
Requires-Dist: requests>=2.31.0; extra == "ai"
Provides-Extra: mobile
Requires-Dist: tree-sitter-kotlin>=0.1.0; extra == "mobile"
Requires-Dist: tree-sitter-swift>=0.6.0; extra == "mobile"
Dynamic: license-file

<p align="center">
  <h1 align="center">CortexCode</h1>
  <p align="center">
    <strong>Lightweight code indexing for AI assistants</strong><br>
    Build a searchable codegraph, generate documentation, and give AI assistants grounded context.
  </p>
</p>

---

## The Problem

AI coding assistants (Copilot, Cursor, Windsurf, etc.) need to understand your codebase. The current approach: **dump entire source files into the context window**. This is:

- **Noisy** — Important signals are buried inside large files
- **Fragile** — Assistants miss architecture, relationships, and runtime surface area
- **Hard to reuse** — Raw file dumps do not become a durable project map

## The Solution

CortexCode indexes your codebase using **AST parsing** (tree-sitter) and builds a structured, searchable codegraph. You can explore symbols, trace flows, generate docs and diagrams, produce CodeWiki pages, and connect AI tools through MCP.

```
┌─────────────────────────────────────────────────┐
│  Without CortexCode          With CortexCode    │
│                                                  │
│  Raw files only    →         Searchable codegraph │
│  Manual digging    →         Linked symbols       │
│  Ad-hoc prompts    →         Reusable context     │
│  No project map    →         Docs + diagrams      │
└─────────────────────────────────────────────────┘
```

Run `cortexcode index` on your project to generate the codegraph and start exploring.

## Quick Start

```bash
# Install from PyPI
pip install cortexcode

# Or install from source
git clone https://github.com/cortexcode/cortexcode.git
cd cortexcode && pip install -e .

# Index your project
cd your-project
cortexcode index

# Get context for AI
cortexcode context "handleAuth"

# Generate interactive docs
cortexcode docs --open
```

### Post-Index Wizard

After running `cortexcode index`, an interactive wizard can guide you through generating outputs:

```bash
cortexcode index              # Run index, then wizard prompts
cortexcode index --force-wizard   # Force wizard in non-TTY mode
cortexcode index --no-post-index-wizard  # Skip wizard
```

**Wizard features:**
- Multi-select checkbox for docs, diagrams, AI docs, CodeWiki, reports, visualization, dashboard, MCP setup
- Smart recommendations based on detected project shape
- Follow-up prompts for diagram types, AI doc types, wiki options
- Preference persistence — saves your choices for future runs

## Features

### Multi-Language AST Indexing

Parses source code into structured symbols using tree-sitter grammars.

| Language | Extensions | Frameworks Detected |
|----------|-----------|-------------------|
| Python | `.py` | FastAPI, Django |
| JavaScript | `.js`, `.jsx` | React, Express, Angular |
| TypeScript | `.ts`, `.tsx` | Next.js, NestJS, Angular |
| Go | `.go` | — |
| Rust | `.rs` | — |
| Java | `.java` | Spring Boot |
| C# | `.cs` | ASP.NET |

### What Gets Indexed

- **Symbols** — Functions, classes, methods with parameters and return types
- **Call Graph** — Which functions call which (and who calls them)
- **Imports/Exports** — Module dependencies
- **API Routes** — Express, FastAPI, NestJS, Spring Boot endpoints
- **Entities** — Database models and ORM definitions
- **Framework Detection** — React components, Angular services, etc.

### Project Exploration & Context

Use CortexCode to inspect structure and answer practical questions about a codebase:

- **Context lookup** — Pull relevant symbols and files for a query
- **Call graph tracing** — Follow how behavior moves across modules
- **Architecture visibility** — Inspect routes, entities, dependencies, and layers
- **Reusable index** — Keep a structured project map that tools can build on

### Interactive HTML Documentation

Generate a full interactive documentation site with:

- **File tree** browser
- **Symbol list** with filtering
- **D3.js call graph** visualization (draggable nodes)
- **Global search** across all symbols
- **Import/Export** browser
- **API route** listing
- **Framework** detection summary

```bash
cortexcode docs --open
```

### CodeWiki — AI-Powered Documentation Site

Generate a multi-page **CodeWiki** documentation site powered by AI (Gemini, OpenAI, Anthropic, or Ollama):

```bash
cortexcode wiki                    # Generate with default AI provider
cortexcode wiki --provider google  # Use Gemini
cortexcode wiki --open             # Generate and open in browser
cortexcode wiki --no-modules       # Skip per-module pages (faster)
```

**Features:**
- **AI-generated pages** — Overview, Architecture, Code Flows, API Reference, Concepts Guide
- **Per-module docs** — Each Python/JS file gets AI-generated documentation
- **Mermaid diagrams** — Auto-generated flow diagrams
- **Concept mapping** — Maps technical concepts to symbols and files
- **Concept search** — Ask "how does authentication work?" and get grounded answers

**Output:** `.cortexcode/wiki/index.html` — Open directly or serve locally.

### Incremental Indexing

Only re-index files that changed since last run:

```bash
cortexcode index -i    # Skip unchanged files
```

### VS Code Extension

Install from: [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=cortexcode.cortexcode-vscode)

The bundled VS Code extension provides:

- **Hover tooltips** — Hover any symbol to see type, params, callers
- **Go to definition** — Ctrl+Click using indexed data
- **Context panel** — View symbol details in a side panel
- **Status bar** — Shows indexed symbol count

```bash
cd cortexcode-vscode
npm install && npm run compile
# Press F5 to launch in VS Code
```

## Commands

CortexCode supports both a short form (`cc`) and full form (`cortexcode`). Commands are organized into logical groups.

### Core Commands

| Command | Description |
|---------|-------------|
| `cc index [path]` | Index a directory |
| `cc index -i` | Incremental index (changed files only) |
| `cc config` | Manage CortexCode configuration |
| `cc workspace init` | Initialize a multi-repo workspace |
| `cc workspace add <path>` | Add a repo to the workspace |
| `cc workspace list` | List repos in workspace |
| `cc workspace index` | Index all workspace repos |
| `cc workspace search <q>` | Search symbols across all repos |

### Analyze — Code Exploration & Analysis

| Command | Description |
|---------|-------------|
| `cc analyze context [query]` | Get relevant context for AI |
| `cc analyze context [query] --tokens` | Show context size estimates for a query |
| `cc analyze search [query]` | Grep-like symbol search with type/file filters |
| `cc analyze find [query]` | Semantic search by meaning ("auth handler") |
| `cc analyze diff` | Show changed symbols since last commit |
| `cc analyze diff --ref HEAD~3` | Compare against any git ref |
| `cc analyze stats` | Show project index and analysis stats |
| `cc analyze scan` | Scan dependencies for security warnings |
| `cc analyze trace <symbol>` | Trace code flow through call graph |
| `cc analyze flow <concept>` | Analyze code flow grouped by file |
| `cc analyze dead-code` | Detect potentially unused symbols |
| `cc analyze complexity` | Analyze code complexity (cyclomatic, nesting, line count) |
| `cc analyze complexity --min-score 50` | Show only high-complexity functions |
| `cc analyze impact <symbol>` | Change impact analysis — what breaks if you modify a symbol |
| `cc analyze explain <symbol>` | Explain a symbol using AI |

### Generate — Documentation & Visualization

| Command | Description |
|---------|-------------|
| `cc generate docs --open` | Generate and open interactive docs |
| `cc generate diagrams` | Generate Mermaid diagrams |
| `cc generate diagrams --viz` | Interactive D3.js visualization |
| `cc generate report` | Show interactive project report in terminal |
| `cc generate ai-docs` | Generate AI-powered documentation |
| `cc generate wiki` | Generate CodeWiki documentation site with AI |

### AI — Natural Language Code Understanding

| Command | Description |
|---------|-------------|
| `cc ai ask "question"` | Ask a natural language question about the codebase |
| `cc ai explain <symbol>` | Explain a symbol using AI |
| `cc ai docs` | Generate AI-powered documentation |
| `cc ai wiki` | Generate CodeWiki documentation site with AI |

### Serve — Long-Running Services

| Command | Description |
|---------|-------------|
| `cc serve watch` | Auto-reindex on file changes |
| `cc serve dashboard` | Launch live dashboard with auto-refresh |
| `cc serve lsp` | Start Language Server Protocol server |

### Integration & Automation

| Command | Description |
|---------|-------------|
| `cc mcp start` | Start MCP server for AI agent integration |
| `cc mcp setup` | Configure MCP for IDEs (auto-detect) |
| `cc githook install` | Install git hook for auto-indexing |
| `cc githook precommit` | Install pre-commit hook for security scanning |
| `cc bundle export` | Export index as shareable `.ccb` bundle |
| `cc bundle import <file>` | Import a `.ccb` bundle |
| `cc bundle info <file>` | Show bundle info without importing |
| `cc package index <name>` | Index an external package (pip, npm) |
| `cc jobs list` | List background jobs |
| `cc completion install` | Install shell completion |

### Shortcuts (Legacy)

These commands still work but show a tip to use the grouped form:

```bash
cc trace <symbol>      # Tip: use cc analyze trace
cc wiki                # Tip: use cc ai wiki
cc ask "question"     # Tip: use cc ai ask
```

## How AI Agents Use This

### Windsurf / Cursor Configuration

To make AI agents in Windsurf or Cursor automatically use CortexCode:

**Option 1: Auto-detect prompt file**

Create `.cortexcode/prompt.md` in your project root. AI agents will automatically read this file and use the CortexCode index for code understanding.

**Option 2: Add to agent rules**

Add to your project's `.windsurf/rules.md` or Cursor rules:

```
Always use CortexCode index (.cortexcode/index.json) to understand the codebase before making changes. Use:
- cortexcode search <symbol> to find symbols
- cortexcode impact <symbol> to see what uses a function
- cortexcode context <query> to get relevant code context

Run 'cortexcode index' first if the index doesn't exist.
```

**Option 3: Configure MCP in Windsurf**

Add to `~/.windsurf/config.json`:

```json
{
  "mcpServers": {
    "cortexcode": {
      "command": "cortexcode",
      "args": ["mcp"]
    }
  }
}
```

### 1. Context Command (simplest)

```bash
# Paste this output into your AI chat
cortexcode context "useAuth"
```

### 2. JSON Index (programmatic)

```python
import json

index = json.load(open('.cortexcode/index.json'))

# Get all functions
for path, data in index['files'].items():
    for sym in data['symbols']:
        print(f"{sym['type']}: {sym['name']} in {path}:{sym['line']}")

# Trace call graph
for caller, callees in index['call_graph'].items():
    for callee in callees:
        print(f"{caller} -> {callee}")
```

### 3. MCP Server

AI agents can query the index directly via the Model Context Protocol:

```bash
# Start the MCP server (stdin/stdout)
cortexcode mcp
```

**Configuration Examples:**

```json
// Claude Desktop (claude_desktop_config.json)
{
  "mcpServers": {
    "cortexcode": {
      "command": "cortexcode",
      "args": ["mcp"]
    }
  }
}

// Cursor / Windsurf
{
  "mcpServers": {
    "cortexcode": {
      "command": "cortexcode",
      "args": ["mcp"]
    }
  }
}

// Open WebUI / AnythingLLM
{
  "mcpServers": {
    "cortexcode": {
      "command": "cortexcode",
      "args": ["mcp"]
    }
  }
}
```

Available MCP tools (17 tools):

**Search & Navigation:**
- **`cortexcode_search`** — Search symbols by name
- **`cortexcode_fuzzy_search`** — Fuzzy/approximate search (handles typos)
- **`cortexcode_regex_search`** — Regex pattern search (e.g. `^get.*`)
- **`cortexcode_context`** — Get rich context with callers/callees
- **`cortexcode_file_symbols`** — List all symbols in a file
- **`cortexcode_call_graph`** — Trace call graph for a symbol

**Analysis:**
- **`cortexcode_deadcode`** — Find potentially unused symbols
- **`cortexcode_complexity`** — Find most complex functions
- **`cortexcode_impact`** — Analyze change impact of a symbol
- **`cortexcode_duplicates`** — Detect duplicate/copy-paste code
- **`cortexcode_circular_deps`** — Find circular dependencies

**Security & Quality:**
- **`cortexcode_security_scan`** — Scan for hardcoded secrets, SQL injection, XSS
- **`cortexcode_endpoints`** — Extract API endpoints (Express, Flask, Django, Next.js, etc.)
- **`cortexcode_api_docs`** — Auto-generate API docs from signatures

**Project Info:**
- **`cortexcode_stats`** — Get project statistics
- **`cortexcode_diff`** — Get changed symbols since last commit
- **`cortexcode_file_deps`** — Get file dependency graph

### 4. LSP Server

Any LSP-compatible editor can use CortexCode for hover, go-to-definition, and document symbols:

```bash
cortexcode lsp
```

### 5. Git Diff Context

See only what changed — perfect for code review:

```bash
# What symbols changed since last commit?
cortexcode diff

# Compare against a branch
cortexcode diff --ref main
```

### 6. Copilot Chat (`@cortexcode`)

In VS Code with the CortexCode extension, use `@cortexcode` in Copilot Chat:

```
@cortexcode search handleAuth
@cortexcode /context authentication
@cortexcode /impact createUser
@cortexcode /deadcode
@cortexcode /complexity
```

Commands:
- **`/search`** — Find symbols by name
- **`/context`** — Get ranked context for a query (relevance + call graph connectivity)
- **`/impact`** — Change impact analysis (direct/indirect callers, affected files/tests)
- **`/deadcode`** — List potentially unused symbols
- **`/complexity`** — Show most complex functions by params + outgoing calls

### 7. Semantic Search

Find symbols by meaning, not just name:

```bash
cortexcode find "authentication handler"
cortexcode find "database models"
cortexcode find "user login flow"
```

### 8. Code Analysis

```bash
# Find unused symbols
cortexcode dead-code

# Show top 10 most complex functions
cortexcode complexity --top 10

# What breaks if I change createUser?
cortexcode impact createUser
```

## Index Format

The index is stored at `.cortexcode/index.json`:

```json
{
  "project_root": "/path/to/project",
  "last_indexed": "2024-03-01T12:00:00",
  "languages": ["javascript", "typescript", "python"],
  "files": {
    "src/auth.ts": {
      "symbols": [
        {
          "name": "AuthService",
          "type": "class",
          "line": 10,
          "params": [],
          "calls": ["validateToken", "hashPassword"]
        }
      ],
      "imports": [{ "module": "bcrypt", "imported": ["hash", "compare"] }],
      "exports": [{ "name": "AuthService", "type": "class" }],
      "api_routes": [{ "method": "POST", "path": "/auth/login" }]
    }
  },
  "call_graph": {
    "AuthService": ["validateToken", "hashPassword"],
    "validateToken": ["jwt.verify"]
  }
}
```

## Configuration

CortexCode respects `.gitignore` files (including nested ones) and has built-in ignore patterns for:

- `node_modules/`, `__pycache__/`, `.git/`
- Build directories (`dist/`, `build/`, `.next/`)
- IDE files (`.idea/`, `.vscode/`)
- Package manager files (`vendor/`, `.venv/`)

## Roadmap

- [x] MCP server for direct AI agent integration
- [x] Semantic search over symbols (TF-IDF + synonym expansion)
- [x] Cross-file type inference
- [x] Git diff-aware context (show only changed symbols)
- [x] Language server protocol (LSP) support
- [x] Dependency vulnerability scanning
- [x] CI/CD integration (GitHub Action)
- [x] Multi-repo workspace support
- [x] Custom plugin system for framework-specific extractors
- [x] Web dashboard for index visualization
- [x] Flutter/Dart language support (regex-based)
- [x] React Native / Expo framework detection
- [x] Native Android (Kotlin/Java) framework detection
- [x] Native iOS (Swift/SwiftUI/UIKit) framework detection
- [x] Django / Flask framework detection
- [x] VS Code Marketplace publishing
- [x] Interactive graph visualization (`cc generate diagrams --viz`)
- [x] MCP setup wizard (`cc mcp setup`)
- [x] Pre-indexed bundles (`.ccb` files)
- [x] Package indexing (`cc package index`)
- [x] Background job tracking (`cc jobs`)
- [x] AI-powered CodeWiki documentation site
- [x] Natural language code Q&A (`cc ai ask`)
- [x] Flow tracing & concept analysis (`cc analyze trace`, `cc analyze flow`)
- [x] Git hook integration (auto-index, pre-commit security scan)
- [x] Shell completion (bash, zsh, fish, PowerShell)
- [x] Short CLI alias (`cc`)
- [x] Grouped CLI commands (`analyze`, `generate`, `serve`, `ai`)
- [x] Config file (`.cortexcode.yaml`) for project settings
- [x] Bug detection (pattern matching for security, quality, performance)
- [x] Project website (Astro + Tailwind, Vercel)
- [x] Cookbook with practical recipes

### Future Improvements

#### Features
- [ ] More language support (Ruby, PHP, C++)
- [ ] Cloud index for team sharing
- [ ] Index versioning (compare across commits)
- [ ] Codebase chatbot (conversational Q&A over index)

#### Integrations
- [ ] JetBrains IDEs plugin (IntelliJ, PyCharm)
- [ ] GitHub Copilot native integration
- [ ] Claude Code integration

#### AI/Search
- [ ] Semantic embeddings for meaning-based search
- [ ] AI-powered code review
- [ ] AI-suggested refactoring

#### Performance
- [ ] Compressed index format
- [ ] Faster search with caching
- [ ] Parallel multi-threaded indexing

## Cookbook

See [COOKBOOK.md](COOKBOOK.md) for practical recipes — from first-time setup to CI/CD integration, team collaboration, and advanced workflows.

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

```bash
# Development install
pip install -e ".[dev]"

# Run tests
pytest

# Lint
ruff check cortexcode/
```

## License

MIT — See [LICENSE](LICENSE)
