# CVC — Master Architecture Document

**Project:** CVC (Cognitive Version Control) — Time Machine for AI Agents  
**Package:** `tm-ai` on PyPI  
**Version:** 2.5.x  
**Status:** Phase 0 lock-in — authoritative reference  
**Last updated:** 2026-05-07

---

## 1. Mission Statement

CVC is **Git for the AI agent's brain**. Instead of versioning source code, it versions
the agent's entire cognitive state — every conversation turn, decision, and tool call —
as an immutable, content-addressed **Merkle DAG**. It solves context rot, error loops,
and runaway token spend in autonomous AI agents.

---

## 2. Technology Stack (Locked)

| Layer | Technology | Version | Role |
|---|---|---|---|
| Language | Python | 3.11+ | Primary runtime |
| CLI framework | Click + Rich | 8.x / 13.x | Terminal UX |
| HTTP / API | FastAPI + Uvicorn | 0.115+ | Gateway & REST |
| Validation | Pydantic v2 | 2.9+ | All data models |
| Storage (index) | SQLite via aiosqlite | 0.20+ | Commit graph, branch pointers |
| Storage (blobs) | Content-Addressable Storage (disk) | built-in | Object store (.cvc/objects/) |
| Compression | zstandard | 0.23+ | Blob compression |
| Vector search | ChromaDB | 1.0+ | Tier 3 semantic recall |
| PDF / doc index | PyMuPDF | 1.25+ | Tier 4 PageIndex (optional) |
| AI orchestration | LangGraph + LangChain-core | 0.2+ | Agent reasoning graphs |
| Telegram adapter | aiogram | 3.26+ | Telegram gateway |
| HTTP client | httpx (http2) | 0.27+ | All outbound calls |
| Build system | Hatchling | latest | Wheel + sdist |
| Linter / formatter | Ruff | 0.7+ | py311 target, 100-char line limit |
| Test runner | pytest + pytest-asyncio | 8.x | async mode = auto |

**LLM providers (optional extras):**  
`anthropic`, `openai`, `google` (genai), `vertex` (Google Cloud ADC), `ollama` (httpx-only)

---

## 3. Repository Layout

```
cvc/                        # Python package root
  cli.py                    # Click entrypoint: `cvc <command>`
  mcp_server.py             # MCP (Model Context Protocol) stdio/SSE server
  gateway.py                # FastAPI proxy gateway
  gateway_manager.py        # Gateway lifecycle manager
  daemon.py                 # Background daemon process
  launcher.py               # Cross-platform launcher
  auth.py                   # Auth helpers
  workspace_manager.py      # Multi-workspace isolation

  core/                     # Storage + data models
    models.py               # Pydantic schemas: CognitiveCommit, Merkle DAG
    database.py             # Four-Tiered Context Database (CDB)
    persistence.py          # Checkpoint persistence
    snapshot.py             # Context snapshot logic
    user_model.py           # Versioned user identity
    skill_graph.py          # Skill dependency graph
    learning_extractor.py   # Learning extraction from commits
    pageindex.py            # Tier 4 PageIndex (pymupdf)

  operations/               # Cognitive operations
    engine.py               # Core CVC operation dispatcher
    cognome.py              # COGNOME L1: heuristic Engram compiler
    cognome_layers.py       # COGNOME layer definitions (L1/L2/L3)
    cognome_manager.py      # COGNOME substrate manager
    cognome_runtime.py      # Runtime Engram injection
    engram_injectors.py     # Provider-specific Engram injection
    semantic_merge.py       # ChromaDB-powered semantic branch merge
    state_machine.py        # Commit state machine
    handoff.py              # Agent-to-agent context handoff
    telepathy.py            # .cvcpack cross-machine context transfer
    tournament.py           # Quantum branching: Tree-of-Thoughts tournament
    dreaming.py             # DAG dreaming: idle knowledge distillation
    prompt_evolution.py     # Prompt self-improvement
    cognitive_hooks.py      # Lifecycle event hooks
    skill_extractor.py      # Skill mining from commit history
    session_scratchpad.py   # In-session volatile scratchpad

  agent/                    # Agent runtime (embedded CLI agent)
    llm.py                  # LLM call abstraction
    chat.py                 # Chat loop
    memory.py               # Agent memory layer
    sessions.py             # Session management
    tools.py                # Built-in agent tools
    skills.py               # Skill loader
    providers/              # Per-provider connection configs
    executor.py             # Tool execution sandbox
    subagent.py             # Sub-agent spawning
    system_prompt.py        # System prompt builder
    context_autopilot.py    # Auto context management
    continuation.py         # Continuation / resumption logic
    cost_tracker.py         # Token cost tracker
    grounding.py            # Grounding / hallucination guard
    metacognition.py        # Self-reflection layer
    predictive_loader.py    # Predictive context preloading
    quantum.py              # Quantum branch tournament bridge
    git_integration.py      # Git hook sync
    hooks.py / plugins.py   # Extension points

  adapters/                 # External LLM + service adapters
    base.py                 # Abstract adapter interface
    anthropic.py            # Anthropic Claude
    openai.py               # OpenAI / OpenAI-compatible
    google.py               # Google Generative AI
    vertex.py               # Google Cloud Vertex AI (ADC auth)
    ollama.py               # Ollama local inference
    lmstudio.py             # LM Studio local inference
    github.py               # GitHub integration adapter
    telegram_gateway.py     # Telegram bot gateway
    telegram_handler.py     # Telegram message handler
    telegram_streamer.py    # Telegram streaming output

  sdk/                      # Public SDK for external agent integration
    agent.py                # Per-agent hive mind interface
    hivemind.py             # Hive mind coordinator
    registry.py             # Agent registry
    router.py               # Branch-scoped message router
    events.py               # EventBus: commit/branch lifecycle events
    sync.py                 # Remote CVC sync (push/pull)
    compactor.py            # Context compaction
    telemetry.py            # Usage telemetry

  cogs/                     # SDCP: Structured Dynamic Context Protocol
    models.py               # SDCP data models
    compiler.py             # SDCP compiler
    executor.py             # SDCP executor
    registry.py             # SDCP registry
    sdcp.py                 # SDCP core
    cache.py                # SDCP cache
    integration.py          # SDCP integration hooks

  dashboard/                # Web dashboard (FastAPI + TypeScript)
    routes.py               # Dashboard API routes
    static/                 # Built static assets
    ts/                     # TypeScript source
    tsconfig.json

docs/                       # Documentation
  CHANGELOG.md
  CLI_AGENT_GUIDE.md
  CLI_SLASH_COMMANDS.md
  CROSS_MODE_GUIDE.md
  CVC_TOOLS_REFERENCE.md
  MCP_DOCUMENTATION.md
  MULTI_WORKSPACE.md
  documentation.md
  website/                  # jaimeena.com/cvc docs site

tests/                      # pytest test suite
scripts/                    # Dev and install scripts
vscode-extension/           # VS Code extension source
pyproject.toml              # Build config, deps, tool config
```

---

## 4. Core Storage: Four-Tiered Context Database (CDB)

```
Tier 1 — SQLite Index         commits, branches, agent registry, metadata
Tier 2 — CAS Blob Store       .cvc/objects/  content-addressed, zstd-compressed
Tier 3 — ChromaDB             Semantic vector search across commit content
Tier 4 — PageIndex (opt.)     LLM-powered hierarchical document RAG (pymupdf)
```

**Merkle DAG hashing:**
```
commit_hash = SHA-256( parent_hash || serialized_content_blob || metadata_json )
```
Altering any ancestor invalidates every descendant hash — cryptographic immutability by design.

---

## 5. COGNOME Substrate (L1/L2/L3)

COGNOME replaces the static `.md` memory paradigm (CLAUDE.md, Cursor rules, etc.) with
**query-specific Engram compilation**. Instead of injecting all memory into every prompt,
it compiles a minimal, token-budgeted snippet containing only the noemata (facts,
summaries, provenance) that the current intent requires.

```
L1 — Heuristic Engram compiler   deterministic, CPU-only, sub-millisecond
L2 — Learned soft-prompt         tiny model trained during idle time (future)
L3 — LoRA refinement head        optional GPU layer (future)
```

L1 is the permanent foundation. L2 and L3 are additive heads — they refine selection
without replacing L1. Every Engram carries source commit hashes for full DAG provenance.

---

## 6. Key Subsystems

### Quantum Branching (Tree of Thoughts)
Multiple LangGraph agent instances race down parallel thought branches simultaneously.
The winning branch is merged; losers are archived as learning data. Implemented in
`operations/tournament.py` + `agent/quantum.py`.

### Semantic Merge
Resolves cognitive collisions between branches using ChromaDB vector embeddings.
Merges insights semantically, not just by line diffs. `operations/semantic_merge.py`.

### Multi-Agent Telepathy
Packs a branch's cognitive state into a portable `.cvcpack` and transfers it over MCP
to another machine or agent identity. `operations/telepathy.py`.

### Micro-Rollbacks
Rewind execution at the THOUGHT_STEP or TOOL_CALL granularity using the commit state
machine. `operations/state_machine.py`.

### DAG Dreaming
Idle-time knowledge distillation: CVC processes the commit DAG during quiet periods to
extract cross-session insights and strengthen the skill graph. `operations/dreaming.py`.

### MCP Server
CVC exposes all cognitive operations (commit, branch, merge, restore, status, log) as
MCP tools over stdio or SSE transport. Enables IDEs (Windsurf, Cursor, VS Code, GitHub
Copilot native) that lock API endpoints to still use CVC. `cvc/mcp_server.py`.

### Hive Mind SDK
External agents embed CVC via the SDK. Each `Agent` instance is bound to an identity
and gets scoped commit/recall/query access through the Router and AgentRegistry.
`cvc/sdk/`.

---

## 7. Interfaces

| Interface | Module | Transport |
|---|---|---|
| CLI | `cvc/cli.py` | Click → terminal |
| MCP Server | `cvc/mcp_server.py` | stdio / SSE |
| REST Gateway | `cvc/gateway.py` | HTTP (FastAPI) |
| Web Dashboard | `cvc/dashboard/` | HTTP (FastAPI + TS) |
| Telegram Bot | `cvc/adapters/telegram_gateway.py` | WebSocket / long-poll |
| Python SDK | `cvc/sdk/` | Direct import |

---

## 8. Project Configuration

```toml
[project]
name = "tm-ai"
version = "2.5.x"
requires-python = ">=3.11"
license = "MIT"

[project.scripts]
cvc = "cvc.cli:main"

[tool.ruff]
target-version = "py311"
line-length = 100

[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
```

Install targets:
- `pip install "tm-ai[all]"` — full install (Anthropic + OpenAI + Google + Vertex)
- `pip install "tm-ai"` — core only
- `pip install -e ".[all,dev]"` — dev mode
- `curl -fsSL https://jaimeena.com/cvc/install.sh | bash` — one-line installer

---

## 9. Coding Conventions

- **Async first**: use `aiosqlite`, async FastAPI endpoints, `pytest-asyncio` auto mode
- **Type hints everywhere**: Pydantic v2 models for all API boundaries and data schemas
- **No hardcoded secrets**: API keys via env vars or `cvc setup` (stored in global config dir)
- **Ruff enforced**: rules E, F, I, W; max line 100; target py311
- **Sensitive data**: treat all cognitive state, vector embeddings, and context blobs as PII

---

## 10. Distribution & Install Infrastructure

| Artifact | Location |
|---|---|
| PyPI package | `tm-ai` at pypi.org/project/tm-ai |
| Docs & install page | jaimeena.com/cvc |
| macOS/Linux installer | jaimeena.com/cvc/install.sh → public/cvc/install.sh in Portfolio-E |
| Windows installer | jaimeena.com/cvc/install.ps1 |
| Source | github.com/mannuking/cvc |
| VS Code extension | vscode-extension/ (bundled) |

**Important (per SIP):** When updating install scripts, edit both
`src/app/cvc/scripts/` AND copy into `public/cvc/` in the Portfolio-E project.
The `public/cvc/` directory is the live curl endpoint.

---

## 11. What Is NOT in Scope

- Node.js CVC: fully deprecated. Never distribute `cvc-node/` or Node install scripts.
- Self-modifying gateway config: CVC must never write to `~/.hermes/` config files.
- Recursive agent spawning: CVC cron jobs and SDK agents must not spawn further cron jobs.

---

*This document is the authoritative architecture reference for all CVC development.
Update it when stack decisions change. Tina (developer agent) and Robin (CTO agent)
must read this before any implementation or deployment work on the CVC project.*
