mvp-factory-openhands/openhands-subagents-doc.md

9.3 KiB

Code Efficiency & Sub-Agents Guide - Phase 3

Purpose: Optimize code efficiency, reduce API costs, and leverage OpenHands sub-agents for Phase 3 autonomous build testing.


🤖 OpenHands Sub-Agents

What Are Sub-Agents?

Sub-agents are specialized AI agents within OpenHands that handle specific tasks:

  • File Editor - Create, edit, view files
  • Bash Runner - Execute shell commands
  • Search Agent - Find files, code patterns
  • Code Analyzer - Review code structure

Benefits for Phase 3

  • Targeted Actions - Each sub-agent is optimized for specific tasks
  • Cost Efficiency - More focused tasks = fewer tokens
  • Faster Execution - Specialized agents work quicker
  • Better Results - Right tool for the right job

Using Sub-Agents in Phase 3

1. File Creation & Editing

Task: "Create a package.json for Node.js project"
→ Uses: File Editor sub-agent
Result: Optimized package.json with correct dependencies

2. Build Script Execution

Task: "Run npm install && npm run build"
→ Uses: Bash Runner sub-agent
Result: Executed commands with exit codes

3. Code Review & Analysis

Task: "Analyze build errors in /workspace/project"
→ Uses: Code Analyzer sub-agent
Result: Identified syntax errors, missing dependencies

4. Error Diagnosis

Task: "Find all TypeScript errors in the project"
→ Uses: Search Agent + Code Analyzer
Result: List of files with errors + solutions

💰 Reducing API Usage Costs

1. Efficient Task Formulation

Bad (High Cost):

"Build the project, test it, fix any errors, optimize performance,
and make sure everything works perfectly"

Good (Low Cost):

Task: "Build project at /workspace/my-project"
Follow-up: "Fix npm install errors"
Follow-up: "Resolve TypeScript compilation errors"

Why: Smaller, specific tasks = fewer tokens = lower cost

2. Use Structured Commands

Instead of:

"Please look at my code and see if there are any issues"

Use:

Task: "Search for console.log statements in /workspace/project/src"

3. Leverage File Editor for Batch Operations

Efficient Pattern:

1. Task: "Create /workspace/project/test.js with basic tests"
2. Task: "Edit /workspace/project/index.js to import test.js"
3. Task: "Run npm test"

4. Cache & Reuse Context

Strategy:

  • Use same workspace for multiple builds
  • Keep dependencies installed
  • Reuse configuration files

⏱️ Reducing Execution Time

1. Parallel Sub-Agent Execution

OpenHands can run multiple sub-agents concurrently:

Task: [
  "Install npm dependencies",
  "Check TypeScript configuration",
  "Verify package.json scripts"
]
→ Runs in parallel = 3x faster

2. Incremental Builds

Instead of full rebuild:

Task: "Build only changed files"
→ Checks git diff
→ Rebuilds modified components
→ Saves time on large projects

3. Smart Dependency Caching

# Cache node_modules
Task: "Copy cached node_modules from /workspace/cache to /workspace/project"

# Skip npm install if cached
Task: "Check if node_modules exists, if yes skip npm install"

4. Pre-configured Build Environments

Task: "Use pre-configured Docker build environment"
→ Skip environment setup
→ Start build immediately

🔧 Best Practices for Phase 3

1. Build Task Optimization

Template for Build Tasks:

Task: "Build project: /workspace/{project_name}
Commands:
  1. cd /workspace/{project_name}
  2. npm install  # Only if node_modules missing
  3. npm run build  # Or build command from package.json
  4. Report exit code and any errors"

2. Error Handling Pattern

Standard Error Response:

{
  "success": false,
  "exit_code": 1,
  "errors": [
    {
      "file": "src/index.ts",
      "line": 15,
      "error": "Type 'string' is not assignable to type 'number'"
    }
  ],
  "suggestions": [
    "Fix type annotation on line 15",
    "Convert string to number or update type definition"
  ]
}

3. Retry-Friendly Tasks

Each task should be:

  • Idempotent - Can run multiple times safely
  • Self-contained - Includes context
  • Actionable - Clear next steps
  • Specific - Not vague or multi-part

Avoid:

"Fix the build issues"

Prefer:

Task: "Fix TypeScript error: Type 'string' is not assignable to type 'number' in src/index.ts:15
Solution: Add type conversion: const num = parseInt(str)"

4. Progress Tracking

For Long Builds:

Progress: "Building project... (1/4 steps: npm install)"
Progress: "Building project... (2/4 steps: TypeScript compilation)"
Progress: "Building project... (3/4 steps: Webpack bundling)"
Progress: "Build completed successfully"

📊 Cost Optimization Strategies

1. Token Budget Management

Per Retry Budget:

  • 1st Attempt: 500 tokens (basic task)
  • 2nd Attempt: 750 tokens (with error context)
  • 3rd Attempt: 1000 tokens (detailed debugging)

Implementation:

// In n8n Code node
const retryCount = $workflow.staticData.retry_count || 0;
const tokenLimit = 500 + (retryCount * 250); // 500, 750, 1000

return {
  task: `Build project with ${tokenLimit} token budget`,
  retry_count: retryCount
};

2. Smart Error Collection

Collect Only Relevant Errors:

// Extract only build-blocking errors
const errors = buildOutput.stderr
  .split('\n')
  .filter(line => line.includes('error'))
  .slice(0, 5) // Limit to 5 errors
  .join('\n');

3. Cached Dependencies

Reduce Install Time:

# Check cache first
if [ -d "/workspace/cache/node_modules" ]; then
  cp -r /workspace/cache/node_modules /workspace/project/
  echo "Used cached dependencies"
else
  npm install
  cp -r node_modules /workspace/cache/
fi

4. Selective Testing

For Large Projects:

Task: "Run tests only for modified files (git diff --name-only)"
→ Tests: {list of changed files}
→ Time saved: 90%

🚀 Sub-Agent Usage Examples

Example 1: Quick Build Test

Task: "Test build in /workspace/project
Steps:
  1. Check if package.json exists
  2. Run npm install (if needed)
  3. Run npm run build
  4. Verify build/ directory created
  5. Report: success/failure + exit code"

Example 2: Error Diagnosis

Task: "Diagnose build failure in /workspace/project
Steps:
  1. Read last 50 lines of build output
  2. Identify error type (TS, Webpack, Runtime)
  3. Find source file causing error
  4. Suggest specific fix
  5. Return actionable error report"

Example 3: Code Optimization

Task: "Optimize build performance in /workspace/project
Steps:
  1. Check bundle size (webpack-bundle-analyzer)
  2. Identify large dependencies
  3. Suggest tree-shaking improvements
  4. Propose code splitting strategy"

📈 Phase 3 Implementation Tips

1. Task Granularity

Fine-grained tasks (Recommended):

const tasks = [
  "Install dependencies",
  "Compile TypeScript",
  "Bundle with Webpack",
  "Run unit tests",
  "Generate build report"
];

Instead of one large task:

const task = "Build and test the entire project"

2. State Persistence

Use n8n staticData:

$workflow.staticData = $workflow.staticData || {};
$workflow.staticData.build_state = {
  stage: "installing",
  completed_steps: [],
  errors: []
};

3. Resource Limits

Per Task Limits:

  • Timeout: 300 seconds max
  • Token Budget: 1000 tokens max
  • Retries: 3 attempts max
  • Concurrency: 1 task at a time

4. Monitoring

Track Performance:

const startTime = Date.now();
await runBuildTask();
const duration = Date.now() - startTime;

return {
  success: true,
  duration_ms: duration,
  cost_estimate: calculateCost(tokens_used)
};

🎯 Phase 3 Success Metrics

Performance Targets

  • Build Time: < 60 seconds (simple project)
  • Error Detection: < 10 seconds
  • Retry Success Rate: > 70%
  • API Cost: < $0.10 per build
  • Token Usage: < 3000 tokens per workflow

Quality Targets

  • Error Accuracy: 95%+ (correctly identify real issues)
  • False Positives: < 5%
  • Build Success Rate: 90%+ (after retries)
  • Documentation: All errors documented with solutions

🔍 Troubleshooting Sub-Agents

Common Issues & Solutions

Issue: Sub-agent timeout Solution: Break task into smaller pieces

Issue: Token limit exceeded Solution: Reduce task scope, use more specific commands

Issue: Build hangs Solution: Add timeout wrapper, kill long-running processes

Issue: Errors not captured Solution: Use structured error collection, check exit codes


📚 Reference Commands

Testing Sub-Agent Efficiency

# Test single sub-agent
Task: "Create file /workspace/test.txt with 'Hello'"

# Test parallel execution
Task: [
  "Create /workspace/file1.txt",
  "Create /workspace/file2.txt",
  "List /workspace directory"
]

Monitoring API Usage

// Track tokens per task
const tokenCount = estimateTokens(task);
if (tokenCount > 1000) {
  console.warn(`High token usage: ${tokenCount}`);
}

Caching Strategy

# Cache directory structure
/cache/
  /node_modules/
  /dist/
  /test-results/

Code Efficiency Guide - Last Updated: 2025-12-02 Optimized for Phase 3 Autonomous Build Testing