<p align="center">
  <img src="docs/foundation-banner.jpg" alt="Foundation - Unified MCP Server" width="100%">
</p>

<p align="center">
  <a href="https://www.npmjs.com/package/@sashabogi/foundation"><img src="https://img.shields.io/npm/v/@sashabogi/foundation.svg" alt="npm version"></a>
  <a href="https://www.npmjs.com/package/@sashabogi/foundation"><img src="https://img.shields.io/npm/dm/@sashabogi/foundation.svg" alt="npm downloads"></a>
  <a href="https://github.com/sashabogi/foundation/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@sashabogi/foundation.svg" alt="license"></a>
</p>

Three pillars from Asimov's Foundation universe, working together:

| Module | Character | Purpose | Tools |
|--------|-----------|---------|-------|
| **Demerzel** | R. Daneel Olivaw | Codebase intelligence - 20,000 years of perfect memory | 9 |
| **Seldon** | Hari Seldon | Multi-agent orchestration - the Plan guides the future | 19 |
| **Gaia** | The Collective | Workflow patterns - "We are all one, and one is all" | 13 |

**One install. One config. 41 tools.**

---

## Quick Start

```bash
# Install
npm install -g @sashabogi/foundation

# Setup wizard (configure providers)
foundation init

# Add to Claude Code
foundation mcp install
```

Restart Claude Code. Foundation is now available.

---

## Modules

### 🤖 Demerzel: Codebase Intelligence

*"I have been watching for 20,000 years."*

Named after R. Daneel Olivaw/Demerzel - the robot who guided humanity across millennia with perfect memory and silent observation.

```bash
# Create a snapshot of your codebase
demerzel_snapshot path="." enhanced=true

# Search (zero AI cost)
demerzel_search path=".foundation/snapshot.txt" pattern="TODO"

# Find where a symbol is defined (zero AI cost)
demerzel_find_symbol path=".foundation/snapshot.txt" symbol="AuthProvider"

# Deep AI analysis (~500 tokens)
demerzel_analyze path=".foundation/snapshot.txt" query="How does authentication work?"
```

**Tools**: `demerzel_snapshot`, `demerzel_search`, `demerzel_find_files`, `demerzel_find_symbol`, `demerzel_find_importers`, `demerzel_get_deps`, `demerzel_get_context`, `demerzel_analyze`, `demerzel_semantic_search`

---

### 📊 Seldon: Multi-Agent Orchestration

*"The future is not set, but it can be guided."*

Named after Hari Seldon - the mathematician who created psychohistory to predict and guide humanity's future through the Seldon Plan.

#### Agent Invocation
```bash
# Invoke a specific agent role
seldon_invoke role="critic" task="Review this architectural decision..."

# Compare multiple agents on the same task
seldon_compare roles=["critic", "reviewer"] task="Evaluate this approach..."

# Get code review
seldon_review code="function auth() { ... }" focus=["security", "performance"]
```

#### Planning
```bash
# Generate a detailed implementation plan
seldon_plan intent="Add OAuth2 authentication" context="Express backend"

# Break work into phases
seldon_phase_create intent="Build user dashboard with real-time updates"

# View phase status
seldon_phase_list
```

#### Verification Loop (The Key Innovation)
```
Plan → Execute → Verify → Fix → Re-verify → ✓ Next Phase
                   ↑_____________|
                   (automatic, with severity thresholds)
```

```bash
# Verify implementation against a plan
seldon_verify planId="plan_abc123" runTests=true

# Generate fixes for issues
seldon_fix verificationId="ver_xyz789" severityThreshold="major" autoApply=true

# YOLO Mode: Execute with automatic verify/fix loop
seldon_execute_verified \
  phaseId="phase_abc123" \
  maxAttempts=3 \
  severityThreshold="major" \
  autoFix=true

# Execute multiple phases in parallel (each in its own worktree)
seldon_execute_parallel \
  phaseIds=["phase_1", "phase_2", "phase_3"] \
  worktreePerPhase=true \
  mergeStrategy="sequential"
```

#### Pipelines
```bash
# Create and execute pipelines
seldon_pipeline_create name="feature-dev" steps=[...]
seldon_pipeline_execute pipelineId="pipe_abc123"
```

**Agent Roles**: `orchestrator`, `coder`, `critic`, `reviewer`, `designer`, `researcher`, `verifier`

**Providers**: Anthropic, OpenAI, Google Gemini, DeepSeek, Groq, Together, Fireworks, OpenRouter, Z.AI, Kimi, Ollama, Perplexity

**Tools**:
- *Invocation*: `seldon_invoke`, `seldon_compare`, `seldon_critique`, `seldon_review`, `seldon_design`
- *Planning*: `seldon_plan`, `seldon_phase_create`, `seldon_phase_list`
- *Verification*: `seldon_verify`, `seldon_fix`, `seldon_execute_verified`, `seldon_execute_parallel`
- *Pipelines*: `seldon_pipeline_create`, `seldon_pipeline_execute`, `seldon_pipeline_status`
- *Tasks*: `seldon_task_execute`, `seldon_task_claim`
- *Providers*: `seldon_providers_list`, `seldon_providers_test`

---

### 🌍 Gaia: Workflow Patterns

*"We are all one, and one is all."*

Named after Gaia - the planet-wide collective consciousness where every individual shares memory and learns as one.

#### Parallel Worktrees
*"The single biggest productivity unlock"*

```bash
# Create worktrees for parallel Claude sessions
gaia_worktree_create branch="feature/auth" alias="a" purpose="OAuth implementation"
gaia_worktree_create branch="bugfix/login" alias="b" purpose="Fix login crash"

# Quick switch (generates shell aliases)
# alias za='cd /path/to/project-a && claude'
# alias zb='cd /path/to/project-b && claude'
```

#### Collective Learning
*"Every correction benefits all future sessions"*

```bash
# Capture a correction
gaia_learn \
  mistake="Used any type instead of proper typing" \
  correction="Always use explicit types, never any" \
  category="code_style"

# Apply to CLAUDE.md
gaia_apply
```

#### Session Memory

```bash
# Register a session
gaia_session_register purpose="Implementing OAuth2" taskType="feature"

# Create handoff document for another session
gaia_session_handoff sessionId="sess_abc123" includeGitStatus=true

# Remember context for later
gaia_remember name="pre-refactor" notes="Before auth rewrite"

# Recall a memory
gaia_recall name="pre-refactor"
```

**Tools**: `gaia_worktree_create`, `gaia_worktree_list`, `gaia_worktree_switch`, `gaia_worktree_cleanup`, `gaia_session_register`, `gaia_session_status`, `gaia_session_handoff`, `gaia_session_complete`, `gaia_learn`, `gaia_apply`, `gaia_review`, `gaia_remember`, `gaia_recall`

---

## Configuration

Foundation uses a single YAML config file:

**Location**: `~/.foundation/config.yaml`

```yaml
version: "1.0"

# Global defaults
defaults:
  temperature: 0.7
  max_tokens: 4096
  timeout_ms: 60000

# Provider API keys (use environment variables)
providers:
  anthropic:
    api_key: ${ANTHROPIC_API_KEY}
    access_mode: session  # Use current Claude session when possible
  openai:
    api_key: ${OPENAI_API_KEY}
    default_model: gpt-4o
  deepseek:
    api_key: ${DEEPSEEK_API_KEY}
    default_model: deepseek-reasoner
  ollama:
    base_url: http://localhost:11434
    default_model: llama3.3:70b

# Role assignments with fallback chains
roles:
  orchestrator:
    provider: anthropic
    model: claude-sonnet-4-20250514
  coder:
    provider: deepseek
    model: deepseek-reasoner
    needs_worktree: true
    fallback_chain:
      - provider: openai
        model: gpt-4o
  critic:
    provider: deepseek
    model: deepseek-reasoner
    temperature: 0.3
  reviewer:
    provider: openai
    model: gpt-4o

# Demerzel settings (codebase intelligence)
demerzel:
  provider: ollama
  model: qwen2.5-coder:7b
  snapshot_max_age_hours: 24

# Gaia settings (workflow patterns)
worktrees:
  base_dir: .foundation/worktrees
  max_count: 10
  auto_cleanup: true

learning:
  auto_apply: false
```

---

## The Foundation Trilogy

Just as in Asimov's universe, the three work together:

```
┌─────────────────────────────────────────────────────────────┐
│                      FOUNDATION                              │
│                                                              │
│   DEMERZEL          SELDON              GAIA                │
│   (The Observer)    (The Planner)       (The Memory)        │
│                                                              │
│   Knows the         Orchestrates        Preserves context   │
│   codebase          the agents          across sessions     │
│   perfectly         and plans           and learns          │
│                                                              │
│   "I have been      "The future is      "We are all one,    │
│    watching for      not set, but it     and one is all"    │
│    20,000 years"     can be guided"                         │
└─────────────────────────────────────────────────────────────┘
```

---

## Data Storage

```
~/.foundation/
├── config.yaml              # Main configuration
├── state/
│   ├── worktrees.json       # Active worktrees
│   ├── sessions.json        # Session tracking
│   ├── learnings.json       # Global learnings
│   ├── pipelines.json       # Pipeline state
│   ├── tasks.json           # Task queue
│   ├── snapshots.json       # Context memories
│   └── provider-health.json # Provider health tracking
└── cache/
    └── ...

.foundation/                 # Project-level (in repo root)
├── config.yaml              # Project overrides
├── snapshot.txt             # Codebase snapshot (Demerzel)
├── learnings.json           # Project-specific learnings (Gaia)
└── sessions.json            # Project sessions (Gaia)
```

---

## Development

```bash
# Clone and install
git clone https://github.com/sashabogi/foundation.git
cd foundation
npm install

# Build
npm run build

# Development with watch
npm run dev

# Run directly
npm start
```

---

## Credits

Foundation consolidates work from:
- [Argus](https://github.com/sashabogi/argus) → **Demerzel**
- [Hari Seldon](https://github.com/sashabogi/hari-seldon) → **Seldon**
- Claude Workflow Orchestrator → **Gaia**

Inspired by Isaac Asimov's Foundation series.

---

## License

MIT
