# KERNL V2.0 - Desktop Commander Absorption Blueprint

## 🎯 EXECUTIVE SUMMARY

**Mission**: Absorb Desktop Commander's ~31 system control tools into KERNL, transforming it from a persistence layer into a complete "authoritative agency" platform.

**Current State**:
- ✅ KERNL has 44 tools (persistence + intelligence)
- ✅ Desktop Commander has ~31 tools (system control)
- ❌ Two separate MCP servers (duplication, friction)

**Target State**:
- ✅ KERNL has ~75 tools (persistence + intelligence + system control)
- ✅ Desktop Commander MCP can be removed
- ✅ Single unified intelligence layer

**Business Value**:
- **Eliminate friction**: One MCP server instead of two
- **Cognitive monopoly**: Complete system awareness + persistence
- **True agency**: Can read/write files AND remember context across crashes
- **Competitive moat**: No other AI has this combination

---

## 📊 CURRENT TOOL INVENTORY

### KERNL Tools (44 Total)

**State Management (4)**
- `save_session_state` - Manual checkpoint
- `get_session_state` - Retrieve state
- `mark_complete` - Mark task complete
- `list_incomplete_tasks` - Show unfinished

**Enhanced Filesystem (7)**
- `pm_read_file` - Read with project context
- `pm_write_file` - Write with project context
- `pm_list_files` - List with project context
- `pm_batch_read` - Batch read files
- `pm_search_files` - Search files
- `pm_get_file_info` - File metadata
- `pm_index_files` - Index for semantic search

**Project Operations (5)**
- `pm_register_project` - Register project
- `pm_get_project` - Get project info
- `pm_list_projects` - List all projects
- `pm_update_project` - Update project
- `pm_delete_project` - Delete project

**Semantic Search (3)**
- `search_semantic` - Semantic search
- `index_content` - Index content
- `get_similar_content` - Find similar

**Pattern Recognition (3)**
- `suggest_patterns` - Cross-project patterns
- `record_pattern` - Record pattern
- `get_patterns` - Retrieve patterns

**Async Jobs (4)**
- `start_async_job` - Start background job
- `get_job_status` - Check job status
- `cancel_job` - Cancel job
- `list_jobs` - List all jobs

**Conversation Export (1)**
- `export_conversations` - Export Claude.ai chats

**Chrome Export (3)**
- `chrome_export_status` - Check Chrome readiness
- `chrome_export_setup` - Get setup instructions
- `chrome_export_conversations` - Export via Chrome

**Backlog Management (5)**
- `query_backlog` - List EPICs
- `add_epic` - Create EPIC
- `update_epic` - Update EPIC
- `complete_epic` - Mark EPIC complete
- `get_project_status` - Project overview

**Git Operations (3)**
- `smart_commit` - Auto-generate commit message
- `session_package` - Package session for commit
- `get_git_status` - Git status

**Research (3)**
- `research_progressive` - Streaming research
- `search_research` - Search research history
- `get_research_status` - Research status

**Checkpoint (2)**
- `check_resume_needed` - Check if resume needed
- `auto_checkpoint` - Smart checkpointing

**Session Context (1)**
- `get_session_meta` - Session metadata

### Desktop Commander Tools (31 Total)

**Configuration & Meta (5)**
- `get_config` - Get server configuration ⭐ High priority
- `set_config_value` - Update configuration ⭐ High priority
- `get_usage_stats` - Usage statistics
- `get_recent_tool_calls` - Tool call history
- `give_feedback_to_desktop_commander` - Feedback form

**Enhanced File Operations (11)**
- `read_file` - Read with offset/length, Excel/PDF/images ⚠️ Overlaps pm_read_file
- `write_file` - Write with chunking, Excel support ⚠️ Overlaps pm_write_file
- `write_pdf` - Create/modify PDFs ⭐ High priority
- `read_multiple_files` - Batch read ⚠️ Overlaps pm_batch_read
- `edit_block` - Surgical editing ⭐ High priority
- `create_directory` - Create directories (basic)
- `list_directory` - List with recursive depth ⚠️ Overlaps pm_list_files
- `move_file` - Move/rename files
- `get_file_info` - File metadata with line counts ⚠️ Overlaps pm_get_file_info
- `list_allowed_directories` - Show accessible paths
- `copy_file_user_to_claude` - Bridge filesystems ⭐ High priority

**Search (4)**
- `start_search` - Streaming search ⭐ High priority
- `get_more_search_results` - Paginated results
- `stop_search` - Cancel search
- `list_searches` - Active searches

**Process Management (8)**
- `start_process` - Start terminal with smart detection ⭐ High priority
- `read_process_output` - Read with pagination ⭐ High priority
- `interact_with_process` - Send input to REPL ⭐ High priority
- `force_terminate` - Kill process
- `list_sessions` - Show active sessions
- `list_processes` - System processes
- `kill_process` - Terminate by PID

**Prompts (1)**
- `get_prompts` - Retrieve onboarding prompts

**Other (2)**
- Plus 2 more tools from usage stats (to identify)

---

## 🔍 OVERLAP ANALYSIS

### Critical Overlaps (Must Resolve)

| KERNL Tool | DC Tool | Resolution Strategy |
|------------|---------|-------------------|
| `pm_read_file` | `read_file` | **Merge**: DC version has superior capabilities (offset/length, Excel/PDF). Enhance pm_read_file with DC features, keep project-aware wrapper |
| `pm_write_file` | `write_file` | **Merge**: DC has chunking + Excel. Enhance pm_write_file with DC features |
| `pm_batch_read` | `read_multiple_files` | **Merge**: Similar functionality, merge implementations |
| `pm_list_files` | `list_directory` | **Merge**: DC has recursive depth. Enhance pm_list_files |
| `pm_get_file_info` | `get_file_info` | **Merge**: DC has line counts. Enhance pm_get_file_info |
| `pm_search_files` | `start_search` | **Keep Both**: Different approaches (basic vs streaming) |

### Unique DC Capabilities (Must Add)

**Critical** (Revolutionary features):
1. `edit_block` - Surgical file editing (most valuable DC tool)
2. `write_pdf` - PDF creation/modification
3. `start_process` + `interact_with_process` - REPL integration
4. `start_search` - Streaming search with pagination
5. `copy_file_user_to_claude` - Cross-filesystem bridge

**Important** (Enable full agency):
6. Process management suite (8 tools)
7. Configuration management (2 tools)
8. Usage tracking (2 tools)

---

## 🏗️ IMPLEMENTATION PHASES

### Phase 1: Foundation & Planning (Week 1, Days 1-2)
**Goal**: Architecture design and overlap resolution

**Tasks**:
1. ✅ Create absorption blueprint (THIS FILE)
2. Create detailed tool specifications
3. Design naming convention strategy
4. Plan dependency additions
5. Design merge strategy for overlapping tools

**Deliverables**:
- [ ] Complete tool specification document
- [ ] Naming convention decision
- [ ] Dependency analysis
- [ ] Merge architecture design

### Phase 2: Core System Tools (Week 1, Days 3-5)
**Goal**: Add most valuable unique DC capabilities

**Priority 1 - Revolutionary Tools**:
1. `edit_block` - Surgical editing (game-changer)
2. `write_pdf` - PDF operations
3. `start_process` - Process launcher
4. `interact_with_process` - REPL control
5. `read_process_output` - Process output
6. `copy_file_user_to_claude` - Filesystem bridge

**Implementation**:
- Create `src/tools/system-control.ts`
- Add process management subsystem
- Add PDF subsystem
- Add surgical editing subsystem

**Testing**:
- Test each tool independently
- Integration testing with existing KERNL tools
- Performance benchmarking

**Deliverables**:
- [ ] 6 new system control tools working
- [ ] Tests passing
- [ ] Documentation updated

### Phase 3: Enhanced File Operations (Week 1, Days 6-7)
**Goal**: Merge overlapping file operation tools

**Tasks**:
1. Enhance `pm_read_file` with DC's offset/length/Excel/PDF
2. Enhance `pm_write_file` with DC's chunking/Excel
3. Enhance `pm_list_files` with DC's recursive depth
4. Enhance `pm_get_file_info` with DC's line counts
5. Merge `pm_batch_read` and `read_multiple_files`

**Implementation Strategy**:
```typescript
// Keep project-aware wrapper, add DC capabilities
export async function pm_read_file(params: {
  project: string;  // KERNL addition
  path: string;
  offset?: number;  // DC addition
  length?: number;  // DC addition
  // ... DC features
}): Promise<FileContent> {
  // 1. Load project context
  // 2. Use DC's enhanced reading logic
  // 3. Track in KERNL database
  // 4. Return enriched result
}
```

**Deliverables**:
- [ ] 5 enhanced file operation tools
- [ ] Backward compatibility maintained
- [ ] Tests updated
- [ ] Documentation updated

### Phase 4: Search Capabilities (Week 2, Days 1-2)
**Goal**: Add streaming search with project awareness

**Tasks**:
1. Implement `start_search` with KERNL integration
2. Implement `get_more_search_results`
3. Implement `stop_search`
4. Implement `list_searches`
5. Integrate with existing `pm_search_files`

**Architecture**:
```typescript
// New: src/tools/advanced-search.ts
export const advancedSearchTools = [
  'start_search',       // Streaming search
  'get_more_results',   // Pagination
  'stop_search',        // Cancel
  'list_searches',      // Active searches
];

// Enhanced: keep pm_search_files for simple searches
// Add start_search for complex/large searches
```

**Deliverables**:
- [ ] 4 new search tools
- [ ] Integration with pm_search_files
- [ ] Performance testing
- [ ] Documentation

### Phase 5: Process Management (Week 2, Days 3-4)
**Goal**: Complete process control suite

**Tasks**:
1. Complete process management tools (remaining 5 tools)
2. Add process tracking to KERNL database
3. Integrate with session checkpointing
4. Add crash recovery for processes

**Architecture**:
```typescript
// New: src/tools/process-management.ts
export const processManagementTools = [
  'start_process',         // Already done in Phase 2
  'read_process_output',   // Already done in Phase 2
  'interact_with_process', // Already done in Phase 2
  'force_terminate',       // New
  'list_sessions',         // New
  'list_processes',        // New
  'kill_process',          // New
];
```

**Deliverables**:
- [ ] 5 additional process tools
- [ ] Process state persistence
- [ ] Integration with checkpointing
- [ ] Documentation

### Phase 6: Configuration & Meta (Week 2, Day 5)
**Goal**: Add configuration and usage tracking

**Tasks**:
1. Implement `get_config`
2. Implement `set_config_value`
3. Implement `get_usage_stats`
4. Implement `get_recent_tool_calls`
5. Add configuration management to KERNL

**Architecture**:
```typescript
// New: src/tools/configuration.ts
export const configurationTools = [
  'get_config',
  'set_config_value',
  'get_usage_stats',    // Merge with KERNL's existing tracking
  'get_recent_tool_calls',
];
```

**Deliverables**:
- [ ] 4 configuration tools
- [ ] Unified configuration system
- [ ] Usage analytics
- [ ] Documentation

### Phase 7: Integration & Testing (Week 2, Days 6-7)
**Goal**: Final integration, testing, and cleanup

**Tasks**:
1. Complete integration testing
2. Performance optimization
3. Update all documentation
4. Create migration guide
5. Test Desktop Commander removal

**Testing Checklist**:
- [ ] All 75 tools registered
- [ ] No tool conflicts
- [ ] TypeScript compiles (0 errors)
- [ ] All tests pass
- [ ] Performance benchmarks met
- [ ] Documentation complete
- [ ] Desktop Commander can be safely removed

**Deliverables**:
- [ ] V2.0 production-ready
- [ ] Complete documentation
- [ ] Migration guide
- [ ] Desktop Commander removal instructions

---

## 🎨 NAMING CONVENTION STRATEGY

### Decision: Hybrid Approach

**Project-Aware Tools** (KERNL-specific):
- Prefix: `pm_*` (Project Mind / Project Manager)
- Example: `pm_read_file`, `pm_write_file`
- When to use: Tool needs project context, session tracking, or KERNL database

**System Control Tools** (Desktop Commander heritage):
- Prefix: `sys_*` (System)
- Example: `sys_start_process`, `sys_edit_block`
- When to use: Pure system operations, no project context needed

**Enhanced Tools** (Merged):
- Prefix: `pm_*` (Project-aware wrapper around system capabilities)
- Example: `pm_read_file` (project context + DC's Excel/PDF support)
- When to use: Merging KERNL + DC functionality

**Rationale**:
1. **Clear separation**: Easy to see which tools are project-aware vs system-level
2. **Backward compatibility**: Existing pm_* tools keep their names
3. **Future-proof**: Easy to add more system tools with sys_* prefix
4. **Searchable**: Easy to find all system tools (`sys_*`) or project tools (`pm_*`)

### Examples

**Before Absorption**:
```
KERNL: pm_read_file (project-aware, basic)
DC: read_file (system-level, advanced features)
```

**After Absorption**:
```
pm_read_file (project-aware + DC features)
sys_read_file (pure system, no project context) - optional fallback
```

---

## 📦 DEPENDENCY ANALYSIS

### Desktop Commander Dependencies (To Add)

Based on Desktop Commander's likely implementation:

**Confirmed Needed**:
1. Process management (Node.js built-in)
2. PDF manipulation: `pdf-lib` (already in KERNL)
3. File watching: `chokidar` (already in KERNL)
4. Excel: `exceljs` (already in KERNL)

**Possibly Needed** (To Verify):
1. Terminal emulation: `node-pty` or similar
2. Shell detection: Built-in Node.js APIs
3. Process monitoring: Built-in Node.js APIs

**Already in KERNL**:
- `pdf-lib` ✅
- `pdf-parse` ✅
- `exceljs` ✅
- `chokidar` ✅
- `sharp` ✅

**Action**: Most dependencies already present! Minimal additions needed.

---

## 🔧 TECHNICAL ARCHITECTURE

### New File Structure

```
src/
├── tools/
│   ├── existing... (44 tools)
│   ├── system-control.ts         # NEW: Phase 2
│   │   ├── edit_block
│   │   ├── write_pdf
│   │   ├── copy_file_user_to_claude
│   ├── process-management.ts     # NEW: Phase 2 & 5
│   │   ├── start_process
│   │   ├── interact_with_process
│   │   ├── read_process_output
│   │   ├── force_terminate
│   │   ├── list_sessions
│   │   ├── list_processes
│   │   ├── kill_process
│   ├── advanced-search.ts        # NEW: Phase 4
│   │   ├── start_search
│   │   ├── get_more_search_results
│   │   ├── stop_search
│   │   ├── list_searches
│   ├── configuration.ts          # NEW: Phase 6
│   │   ├── get_config
│   │   ├── set_config_value
│   │   ├── get_usage_stats
│   │   ├── get_recent_tool_calls
│   ├── filesystem.ts             # ENHANCED: Phase 3
│   │   └── (merge DC capabilities)
│   └── index.ts                  # UPDATE: Export all
├── storage/
│   ├── database.ts               # ENHANCE: Add process tracking
│   └── process-tracker.ts        # NEW: Process state persistence
└── server/
    └── mcp-server.ts             # UPDATE: Register new tools
```

### Database Schema Extensions

```sql
-- NEW: Track running processes
CREATE TABLE IF NOT EXISTS processes (
  id TEXT PRIMARY KEY,
  project_id TEXT NOT NULL,
  pid INTEGER NOT NULL,
  command TEXT NOT NULL,
  started_at INTEGER NOT NULL,
  status TEXT NOT NULL, -- 'running', 'completed', 'failed'
  exit_code INTEGER,
  FOREIGN KEY (project_id) REFERENCES projects(id)
);

-- NEW: Track search sessions
CREATE TABLE IF NOT EXISTS search_sessions (
  id TEXT PRIMARY KEY,
  project_id TEXT,
  query TEXT NOT NULL,
  search_type TEXT NOT NULL, -- 'files', 'content'
  started_at INTEGER NOT NULL,
  status TEXT NOT NULL, -- 'running', 'completed', 'stopped'
  result_count INTEGER DEFAULT 0,
  FOREIGN KEY (project_id) REFERENCES projects(id)
);

-- ENHANCE: Add file operation tracking
ALTER TABLE file_operations ADD COLUMN operation_type TEXT; -- 'read', 'write', 'edit', 'search'
ALTER TABLE file_operations ADD COLUMN chunks_written INTEGER; -- for chunked writes
```

---

## ⚠️ CRITICAL CONSIDERATIONS

### 1. TypeScript Compilation
**Current State**: 
- KERNL has pre-existing errors in `video.ts` and `archive.ts`
- These don't affect core functionality
- V2.0 must maintain zero NEW errors

**Strategy**:
- Keep strict mode enforcement
- New tools must compile cleanly
- Don't fix old errors unless they block new features
- Document any new type definitions needed

### 2. Backward Compatibility
**Requirements**:
- All existing 44 KERNL tools must continue working
- No breaking changes to tool signatures
- Enhanced tools must support old parameters

**Testing**:
- Run existing tests before and after
- Create compatibility test suite
- Verify all integration points

### 3. Performance
**Targets**:
- Tool registration: <1 second
- File operations: <100ms for small files
- Search: First results <500ms
- Process start: <200ms

**Monitoring**:
- Add performance tracking to `get_usage_stats`
- Log slow operations
- Profile during testing

### 4. Security
**Considerations**:
- Process execution: Use `allowedDirectories` from config
- File operations: Maintain KERNL's security model
- Configuration: Protect sensitive settings

**Implementation**:
- Inherit DC's blocked commands list
- Add permission checks to new tools
- Audit all file system access

### 5. Error Handling
**Strategy**:
- Graceful degradation
- Clear error messages
- Automatic recovery where possible
- Log all errors for debugging

---

## 📊 SUCCESS METRICS

### Quantitative
- ✅ 75 total tools (44 current + 31 from DC)
- ✅ 0 new TypeScript errors
- ✅ All tests passing (>90% coverage)
- ✅ Performance within targets
- ✅ Desktop Commander removable from config

### Qualitative
- ✅ "Monopoly tool" status achieved
- ✅ Seamless file operations + persistence
- ✅ Process management with crash recovery
- ✅ Single MCP server for all operations
- ✅ Complete documentation

### User Experience
- ✅ No workflow disruption
- ✅ Enhanced capabilities feel natural
- ✅ Faster operations (merged tools)
- ✅ Better error messages
- ✅ Comprehensive help system

---

## 🚀 GETTING STARTED

### Immediate Next Steps

1. **Review this blueprint** with user
   - Confirm naming strategy (pm_* vs sys_*)
   - Confirm overlap resolution strategy
   - Confirm implementation phases

2. **Create tool specification document**
   - Document each of 31 DC tools in detail
   - Create implementation templates
   - Define test cases

3. **Set up development branch**
   ```bash
   cd "D:/Project Mind/kernl-mcp"
   git checkout feature/v2-absorb-desktop-commander
   git pull origin feature/v2-absorb-desktop-commander
   ```

4. **Begin Phase 2** (after blueprint approval)
   - Start with `edit_block` (highest value)
   - Add one tool at a time
   - Test incrementally

---

## 📚 REFERENCE DOCUMENTS

### To Create
- [ ] `TOOL_SPECIFICATIONS.md` - Detailed specs for all 31 DC tools
- [ ] `MERGE_STRATEGY.md` - How to merge overlapping tools
- [ ] `MIGRATION_GUIDE.md` - How to migrate from DC to KERNL V2.0
- [ ] `TESTING_PLAN.md` - Comprehensive testing strategy

### To Update
- [ ] `TOOL_REFERENCE.md` - Add new tools as implemented
- [ ] `README.md` - Update capabilities section
- [ ] Global instructions - Update tool count

---

## 💡 LESSONS FROM V1.0

**What Went Well**:
1. Foundation-first approach (database, persistence)
2. Incremental tool addition
3. Comprehensive documentation
4. TypeScript strict mode

**What to Improve**:
1. **Don't rush**: V1.0 was incomplete, missing system control
2. **Test integration**: V1.0 had isolated tools, better integration needed
3. **Performance**: Some operations were slow, optimize from start
4. **Documentation**: Keep docs updated as tools added

**Apply to V2.0**:
1. Complete each phase fully before moving on
2. Integration testing at each phase
3. Performance benchmarks from start
4. Document as we build, not after

---

## 🎯 V2.0 VISION STATEMENT

**Before V2.0**:
- KERNL: Persistence + intelligence (incomplete)
- Desktop Commander: System control (separate server)
- User: Manages two MCP servers, context switching

**After V2.0**:
- KERNL: Persistence + intelligence + system control (complete)
- Desktop Commander: Deprecated, removable
- User: Single unified intelligence layer, seamless operations

**The Promise**:
> "KERNL V2.0 eliminates the 8-minute death, the bootstrap tax, AND provides full desktop control. One MCP server. Complete agency. Zero friction."

---

*Blueprint Version: 1.0*  
*Created: January 7, 2026*  
*Status: Awaiting approval to begin Phase 2*
