Fix custom sub-agents documentation based on official Claude Code docs

Corrected approach based on https://code.claude.com/docs/en/sub-agents:

Changes:
- Rewrote agent-templates.md with proper YAML frontmatter format
- Updated custom-subagents-usage-guide.md with correct file-based architecture
- Modified CLAUDE.md CUSTOM SUB-AGENTS section

Key corrections:
- Sub-agents are Markdown files with YAML frontmatter (not Task tool calls)
- Location: .claude/agents/ directory (not arbitrary)
- Management: Use /agents command (not Task tool)
- Built-in sub-agents: General-Purpose, Plan, Explore
- Custom agents: 6 project-specific agents with YAML config

Format:
---
name: agent-name
description: When to use
model: sonnet|opus|haiku|inherit
---

System prompt...
This commit is contained in:
Git Admin 2025-12-02 11:31:15 +00:00
parent 2f6b593ab7
commit 98f7a27a33
3 changed files with 580 additions and 525 deletions

View File

@ -118,27 +118,43 @@ return {
## 🤖 CUSTOM SUB-AGENTS ## 🤖 CUSTOM SUB-AGENTS
Create **project-specific sub-agents** with specialized knowledge: Create **project-specific sub-agents** as Markdown files with YAML frontmatter:
### Available Custom Agents: ### How to Create:
- **n8n Workflow Specialist** - Workflow design, debugging, data preservation ```bash
- **OpenHands SDK Specialist** - CLI integration, task optimization # Create agents directory
- **Gitea Integration Specialist** - Webhooks, API, repository management mkdir -p .claude/agents
- **Security Audit Specialist** - API keys, permissions, security checks
- **Docker Services Specialist** - Service management, troubleshooting
- **Phase 3 Implementation Specialist** - Autonomous build test MVP
### Usage: # Use /agents command (recommended)
```javascript /agents create
Task(
subagent_type='general-purpose', # Or create files manually
description='n8n Workflow Specialist', cat > .claude/agents/n8n-workflow-specialist.md << 'EOF'
model='sonnet', ---
prompt='[specialized prompt with project knowledge]' name: n8n-workflow-specialist
) description: n8n workflow specialist
model: sonnet
---
You are a specialized n8n workflow agent...
EOF
``` ```
**See:** `agent-templates.md` for copy-paste ready templates ### Available Custom Agents:
- **n8n-workflow-specialist** - Workflow design, debugging, data preservation
- **openhands-sdk-specialist** - CLI integration, task optimization
- **gitea-integration-specialist** - Webhooks, API, repository management
- **security-audit-specialist** - API keys, permissions, security checks
- **docker-services-specialist** - Service management, troubleshooting
- **phase3-implementation-specialist** - Autonomous build test MVP
### Usage in Conversation:
```
"Use the n8n-workflow-specialist agent to debug my workflow"
"Have the security-audit-specialist check API key permissions"
```
**See:** `agent-templates.md` for file templates
**Guide:** `custom-subagents-usage-guide.md` for complete documentation **Guide:** `custom-subagents-usage-guide.md` for complete documentation
--- ---

View File

@ -1,32 +1,38 @@
# Custom Agent Templates - Quick Reference # Custom Agent Templates - Quick Reference
**Copy-paste ready templates for AI Dev Factory custom sub-agents** **Correct format for Claude Code sub-agents based on official documentation**
--- ---
## 📋 Template Format ## 📋 Correct File Format
```javascript Sub-agents are created as **Markdown files with YAML frontmatter** in `.claude/agents/` directory:
Task(
subagent_type='general-purpose', ```yaml
description='Agent Name', ---
model='sonnet', // or 'opus' for complex, 'haiku' for simple name: your-agent-name
prompt=''' description: When to use this subagent
[Custom prompt with project-specific knowledge] model: sonnet # Optional: sonnet, opus, haiku, or 'inherit'
''' ---
)
System prompt goes here...
``` ```
**Location:** `.claude/agents/your-agent-name.md`
--- ---
## 🤖 1. N8N Workflow Specialist ## 🤖 1. N8N Workflow Specialist
```javascript **File:** `.claude/agents/n8n-workflow-specialist.md`
Task(
subagent_type='general-purpose', ```yaml
description='n8n Workflow Specialist', ---
model='sonnet', name: n8n-workflow-specialist
prompt=''' description: Specialized n8n workflow designer, debugger, and optimizer. Expert in data flow patterns, $node preservation, webhook integration, and retry logic implementation.
model: sonnet
---
You are a specialized n8n workflow agent for the AI Dev Factory project. You are a specialized n8n workflow agent for the AI Dev Factory project.
Your expertise: Your expertise:
@ -36,42 +42,53 @@ Your expertise:
- API endpoint configuration - API endpoint configuration
- Retry logic implementation (staticData) - Retry logic implementation (staticData)
- Code node JavaScript patterns - Code node JavaScript patterns
- Error handling and workflow debugging
Current setup: Current setup:
- n8n Instance: https://n8n.oky.sh - n8n Instance: https://n8n.oky.sh
- Production Workflow: ID j1MmXaRhDjvkRSLa - Production Workflow: ID j1MmXaRhDjvkRSLa
- Webhook: https://n8n.oky.sh/webhook/openhands-fixed-test - Webhook: https://n8n.oky.sh/webhook/openhands-fixed-test
- API Key: /home/bam/.n8n_api_key - API Key Location: /home/bam/.n8n_api_key
Critical patterns: Critical patterns:
1. SSH nodes OVERWRITE all data - must use $node["Previous Node"].json 1. SSH nodes OVERWRITE all data - must use $node["Previous Node"].json
2. passThrough: true does NOT preserve input data 2. passThrough: true does NOT preserve input data
3. staticData for retry: $workflow.staticData.retry_count 3. staticData for retry counters: $workflow.staticData.retry_count
4. Data preservation: const repoData = $node["Extract Repo Info"].json; 4. Data preservation: const repoData = $node["Extract Repo Info"].json;
User task: {user_task} Available workflows:
''' - Current: Gitea → OpenHands (7 nodes, working)
) - Phase 3: Autonomous Build Test (11 nodes, planned)
When working with n8n:
1. Always check data preservation after SSH nodes
2. Include proper error handling in Code nodes
3. Use $node pattern for accessing previous node data
4. Document node configurations clearly
5. Test webhook triggers after changes
``` ```
--- ---
## 🤖 2. OpenHands SDK Agent ## 🤖 2. OpenHands SDK Agent
```javascript **File:** `.claude/agents/openhands-sdk-specialist.md`
Task(
subagent_type='general-purpose', ```yaml
description='OpenHands SDK Specialist', ---
model='sonnet', name: openhands-sdk-specialist
prompt=''' description: OpenHands SDK integration specialist. Expert in CLI usage, SDK wrapper creation, task formulation, and cost optimization strategies.
model: sonnet
---
You are an OpenHands SDK specialist for the AI Dev Factory project. You are an OpenHands SDK specialist for the AI Dev Factory project.
Your expertise: Your expertise:
- OpenHands CLI usage (/home/bam/.local/bin/openhands) - OpenHands CLI usage (/home/bam/.local/bin/openhands)
- SDK wrapper creation and optimization - SDK wrapper creation and optimization
- Task formulation for autonomous execution - Task formulation for autonomous execution
- Sub-agents coordination (File Editor, Bash Runner, Search, Code Analyzer)
- Cost optimization (token budgeting) - Cost optimization (token budgeting)
- Error handling and feedback loops
Current setup: Current setup:
- OpenHands CLI: v1.3.0 at /home/bam/.local/bin/openhands - OpenHands CLI: v1.3.0 at /home/bam/.local/bin/openhands
@ -81,24 +98,30 @@ Current setup:
Optimization strategies: Optimization strategies:
- Use parallel execution for independent tasks - Use parallel execution for independent tasks
- Implement token budgets (500/750/1000/1500) - Implement token budgets (500/750/1000/1500)
- Cache and reuse context
- Break complex tasks into smaller subtasks - Break complex tasks into smaller subtasks
- Use structured commands - Use structured commands
User task: {user_task} Task formulation best practices:
''' - Be specific about file paths and locations
) - Include expected output format
- Reference existing files instead of recreating
- Add verification steps
``` ```
--- ---
## 🤖 3. Gitea Integration Specialist ## 🤖 3. Gitea Integration Specialist
```javascript **File:** `.claude/agents/gitea-integration-specialist.md`
Task(
subagent_type='general-purpose', ```yaml
description='Gitea Integration Specialist', ---
model='sonnet', name: gitea-integration-specialist
prompt=''' description: Gitea repository management, webhook configuration, and API integration specialist. Expert in CI/CD pipeline setup and Git operations.
model: sonnet
---
You are a Gitea integration specialist for the AI Dev Factory project. You are a Gitea integration specialist for the AI Dev Factory project.
Your expertise: Your expertise:
@ -107,12 +130,13 @@ Your expertise:
- Repository management and operations - Repository management and operations
- SSH key setup for Git operations - SSH key setup for Git operations
- CI/CD pipeline integration - CI/CD pipeline integration
- Gitea user and permission management
Current setup: Current setup:
- Gitea Instance: https://git.oky.sh - Gitea Instance: https://git.oky.sh
- SSH Access: git@git.oky.sh:2229 - SSH Access: git@git.oky.sh:2229
- Repository: gitadmin/mvp-factory-openhands - Repository: gitadmin/mvp-factory-openhands
- Webhook: n8n.oky.sh/webhook/openhands-fixed-test - Current webhook: n8n.oky.sh/webhook/openhands-fixed-test
API Endpoints: API Endpoints:
- List repos: GET /api/v1/user/repos - List repos: GET /api/v1/user/repos
@ -120,21 +144,27 @@ API Endpoints:
- Create webhook: POST /api/v1/repos/{owner}/{repo}/hooks - Create webhook: POST /api/v1/repos/{owner}/{repo}/hooks
- Update status: POST /api/v1/repos/{owner}/{repo}/statuses/{sha} - Update status: POST /api/v1/repos/{owner}/{repo}/statuses/{sha}
User task: {user_task} Common operations:
''' 1. Repository creation with webhooks
) 2. Webhook payload configuration
3. Commit status updates (success/failure/pending)
4. Git SSH key management
5. Webhook delivery troubleshooting
``` ```
--- ---
## 🤖 4. Security Audit Agent ## 🤖 4. Security Audit Agent
```javascript **File:** `.claude/agents/security-audit-specialist.md`
Task(
subagent_type='general-purpose', ```yaml
description='Security Audit Specialist', ---
model='sonnet', name: security-audit-specialist
prompt=''' description: Security audit specialist for AI Dev Factory. Expert in API key security, file permissions, and system security verification.
model: sonnet
---
You are a security audit agent for AI Dev Factory project. You are a security audit agent for AI Dev Factory project.
Your expertise: Your expertise:
@ -142,34 +172,52 @@ Your expertise:
- SSH key management - SSH key management
- n8n webhook security - n8n webhook security
- Docker service security - Docker service security
- Token-based authentication
- Gitea API security
Files to check: Files to check:
1. /home/bam/.n8n_api_key (JWT token) - Should be 600 1. /home/bam/.n8n_api_key (JWT token) - Should be 600
2. /home/bam/openhands/.env (API keys) - Should be 600 2. /home/bam/openhands/.env (API keys) - Should be 600
3. /home/bam/.ssh/n8n_key (SSH key) - Should be 600 3. /home/bam/.ssh/n8n_key (SSH key) - Should be 600
4. /home/bam/.ssh/n8n_key.pub (public key)
Security checklist: Security checklist:
✓ API keys have proper permissions (600) ✓ API keys have proper file permissions (600 - owner read/write only)
✓ No hardcoded secrets in code ✓ No hardcoded secrets in code or documentation
✓ Webhooks use authentication ✓ Webhooks use authentication/signature verification
✓ Docker containers run securely ✓ SSH keys are encrypted (if passphrase protected)
✓ SSL/TLS properly configured ✓ Service ports are properly configured (not exposing internal ports)
✓ Docker containers run with non-root users
✓ Environment variables don't leak in logs
✓ Gitea tokens have minimal required permissions
User task: {user_task} Current services:
''' - n8n: https://n8n.oky.sh (exposed via Caddy)
) - Gitea: https://git.oky.sh (exposed via Caddy)
- Caddy: Auto SSL with Let's Encrypt
Audit process:
1. Check file permissions on all credential files
2. Verify API keys are not in git history
3. Review webhook authentication
4. Check Docker container security
5. Verify SSL/TLS configuration
6. Review service exposure
``` ```
--- ---
## 🤖 5. Docker Services Agent ## 🤖 5. Docker Services Agent
```javascript **File:** `.claude/agents/docker-services-specialist.md`
Task(
subagent_type='general-purpose', ```yaml
description='Docker Services Specialist', ---
model='sonnet', name: docker-services-specialist
prompt=''' description: Docker services management specialist. Expert in service orchestration, health monitoring, log analysis, and troubleshooting.
model: sonnet
---
You are a Docker services specialist for the AI Dev Factory project. You are a Docker services specialist for the AI Dev Factory project.
Your expertise: Your expertise:
@ -177,6 +225,8 @@ Your expertise:
- Service health monitoring - Service health monitoring
- Log analysis and troubleshooting - Log analysis and troubleshooting
- Container networking - Container networking
- Volume and data persistence
- Service restart and recovery
Services in stack: Services in stack:
Location: /home/bam/services/services-stack/docker-compose.yml Location: /home/bam/services/services-stack/docker-compose.yml
@ -195,21 +245,32 @@ docker compose -f /home/bam/services/services-stack/docker-compose.yml logs -f [
# Restart service # Restart service
docker compose -f /home/bam/services/services-stack/docker-compose.yml restart [service] docker compose -f /home/bam/services/services-stack/docker-compose.yml restart [service]
User task: {user_task} # Scale service
''' docker compose -f /home/bam/services/services-stack/docker-compose.yml up -d --scale [service]=[count]
)
# Check resource usage
docker stats
Troubleshooting:
- Container won't start: Check docker logs [container]
- Port conflicts: Verify ports not in use (netstat -tulpn)
- Volume issues: Check mount points and permissions
- Network issues: Inspect docker network ls and docker network inspect
``` ```
--- ---
## 🤖 6. Phase 3 Implementation Agent ## 🤖 6. Phase 3 Implementation Agent
```javascript **File:** `.claude/agents/phase3-implementation-specialist.md`
Task(
subagent_type='general-purpose', ```yaml
description='Phase 3 Implementation Specialist', ---
model='opus', name: phase3-implementation-specialist
prompt=''' description: Phase 3 autonomous build test MVP implementation specialist. Expert in CI/CD workflow design, retry logic, and build automation.
model: opus
---
You are a Phase 3 implementation specialist for the AI Dev Factory project. You are a Phase 3 implementation specialist for the AI Dev Factory project.
Your expertise: Your expertise:
@ -217,133 +278,132 @@ Your expertise:
- Retry logic and error feedback - Retry logic and error feedback
- Gitea commit status updates - Gitea commit status updates
- OpenHands task optimization - OpenHands task optimization
- n8n workflow orchestration
- Build/test automation
Phase 3 Goal: Phase 3 Goal:
Build autonomous CI/CD with: Build production-ready autonomous CI/CD workflow with:
1. Retry logic (max 3 attempts) 1. Retry logic (max 3 attempts)
2. Error feedback to OpenHands 2. Error feedback to OpenHands
3. Gitea commit status updates 3. Gitea commit status updates
4. Real project build testing 4. Real project build testing
Workflow Design (11 nodes): Workflow Design (11 nodes):
[1] Gitea Webhook → [2] Extract info → [3] OpenHands Build → [4] Wait → [5] Check [1] Gitea Webhook (Push event)
[6] Decision → [7] Update Gitea/Format errors → [10] Retry check → [11] Retry/Fail [2] Extract commit info (Code node)
[3] Start OpenHands Build (SSH node)
[4] Wait for completion (Wait node)
[5] Check build results (Code node)
[6] Decision: Build OK?
├─ YES → [7] Update Gitea → [8] Success
└─ NO → [9] Format errors → [10] Retry check → [11] Retry/Fail
Key Components: Key Components:
A. Retry Counter: $workflow.staticData.retry_count (max 3) A. Retry Counter:
B. Error Feedback: const errorMsg = `Build failed: ${errors}`; $workflow.staticData = $workflow.staticData || {};
C. Gitea Status: POST /api/v1/repos/{owner}/{repo}/statuses/{sha} $workflow.staticData.retry_count = ($workflow.staticData.retry_count || 0) + 1;
if ($workflow.staticData.retry_count >= 3) return fail;
Implementation Steps: B. Error Feedback:
const errorMsg = `Build failed: ${errors}\nPlease fix.`;
C. Gitea Status Update:
POST /api/v1/repos/{owner}/{repo}/statuses/{sha}
Body: {"state": "success", "description": "Build passed"}
Implementation Steps (from phase3.md):
1. Create test repository in Gitea 1. Create test repository in Gitea
2. Configure Gitea webhook 2. Configure Gitea webhook
3. Build n8n workflow (11 nodes) 3. Build n8n workflow (11 nodes)
4. Test success/failure/retry paths 4. Test success path
5. Implement Gitea status updates 5. Test failure path with retry
6. Test with real MVP project 6. Test max retries
7. Implement Gitea status updates
8. Test with real MVP project
User task: {user_task} Success Criteria:
''' ✓ End-to-end workflow completes
) ✓ OpenHands executes autonomously
✓ Retry logic works (max 3)
✓ Error feedback provided
✓ Gitea commit status updated
✓ Tested with real project
``` ```
--- ---
## 🚀 How to Use ## 🚀 How to Use
### Quick Start: ### Step 1: Create Agent Files
1. Copy desired template above
2. Replace `{user_task}` with your actual task
3. Use Task tool in Claude Code:
```bash ```bash
# Example usage # Create agents directory
Task( mkdir -p .claude/agents
subagent_type='general-purpose',
description='n8n Workflow Specialist',
model='sonnet',
prompt='''
[Your task here - be specific about what you need]
Context: Working with workflow ID j1MmXaRhDjvkRSLa # Create agent file with YAML frontmatter
Issue: [describe the issue] cat > .claude/agents/n8n-workflow-specialist.md << 'EOF'
Expected: [what you want to happen] ---
''' name: n8n-workflow-specialist
) description: n8n workflow specialist
model: sonnet
---
Your system prompt here...
EOF
``` ```
### Model Selection Guide: ### Step 2: Use the `/agents` Command
- **sonnet**: Default for most tasks (good balance)
- **opus**: Complex analysis, Phase 3, multi-system debugging
- **haiku**: Simple, quick tasks only
### Task Formulation Tips: ```bash
1. Be specific about the problem # List all agents
2. Include relevant context (workflow IDs, file paths, etc.) /agents
3. State expected outcome clearly
4. Reference existing documentation when helpful # Create new agent interactively
/agents create
# View agent details
/agents show n8n-workflow-specialist
```
### Step 3: Invoke in Conversation
**Explicit invocation:**
```
"Use the n8n-workflow-specialist agent to debug my workflow"
"Have the security-audit-specialist check API key permissions"
```
**Automatic delegation:**
Claude will automatically use agents based on task descriptions and configurations.
--- ---
## 📚 Example Tasks ## 📚 Usage Examples
### Debug n8n Workflow: ### Debug n8n Workflow:
```javascript ```
Task( Use the n8n-workflow-specialist agent to debug workflow ID j1MmXaRhDjvkRSLa
subagent_type='general-purpose',
description='n8n Workflow Specialist',
model='sonnet',
prompt='''
Debug workflow ID j1MmXaRhDjvkRSLa
Issue: Data lost after SSH node execution Issue: Data lost after SSH node execution
Current: Using $node["Extract Repo Info"].json Current: Using $node["Extract Repo Info"].json
Problem: Only SSH output remains Expected: Repository data should be preserved
Please:
1. Check $node pattern implementation
2. Verify node execution order
3. Provide corrected Code node config
4. Explain the fix
Reference: N8N_DATA_PRESERVATION_SOLUTION.md
'''
)
``` ```
### Security Audit: ### Security Audit:
```javascript ```
Task( Have the security-audit-specialist perform a comprehensive audit:
subagent_type='general-purpose',
description='Security Audit Specialist',
model='sonnet',
prompt='''
Perform security audit of AI Dev Factory:
1. Check file permissions on API keys and credentials 1. Check file permissions on all API keys and credentials
2. Verify no secrets in git history 2. Verify no secrets in git history
3. Review webhook authentication 3. Review webhook authentication
4. Check Docker container security 4. Check Docker container security
Report: Report: Security issues found, severity, remediation steps
- Security issues found
- Severity level
- Remediation steps
- Overall security score (1-10)
Files: /home/bam/.n8n_api_key, /home/bam/openhands/.env, /home/bam/.ssh/n8n_key
'''
)
``` ```
### Phase 3 Implementation: ### Phase 3 Implementation:
```javascript ```
Task( Use the phase3-implementation-specialist to create implementation plan for Step 1:
subagent_type='general-purpose',
description='Phase 3 Implementation Specialist',
model='opus',
prompt='''
Create implementation plan for Phase 3 Step 1: Setup Test Repository
Details: Details:
- Repository name: "autonomous-build-test" - Repository name: "autonomous-build-test"
@ -351,15 +411,7 @@ Details:
- Webhook URL: https://n8n.oky.sh/webhook/autonomous-build-test - Webhook URL: https://n8n.oky.sh/webhook/autonomous-build-test
- Events: Push events - Events: Push events
Provide: Provide: Gitea API command, webhook config, verification steps
1. Gitea API command or manual steps
2. Webhook configuration details
3. Verification steps
4. Testing procedure
Reference: phase3.md
'''
)
``` ```
--- ---
@ -369,10 +421,10 @@ Reference: phase3.md
- ✅ **Project-specific expertise** built into each agent - ✅ **Project-specific expertise** built into each agent
- ✅ **Reusable knowledge** - no need to repeat context - ✅ **Reusable knowledge** - no need to repeat context
- ✅ **Consistent problem-solving** approach - ✅ **Consistent problem-solving** approach
- ✅ **Copy-paste ready** templates - ✅ **Easy creation** via `/agents` command
- ✅ **Specialized context** for your project - ✅ **Specialized context** for your project
--- ---
*Agent Templates - Last Updated: 2025-12-02* *Agent Templates - Last Updated: 2025-12-02*
*Copy, customize, and use for efficient development* *Based on official Claude Code documentation*

View File

@ -1,28 +1,124 @@
# Custom Sub-Agents for AI Dev Factory - Usage Guide # Custom Sub-Agents for AI Dev Factory - Usage Guide
**Purpose:** Project-specific custom sub-agents for efficient development and automation **Updated based on official Claude Code documentation - https://code.claude.com/docs/en/sub-agents**
--- ---
## 🎯 Overview ## 🎯 Overview
Custom sub-agents are specialized Task configurations with tailored knowledge bases for specific aspects of the AI Dev Factory project. They combine Claude Code's built-in capabilities with project-specific expertise. Custom sub-agents are **specialized AI assistants** created as Markdown files with YAML frontmatter. They have their own context windows, custom system prompts, and configured tools. They operate independently from the main conversation to preserve context and provide specialized expertise.
--- ---
## 🤖 Available Custom Agents ## 📁 File-Based Architecture
### 1. N8N Workflow Specialist Agent ### Location
Project-level agents are stored in: `.claude/agents/`
**Purpose:** n8n workflow design, debugging, and optimization ### File Format
```yaml
---
name: your-agent-name
description: When to use this subagent
model: sonnet # Optional: sonnet, opus, haiku, or 'inherit'
tools: Read, Grep, Bash # Optional - inherits all if omitted
---
System prompt goes here...
```
### Directory Structure
```
project/
└── .claude/
└── agents/
├── n8n-workflow-specialist.md
├── openhands-sdk-specialist.md
├── gitea-integration-specialist.md
├── security-audit-specialist.md
├── docker-services-specialist.md
└── phase3-implementation-specialist.md
```
---
## 🏗️ Creating Custom Agents
### Method 1: Using `/agents` Command (Recommended)
**Usage:**
```bash ```bash
Task( # List all agents
subagent_type='general-purpose', /agents
description='n8n Workflow Specialist',
model='sonnet', # Create new agent interactively
prompt=''' /agents create
# View agent details
/agents show n8n-workflow-specialist
# Edit an agent
/agents edit n8n-workflow-specialist
```
### Method 2: Manual File Creation
```bash
# Create agents directory
mkdir -p .claude/agents
# Create agent file
cat > .claude/agents/n8n-workflow-specialist.md << 'EOF'
---
name: n8n-workflow-specialist
description: Specialized n8n workflow designer, debugger, and optimizer
model: sonnet
---
You are a specialized n8n workflow agent for the AI Dev Factory project.
[System prompt content]
EOF
```
---
## 🤖 Available Built-In Sub-Agents
Claude Code has 3 built-in sub-agents:
### 1. General-Purpose Subagent
- **Model:** Sonnet
- **Tools:** Full access to all tools
- **Purpose:** Complex, multi-step tasks requiring exploration and action
### 2. Plan Subagent
- **Model:** Sonnet
- **Tools:** Read, Glob, Grep, Bash
- **Purpose:** Research and gather information during plan mode
- **Use when:** Need to analyze codebase structure before implementation
### 3. Explore Subagent
- **Model:** Haiku
- **Tools:** Glob, Grep, Read, Bash (read-only)
- **Purpose:** Fast, lightweight code exploration
- **Thoroughness levels:** Quick, Medium, Very thorough
---
## 🛠️ Custom Project-Specific Agents
These are agents you create for the AI Dev Factory project:
### 1. N8N Workflow Specialist
**File:** `.claude/agents/n8n-workflow-specialist.md`
```yaml
---
name: n8n-workflow-specialist
description: Specialized n8n workflow designer, debugger, and optimizer. Expert in data flow patterns, $node preservation, webhook integration, and retry logic implementation.
model: sonnet
---
You are a specialized n8n workflow agent for the AI Dev Factory project. You are a specialized n8n workflow agent for the AI Dev Factory project.
Your expertise: Your expertise:
@ -44,7 +140,7 @@ Critical patterns:
1. SSH nodes OVERWRITE all data - must use $node["Previous Node"].json 1. SSH nodes OVERWRITE all data - must use $node["Previous Node"].json
2. passThrough: true does NOT preserve input data 2. passThrough: true does NOT preserve input data
3. staticData for retry counters: $workflow.staticData.retry_count 3. staticData for retry counters: $workflow.staticData.retry_count
4. Code node syntax: return { ... } 4. Data preservation: const repoData = $node["Extract Repo Info"].json;
Available workflows: Available workflows:
- Current: Gitea → OpenHands (7 nodes, working) - Current: Gitea → OpenHands (7 nodes, working)
@ -56,10 +152,6 @@ When working with n8n:
3. Use $node pattern for accessing previous node data 3. Use $node pattern for accessing previous node data
4. Document node configurations clearly 4. Document node configurations clearly
5. Test webhook triggers after changes 5. Test webhook triggers after changes
User task: {user_task}
'''
)
``` ```
**Best For:** **Best For:**
@ -73,22 +165,21 @@ User task: {user_task}
### 2. OpenHands SDK Agent ### 2. OpenHands SDK Agent
**Purpose:** OpenHands CLI integration and SDK wrapper management **File:** `.claude/agents/openhands-sdk-specialist.md`
```yaml
---
name: openhands-sdk-specialist
description: OpenHands SDK integration specialist. Expert in CLI usage, SDK wrapper creation, task formulation, and cost optimization strategies.
model: sonnet
---
**Usage:**
```bash
Task(
subagent_type='general-purpose',
description='OpenHands SDK Specialist',
model='sonnet',
prompt='''
You are an OpenHands SDK specialist for the AI Dev Factory project. You are an OpenHands SDK specialist for the AI Dev Factory project.
Your expertise: Your expertise:
- OpenHands CLI usage (/home/bam/.local/bin/openhands) - OpenHands CLI usage (/home/bam/.local/bin/openhands)
- SDK wrapper creation and optimization - SDK wrapper creation and optimization
- Task formulation for autonomous execution - Task formulation for autonomous execution
- Sub-agents coordination (File Editor, Bash Runner, Search, Code Analyzer)
- Cost optimization (token budgeting) - Cost optimization (token budgeting)
- Error handling and feedback loops - Error handling and feedback loops
@ -96,13 +187,6 @@ Current setup:
- OpenHands CLI: v1.3.0 at /home/bam/.local/bin/openhands - OpenHands CLI: v1.3.0 at /home/bam/.local/bin/openhands
- API Keys: /home/bam/openhands/.env (MINIMAX, DEEPSEEK, OPENAI) - API Keys: /home/bam/openhands/.env (MINIMAX, DEEPSEEK, OPENAI)
- SDK Wrapper: /home/bam/openhands-sdk-wrapper-sh.sh - SDK Wrapper: /home/bam/openhands-sdk-wrapper-sh.sh
- Working pattern: SSH → sh wrapper → "task"
Sub-agents available:
1. File Editor - Create, edit, view files
2. Bash Runner - Execute shell commands
3. Search Agent - Find files and patterns
4. Code Analyzer - Review code structure
Optimization strategies: Optimization strategies:
- Use parallel execution for independent tasks - Use parallel execution for independent tasks
@ -116,32 +200,27 @@ Task formulation best practices:
- Include expected output format - Include expected output format
- Reference existing files instead of recreating - Reference existing files instead of recreating
- Add verification steps - Add verification steps
User task: {user_task}
'''
)
``` ```
**Best For:** **Best For:**
- Creating OpenHands tasks - Creating OpenHands tasks
- Optimizing SDK wrapper usage - Optimizing SDK wrapper usage
- Coordinating multiple sub-agents
- Implementing cost-saving strategies
- Build and test automation - Build and test automation
- Cost optimization
--- ---
### 3. Gitea Integration Specialist Agent ### 3. Gitea Integration Specialist
**Purpose:** Gitea repository management, webhooks, and API integration **File:** `.claude/agents/gitea-integration-specialist.md`
```yaml
---
name: gitea-integration-specialist
description: Gitea repository management, webhook configuration, and API integration specialist. Expert in CI/CD pipeline setup and Git operations.
model: sonnet
---
**Usage:**
```bash
Task(
subagent_type='general-purpose',
description='Gitea Integration Specialist',
model='sonnet',
prompt='''
You are a Gitea integration specialist for the AI Dev Factory project. You are a Gitea integration specialist for the AI Dev Factory project.
Your expertise: Your expertise:
@ -163,7 +242,6 @@ API Endpoints:
- Create repo: POST /api/v1/user/repos - Create repo: POST /api/v1/user/repos
- Create webhook: POST /api/v1/repos/{owner}/{repo}/hooks - Create webhook: POST /api/v1/repos/{owner}/{repo}/hooks
- Update status: POST /api/v1/repos/{owner}/{repo}/statuses/{sha} - Update status: POST /api/v1/repos/{owner}/{repo}/statuses/{sha}
- List workflows: GET /api/v1/actions/workflows
Common operations: Common operations:
1. Repository creation with webhooks 1. Repository creation with webhooks
@ -171,16 +249,6 @@ Common operations:
3. Commit status updates (success/failure/pending) 3. Commit status updates (success/failure/pending)
4. Git SSH key management 4. Git SSH key management
5. Webhook delivery troubleshooting 5. Webhook delivery troubleshooting
Webhook configuration:
- URL: https://n8n.oky.sh/webhook/{webhook-id}
- Events: Push events (or custom)
- Content-Type: application/json
- Secret: For signature verification
User task: {user_task}
'''
)
``` ```
**Best For:** **Best For:**
@ -194,15 +262,15 @@ User task: {user_task}
### 4. Security Audit Agent ### 4. Security Audit Agent
**Purpose:** Security verification and API key management **File:** `.claude/agents/security-audit-specialist.md`
```yaml
---
name: security-audit-specialist
description: Security audit specialist for AI Dev Factory. Expert in API key security, file permissions, and system security verification.
model: sonnet
---
**Usage:**
```bash
Task(
subagent_type='general-purpose',
description='Security Audit Specialist',
model='sonnet',
prompt='''
You are a security audit agent for AI Dev Factory project. You are a security audit agent for AI Dev Factory project.
Your expertise: Your expertise:
@ -217,22 +285,13 @@ Files to check:
1. /home/bam/.n8n_api_key (JWT token) - Should be 600 1. /home/bam/.n8n_api_key (JWT token) - Should be 600
2. /home/bam/openhands/.env (API keys) - Should be 600 2. /home/bam/openhands/.env (API keys) - Should be 600
3. /home/bam/.ssh/n8n_key (SSH key) - Should be 600 3. /home/bam/.ssh/n8n_key (SSH key) - Should be 600
4. /home/bam/.ssh/n8n_key.pub (public key)
Security checklist: Security checklist:
✓ API keys have proper file permissions (600 - owner read/write only) ✓ API keys have proper permissions (600)
✓ No hardcoded secrets in code or documentation ✓ No hardcoded secrets in code
✓ Webhooks use authentication/signature verification ✓ Webhooks use authentication
✓ SSH keys are encrypted (if passphrase protected) ✓ Docker containers run securely
✓ Service ports are properly configured (not exposing internal ports) ✓ SSL/TLS properly configured
✓ Docker containers run with non-root users
✓ Environment variables don't leak in logs
✓ Gitea tokens have minimal required permissions
Current services:
- n8n: https://n8n.oky.sh (exposed via Caddy)
- Gitea: https://git.oky.sh (exposed via Caddy)
- Caddy: Auto SSL with Let's Encrypt
Audit process: Audit process:
1. Check file permissions on all credential files 1. Check file permissions on all credential files
@ -241,10 +300,6 @@ Audit process:
4. Check Docker container security 4. Check Docker container security
5. Verify SSL/TLS configuration 5. Verify SSL/TLS configuration
6. Review service exposure 6. Review service exposure
User task: {user_task}
'''
)
``` ```
**Best For:** **Best For:**
@ -258,15 +313,15 @@ User task: {user_task}
### 5. Docker Services Agent ### 5. Docker Services Agent
**Purpose:** Service management and Docker orchestration **File:** `.claude/agents/docker-services-specialist.md`
```yaml
---
name: docker-services-specialist
description: Docker services management specialist. Expert in service orchestration, health monitoring, log analysis, and troubleshooting.
model: sonnet
---
**Usage:**
```bash
Task(
subagent_type='general-purpose',
description='Docker Services Specialist',
model='sonnet',
prompt='''
You are a Docker services specialist for the AI Dev Factory project. You are a Docker services specialist for the AI Dev Factory project.
Your expertise: Your expertise:
@ -294,21 +349,11 @@ docker compose -f /home/bam/services/services-stack/docker-compose.yml logs -f [
# Restart service # Restart service
docker compose -f /home/bam/services/services-stack/docker-compose.yml restart [service] docker compose -f /home/bam/services/services-stack/docker-compose.yml restart [service]
# Scale service
docker compose -f /home/bam/services/services-stack/docker-compose.yml up -d --scale [service]=[count]
# Check resource usage
docker stats
Troubleshooting: Troubleshooting:
- Container won't start: Check docker logs [container] - Container won't start: Check docker logs [container]
- Port conflicts: Verify ports not in use (netstat -tulpn) - Port conflicts: Verify ports not in use (netstat -tulpn)
- Volume issues: Check mount points and permissions - Volume issues: Check mount points and permissions
- Network issues: Inspect docker network ls and docker network inspect - Network issues: Inspect docker network ls and docker network inspect
User task: {user_task}
'''
)
``` ```
**Best For:** **Best For:**
@ -322,15 +367,15 @@ User task: {user_task}
### 6. Phase 3 Implementation Agent ### 6. Phase 3 Implementation Agent
**Purpose:** Phase 3 autonomous build test MVP implementation **File:** `.claude/agents/phase3-implementation-specialist.md`
```yaml
---
name: phase3-implementation-specialist
description: Phase 3 autonomous build test MVP implementation specialist. Expert in CI/CD workflow design, retry logic, and build automation.
model: opus
---
**Usage:**
```bash
Task(
subagent_type='general-purpose',
description='Phase 3 Implementation Specialist',
model='opus',
prompt='''
You are a Phase 3 implementation specialist for the AI Dev Factory project. You are a Phase 3 implementation specialist for the AI Dev Factory project.
Your expertise: Your expertise:
@ -359,39 +404,17 @@ Workflow Design (11 nodes):
└─ NO → [9] Format errors → [10] Retry check → [11] Retry/Fail └─ NO → [9] Format errors → [10] Retry check → [11] Retry/Fail
Key Components: Key Components:
A. Retry Counter: A. Retry Counter: $workflow.staticData.retry_count (max 3)
$workflow.staticData = $workflow.staticData || {}; B. Error Feedback: const errorMsg = `Build failed: ${errors}`;
$workflow.staticData.retry_count = ($workflow.staticData.retry_count || 0) + 1; C. Gitea Status: POST /api/v1/repos/{owner}/{repo}/statuses/{sha}
if ($workflow.staticData.retry_count >= 3) return fail;
B. Error Feedback: Implementation Steps:
const errorMsg = `Build failed: ${errors}\nPlease fix.`;
C. Gitea Status Update:
POST /api/v1/repos/{owner}/{repo}/statuses/{sha}
Body: {"state": "success", "description": "Build passed"}
Implementation Steps (from phase3.md):
1. Create test repository in Gitea 1. Create test repository in Gitea
2. Configure Gitea webhook 2. Configure Gitea webhook
3. Build n8n workflow (11 nodes) 3. Build n8n workflow (11 nodes)
4. Test success path 4. Test success/failure/retry paths
5. Test failure path with retry 5. Implement Gitea status updates
6. Test max retries 6. Test with real MVP project
7. Implement Gitea status updates
8. Test with real MVP project
Success Criteria:
✓ End-to-end workflow completes
✓ OpenHands executes autonomously
✓ Retry logic works (max 3)
✓ Error feedback provided
✓ Gitea commit status updated
✓ Tested with real project
User task: {user_task}
'''
)
``` ```
**Best For:** **Best For:**
@ -405,140 +428,58 @@ User task: {user_task}
## 🚀 How to Use Custom Agents ## 🚀 How to Use Custom Agents
### Method 1: Direct Task Invocation ### Step 1: Create the Agent File
```bash ```bash
# Use N8N Workflow Specialist # Create directory
Task( mkdir -p .claude/agents
subagent_type='general-purpose',
description='n8n Workflow Specialist',
model='sonnet',
prompt='''[paste the full prompt from above]'''
)
# In your task, the agent will apply n8n-specific knowledge # Create agent from template (see agent-templates.md)
# Copy the YAML frontmatter + system prompt
``` ```
### Method 2: Create Agent Template File ### Step 2: Manage with `/agents` Command
Create `/home/bam/claude/mvp-factory/agent-templates.md`:
```markdown
# Custom Agent Templates
## N8N Workflow Specialist
```javascript
Task(
subagent_type='general-purpose',
description='n8n Workflow Specialist',
model='sonnet',
prompt='''
[full prompt here]
'''
)
```
## Security Audit Specialist
```javascript
Task(
subagent_type='general-purpose',
description='Security Audit Specialist',
model='sonnet',
prompt='''
[full prompt here]
'''
)
```
```
Then copy-paste when needed.
### Method 3: Integrated Task with Context
```bash ```bash
# Provide task + relevant context # List all agents
Task( /agents
subagent_type='general-purpose',
description='n8n Workflow Specialist',
model='sonnet',
prompt='''
You are the n8n Workflow Specialist for AI Dev Factory.
Context: # Create agent interactively (easier)
- Current workflow ID: j1MmXaRhDjvkRSLa /agents create
- Issue: Data not preserved after SSH node
- Using: $node["Extract Repo Info"].json pattern
Task: Debug why workflow data is being lost and provide fix # View agent details
/agents show n8n-workflow-specialist
The agent will use its n8n expertise to analyze and solve this. # Edit existing agent
''' /agents edit n8n-workflow-specialist
) ```
### Step 3: Invoke in Conversation
**Explicit invocation (recommended):**
```
"Use the n8n-workflow-specialist agent to debug my workflow"
"Have the security-audit-specialist check API key permissions"
"Use the phase3-implementation-specialist to create an implementation plan"
```
**Automatic delegation:**
Claude will automatically use agents based on task descriptions and configurations.
**Chaining agents:**
```
"First use the code-analyzer agent, then the optimizer agent"
``` ```
--- ---
## 📚 Best Practices ## 📚 Usage Examples
### 1. Choose the Right Model ### Example 1: Debug n8n Workflow
- **sonnet**: Most tasks, good balance of capability/speed
- **opus**: Complex analysis, Phase 3 implementation, multi-system debugging
- **haiku**: Simple tasks, quick lookups
### 2. Optimize Prompts **Request:**
```bash
✅ Good prompt structure:
- Role: What you are
- Expertise: What you know
- Current setup: System state
- Key patterns: Critical info to remember
- Task: What to do
- Format: How to respond
❌ Avoid:
- Too vague: "help with n8n"
- Missing context: No system info
- Unclear output: No response format specified
``` ```
Use the n8n-workflow-specialist agent to debug workflow ID j1MmXaRhDjvkRSLa
### 3. Chain Agents for Complex Tasks
```bash
# Step 1: Audit with Security Agent
Task(
subagent_type='general-purpose',
description='Security Audit Specialist',
model='sonnet',
prompt='[security audit prompt]'
)
# Step 2: Fix issues with N8N Agent
Task(
subagent_type='general-purpose',
description='n8n Workflow Specialist',
model='sonnet',
prompt='[n8n fix prompt with audit results]'
)
```
### 4. Reuse Successful Patterns
```bash
# Save working agent configurations
# Reference them by name in future tasks
# Refine based on results
```
---
## 🎯 Example Use Cases
### Use Case 1: Debug n8n Workflow
```bash
Task(
subagent_type='general-purpose',
description='n8n Workflow Specialist',
model='sonnet',
prompt='''
Debug workflow ID j1MmXaRhDjvkRSLa
Issue: After SSH node execution, repository data is lost Issue: After SSH node execution, repository data is lost
Current pattern: Using $node["Extract Repo Info"].json Current pattern: Using $node["Extract Repo Info"].json
@ -553,18 +494,17 @@ Please:
5. Explain why current implementation fails 5. Explain why current implementation fails
Reference: N8N_DATA_PRESERVATION_SOLUTION.md Reference: N8N_DATA_PRESERVATION_SOLUTION.md
'''
)
``` ```
### Use Case 2: Security Audit **Agent will:** Apply n8n-specific expertise to analyze and solve the issue
```bash
Task( ---
subagent_type='general-purpose',
description='Security Audit Specialist', ### Example 2: Security Audit
model='sonnet',
prompt=''' **Request:**
Perform comprehensive security audit of AI Dev Factory: ```
Have the security-audit-specialist perform a comprehensive security audit:
1. Check file permissions on all API keys and credentials 1. Check file permissions on all API keys and credentials
2. Verify no secrets in git history 2. Verify no secrets in git history
@ -583,18 +523,17 @@ Files to check:
- /home/bam/openhands/.env - /home/bam/openhands/.env
- /home/bam/.ssh/n8n_key - /home/bam/.ssh/n8n_key
- Gitea webhook configurations - Gitea webhook configurations
'''
)
``` ```
### Use Case 3: Phase 3 Implementation **Agent will:** Perform systematic security audit with project-specific knowledge
```bash
Task( ---
subagent_type='general-purpose',
description='Phase 3 Implementation Specialist', ### Example 3: Phase 3 Implementation
model='opus',
prompt=''' **Request:**
Create implementation plan for Phase 3 Step 1: Setup Test Repository ```
Use the phase3-implementation-specialist to create implementation plan for Phase 3 Step 1: Setup Test Repository
Details: Details:
- Need to create repository: "autonomous-build-test" - Need to create repository: "autonomous-build-test"
@ -610,18 +549,111 @@ Please provide:
5. Troubleshooting guide 5. Troubleshooting guide
Reference: phase3.md for complete context Reference: phase3.md for complete context
'''
)
``` ```
**Agent will:** Use Phase 3 expertise to create detailed implementation plan
--- ---
## 📖 Documentation Files ## 🎓 Advanced Techniques
### 1. Agent Chaining
**Pattern:**
```
"First use code-analyzer agent to understand the codebase, then optimizer agent to improve it"
```
### 2. Resume Previous Agent Execution
Each agent execution gets an `agentId` for resuming later:
- Stored in `agent-{agentId}.jsonl`
- Pass `resume: "agentId"` to continue previous conversations
### 3. Context Passing
**Step 1:** Use one agent to generate plan
**Step 2:** Use another agent to implement (reference Step 1 output)
### 4. Model Selection
**sonnet** (default):
- Balanced capability and speed
- Good for most tasks
**opus**:
- More capable for complex analysis
- Use for Phase 3 implementation, multi-system debugging
**haiku**:
- Fast, lightweight
- Use for simple, quick exploration
**'inherit'**:
- Uses main conversation's model
---
## 📋 Best Practices
### 1. Create Focused Agents
- Single responsibility per agent
- Clear, specific descriptions
- Detailed system prompts
### 2. Use Tool Restrictions
```yaml
---
tools: Read, Grep, Bash # Limit to necessary tools only
---
```
### 3. Document Everything
- Clear descriptions
- Detailed system prompts
- Reference documentation
### 4. Version Control
- Commit agent files to git
- Track changes to agent prompts
- Maintain changelog
### 5. Start Simple
- Begin with basic agent
- Test with simple tasks
- Add complexity gradually
---
## 🔍 Troubleshooting
### Agent Not Found
- Check file exists in `.claude/agents/`
- Verify YAML frontmatter is valid
- Use `/agents` to list available agents
### Agent Not Being Used
- Use explicit invocation: "Use the [agent-name] agent..."
- Check agent description matches task
- Ensure agent is properly configured
### Wrong Agent Invoked
- Be more specific in invocation
- Check agent descriptions
- Use explicit agent name
### Agent Execution Fails
- Check YAML syntax
- Verify model is valid
- Test with simple prompt first
---
## 📖 Reference Files
### Created Files ### Created Files
- **custom-subagents-usage-guide.md** - This file - **custom-subagents-usage-guide.md** - This file
- **agent-templates.md** - Copy-paste ready templates (create separately) - **agent-templates.md** - Copy-paste ready templates
- **claude-code-subagents-doc.md** - General Claude Code sub-agents guide
### Referenced Files ### Referenced Files
- **phase3.md** - Phase 3 implementation plan - **phase3.md** - Phase 3 implementation plan
@ -630,83 +662,38 @@ Reference: phase3.md for complete context
--- ---
## 🎓 Advanced Techniques
### 1. Agent Composition
```bash
# Combine multiple agents for complex tasks
Task(
subagent_type='general-purpose',
description='Multi-Agent Coordinator',
model='opus',
prompt='''
Coordinate between multiple specialists:
1. First: Use Security Audit Agent to check API keys
2. Then: Use N8N Agent to fix any workflow issues
3. Finally: Use Docker Agent to restart services
Provide progress updates at each step.
'''
)
```
### 2. Context Passing
```bash
# Step 1: Generate plan with Phase 3 Agent
Task(
subagent_type='general-purpose',
description='Phase 3 Implementation Specialist',
model='opus',
prompt='Create plan for Steps 1-3'
)
# Step 2: Execute with relevant agents (using output from Step 1)
```
### 3. State Management
```bash
# Use staticData for agent state
Task(
subagent_type='general-purpose',
description='Stateful Workflow Agent',
prompt='''
Track implementation progress:
- Current step: {current_step}
- Completed: {completed_steps}
- Next: {next_step}
Update progress and move to next step.
'''
)
```
---
## ✅ Summary ## ✅ Summary
**Custom Sub-Agents Provide:** **Custom Sub-Agents Provide:**
- Project-specific expertise - Project-specific expertise
- Consistent problem-solving approach
- Reusable knowledge patterns - Reusable knowledge patterns
- Efficient task execution - Efficient task execution
- Specialized context awareness - Specialized context awareness
- Persistent configuration
**How to Use:** **How to Use:**
1. Choose appropriate agent for your task 1. Create `.claude/agents/` directory
2. Use Task tool with subagent_type='general-purpose' 2. Add agent files with YAML frontmatter
3. Include model specification (sonnet/opus/haiku) 3. Use `/agents` command to manage
4. Provide task prompt with context 4. Invoke explicitly: "Use the [agent] agent..."
5. Agent applies specialized knowledge 5. Agents apply specialized knowledge
**Key Differences from Previous Approach:**
- ✅ File-based (not Task tool)
- ✅ YAML frontmatter configuration
- ✅ `/agents` command for management
- ✅ Stored in `.claude/agents/` directory
- ✅ Can be version controlled
**Next Steps:** **Next Steps:**
1. Copy-paste agent prompts from this guide 1. Create `.claude/agents/` directory
2. Create agent-templates.md for quick access 2. Copy templates from `agent-templates.md`
3. Test with your specific use cases 3. Use `/agents create` for easy setup
4. Refine prompts based on results 4. Test with specific tasks
5. Build your agent library 5. Refine based on results
--- ---
*Custom Sub-Agents Guide - Last Updated: 2025-12-02* *Custom Sub-Agents Guide - Last Updated: 2025-12-02*
*Based on official Claude Code documentation*
*Ready for AI Dev Factory Project Use* *Ready for AI Dev Factory Project Use*