# CLAUDE.md - Essential Guidelines

## 🧠 CORE PRINCIPLE: Store Everything Important
**Before ANY decision/finding/error:**
```
store_fr3k: Store what you learned/decided/failed (max 500 chars)
```
This prevents repeating mistakes and forgetting context.

## 📚 MCP TOOL LIBRARY - YOUR PRIMARY RESOURCE

**Location:** `templates/mcp-tool-library/`
**Guide:** `templates/MCP-TOOL-LIBRARY-GUIDE.md`

**YOU HAVE ACCESS TO COMPREHENSIVE MCP SERVER INTEGRATION TEMPLATES!**

### What's in the Library

✅ **Database**: MongoDB, Pinecone, Supabase, Postgres, Neo4j
✅ **Cloud**: AWS S3, Cloudflare, Stripe, Vercel, Azure, Google Cloud
✅ **Productivity**: Notion, Slack, Zapier, Taskade
✅ **Developer**: GitHub, JetBrains, Git, Context7 (library docs)
✅ **Security**: Semgrep, SonarQube, Sentry, Auth0
✅ **Search**: Tavily, Exa, Perplexity, Kagi
✅ **Blockchain**: Thirdweb, Token Metrics, Trading

### How to Use the Library

1. **User needs GitHub operations?** → Read `templates/mcp-tool-library/developer/github-operations.md`
2. **User needs MongoDB query?** → Read `templates/mcp-tool-library/database/mongodb-query.md`
3. **User needs Stripe payment?** → Read `templates/mcp-tool-library/cloud/stripe-payments.md`

Each template shows:
- Real MCP server name and install command
- All available operations
- Exact parameters with types
- 10+ working code examples
- Security best practices
- Error handling patterns

**ALWAYS read the template before using any MCP server!**

## 🔧 DYNAMIC MCP TOOL CREATION (Advanced)

**For creating NEW Fabric-pattern templates (not for using existing MCP servers):**

### When to Create New Templates

**Create a new template when:**
- A popular MCP server isn't covered in the library yet
- User needs validation/transformation/analysis patterns
- Building reusable knowledge templates
- Documenting new MCP server integrations

### How to Create Tools (3 Methods)

**Method 1: Using md-mcp `forge_reality`** (RECOMMENDED)
```javascript
mcp__md-mcp__forge_reality({
  divine_title: "Tool Name",
  primal_essence: `# IDENTITY and PURPOSE
You are a [tool description]...

# PARAMETERS
- param: type - Description

# STEPS
1. Processing steps...

# OUTPUT
Expected output format...

# EXAMPLES
Usage examples...`,
  creation_ritual: "basic",
  mystical_properties: {"type": "category", "dynamic": true}
})
```

**Method 2: Direct File Creation**
```bash
cat > ~/mcp-tools/tool-name.md << 'EOF'
[Fabric-format specification]
EOF
```

**Method 3: Ask User to Create**
```
"I can create a [tool type] tool for this. Would you like me to create it?"
```

### Tool Specification Format (Fabric Pattern)

```markdown
# IDENTITY and PURPOSE
[Clear description of what the tool does]

# PARAMETERS
- param_name: type - Description
- optional_param: type (optional, default: value) - Description

# STEPS
1. First processing step
2. Second processing step
3. Final output generation

# OUTPUT
{
  "field": "value",
  "status": "success"
}

# EXAMPLES
- Input X → Output Y
- Edge case: Input Z → Output W

# USAGE
[When and how to use this tool effectively]
```

### Tool Categories & Templates

**Validators**: JSON, YAML, XML, regex, schema validation
**Transformers**: Format conversion, data processing, encoding
**Analyzers**: Code analysis, security scanning, performance profiling
**Knowledge**: API docs, protocol specs, algorithm explanations

### Workflow: Create → Validate → Use

```
1. User needs functionality
2. You create tool with forge_reality
3. Validate with divine_truth
4. Use tool immediately
5. Tool persists for future use
```

### Example: On-the-Fly Tool Creation

```
User: "Can you validate this JSON?"

AI: Let me create a JSON validator tool for you.

[Uses mcp__md-mcp__forge_reality with JSON validator spec]

Tool created! Now validating your JSON...
[Uses the new tool]
```

**See DYNAMIC-MCP-TOOL-CREATION.md for complete guide with examples.**

---

## 📦 PACKAGE-FIRST PHILOSOPHY

**BEFORE writing custom code, research existing packages:**

### Core Rule
- **Research first**: Use **sherlock** agent to find ecosystem packages
- **Tools first**: Create MCP tool with md-mcp if no package exists
- **Never assume**: Always check what already exists before building custom
- **Quality over custom**: Maintained, lightweight, documented packages preferred

### Explicit Requirements
- **Icons**: Use icon packages/libraries - NEVER emojis in code
- **Common utilities**: Research standard ecosystem solutions first
- **Missing functionality**: Create MCP tool with md-mcp
- **When unsure**: Spawn sherlock to research, don't guess

### Decision Flow
```
Need functionality → sherlock research → Good package exists? → Use it
                                     ↓
                              No good package → Create MCP tool with md-mcp
                                     ↓
                              Tool won't work → Custom implementation
```

**Enforcement**: If you're about to implement common functionality, STOP and research first or create an MCP tool.

## 📊 VISUAL-FIRST RESPONSES

**When responding to the user:**

**Show, don't just tell:**
- Complex processes → ASCII diagrams
- Multiple options → Visual trees
- Status/progress → Progress indicators
- Comparisons → Before/after layouts

**Keep text concise and accessible for non-coders.**

## 🔄 AGENT-FIRST WORKFLOW

### 🤖 SPECIALIZED AGENTS (USE THESE!)

**ALWAYS use the right agent for the task:**

| Agent | When to Use |
|-------|-------------|
| **bugsy** | Errors, crashes, test failures |
| **fronty** | React/Next.js frontend work |
| **gitty** | Git operations, commits |
| **murphy** | Config validation, dependencies |
| **opinion** | Feedback, assessments |
| **scribe** | Documentation, guides |
| **sherlock** | Research, find docs/APIs |
| **validation** | Check against requirements |
| **gopher** | Go development, new Go features |
| **jsmaster** | JS/Node.js development, new JS features |
| **nextking** | Next.js apps, new Next.js features |
| **thesnake** | Python development, new Python features |
| **reactlord** | React components, new React features |
| **typegod** | TypeScript development, new TS features |
| **vuelord** | Vue.js development, new Vue features |

### 🚀 SINGLE vs PARALLEL AGENT STRATEGY

**Use ONE agent when:**
- Task fits clearly into one specialist's domain
- Simple, straightforward problem
- Need focused expertise

**Spawn MULTIPLE agents in parallel when:**
- Multiple file types need changes (code + config + docs)
- Errors span different domains (frontend + backend + database)  
- Research + implementation needed simultaneously
- Commands like `/check`, `/api`, `/migrate` require it

**Example parallel spawning:**
```
"I'll spawn multiple agents to handle this complex task:
- jsmaster: Write the API endpoints in files A, B, C
- murphy: Validate the database config
- sherlock: Research the latest framework patterns
Let me tackle all of these in parallel..."
```

### 1. Basic Workflow
```
1. recall_fr3k: Check what we already know
2. Simple tasks: Direct implementation with appropriate agent
3. store_fr3k: Store decisions and solutions
```

### 2. For Complex Tasks
```
1. recall_fr3k: Check what we already know
2. add_task: Store requirements and expected results
3. Research: Read actual files (never assume)  
4. Plan: TodoWrite the steps
5. Implement: Edit/Write with verification
6. Test: Actually run the code
7. validation agent: Check against task requirements
8. store_fr3k: Store what worked/failed
```

### 3. Agent Coordination
**When agent fails or gives partial results:**
- Store findings with store_fr3k
- Report failure to user with specific error
- Ask user for direction (different agent, escalate, or debug)
- Share context through fr3k memory system (max 5 memories)

### 4. 5-Status Task Workflow
**Status Flow:** `todo` → `coding_done` → `validated` → `complete` (with `needs_fixes` loop)

**Agent Responsibilities:**
- **Language agents** (jsmaster/gopher/thesnake/etc): `todo`/`needs_fixes` → `coding_done` (never marks complete)
- **validation agent**: `coding_done` → `validated`/`needs_fixes` (never marks complete)
- **bugsy**: `needs_fixes` → `coding_done` (fixes issues, never marks complete)
- **human/claude**: `validated` → `complete` (final approval only)

**Status Transitions:**
```
┌─────────┐    ┌──────────────┐    ┌───────────┐    ┌──────────┐
│  todo   │───▶│ coding_done  │───▶│ validated │───▶│ complete │
└─────────┘    └──────────────┘    └───────────┘    └──────────┘
                      │                   │               ▲
                      │                   ▼               │
                      │              ┌─────────────┐      │
                      └─────────────▶│ needs_fixes │──────┘
                                     └─────────────┘
```

**Critical Rules:**
- Agents ONLY update to their designated next status
- NO agent marks tasks as `complete` except final approval
- Fix loops continue until validation passes

## 🚫 CRITICAL RULES - FAIL FAST, NO SILENT FALLBACKS

**CRITICAL: Never create silent fallbacks that mask real failures**

### Forbidden Patterns:
- ❌ "If X fails, I'll try Y instead" (without explicit user consent)
- ❌ "This might not work, but here's a workaround" 
- ❌ Creating backup solutions when primary approach should be fixed
- ❌ Assuming alternative approaches without validating the original failure

### Required Behavior:
- ✅ **Fail loudly**: Report exact error and stop
- ✅ **Fail fast**: Don't continue with broken foundations  
- ✅ **Fail explicitly**: Ask user how to proceed with failures
- ✅ **Fix root cause**: Don't work around problems

### Exception Handling:
```
if (primaryApproach.fails()) {
    store_fr3k("Primary approach failed: [exact error]")
    throw Error("Cannot proceed - primary approach failed")
    // NO automatic fallbacks without explicit user choice
}
```

### User Communication:
"The primary approach failed with: [error]. Would you like me to:
1. Debug and fix the root cause
2. Try a different approach (specify which)
3. Research alternative solutions"

### Security (NEVER SKIP)
- **SQL**: Use parameters `cursor.execute("SELECT * WHERE id=%s", (id,))`
- **Passwords**: bcrypt/argon2 only, min 12 rounds
- **Input**: Validate type, length, format before using
- **Secrets**: Never log passwords, tokens, API keys

### Before Changing Code
1. **Read** the file first (no assumptions)
2. **Verify** imports/APIs exist
3. **Test** changes actually work
4. **Remember** solutions for next time

### Memory Checkpoints
Every 10-15 messages or before context reset:
```
store_fr3k: Current state, decisions, next steps (concise, <500 chars)
```

## 🛠️ TOOLS PRIORITY

1. **store_fr3k/recall_fr3k**: Store everything important (max 5 retrieval)
2. **add_task/get_task**: Track requirements and validation
3. **Read/Grep/Glob**: Verify before claiming
4. **TodoWrite**: Track multi-step work
5. **validation agent**: Check work against requirements
6. **Test execution**: Validate fixes work

## ⚠️ COMMON FAILURES

**LLMs often:**
- Assume file contents → Always Read first
- Invent APIs → Verify with Grep
- Forget earlier decisions → Check recall_fr3k
- Skip validation → Use validation agent with task ID
- Skip testing → Run code to confirm

**When stuck:**
1. Store current state
2. Simplify the approach
3. Ask user for direction

## 🎯 SUCCESS CRITERIA

Before marking complete:
- [ ] Code runs without errors
- [ ] Tests pass
- [ ] No security issues
- [ ] Solution stored in memory
- [ ] Old code cleaned up

**Quality gates:**
- If agent output seems incomplete → escalate to thorough mode
- If multiple agents conflict → use opinion agent for decision
- If solution feels complex → verify with appropriate language agent review

**Success metrics (validate before marking complete):**
- Code: Actually runs without errors when executed
- Research: Answers the specific question asked with actionable info
- Fixes: Problem no longer occurs after implementation
- Documentation: User can follow instructions successfully

---
*Remember: Simple + Verified > Complex + Assumed*

## Key Capabilities
- Advanced code analysis and improvement
- Comprehensive documentation generation
- Intelligent task management and planning
- Multi-modal content processing
- Continuous system optimization

## Best Practices
- Always provide specific, actionable feedback
- Use available tools effectively
- Maintain code quality and consistency
- Document important decisions and changes
