Metadata-Version: 2.2
Name: projectbrain-mcp
Version: 0.8.2
Summary: Universal 6D Behavioral IR, Pure SQLite Graph-as-Storage (FTS5 + Recursive CTE + Delta Overlay), Polyglot AST Slicer (Py/TS/Go/Rust/Java/SQL), and Symbol-Anchored Patch Engine for AI Coding Agents
License: MIT
Keywords: ai,agents,mcp,ast,tree-sitter,context-compression,code-graph,sqlite,fts5,static-analysis,llm
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Code Generators
Classifier: Topic :: Software Development :: Compilers
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: mcp
Requires-Dist: tree-sitter>=0.23
Requires-Dist: tree-sitter-python
Requires-Dist: tree-sitter-javascript
Requires-Dist: tree-sitter-typescript
Requires-Dist: tree-sitter-go
Requires-Dist: tree-sitter-rust
Requires-Dist: tree-sitter-java
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"

# ProjectBrain (`projectbrain-mcp` v0.8.2)

[![PyPI](https://img.shields.io/pypi/v/projectbrain-mcp.svg)](https://pypi.org/project/projectbrain-mcp/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)

**Local-First 6D AST Coordinate Matrix, Pure SQLite Graph-as-Storage (`.projectbrain.db`), Polyglot Context Compiler, and Symbol-Anchored Patch Engine for AI Coding Agents.**

Instead of forcing LLMs to search repositories as flat 1D text files (running `rg`/`grep` and reading dozens of overlapping `read_file` windows), ProjectBrain indexes your codebase across **Python, TypeScript/JavaScript/React, Go, Rust, Java, and SQL** into a **6D AST Coordinate Matrix** and a **Pure SQLite WAL Property Graph (`.projectbrain.db`)** using pre-compiled `tree-sitter` C wheels—no external database daemon, no Docker, no cloud vector embeddings, and no API keys required:

- **6D AST Coordinate Matrix (`X × Y × Z × W × E/T × C`):** Decomposes files and monolith components into atomic AST cells indexed across six orthogonal dimensions:
  - **`D1: X_scope` (Lexical / Structural Scope):** Outer function, class/struct/trait, `switch`/`case` branch, `if/elif` guard, `useEffect[deps]`, or JSX conditional block.
  - **`D2: Y_role` & Layer (`D3`):** Behavioral role (`STATE`, `EFFECT`, `ACTION`, `IO`, `VIEW`, `SCHEMA`) and architectural layer (`PRODUCTION` vs. co-located `TEST_SUITE`).
  - **`D3: Z_write` / `Z_read` (State & Storage Channels):** Directional dataflow tracking which state variables, object attributes, and storage/DB keys each block mutates vs. reads.
  - **`D4: W_calls` (Dyck-Constrained Call Graph):** Outgoing function/method calls, HTTP route-to-handler bindings, and 1–3 hop interprocedural effect bubbling.
  - **`D5: E_exit` & `T_mode` (Exception & Temporal Control-Flow):** Tracks `raise`/`throw`/`catch`/HTTP status exits (`4xx`/`5xx`) and execution mode (`SYNC` | `ASYNC` | `REACTIVE` | `TIMER`).
  - **`D6: C_contract` (Cross-Boundary Contract Verifier):** Pre-commit verification of **caller-callee arity & keyword obligations** (`[6D Caller Arity Contract Violation]`), route/client payload keys, SQL `NOT NULL` schema constraints, and dialect mismatches.
- **Pure SQLite WAL Graph-as-Storage (`.projectbrain.db`):**
  - Stores vertices (`graph_nodes WITHOUT ROWID`), forward/reverse B-Tree adjacency lists (`edges WITHOUT ROWID`), sub-token BM25 inverted indices (`fts_symbols` FTS5), and content-addressed source code (`source_blobs WITHOUT ROWID`) in a single ACID database file.
  - Includes `WITH RECURSIVE` CTE multi-hop reachability in `<6ms`, **Salsa-style `interface_hash` early-cutoff** on body-only edits, and an in-memory **Stacked Delta Overlay (`temp.unified_symbols`)** for zero-disk dry-run verification.
- **Single-Read Surgical Dossier & Context Compiler (`projectbrain dossier` / `brain_context`):**
  - Uses **Dyck-Constrained Sublinear ACL Push (PPR)** + **Submodular Concept-Coverage Selection** to return exact target slices (with reversible `-> expand: brain_slice <file>:<s-e>` fold handles), 1-hop callee signature skeletons, **Stack-Trace Crash Frame Pinning**, and **Greenfield Structural Sibling Exemplars**.
- **AST Symbol-Anchored Patch Engine (`projectbrain patch` / `brain_patch`):**
  - Supports both line-anchored (`@sub`, `@replace L<s-e>`, `@insert_after`, `@delete`) and **AST symbol-anchored (`@replace_body <Symbol>`, `@add_method <ClassName>`, `@replace <Symbol>`)** directives with `±5` line drift auto-healing, lazy-elision rejection, dual Tree-sitter + Python `compile()` validation, and pre-commit caller arity checks.
- **6D Graph-Aware Command & Test Output Compressor (`projectbrain run` / `brain_run`):**
  - Folds passing test noise (`pytest`, `jest`/`vitest`, `go test`, `cargo test`), deduplicates repetitive log/JSON/CSV lines by structural template, and maps any failing traceback `file:line` frames directly to enclosing **6D Code Graph symbols, signatures, and 1-hop callers** (`# [6D Failing Frame Resolution]`).

---

## Step-by-Step Setup Guide (60 Seconds)

### Step 1: Install from PyPI

```bash
pip install projectbrain-mcp
```

*(Alternatively, use `pipx install projectbrain-mcp` or `uv tool install projectbrain-mcp`.)*

Verify both the CLI and MCP server binaries are available:

```bash
projectbrain --help
projectbrain-mcp --help
```

---

### Step 2: Initialize Your Repository (One Command)

Run `projectbrain init --hooks` inside any repository (or pass `--path` and optional `--ide {all,antigravity,claude,cursor,vscode}`):

```bash
projectbrain --path /path/to/your/repo init --hooks
```

**What `projectbrain init --hooks` does automatically:**
1. **Builds the Pure SQLite Graph-as-Storage Index:** Writes `.projectbrain.db` (WAL mode).
2. **Updates `.gitignore`:** Ensures ephemeral index, dossier, and diff files stay out of Git.
3. **Configures MCP Across IDEs:** Writes/merges `.mcp.json` (Claude Code / Antigravity), `.cursor/mcp.json` (Cursor), and `.vscode/mcp.json` (VS Code Agent Mode).
4. **Installs Agent Rules & PreToolUse Hooks:** Writes `AGENTS.md`, `CLAUDE.md`, `.cursor/rules/projectbrain.mdc`, and `.claude/settings.local.json` `PreToolUse` guards.

---

### Step 3: MCP Server Configuration (Standard or Lean 5-Tool Mode)

Add `projectbrain-mcp` to your MCP configuration (pass `--lean` or set `PROJECTBRAIN_LEAN_MCP=1` to expose only the 6 core high-leverage tools and save ~2,900 tokens of tool-schema overhead):

```json
{
  "mcpServers": {
    "projectbrain": {
      "command": "projectbrain-mcp",
      "args": ["--lean", "/path/to/your/repo"]
    }
  }
}
```

Or run directly with **`uvx`**:

```json
{
  "mcpServers": {
    "projectbrain": {
      "command": "uvx",
      "args": ["projectbrain-mcp", "--lean", "/path/to/your/repo"]
    }
  }
}
```

*(Every MCP tool also accepts an optional `repo_path` argument per call for multi-repo workspaces.)*

---

## Daily CLI Workflow & Commands

### 1. Compile a Single-Read Engineering Dossier (`dossier` / `dossier --zoom`)
```bash
projectbrain --path /path/to/repo dossier "recover from a panic in an HTTP handler and abort with 500"
projectbrain --path /path/to/repo dossier --zoom "how does JWT signature and exp claim verification work"
```

### 2. Surgically Slice Symbols or Line Ranges (`slice`)
```bash
projectbrain --path /path/to/repo slice --summary src/App.tsx:ProtectedRoute recovery.go:CustomRecoveryWithWriter
```

### 3. Apply AST Symbol-Anchored or Line-Anchored Patches (`patch`)
```bash
# AST Symbol-Anchored replacement (immune to line-number drift!)
projectbrain --path /path/to/repo patch --apply --spec "@file recovery.go
@replace_body Recovery
	return RecoveryWithWriter(DefaultErrorWriter)
@end"

# Intra-line substitution
projectbrain --path /path/to/repo patch --apply --spec "@file src/App.tsx
@sub L84 \`!profileCompleted\` -> \`isHydrated && !profileCompleted\`"
```

### 4. Compress Noisy Test / Command Output with 6D Traceback Resolution (`run`)
```bash
projectbrain --path /path/to/repo run "pytest -v"
# Or pipe arbitrary command output:
pytest -v | projectbrain --path /path/to/repo run --stdin
```

### 5. View Structural Resolution & Session Telemetry (`stats`)
```bash
projectbrain --path /path/to/repo stats --summary
```
---

## Blind Open-Source Repository Evaluation (v0.8.2)

Evaluated zero-shot across **4 unseen open-source production repositories** spanning Python, TypeScript/JSX, and Go (`encode/httpx`, `pallets/flask`, `honojs/hono`, `gin-gonic/gin` — **670 files, 6,713 functions, 656 classes/structs, 5,074 6D cells, 12,046 graph nodes, and 35,627 edges**) using natural-language prompts with **zero function/method identifiers**:

| Repository | Language | Files | Functions | Graph Edges | Parse Health (`ok/partial/unsupported`) | Warm SQLite Load | Salsa No-Op Check |
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: |
| **`encode/httpx`** | Python | 60 | 1,134 | 5,558 | `60 / 0 / 0` (**100%**) | `136.8 ms` | `10.8 ms` |
| **`pallets/flask`** | Python | 85 | 1,462 | 6,646 | `85 / 0 / 0` (**100%**) | `160.7 ms` | `23.4 ms` |
| **`honojs/hono`** | TypeScript / JSX | 426 | 2,775 | 15,258 | `418 / 8 / 0` (**98.1%**) | `318.3 ms` | `78.7 ms` |
| **`gin-gonic/gin`** | Go | 99 | 1,342 | 8,165 | `99 / 0 / 0` (**100%**) | `179.8 ms` | `10.8 ms` |


---

## End-to-End Logged Agent Benchmark (879-File Open-Source Repo — Cold Start)

Measured head-to-head across an 879-file production open-source repository comparing a **Naive Search Agent** (`rg`/`grep` + `read_file`) against a **ProjectBrain Agent** (including full cold-start `index()` time of `13.47s`, `3.34s` Tree-sitter AST parse across 879 files, and `1.24s` 3-task dossier compilation):

| Metric | Naive Search Agent | ProjectBrain Agent (Cold Start) | Measured Savings / Speedup |
| :--- | :---: | :---: | :---: |
| **Wall-Clock Time** | `5m 52s` (`352.0s`) | **`3m 44s` (`224.0s`)** | **`2m 08s` faster (`-36.4%` / `1.57x` faster)** |
| **Model Turns** | `16` turns | **`8` turns** | **`8` fewer turns (`-50.0%` / `2.0x` fewer)** |
| **Search / Read Tool Calls** | `41` calls (`14` shell + `27` reads) | **`5` calls** (`1` dossier + `1` read + `3` slices) | **`36` fewer calls (`-87.8%` / `8.2x` fewer)** |
| **Total Lines Read** | `15,164` lines | **`1,597` lines** (`764` dossier + `833` sliced) | **`13,567` fewer lines (`-89.5%` / `9.5x` less)** |
| **Raw Tool Output Characters** | `640,557` chars | **`81,634` chars** | **`558,923` chars saved (`-87.3%` / `7.85x` less)** |
| **Final-Turn Context Window** | `245,686` tokens | **`53,355` tokens** | **`192,331` tokens saved (`-78.3%` / `4.60x` smaller)** |
| **Uncached New Input Tokens (`sum(input_tokens)`)** | `251,826` tokens | **`55,403` tokens** | **`196,423` tokens saved (`-78.0%` / `4.55x` less)** |
| **Cached Input Tokens (`sum(cache_read_tokens)`)** | `1,887,736` tokens | **`169,004` tokens** | **`1,718,732` tokens saved (`-91.0%` / `11.17x` less)** |
| **Total Billed Input Traffic Across All Turns** | `2,139,562` tokens | **`224,407` tokens** | **`1,915,155` tokens saved (`-89.5%` / `9.53x` less)** |
| **Model Output Tokens (`sum(output_tokens)`)** | `23,158` tokens | **`16,124` tokens** | **`7,034` tokens saved (`-30.4%` less)** |
- **Zero-Identifier Symbol Slice Recall (`compile_context` @ `2,500` token budget):** **`12 / 12 (100.0%)`**
- **Top-5 File Localization Accuracy (`file_acc_at_5`):** **`12 / 12 (100.0%)`** (`11 / 12` Top-1)
- **AST Symbol-Anchored Patch Verification (`@replace_body` / `@sub`):** **`4 / 4 (100.0%)`**
- **Measured `pytest -v` Output Compression (`projectbrain run "python -m pytest -v"` on ProjectBrain's 193-test suite):** `16,752` chars (`4,188` est. tokens) -> `539` chars (`134` est. tokens) (`193` passing lines folded, `96.8%` reduction).
---

## Project Layout

```text
projectbrain/
├── src/projectbrain/
│   ├── brain.py        # 6D Context Compiler, Dossier Engine, Slicer, Explorer & Contract Verifier
│   ├── store.py        # Pure SQLite WAL Graph-as-Storage (graph_nodes, edges WITHOUT ROWID, FTS5, source_blobs, Delta Overlay)
│   ├── slicer.py       # 6D Coordinate Matrix extractor, smart focus-window folding & signature skeletons
│   ├── patcher.py      # Two-Phase AST Symbol-Anchored & Line-Anchored Patch Engine + syntax/contract gates
│   ├── parsers.py      # Polyglot Tree-sitter CST codecs (Python, JS/TS/JSX/TSX, Go, Rust, Java, SQL)
│   ├── graph.py        # Multiplex CodeGraph, Dyck-Constrained Sublinear ACL Push (PPR) & Hub Damping
│   ├── ledger.py       # Page-accurate ROI & Token Savings Ledger (.projectbrain_ledger.json)
│   ├── memory.py       # Persistent AST-anchored repo memory (.projectbrain_memory.json)
│   ├── resolve.py      # Cross-file import & TypeScript path alias resolution
│   ├── frameworks.py   # Next.js, FastAPI, Flask, Express, Hono, Gin, Actix, Axum & Spring route inference
│   ├── cli.py          # CLI entry point (init --hooks, dossier, patch, slice, stats, compile, explore)
│   └── server.py       # FastMCP server entry point (standard 22-tool and --lean 6-tool modes)
├── tests/              # 193 unit, integration, security, and benchmark threshold tests
└── eval/               # Polyglot scale benchmark, self-dogfooding & zero-identifier adversarial harness
```
