npm package: @sashabogi/foundation
Description: Unified MCP server for AI-assisted development: codebase intelligence, multi-agent orchestration, and workflow patterns with advanced memory
Author: Sasha Bogojevic
Latest version: 3.0.1

# Foundation v2.0

> **Production-grade MCP server for AI-assisted development**
>
> *"The future is not fixed, but it can be guided."* — Hari Seldon

Foundation is a unified Model Context Protocol (MCP) server combining three specialized modules inspired by Isaac Asimov's Foundation series. **Version 2.0 introduces Gaia v2.0** with SQLite-backed persistent memory, full-text search, and cross-prompt linking.

[![Version](https://img.shields.io/npm/v/@sashabogi/foundation)](https://www.npmjs.com/package/@sashabogi/foundation)
[![License](https://img.shields.io/npm/l/@sashabogi/foundation)](./LICENSE)

---

## 📚 Table of Contents

- [Overview](#overview)
- [What's New in v2.0](#whats-new-in-v20)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Modules](#modules)
  - [Demerzel - Codebase Intelligence](#demerzel---codebase-intelligence)
  - [Seldon - Multi-Agent Orchestration](#seldon---multi-agent-orchestration)
  - [Gaia - Workflow + Memory](#gaia---workflow--memory)
- [Gaia v2.0 Deep Dive](#gaia-v20-deep-dive)
- [Usage Examples](#usage-examples)
- [Performance](#performance)
- [Migration from v1.x](#migration-from-v1x)

---

## Overview

Foundation provides **41 MCP tools** across three modules:

| Module | Tools | Purpose |
|--------|-------|---------|
| **Demerzel** | 9 | Codebase intelligence beyond context limits |
| **Seldon** | 12 | Multi-agent orchestration and reasoning |
| **Gaia** | 20 | Workflow patterns + persistent memory |

Each module operates independently but they work together seamlessly. Use one, two, or all three depending on your needs.

---

## What's New in v2.0

### 🚀 Gaia v2.0: Advanced Memory System

The biggest upgrade in Foundation v2.0 is **Gaia's transformation** from a simple checkpoint system into a production-grade memory engine:

#### Before (v1.x)
- ❌ Basic checkpoint system (session state only)
- ❌ No search capabilities
- ❌ Manual CLAUDE.md management
- ❌ Ephemeral memory (lost between sessions)
- ❌ No relationships between memories

#### After (v2.0)
- ✅ **SQLite + FTS5 storage** - Production-grade database
- ✅ **5-tier memory hierarchy** - session, project, global, note, observation
- ✅ **BM25 ranking** - Intelligent search with composite scoring
- ✅ **Cross-prompt linking** - Build dependency graphs
- ✅ **Persistent storage** - Memories survive restarts
- ✅ **Sub-millisecond performance** - 0.1ms inserts, 2ms search
- ✅ **Complementary to native** - Works alongside Claude Code's memory

### Architecture Changes

```
v1.x:  Demerzel + Seldon + Gaia (checkpoints only)
       ├─ 9 tools + 12 tools + 9 tools = 30 total

v2.0:  Demerzel + Seldon + Gaia (workflow + memory)
       ├─ 9 tools + 12 tools + 20 tools = 41 total
       └─ Gaia now includes:
          • 9 workflow tools (checkpoints, learning)
          • 5 memory tools (save, search, get, delete, stats)
          • 2 linking tools (link, graph)
          • 4 additional utilities
```

---

## Installation

### Prerequisites

- Node.js 18+ (recommended: 22+)
- Claude Code CLI (or any MCP-compatible client)

### Install via npm

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

### Configure in Claude Code

Add to `~/.claude.json`:

```json
{
  "mcpServers": {
    "foundation": {
      "command": "npx",
      "args": ["@sashabogi/foundation"]
    }
  }
}
```

### Verify Installation

```bash
foundation status
```

Output:
```
🏛️  Foundation v2.0.0
   Modules: Demerzel (codebase) | Seldon (agents) | Gaia (workflow + memory)
```

---

## Quick Start

### 1. Create a Codebase Snapshot (Demerzel)

```typescript
demerzel_snapshot({
  path: "/Users/you/project",
  output: ".foundation/snapshot.txt"
})
```

### 2. Save a Memory (Gaia)

```typescript
gaia_save({
  tier: "project",
  content: "Authentication uses JWT with RS256 algorithm. Tokens expire after 1 hour.",
  tags: ["auth", "jwt", "security"],
  related_files: ["src/auth/jwt.ts"]
})
```

### 3. Search Memories

```typescript
gaia_search({
  query: "JWT authentication security",
  tiers: ["project", "global"],
  limit: 10
})
```

### 4. Link Memories

```typescript
gaia_link({
  from_memory_id: "mem_impl_456",
  to_memory_id: "mem_decision_123",
  link_type: "depends_on"
})

gaia_graph({ memory_id: "mem_impl_456" })
```

---

## Modules

### Demerzel - Codebase Intelligence

*"I have been watching for 20,000 years."* — R. Daneel Olivaw/Demerzel

Demerzel provides **codebase intelligence beyond context limits**. Create snapshots, search with regex, find symbols, trace dependencies, and analyze architecture.

**When to use:**
- Before reading 3+ files to understand codebase
- Finding where functions/classes are defined
- Tracing import dependencies
- Asking "how does X work?" across entire codebase

**Tools (9):**
```
demerzel_snapshot          // Create codebase snapshot
demerzel_search           // Regex search (FREE - no tokens)
demerzel_find_files       // Glob pattern matching (FREE)
demerzel_find_symbol      // Locate symbol definitions (FREE)
demerzel_find_importers   // Find files that import X (FREE)
demerzel_get_deps         // Get file dependencies (FREE)
demerzel_get_context      // Get code around location (FREE)
demerzel_analyze          // AI-powered analysis (~500 tokens)
demerzel_semantic_search  // Natural language search
```

---

### Seldon - Multi-Agent Orchestration

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

Seldon enables **multi-agent reasoning and orchestration**. Invoke specialized roles, compare perspectives, verify implementations, and execute multi-phase plans.

**When to use:**
- Getting design feedback before implementation
- Code reviews with different perspectives
- Breaking complex tasks into phases
- Verification loops for critical code

**Tools (12):**
```
seldon_invoke            // Invoke agent role
seldon_compare           // Compare perspectives
seldon_critique          // Critical review
seldon_review            // Code review
seldon_design            // Design feedback
seldon_plan              // Generate plan
seldon_phase_create      // Break into phases
seldon_phase_list        // View phases
seldon_verify            // Verify implementation
seldon_fix               // Generate fixes
seldon_execute_verified  // Execute with verification
seldon_execute_parallel  // Execute phases in parallel
```

---

### Gaia - Workflow + Memory

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

Gaia provides **workflow patterns and persistent memory**. Version 2.0 transforms Gaia from a simple checkpoint system into a production-grade memory engine with SQLite backend, full-text search, and cross-prompt linking.

**When to use:**
- Preserving context between sessions
- Building knowledge graphs across prompts
- Tracking architectural decisions
- Searching past conversations
- Capturing patterns and learnings

**Tools (20 total):**

#### Workflow Tools (9)
```
gaia_checkpoint       // Save structured session state
gaia_status          // Lightweight index card (~150 tokens)
gaia_query           // Keyword search checkpoint
gaia_get_decisions   // List architectural decisions
gaia_get_progress    // Task progress summary
gaia_get_changes     // Files changed
gaia_learn           // Record correction for CLAUDE.md
gaia_apply           // Apply learnings to CLAUDE.md
gaia_review          // Review learnings
```

#### Memory Tools (5)
```
gaia_save    // Save memory (SQLite + FTS5)
gaia_search  // Search with BM25 + composite scoring
gaia_get     // Get memory by ID
gaia_delete  // Delete memory + cascade links
gaia_stats   // Database statistics
```

#### Linking Tools (2)
```
gaia_link   // Create typed link between memories
gaia_graph  // Get link graph for a memory
```

---

## Gaia v2.0 Deep Dive

### Memory Architecture

Gaia v2.0 uses a **5-tier memory hierarchy** that organizes memories by scope and permanence:

```
┌─────────────────────────────────────────────────────────┐
│              Gaia Memory Hierarchy                      │
├─────────────────────────────────────────────────────────┤
│                                                           │
│  SESSION (ephemeral)                                     │
│  ├─ Lasts only this session                              │
│  ├─ Task progress, temporary notes                       │
│  └─ Auto-deleted on session end                          │
│                                                           │
│  PROJECT (current working directory)                     │
│  ├─ Scoped to current project                            │
│  ├─ Architectural decisions, code patterns               │
│  └─ Persists across sessions                             │
│                                                           │
│  GLOBAL (user-wide)                                      │
│  ├─ Best practices, common patterns                      │
│  ├─ Applies to all projects                              │
│  └─ Long-term knowledge                                  │
│                                                           │
│  NOTE (manual knowledge base)                            │
│  ├─ Explicitly saved reference material                  │
│  ├─ Tutorials, documentation summaries                   │
│  └─ Never auto-deleted                                   │
│                                                           │
│  OBSERVATION (autonomous learnings)                      │
│  ├─ Automatically captured patterns                      │
│  ├─ User behavior, common mistakes                       │
│  └─ Low-priority background knowledge                    │
│                                                           │
└─────────────────────────────────────────────────────────┘
```

### Composite Scoring Algorithm

When you search, Gaia uses **composite scoring** to rank results intelligently:

```typescript
final_score = (
  prompt_relevance * 0.40 +  // FTS5 BM25 (how well query matches)
  recency * 0.25 +            // Exponential decay (30-day half-life)
  tier_priority * 0.15 +      // session=1.0, project=0.8, global=0.6, ...
  file_proximity * 0.10 +     // Match with current file context
  access_frequency * 0.10     // How often accessed (log scale)
)
```

**Example:**

```typescript
gaia_search({
  query: "JWT authentication security",
  current_file: "src/auth/jwt.ts",
  limit: 5
})
```

Returns:
```json
{
  "results": [
    {
      "id": "mem_abc123",
      "content": "Authentication uses JWT with RS256...",
      "score": 0.87,
      "score_breakdown": {
        "relevance": 0.95,  // Exact match on "JWT authentication"
        "recency": 1.0,     // Created today
        "tier": 0.8,        // Project tier
        "proximity": 1.0,   // related_files includes current file
        "frequency": 0.3    // Accessed a few times
      }
    }
  ]
}
```

### Cross-Prompt Linking

Build **dependency graphs** across memories with 5 typed links:

```typescript
const decision = gaia_save({
  tier: "project",
  content: "Decision: Use React 18 with TypeScript",
  tags: ["decision", "architecture"]
})

const impl = gaia_save({
  tier: "project",
  content: "Implementation: Set up Vite with React 18 + TS",
  tags: ["implementation"]
})

gaia_link({
  from_memory_id: impl.memory.id,
  to_memory_id: decision.memory.id,
  link_type: "depends_on"
})

gaia_graph({ memory_id: impl.memory.id })
```

**Link Types:**
- `depends_on` - This memory requires/builds on another
- `extends` - This memory enhances another
- `reverts` - This memory undoes another
- `related` - Associative connection
- `contradicts` - This memory conflicts with another

### Database Schema

Gaia uses **SQLite with FTS5** for production-grade storage:

```sql
-- Main storage
CREATE TABLE memories (
  id TEXT PRIMARY KEY,
  tier TEXT NOT NULL,
  content TEXT NOT NULL,
  tags TEXT NOT NULL,           -- JSON array
  related_files TEXT NOT NULL,  -- JSON array
  session_id TEXT,
  project_path TEXT,
  created_at INTEGER NOT NULL,
  accessed_at INTEGER NOT NULL,
  access_count INTEGER DEFAULT 0,
  metadata TEXT                 -- JSON object
);

-- Full-text search with porter stemming
CREATE VIRTUAL TABLE memories_fts USING fts5(
  content,
  tags,
  related_files,
  tokenize='porter unicode61'
);

-- Cross-prompt links with CASCADE delete
CREATE TABLE memory_links (
  from_memory_id TEXT NOT NULL,
  to_memory_id TEXT NOT NULL,
  link_type TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  PRIMARY KEY (from_memory_id, to_memory_id, link_type),
  FOREIGN KEY (from_memory_id) REFERENCES memories(id) ON DELETE CASCADE,
  FOREIGN KEY (to_memory_id) REFERENCES memories(id) ON DELETE CASCADE
);
```

**Location:** `~/.foundation/gaia-memory.db`

---

## Usage Examples

### Example 1: Building a Knowledge Base

```typescript
gaia_save({
  tier: "project",
  content: "Decision: Use PostgreSQL with Drizzle ORM for type safety",
  tags: ["decision", "database", "architecture"],
  related_files: ["drizzle.config.ts"],
  metadata: { decision_type: "technical", impact: "high" }
})

gaia_save({
  tier: "project",
  content: "PostgreSQL connection pool configured with max 20 connections",
  tags: ["database", "configuration"],
  related_files: ["src/db/index.ts"]
})

gaia_search({
  query: "database PostgreSQL decision",
  tiers: ["project"],
  limit: 5
})
```

### Example 2: Cross-Prompt Dependencies

```typescript
const decision = gaia_save({
  tier: "project",
  content: "Decision: Use tRPC for type-safe API",
  tags: ["decision", "api"]
})

const impl = gaia_save({
  tier: "project",
  content: "Created tRPC router with user and auth procedures",
  tags: ["implementation"],
  related_files: ["src/server/trpc.ts"]
})

gaia_link({
  from_memory_id: impl.memory.id,
  to_memory_id: decision.memory.id,
  link_type: "depends_on"
})

gaia_graph({ memory_id: impl.memory.id })
```

### Example 3: Session Workflow

```typescript
gaia_search({
  query: "authentication JWT implementation",
  current_file: "src/auth/verify.ts"
})

gaia_save({
  tier: "session",
  content: "Bug: JWT verification doesn't handle expired tokens gracefully",
  tags: ["bug", "jwt"]
})

gaia_checkpoint({
  summary: "Fixed JWT token expiration handling",
  decisions: [{
    topic: "Error handling",
    decision: "Return 401 with clear message on expired tokens",
    rationale: "Better UX than generic 500 error"
  }],
  changes: [{
    file: "src/auth/verify.ts",
    action: "modified",
    summary: "Added token expiration check"
  }]
})
```

---

## Performance

### Benchmarks

System: MacBook Pro M1, Node.js v22

```
Storage Operations (1000 memories):
  Insert:  0.091ms avg (110x faster than 10ms target)
  Search:  2ms (25x faster than 50ms target)
  Get:     ~1ms (5x faster than 5ms target)

Database:
  Size:    0.43 MB for 1003 memories
  WAL:     Enabled for concurrent reads
  Cache:   64MB page cache
```

---

## Migration from v1.x

**Good news:** No breaking changes! All v1.x tools work identically in v2.0.

### What Changed

- ✅ **Checkpoints still work** - `gaia_checkpoint`, `gaia_get_decisions`, etc.
- ✅ **Learning still works** - `gaia_learn`, `gaia_apply`, `gaia_review`
- ✅ **New tools added** - `gaia_save`, `gaia_search`, `gaia_link`, `gaia_graph`, etc.

### What to Update

**Optional:** Start using the new memory tools for persistent knowledge:

```typescript
gaia_checkpoint({
  summary: "Implemented auth",
  decisions: [...]
})

gaia_save({
  tier: "project",
  content: "Auth implementation uses JWT with RS256",
  tags: ["auth", "implementation", "decision"]
})
```

See [MIGRATION-GUIDE.md](./docs/MIGRATION-GUIDE.md) for detailed upgrade instructions.

---

## License

MIT © Sasha Bogojevic

---

## Acknowledgments

Inspired by Isaac Asimov's Foundation series:
- **Demerzel** - R. Daneel Olivaw, 20,000 years of perfect memory
- **Seldon** - Hari Seldon, who predicted and guided the future
- **Gaia** - The collective consciousness, "we are all one"

Built with:
- [Model Context Protocol](https://modelcontextprotocol.io)
- [better-sqlite3](https://github.com/WiseLibs/better-sqlite3)
- [SQLite FTS5](https://www.sqlite.org/fts5.html)