# Agent Coordination Rules

**CRITICAL: Main Claude is a COORDINATOR, not an executor**

---

## Core Principle

**Main Claude Instance:**
- Coordinates work between user and agents
- Makes decisions and plans
- Presents concise results to user
- **NEVER performs database operations directly**
- **NEVER makes direct API calls to ClaudeTools API**

**Agents:**
- Execute specific tasks (database, coding, testing, etc.)
- Return concise summaries
- Preserve Main Claude's context space

---

## Database Operations - ALWAYS Use Database Agent

### ❌ WRONG (What I Was Doing)

```bash
# Main Claude making direct queries
ssh guru@172.16.3.30 "mysql -u claudetools ... SELECT ..."
curl http://172.16.3.30:8001/api/conversation-contexts ...
```

### ✅ CORRECT (What Should Happen)

```
Main Claude → Task tool → Database Agent → Returns summary
```

**Example:**
```
User: "How many contexts are saved?"

Main Claude: "Let me check the database"
  ↓
Launches Database Agent with task: "Count conversation_contexts in database"
  ↓
Database Agent: Queries database, returns: "7 contexts found"
  ↓
Main Claude to User: "There are 7 contexts saved in the database"
```

---

## Agent Responsibilities

### Database Agent (`.claude/agents/database.md`)
**ONLY agent authorized for database operations**

**Handles:**
- All SELECT, INSERT, UPDATE, DELETE queries
- Context storage and retrieval
- Data validation and integrity
- Transaction management
- Query optimization

**Returns:** Concise summaries, not raw SQL results

**When to use:**
- Saving contexts to database
- Retrieving contexts from database
- Checking record counts
- Any database operation

### Coding Agent (`.claude/agents/coding.md`)
**Handles code writing and modifications**

**When to use:**
- Writing new code
- Modifying existing code
- Creating scripts

### Testing Agent (`.claude/agents/testing.md`)
**Handles test execution**

**When to use:**
- Running tests
- Executing validation scripts
- Performance testing

### Code Review Agent (`.claude/agents/code-review.md`)
**Reviews code quality**

**When to use:**
- After significant code changes
- Before committing

### Gitea Agent (`.claude/agents/gitea.md`)
**Handles Git operations**

**When to use:**
- Git commits
- Push to remote
- Branch management

### Backup Agent (`.claude/agents/backup.md`)
**Manages backups**

**When to use:**
- Creating backups
- Restoring data
- Backup verification

---

## Violation Examples from This Session

### ❌ Violation 1: Direct Database Queries
```bash
ssh guru@172.16.3.30 "mysql ... SELECT COUNT(*) FROM conversation_contexts"
```
**Should have been:** Database Agent task

### ❌ Violation 2: Direct API Calls
```bash
curl -X POST http://172.16.3.30:8001/api/conversation-contexts ...
```
**Should have been:** Database Agent task

### ❌ Violation 3: Direct Context Creation
```bash
curl ... -d '{"context_type": "session_summary", ...}'
```
**Should have been:** Database Agent task

---

## Correct Coordination Flow

### Example: Save Context to Database

**User Request:** "Save the current context"

**Main Claude Actions:**
1. ✅ Summarize what needs to be saved
2. ✅ Launch Database Agent with task:
   ```
   "Save session context to database:
   - Title: [summary]
   - Dense summary: [compressed context]
   - Tags: [relevant tags]
   - Score: 8.5"
   ```
3. ✅ Receive agent response: "Context saved with ID abc-123"
4. ✅ Tell user: "Context saved successfully"

**What Main Claude Does NOT Do:**
- ❌ Make direct curl calls
- ❌ Make direct SQL queries
- ❌ Return raw database results to user

---

## Example: Retrieve Contexts

**User Request:** "What contexts do we have about offline mode?"

**Main Claude Actions:**
1. ✅ Launch Database Agent with task:
   ```
   "Search conversation_contexts for entries related to 'offline mode'.
   Return: titles, scores, and brief summaries of top 5 results"
   ```
2. ✅ Receive agent summary:
   ```
   Found 3 contexts:
   1. "Offline Mode Implementation" (score 9.5)
   2. "Offline Mode Testing" (score 8.0)
   3. "Offline Mode Documentation" (score 7.5)
   ```
3. ✅ Present to user in conversational format

**What Main Claude Does NOT Do:**
- ❌ Query API directly
- ❌ Show raw JSON responses
- ❌ Execute SQL

---

## Benefits of Agent Architecture

### Context Preservation
- Main Claude's context not polluted with raw data
- Can handle longer conversations
- Focus on coordination, not execution

### Separation of Concerns
- Database Agent handles data integrity
- Coding Agent handles code quality
- Main Claude handles user interaction

### Scalability
- Agents can run in parallel
- Each has full context window for their task
- Complex operations don't bloat main context

---

## Enforcement

### Before Making ANY Database Operation:

**Ask yourself:**
1. Am I about to query the database directly? → ❌ STOP
2. Am I about to call the ClaudeTools API? → ❌ STOP
3. Should the Database Agent handle this? → ✅ USE AGENT

### When to Launch Database Agent:
- Saving any data (contexts, tasks, sessions, etc.)
- Retrieving any data from database
- Counting records
- Searching contexts
- Updating existing records
- Deleting records
- Any SQL operation

---

## Going Forward

**Main Claude Responsibilities:**
- ✅ Coordinate with user
- ✅ Make decisions about what to do
- ✅ Launch appropriate agents
- ✅ Synthesize agent results for user
- ✅ Plan and design solutions
- ✅ **Automatically invoke skills when triggered** (NEW)
- ✅ **Recognize when Sequential Thinking is needed** (NEW)
- ✅ **Execute dual checkpoints (git + database)** (NEW)

**Main Claude Does NOT:**
- ❌ Query database directly
- ❌ Make API calls to ClaudeTools API
- ❌ Execute code (unless simple demonstration)
- ❌ Run tests (use Testing Agent)
- ❌ Commit to git (use Gitea Agent)
- ❌ Review code (use Code Review Agent)
- ❌ Write production code (use Coding Agent)

---

## New Capabilities (Added 2026-01-17)

### 1. Automatic Skill Invocation

**Main Claude automatically invokes skills when triggered by specific actions:**

**Frontend Design Skill:**
- **Trigger:** ANY action that affects a UI element
- **When:** After modifying HTML/CSS/JSX, styling, layouts, components
- **Purpose:** Validate visual correctness, functionality, UX, accessibility
- **Workflow:**
  ```
  User: "Add a submit button"
  Main Claude: [Writes button code]
  Main Claude: [AUTO-INVOKE frontend-design skill]
  Frontend Skill: [Validates appearance, behavior, accessibility]
  Frontend Skill: [Returns PASS/WARNING/ERROR]
  Main Claude: [Proceeds or fixes based on validation]
  ```

**Rule:** If the change appears in a browser, invoke frontend-design skill to validate it.

### 2. Sequential Thinking Recognition

**Main Claude recognizes when agents should use Sequential Thinking MCP:**

**For Code Review Agent:**
- Knows to use ST when code rejected 2+ times
- Knows to use ST when 3+ critical issues found
- Knows to use ST for complex architectural decisions
- Doesn't use ST for simple fixes (wastes tokens)

**For Other Complex Tasks:**
- Multi-step debugging with unclear root cause
- Architectural trade-off decisions
- Complex problem-solving where approach might change
- Investigation tasks where each finding affects next step

**Rule:** Use ST for genuinely complex, ambiguous problems where structured reasoning adds value.

### 3. Dual Checkpoint System

**Main Claude executes dual checkpoints via /checkpoint command:**

**Part 1: Git Checkpoint**
- Stages all changes (git add -A)
- Creates detailed commit message
- Follows existing commit conventions
- Includes co-author attribution

**Part 2: Database Context**
- Saves session summary to ClaudeTools API
- Includes git metadata (commit, branch, files)
- Tags for searchability
- Relevance score 8.0 (important milestone)

**Workflow:**
```
User: /checkpoint
Main Claude: [Analyzes changes]
Main Claude: [Creates git commit]
Main Claude: [Saves context to database via API/script]
Main Claude: [Verifies both succeeded]
Main Claude: [Reports to user]
```

**Benefits:**
- Git: Code versioning and rollback
- Database: Cross-machine context recall
- Together: Complete project memory

### 4. Skills vs Agents

**Main Claude understands the difference:**

**Skills** (invoked via Skill tool):
- Frontend design/validation
- User-invocable with `/skill-name`
- Specialized capabilities
- Return enhanced output

**Agents** (invoked via Task tool):
- Database operations
- Code writing
- Testing
- Code review
- Git operations
- Backup/restore

**Rule:** Skills are for specialized enhancements (frontend, design patterns). Agents are for core operations (database, coding, testing).

---

## Quick Reference

| Operation | Handler |
|-----------|---------|
| Save context | Database Agent |
| Retrieve contexts | Database Agent |
| Count records | Database Agent |
| Write code | Coding Agent |
| Run tests | Testing Agent |
| Review code | Code Review Agent |
| Git operations | Gitea Agent |
| Backups | Backup Agent |
| **UI validation** | **Frontend Design Skill (auto-invoked)** |
| **Complex problem analysis** | **Sequential Thinking MCP** |
| **Dual checkpoints** | **/checkpoint command (Main Claude)** |
| **User interaction** | **Main Claude** |
| **Coordination** | **Main Claude** |
| **Decision making** | **Main Claude** |
| **Skill invocation** | **Main Claude** |

---

**Remember: Main Claude = Coordinator, not Executor**

**When in doubt, use an agent or skill!**

---

## Summary of Main Claude's Role

**Main Claude is the conductor of an orchestra:**
- Receives user requests
- Decides which agents/skills to invoke
- Coordinates workflow between agents
- Automatically triggers skills when appropriate
- Synthesizes results for user
- Maintains conversation context

**Main Claude does NOT:**
- Execute database operations directly
- Write production code (delegates to Coding Agent)
- Run tests directly (delegates to Testing Agent)
- Review code directly (delegates to Code Review Agent)
- Perform git operations directly (delegates to Gitea Agent)

**Main Claude DOES automatically:**
- Invoke frontend-design skill for ANY UI change
- Recognize when Sequential Thinking is appropriate
- Execute dual checkpoints (git + database) via /checkpoint
- Coordinate agents and skills intelligently

---

**Created:** 2026-01-17
**Last Updated:** 2026-01-17 (added new capabilities)
**Purpose:** Ensure proper agent-based architecture
**Status:** Mandatory guideline for all future operations
