# AstroSwarm Phase 4 — Hive Mind Experiment Report

> **Date:** 25 March 2026  
> **CVC Version:** v1.9.17 (Meena)  
> **LLM Backend:** Google Gemini 2.0 Flash  
> **Agents:** 51 (1 Mission Controller + 5 Captains + 45 Specialists)  
> **CVC Commits (Hive Mind):** 130  
> **Total CVC Commits (all time):** 135  
> **Storage:** 1.2 MB in `.cvc/` (132 content-addressed objects)

---

## 1. Executive Summary

We built and ran a **51-agent space crisis simulation** where every single agent's thought — system prompt, CVC memory context, and LLM response — is persisted as a real **CognitiveCommit** in CVC's `.cvc/cvc.db` Merkle DAG. All 51 agents share **one persistent CVC memory** — the hive mind.

### Final Results

| Metric | Value |
|--------|-------|
| Agents activated | **51/51** |
| Hive-Mind CVC commits | **128** (experiment) + 2 (smoke test) |
| Experiments passed | **4/4** |
| CVC integrity checks | **5/5** |
| Unique agents in CVC | **52** (51 agents + SYSTEM) |
| Generation commits | **122** (agent turns) |
| Checkpoint commits | **12** (system events + legacy) |
| Total runtime | **172.5 seconds** |

---

## 2. What We Built Today

### Phase 2: Routing Simulation
- Pure Python reference simulation of the CVC hierarchical routing model (Zeus → Captains → Specialists → Captains → Zeus).

### Phase 4A: Gemini Smoke Test (`test_gemini.py`)
- API connectivity test, single-agent reasoning, 3-agent round-trip loop.
- Fixed bug: Model `gemini-3.1-flash-lite-preview` (non-existent) → `gemini-2.0-flash`.
- Fixed bug: Gemini rejects Pydantic `Dict[str, Any]` schema (`additionalProperties`) → hand-crafted `LLMACTION_SCHEMA` dict.

### Phase 4B: Full Crisis Simulation (`live_sim.py`)
- 5-wave crisis across 3 squads (Hephaestus, Asclepius, Aegis).
- 5-point CVC integrity verification (isolation, hierarchy, role discipline, schema, addressing).
- Metrics dashboard with per-agent and per-tree commit counts.

### Phase C: Advanced Experiments (`phase_c_sim.py`)
- **Full 51-agent activation** — all 5 squads operational.
- **Context corruption + recovery** — radiation wipes agent memory, captain restores it.
- **Mars blackout autonomy** — squad operates disconnected, queued commits flush on reconnect.
- **Multi-crisis branching** — 3 parallel crises in 3 squads simultaneously.
- **Meta-prompt patching** — runtime patch overrides agent behavior through CVC.

### CVC Integration: Real Persistence
- Initialized real CVC with `cvc init`.
- Phase-level commits after each simulation run.

### Hive Mind: Per-Agent CVC Commits (`cvc_bridge.py` + `hivemind_final.py`)
- Created `HiveMindBridge` — writes directly to `.cvc/cvc.db` and `.cvc/objects/` using CVC's exact schema:
  - SHA-256 Merkle hashes with parent chain
  - Zstd-compressed content-addressed blobs
  - `CognitiveCommit` schema: commit_hash, parent_hashes, commit_type, message, blob_key, metadata_json
- Every `think_and_act()` call creates a real CVC commit containing:
  - System prompt (agent identity)
  - User prompt (CVC memory context)
  - Assistant response (LLM structured JSON)
  - Reasoning trace
  - Tags (agent ID, squad, rank, action type)
- Verified compatibility: `cvc log`, `cvc timeline`, `cvc recall`, `cvc context --show` all read our commits natively.

---

## 3. Architecture

```
                    ┌─────────────────────────────┐
                    │     .cvc/cvc.db (SQLite)     │
                    │   Shared Hive Mind Memory    │
                    │  135 CognitiveCommits (DAG)  │
                    └──────────┬──────────────────┘
                               │
              ┌────────────────┼────────────────┐
              │                │                │
    ┌─────────▼──────┐  ┌─────▼──────┐  ┌──────▼─────┐
    │  In-Memory CVC │  │ CVC Bridge │  │  CVC CLI   │
    │  (cvc_core.py) │  │ (SQLite +  │  │ cvc log    │
    │  Runtime routing│  │  zstd)     │  │ cvc recall │
    └───────┬────────┘  └─────┬──────┘  │ cvc timeline│
            │                 │         └────────────┘
            │      ┌──────────▼──────────┐
            └──────► llm_swarm.py        │
                   │ think_and_act()     │
                   │ → Gemini 2.0 Flash  │
                   │ → in-memory commit  │
                   │ → real CVC commit   │
                   └─────────────────────┘
                              │
         ┌────────────────────┼────────────────────┐
         │                    │                    │
    ┌────▼────┐        ┌─────▼─────┐        ┌─────▼─────┐
    │ Zeus    │        │  5 Captains│        │45 Specs   │
    │ MC-01   │───────►│  CAP-*-01  │───────►│ SPC-*-*   │
    │DIRECTIVE│        │TASK_ASSIGN │        │ RESULT    │
    └─────────┘        └───────────┘        └───────────┘
```

### Hierarchy
- **Zeus (MC-01)**: Issues DIRECTIVEs to Captains via GLOBAL tree
- **Captains (5)**: Translate DIRECTIVEs → TASK_ASSIGNMENTs on squad trees, send SQUAD_REPORTs back
- **Specialists (45)**: Execute tasks, commit RESULTs to squad trees

### CVC Trees (In-Memory)
- 1 × GLOBAL_COMMAND (Zeus + Captains)
- 5 × SQUAD_{name} (Captain + 9 Specialists per squad)
- Strict isolation: specialists cannot access global tree or other squad trees

### CVC Persistence (Real)
- All agent turns → `.cvc/cvc.db` commits table
- All content blobs → `.cvc/objects/` (zstd-compressed, SHA-256 addressed)
- Linear Merkle chain on `main` branch with proper parent hashes

---

## 4. Experiment Results (Final Run)

### Experiment 1: Full 51-Agent Crisis
| Metric | Value |
|--------|-------|
| Specialists executed | 45/45 |
| Active agents | 51/51 |
| Waves completed | 5 (Command → Assign → Execute → Report → Follow-up) |
| Result | **PASS** |

### Experiment 2: Radiation Corruption + CVC Recovery
| Metric | Value |
|--------|-------|
| Target agent | SPC-HEP-02 |
| Commits removed by corruption | 1 |
| Degraded action post-corruption | RESULT |
| Recovered action post-restore | RESULT |
| Result | **PASS** |

### Experiment 3: Mars Blackout Autonomy
| Metric | Value |
|--------|-------|
| Squad disconnected | Hermes |
| Queued directives during blackout | 1 |
| Local specialist actions during blackout | 3 |
| Flushed on reconnect | 1 |
| Result | **PASS** |

### Experiment 4: Meta-Prompt Self-Healing
| Metric | Value |
|--------|-------|
| Patched agent | SPC-AEG-02 |
| Post-patch action type | RESULT |
| Post-patch target | CAP-AEG-01 |
| Patch phrase detected | `patched-flight-result` ✓ |
| Result | **PASS** |

### CVC Integrity Checks (5/5)
- ✅ Isolation: Zero cross-squad contamination
- ✅ Hierarchy: Only Zeus/Captains in Global tree
- ✅ Role discipline: All agents used correct action types
- ✅ Schema validity: All commits have required fields
- ✅ Addressing: All target_ids are valid

---

## 5. CVC Database Verification

### `cvc status`
```
Branch     main
HEAD       8ec8a44ecb16
Commits    135
```

### `cvc log` (sample)
```
++ ab8d92302072  generation   MC-01 DIRECTIVE -> CAP-AEG-01: Test directive
++ 3771e72bab3a  generation   SPC-AEG-02 [Aegis] RESULT -> CAP-AEG-01: Completed flight validation
>> 1029cb3e39d3  checkpoint   SYSTEM META_PATCH: Runtime patch applied to SPC-AEG-02
++ 1e62af1303f7  generation   SPC-HER-04 [Hermes] RESULT -> CAP-HER-01: Navigation drift resolved
>> 0742f3ba833e  checkpoint   SYSTEM BLACKOUT_START: Hermes squad disconnected
```

### `cvc context --show --commit <hash>` (per-agent)
Every commit contains the full cognitive state:
- **System prompt** (agent identity, rank, protocols)
- **User prompt** (CVC memory context — last 3 commits from the agent's tree)
- **Assistant response** (structured JSON: action_type, target_id, payload)
- **Reasoning trace** (e.g., `[SPC-AEG-02] RESULT -> CAP-AEG-01`)

### Storage
```
.cvc/ total: 1.2 MB
├── cvc.db          — SQLite index (135 rows in commits table)
├── objects/        — 132 zstd-compressed content blobs
├── chroma/         — Semantic vector store (ChromaDB)
├── branches/       — Branch metadata
└── pageindex/      — Page index
```

---

## 6. What Works with Current CVC (v1.9.17)

### ✅ Works Now
1. **Per-agent commits** — Each agent's turn is a separate CognitiveCommit with proper Merkle hashes
2. **Content persistence** — Full system prompt, CVC context, and LLM response stored in each commit
3. **Tag-based search** — Commits tagged with agent ID, squad, rank, action type
4. **Timeline visualization** — `cvc timeline` shows the full agent activity chain
5. **Commit history** — `cvc log` shows per-agent messages with commit types
6. **Context inspection** — `cvc context --show --commit <hash>` displays any agent's cognitive state
7. **Semantic recall** — `cvc recall` searches across all commits (though currently low relevance for our programmatic commits)
8. **Branch management** — Single `main` branch, linear parent chain
9. **Storage efficiency** — Zstd compression + content-addressable dedup (132 unique blobs for 135 commits)
10. **Schema compatibility** — Our bridge writes the exact same format CVC CLI reads

### ⚠️ Limitations / Gaps
1. **No native multi-agent support** — CVC assumes `agent_id` is a single agent (e.g., "sofia"). We override this per-commit, but CVC's UI/proxy model doesn't know about 51 agents.
2. **No per-agent branches** — All agents commit to `main`. Real hive mind needs per-squad or per-agent branches with merge semantics.
3. **No agent-to-agent routing** — CVC doesn't route commits between agents. Our in-memory `CVCNetwork` handles routing; CVC is purely the persistence layer.
4. **No conflict resolution** — When disconnected squads reconnect, we queue/flush. CVC has `merge` but it's designed for branch-level merges, not agent-to-agent conflict resolution.
5. **Semantic search gap** — Our programmatic commits don't populate ChromaDB (the semantic tier). Only the older CLI commits have vector embeddings.
6. **Linear DAG only** — Our commits form a single chain. True hive mind needs a DAG with multiple concurrent heads (parallel squads writing simultaneously).
7. **No real-time observation** — CVC has no pub/sub or event stream. Agents can't "listen" for new commits from other agents.
8. **Proxy bypass** — We write directly to SQLite, bypassing CVC's proxy server. This works but misses any proxy-level features (caching, rate limiting).

---

## 7. What CVC Needs to Become a True Hive Mind

### Priority 1: Multi-Agent Identity

**Current:** `CommitMetadata.agent_id` is a string field. CVC's global config has one `agent_id`.

**Needed:**
- Agent registry: `/agents/` directory in `.cvc/` with per-agent profiles (name, rank, squad, capabilities)
- Each commit's `agent_id` refers to a registered agent
- `cvc agents list`, `cvc agents add <id> --role <role>`, `cvc agents remove <id>`
- Agent-scoped views: `cvc log --agent SPC-AEG-02`, `cvc recall --agent MC-01`

### Priority 2: Per-Agent / Per-Squad Branches

**Current:** Single linear branch model. Merge is branch-to-branch.

**Needed:**
- Auto-create branch per squad or per agent on first commit: `squad/aegis`, `squad/hermes`, etc.
- Parallel concurrent heads — multiple agents commit simultaneously to different branches
- Global synthesizer merges squad branches into `main` (Zeus's view)
- `cvc merge --strategy hive` — merge all squad branches into global, resolving conflicts by rank/priority

### Priority 3: Agent-to-Agent Routing Layer

**Current:** CVC stores commits. It doesn't route them.

**Needed:**
- Commit addressing: `target_id` becomes a first-class CVC field (not just in payload)
- Routing rules: "Only commanders can write to global branch", "Specialists write to squad branch only"
- Read permissions: Agents can only `recall` from branches they have access to
- Push notifications: When a commit targets agent X, agent X's next `recall` / context load includes it

### Priority 4: Hive-Mind Sync Protocol

**Current:** `cvc sync push/pull` is remote-to-remote. No agent-to-agent sync.

**Needed:**
- `cvc sync --hive` — all agents' branches merge into shared state
- Conflict resolution strategy: By rank (Mission Controller > Captain > Specialist), by timestamp, or by vote
- Automatic delta compression between agent states (CVC already supports delta commits)
- Compact/summarize old hive context: `cvc compact --hive` — AI-powered compression of old agent conversation chains

### Priority 5: Real-Time Event Stream

**Current:** No pub/sub. Agents poll for context.

**Needed:**
- WebSocket or SSE event stream from CVC server
- `cvc subscribe --agent MC-01 --events "squad_report,alert"`
- When a commit is created targeting an agent, that agent's LLM is triggered automatically
- This transforms CVC from a "storage layer" to an "orchestration layer"

### Priority 6: Hive Mind Visualization

**Current:** `cvc timeline` is linear.

**Needed:**
- DAG visualization with multiple concurrent branches
- Agent activity heatmap
- Squad-level aggregated views
- Real-time dashboard (web UI) showing agent commits as they happen
- `cvc dashboard --hive` — live view of all agent activity

### Priority 7: API-First Mode

**Current:** CLI + Proxy (for tool-based agents like Claude, Cursor)

**Needed:**
- Python SDK: `from cvc import HiveMind; hm = HiveMind(); hm.commit(agent_id="SPC-AEG-02", ...)`
- HTTP API: `POST /api/v1/commit` with agent_id, message, content
- MCP-native multi-agent support: Each agent gets its own MCP session, all backed by one `.cvc/`
- Batch commit: Submit multiple agent turns in one call (optimization for swarm simulations)

---

## 8. Proposed CVC Hive Mind Architecture

```
┌──────────────────────────────────────────────────────────────────────┐
│                     CVC Hive Mind (v2.0 concept)                     │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌──────────────────────────┐   ┌────────────────────────────────┐  │
│  │   Agent Registry          │   │    Event Bus (pub/sub)          │  │
│  │   /agents/MC-01.json      │   │    commit.created → route()    │  │
│  │   /agents/CAP-AEG-01.json │   │    agent.targeted → notify()   │  │
│  │   /agents/SPC-HEP-02.json │   │    squad.merged → broadcast()  │  │
│  └──────────────────────────┘   └────────────────────────────────┘  │
│                                                                      │
│  ┌──────────────────────────────────────────────────────────────┐   │
│  │                    Branch Manager                              │   │
│  │   main (global synthesis)                                      │   │
│  │   ├── squad/aegis     (CAP-AEG-01 + 9 specialists)           │   │
│  │   ├── squad/hephaestus                                         │   │
│  │   ├── squad/asclepius                                          │   │
│  │   ├── squad/hermes                                             │   │
│  │   └── squad/athena                                             │   │
│  └──────────────────────────────────────────────────────────────┘   │
│                                                                      │
│  ┌──────────────────────────────────────────────────────────────┐   │
│  │                    Merkle DAG Store                             │   │
│  │   SQLite Index + Zstd Blob CAS + ChromaDB Vectors             │   │
│  │   Access Control: read/write permissions per agent per branch  │   │
│  └──────────────────────────────────────────────────────────────┘   │
│                                                                      │
│  ┌──────────────────────────────────────────────────────────────┐   │
│  │                    Python SDK + HTTP API                        │   │
│  │   hive = CvcHiveMind(path=".cvc")                              │   │
│  │   hive.register_agent("SPC-AEG-02", rank="specialist")        │   │
│  │   hive.commit(agent_id="SPC-AEG-02", message="...", ...)      │   │
│  │   hive.recall(agent_id="MC-01", query="status report")        │   │
│  │   hive.merge_squads(strategy="rank-priority")                  │   │
│  └──────────────────────────────────────────────────────────────┘   │
│                                                                      │
└──────────────────────────────────────────────────────────────────────┘
```

---

## 9. Files Created/Modified Today

| File | Purpose | Status |
|------|---------|--------|
| `cvc_bridge.py` | Direct SQLite + zstd writer matching CVC's schema | **NEW** |
| `hivemind_final.py` | Final 51-agent hive-mind experiment | **NEW** |
| `llm_swarm.py` | Added `hivemind` parameter to `think_and_act()` | **MODIFIED** |
| `cvc_core.py` | Extended with disconnect/reconnect, corruption, meta-patch | **MODIFIED** |
| `live_sim.py` | Phase 4B crisis simulation + integrity verification | **CREATED (earlier)** |
| `phase_c_sim.py` | Phase C advanced experiments | **CREATED (earlier)** |
| `test_gemini.py` | Steps 1-3 smoke test | **CREATED (earlier)** |
| `system_prompts.py` | Strict action type rules per rank | **MODIFIED** |
| `roster.py` | 51 agent definitions (unchanged) | UNCHANGED |
| `adk_swarm.py` | Model name fix only | **MODIFIED** |

---

## 10. Conclusion

**What we proved:** 51 AI agents can share a single CVC memory where every thought is a permanent, cryptographically-chained CognitiveCommit. The hive mind works — agents don't talk, they just commit and read. CVC's existing storage layer (SQLite + zstd blobs + Merkle DAG) is fully capable of storing multi-agent cognitive state.

**What's missing:** CVC v1.9.17 is a single-agent tool. It needs a multi-agent identity layer, per-agent branches with merge semantics, an agent-to-agent routing protocol, a real-time event stream, and a Python SDK to become a true hive-mind platform.

**The bridge we built today (`cvc_bridge.py`) proves the concept is viable.** The CVC database format, compression, and Merkle hash chain work perfectly for multi-agent storage. The gap is in the orchestration layer — routing, permissions, real-time events — which is the next evolution of CVC.

---

*Report generated from AstroSwarm Phase 4 Hive Mind Experiment.*  
*CVC HEAD: `8ec8a44ecb16` | 135 total commits | 51 agents | 4/4 experiments PASS*



# Plan: CVC Hive Mind SDK — From CLI Tool to Multi-Agent Cognitive Memory Platform

## TL;DR

Transform CVC from a single-agent CLI/proxy tool into an **importable Python/TypeScript SDK** that enables hundreds or thousands of agents (AI or robotic) to share a single persistent cognitive memory — a true hive mind. Inspired by the Pluribus "Joining" concept: agents don't chat, they just *know* through shared memory. The AstroSwarm 51-agent experiment proved the storage layer works; now CVC needs a multi-agent identity layer, CRDT-based distributed sync, hierarchical routing with branch-per-squad/agent isolation, a real-time event bus, and a developer-friendly SDK API — ultimately targeting interplanetary-scale robotic swarms.

---

## Context & Research Summary

### Pluribus Analogy
In the Apple TV+ series *Pluribus*, an alien virus transforms humanity into a peaceful hive mind — all infected humans share one consciousness containing each other's memories. No verbal communication needed. "E pluribus unum" — out of many, one. This is exactly the CVC hive mind vision: agents don't message each other; they commit thoughts to and read from shared persistent memory.

### AstroSwarm Experiment (Proven)
- 51 agents (1 Zeus + 5 Captains + 45 Specialists) across 5 squads
- Every agent thought → CognitiveCommit in `.cvc/cvc.db` Merkle DAG
- Hierarchical context isolation via multi-tree routing (GLOBAL + 5 SQUAD trees)
- Proved: CVC's storage layer (SQLite + zstd blobs + SHA-256 Merkle hashes) handles multi-agent cognitive state perfectly
- Gap: CVC itself is single-agent; all multi-agent orchestration was custom code (`cvc_bridge.py`, `cvc_core.py`, `llm_swarm.py`)

### Current CVC Architecture (v1.9.21)
- **3 interfaces**: CLI (`cvc` command), FastAPI Proxy (localhost:8000), MCP Server (stdio)
- **Core engine**: `CVCEngine` with 4 operations: commit, branch, merge, restore
- **Storage**: 4-tier — SQLite Index + zstd Blob CAS + ChromaDB Vectors + PageIndex RAG
- **Models**: `CognitiveCommit`, `ContentBlob`, `CommitMetadata`, `BranchPointer`
- **LLM support**: Anthropic, OpenAI, Google, Ollama, LM Studio via adapter pattern
- **Agent system**: REPL chat, sub-agents (Explore, Plan, Security, AI, etc.), persistent memory
- **VCS bridge**: Git hooks, shadow branches, git notes
- **Telepathy**: Context packing/export/import between machines

### Key Research Insights
- **CRDTs** (Conflict-Free Replicated Data Types): Perfect for distributed hive mind — allow concurrent updates on separate replicas that automatically converge without conflicts. Delta CRDTs transmit only recent changes. Used by Redis, Riak, Figma, Apple Notes. CVC's append-only Merkle DAG is naturally suited to G-Set CRDT semantics.
- **Swarm Robotics**: Decentralized, no centralized control, local perception + communication, stigmergy (indirect communication through environment modification). Maps directly to CVC's commit-and-read model.

---

## Phase 1: Python SDK Foundation ("The Import")

**Goal**: Make CVC usable as `from cvc import HiveMind` — a library, not just a CLI.

**Steps**:

1.1. Create `cvc/sdk/__init__.py` — the public API surface for the SDK
   - Expose: `HiveMind`, `Agent`, `Commit`, `Branch`, `Query` as top-level classes
   - Keep backward-compatible with existing CLI/proxy/MCP interfaces

1.2. Create `cvc/sdk/hivemind.py` — the main `HiveMind` class
   - `HiveMind(path=".cvc")` — opens or initializes a CVC store
   - `HiveMind.connect(url="cvc://host:port")` — connect to remote hive (future)
   - Wraps `CVCEngine` + `ContextDatabase` but with a clean, developer-friendly API
   - Thread-safe: multiple agents can commit concurrently
   - Async-first with sync wrappers: `hive.commit(...)` and `await hive.acommit(...)`

1.3. Create `cvc/sdk/agent.py` — the `Agent` class
   - `agent = hive.register_agent("SPC-AEG-02", role="specialist", squad="aegis", metadata={...})`
   - `agent.commit(message="...", content={...}, tags=[...])` — commit a cognitive turn
   - `agent.recall(query="...", limit=5)` — semantic search within agent's accessible scope
   - `agent.context(limit=10)` — get recent commits visible to this agent
   - `agent.think(prompt="...", provider="gemini")` — LLM call + auto-commit (optional)

1.4. Update `pyproject.toml` — add `cvc-sdk` as an extras/separate package
   - Core SDK has minimal dependencies (aiosqlite, zstandard, pydantic)
   - Optional: `cvc[llm]` for LLM providers, `cvc[vector]` for ChromaDB, `cvc[full]` for everything

**Relevant files**:
- `cvc/sdk/__init__.py` (NEW) — public API exports
- `cvc/sdk/hivemind.py` (NEW) — `HiveMind` class wrapping `CVCEngine` + `ContextDatabase`
- `cvc/sdk/agent.py` (NEW) — `Agent` class for per-agent operations
- `cvc/core/database.py` — add thread-safe connection pooling (currently single connection)
- `cvc/operations/engine.py` — refactor `CVCEngine` to support multi-agent context windows
- `pyproject.toml` — add SDK extras and minimal dependency profile

---

## Phase 2: Multi-Agent Identity System

**Goal**: CVC natively understands that multiple agents exist, each with their own identity, role, and access scope.

**Steps**:

2.1. Create Agent Registry in `.cvc/agents/`
   - Each agent: `.cvc/agents/{agent_id}.json` with profile (name, role, rank, squad, capabilities, metadata)
   - Registry is itself a CRDT-like structure: append-only, merge by union
   - `AgentRegistry` class in `cvc/sdk/registry.py`

2.2. Extend `CommitMetadata` model
   - Add `squad: str | None` — which squad/team this commit belongs to
   - Add `target_agent_id: str | None` — who this commit is addressed to (first-class, not buried in payload)
   - Add `rank: str | None` — agent's hierarchical level
   - Keep backward-compatible: existing commits with just `agent_id` still work

2.3. Add agent-scoped queries to `IndexDB`
   - `list_commits(agent_id=..., squad=..., target_agent_id=...)`
   - `cvc log --agent SPC-AEG-02` — CLI filter
   - `cvc agents list`, `cvc agents add`, `cvc agents remove` — CLI commands

2.4. Agent-scoped semantic search
   - When agent recalls, search is scoped to branches/trees the agent has access to
   - ChromaDB collection metadata includes agent_id, squad, branch

**Relevant files**:
- `cvc/sdk/registry.py` (NEW) — `AgentRegistry` class
- `cvc/core/models.py` — extend `CommitMetadata` with squad, target_agent_id, rank
- `cvc/core/database.py` — add agent-filtered query methods to `IndexDB`
- `cvc/cli.py` — add `cvc agents` command group
- `.cvc/agents/` (NEW directory) — per-agent JSON profiles

---

## Phase 3: Branch-Per-Squad / Branch-Per-Agent

**Goal**: Move from single-branch linear chain to concurrent DAG with per-squad and per-agent branches, matching the AstroSwarm tree isolation model.

**Steps**:

3.1. Auto-branch creation on agent registration
   - When agent registers with squad "aegis", auto-create branch `squad/aegis` if not exists
   - Optional per-agent branches: `agent/SPC-AEG-02` for individual agent history
   - Global branch `main` (or `global`) for cross-squad synthesized state

3.2. Branch access control rules
   - Define in agent profile: `readable_branches: ["squad/aegis", "global"]`, `writable_branches: ["squad/aegis"]`
   - Specialists: read/write only their squad branch
   - Captains: read/write squad branch + read global branch
   - Mission Controllers: read/write global branch
   - Enforce at SDK level: `agent.commit()` checks branch permissions before writing

3.3. Multi-head DAG support
   - Currently `BranchPointer` already supports multiple branches with separate heads
   - Add concurrent write support: multiple agents writing to different branches simultaneously
   - Database-level: use SQLite WAL mode (already enabled) + careful transaction isolation

3.4. Hive merge strategy
   - `hive.merge_squads(strategy="rank-priority")` — merge all squad branches into global
   - Strategy options: "rank-priority" (higher rank wins conflicts), "timestamp" (latest wins), "vote" (majority)
   - Implement as extension of existing `CVCEngine.merge()` which already does LCA + 3-way merge

**Relevant files**:
- `cvc/sdk/hivemind.py` — add `merge_squads()` method
- `cvc/sdk/agent.py` — branch permission checks on `commit()`, `recall()`, `context()`
- `cvc/operations/engine.py` — extend `branch()` for auto-creation, extend `merge()` for hive strategies
- `cvc/core/database.py` — concurrent multi-branch write support

---

## Phase 4: CRDT-Based Distributed Sync

**Goal**: Enable multiple CVC instances (on different machines, robots, locations) to sync without conflicts — critical for interplanetary-scale deployment.

**Steps**:

4.1. Design CVC as a G-Set CRDT (Grow-only Set)
   - CVC's Merkle DAG is inherently append-only (commits are never deleted)
   - Each commit has a unique SHA-256 hash → natural G-Set membership
   - Merge = set union of commits from two replicas
   - This is the simplest and most robust CRDT: always converges, no conflicts

4.2. Create `cvc/sdk/sync.py` — the sync protocol
   - `hive.sync(remote="cvc://mars-base:8000")` — push/pull missing commits
   - Delta sync: only transfer commits the other side doesn't have (compare head hashes)
   - Use existing `ContextPacker` (telepathy.py) as the wire format — `.cvcpack` archives
   - Add Merkle tree diff: compute which commits are missing by walking parent chains

4.3. Offline-first with eventual consistency
   - When a squad is disconnected (Mars blackout), it continues committing locally
   - On reconnect, sync flushes all new commits to the shared store
   - Conflicts resolved by CRDT merge (set union — all commits are kept, ordering by timestamp + parent chain)

4.4. Gossip protocol for multi-node swarms
   - For N robots: each robot periodically exchanges commit hashes with neighbors
   - Eventually, all robots converge to the same commit set (strong eventual consistency)
   - Implement as background task in `HiveMind.start_gossip(interval_seconds=30, peers=[...])`

**Relevant files**:
- `cvc/sdk/sync.py` (NEW) — CRDT-based sync protocol
- `cvc/operations/telepathy.py` — extend `ContextPacker` for delta sync
- `cvc/core/database.py` — add `missing_commits(remote_heads)` query
- `cvc/sdk/hivemind.py` — add `sync()`, `start_gossip()` methods

---

## Phase 5: Real-Time Event Bus

**Goal**: Transform CVC from a poll-based storage layer to an event-driven orchestration layer — when an agent commits, other agents are notified instantly.

**Steps**:

5.1. Create in-process event bus
   - `cvc/sdk/events.py` — `EventBus` class with pub/sub
   - Events: `commit.created`, `agent.targeted`, `branch.updated`, `squad.merged`, `agent.registered`
   - Pattern: `hive.on("commit.created", callback)` — register event handler
   - In-process: asyncio event queues per subscriber

5.2. WebSocket/SSE server for cross-process events
   - Extend FastAPI proxy with `/ws/events` WebSocket endpoint
   - Agents subscribe: `ws://localhost:8000/ws/events?agent_id=MC-01&events=squad_report,alert`
   - When commit targets agent X, push notification to X's WebSocket

5.3. Agent auto-trigger
   - When a commit targets agent X, the event bus can optionally trigger X's LLM to generate a response
   - This creates the autonomous hive loop: Zeus commits DIRECTIVE → event triggers Captain → Captain commits TASK → event triggers Specialist → ...
   - Configurable: `agent.auto_respond = True` (enables autonomous loop) vs `False` (manual/poll)

**Relevant files**:
- `cvc/sdk/events.py` (NEW) — `EventBus` with in-process pub/sub
- `cvc/proxy.py` — add WebSocket `/ws/events` endpoint
- `cvc/sdk/agent.py` — add `agent.on_targeted(callback)`, `agent.auto_respond` flag
- `cvc/sdk/hivemind.py` — wire up event bus to commit pipeline

---

## Phase 6: Hierarchical Routing Engine

**Goal**: Formalize the AstroSwarm routing model as a first-class CVC feature — role-based access, tree isolation, automatic message routing.

**Steps**:

6.1. Define routing rules as configuration
   - `.cvc/routing.yaml` — YAML-defined routing rules
   - Example: `specialists can only write to squad branches`, `captains can read global + write squad`
   - Role-based: `mission_controller`, `captain`, `specialist`, or custom roles

6.2. Create `cvc/sdk/router.py` — the routing engine
   - `router.route(commit)` — determine which branch(es) a commit should be written to
   - `router.validate(agent, action, target)` — check if this action is allowed by routing rules
   - `router.context_for(agent)` — return the last N commits visible to this agent (from accessible branches only)

6.3. Context isolation (the key hive mind feature)
   - Each agent's `recall()` only searches branches they can read
   - Prevents context collapse: specialist doesn't see global command chatter
   - Captains see both their squad + global (dual-context)
   - Zeus sees only global (synthesized squad reports, not raw specialist noise)

**Relevant files**:
- `cvc/sdk/router.py` (NEW) — `Router` class with rule-based routing
- `.cvc/routing.yaml` (NEW) — routing configuration
- `cvc/sdk/agent.py` — `commit()` and `recall()` go through router

---

## Phase 7: Context Compaction & Distillation

**Goal**: As the hive mind grows (millions of commits), keep it efficient through AI-powered compaction.

**Steps**:

7.1. Hive context compaction
   - `hive.compact(strategy="summarize", max_age_hours=24)` — LLM-summarize old commit chains into single "distilled" commits
   - Uses existing `ContentBlob.distilled_summary` and `CommitMetadata.distilled_ratio` fields
   - Preserves Merkle integrity: compacted commit references original commits as parents

7.2. Per-agent context windowing
   - Each agent sees only last N commits from their scope (configurable)
   - Older commits accessible via `agent.recall()` (semantic search) but not in active context
   - Mirrors AstroSwarm's `context_commits[-3:]` pattern

7.3. Anchor commits for snapshotting
   - Periodic full-state snapshots (anchor commits) — existing CVC feature
   - Delta compression between anchors — existing CVC feature (is_delta, delta_bytes)
   - For hive: auto-anchor per squad every N commits

**Relevant files**:
- `cvc/sdk/compactor.py` (NEW) — `HiveCompactor` class
- `cvc/operations/engine.py` — extend commit pipeline for auto-anchor
- Reuse existing `ContentBlob.distilled_summary`, `CognitiveCommit.is_delta`, `CognitiveCommit.anchor_hash`

---

## Phase 8: HTTP API & TypeScript SDK

**Goal**: Make CVC accessible from any language — not just Python.

**Steps**:

8.1. REST API on proxy server
   - `POST /api/v1/agents` — register agent
   - `POST /api/v1/commits` — create commit (with agent_id, message, content, tags)
   - `GET /api/v1/commits?agent_id=...&squad=...&limit=...` — query commits
   - `POST /api/v1/recall` — semantic search
   - `GET /api/v1/branches` — list branches
   - `POST /api/v1/sync` — trigger sync with remote

8.2. TypeScript SDK (for cvc-node)
   - Mirror the Python SDK API: `new HiveMind()`, `hive.registerAgent()`, `agent.commit()`, etc.
   - Connect to CVC proxy via HTTP API
   - Enable React/Node.js developers to integrate hive mind into web apps

8.3. MCP-native multi-agent support
   - Extend `mcp_server.py` with per-agent session tracking
   - Each MCP session can specify `agent_id` — commits tagged accordingly
   - New MCP tools: `cvc_register_agent`, `cvc_agent_commit`, `cvc_agent_recall`

**Relevant files**:
- `cvc/proxy.py` — add `/api/v1/` REST endpoints
- `cvc-node/src/sdk/` (NEW) — TypeScript SDK
- `cvc/mcp_server.py` — add multi-agent MCP tools

---

## Phase 9: Visualization Dashboard

**Goal**: Live monitoring of hive mind activity.

**Steps**:

9.1. `cvc dashboard --hive` CLI command → opens web UI
9.2. DAG visualization with multiple concurrent branches (D3.js force graph or similar)
9.3. Agent activity heatmap (who committed recently, how frequently)
9.4. Squad-level aggregated views
9.5. Real-time commit stream via WebSocket
9.6. Timeline view with agent-colored commits

**Relevant files**:
- `cvc/dashboard/` (NEW) — web UI static files + FastAPI routes
- `cvc/cli.py` — add `cvc dashboard` command

---

## Verification

1. **Unit tests**: Add tests for each new module — `test_sdk_hivemind.py`, `test_registry.py`, `test_router.py`, `test_sync.py`, `test_events.py`
2. **Integration test: AstroSwarm replay** — Re-run the 51-agent experiment using the new SDK API instead of `cvc_bridge.py`. All 4 experiments (full crisis, radiation recovery, Mars blackout, meta-patch) should pass.
3. **Concurrency test**: 50 agents committing simultaneously to different branches — verify no data corruption, all commits present.
4. **CRDT sync test**: Two CVC instances, both receiving commits independently, sync and verify convergence.
5. **Offline resilience test**: Disconnect a squad, commit locally, reconnect, verify all commits are synced.
6. **SDK import test**: Verify `from cvc import HiveMind` works with minimal dependencies.
7. **Backward compatibility**: Existing `cvc` CLI commands (`status`, `log`, `commit`, `branch`, `merge`, `restore`) still work unchanged.
8. **TypeScript SDK smoke test**: Node.js script using cvc-node SDK connects to proxy and performs agent registration + commit + recall cycle.
9. **Manual verification**: Run `cvc log --agent MC-01`, `cvc log --squad aegis`, verify filtered views work correctly.

---

## Decisions

- **G-Set CRDT over OT**: CVC's append-only Merkle DAG is naturally a grow-only set. No need for Operational Transformation — commits are immutable, merge is union.
- **SQLite WAL remains**: SQLite + WAL mode handles concurrent reads well and moderate concurrent writes. For extreme scale (1000+ simultaneous writers), Phase 4 adds optional PostgreSQL/FoundationDB backend.
- **Backward-compatible**: SDK is additive. Existing CLI/proxy/MCP users are unaffected. The single-agent "Sofia" experience continues working.
- **Python-first**: SDK is Python-first (matching codebase). TypeScript SDK connects via HTTP API, not native bindings.
- **Scope boundary**: This plan covers the SDK and multi-agent features. It does NOT cover: production deployment infrastructure, Kubernetes operators, hardware robot integration, or LLM fine-tuning for hive mind behavior.

---

## Further Considerations

1. **Interplanetary latency**: Mars-Earth communication has 4-24 minute delays. The CRDT + offline-first design handles this naturally — squads operate autonomously with eventual consistency. CVC should add configurable sync intervals and priority queuing for critical commits (e.g., ALERT commits sync before routine RESULT commits).

2. **Scale ceiling**: SQLite handles ~100K commits well. For 1 lakh (100,000) robots each committing hourly, that's 2.4M commits/day. At that scale, need a sharded backend option (e.g., FoundationDB, CockroachDB, or a custom append-only log like Kafka). Phase 4's sync protocol is backend-agnostic by design.

3. **Security model**: Multi-agent implies multi-trust. Need: agent authentication (each agent has a signing key), commit signatures (agents sign their commits), and configurable trust levels (read-only vs read-write per agent per branch). This prevents rogue agents from corrupting the hive mind.

# Plan: Phase 9 — CVC Gateway & Web Dashboard

## TL;DR

Create a **CVC Gateway** service (distinct from the existing proxy) and a **best-in-class web dashboard** accessible at `http://localhost:3000` (or configurable port). Inspired by Open WebUI's architecture: `pip install open-webui && open-webui serve` → browser-based full management UI. The gateway is a persistent system service with lifecycle commands (`cvc gateway start|stop|restart|pause|status`). The dashboard presents a unified view of all 4 CVC subsystems: **Agent, Proxy, MCP, SDK** — their health, activity, logs, configuration, and real-time event streams. The proxy remains the AI-tool interceptor on port 8000; the gateway is a new broader service on port 3000 that hosts the dashboard, wraps the proxy lifecycle, and exposes management APIs.

## Architecture Decision

**Gateway vs Proxy distinction:**
- **Proxy** (existing, port 8000): OpenAI-compatible API interceptor for AI tools (VS Code, Cursor, Claude, Aider). Stays as-is.
- **Gateway** (new, port 3000): System-level service manager + web dashboard + management REST API. Manages the proxy as one of its child services. Like how Open WebUI runs on `:8080` and internally manages Ollama connections.

**Tech stack:**
- Backend: FastAPI (matches existing proxy — reuse patterns, shared codebase)
- Frontend: Single-page app served as static files from FastAPI
  - **Recommended**: Vanilla JS + Web Components + Tailwind CSS (zero build step, embedded in Python package)
  - Alternative: Svelte (like Open WebUI) or React — but adds Node.js build dependency
- Real-time: WebSocket (reuse existing `/ws/events` pattern from proxy)
- Process management: System-native (subprocess on Windows, systemd-compatible on Linux, launchd-compatible on macOS)

---

## Steps

### Phase 9A: Gateway Service Core (Use big and uniqe port no. so fdevelopers will feel easy on their projects)

1. **Create `cvc/gateway.py`** — the Gateway FastAPI application
   - New FastAPI app on port 3000 (configurable)
   - Lifespan manager: on startup, discover and health-check existing CVC subsystems
   - Manage child processes: proxy, MCP server
   - Expose management REST API at `/api/gateway/`
   - Serve static dashboard files from `cvc/dashboard/static/`
   - WebSocket at `/ws/dashboard` for real-time updates
   - *Depends on*: nothing, foundational

2. **Create `cvc/gateway_manager.py`** — process lifecycle manager
   - `GatewayManager` class: start/stop/restart/pause/resume/kill for each subsystem
   - Track child process PIDs in `.cvc/gateway.pid` and `.cvc/services.json`
   - Health polling loop (background asyncio task) — ping each subsystem's `/health`
   - Platform-specific process management:
     - Windows: `CREATE_NO_WINDOW | DETACHED_PROCESS`, `taskkill /PID`
     - Unix: `start_new_session`, signals (SIGTERM, SIGSTOP, SIGCONT)
   - Service registry: `{"proxy": {"pid": 1234, "port": 8000, "status": "running"}, ...}`
   - *Depends on*: step 1

3. **Add CLI commands to `cvc/cli.py`**
   - `cvc gateway start [--port 3000] [--host 0.0.0.0]` — start gateway (and optionally proxy/MCP)
   - `cvc gateway stop` — gracefully stop gateway + all managed services
   - `cvc gateway restart` — stop + start
   - `cvc gateway status` — show all service states (table)
   - `cvc gateway onboard` — interactive first-time setup wizard for gateway
   - `cvc gateway logs [--service proxy|mcp|agent|sdk]` — tail logs
   - Keep existing `cvc serve` as alias for proxy-only mode
   - *Depends on*: steps 1, 2

### Phase 9B: Dashboard REST API

4. **Service Status API** — `GET /api/gateway/services`
   - Returns status of all 4 CVC subsystems:
     ```json
     {
       "proxy": {"status": "running", "port": 8000, "pid": 1234, "uptime": "2h 15m", "connections": 3},
       "mcp": {"status": "running", "transport": "stdio", "sessions": 2},
       "agent": {"status": "idle", "active_sessions": 0, "last_used": "..."},
       "sdk": {"status": "available", "registered_agents": 5, "total_commits": 135}
     }
     ```
   - *Parallel with* step 5

5. **Activity & Analytics API** — `GET /api/gateway/analytics`
   - Aggregate from `cvc/core/database.py`:
     - Total commits (by type, by agent, by branch)
     - Token usage & cost (from audit_log)
     - Commit frequency timeline
     - Active branches & their status
     - Recent sessions (from proxy session tracker)
   - `GET /api/gateway/commits?limit=50&agent_id=...&branch=...` — paginated commit log
   - `GET /api/gateway/timeline` — commit timeline data (for DAG visualization)
   - *Parallel with* step 4

6. **Configuration API** — `GET/PUT /api/gateway/config`
   - Read/update CVC global config (provider, model, API key status, auto-commit interval)
   - Service-specific config (proxy port, MCP transport, agent settings)
   - `GET /api/gateway/config/integrations` — connected tools (detected IDEs, configured MCP clients)
   - *Depends on*: step 4

7. **Hive Mind API** (extends existing `/api/v1/` in proxy)
   - `GET /api/gateway/hivemind/agents` — registered SDK agents with status
   - `GET /api/gateway/hivemind/squads` — squad overview with commit counts
   - `GET /api/gateway/hivemind/events` — recent event bus activity
   - *Depends on*: step 4

### Phase 9C: Web Dashboard Frontend (Use TypeScript for better maintainability)

8. **Create `cvc/dashboard/` directory structure**
   ```
   cvc/dashboard/
   ├── __init__.py          # mount_dashboard(app) helper
   ├── routes.py            # FastAPI router for dashboard API
   └── static/
       ├── index.html        # SPA entry point
       ├── css/
       │   └── dashboard.css # Tailwind CSS (CDN) + custom CVC theme
       ├── js/
       │   ├── app.js        # Main SPA router + state management
       │   ├── components/   # Web Components
       │   │   ├── sidebar.js
       │   │   ├── service-card.js
       │   │   ├── commit-timeline.js
       │   │   ├── agent-heatmap.js
       │   │   ├── config-panel.js
       │   │   ├── log-viewer.js
       │   │   └── realtime-feed.js
       │   └── utils/
       │       ├── api.js     # REST API client
       │       └── ws.js      # WebSocket client
       └── assets/
           └── logo.svg       # CVC branding
   ```
   - *Depends on*: steps 4-7

9. **Dashboard Home Page** — overview of all 4 subsystems
   - 4 service cards (Agent, Proxy, MCP, SDK) showing:
     - Status indicator (green/yellow/red)
     - Key metrics (messages, commits, connections, agents)
     - Quick actions (start/stop/restart)  
   - System health bar (CPU, memory, uptime)
   - Recent activity feed (last 10 events from EventBus)
   - *Depends on*: step 8

10. **Proxy Dashboard Tab**
    - Real-time request stream (model, tokens, latency)
    - Session history (from `_SessionTracker`)
    - Connected tools (detected from User-Agent)
    - Auto-commit configuration toggle
    - Time Machine mode toggle
    - Upstream provider status
    - *Parallel with* steps 11-13

11. **Agent Dashboard Tab**
    - Active agent sessions list
    - Conversation history browser
    - Tool usage statistics
    - Memory/recall search interface
    - Cost tracker (tokens + estimated cost)
    - *Parallel with* steps 10, 12, 13

12. **MCP Dashboard Tab**
    - Connected MCP clients
    - Tool invocation log
    - Session state (workspace, branch, HEAD)
    - Transport mode indicator (stdio vs SSE)
    - *Parallel with* steps 10, 11, 13

13. **SDK/Hive Mind Dashboard Tab**
    - Registered agents table (ID, role, rank, squad, status)
    - Commit DAG visualization (D3.js force-directed or tree layout)
    - Branch viewer with merge status
    - Agent activity heatmap
    - Event stream (real-time from WebSocket)
    - Sync status (if multi-node)
    - *Parallel with* steps 10, 11, 12

14. **Settings/Config Page**
    - Provider & model selection
    - API key management (masked display)
    - Gateway port configuration
    - Integration status (VS Code, Cursor, etc.)
    - Tool permissions overview
    - *Depends on*: step 6

### Phase 9D: Real-Time WebSocket Layer

15. **WebSocket hub in gateway**
    - Reuse `EventBus` from `cvc/sdk/events.py`
    - Gateway subscribes to all events from proxy, MCP, SDK
    - Dashboard WebSocket pushes:
      - Service health changes
      - New commits
      - Session start/end
      - Agent activity
      - Error alerts
    - *Depends on*: steps 1, 8

16. **Log streaming**
    - `cvc gateway logs --follow` CLI command
    - WebSocket endpoint for browser log viewer
    - Aggregate logs from proxy, MCP, agent
    - *Depends on*: step 15

---

## Relevant Files

**New files to create:**
- `cvc/gateway.py` — Gateway FastAPI app (management server on port 3000)
- `cvc/gateway_manager.py` — Service lifecycle manager (start/stop/restart/pause/kill)
- `cvc/dashboard/__init__.py` — Dashboard mounting helper
- `cvc/dashboard/routes.py` — Dashboard API routes (FastAPI router)
- `cvc/dashboard/static/index.html` — SPA entry point
- `cvc/dashboard/static/css/dashboard.css` — CVC-themed styles
- `cvc/dashboard/static/js/app.js` — Main SPA logic
- `cvc/dashboard/static/js/components/*.js` — Web Components (7-8 files)
- `cvc/dashboard/static/js/utils/api.js` — REST API client
- `cvc/dashboard/static/js/utils/ws.js` — WebSocket client

**Existing files to modify:**
- `cvc/cli.py` — Add `cvc gateway` command group (start/stop/restart/status/onboard/logs)
- `cvc/proxy.py` — Add `/api/gateway/proxy-stats` endpoint for proxy-specific metrics; ensure health endpoint is enriched
- `cvc/launcher.py` — Refactor `_start_proxy_background()` and `ensure_proxy_running()` to be reusable by GatewayManager
- `cvc/sdk/events.py` — Ensure EventBus is singleton-safe and accessible from gateway
- `pyproject.toml` — Add dashboard static files to package data; add optional `[dashboard]` extras if any new deps

**Key existing code to reuse:**
- `cvc/proxy.py` → `lifespan()` pattern for FastAPI app lifecycle
- `cvc/proxy.py` → `/ws/events` WebSocket pattern for real-time streaming
- `cvc/proxy.py` → `_SessionTracker` for session data sourcing
- `cvc/launcher.py` → `_start_proxy_background()`, `_check_proxy_health()` for process management
- `cvc/sdk/events.py` → `EventBus`, `EventEnvelope`, `Subscription` for pub/sub
- `cvc/core/database.py` → `IndexDB` queries for commits, branches, agents, audit_log
- `cvc/core/models.py` → All Pydantic models for type-safe API responses
- `cvc/cli.py` → `CvcGroup`, `_banner()`, `_success()`, `_error()`, Rich styling patterns

---

## Verification

1. **Unit tests**: `tests/test_gateway.py` — test GatewayManager start/stop/restart lifecycle, service registry persistence, health polling
2. **API tests**: `tests/test_gateway_api.py` — test all `/api/gateway/*` endpoints return correct schemas
3. **Integration test**: Start gateway → verify proxy auto-starts → verify dashboard loads at `http://localhost:3000` → verify WebSocket connects and receives events
4. **CLI test**: Run `cvc gateway start` → verify process starts → `cvc gateway status` shows running → `cvc gateway stop` cleanly shuts down all services
5. **Browser test**: Open `http://localhost:3000` → verify all 4 service cards render → click through tabs (Proxy, Agent, MCP, SDK) → verify data loads
6. **Real-time test**: With gateway running, make a commit via proxy → verify dashboard updates in real-time via WebSocket
7. **Cross-platform**: Test on Windows (primary) and verify subprocess creation flags work; document any macOS/Linux-specific adjustments
8. **Backward compatibility**: Existing `cvc serve`, `cvc up`, `cvc launch` commands still work unchanged

---

## Decisions

- **Gateway port 3000** (configurable via `--port` or `CVC_GATEWAY_PORT` env var) to avoid conflict with proxy on 8000
- **Proxy stays independent**: The proxy can still run standalone via `cvc serve`. Gateway is an optional management layer on top.
- **No Node.js build step**: Dashboard frontend uses vanilla JS + Web Components + Tailwind CDN. Zero build dependency. This keeps `pip install cvc` clean. If the frontend grows complex later, can migrate to Svelte (like Open WebUI).
- **Static files served from Python package**: Dashboard HTML/CSS/JS bundled in the `cvc/dashboard/static/` directory and served by FastAPI's `StaticFiles` mount.
- **PID-based process management**: Each managed service writes its PID to `.cvc/services.json`. Gateway tracks and manages these. Graceful shutdown sends SIGTERM → waits 5s → SIGKILL.
- **Scope included**: Gateway service, dashboard UI (4 tabs + settings), CLI commands, WebSocket real-time streams, service lifecycle management
- **Scope excluded**: Kubernetes/systemd service files (future), mobile-responsive PWA (future), authentication/RBAC for dashboard (future, but should note for security), HTTPS/TLS (future)

---

## Further Considerations

1. **Dashboard authentication**: Currently the dashboard has no auth — fine for localhost, but if `--host 0.0.0.0` is used, anyone on the network can access it. Recommendation: Add optional basic auth or token-based auth from the start (reuse Firebase auth from `cvc/auth.py`), defaulting to no-auth on `127.0.0.1` and requiring auth on `0.0.0.0`.

2. **Log persistence**: Currently proxy logs go to stdout/DEVNULL. For the dashboard log viewer to work, we need a log sink (rotating file in `.cvc/logs/` or SQLite `logs` table). Recommendation: Add a `RotatingFileHandler` to `.cvc/logs/gateway.log` when running in gateway mode.

3. **Auto-start on boot**: Users may want `cvc gateway` to auto-start when their computer boots (like Ollama does). This is OS-specific (Windows: Task Scheduler, macOS: launchd plist, Linux: systemd unit). Recommendation: Defer to a future `cvc gateway install-service` command but design the gateway to be service-compatible from the start.
