# WZRDClaw Patterns Skill
## Drive/Steer/Toolshed Architecture Implementation Guide

### Overview
Provides specialized instructions for working with WZRDClaw architecture patterns: **Drive** (execution), **Steer** (guidance), and **Toolshed** (tool management). Use this skill when implementing, extending, or debugging WZRDClaw components.

### Core Architecture Components

#### 1. Toolshed - Tool & Skill Management
```
Toolshed = {
  tools: Map<string, Tool>       // Registered tools (bash, read, write, etc.)
  skills: Map<string, Skill>     // Specialized skill modules  
  mcps: Map<string, MCPClient>   // Model Context Protocol clients
}
```

**Key Responsibilities:**
- Tool registration and discovery
- Skill loading and execution
- MCP client integration
- Tool/skill search and filtering

**Usage Patterns:**
```javascript
// Register a tool
toolshed.registerTool('custom', {
  description: 'Custom tool',
  execute: async (params) => ({ success: true })
});

// Load a skill  
toolshed.registerSkill('wzrdclaw-patterns', skillModule);

// Get MCP client
const jcodemunch = toolshed.getMCP('jcodemunch');
```

#### 2. Drive - Execution Engine
```
Drive = {
  mode: 'CHAT'|'CODER'|'THINKER'|'DEBUG'|'RESEARCH'
  context: Record<string, any>
  session: SessionState
  activeTask: Task|null
  performance: PerformanceMetrics
}
```

**Mode Detection Rules:**
- **CHAT**: Casual conversation, simple questions, greetings
- **CODER**: Code generation, implementation, "write function", "create code"
- **THINKER**: Architecture, planning, design, "how should I", system-level
- **DEBUG**: Error fixing, "broken", "not working", stack traces  
- **RESEARCH**: Deep investigation, "compare", "analyze", "latest trends"

**Context Management:**
```javascript
// Update context
drive.updateContext('currentFile', '/path/to/file.js');

// Change mode
drive.setMode('CODER');

// Execute tool through drive
const result = await drive.executeTool('bash', { command: 'ls -la' });
```

#### 3. Steer - Guidance & Routing
```
Steer = {
  rules: Array<Rule>  // Conditional routing rules
  suggestions: Array<ToolSuggestion>
  history: Array<Interaction>
}
```

**Rule Definition:**
```javascript
steer.addRule({
  name: 'Auto Mode Detection',
  condition: (input) => true, // Always evaluate
  action: async (input, drive) => {
    const detectedMode = analyzeInputForMode(input);
    drive.setMode(detectedMode);
  }
});
```

**Tool Suggestions:**
```javascript
// Based on input pattern, suggest relevant tools
const suggestions = steer.getToolSuggestions('search for files');
// Returns: ['glob', 'grep', 'find']
```

### Common Implementation Patterns

#### Pattern A: Tool Extension
When adding new tools to WZRDClaw:
1. Create tool class with `execute` method
2. Register in Toolshed
3. Add usage examples to skill documentation
4. Update API client if needed

#### Pattern B: Mode-Specific Behavior  
When implementing mode-specific logic:
1. Detect mode via keyword patterns
2. Load mode-specific skills/tools
3. Adjust response style (code-first for CODER, analysis-first for THINKER)
4. Track mode transitions

#### Pattern C: Session Management
When handling multi-turn conversations:
1. Preserve context across turns
2. Update session state with tool results
3. Manage conversation history
4. Handle session persistence

#### Pattern D: MCP Integration
When integrating external MCP clients:
1. Check for existing MCP implementations
2. Create fallback simulation
3. Handle connection failures gracefully
4. Provide enhanced simulation when real client unavailable

### WZRDClaw Skill Templates

#### Skill: wzrdclaw-tools
```javascript
// Skill for creating WZRDClaw-compatible tools
module.exports = {
  name: 'wzrdclaw-tools',
  description: 'Create and register WZRDClaw tools',
  
  execute: async (params) => {
    const { toolName, implementation } = params;
    
    // Template for new tool
    const toolTemplate = `
class ${toolName.charAt(0).toUpperCase() + toolName.slice(1)}Tool {
  constructor() {
    this.description = '${toolName} tool for WZRDClaw';
  }
  
  async execute(params) {
    // Implementation here
    ${implementation}
  }
}

module.exports = ${toolName.charAt(0).toUpperCase() + toolName.slice(1)}Tool;
    `;
    
    return { template: toolTemplate };
  }
};
```

#### Skill: wzrdclaw-mcp-integration  
```javascript
// Skill for MCP client integration
module.exports = {
  name: 'wzrdclaw-mcp-integration',
  description: 'Integrate MCP clients with WZRDClaw',
  
  patterns: {
    // jcodemunch integration pattern
    jcodemunch: {
      checkClient: 'test-jcodemunch-minimal.py',
      integration: 'real-jcodemunch-integration.js',
      fallback: 'enhanced simulation in wzrdclaw-core.js'
    },
    
    // Generic MCP pattern
    generic: {
      steps: [
        '1. Create MCP client class with execute method',
        '2. Add start/stop methods for process management',
        '3. Implement fallback simulation',
        '4. Integrate with toolshed.registerMCP()',
        '5. Test connection and fallback'
      ]
    }
  }
};
```

### Troubleshooting Guide

#### Problem: Toolshed not finding registered tools
**Solution:**
1. Verify tool registration happened before usage
2. Check tool name matches exactly (case-sensitive)
3. Ensure toolshed instance is same reference
4. Add logging to registration methods

#### Problem: Mode detection incorrect
**Solution:**
1. Review keyword patterns in `analyzeInputForMode()`
2. Check mode priority (CODER > THINKER > DEBUG > RESEARCH > CHAT)
3. Add custom rules to Steer for domain-specific detection
4. Log mode detection decisions for debugging

#### Problem: MCP client not connecting
**Solution:**
1. Test Python client independently with test script
2. Check Python dependencies are installed
3. Verify client path in integration code
4. Enable enhanced simulation fallback
5. Add timeout and graceful degradation

#### Problem: Performance issues
**Solution:**
1. Monitor tool execution times in Drive.performance
2. Implement tool caching where appropriate
3. Use background tasks for long-running operations
4. Add concurrency limits for resource-intensive tools

### Best Practices

1. **Always provide fallbacks**: Enhanced simulation > real integration failure
2. **Log key operations**: Tool registration, mode changes, MCP connections
3. **Preserve context**: Carry relevant information across turns
4. **Handle errors gracefully**: Don't crash on tool failures
5. **Document patterns**: Add to this skill when new patterns emerge
6. **Test integrations**: Use test scripts for Python clients, MCP connections
7. **Follow OpenCode patterns**: For TUI integration consistency

### Integration Examples

#### Example 1: Adding a Custom Tool
```javascript
const { Toolshed } = require('./wzrdclaw-core.js');

// Create tool
class CustomAnalysisTool {
  async execute(params) {
    const { code, language } = params;
    return {
      success: true,
      analysis: `Analyzed ${language} code with ${code.length} chars`
    };
  }
}

// Register
const toolshed = new Toolshed();
toolshed.registerTool('analyze', new CustomAnalysisTool());
```

#### Example 2: Creating a Mode-Specific Skill
```javascript
// CODER mode skill - adds code generation helpers
const coderSkill = {
  name: 'coder-enhancements',
  
  activate: (drive) => {
    // Only activate in CODER mode
    if (drive.state.mode !== 'CODER') return;
    
    // Add code generation templates
    drive.updateContext('codeTemplates', {
      function: 'function {{name}}({{params}}) {\n  // TODO: implement\n}',
      class: 'class {{name}} {\n  constructor() {}\n}'
    });
  }
};
```

### Related Skills
- `opentui` - For TUI integration patterns
- `mcp` - General MCP client patterns
- `api` - REST/HTTP integration patterns
- `coding` - General coding patterns
- `system-health` - Monitoring and performance

### Version
1.0.0 - Initial WZRDClaw patterns skill