﻿# KERNL V2.0 - MONOPOLY TOOL SPECIFICATION
**Date:** January 7, 2026  
**Version:** 2.0.0  
**Status:** Ready for Implementation  
**Architecture:** Direct Implementation (Replaces Desktop Commander)

---

## 🎯 MISSION

Transform KERNL from a **persistence layer** into **THE ONLY TOOL YOU NEED** by:
- ✅ Implementing full filesystem access directly (Node.js fs)
- ✅ Implementing process management directly (child_process)
- ✅ Implementing Chrome control directly (puppeteer/chrome-launcher)
- ✅ Implementing desktop control directly (robotjs, screenshot-desktop)
- ✅ **PRIORITY: Complete conversation export system (all 4 approaches)**

**Result:** Desktop Commander → DELETED. Filesystem MCP → DELETED. One tool does everything.

---

## 🚀 PRIORITY FEATURE: CONVERSATION EXPORT

### Why This Is The Game Changer

**User Need:**
> "For another project, it's imperative that I absorb all the conversations in and out of projects - all conversations."

**The Problem:**
- Claude Desktop stores conversations locally
- Web interface limits bulk export
- Current v1.0 Playwright scraper is slow
- Need access to ALL conversations (including deleted)

**The Solution: Four Simultaneous Approaches**

---

## 📦 APPROACH 1: FILESYSTEM DIRECT (Fastest)

### Discovery Phase

```typescript
async function discoverClaudeData(): Promise<string[]> {
  const searchPaths = [
    // Windows
    path.join(process.env.APPDATA, 'Claude'),
    path.join(process.env.LOCALAPPDATA, 'Claude'),
    
    // Mac
    path.join(os.homedir(), 'Library', 'Application Support', 'Claude'),
    
    // Linux
    path.join(os.homedir(), '.config', 'claude')
  ];
  
  const found = [];
  for (const p of searchPaths) {
    if (await fs.access(p).then(() => true).catch(() => false)) {
      found.push(p);
    }
  }
  
  return found;
}
```

### Database Access

```typescript
async function readClaudeDatabase(dbPath: string) {
  // Claude Desktop likely uses SQLite or LevelDB
  const db = await open({ filename: dbPath, driver: sqlite3.Database });
  
  // Find conversations table
  const tables = await db.all(`
    SELECT name FROM sqlite_master 
    WHERE type='table'
  `);
  
  // Export all conversations
  const conversations = await db.all(`
    SELECT * FROM conversations 
    ORDER BY created_at DESC
  `);
  
  return conversations;
}
```

### IndexedDB/LocalStorage

```typescript
async function readWebStorage() {
  // If Claude Desktop uses Electron's web storage
  const userDataPath = app.getPath('userData');
  
  // Read IndexedDB
  const indexedDB = await readIndexedDB(userDataPath);
  
  // Read LocalStorage
  const localStorage = await readLocalStorage(userDataPath);
  
  return { indexedDB, localStorage };
}
```

**Benefits:**
- ⚡ Fastest approach (direct file read)
- 📦 Access to deleted conversations (if in cache)
- 🔓 Bypasses web rate limits
- 💯 Most complete dataset

---

## 🌐 APPROACH 2: CHROME CONTROL (Most Reliable)

### Implementation

```typescript
import puppeteer from 'puppeteer';
import { ChromeLauncher } from 'chrome-launcher';

async function exportViaChrome() {
  // Option A: Use existing Chrome instance
  const chrome = await ChromeLauncher.launch({
    startingUrl: 'https://claude.ai',
    chromeFlags: ['--remote-debugging-port=9222']
  });
  
  const browser = await puppeteer.connect({
    browserURL: 'http://localhost:9222'
  });
  
  // Option B: Execute JS in user's active Chrome tab
  const page = await browser.pages().then(pages => 
    pages.find(p => p.url().includes('claude.ai'))
  );
  
  // Access conversation data directly from page
  const conversations = await page.evaluate(() => {
    // Access React component state
    const reactRoot = document.querySelector('#root');
    const internalInstance = reactRoot['__reactFiber$'] || 
                            reactRoot['__reactInternalInstance$'];
    
    // Navigate to conversation store
    const store = findConversationStore(internalInstance);
    
    // Extract all conversations
    return store.conversations.map(conv => ({
      id: conv.id,
      title: conv.title,
      messages: conv.messages,
      created: conv.createdAt,
      updated: conv.updatedAt
    }));
  });
  
  return conversations;
}
```

### Streaming Export

```typescript
async function streamConversations(onProgress: (data: any) => void) {
  const page = await setupChromePage();
  
  // Stream conversations one by one
  const conversationIds = await page.evaluate(() => {
    return window.__CLAUDE_STORE__.conversationIds;
  });
  
  for (let i = 0; i < conversationIds.length; i++) {
    const conv = await page.evaluate((id) => {
      return window.__CLAUDE_STORE__.getConversation(id);
    }, conversationIds[i]);
    
    onProgress({
      progress: (i + 1) / conversationIds.length,
      conversation: conv
    });
  }
}
```

**Benefits:**
- 🔐 Uses YOUR logged-in session (no auth)
- ⚡ Direct access to page data
- 🎯 Can access active conversations
- 📡 Real-time updates

---

## 🖥️ APPROACH 3: DESKTOP APP CONTROL (Game Changer)

### Window Control

```typescript
import robot from 'robotjs';
import screenshot from 'screenshot-desktop';

async function controlClaudeDesktop() {
  // Find Claude Desktop window
  const windows = await getWindowList();
  const claudeWindow = windows.find(w => 
    w.title.includes('Claude') || w.process.includes('Claude')
  );
  
  if (!claudeWindow) {
    throw new Error('Claude Desktop not running');
  }
  
  // Focus window
  await focusWindow(claudeWindow.id);
  
  // Wait for focus
  await sleep(500);
  
  return claudeWindow;
}
```

### Automated Export

```typescript
async function exportViaDesktopControl() {
  const conversations = [];
  
  // 1. Focus Claude Desktop
  await controlClaudeDesktop();
  
  // 2. Open search/conversations list
  robot.keyTap('k', ['command']); // Cmd+K or Ctrl+K
  await sleep(300);
  
  // 3. Capture screen to see conversation list
  const screen = await screenshot();
  const convList = await ocrConversationList(screen);
  
  // 4. For each conversation
  for (const conv of convList) {
    // Click on conversation
    await clickConversation(conv.position);
    await sleep(500);
    
    // Select all text
    robot.keyTap('a', ['command']);
    await sleep(100);
    
    // Copy
    robot.keyTap('c', ['command']);
    await sleep(100);
    
    // Read clipboard
    const content = await readClipboard();
    
    conversations.push({
      title: conv.title,
      content: content,
      captured: new Date()
    });
  }
  
  return conversations;
}
```

### OCR Support

```typescript
import Tesseract from 'tesseract.js';

async function ocrConversationList(screenshot: Buffer) {
  const { data: { text } } = await Tesseract.recognize(screenshot, 'eng');
  
  // Parse conversation titles from OCR
  const titles = text.split('\n')
    .filter(line => line.trim().length > 0)
    .map(line => ({
      title: line.trim(),
      // Estimate position (would need better detection)
      position: estimatePosition(line, screenshot)
    }));
  
  return titles;
}
```

**Benefits:**
- 🎮 Complete automation (no user interaction)
- 📸 Can capture visual state
- 🔍 OCR reads any text on screen
- 💪 Works even if web APIs change
- 🎯 Controls ACTUAL Claude Desktop app

---

## 🔄 APPROACH 4: META-RECURSIVE (Creative)
### Inception Approach

```typescript
async function metaRecursiveExport() {
  // Use Claude's native tools through MCP
  const request = {
    task: 'export_all_conversations',
    instructions: `
      Use your native tools to export all conversations:
      1. Call recent_chats({n: 20}) repeatedly to paginate
      2. For each chat, call conversation_search to get full content
      3. Use web_fetch on claude.ai URLs if needed
      4. Return as structured JSON
    `,
    format: 'json'
  };
  
  // KERNL asks Claude to do the work
  const response = await askClaude(request);
  
  // Parse Claude's response
  const conversations = JSON.parse(response);
  
  // Store in database
  await storeConversations(conversations);
  
  return conversations;
}
```

### Cross-Validation

```typescript
async function validateCompleteness() {
  // Use meta approach to validate filesystem/chrome exports
  const filesystemCount = await countFilesystemConversations();
  const chromeCount = await countChromeConversations();
  
  // Ask Claude how many conversations exist
  const claudeCount = await askClaude({
    task: 'count_conversations',
    instructions: 'Use recent_chats tool repeatedly to count total'
  });
  
  // Compare
  const complete = (filesystemCount >= claudeCount) || 
                   (chromeCount >= claudeCount);
  
  return { complete, counts: { filesystem, chrome, claude } };
}
```

**Benefits:**
- 🧠 Uses Claude's built-in tools
- ✅ Can validate other approaches
- 🔄 Self-aware export process
- 🎯 Leverages existing MCP tools

---

## 🏗️ UNIFIED EXPORT SYSTEM

### Master Export Function

```typescript
interface ExportOptions {
  methods: ('filesystem' | 'chrome' | 'desktop' | 'meta')[];
  deduplicate: boolean;
  validate: boolean;
  streaming: boolean;
  onProgress?: (status: ExportProgress) => void;
}

async function exportAllConversations(options: ExportOptions) {
  const results = {
    filesystem: null,
    chrome: null,
    desktop: null,
    meta: null
  };
  
  // Try methods in parallel
  const promises = options.methods.map(async method => {
    try {
      switch(method) {
        case 'filesystem':
          results.filesystem = await exportViaFilesystem();
          break;
        case 'chrome':
          results.chrome = await exportViaChrome();
          break;
        case 'desktop':
          results.desktop = await exportViaDesktopControl();
          break;
        case 'meta':
          results.meta = await metaRecursiveExport();
          break;
      }
    } catch (error) {
      console.error(`${method} export failed:`, error);
    }
  });
  
  await Promise.all(promises);
  
  // Merge and deduplicate
  const merged = mergeConversations(results, options.deduplicate);
  
  // Validate completeness
  if (options.validate) {
    const validation = await validateCompleteness();
    merged.validation = validation;
  }
  
  // Store in database
  await storeInDatabase(merged.conversations);
  
  return merged;
}
```

### Deduplication Strategy

```typescript
function mergeConversations(
  results: ExportResults, 
  deduplicate: boolean
) {
  const all = [
    ...(results.filesystem || []),
    ...(results.chrome || []),
    ...(results.desktop || []),
    ...(results.meta || [])
  ];
  
  if (!deduplicate) {
    return { conversations: all, duplicates: 0 };
  }
  
  // Deduplicate by conversation ID
  const seen = new Map();
  const unique = [];
  const duplicates = [];
  
  for (const conv of all) {
    const id = conv.id || generateId(conv);
    
    if (seen.has(id)) {
      duplicates.push(conv);
      // Merge content if different
      const existing = seen.get(id);
      if (conv.content !== existing.content) {
        existing.content = mergeDifferentVersions(
          existing.content, 
          conv.content
        );
      }
    } else {
      seen.set(id, conv);
      unique.push(conv);
    }
  }
  
  return {
    conversations: unique,
    duplicates: duplicates.length,
    sources: {
      filesystem: results.filesystem?.length || 0,
      chrome: results.chrome?.length || 0,
      desktop: results.desktop?.length || 0,
      meta: results.meta?.length || 0
    }
  };
}
```

---

## 📊 IMPLEMENTATION PHASES

### Phase 1: Core Infrastructure (Days 1-3)

**Files to Create:**
```
src/export/
├── index.ts                    # Main export coordinator
├── filesystem-export.ts        # Approach 1
├── chrome-export.ts            # Approach 2
├── desktop-export.ts           # Approach 3
├── meta-export.ts              # Approach 4
├── deduplication.ts            # Merge & dedupe
└── storage.ts                  # Database storage
```

**Dependencies to Install:**
```bash
npm install puppeteer chrome-launcher
npm install robotjs screenshot-desktop
npm install tesseract.js
npm install better-sqlite3
npm install clipboardy  # Clipboard access
```

**Day 1: Filesystem Discovery**
- Implement discoverClaudeData()
- Test on Windows/Mac/Linux
- Find SQLite database
- Read conversation tables
- Export to JSON

**Day 2: Chrome Control**
- Setup puppeteer
- Connect to existing Chrome
- Execute JS in page
- Extract conversation data
- Test streaming export

**Day 3: Desktop Control**
- Setup robotjs
- Implement window focus
- Test keyboard/mouse control
- Implement clipboard reading
- Basic OCR setup

### Phase 2: Integration (Days 4-5)

**Day 4: Unified Export**
- Create master export function
- Implement parallel execution
- Add progress streaming
- Build deduplication logic

**Day 5: Meta-Recursive**
- Implement Claude-asks-Claude approach
- Use MCP tools (recent_chats, conversation_search)
- Cross-validate results
- Add completeness checking

### Phase 3: Storage & Search (Day 6)

**Database Schema:**
```sql
CREATE TABLE exported_conversations (
  id TEXT PRIMARY KEY,
  title TEXT,
  content TEXT,
  created_at TIMESTAMP,
  updated_at TIMESTAMP,
  source TEXT,  -- 'filesystem', 'chrome', 'desktop', 'meta'
  project_id TEXT,
  embedding BLOB,  -- For semantic search
  metadata JSON
);

CREATE INDEX idx_conversations_created 
  ON exported_conversations(created_at);
CREATE INDEX idx_conversations_project 
  ON exported_conversations(project_id);
```

**Semantic Search Integration:**
```typescript
async function indexConversations(conversations: Conversation[]) {
  for (const conv of conversations) {
    // Generate embedding
    const embedding = await generateEmbedding(conv.content);
    
    // Store with embedding
    await db.run(`
      INSERT OR REPLACE INTO exported_conversations
      (id, title, content, created_at, updated_at, 
       source, embedding, metadata)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `, [
      conv.id,
      conv.title,
      conv.content,
      conv.created_at,
      conv.updated_at,
      conv.source,
      embedding,
      JSON.stringify(conv.metadata)
    ]);
  }
}
```

### Phase 4: MCP Tools (Day 7)

**New Tools:**
```typescript
{
  name: 'export_all_conversations',
  description: 'Export ALL Claude conversations using 4 simultaneous approaches',
  inputSchema: {
    type: 'object',
    properties: {
      methods: {
        type: 'array',
        items: {
          enum: ['filesystem', 'chrome', 'desktop', 'meta', 'all']
        },
        default: ['all']
      },
      streaming: { type: 'boolean', default: true },
      deduplicate: { type: 'boolean', default: true }
    }
  }
}

{
  name: 'search_exported_conversations',
  description: 'Search exported conversations semantically or by keyword',
  inputSchema: {
    type: 'object',
    properties: {
      query: { type: 'string' },
      semantic: { type: 'boolean', default: true },
      project: { type: 'string' },
      dateFrom: { type: 'string' },
      dateTo: { type: 'string' },
      limit: { type: 'number', default: 20 }
    },
    required: ['query']
  }
}

{
  name: 'analyze_conversations',
  description: 'Analyze patterns across all exported conversations',
  inputSchema: {
    type: 'object',
    properties: {
      analysisType: {
        enum: ['patterns', 'topics', 'decisions', 'lessons']
      },
      project: { type: 'string' },
      timeRange: { type: 'string' }
    },
    required: ['analysisType']
  }
}
```

---

## 🎯 SUCCESS CRITERIA

### Phase 1 Complete When:
- ✅ Can read Claude Desktop's local database
- ✅ Can control Chrome and extract conversations
- ✅ Can control Claude Desktop app
- ✅ All 4 approaches work independently

### Phase 2 Complete When:
- ✅ Unified export runs all 4 in parallel
- ✅ Deduplication works correctly
- ✅ Progress streaming implemented
- ✅ Validation confirms completeness

### Phase 3 Complete When:
- ✅ All conversations stored in database
- ✅ Semantic search works
- ✅ Can search by project/date/topic
- ✅ Fast queries (<100ms)

### Phase 4 Complete When:
- ✅ MCP tools registered
- ✅ Claude can export conversations
- ✅ Search works from chat
- ✅ Analysis tools provide insights

---

## 📈 EXPECTED RESULTS

**Speed Comparison:**
| Method | Time for 1000 Conversations |
|--------|---------------------------|
| v1.0 Playwright | ~60 minutes |
| Filesystem Direct | ~5 seconds |
| Chrome Control | ~30 seconds |
| Desktop Control | ~10 minutes |
| Meta-Recursive | ~2 minutes |
| **All 4 Parallel** | **~10 minutes** |

**Completeness:**
- Filesystem: 100% (includes deleted if cached)
- Chrome: 95% (current web conversations)
- Desktop: 90% (visible conversations)
- Meta: 85% (via MCP tools)
- **Combined: 100%**

---

## 🔧 NEXT: FILESYSTEM OPERATIONS

After conversation export, implement remaining Desktop Commander functionality:

**Week 2: File Operations**
- Read/write any file (Node.js fs)
- All formats (PDF, Excel, images)
- Streaming for large files
- Transaction support

**Week 3: Process Management**
- Interactive REPLs (Python/Node/Shell)
- Background jobs
- State persistence

**Week 4: Search**
- Streaming file search
- Content search
- Semantic ranking

---

## ✅ READY TO BUILD

**First Commit:**
```bash
git add docs/V2_MONOPOLY_SPEC.md
git commit -m "feat(v2): Add monopoly tool spec with 4-approach conversation export"
```

**First Implementation:**
```bash
mkdir -p src/export
touch src/export/{index,filesystem-export,chrome-export,desktop-export,meta-export}.ts
npm install puppeteer robotjs screenshot-desktop tesseract.js clipboardy
```

**LET'S BUILD THE GAME CHANGER! 🚀**