# Foundation MCP Server - Product Requirements Document

## Executive Summary

**Foundation** is a unified MCP server that consolidates three specialized tools into a single, cohesive platform for AI-assisted development, themed around Asimov's Foundation universe:

1. **Demerzel** - Codebase intelligence beyond context limits (R. Daneel Olivaw)
2. **Seldon** - Multi-agent orchestration with provider routing (Hari Seldon)
3. **Gaia** - Session management and collective learning (The Collective Consciousness)

The result is a comprehensive toolkit that any Claude Code user (CLI or GUI) can leverage, while visual frontends like Ludicrous Ralphy become thin clients that consume Foundation's capabilities via MCP.

---

## Problem Statement

Currently, developers using Claude Code must:
- Install and configure 3+ separate MCP servers
- Deal with overlapping functionality (worktrees in 2 places, reviews in 2 places)
- Manage separate configuration files for each tool
- Hope that tools don't conflict with each other

Ludicrous Ralphy has internal implementations (ArgusManager, AgentRouter) that duplicate MCP server functionality, creating maintenance burden and feature drift.

---

## Solution

**One MCP server. One configuration. Complete AI development toolkit.**

```
┌──────────────────────────────────────────────────────────────────┐
│                         FOUNDATION                                │
│                                                                   │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐               │
│  │  DEMERZEL   │  │   SELDON    │  │    GAIA     │               │
│  │ (Codebase)  │  │  (Agents)   │  │ (Workflow)  │               │
│  └─────────────┘  └─────────────┘  └─────────────┘               │
│         │                │                │                       │
│         └────────────────┼────────────────┘                       │
│                          ▼                                        │
│  ┌──────────────────────────────────────────────────────────┐    │
│  │                    SHARED SERVICES                        │    │
│  │  • StorageService (unified JSON persistence)              │    │
│  │  • GitService (worktrees, branches, diffs)                │    │
│  │  • ProviderService (13+ AI providers with failover)       │    │
│  │  • ConfigService (single ~/.foundation/config.yaml)       │    │
│  └──────────────────────────────────────────────────────────┘    │
│                          │                                        │
│                          ▼                                        │
│                    MCP STDIO TRANSPORT                            │
└──────────────────────────────────────────────────────────────────┘
                           │
            ┌──────────────┼──────────────┐
            ▼              ▼              ▼
      Claude Code    Ludicrous      Other MCP
         (CLI)       Ralphy (GUI)    Clients
```

---

## Modules

### Module 1: Demerzel (Codebase Intelligence)

**Source:** `@sashabogi/argus-mcp`
**Character:** R. Daneel Olivaw/Demerzel - 20,000 years of perfect memory, observing silently

**Purpose:** Understand codebases that exceed LLM context limits through intelligent snapshots and progressive disclosure.

**Tools (9):**

| Tool | Description | Token Cost |
|------|-------------|------------|
| `demerzel_snapshot` | Create codebase snapshot | 0 |
| `demerzel_search` | Regex search across codebase | 0 |
| `demerzel_find_files` | Glob pattern file matching | 0 |
| `demerzel_find_symbol` | Locate function/class definitions | 0 |
| `demerzel_find_importers` | Find files that import a module | 0 |
| `demerzel_get_deps` | Get file dependencies | 0 |
| `demerzel_get_context` | Get lines around a location | 0 |
| `demerzel_analyze` | AI-powered deep analysis | ~500 |
| `demerzel_semantic_search` | Natural language code search | ~100 |

**Key Features:**
- Enhanced snapshots with import graph and export index
- Zero-cost tools for 90% of queries
- Configurable AI provider for deep analysis
- Snapshot staleness detection

---

### Module 2: Seldon (Multi-Agent Orchestration)

**Source:** `hari-seldon`
**Character:** Hari Seldon - Created psychohistory, the Plan guides humanity's future

**Purpose:** Route tasks to specialized AI agents across 13+ providers with intelligent failover. Includes verification loop for automated plan → execute → verify → fix cycles.

**Tools (19):**

| Tool | Description |
|------|-------------|
| **Agent Invocation** | |
| `seldon_invoke` | Invoke a single agent by role |
| `seldon_compare` | Run same task through multiple agents |
| `seldon_critique` | Get adversarial plan critique |
| `seldon_review` | Get code review feedback |
| `seldon_design` | Get UI/UX design feedback |
| **Planning** | |
| `seldon_plan` | Generate detailed implementation plan from intent |
| `seldon_phase_create` | Break work into sequential, verifiable phases |
| `seldon_phase_list` | View all phases and their status |
| **Verification Loop** | |
| `seldon_verify` | Verify implementation against plan (critical/major/minor) |
| `seldon_fix` | Generate fixes for verification issues |
| `seldon_execute_verified` | YOLO Mode - execute with auto verify/fix loop |
| `seldon_execute_parallel` | Execute phases in parallel worktrees |
| **Pipelines** | |
| `seldon_pipeline_create` | Create multi-step DAG workflow |
| `seldon_pipeline_execute` | Execute a pipeline |
| `seldon_pipeline_status` | Get pipeline execution status |
| **Tasks** | |
| `seldon_task_execute` | Execute task in isolated worktree |
| `seldon_task_claim` | Claim next available task (worker pattern) |
| **Providers** | |
| `seldon_providers_list` | List available providers and health |
| `seldon_providers_test` | Test provider connectivity |

**Agent Roles:**
- `orchestrator` - Task synthesis, planning
- `coder` - Code generation (uses worktrees)
- `critic` - Adversarial plan review
- `reviewer` - Code review
- `designer` - UI/UX feedback
- `researcher` - Information gathering
- `verifier` - Implementation verification against plans

**Key Features:**
- 13+ AI providers (OpenAI, Anthropic, Gemini, DeepSeek, Ollama, etc.)
- Intelligent failover with health tracking and circuit breakers
- Cost-aware routing
- Session delegation mode for Claude Code (zero-cost Anthropic calls)
- DAG pipeline execution with dependency resolution
- **Verification Loop:** Plan → Execute → Verify → Fix → Re-verify (automatic)
- **Severity Thresholds:** Critical, Major, Minor issue categorization
- **Parallel Execution:** Multiple phases in separate worktrees simultaneously

---

### Module 3: Gaia (Workflow Patterns)

**Source:** `claude-workflow-orchestrator`
**Character:** Gaia - The collective consciousness, "We are all one, and one is all"

**Purpose:** Implement proven workflow patterns from the Claude Code team. Collective learning and memory.

**Tools (13):**

| Tool | Description |
|------|-------------|
| `gaia_worktree_create` | Create git worktree with session |
| `gaia_worktree_list` | List active worktrees |
| `gaia_worktree_switch` | Navigate between worktrees |
| `gaia_worktree_cleanup` | Remove stale worktrees |
| `gaia_session_register` | Track Claude session purpose |
| `gaia_session_status` | View active sessions |
| `gaia_session_handoff` | Prepare context for handoff |
| `gaia_session_complete` | Mark session as done |
| `gaia_learn` | Record correction for CLAUDE.md |
| `gaia_apply` | Write learnings to CLAUDE.md |
| `gaia_review` | Review accumulated learnings |
| `gaia_remember` | Save context state |
| `gaia_recall` | Restore previous context |

**Key Features:**
- Self-learning CLAUDE.md (capture mistakes, apply fixes)
- Session handoff documents with git status, changes, next steps
- Context memories for project state preservation
- Shell alias generation for quick worktree navigation

---

## Tool Naming Convention

All tools are prefixed by module for clarity:

- `demerzel_*` - Codebase intelligence (The Observer)
- `seldon_*` - Agent orchestration (The Planner)
- `gaia_*` - Workflow patterns (The Memory)

This prevents conflicts and makes tool discovery intuitive.

---

## Migration Plan

### Phase 1: Foundation Core (Week 1)
- [x] Project setup (TypeScript, MCP SDK, Zod)
- [x] ConfigService with YAML parsing
- [x] StorageService with JSON persistence
- [x] GitService with worktree operations
- [x] Basic MCP server with stdio transport

### Phase 2: Demerzel Module (Week 2)
- [ ] Port snapshot creation (basic + enhanced)
- [ ] Port search tools (regex, glob, symbol, importers)
- [ ] Port context tools (get_context, get_deps)
- [ ] Port AI analysis (with provider abstraction)
- [ ] Add semantic search

### Phase 3: Seldon Module (Week 3)
- [ ] Port ProviderService with all 13+ providers
- [ ] Port failover system (health, circuit breakers)
- [ ] Port agent invocation tools
- [ ] Port pipeline execution (DAG)
- [ ] Port task execution with worktree isolation

### Phase 4: Gaia Module (Week 4)
- [ ] Port worktree tools (unified with GitService)
- [ ] Port session management
- [ ] Port learning capture/apply
- [ ] Port context memories
- [ ] Add shell alias generation

### Phase 5: Integration & Polish (Week 5)
- [ ] CLI interface
- [ ] Setup wizard
- [ ] Documentation
- [ ] Testing
- [ ] Ludicrous Ralphy integration guide

---

## Success Metrics

1. **Single Install:** One `npm install` provides all capabilities
2. **Single Config:** One `~/.foundation/config.yaml` for everything
3. **No Duplication:** Each feature exists in exactly one place
4. **Full Coverage:** All features from all 3 projects are preserved
5. **Clean API:** Intuitive tool naming and consistent patterns
6. **Backward Compat:** Existing Argus/Hari Seldon users can migrate easily

---

## Appendix: Tool Count Summary

| Module | Tools | From | Character |
|--------|-------|------|-----------|
| Demerzel | 9 | argus-mcp | R. Daneel Olivaw |
| Seldon | 19 | hari-seldon | Hari Seldon |
| Gaia | 13 | workflow-orchestrator | The Collective |
| **Total** | **41** | | |

**Final Count: 41 unique tools** (after adding verification loop)
