# CVC — Cognitive Version Control

```
 ██████╗██╗   ██╗ ██████╗
██╔════╝██║   ██║██╔════╝
██║     ██║   ██║██║
██║     ╚██╗ ██╔╝██║
╚██████╗ ╚████╔╝ ╚██████╗
 ╚═════╝  ╚═══╝   ╚═════╝
```

**Git for AI Context** — A Merkle DAG-based version control system for AI conversations, built as a standalone TypeScript/Bun binary.

[![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)
[![Bun](https://img.shields.io/badge/Bun-1.x-f472b6.svg)](https://bun.sh/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

---

## Why CVC?

Every AI coding session loses context. Switch branches, restart your IDE, or hit a token limit — and the AI forgets everything. CVC solves this by treating AI conversations as first-class version-controlled artifacts.

**CVC gives your AI a persistent, searchable, branchable memory.**

- **Time Travel**: Restore any prior conversation state with a single command
- **Shadow Branches**: Branch conversations like Git branches — explore alternatives without losing progress
- **Cognitive Blame**: Link every AI-generated code change back to the conversation that produced it
- **Hybrid Search**: Find past conversations by meaning (semantic) or by text (keyword)
- **Multi-Provider**: Works with Anthropic, OpenAI, Google Gemini, Ollama, and LM Studio

---

## Installation

### Standalone Binary (Recommended)

```bash
# Linux / macOS
curl -fsSL https://github.com/your-org/cvc/releases/latest/download/cvc-linux-x64 -o cvc
chmod +x cvc && sudo mv cvc /usr/local/bin/

# Windows (PowerShell)
irm https://github.com/your-org/cvc/releases/latest/download/cvc-win-x64.exe -OutFile cvc.exe
```

### From Source (Development)

```bash
git clone https://github.com/your-org/cvc.git
cd cvc/cvc-node
bun install
bun run dev
```

---

## Quick Start

```bash
# 1. Initialize CVC in your project
cvc init

# 2. Start the AI agent
cvc agent --provider anthropic --model claude-sonnet-4-20250514

# 3. Have a conversation — CVC auto-commits context
> Explain the architecture of this project
> Refactor the database module for better performance

# 4. Branch to explore an alternative approach
cvc branch experiment --desc "Try a different DB strategy"

# 5. Time-travel back if needed
cvc log
cvc restore abc123def456
```

---

## Core Concepts

### The Four-Tier Context Database

```
┌──────────────────────────────────────────────┐
│ Tier 1: Index (SQLite)                       │
│   Commit graph, branches, audit log, search  │
├──────────────────────────────────────────────┤
│ Tier 2: Content-Addressable Store            │
│   Zlib-compressed blobs in .cvc/objects/     │
│   SHA-256 deduplication + delta compression  │
├──────────────────────────────────────────────┤
│ Tier 3: Semantic Vector Store                │
│   Summary embeddings for hybrid search       │
├──────────────────────────────────────────────┤
│ Tier 4: PageIndex (Optional)                 │
│   LLM-powered hierarchical document RAG      │
└──────────────────────────────────────────────┘
```

### Shadow Branches

CVC creates Git shadow branches (`cvc/main`, `cvc/feature-x`) that travel alongside your Git branches. When you `git checkout`, CVC automatically restores the matching conversation context.

### Cognitive Blame

Every Git commit is linked to its CVC conversation context via Git Notes (`refs/notes/cvc`). Run `git notes show` to trace any code change back to the AI conversation that produced it.

### Delta Compression

Consecutive commits share most of their context. CVC stores only the diff (unified text patches) relative to periodic anchor commits, typically achieving 60-80% storage reduction.

---

## CLI Reference

| Command | Description |
|---------|-------------|
| `cvc init` | Initialize CVC in the current project |
| `cvc agent` | Start the interactive AI agent (REPL) |
| `cvc setup` | Configure provider, model, and API key |
| `cvc status` | Show current branch, HEAD, and context size |
| `cvc log [-n N]` | Show commit history |
| `cvc commit <msg>` | Create a manual checkpoint |
| `cvc branch <name>` | Create a new conversation branch |
| `cvc merge <source>` | Merge a branch (semantic three-way) |
| `cvc restore <hash>` | Time-travel to a prior commit |
| `cvc recall <query>` | Natural language search across all conversations |
| `cvc diff <a> [b]` | Compare two commits |
| `cvc timeline` | ASCII timeline visualization |
| `cvc compact` | Compress context window to reduce tokens |
| `cvc stats` | Aggregated analytics |
| `cvc doctor` | Health diagnostics |
| `cvc serve` | Start the CVC Cognitive Proxy (HTTP) |
| `cvc launch <tool>` | Launch an IDE tool (Cursor, Aider, etc.) |
| `cvc mcp` | Start the MCP server (stdio) |
| `cvc docs search` | Search API documentation |
| `cvc docs fetch` | Fetch API docs from Context Hub |
| `cvc login` / `cvc logout` | Firebase authentication |

---

## Agent Mode

The `cvc agent` command starts an interactive REPL with a full-featured AI coding assistant:

### Slash Commands

| Command | Description |
|---------|-------------|
| `/help` | Show available commands |
| `/status` | Current branch, HEAD, context size |
| `/commit <msg>` | Manual checkpoint |
| `/branch <name>` | Create conversation branch |
| `/restore <hash>` | Time-travel |
| `/log` | Commit history |
| `/recall <query>` | Search past conversations |
| `/diff [file]` | Show uncommitted changes |
| `/compact` | Compress context |
| `/cost` | Show session cost breakdown |
| `/clear` | Clear conversation |
| `/model <name>` | Switch model mid-session |
| `/exit` | End session |

### Tools Available to the Agent

The agent has access to 20+ tools: file read/write/edit, bash execution, glob search, grep, web search, API doc lookup, sub-agent delegation, and all CVC operations.

### Providers

| Provider | Models | API Key Env |
|----------|--------|-------------|
| Anthropic | Claude Opus, Sonnet, Haiku | `ANTHROPIC_API_KEY` |
| OpenAI | GPT-4o, GPT-5 | `OPENAI_API_KEY` |
| Google | Gemini 2.5 Flash/Pro | `GOOGLE_API_KEY` |
| Ollama | Any local model | (none) |
| LM Studio | Any local model | (none) |

---

## MCP Integration

CVC exposes all operations as MCP (Model Context Protocol) tools, making it compatible with Claude Desktop, Cursor, VS Code Copilot Chat, and any MCP-compatible client.

```json
{
  "mcpServers": {
    "cvc": {
      "command": "cvc",
      "args": ["mcp"],
      "cwd": "/path/to/your/project"
    }
  }
}
```

Available MCP tools: `cvc_commit`, `cvc_branch`, `cvc_merge`, `cvc_restore`, `cvc_recall`, `cvc_log`, `cvc_diff`, `cvc_status`, `cvc_timeline`, `cvc_compact`.

---

## Configuration

### Settings Hierarchy

```
.cvc/managed-settings.json   (highest priority — plugin-managed)
.cvc/settings.json            (project settings)
.cvc/settings.local.json      (local overrides — gitignored)
~/.cvc/settings.json          (global defaults)
```

### CVC.md

Place a `CVC.md` file in your project root to provide persistent instructions to the AI agent. This file is automatically included in the system prompt.

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `ANTHROPIC_API_KEY` | Anthropic API key | — |
| `OPENAI_API_KEY` | OpenAI API key | — |
| `GOOGLE_API_KEY` | Google AI API key | — |
| `CVC_PROVIDER` | Default provider | `anthropic` |
| `CVC_MODEL` | Default model | `claude-sonnet-4-20250514` |
| `CVC_ANCHOR_INTERVAL` | Commits between anchors | `10` |
| `CVC_DELTA_ENABLED` | Enable delta compression | `true` |

---

## Plugins & Skills

### Plugins

Place plugin directories in `.cvc/plugins/` or `~/.cvc/plugins/`:

```
my-plugin/
├── .cvc-plugin/
│   └── plugin.json          # {"name": "my-plugin", "version": "1.0.0"}
├── commands/
│   └── analyze.md           # Slash command (Markdown)
├── agents/
│   └── reviewer.md          # Sub-agent definition
└── hooks/
    └── pre-tool-use.sh      # Hook script
```

### Skills

Place `.md` files in `.cvc/skills/` or `~/.cvc/skills/` with YAML frontmatter:

```markdown
---
name: code-review
description: Automated code review
auto_invoke:
  - "review.*code"
  - "check.*quality"
tools: [read_file, grep_search]
---

Perform a thorough code review...
```

### Hooks

CVC supports 9 hook events (Claude Code 2.0 parity):

| Event | When |
|-------|------|
| `PreToolUse` | Before a tool executes |
| `PostToolUse` | After a tool executes |
| `SessionStart` | Agent session begins |
| `SessionStop` | Agent session ends |
| `Stop` | Agent tries to end turn |
| `SubagentStop` | Sub-agent completes |
| `UserPromptSubmit` | User submits input |
| `PreCompact` | Before context compression |
| `Notification` | Custom alert |

Hook exit codes: `0` = proceed, `1` = ask user, `2` = block.

---

## Architecture

See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the full system design with diagrams.

**Module Map:**

```
src/
├── cli.ts                  # Commander.js CLI (26 commands)
├── proxy.ts                # Hono HTTP proxy server
├── mcp-server.ts           # MCP stdio server
├── launcher.ts             # IDE tool launcher
├── auth.ts                 # Firebase authentication
├── index.ts                # Entry point
├── core/
│   ├── database.ts         # 4-tier context database
│   ├── delta-engine.ts     # Delta compression
│   ├── models.ts           # Types, schemas, config
│   ├── pageindex.ts        # Tier 4 hierarchical RAG
│   └── util.ts             # Utilities
├── agent/
│   ├── chat.ts             # Agent session + REPL loop
│   ├── executor.ts         # Tool execution (20+ tools)
│   ├── llm.ts              # Multi-provider LLM client
│   ├── sub-agent.ts        # Parallel sub-agent orchestration
│   ├── continuation.ts     # Hedging detection + plan tracking
│   ├── grounding.ts        # Import validation + anti-hallucination
│   ├── hooks.ts            # 9-event hook engine
│   ├── plugins.ts          # Plugin discovery + loading
│   ├── skills.ts           # Skill matching + auto-invoke
│   ├── renderer.ts         # Terminal rendering + diff display
│   ├── stream-renderer.ts  # Token-by-token markdown streaming
│   ├── multi-progress.ts   # Parallel agent progress display
│   ├── menus.ts            # Interactive menus (@clack/prompts)
│   ├── onboarding.ts       # Smart onboarding + scaffolding wizard
│   ├── web-search.ts       # DuckDuckGo web search
│   ├── api-docs.ts         # API doc fetching + Context Hub
│   ├── sessions.ts         # Session management + fork
│   └── ...                 # 10+ more modules
├── adapters/
│   ├── anthropic.ts        # Anthropic (with prompt caching)
│   ├── openai.ts           # OpenAI
│   ├── google.ts           # Google Gemini
│   ├── ollama.ts           # Ollama (local)
│   └── lmstudio.ts         # LM Studio (local)
├── operations/
│   ├── engine.ts           # Commit, branch, merge, restore
│   └── router.ts           # Operation routing
└── vcs/
    └── bridge.ts           # Git shadow branches + notes
```

---

## Building

```bash
# Development
bun run dev                    # Run from source

# Compile standalone binaries
bun run build:bin:linux        # Linux x64
bun run build:bin:mac          # macOS ARM64
bun run build:bin:win          # Windows x64
bun run build:all              # All platforms

# Quality
bun run typecheck              # TypeScript strict mode
bun run lint                   # Biome linter
bun test                       # Run tests
```

---

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, code style, and PR guidelines.

---

## License

MIT
