# CVC Architecture

This document describes the system architecture of CVC (Cognitive Version Control) — a Merkle DAG-based context versioning system for AI conversations.

---

## System Overview

```mermaid
graph TB
    CLI[CLI / Commander.js] --> OPS[Operations Engine]
    AGENT[Agent REPL] --> OPS
    MCP[MCP Server] --> OPS
    PROXY[Cognitive Proxy] --> OPS

    OPS --> DB[Context Database]
    OPS --> VCS[Git Shadow Bridge]

    DB --> T1[Tier 1: SQLite Index]
    DB --> T2[Tier 2: Blob Store]
    DB --> T3[Tier 3: Semantic Search]
    DB --> T4[Tier 4: PageIndex RAG]

    AGENT --> LLM[LLM Client]
    AGENT --> TOOLS[Tool Executor]
    AGENT --> HOOKS[Hook Engine]
    AGENT --> PLUGINS[Plugin System]

    LLM --> ANTH[Anthropic]
    LLM --> OAI[OpenAI]
    LLM --> GEM[Gemini]
    LLM --> OLL[Ollama]
    LLM --> LMS[LM Studio]
```

---

## Entry Points

CVC has four entry points, all sharing the same operations engine:

### CLI (`src/cli.ts`)
Commander.js-based CLI with 26+ commands. The primary user interface. Parses arguments, dispatches to the operations engine, and formats output.

### Agent REPL (`src/agent/chat.ts`)
Interactive AI coding assistant with a read-eval-print loop. Manages conversation state, tool execution, and context auto-commits.

### MCP Server (`src/mcp-server.ts`)
Model Context Protocol server (stdio transport). Exposes CVC operations as MCP tools for use with Claude Desktop, Cursor, VS Code, and other MCP clients.

### Cognitive Proxy (`src/proxy.ts`)
Hono-based HTTP server that intercepts LLM API calls and injects CVC context. Allows existing tools (Cursor, Aider, etc.) to benefit from CVC without modification.

---

## Core Layer

### Context Database (`src/core/database.ts`)

The heart of CVC. A four-tier storage system built on Bun's native SQLite:

#### Tier 1: Index (SQLite)

```sql
-- Core tables
commits(hash, parent, branch, timestamp, summary, type, is_delta, anchor_hash)
branches(name, head, description, created, shadow_ref)
config(key, value)
audit_log(id, event, data, timestamp)

-- Search indexes
search_index(commit_hash, content)      -- FTS5 full-text search
embeddings(commit_hash, vector, summary) -- Semantic vectors
```

**Design decisions:**
- Synchronous SQLite (Bun native, not better-sqlite3) — no async overhead
- WAL mode + 64MB page cache for concurrent read performance
- SHA-256 content hashing for deduplication

#### Tier 2: Content-Addressable Blob Store

```
.cvc/objects/
├── ab/
│   └── cdef1234...   # zlib-compressed blobs
├── 01/
│   └── 23456789...
└── ...
```

Blobs are addressed by their SHA-256 hash (first 2 chars = directory prefix). Content is zlib-compressed before storage. The delta engine further reduces storage through unified text patches.

#### Tier 3: Semantic Vector Store

Required embedding-based search. Commit summaries, user queries, and file manifests are embedded and stored alongside blobs with rich metadata (session, tokens, cost, files touched). The `recall` command performs hybrid search: FTS5 keyword match + cosine similarity on embeddings, with score fusion.

#### Tier 4: PageIndex (Optional)

LLM-powered hierarchical document indexing for RAG. Processes PDF, Markdown, and text documents into searchable tree structures. See [PageIndex section](#pageindex) below.

### Delta Engine (`src/core/delta-engine.ts`)

Reduces storage by computing unified text patches between consecutive commits:

```mermaid
graph LR
    A[Anchor Commit<br/>Full blob] --> D1[Delta 1<br/>Patch only]
    D1 --> D2[Delta 2<br/>Patch only]
    D2 --> D3[Delta 3<br/>Patch only]
    D3 --> A2[Anchor Commit<br/>Full blob]
    A2 --> D4[Delta 4]
```

**Key parameters:**
- `ANCHOR_INTERVAL`: Full blob stored every N commits (default: 50, env: `CVC_ANCHOR_INTERVAL`)
- `DELTA_SIZE_THRESHOLD`: Only store delta if it's < 80% of full blob size
- Uses `diff` library (`createPatch` / `applyPatch`) for human-readable unified patches

**Storage flow:**
1. On commit: find nearest ancestor anchor blob
2. Compute unified patch between anchor and new content
3. If patch < threshold × full size → store as delta (with `is_delta=true`, `anchor_hash`)
4. Every N commits → promote to new anchor (store full blob)
5. On retrieval: if delta → fetch anchor blob → apply patch → return reconstructed content

### Models (`src/core/models.ts`)

TypeScript interfaces and Zod schemas for all CVC data structures:
- `CVCConfig`: Runtime configuration (provider, model, delta_enabled, etc.)
- `Commit`, `Branch`, `AuditEntry`: Core data types
- `ToolCall`, `ToolResult`: Agent tool schemas
- Environment variable resolution with defaults

---

## Agent Layer

### Agent Session (`src/agent/chat.ts`)

The main agent loop:

```mermaid
sequenceDiagram
    participant U as User
    participant R as REPL
    participant L as LLM Client
    participant T as Tool Executor
    participant D as Database

    U->>R: Prompt
    R->>R: Check slash commands
    R->>L: Send messages + system prompt
    L-->>R: Stream response
    loop Tool calls
        L->>T: Tool request
        T->>T: Run hooks (PreToolUse)
        T->>T: Execute tool
        T->>T: Run hooks (PostToolUse)
        T-->>L: Tool result
    end
    L-->>R: Final response
    R->>D: Auto-commit context
    R->>U: Rendered output
```

**Key behaviors:**
- Onboarding wizard on first run (detects project type, offers scaffolding)
- Auto-commit after each turn (configurable interval)
- Context compaction when approaching token limits
- Hedging detection via continuation module
- Session persistence + fork support

### Tool Executor (`src/agent/executor.ts`)

Executes 20+ tools with permission checks and hook integration:

| Category | Tools |
|----------|-------|
| File I/O | `read_file`, `write_file`, `edit_file`, `multi_edit` |
| Search | `glob_search`, `grep_search`, `web_search`, `api_docs` |
| Execution | `bash`, `run_command` |
| CVC | `commit`, `branch`, `restore`, `recall`, `log`, `diff` |
| Agent | `sub_agent`, `compact`, `cost` |

**Sub-agent delegation:**
The executor can spawn sub-agents (via `src/agent/sub-agent.ts`) for parallel work. Sub-agents:
- Share the parent's LLM client
- Run with restricted read-only tools
- Execute up to 15 iterations before forced completion
- Up to 4 run concurrently via `Promise.allSettled`

### LLM Client (`src/agent/llm.ts`)

Unified interface over 5 provider adapters. Handles:
- Message formatting (provider-specific)
- Token counting and budget tracking
- Prompt caching (Anthropic `cache_control: ephemeral`)
- Streaming with backpressure
- Cost calculation

### Hook Engine (`src/agent/hooks.ts`)

Shell-script and JavaScript hooks for 9 events:

```
.cvc/hooks/
├── pre-tool-use.sh        # Before any tool executes
├── post-tool-use.js       # After tool completes
├── session-start.sh       # Agent session begins
└── notification.sh        # Custom alerts
```

**Exit code semantics:**
| Code | Meaning |
|------|---------|
| 0 | Proceed normally |
| 1 | Ask user for confirmation |
| 2 | Block the action |

Hooks receive JSON payloads via stdin and can emit structured responses to stdout.

### Plugin System (`src/agent/plugins.ts`)

Auto-discovers plugins from `.cvc/plugins/` and `~/.cvc/plugins/`:

```mermaid
graph TB
    PD[Plugin Discovery] --> V[Validate plugin.json]
    V --> C[Load Commands]
    V --> A[Load Agents]
    V --> H[Register Hooks]
    V --> S[Apply Settings]
    C --> SP[System Prompt Injection]
    A --> SE[Sub-agent Registry]
```

### Skill System (`src/agent/skills.ts`)

Auto-invoked skills with pattern matching:

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

Skills are matched against user prompts using regex patterns. When matched, the skill's instructions are injected into the system prompt.

### Grounding (`src/agent/grounding.ts`)

Output validation that catches hallucinated imports and APIs:
1. Extract `import` statements from generated code
2. Check against known stdlib modules (Node builtins, Python stdlib)
3. Check against project dependencies (`package.json`, `requirements.txt`)
4. Validate symbols exist in the workspace via grep
5. Return a `GroundingReport` with warnings for unresolvable references

### Continuation (`src/agent/continuation.ts`)

Detects when the LLM is hedging or producing incomplete output:
- Tracks plan items and completion state
- Identifies hedging patterns ("I'll leave the rest...", "You can implement...")
- Auto-prompts for continuation when incomplete work is detected

---

## VCS Layer

### Git Shadow Bridge (`src/vcs/bridge.ts`)

Maintains invisible Git branches that mirror CVC branches:

```
Git branches:           CVC shadow branches:
  main          ←→        cvc/main
  feature-x     ←→        cvc/feature-x
  bugfix-y      ←→        cvc/bugfix-y
```

**Shadow branch lifecycle:**
1. `cvc init` → creates `cvc/main` shadow branch
2. `cvc branch foo` → creates `cvc/foo` shadow branch
3. `git checkout feature-x` → CVC auto-switches to `cvc/feature-x`
4. `cvc merge foo` → three-way merge on shadow branches

**Cognitive Blame** (Git Notes):
Every CVC commit writes a Git Note under `refs/notes/cvc` linking the Git HEAD to the conversation context hash.

---

## PageIndex

Tier 4 of the database — LLM-powered hierarchical document indexing:

```mermaid
graph TB
    DOC[Document] --> CHUNK[Chunking]
    CHUNK --> TOC[TOC Detection<br/>via LLM]
    TOC --> TREE[Tree Building]
    TREE --> ENRICH[Node Enrichment<br/>via LLM]
    ENRICH --> STORE[Compressed JSON<br/>in .cvc/pageindex/]

    QUERY[Search Query] --> MATCH[Tree Traversal<br/>+ Scoring]
    STORE --> MATCH
    MATCH --> RESULTS[Ranked Nodes]
```

**Ingestion pipeline:**
1. Read document (PDF, Markdown, plain text)
2. Split into chunks (respecting section boundaries)
3. LLM call to detect table of contents / headings
4. Build hierarchical tree from detected structure
5. LLM calls to enrich each node with summaries
6. Store as compressed JSON in `.cvc/pageindex/<doc_id>.json`

**Search:**
- Tree traversal with keyword + semantic scoring
- Returns ranked nodes with location references
- Supports multi-document search

---

## Transport & Integration

### Cognitive Proxy

Hono HTTP server that transparently intercepts LLM API calls:

```
Client (Cursor/Aider) → CVC Proxy → Real LLM API
                           ↓
                     Inject CVC context
                     into system prompt
```

### MCP Server

Stdio-based MCP server exposing CVC operations:
- Uses `@modelcontextprotocol/sdk`
- Zod schema validation for all tool inputs
- Compatible with Claude Desktop, VS Code, Cursor

---

## Build & Distribution

### Compilation

```bash
bun build --compile --target=bun-linux-x64 src/cli.ts --outfile cvc
```

Produces a self-contained binary (~40-60MB) that includes the Bun runtime, all dependencies, and SQLite.

### CI/CD

- **CI** (`.github/workflows/ci.yml`): Biome lint → TypeScript typecheck → Bun test → Build matrix (3 platforms)
- **Release** (`.github/workflows/release.yml`): Tag `v*` → Full CI → GitHub Release with binary artifacts
