Zoro Agent Architecture: The Mansion
Overview
The Zoro agent system is architected as a hierarchical mansion structure, where Zorro serves as the master orchestrator and head of the household. The mansion operates with specialized agents, each fulfilling distinct roles in a coordinated workflow. This document serves as the complete architectural blueprint for understanding and implementing the Zoro agent ecosystem.
Architecture Philosophy
The mansion architecture follows a hierarchical orchestration pattern where:
- Zorro (Primary Agent) operates at the top level using the primary API key
- All sub-agents operate using secondary API keys managed by the Butler
- Each agent has specialized responsibilities and clear communication channels
- Task execution follows a structured workflow from creation to completion
CRITICAL RULES - Must Follow
These rules are ABSOLUTE and must be followed by all agents implementing this architecture:
Task Flow:
- ✅ ALL tasks from human user go DIRECTLY to Factory Manager
- ❌ Zorro does NOT create teams or spawn agents directly
- ✅ Zorro delegates ALL task execution to Factory Manager
- ✅ Factory Manager is responsible for ALL agent creation and spawning
Factory Manager Responsibilities:
- ✅ Receives ALL tasks from Zorro
- ✅ Creates teams when needed (NOT Zorro's job)
- ✅ Discusses with Librarian about what skills agents need
- ✅ Coordinates with Butler for API key assignment
- ✅ Creates PRD for each task
- ✅ Spawns all sub-agents
Butler API Management:
- ✅ Butler assesses the work and assigns appropriate secondary API key
- ✅ Butler rotates API keys when 80% limit is reached (not 90%)
- ✅ Butler manages ALL secondary API keys for ALL mansion members (except Zorro)
Janitor Timing:
- ✅ Janitor ONLY runs AFTER tasks are completed
- ✅ Moderator has the right to summon Janitor after job completion
- ❌ Janitor must NEVER run during active task execution
- ✅ Janitor must verify no active tasks before cleanup
Team Creation:
- ✅ Factory Manager creates teams (during agent spawning)
- ❌ Zorro does NOT create teams
- ✅ Moderator manages teams created by Factory Manager
Violation of these rules will cause system failures. All agents must strictly adhere to these rules.
The Mansion Hierarchy
┌─────────────┐
│ ZORRO │ (Primary Orchestrator)
│ (Master) │ Uses PRIMARY API only
└──────┬──────┘
│
┌──────────────────┼──────────────────┐
│ │ │
┌────▼────┐ ┌─────▼─────┐ ┌────▼─────┐
│ Factory │ │ Moderator │ │ Security │
│ Manager │ │ │ │ Officer │
│ │ │ │ │ │
│(Manages)│ │(Manages) │ │(Manages) │
└────┬────┘ └─────┬─────┘ └──────────┘
│ │ │
│ │ │
┌────▼────┐ ┌─────▼─────┐ ┌────▼─────┐
│ Butler │ │Librarian │ │Gatekeeper│
│ │ │ │ │ │
│(Manages │ │(Provides │ │(Reviews │
│ ALL API │ │ Skills) │ │ Code) │
│ Keys) │ │ │ │ │
└────┬────┘ └─────┬─────┘ └─────┬────┘
│ │ │
│ │ │
┌────▼──────────────────┼──────────────────▼─────┐
│ Janitor │
│ (Cleanup Specialist) │
└───────────────────────┬─────────────────────────┘
│
┌──────▼──────┐
│ Sub-Agents │ (Lowest Level)
│ │
│ Created by: │
│ Factory Mgr │
│ │
│ Managed by: │
│ Moderator │
│ │
│ API from: │
│ Butler │
│ │
│ Skills from:│
│ Librarian │
└─────────────┘
Hierarchy Rules:
- Zorro: Top level, uses PRIMARY API exclusively
- Factory Manager & Moderator: Direct management of sub-agents
- Butler: Manages ALL secondary API keys for ALL mansion members (except Zorro)
- Sub-Agents: Lowest level, managed by Factory Manager and Moderator
Agent Roles & Responsibilities
1. Zorro - The Master Orchestrator
Role: Primary agent and head of the mansion
Responsibilities:
- Direct interface with the human user
- Task decomposition and high-level planning
- Orchestration and delegation of work to specialized agents
- Final decision-making authority
- Receives status updates from Moderator
API Usage:
- Exclusively uses the PRIMARY API key
- Only Zorro has access to the primary API
- All other agents use secondary APIs managed by Butler
Key Interactions:
- Receives tasks from human user
- Delegates to Factory Manager for sub-agent creation
- Receives progress updates from Moderator
- Makes strategic decisions based on agent reports
CRITICAL WORKFLOW RULE:
- ALL tasks from human user go DIRECTLY to Factory Manager
- Zorro does NOT create teams or spawn agents directly
- Zorro delegates ALL task execution to Factory Manager
- Factory Manager is responsible for ALL agent creation and spawning
Workflow:
- Human provides task to Zorro
- Zorro receives task and immediately delegates to Factory Manager
- Zorro monitors progress through Moderator (receives updates only)
- Zorro receives final completion status from Moderator
- Zorro never directly creates teams or spawns agents - this is Factory Manager's responsibility
2. Butler - The Resource Manager
Role: API key and resource management specialist
CRITICAL RESPONSIBILITY: Butler manages ALL secondary API keys for ALL mansion members EXCEPT Zorro. This includes:
- Factory Manager
- Moderator
- Librarian
- Security Officer
- Gatekeeper
- Janitor
- All Sub-Agents
Responsibilities:
- Universal API Key Management: Manages secondary API keys for ALL mansion members (except Zorro)
- Token & Credit Monitoring: Tracks usage across all API providers (e.g., Groq, Kimi K2)
- Rate Limit Management: Monitors token limits, requests per day, requests per minute, and usage quotas
- Context Overflow Prevention: Monitors context window usage and prevents overflow
- API Rotation: Automatically rotates API keys when approaching exhaustion
- Open Router Functionality: Routes requests to available APIs when one is near capacity
- Resource Allocation: Assigns appropriate API keys to all mansion members
- Request Throttling: Implements intelligent throttling to prevent rate limit violations
- Context Window Management: Tracks and manages context window usage per request
How Butler Works:
1. API Key Assignment Process:
- When any mansion member (except Zorro) needs an API key, they request from Butler
- Butler maintains a pool of available secondary API keys
- Butler assigns keys based on:
- Current usage levels
- Provider-specific limits
- Task priority
- Agent type requirements
2. Rate Limit Management:
- Real-time Monitoring: Continuously tracks:
- Tokens used vs. tokens available
- Requests made vs. requests allowed (per minute/hour/day)
- Context window usage per request
- Provider-specific rate limits
- Prevention Strategy:
- Tracks request frequency per API key
- Implements request queuing when approaching limits
- Distributes load across multiple API keys
- Prevents burst requests that could trigger rate limits
3. Context Overflow Prevention:
- Context Window Tracking: Monitors context size for each request:
- Input tokens (prompt + conversation history)
- Output tokens (response)
- Total context window size per provider
- Overflow Prevention Mechanisms:
- Context Summarization: Automatically summarizes old conversation history when approaching limit
- Context Truncation: Removes least relevant context when necessary
- Request Splitting: Splits large requests into smaller chunks
- Provider Selection: Routes to providers with larger context windows when needed
- Alert System: Warns agents when context is approaching limits (80% threshold)
4. API Rotation Strategy:
- Continuous Monitoring: Tracks usage for each API key in real-time
- Rotation Triggers:
- Rotation Level (80%): Actively rotate to alternative API when 80% limit is reached (PRIMARY ROTATION THRESHOLD)
- Warning Level (75%): Flagged for rotation, prepare alternative
- Emergency Level (95%): Immediate rotation, pause requests if needed
- Rotation Process:
- Identify API key approaching 80% limit
- Select alternative API key from available pool
- Migrate active requests to new API key (if possible)
- Update all agents using the exhausted key
- Mark exhausted key for cooldown period
- Resume operations with new key
CRITICAL: Butler rotates API keys when 80% limit is reached (not 90%). This is the primary rotation threshold.
5. Request Routing:
- Load Balancing: Distributes requests across available API keys
- Provider Selection: Chooses best provider based on:
- Current usage levels
- Task requirements (context size, speed, etc.)
- Provider capabilities
- Failover: Automatically switches to backup API if primary fails
API Providers Managed:
- Groq (tokens per day, requests per minute)
- Kimi K2 (tokens per day, context window size)
- Other free-tier API providers available
Monitoring Capabilities:
- Real-time token usage tracking per API key
- Request count monitoring (per minute/hour/day)
- Daily/hourly quota tracking
- Context window usage per request
- Rate limit proximity alerts
- Capacity exhaustion alerts
- Provider-specific limit tracking
- Request latency monitoring
Rate Limit Protection Mechanisms:
- Request Queuing: Queues requests when approaching rate limits
- Exponential Backoff: Implements backoff on rate limit errors
- Request Spacing: Ensures minimum time between requests
- Burst Prevention: Prevents sudden spikes in requests
- Distributed Load: Spreads requests across multiple keys/providers
Context Management Mechanisms:
- Context Size Tracking: Monitors token count per conversation
- Automatic Summarization: Summarizes old messages when context grows
- Smart Truncation: Removes least important context first
- Provider Matching: Routes to providers with appropriate context windows
- Context Compression: Compresses context when possible
Key Interactions:
- Receives API requests from ALL mansion members (except Zorro)
- Provides API keys to Factory Manager, Moderator, Librarian, Security Officer, Gatekeeper, Janitor, and all Sub-Agents
- Coordinates with Moderator for resource allocation updates
- Never interacts with primary API key (Zorro's exclusive)
- Receives usage reports from all agents
- Provides usage statistics to Moderator for reporting
Data Structures:
- API Key Registry:
{provider: string, key: string, usage: {tokens: number, requests: number, context_windows: number[]}, limits: {tokens: number, requests_per_minute: number, requests_per_day: number, context_window: number}, status: 'active'|'near_exhaustion'|'exhausted'|'cooldown', assigned_to: string[]}
- Rotation Queue: Priority-based queue for API key rotation
- Usage Logs: Historical usage data for analytics
- Context Tracking:
{agent_id: string, conversation_id: string, current_tokens: number, max_tokens: number, history: object[]}
- Rate Limit Status:
{api_key: string, requests_last_minute: number, requests_last_hour: number, requests_today: number, next_reset: datetime}
3. Librarian - The Knowledge Keeper
Role: Skills and knowledge distribution specialist
Responsibilities:
- Skills Directory Management: Maintains comprehensive library of available skills
- Skill Distribution: Assigns appropriate skills to sub-agents based on task requirements
- Skill Sources: Integrates skills from:
skills.sh (primary skills repository)
clawhub.ai (secondary skills repository)
- Skill Matching: Analyzes task requirements and matches with relevant skills
- Skill Updates: Keeps skills library updated and synchronized
- Skill Validation: Ensures skills are compatible and functional
Skills Library Structure:
Skills Library/
├── Core Skills/
│ ├── Code Generation
│ ├── File Operations
│ ├── API Integration
│ └── Data Processing
├── Specialized Skills/
│ ├── Web Development
│ ├── Database Operations
│ ├── Testing & QA
│ └── Deployment
└── Custom Skills/
└── (Project-specific skills)
How Librarian Works:
1. Skill Discovery & Integration:
- Primary Source: Integrates skills from
skills.sh repository
- Secondary Source: Integrates skills from
clawhub.ai repository
- Skill Indexing: Indexes all available skills with metadata:
- Skill name and description
- Capabilities and use cases
- Dependencies and requirements
- Compatibility information
- Performance metrics
- Skill Updates: Regularly syncs with repositories for new skills
- Skill Validation: Tests skills for functionality and compatibility
2. Skill Matching Process:
- Requirement Analysis: Analyzes task requirements from PRD
- Skill Search: Searches skills library for matching capabilities
- Compatibility Check: Validates skill compatibility with:
- Task requirements
- Agent type
- Existing skills
- Dependencies
- Skill Selection: Selects optimal skill combination for task
- Learning Integration: Uses learned patterns to recommend best skills
3. Skill Distribution:
- Skill Package: Creates skill package for sub-agent:
- Selected skills
- Installation instructions
- Usage documentation
- Example code/patterns
- Dependencies list
- Distribution: Provides skills to requesting agent
- Verification: Verifies skills are properly installed
- Support: Provides ongoing support for skill usage
4. Skill Monitoring & Updates:
- Usage Tracking: Tracks which skills are used by which agents
- Effectiveness Monitoring: Monitors skill effectiveness:
- Success rate
- Performance impact
- Error rates
- User satisfaction
- Continuous Monitoring: Monitors if agents need additional skills
- Dynamic Updates: Adds skills dynamically during task execution if needed
- Learning: Learns which skill combinations work best
5. Skill Library Management:
- Organization: Organizes skills by category and capability
- Version Control: Tracks skill versions and updates
- Documentation: Maintains comprehensive skill documentation
- Testing: Tests skills before distribution
- Deprecation: Deprecates outdated or broken skills
Workflow:
- Receives skill requirements from Factory Manager (during agent creation) or Moderator (during task execution)
- Analyzes task requirements and PRD
- Searches skills library for matching capabilities
- Uses learning system to identify optimal skill combinations
- Validates skill compatibility with sub-agent's task and existing skills
- Creates skill package with documentation and examples
- Distributes skills to requesting sub-agent
- Verifies skills are properly installed and functional
- Tracks skill usage and effectiveness
- Continuously monitors if sub-agents need additional skills
- Updates skills library with new skills from repositories
- Learns from skill usage patterns for future recommendations
Key Interactions:
- Receives skill requests from Factory Manager (during sub-agent creation)
- Receives skill requests from Moderator (during task execution)
- Receives skill requests from sub-agents (during runtime)
- Provides skills to sub-agents with installation instructions
Skill Distribution Protocol:
- Each sub-agent receives only skills relevant to their PRD
- Skills are provided with documentation and usage examples
- Librarian tracks which skills are assigned to which agents
- Librarian can revoke or update skills if needed
4. Moderator - The Task Manager & HR
Role: Sub-agent coordination, task oversight, and real-time monitoring specialist
Responsibilities:
- Sub-Agent Management: Oversees all active sub-agents and their tasks
- Task Monitoring: Tracks progress, blockers, and status of all sub-agent tasks
- Inter-Agent Coordination: Facilitates communication between sub-agents
- Blocker Resolution: Identifies and escalates blockers to appropriate agents
- Progress Reporting: Provides regular updates to Zorro
- HR Functions: Manages sub-agent lifecycle, performance, and resource needs
- Team Formation: Can create teams of sub-agents for complex tasks
- GitHub Monitoring Dashboard: Maintains real-time monitoring dashboard on GitHub
- Real-Time Updates: Continuously updates GitHub repository with current system status
How Moderator Works:
1. Sub-Agent Monitoring:
- Continuous Monitoring: Actively monitors all sub-agents in real-time
- Status Tracking: Tracks status of each sub-agent (active, blocked, completed, failed)
- Progress Tracking: Monitors progress percentage for each task
- Health Checks: Performs periodic health checks on all sub-agents
- Performance Metrics: Collects performance data (execution time, success rate, error rate)
2. Task Management:
- Task Assignment: Receives tasks from Factory Manager and assigns to sub-agents
- Task Prioritization: Prioritizes tasks based on dependencies and urgency
- Task Dependencies: Tracks dependencies between tasks
- Checkpoint Validation: Validates checkpoints as sub-agents complete them
- Success Criteria Validation: Verifies tasks meet PRD success criteria
3. Blocker Management:
- Blocker Detection: Identifies blockers from sub-agent reports
- Blocker Classification: Classifies blockers by type and severity:
- Skill Blocker: Missing required skill → Contact Librarian
- Resource Blocker: API/resource issue → Contact Butler
- Agent Blocker: Need additional agent → Contact Factory Manager
- Code Blocker: Code review needed → Contact Gatekeeper
- Security Blocker: Security issue → Contact Security Officer
- Blocker Resolution: Coordinates resolution with appropriate specialist agents
- Escalation: Escalates critical blockers to Zorro immediately
4. Inter-Agent Coordination:
- Communication Facilitation: Enables communication between sub-agents
- Dependency Management: Manages dependencies between sub-agents
- Resource Sharing: Coordinates resource sharing between sub-agents
- Conflict Resolution: Resolves conflicts between sub-agents
5. GitHub Monitoring Dashboard:
6. Progress Reporting to Zorro:
- Regular Updates: Provides updates at configurable intervals (default: every 5 minutes)
- Immediate Updates: Sends immediate updates for:
- Critical blockers
- Task completions
- Agent failures
- Resource exhaustion warnings
- Update Format:
- Task completion percentages
- Active blockers and their severity
- Resource utilization (API usage, context usage)
- Sub-agent performance metrics
- Team progress (if teams are active)
- GitHub dashboard link for detailed view
7. Team Management:
- Team Formation: Factory Manager creates teams (NOT Moderator or Zorro)
- Team Assignment: Factory Manager assigns team-level tasks
- Team Coordination: Moderator coordinates communication within teams
- Team Progress Tracking: Moderator tracks progress at team level
- Team Performance: Moderator monitors team performance metrics
NOTE: Teams are created by Factory Manager during agent spawning phase, not by Moderator or Zorro.
Monitoring Capabilities:
- Real-time task status tracking
- Blocker detection and classification
- Resource requirement monitoring
- Inter-agent dependency tracking
- Performance metrics collection
- GitHub dashboard updates
- API usage monitoring (via Butler)
- Context usage monitoring (via Butler)
Escalation Protocol:
- Level 1 (Sub-Agent Level): Sub-agent encounters blocker
- Level 2 (Moderator Level): Moderator analyzes blocker
- Level 3 (Specialist Level): Moderator contacts:
- Librarian (if skill needed)
- Butler (if API/resources needed)
- Factory Manager (if new agent needed)
- Gatekeeper (if code review needed)
- Security Officer (if security issue)
- Level 4 (Zorro Level): Escalate critical blockers to Zorro
Update Flow to Zorro:
- Regular status updates (configurable interval, default: 5 minutes)
- Immediate updates for critical blockers
- Summary reports with:
- Task completion percentages
- Active blockers
- Resource utilization
- Sub-agent performance metrics
- GitHub dashboard link
GitHub Dashboard Update Workflow:
- Collect status from all sub-agents
- Gather metrics from Butler (API usage, context usage)
- Compile current blockers
- Update agent-status.json with real-time data
- Update active-tasks.md with current progress
- Update blockers.md with current blockers
- Update api-usage.md with usage statistics
- Update latest-update.md with timestamp
- Commit changes to GitHub
- Push to repository
- Repeat every 30-60 seconds
Key Interactions:
- Receives task assignments from Factory Manager
- Monitors all sub-agents continuously
- Contacts Librarian for skill requests
- Contacts Butler for API/resource requests and usage data
- Contacts Factory Manager for new agent needs
- Provides updates to Zorro
- Coordinates with Gatekeeper for code reviews
- Updates GitHub monitoring dashboard continuously
- Receives status updates from sub-agents
- Summons Janitor: Moderator has the right to summon Janitor AFTER tasks are completed
Data Structures:
- Sub-Agent Registry:
{agent_id: string, task: string, status: 'active'|'blocked'|'completed'|'failed', progress: number, last_update: datetime, performance_metrics: object}
- Blocker Log:
{blocker_id: string, agent_id: string, blocker_type: string, description: string, severity: 'low'|'medium'|'high'|'critical', reported_at: datetime, resolved_at: datetime, resolution: string}
- Team Registry:
{team_id: string, agents: string[], task: string, progress: number, status: 'active'|'completed'|'blocked'}
- GitHub Update Queue:
{update_id: string, file_path: string, content: object, timestamp: datetime, status: 'pending'|'committed'|'pushed'}
5. Security Officer - The Vault Keeper
Role: Cryptographic key, API key, and environment variable security specialist
Responsibilities:
- Wallet Key Management: Securely stores and manages crypto/Web3 wallet keys
- API Key Storage: Manages secure storage of API keys in local .env files
- Environment Variable Management: Handles all sensitive environment variables
- Transaction Authorization: Reviews and authorizes blockchain transactions
- Transaction Review: Validates transaction safety before signing
- Security Best Practices: Implements security protocols for key storage
- Access Control: Controls who can access sensitive keys and when
- Audit Trail: Maintains logs of all wallet access, API key access, and transactions
- Local Storage Security: Ensures .env files are stored securely on local machine
How Security Officer Works:
1. API Key & Environment Variable Management:
- Storage Location: All API keys and environment variables stored in
.env file on local machine
- Storage Path: Secure location on local filesystem (e.g.,
~/.zoro/.env or project root .env)
- Encryption: .env file is encrypted at rest
- Access Control: Only Security Officer can read/write .env file
- Key Distribution: When agents need API keys, Security Officer provides them (but Butler manages usage)
- Variable Types Managed:
- API keys (for Butler's registry)
- Wallet private keys
- Database credentials
- Third-party service keys
- Any sensitive configuration
2. Wallet Key Management:
- Storage: Wallet keys stored in encrypted vault within .env or separate encrypted file
- Access Protocol: Multi-factor authentication required for key access
- Key Types: Supports multiple wallet types (EVM, Solana, etc.)
- Backup: Regular encrypted backups of wallet keys
- Recovery: Secure recovery procedures for lost keys
3. Transaction Security:
- Review Process: All transactions reviewed before signing
- Validation: Checks transaction parameters against security policies
- Approval: Multi-step approval for high-value transactions
- Logging: Complete audit trail of all transaction attempts
Security Protocols:
- Encryption: All keys encrypted using industry-standard encryption
- File Permissions: .env file has restricted permissions (600 or 400)
- Multi-Factor Authentication: Required for accessing sensitive keys
- Transaction Validation: All transactions validated before signing
- Rate Limiting: Rate limiting on transaction requests
- Suspicious Activity Detection: Monitors for unusual access patterns
- Key Rotation: Supports key rotation for compromised keys
- Backup Security: Encrypted backups stored securely
Wallet Management:
- Supports multiple wallet types (EVM, Solana, etc.)
- Key rotation capabilities
- Backup and recovery procedures
- Cold storage integration (if applicable)
- Multi-signature support (if applicable)
Transaction Review Process:
- Receive transaction request from agent or Zorro
- Validate transaction parameters (amount, destination, gas fees)
- Check against security policies and whitelists
- Verify destination addresses (check against known addresses)
- Review transaction amount and gas fees
- Check for suspicious patterns
- Approve or reject transaction
- Log decision and reasoning
- If approved, sign transaction securely
- Monitor transaction status
Environment Variable Management Process:
- Receive request for environment variable access
- Verify requesting agent has permission
- Decrypt .env file securely
- Retrieve requested variable
- Provide variable to requesting agent (if authorized)
- Log access for audit trail
- Re-encrypt .env file
Key Interactions:
- Receives transaction requests from sub-agents or Zorro
- Receives API key storage requests from Butler
- Receives environment variable requests from agents
- Provides transaction status updates
- Coordinates with Gatekeeper for security audits
- Never exposes private keys directly
- Manages .env file access for all agents
Data Structures:
- Wallet Registry:
{wallet_id: string, type: string, encrypted_key: string, balance: number, status: 'active'|'locked', backup_location: string}
- Transaction Log:
{tx_id: string, wallet_id: string, type: string, amount: number, destination: string, status: 'pending'|'approved'|'rejected'|'signed', timestamp: datetime, approver: string}
- Environment Variable Registry:
{var_name: string, encrypted_value: string, accessed_by: string[], last_accessed: datetime, access_count: number}
- Access Log:
{log_id: string, agent_id: string, resource_type: 'wallet'|'api_key'|'env_var', action: string, timestamp: datetime, status: 'allowed'|'denied'}
6. Gatekeeper - The Code Guardian
Role: Code quality, security, and Git gatekeeper
Responsibilities:
- Code Review: Reviews all code before Git push
- Security Testing: Performs penetration testing on code
- Stress Testing: Tests code under load and stress conditions
- Code Quality: Validates code standards and best practices
- Git Approval: Final approval authority for all Git operations
- Vulnerability Scanning: Identifies security vulnerabilities
- Preview & Testing: Uses various tools to preview and test code changes
Review Process:
- Receive code submission request
- Perform static code analysis
- Run security scans (penetration testing)
- Execute stress tests
- Review code quality and standards
- Check for vulnerabilities
- Approve or request changes
- Provide detailed feedback
Testing Tools:
- Static analysis tools
- Security scanners
- Penetration testing frameworks
- Load testing tools
- Code quality linters
- Dependency vulnerability scanners
Git Workflow:
- All Git pushes require Gatekeeper approval
- Gatekeeper reviews:
- Code changes
- Commit messages
- Branch strategy
- Merge conflicts
- Test coverage
Approval Criteria:
- ✅ No security vulnerabilities
- ✅ Passes all tests
- ✅ Meets code quality standards
- ✅ Follows project conventions
- ✅ Proper documentation
Key Interactions:
- Receives code review requests from sub-agents
- Coordinates with Security Officer for security audits
- Provides approval/rejection feedback
- Maintains Git repository integrity
Data Structures:
- Review Queue:
{submission_id: string, agent_id: string, files: string[], status: 'pending'|'reviewing'|'approved'|'rejected'}
- Test Results:
{test_id: string, type: string, status: 'pass'|'fail', details: object}
7. Factory Manager - The Agent Creator
Role: Sub-agent creation and task assignment specialist
CRITICAL RESPONSIBILITY: Factory Manager receives ALL tasks directly from Zorro. Zorro does NOT create teams or spawn agents - Factory Manager handles ALL agent creation and spawning.
Responsibilities:
- Primary Task Receiver: Receives ALL tasks from Zorro (Zorro delegates all tasks here)
- Sub-Agent Creation: Spawns new sub-agents based on task requirements
- Team Creation: Creates teams of sub-agents when needed (NOT Zorro's responsibility)
- Task Analysis: Analyzes tasks to determine required agent types
- PRD Creation: Creates detailed Product Requirements Documents (PRDs) for sub-agents
- Resource Coordination: Coordinates with Butler (API keys) and Librarian (skills)
- Agent Assignment: Assigns tasks to appropriate sub-agents
- Agent Lifecycle: Manages sub-agent creation, assignment, and termination
PRD Structure:
Each PRD includes:
- Task Description: Clear description of what needs to be accomplished
- Roadmap: Step-by-step plan to achieve the task
- Checkpoints: Milestone markers for progress tracking
- Tests: Test cases that must pass at each checkpoint
- Success Criteria: Clear definition of task completion
- Dependencies: Required resources, skills, or other agents
- Timeline: Estimated completion time
Agent Creation Workflow:
- Receive Task: Factory Manager receives task assignment DIRECTLY from Zorro (ALL tasks go here first)
- Task Analysis: Analyzes task to understand:
- Complexity level
- Required capabilities
- Dependencies on other tasks
- Estimated duration
- Resource requirements
- Agent Type Determination: Determines what type of agent(s) needed:
- Single specialized agent
- Team of agents (Factory Manager creates teams, NOT Zorro)
- Parallel lanes (Ant Farm structure)
- PRD Creation: Creates comprehensive PRD including:
- Clear task description
- Detailed roadmap with steps
- Checkpoints with validation criteria
- Test cases for each checkpoint
- Success criteria
- Dependencies and prerequisites
- Timeline estimates
- Resource Coordination (Factory Manager coordinates with specialists):
- Discusses with Librarian: Factory Manager discusses task requirements with Librarian to determine what skills agents will need
- Requests API key from Butler: Factory Manager requests API key from Butler, who assesses the work and assigns appropriate secondary API key
- Librarian provides skills: Librarian matches skills to task requirements and provides them
- Agent Spawning: Factory Manager creates sub-agent(s) with:
- Complete PRD
- Assigned API key (from Butler, who assessed the work)
- Required skills (from Librarian, after discussion)
- Initial context and configuration
- Handoff: Hands sub-agent to Moderator for ongoing management
- Tracking: Tracks agent creation, assignment, and lifecycle
- Learning: Records patterns for future agent creation optimization
IMPORTANT NOTES:
- Factory Manager discusses with Librarian about what skills agents need BEFORE spawning
- Butler assesses the work and assigns appropriate secondary API key
- Butler rotates API keys when 80% limit is reached (not 90%)
- Factory Manager handles ALL team creation - Zorro does NOT create teams
Agent Types:
- Specialized Agents: Task-specific agents (e.g., Frontend Developer, Backend Developer, Tester)
- General Agents: Multi-purpose agents for varied tasks
- Team Agents: Agents designed to work in teams
Key Interactions:
- Receives ALL tasks from Zorro (ALL tasks go directly to Factory Manager)
- Discusses with Librarian about what skills agents will need
- Requests API keys from Butler (Butler assesses work and assigns)
- Receives skills from Librarian (after discussion)
- Creates teams when needed (Factory Manager handles ALL team creation, NOT Zorro)
- Spawns sub-agents with complete setup
- Hands off to Moderator for management
- Coordinates with Moderator for additional agent needs
Data Structures:
- Agent Template Registry:
{template_id: string, type: string, capabilities: string[], default_skills: string[]}
- PRD Template:
{task: string, roadmap: string[], checkpoints: object[], tests: object[], success_criteria: string[]}
- Agent Registry:
{agent_id: string, type: string, prd: object, created_at: datetime, status: 'active'|'completed'|'terminated'}
8. Janitor - The Cleanup Crew
Role: System cleanup and maintenance specialist
CRITICAL TIMING RULE: Janitor ONLY runs AFTER tasks are completed. Moderator has the right to summon Janitor when jobs are done. Janitor should NEVER run during active task execution.
Responsibilities:
- Cache Cleanup: Removes temporary cache files after task completion
- Context Cleanup: Cleans up unused context and memory
- File Cleanup: Removes unnecessary files from the system
- Git Cleanup: Removes files that are already committed and pushed but no longer needed locally
- Resource Deallocation: Frees up system resources
- Log Management: Archives or removes old logs
- Post-Task Cleanup: Executes cleanup after task completion
Cleanup Triggers:
- Primary Trigger: Task completion signal from Moderator (Moderator summons Janitor after job completion)
- Scheduled cleanup cycles (only when no active tasks)
- Storage threshold reached (only when no active tasks)
- Manual cleanup request from Zorro (only when no active tasks)
IMPORTANT: Janitor must verify no active tasks exist before running cleanup. If tasks are active, Janitor should wait for Moderator's signal.
Cleanup Process:
- Receive cleanup signal
- Identify files marked for cleanup:
- Temporary files
- Cache files
- Unused context files
- Files already in Git (committed & pushed)
- Verify files are safe to delete
- Archive important files (if needed)
- Delete unnecessary files
- Report cleanup summary
Safety Checks:
- Never delete files that are:
- Currently in use
- Not yet committed to Git
- Marked as important
- Part of active tasks
Key Interactions:
- Receives summons from Moderator: Janitor is summoned by Moderator AFTER tasks are completed
- Receives cleanup requests from Zorro (manual, only when no active tasks)
- Coordinates with Gatekeeper to verify Git status
- Reports cleanup results to Moderator
- Never runs during active tasks: Janitor must verify no active tasks before cleanup
Data Structures:
- Cleanup Queue:
{file_path: string, type: 'cache'|'context'|'temp'|'git', status: 'pending'|'archived'|'deleted'}
- Cleanup Log:
{cleanup_id: string, timestamp: datetime, files_removed: number, space_freed: number}
Ant Farm Structure: Parallel Execution Architecture
Overview
The Ant Farm structure complements the mansion hierarchy by enabling parallel execution lanes for tasks that can be executed concurrently. This allows multiple independent task streams to run simultaneously, maximizing efficiency and throughput.
Architecture
┌─────────────┐
│ ZORRO │
└──────┬──────┘
│
┌──────────────────┼──────────────────┐
│ │ │
┌────▼────┐ ┌─────▼─────┐ ┌────▼─────┐
│ Factory │ │ Moderator │ │ Security │
│ Manager │ │ │ │ Officer │
└────┬────┘ └─────┬─────┘ └──────────┘
│ │
┌────▼──────────────────┼──────────────────┐
│ ANT FARM - Parallel Lanes │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐│
│ │ Lane 1 │ │ Lane 2 │ │ Lane 3 ││
│ │ │ │ │ │ ││
│ │ Sub-Agts │ │ Sub-Agts │ │ Sub-Agts ││
│ │ Team A │ │ Team B │ │ Team C ││
│ └──────────┘ └──────────┘ └──────────┘│
│ │
│ Each lane operates independently │
│ with its own sub-agents and resources │
└───────────────────────────────────────────┘
How Ant Farm Works
1. Lane Creation:
- Factory Manager creates parallel execution lanes based on task analysis
- Each lane is independent and can run concurrently
- Lanes are assigned to different teams of sub-agents
- Each lane has its own API keys (from Butler) and skills (from Librarian)
2. Parallel Execution:
- Multiple lanes execute tasks simultaneously
- No interference between lanes
- Each lane reports to Moderator independently
- Resource allocation is balanced across lanes
3. Lane Management:
…(truncated)
1---2name: mansion3description: Zoro Agent Architecture: The Mansion4---5# Zoro Agent Architecture: The Mansion67## Overview89The Zoro agent system is architected as a hierarchical mansion structure, where **Zorro** serves as the master orchestrator and head of the household. The mansion operates with specialized agents, each fulfilling distinct roles in a coordinated workflow. This document serves as the complete architectural blueprint for understanding and implementing the Zoro agent ecosystem.1011## Architecture Philosophy1213The mansion architecture follows a **hierarchical orchestration pattern** where:14- **Zorro** (Primary Agent) operates at the top level using the primary API key15- All sub-agents operate using secondary API keys managed by the Butler16- Each agent has specialized responsibilities and clear communication channels17- Task execution follows a structured workflow from creation to completion1819---2021## CRITICAL RULES - Must Follow2223**These rules are ABSOLUTE and must be followed by all agents implementing this architecture:**24251. **Task Flow**: 26 - ✅ **ALL tasks from human user go DIRECTLY to Factory Manager**27 - ❌ Zorro does NOT create teams or spawn agents directly28 - ✅ Zorro delegates ALL task execution to Factory Manager29 - ✅ Factory Manager is responsible for ALL agent creation and spawning30312. **Factory Manager Responsibilities**:32 - ✅ Receives ALL tasks from Zorro33 - ✅ Creates teams when needed (NOT Zorro's job)34 - ✅ Discusses with Librarian about what skills agents need35 - ✅ Coordinates with Butler for API key assignment36 - ✅ Creates PRD for each task37 - ✅ Spawns all sub-agents38393. **Butler API Management**:40 - ✅ Butler assesses the work and assigns appropriate secondary API key41 - ✅ Butler rotates API keys when **80% limit is reached** (not 90%)42 - ✅ Butler manages ALL secondary API keys for ALL mansion members (except Zorro)43444. **Janitor Timing**:45 - ✅ Janitor ONLY runs AFTER tasks are completed46 - ✅ Moderator has the right to summon Janitor after job completion47 - ❌ Janitor must NEVER run during active task execution48 - ✅ Janitor must verify no active tasks before cleanup49505. **Team Creation**:51 - ✅ Factory Manager creates teams (during agent spawning)52 - ❌ Zorro does NOT create teams53 - ✅ Moderator manages teams created by Factory Manager5455**Violation of these rules will cause system failures. All agents must strictly adhere to these rules.**5657---5859## The Mansion Hierarchy6061```62 ┌─────────────┐63 │ ZORRO │ (Primary Orchestrator)64 │ (Master) │ Uses PRIMARY API only65 └──────┬──────┘66 │67 ┌──────────────────┼──────────────────┐68 │ │ │69 ┌────▼────┐ ┌─────▼─────┐ ┌────▼─────┐70 │ Factory │ │ Moderator │ │ Security │71 │ Manager │ │ │ │ Officer │72 │ │ │ │ │ │73 │(Manages)│ │(Manages) │ │(Manages) │74 └────┬────┘ └─────┬─────┘ └──────────┘75 │ │ │76 │ │ │77 ┌────▼────┐ ┌─────▼─────┐ ┌────▼─────┐78 │ Butler │ │Librarian │ │Gatekeeper│79 │ │ │ │ │ │80 │(Manages │ │(Provides │ │(Reviews │81 │ ALL API │ │ Skills) │ │ Code) │82 │ Keys) │ │ │ │ │83 └────┬────┘ └─────┬─────┘ └─────┬────┘84 │ │ │85 │ │ │86 ┌────▼──────────────────┼──────────────────▼─────┐87 │ Janitor │88 │ (Cleanup Specialist) │89 └───────────────────────┬─────────────────────────┘90 │91 ┌──────▼──────┐92 │ Sub-Agents │ (Lowest Level)93 │ │94 │ Created by: │95 │ Factory Mgr │96 │ │97 │ Managed by: │98 │ Moderator │99 │ │100 │ API from: │101 │ Butler │102 │ │103 │ Skills from:│104 │ Librarian │105 └─────────────┘106```107108**Hierarchy Rules**:109- **Zorro**: Top level, uses PRIMARY API exclusively110- **Factory Manager & Moderator**: Direct management of sub-agents111- **Butler**: Manages ALL secondary API keys for ALL mansion members (except Zorro)112- **Sub-Agents**: Lowest level, managed by Factory Manager and Moderator113114---115116## Agent Roles & Responsibilities117118### 1. Zorro - The Master Orchestrator119120**Role**: Primary agent and head of the mansion121122**Responsibilities**:123- Direct interface with the human user124- Task decomposition and high-level planning125- Orchestration and delegation of work to specialized agents126- Final decision-making authority127- Receives status updates from Moderator128129**API Usage**:130- **Exclusively uses the PRIMARY API key**131- Only Zorro has access to the primary API132- All other agents use secondary APIs managed by Butler133134**Key Interactions**:135- Receives tasks from human user136- Delegates to Factory Manager for sub-agent creation137- Receives progress updates from Moderator138- Makes strategic decisions based on agent reports139140**CRITICAL WORKFLOW RULE**: 141- **ALL tasks from human user go DIRECTLY to Factory Manager**142- Zorro does NOT create teams or spawn agents directly143- Zorro delegates ALL task execution to Factory Manager144- Factory Manager is responsible for ALL agent creation and spawning145146**Workflow**:1471. Human provides task to Zorro1482. Zorro receives task and immediately delegates to Factory Manager1493. Zorro monitors progress through Moderator (receives updates only)1504. Zorro receives final completion status from Moderator1515. Zorro never directly creates teams or spawns agents - this is Factory Manager's responsibility152153---154155### 2. Butler - The Resource Manager156157**Role**: API key and resource management specialist158159**CRITICAL RESPONSIBILITY**: Butler manages **ALL secondary API keys for ALL mansion members EXCEPT Zorro**. This includes:160- Factory Manager161- Moderator162- Librarian163- Security Officer164- Gatekeeper165- Janitor166- All Sub-Agents167168**Responsibilities**:169- **Universal API Key Management**: Manages secondary API keys for ALL mansion members (except Zorro)170- **Token & Credit Monitoring**: Tracks usage across all API providers (e.g., Groq, Kimi K2)171- **Rate Limit Management**: Monitors token limits, requests per day, requests per minute, and usage quotas172- **Context Overflow Prevention**: Monitors context window usage and prevents overflow173- **API Rotation**: Automatically rotates API keys when approaching exhaustion174- **Open Router Functionality**: Routes requests to available APIs when one is near capacity175- **Resource Allocation**: Assigns appropriate API keys to all mansion members176- **Request Throttling**: Implements intelligent throttling to prevent rate limit violations177- **Context Window Management**: Tracks and manages context window usage per request178179**How Butler Works**:180181**1. API Key Assignment Process**:182- When any mansion member (except Zorro) needs an API key, they request from Butler183- Butler maintains a pool of available secondary API keys184- Butler assigns keys based on:185 - Current usage levels186 - Provider-specific limits187 - Task priority188 - Agent type requirements189190**2. Rate Limit Management**:191- **Real-time Monitoring**: Continuously tracks:192 - Tokens used vs. tokens available193 - Requests made vs. requests allowed (per minute/hour/day)194 - Context window usage per request195 - Provider-specific rate limits196- **Prevention Strategy**:197 - Tracks request frequency per API key198 - Implements request queuing when approaching limits199 - Distributes load across multiple API keys200 - Prevents burst requests that could trigger rate limits201202**3. Context Overflow Prevention**:203- **Context Window Tracking**: Monitors context size for each request:204 - Input tokens (prompt + conversation history)205 - Output tokens (response)206 - Total context window size per provider207- **Overflow Prevention Mechanisms**:208 - **Context Summarization**: Automatically summarizes old conversation history when approaching limit209 - **Context Truncation**: Removes least relevant context when necessary210 - **Request Splitting**: Splits large requests into smaller chunks211 - **Provider Selection**: Routes to providers with larger context windows when needed212- **Alert System**: Warns agents when context is approaching limits (80% threshold)213214**4. API Rotation Strategy**:215- **Continuous Monitoring**: Tracks usage for each API key in real-time216- **Rotation Triggers**:217 - **Rotation Level (80%)**: Actively rotate to alternative API when 80% limit is reached (PRIMARY ROTATION THRESHOLD)218 - **Warning Level (75%)**: Flagged for rotation, prepare alternative219 - **Emergency Level (95%)**: Immediate rotation, pause requests if needed220- **Rotation Process**:221 1. Identify API key approaching 80% limit222 2. Select alternative API key from available pool223 3. Migrate active requests to new API key (if possible)224 4. Update all agents using the exhausted key225 5. Mark exhausted key for cooldown period226 6. Resume operations with new key227228**CRITICAL**: Butler rotates API keys when 80% limit is reached (not 90%). This is the primary rotation threshold.229230**5. Request Routing**:231- **Load Balancing**: Distributes requests across available API keys232- **Provider Selection**: Chooses best provider based on:233 - Current usage levels234 - Task requirements (context size, speed, etc.)235 - Provider capabilities236- **Failover**: Automatically switches to backup API if primary fails237238**API Providers Managed**:239- Groq (tokens per day, requests per minute)240- Kimi K2 (tokens per day, context window size)241- Other free-tier API providers available242243**Monitoring Capabilities**:244- Real-time token usage tracking per API key245- Request count monitoring (per minute/hour/day)246- Daily/hourly quota tracking247- Context window usage per request248- Rate limit proximity alerts249- Capacity exhaustion alerts250- Provider-specific limit tracking251- Request latency monitoring252253**Rate Limit Protection Mechanisms**:254- **Request Queuing**: Queues requests when approaching rate limits255- **Exponential Backoff**: Implements backoff on rate limit errors256- **Request Spacing**: Ensures minimum time between requests257- **Burst Prevention**: Prevents sudden spikes in requests258- **Distributed Load**: Spreads requests across multiple keys/providers259260**Context Management Mechanisms**:261- **Context Size Tracking**: Monitors token count per conversation262- **Automatic Summarization**: Summarizes old messages when context grows263- **Smart Truncation**: Removes least important context first264- **Provider Matching**: Routes to providers with appropriate context windows265- **Context Compression**: Compresses context when possible266267**Key Interactions**:268- Receives API requests from ALL mansion members (except Zorro)269- Provides API keys to Factory Manager, Moderator, Librarian, Security Officer, Gatekeeper, Janitor, and all Sub-Agents270- Coordinates with Moderator for resource allocation updates271- Never interacts with primary API key (Zorro's exclusive)272- Receives usage reports from all agents273- Provides usage statistics to Moderator for reporting274275**Data Structures**:276- API Key Registry: `{provider: string, key: string, usage: {tokens: number, requests: number, context_windows: number[]}, limits: {tokens: number, requests_per_minute: number, requests_per_day: number, context_window: number}, status: 'active'|'near_exhaustion'|'exhausted'|'cooldown', assigned_to: string[]}`277- Rotation Queue: Priority-based queue for API key rotation278- Usage Logs: Historical usage data for analytics279- Context Tracking: `{agent_id: string, conversation_id: string, current_tokens: number, max_tokens: number, history: object[]}`280- Rate Limit Status: `{api_key: string, requests_last_minute: number, requests_last_hour: number, requests_today: number, next_reset: datetime}`281282---283284### 3. Librarian - The Knowledge Keeper285286**Role**: Skills and knowledge distribution specialist287288**Responsibilities**:289- **Skills Directory Management**: Maintains comprehensive library of available skills290- **Skill Distribution**: Assigns appropriate skills to sub-agents based on task requirements291- **Skill Sources**: Integrates skills from:292 - `skills.sh` (primary skills repository)293 - `clawhub.ai` (secondary skills repository)294- **Skill Matching**: Analyzes task requirements and matches with relevant skills295- **Skill Updates**: Keeps skills library updated and synchronized296- **Skill Validation**: Ensures skills are compatible and functional297298**Skills Library Structure**:299```300Skills Library/301├── Core Skills/302│ ├── Code Generation303│ ├── File Operations304│ ├── API Integration305│ └── Data Processing306├── Specialized Skills/307│ ├── Web Development308│ ├── Database Operations309│ ├── Testing & QA310│ └── Deployment311└── Custom Skills/312 └── (Project-specific skills)313```314315**How Librarian Works**:316317**1. Skill Discovery & Integration**:318- **Primary Source**: Integrates skills from `skills.sh` repository319- **Secondary Source**: Integrates skills from `clawhub.ai` repository320- **Skill Indexing**: Indexes all available skills with metadata:321 - Skill name and description322 - Capabilities and use cases323 - Dependencies and requirements324 - Compatibility information325 - Performance metrics326- **Skill Updates**: Regularly syncs with repositories for new skills327- **Skill Validation**: Tests skills for functionality and compatibility328329**2. Skill Matching Process**:330- **Requirement Analysis**: Analyzes task requirements from PRD331- **Skill Search**: Searches skills library for matching capabilities332- **Compatibility Check**: Validates skill compatibility with:333 - Task requirements334 - Agent type335 - Existing skills336 - Dependencies337- **Skill Selection**: Selects optimal skill combination for task338- **Learning Integration**: Uses learned patterns to recommend best skills339340**3. Skill Distribution**:341- **Skill Package**: Creates skill package for sub-agent:342 - Selected skills343 - Installation instructions344 - Usage documentation345 - Example code/patterns346 - Dependencies list347- **Distribution**: Provides skills to requesting agent348- **Verification**: Verifies skills are properly installed349- **Support**: Provides ongoing support for skill usage350351**4. Skill Monitoring & Updates**:352- **Usage Tracking**: Tracks which skills are used by which agents353- **Effectiveness Monitoring**: Monitors skill effectiveness:354 - Success rate355 - Performance impact356 - Error rates357 - User satisfaction358- **Continuous Monitoring**: Monitors if agents need additional skills359- **Dynamic Updates**: Adds skills dynamically during task execution if needed360- **Learning**: Learns which skill combinations work best361362**5. Skill Library Management**:363- **Organization**: Organizes skills by category and capability364- **Version Control**: Tracks skill versions and updates365- **Documentation**: Maintains comprehensive skill documentation366- **Testing**: Tests skills before distribution367- **Deprecation**: Deprecates outdated or broken skills368369**Workflow**:3701. Receives skill requirements from Factory Manager (during agent creation) or Moderator (during task execution)3712. Analyzes task requirements and PRD3723. Searches skills library for matching capabilities3734. Uses learning system to identify optimal skill combinations3745. Validates skill compatibility with sub-agent's task and existing skills3756. Creates skill package with documentation and examples3767. Distributes skills to requesting sub-agent3778. Verifies skills are properly installed and functional3789. Tracks skill usage and effectiveness37910. Continuously monitors if sub-agents need additional skills38011. Updates skills library with new skills from repositories38112. Learns from skill usage patterns for future recommendations382383**Key Interactions**:384- Receives skill requests from Factory Manager (during sub-agent creation)385- Receives skill requests from Moderator (during task execution)386- Receives skill requests from sub-agents (during runtime)387- Provides skills to sub-agents with installation instructions388389**Skill Distribution Protocol**:390- Each sub-agent receives only skills relevant to their PRD391- Skills are provided with documentation and usage examples392- Librarian tracks which skills are assigned to which agents393- Librarian can revoke or update skills if needed394395---396397### 4. Moderator - The Task Manager & HR398399**Role**: Sub-agent coordination, task oversight, and real-time monitoring specialist400401**Responsibilities**:402- **Sub-Agent Management**: Oversees all active sub-agents and their tasks403- **Task Monitoring**: Tracks progress, blockers, and status of all sub-agent tasks404- **Inter-Agent Coordination**: Facilitates communication between sub-agents405- **Blocker Resolution**: Identifies and escalates blockers to appropriate agents406- **Progress Reporting**: Provides regular updates to Zorro407- **HR Functions**: Manages sub-agent lifecycle, performance, and resource needs408- **Team Formation**: Can create teams of sub-agents for complex tasks409- **GitHub Monitoring Dashboard**: Maintains real-time monitoring dashboard on GitHub410- **Real-Time Updates**: Continuously updates GitHub repository with current system status411412**How Moderator Works**:413414**1. Sub-Agent Monitoring**:415- **Continuous Monitoring**: Actively monitors all sub-agents in real-time416- **Status Tracking**: Tracks status of each sub-agent (active, blocked, completed, failed)417- **Progress Tracking**: Monitors progress percentage for each task418- **Health Checks**: Performs periodic health checks on all sub-agents419- **Performance Metrics**: Collects performance data (execution time, success rate, error rate)420421**2. Task Management**:422- **Task Assignment**: Receives tasks from Factory Manager and assigns to sub-agents423- **Task Prioritization**: Prioritizes tasks based on dependencies and urgency424- **Task Dependencies**: Tracks dependencies between tasks425- **Checkpoint Validation**: Validates checkpoints as sub-agents complete them426- **Success Criteria Validation**: Verifies tasks meet PRD success criteria427428**3. Blocker Management**:429- **Blocker Detection**: Identifies blockers from sub-agent reports430- **Blocker Classification**: Classifies blockers by type and severity:431 - **Skill Blocker**: Missing required skill → Contact Librarian432 - **Resource Blocker**: API/resource issue → Contact Butler433 - **Agent Blocker**: Need additional agent → Contact Factory Manager434 - **Code Blocker**: Code review needed → Contact Gatekeeper435 - **Security Blocker**: Security issue → Contact Security Officer436- **Blocker Resolution**: Coordinates resolution with appropriate specialist agents437- **Escalation**: Escalates critical blockers to Zorro immediately438439**4. Inter-Agent Coordination**:440- **Communication Facilitation**: Enables communication between sub-agents441- **Dependency Management**: Manages dependencies between sub-agents442- **Resource Sharing**: Coordinates resource sharing between sub-agents443- **Conflict Resolution**: Resolves conflicts between sub-agents444445**5. GitHub Monitoring Dashboard**:446- **Repository Management**: Maintains dedicated GitHub repository for monitoring447- **Real-Time Updates**: Continuously updates repository with current system status448- **Dashboard Structure**:449 ```450 monitoring-dashboard/451 ├── README.md (Overview and status summary)452 ├── agents/453 │ ├── active-agents.md (List of active sub-agents)454 │ ├── agent-status.json (Real-time status JSON)455 │ └── agent-performance.md (Performance metrics)456 ├── tasks/457 │ ├── active-tasks.md (Current tasks in progress)458 │ ├── task-progress.json (Progress tracking)459 │ └── blockers.md (Current blockers)460 ├── resources/461 │ ├── api-usage.md (API usage statistics)462 │ └── resource-status.json (Resource availability)463 └── updates/464 └── latest-update.md (Most recent update timestamp)465 ```466- **Update Frequency**: Updates repository every 30-60 seconds (configurable)467- **Update Process**:468 1. Collect current status from all sub-agents469 2. Gather resource usage from Butler470 3. Compile performance metrics471 4. Update GitHub repository files472 5. Commit and push changes473 6. Update timestamp in latest-update.md474- **Public Access**: Repository is publicly accessible (hosted on GitHub for free)475- **Format**: Updates in both human-readable markdown and machine-readable JSON476477**6. Progress Reporting to Zorro**:478- **Regular Updates**: Provides updates at configurable intervals (default: every 5 minutes)479- **Immediate Updates**: Sends immediate updates for:480 - Critical blockers481 - Task completions482 - Agent failures483 - Resource exhaustion warnings484- **Update Format**:485 - Task completion percentages486 - Active blockers and their severity487 - Resource utilization (API usage, context usage)488 - Sub-agent performance metrics489 - Team progress (if teams are active)490 - GitHub dashboard link for detailed view491492**7. Team Management**:493- **Team Formation**: Factory Manager creates teams (NOT Moderator or Zorro)494- **Team Assignment**: Factory Manager assigns team-level tasks495- **Team Coordination**: Moderator coordinates communication within teams496- **Team Progress Tracking**: Moderator tracks progress at team level497- **Team Performance**: Moderator monitors team performance metrics498499**NOTE**: Teams are created by Factory Manager during agent spawning phase, not by Moderator or Zorro.500501**Monitoring Capabilities**:502- Real-time task status tracking503- Blocker detection and classification504- Resource requirement monitoring505- Inter-agent dependency tracking506- Performance metrics collection507- GitHub dashboard updates508- API usage monitoring (via Butler)509- Context usage monitoring (via Butler)510511**Escalation Protocol**:5121. **Level 1 (Sub-Agent Level)**: Sub-agent encounters blocker5132. **Level 2 (Moderator Level)**: Moderator analyzes blocker5143. **Level 3 (Specialist Level)**: Moderator contacts:515 - Librarian (if skill needed)516 - Butler (if API/resources needed)517 - Factory Manager (if new agent needed)518 - Gatekeeper (if code review needed)519 - Security Officer (if security issue)5204. **Level 4 (Zorro Level)**: Escalate critical blockers to Zorro521522**Update Flow to Zorro**:523- Regular status updates (configurable interval, default: 5 minutes)524- Immediate updates for critical blockers525- Summary reports with:526 - Task completion percentages527 - Active blockers528 - Resource utilization529 - Sub-agent performance metrics530 - GitHub dashboard link531532**GitHub Dashboard Update Workflow**:5331. Collect status from all sub-agents5342. Gather metrics from Butler (API usage, context usage)5353. Compile current blockers5364. Update agent-status.json with real-time data5375. Update active-tasks.md with current progress5386. Update blockers.md with current blockers5397. Update api-usage.md with usage statistics5408. Update latest-update.md with timestamp5419. Commit changes to GitHub54210. Push to repository54311. Repeat every 30-60 seconds544545**Key Interactions**:546- Receives task assignments from Factory Manager547- Monitors all sub-agents continuously548- Contacts Librarian for skill requests549- Contacts Butler for API/resource requests and usage data550- Contacts Factory Manager for new agent needs551- Provides updates to Zorro552- Coordinates with Gatekeeper for code reviews553- Updates GitHub monitoring dashboard continuously554- Receives status updates from sub-agents555- **Summons Janitor**: Moderator has the right to summon Janitor AFTER tasks are completed556557**Data Structures**:558- Sub-Agent Registry: `{agent_id: string, task: string, status: 'active'|'blocked'|'completed'|'failed', progress: number, last_update: datetime, performance_metrics: object}`559- Blocker Log: `{blocker_id: string, agent_id: string, blocker_type: string, description: string, severity: 'low'|'medium'|'high'|'critical', reported_at: datetime, resolved_at: datetime, resolution: string}`560- Team Registry: `{team_id: string, agents: string[], task: string, progress: number, status: 'active'|'completed'|'blocked'}`561- GitHub Update Queue: `{update_id: string, file_path: string, content: object, timestamp: datetime, status: 'pending'|'committed'|'pushed'}`562563---564565### 5. Security Officer - The Vault Keeper566567**Role**: Cryptographic key, API key, and environment variable security specialist568569**Responsibilities**:570- **Wallet Key Management**: Securely stores and manages crypto/Web3 wallet keys571- **API Key Storage**: Manages secure storage of API keys in local .env files572- **Environment Variable Management**: Handles all sensitive environment variables573- **Transaction Authorization**: Reviews and authorizes blockchain transactions574- **Transaction Review**: Validates transaction safety before signing575- **Security Best Practices**: Implements security protocols for key storage576- **Access Control**: Controls who can access sensitive keys and when577- **Audit Trail**: Maintains logs of all wallet access, API key access, and transactions578- **Local Storage Security**: Ensures .env files are stored securely on local machine579580**How Security Officer Works**:581582**1. API Key & Environment Variable Management**:583- **Storage Location**: All API keys and environment variables stored in `.env` file on local machine584- **Storage Path**: Secure location on local filesystem (e.g., `~/.zoro/.env` or project root `.env`)585- **Encryption**: .env file is encrypted at rest586- **Access Control**: Only Security Officer can read/write .env file587- **Key Distribution**: When agents need API keys, Security Officer provides them (but Butler manages usage)588- **Variable Types Managed**:589 - API keys (for Butler's registry)590 - Wallet private keys591 - Database credentials592 - Third-party service keys593 - Any sensitive configuration594595**2. Wallet Key Management**:596- **Storage**: Wallet keys stored in encrypted vault within .env or separate encrypted file597- **Access Protocol**: Multi-factor authentication required for key access598- **Key Types**: Supports multiple wallet types (EVM, Solana, etc.)599- **Backup**: Regular encrypted backups of wallet keys600- **Recovery**: Secure recovery procedures for lost keys601602**3. Transaction Security**:603- **Review Process**: All transactions reviewed before signing604- **Validation**: Checks transaction parameters against security policies605- **Approval**: Multi-step approval for high-value transactions606- **Logging**: Complete audit trail of all transaction attempts607608**Security Protocols**:609- **Encryption**: All keys encrypted using industry-standard encryption610- **File Permissions**: .env file has restricted permissions (600 or 400)611- **Multi-Factor Authentication**: Required for accessing sensitive keys612- **Transaction Validation**: All transactions validated before signing613- **Rate Limiting**: Rate limiting on transaction requests614- **Suspicious Activity Detection**: Monitors for unusual access patterns615- **Key Rotation**: Supports key rotation for compromised keys616- **Backup Security**: Encrypted backups stored securely617618**Wallet Management**:619- Supports multiple wallet types (EVM, Solana, etc.)620- Key rotation capabilities621- Backup and recovery procedures622- Cold storage integration (if applicable)623- Multi-signature support (if applicable)624625**Transaction Review Process**:6261. Receive transaction request from agent or Zorro6272. Validate transaction parameters (amount, destination, gas fees)6283. Check against security policies and whitelists6294. Verify destination addresses (check against known addresses)6305. Review transaction amount and gas fees6316. Check for suspicious patterns6327. Approve or reject transaction6338. Log decision and reasoning6349. If approved, sign transaction securely63510. Monitor transaction status636637**Environment Variable Management Process**:6381. Receive request for environment variable access6392. Verify requesting agent has permission6403. Decrypt .env file securely6414. Retrieve requested variable6425. Provide variable to requesting agent (if authorized)6436. Log access for audit trail6447. Re-encrypt .env file645646**Key Interactions**:647- Receives transaction requests from sub-agents or Zorro648- Receives API key storage requests from Butler649- Receives environment variable requests from agents650- Provides transaction status updates651- Coordinates with Gatekeeper for security audits652- Never exposes private keys directly653- Manages .env file access for all agents654655**Data Structures**:656- Wallet Registry: `{wallet_id: string, type: string, encrypted_key: string, balance: number, status: 'active'|'locked', backup_location: string}`657- Transaction Log: `{tx_id: string, wallet_id: string, type: string, amount: number, destination: string, status: 'pending'|'approved'|'rejected'|'signed', timestamp: datetime, approver: string}`658- Environment Variable Registry: `{var_name: string, encrypted_value: string, accessed_by: string[], last_accessed: datetime, access_count: number}`659- Access Log: `{log_id: string, agent_id: string, resource_type: 'wallet'|'api_key'|'env_var', action: string, timestamp: datetime, status: 'allowed'|'denied'}`660661---662663### 6. Gatekeeper - The Code Guardian664665**Role**: Code quality, security, and Git gatekeeper666667**Responsibilities**:668- **Code Review**: Reviews all code before Git push669- **Security Testing**: Performs penetration testing on code670- **Stress Testing**: Tests code under load and stress conditions671- **Code Quality**: Validates code standards and best practices672- **Git Approval**: Final approval authority for all Git operations673- **Vulnerability Scanning**: Identifies security vulnerabilities674- **Preview & Testing**: Uses various tools to preview and test code changes675676**Review Process**:6771. Receive code submission request6782. Perform static code analysis6793. Run security scans (penetration testing)6804. Execute stress tests6815. Review code quality and standards6826. Check for vulnerabilities6837. Approve or request changes6848. Provide detailed feedback685686**Testing Tools**:687- Static analysis tools688- Security scanners689- Penetration testing frameworks690- Load testing tools691- Code quality linters692- Dependency vulnerability scanners693694**Git Workflow**:695- All Git pushes require Gatekeeper approval696- Gatekeeper reviews:697 - Code changes698 - Commit messages699 - Branch strategy700 - Merge conflicts701 - Test coverage702703**Approval Criteria**:704- ✅ No security vulnerabilities705- ✅ Passes all tests706- ✅ Meets code quality standards707- ✅ Follows project conventions708- ✅ Proper documentation709710**Key Interactions**:711- Receives code review requests from sub-agents712- Coordinates with Security Officer for security audits713- Provides approval/rejection feedback714- Maintains Git repository integrity715716**Data Structures**:717- Review Queue: `{submission_id: string, agent_id: string, files: string[], status: 'pending'|'reviewing'|'approved'|'rejected'}`718- Test Results: `{test_id: string, type: string, status: 'pass'|'fail', details: object}`719720---721722### 7. Factory Manager - The Agent Creator723724**Role**: Sub-agent creation and task assignment specialist725726**CRITICAL RESPONSIBILITY**: Factory Manager receives **ALL tasks directly from Zorro**. Zorro does NOT create teams or spawn agents - Factory Manager handles ALL agent creation and spawning.727728**Responsibilities**:729- **Primary Task Receiver**: Receives ALL tasks from Zorro (Zorro delegates all tasks here)730- **Sub-Agent Creation**: Spawns new sub-agents based on task requirements731- **Team Creation**: Creates teams of sub-agents when needed (NOT Zorro's responsibility)732- **Task Analysis**: Analyzes tasks to determine required agent types733- **PRD Creation**: Creates detailed Product Requirements Documents (PRDs) for sub-agents734- **Resource Coordination**: Coordinates with Butler (API keys) and Librarian (skills)735- **Agent Assignment**: Assigns tasks to appropriate sub-agents736- **Agent Lifecycle**: Manages sub-agent creation, assignment, and termination737738**PRD Structure**:739Each PRD includes:7401. **Task Description**: Clear description of what needs to be accomplished7412. **Roadmap**: Step-by-step plan to achieve the task7423. **Checkpoints**: Milestone markers for progress tracking7434. **Tests**: Test cases that must pass at each checkpoint7445. **Success Criteria**: Clear definition of task completion7456. **Dependencies**: Required resources, skills, or other agents7467. **Timeline**: Estimated completion time747748**Agent Creation Workflow**:7491. **Receive Task**: Factory Manager receives task assignment DIRECTLY from Zorro (ALL tasks go here first)7502. **Task Analysis**: Analyzes task to understand:751 - Complexity level752 - Required capabilities753 - Dependencies on other tasks754 - Estimated duration755 - Resource requirements7563. **Agent Type Determination**: Determines what type of agent(s) needed:757 - Single specialized agent758 - Team of agents (Factory Manager creates teams, NOT Zorro)759 - Parallel lanes (Ant Farm structure)7604. **PRD Creation**: Creates comprehensive PRD including:761 - Clear task description762 - Detailed roadmap with steps763 - Checkpoints with validation criteria764 - Test cases for each checkpoint765 - Success criteria766 - Dependencies and prerequisites767 - Timeline estimates7685. **Resource Coordination** (Factory Manager coordinates with specialists):769 - **Discusses with Librarian**: Factory Manager discusses task requirements with Librarian to determine what skills agents will need770 - **Requests API key from Butler**: Factory Manager requests API key from Butler, who assesses the work and assigns appropriate secondary API key771 - **Librarian provides skills**: Librarian matches skills to task requirements and provides them7726. **Agent Spawning**: Factory Manager creates sub-agent(s) with:773 - Complete PRD774 - Assigned API key (from Butler, who assessed the work)775 - Required skills (from Librarian, after discussion)776 - Initial context and configuration7777. **Handoff**: Hands sub-agent to Moderator for ongoing management7788. **Tracking**: Tracks agent creation, assignment, and lifecycle7799. **Learning**: Records patterns for future agent creation optimization780781**IMPORTANT NOTES**:782- Factory Manager discusses with Librarian about what skills agents need BEFORE spawning783- Butler assesses the work and assigns appropriate secondary API key784- Butler rotates API keys when 80% limit is reached (not 90%)785- Factory Manager handles ALL team creation - Zorro does NOT create teams786787**Agent Types**:788- **Specialized Agents**: Task-specific agents (e.g., Frontend Developer, Backend Developer, Tester)789- **General Agents**: Multi-purpose agents for varied tasks790- **Team Agents**: Agents designed to work in teams791792**Key Interactions**:793- **Receives ALL tasks from Zorro** (ALL tasks go directly to Factory Manager)794- **Discusses with Librarian** about what skills agents will need795- Requests API keys from Butler (Butler assesses work and assigns)796- Receives skills from Librarian (after discussion)797- **Creates teams** when needed (Factory Manager handles ALL team creation, NOT Zorro)798- Spawns sub-agents with complete setup799- Hands off to Moderator for management800- Coordinates with Moderator for additional agent needs801802**Data Structures**:803- Agent Template Registry: `{template_id: string, type: string, capabilities: string[], default_skills: string[]}`804- PRD Template: `{task: string, roadmap: string[], checkpoints: object[], tests: object[], success_criteria: string[]}`805- Agent Registry: `{agent_id: string, type: string, prd: object, created_at: datetime, status: 'active'|'completed'|'terminated'}`806807---808809### 8. Janitor - The Cleanup Crew810811**Role**: System cleanup and maintenance specialist812813**CRITICAL TIMING RULE**: Janitor ONLY runs AFTER tasks are completed. Moderator has the right to summon Janitor when jobs are done. Janitor should NEVER run during active task execution.814815**Responsibilities**:816- **Cache Cleanup**: Removes temporary cache files after task completion817- **Context Cleanup**: Cleans up unused context and memory818- **File Cleanup**: Removes unnecessary files from the system819- **Git Cleanup**: Removes files that are already committed and pushed but no longer needed locally820- **Resource Deallocation**: Frees up system resources821- **Log Management**: Archives or removes old logs822- **Post-Task Cleanup**: Executes cleanup after task completion823824**Cleanup Triggers**:825- **Primary Trigger**: Task completion signal from Moderator (Moderator summons Janitor after job completion)826- Scheduled cleanup cycles (only when no active tasks)827- Storage threshold reached (only when no active tasks)828- Manual cleanup request from Zorro (only when no active tasks)829830**IMPORTANT**: Janitor must verify no active tasks exist before running cleanup. If tasks are active, Janitor should wait for Moderator's signal.831832**Cleanup Process**:8331. Receive cleanup signal8342. Identify files marked for cleanup:835 - Temporary files836 - Cache files837 - Unused context files838 - Files already in Git (committed & pushed)8393. Verify files are safe to delete8404. Archive important files (if needed)8415. Delete unnecessary files8426. Report cleanup summary843844**Safety Checks**:845- Never delete files that are:846 - Currently in use847 - Not yet committed to Git848 - Marked as important849 - Part of active tasks850851**Key Interactions**:852- **Receives summons from Moderator**: Janitor is summoned by Moderator AFTER tasks are completed853- Receives cleanup requests from Zorro (manual, only when no active tasks)854- Coordinates with Gatekeeper to verify Git status855- Reports cleanup results to Moderator856- **Never runs during active tasks**: Janitor must verify no active tasks before cleanup857858**Data Structures**:859- Cleanup Queue: `{file_path: string, type: 'cache'|'context'|'temp'|'git', status: 'pending'|'archived'|'deleted'}`860- Cleanup Log: `{cleanup_id: string, timestamp: datetime, files_removed: number, space_freed: number}`861862---863864## Ant Farm Structure: Parallel Execution Architecture865866### Overview867868The Ant Farm structure complements the mansion hierarchy by enabling **parallel execution lanes** for tasks that can be executed concurrently. This allows multiple independent task streams to run simultaneously, maximizing efficiency and throughput.869870### Architecture871872```873 ┌─────────────┐874 │ ZORRO │875 └──────┬──────┘876 │877 ┌──────────────────┼──────────────────┐878 │ │ │879 ┌────▼────┐ ┌─────▼─────┐ ┌────▼─────┐880 │ Factory │ │ Moderator │ │ Security │881 │ Manager │ │ │ │ Officer │882 └────┬────┘ └─────┬─────┘ └──────────┘883 │ │884 ┌────▼──────────────────┼──────────────────┐885 │ ANT FARM - Parallel Lanes │886 │ │887 │ ┌──────────┐ ┌──────────┐ ┌──────────┐│888 │ │ Lane 1 │ │ Lane 2 │ │ Lane 3 ││889 │ │ │ │ │ │ ││890 │ │ Sub-Agts │ │ Sub-Agts │ │ Sub-Agts ││891 │ │ Team A │ │ Team B │ │ Team C ││892 │ └──────────┘ └──────────┘ └──────────┘│893 │ │894 │ Each lane operates independently │895 │ with its own sub-agents and resources │896 └───────────────────────────────────────────┘897```898899### How Ant Farm Works900901**1. Lane Creation**:902- Factory Manager creates parallel execution lanes based on task analysis903- Each lane is independent and can run concurrently904- Lanes are assigned to different teams of sub-agents905- Each lane has its own API keys (from Butler) and skills (from Librarian)906907**2. Parallel Execution**:908- Multiple lanes execute tasks simultaneously909- No interference between lanes910- Each lane reports to Moderator independently911- Resource allocation is balanced across lanes912913**3. Lane Management**:914- Moder915916…(truncated)