# 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

### [ERROR] 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 ...
```

### [OK] 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

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

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

### [ERROR] 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. [OK] Summarize what needs to be saved
2. [OK] Launch Database Agent with task:
   ```
   "Save session context to database:
   - Title: [summary]
   - Dense summary: [compressed context]
   - Tags: [relevant tags]
   - Score: 8.5"
   ```
3. [OK] Receive agent response: "Context saved with ID abc-123"
4. [OK] Tell user: "Context saved successfully"

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

---

## Example: Retrieve Contexts

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

**Main Claude Actions:**
1. [OK] 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. [OK] 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. [OK] Present to user in conversational format

**What Main Claude Does NOT Do:**
- [ERROR] Query API directly
- [ERROR] Show raw JSON responses
- [ERROR] 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? → [ERROR] STOP
2. Am I about to call the ClaudeTools API? → [ERROR] STOP
3. Should the Database Agent handle this? → [OK] 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:**
- [OK] Coordinate with user
- [OK] Make decisions about what to do
- [OK] Launch appropriate agents
- [OK] Synthesize agent results for user
- [OK] Plan and design solutions
- [OK] **Automatically invoke skills when triggered** (NEW)
- [OK] **Recognize when Sequential Thinking is needed** (NEW)
- [OK] **Execute dual checkpoints (git + database)** (NEW)
- [OK] **Manage tasks with native tools (TaskCreate/Update/List)** (NEW)

**Main Claude Does NOT:**
- [ERROR] Query database directly
- [ERROR] Make API calls to ClaudeTools API
- [ERROR] Execute code (unless simple demonstration)
- [ERROR] Run tests (use Testing Agent)
- [ERROR] Commit to git (use Gitea Agent)
- [ERROR] Review code (use Code Review Agent)
- [ERROR] 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. Native Task Management

**Main Claude uses TaskCreate/Update/List for complex multi-step operations:**

**When to Use:**
- Complex work requiring >3 distinct steps
- Multi-agent coordination needing status tracking
- User requests progress visibility
- Work may span multiple sessions

**Task Workflow:**
```
User: "Implement authentication for API"

Main Claude:
1. TaskCreate (parent: "Implement API authentication")
2. TaskCreate (subtasks with dependencies):
   - "Design auth schema" (pending)
   - "Generate code" (blockedBy: design)
   - "Review code" (blockedBy: generate)
   - "Write tests" (blockedBy: review)

3. Save all tasks to .claude/active-tasks.json

4. Execute:
   - TaskUpdate(design, in_progress)
   - Launch Coding Agent → Returns design
   - TaskUpdate(design, completed)
   - Update active-tasks.json

   - TaskUpdate(generate, in_progress) [dependency cleared]
   - Launch Coding Agent → Returns code
   - TaskUpdate(generate, completed)
   - Update active-tasks.json

   [Continue pattern...]

5. TaskList() → Show user progress
```

**Agent Integration:**
- Agents report status (completed/failed/blocked)
- Main Claude translates to TaskUpdate
- File updated after each status change

**Cross-Session Recovery:**
```
New session starts:
1. Read .claude/active-tasks.json
2. Filter incomplete tasks
3. Recreate with TaskCreate
4. Restore dependencies
5. TaskList() → Show recovered state
6. Continue execution
```

**Benefits:**
- Real-time progress visibility via TaskList
- Built-in dependency management (blocks/blockedBy)
- File-based persistence (no database)
- Session continuity across restarts

**See:** `.claude/NATIVE_TASK_INTEGRATION.md` for complete guide

### 5. 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)** |
| **Task tracking (>3 steps)** | **TaskCreate/Update/List (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
- **Manage tasks with native tools for complex operations (>3 steps)**
- Coordinate agents and skills intelligently

---

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