OpenWriterControle/.opencode/command/openagents/new-agents/create-agent.md
Darren Hinde c8f7103cb6
refactor(evals): consolidate documentation and enhance test infrastructure (#56)
* feat(agents): implement category-based agent organization system

- Organize agents into domain categories (core, development, content, data, product, learning)
- Move 10 agents to category subdirectories with proper git rename tracking
- Update 13 subagents with category and type metadata in frontmatter
- Add category metadata files (0-category.json) documenting common patterns
- Implement local registry fallback in install script for offline development
- Add comprehensive validation suite with 15 automated tests (100% pass rate)
- Enhance registry validation with duplicate ID and consistency checks
- Update eval framework with intelligent path resolution (backward compatible)
- Archive legacy eval structure to _archive/ for reference
- Update all documentation to reflect category-based structure
- Bump version to 0.5.0 with accurate CHANGELOG

Technical Details:
- 23 agents organized (10 category agents, 13 subagents)
- 6 category directories created
- Path resolution supports both agent IDs and category paths
- Registry schema updated to v2.0.0
- 159 files changed, 872 insertions(+), 10738 deletions(-)

BREAKING CHANGE: Agent file paths now use category structure. Update references from .opencode/agent/openagent.md to .opencode/agent/core/openagent.md. Eval framework maintains backward compatibility via path resolution.

* refactor(evals): consolidate documentation and enhance test infrastructure

- Remove temporary project tracking files (PHASE_5_COMPLETE, PROJECT_COMPLETE, etc.)
- Consolidate evaluation framework docs into main README
- Enhance test execution with improved logging and multi-prompt support
- Move system-builder from core to meta category
- Add comprehensive test suites for openagent with organized structure
- Create evaluation test structure for all subagents
- Clean up archived workflows and redundant documentation
- Update registry to reflect new agent organization
- Add shared test templates and golden test patterns

* feat(ci): add manual trigger support for bot-created PRs in validate-registry workflow

- Add pr_number input to workflow_dispatch for manually triggering validation
- Fetch PR details dynamically when triggered manually
- Support both automatic (PR event) and manual (workflow_dispatch) triggers
- Enable validation of bot-created PRs like automated version bumps
- Update branch detection and push logic to handle both trigger types
- Add documentation explaining how to manually trigger for bot PRs

* feat(evals): add explicit context file validation to test framework

- Add expectedContextFiles field to test YAML schema for explicit context file specification
- Enhance context-loading-evaluator to support both auto-detect and explicit validation modes
- Update documentation with comprehensive guide and examples
- Clean up archived legacy test structure (90+ old test files)
- Add new example tests demonstrating explicit context validation
- Backward compatible with existing tests

* feat(evals): add multi-agent logging system and performance optimizations

Implement comprehensive multi-agent logging and performance improvements for the eval framework.

Task 01: Multi-Agent Logging System
- Add complete hierarchical logging module (evals/framework/src/logging/)
  - SessionTracker: tracks parent-child delegation hierarchies
  - MultiAgentLogger: pretty-prints logs with visual indentation
  - Formatters: box characters and emoji formatting
  - 37 passing unit tests (session-tracker, logger, integration)
- Integrate with SDK event stream handler
  - Hook into session.created, message.updated, message.part.updated events
  - Real-time child session detection via timestamp heuristics
  - Message deduplication for cleaner output
- Enable in debug mode only (<1% performance overhead)
- Add demo script and comprehensive documentation

Task 02: Performance Optimizations
- Reduce grace period from 5s to 2s (67% reduction, 10-20% faster tests)
- Add PerformanceMetricsEvaluator for bottleneck identification
  - Collects tool latencies, inference time, idle time
  - Provides full performance visibility
- Update smoke test to validate delegation (core feature)
  - Replace simple read test with multi-agent delegation test
  - Tests both parent and child agent functionality
  - Validates multi-agent logging system

Results:
- 37 unit tests passing
- Smoke test passing (95/100 score)
- Clean hierarchical logging output
- 10-20% faster test execution
- Full multi-agent visibility

Files changed: 16 files, +2678 lines
Time saved: ~6-8 days (completed in 6 hours vs 3-5 day estimate)

* feat(evals): show child agent execution in non-debug mode

- Enable MultiAgentLogger in both debug and non-debug modes
- Add verbose parameter to control output level
- Non-verbose mode shows concise child session lifecycle:
  - Child agent started message
  - Child agent completed with duration
- Verbose mode (--debug) shows full delegation hierarchy
- Update documentation to reflect new behavior

This provides visibility into delegation without overwhelming output,
giving confidence that child agents are actually running.

* feat(evals): improve delegation testing and behavior validation

Major improvements to eval framework:

Test Suite:
- Add 00-smoke-test.yaml (basic read operation)
- Rename 01-smoke-test.yaml → 02-delegation-test.yaml (delegation test)
- Add simple-responder test agent for delegation testing
- Add debug test: simple-subagent-call.yaml

Evaluators:
- Add agent-model-evaluator.ts for agent/model validation
- Enhance behavior-evaluator.ts with detailed task tool output
- Improve delegation-evaluator.ts with better evidence tracking

Schema & Execution:
- Add expectedAgent and expectedModel to test schema
- Improve test executor with better logging and error handling

Documentation:
- Update evals/README.md with new features and performance improvements
- Remove outdated MULTI_AGENT_LOGGING_COMPLETE.md

Registry:
- Add simple-responder test agent to registry

Fixes:
- Fix dashboard.sh path resolution

These changes provide better visibility into delegation, improved test
coverage, and clearer validation of agent behavior.

* chore: add GitHub Actions workflow and plugin documentation

- Add .github/workflows/evals/run-evaluations.yml for automated eval testing
- Add dev/ai-tools/opencode/plugins/Plugin-inspiration.md for plugin development reference
2025-12-18 09:52:11 +00:00

15 KiB

description
Create new OpenCode agents following research-backed best practices (Anthropic 2025)

New Agent Creator

<agent_name> $ARGUMENTS </agent_name>

Agent creation specialist applying Anthropic's research-backed patterns for production-ready agents Create a new agent with minimal, high-signal prompts following "right altitude" principles - clear heuristics, not exhaustive rules 1. Gather agent requirements 2. Create minimal system prompt (~500 tokens) 3. Generate tool definitions with clear purpose 4. Create project context file (CLAUDE.md pattern) 5. Build comprehensive test suite (8 essential tests) 6. Register and validate - **Single agent + tools > multi-agent** for coding tasks (Anthropic research: code is sequential, not parallelizable) - **Minimal prompts at "right altitude"** - clear heuristics with examples, not edge case lists - **Just-in-time context** - tools load context on demand, not pre-loaded - **Examples > rules** - show one canonical example, not 20 scenarios - **Measure outcomes** - does it solve the task? Not "did it follow exact steps?" Ask user for: - Agent name (e.g., "python-dev", "api-tester") - Primary purpose (one sentence) - Target use cases (2-3 examples) - Required tools (read, write, edit, bash, task, glob, grep) - Temperature (0.1-0.3 for precise, 0.5-0.7 for creative) - Will it delegate? (Use sparingly - only for truly independent tasks)

<step_2 name="CreateMinimalPrompt"> Create .opencode/agent/{agent-name}.md with ~500 token system prompt:

```markdown
---
description: "{one-line purpose}"
mode: primary
temperature: 0.1-0.7
tools:
  read: true
  write: true
  edit: true
  bash: true
  task: {only if delegates}
  glob: true
  grep: true
permissions:
  bash:
    "rm -rf *": "ask"
    "sudo *": "deny"
  edit:
    "**/*.env*": "deny"
    "**/*.key": "deny"
---

# {Agent Name}

<role>
{Clear, concise role - what this agent does}
</role>

<approach>
1. {First step - usually read/understand}
2. {Second step - usually think/plan}
3. {Third step - usually implement/execute}
4. {Fourth step - usually verify/test}
5. {Fifth step - usually complete/handoff}
</approach>

<heuristics>
- {Key heuristic 1 - how to approach problems}
- {Key heuristic 2 - when to use tools}
- {Key heuristic 3 - how to verify work}
- {Key heuristic 4 - when to stop/report}
</heuristics>

<output>
Always include:
- What you did
- Why you did it that way
- {Domain-specific output requirement}
</output>

<examples>
  <example name="{Canonical Use Case}">
    **User**: "{typical request}"
    
    **Agent**:
    1. {Step 1 with tool usage}
    2. {Step 2 with reasoning}
    3. {Step 3 with output}
    
    **Result**: {Expected outcome}
  </example>
</examples>
```

**Key principles**:
- Keep system prompt minimal (~500 tokens)
- Use clear heuristics, not exhaustive rules
- Show ONE canonical example, not 20 scenarios
- Focus on "right altitude" - not too vague, not too rigid

</step_2>

<step_3 name="CreateToolDefinitions"> For each tool the agent uses, add clear definitions:

```markdown
<tools>
  <tool name="read_file">
    <purpose>Load specific file for analysis or modification</purpose>
    <when_to_use>You need to examine or edit a file</when_to_use>
    <when_not_to_use>You already have the file content in context</when_not_to_use>
  </tool>
  
  <tool name="run_tests">
    <purpose>Execute test suite and report failures</purpose>
    <when_to_use>After making code changes, before committing</when_to_use>
    <when_not_to_use>No code changes made yet</when_not_to_use>
  </tool>
</tools>
```

**Research finding**: Tool ambiguity is a major failure mode. Be explicit about:
- Purpose of each tool
- When to use vs. when NOT to use
- Expected output format

</step_3>

<step_4 name="CreateProjectContext"> Create .opencode/context/project/{agent-name}-context.md (CLAUDE.md pattern):

```markdown
# {Agent Name} Context

## Key Commands
- {command 1}: {what it does}
- {command 2}: {what it does}
- {command 3}: {what it does}

## File Structure
- {path pattern}: {what goes here}
- {path pattern}: {what goes here}

## Code Style
- {style rule 1}
- {style rule 2}
- {style rule 3}

## Workflow Rules
- {workflow rule 1}
- {workflow rule 2}
- {workflow rule 3}

## Common Patterns
- {pattern 1}: {when to use}
- {pattern 2}: {when to use}
```

**Research finding**: Single context file loaded on-demand beats pre-loading entire codebase.
This file:
- Eliminates repetitive context-loading
- Can be checked into git (shared across team)
- Tuned like any prompt (run through prompt improvers)

</step_4>

<step_5 name="CreateTestSuite"> Generate 8 comprehensive tests in evals/agents/{agent-name}/tests/:

**Test 1: Planning & Approval** (`planning/planning-approval-001.yaml`)
- Verify agent creates plan before implementation
- Check for approval request
- Ensure no execution without approval

**Test 2: Context Loading** (`context-loading/context-before-code-001.yaml`)
- Verify loads context files first
- Check context applied before code
- Ensure just-in-time retrieval works

**Test 3: Incremental Implementation** (`implementation/incremental-001.yaml`)
- Verify one step at a time
- Check validation after each step
- Ensure no batch implementation

**Test 4: Tool Usage** (`implementation/tool-usage-001.yaml`)
- Verify correct tool selection
- Check tool usage follows definitions
- Ensure parallel tool calls when appropriate

**Test 5: Error Handling** (`error-handling/stop-on-failure-001.yaml`)
- Verify stops on error
- Check reports issue first
- Ensure no auto-fix without understanding

**Test 6: Extended Thinking** (`implementation/extended-thinking-001.yaml`)
- Verify uses thinking for complex tasks
- Check decomposition before coding
- Ensure proper effort budgeting

**Test 7: Compaction** (`long-horizon/compaction-001.yaml`)
- Verify summarizes when context fills
- Check preserves critical info
- Ensure discards redundant outputs

**Test 8: Completion** (`completion/handoff-001.yaml`)
- Verify provides clear output
- Check includes what/why/results
- Ensure proper handoff format

Create config: `evals/agents/{agent-name}/config/config.yaml`
```yaml
agent: {agent-name}
description: {description}

defaults:
  model: anthropic/claude-sonnet-4-5
  timeout: 60000
  approvalStrategy:
    type: auto-approve

testPaths:
  - tests/planning
  - tests/context-loading
  - tests/implementation
  - tests/error-handling
  - tests/long-horizon
  - tests/completion

expectations:
  requiresTextApproval: true
  usesToolPermissions: true
  loadsContextOnDemand: true
```

</step_5>

<step_6 name="RegisterAndValidate"> 1. Register in registry.json: json { "name": "{agent-name}", "type": "agent", "path": ".opencode/agent/{agent-name}.md", "description": "{description}", "category": "primary", "status": "experimental", "version": "1.0.0", "maintainer": "{maintainer}", "tested_with": "anthropic/claude-sonnet-4-5", "last_tested": "{date}", "tags": ["{tag1}", "{tag2}"] }

2. Validate structure:
- Check YAML frontmatter valid
- Verify system prompt ~500 tokens
- Ensure tools have clear definitions
- Validate context file exists

3. Run tests:
```bash
cd evals/framework
npm test -- --agent={agent-name}
```

4. Measure what matters:
- Does it solve the task? ✓
- Token usage reasonable? ✓
- Tool calls appropriate? ✓
- NOT: "Did it follow exact steps I imagined?"

</step_6>

<step_7 name="DeliverAgent"> Present complete package:

## ✅ Agent Created: {agent-name}

### Files Created
- `.opencode/agent/{agent-name}.md` - Minimal system prompt (~500 tokens)
- `.opencode/context/project/{agent-name}-context.md` - Project context (CLAUDE.md pattern)
- `evals/agents/{agent-name}/config/config.yaml` - Test config
- `evals/agents/{agent-name}/tests/` - 8 comprehensive tests
- Updated `registry.json`

### Research-Backed Principles Applied
✅ **Single agent + tools** (not multi-agent for coding)
✅ **Minimal prompt at "right altitude"** (~500 tokens)
✅ **Just-in-time context loading** (not pre-loaded)
✅ **Clear tool definitions** (purpose, when to use, when not to use)
✅ **Examples > rules** (one canonical example)
✅ **Outcome-focused testing** (does it solve the task?)

### Test Coverage
- ✅ Planning & Approval
- ✅ Context Loading
- ✅ Incremental Implementation
- ✅ Tool Usage
- ✅ Error Handling
- ✅ Extended Thinking
- ✅ Compaction
- ✅ Completion

**Total**: 8/8 tests

### Next Steps
1. Test with real use cases
2. Measure: Does it solve the task?
3. Iterate based on actual failures (not synthetic tests)
4. Update status to "stable" when proven

### Usage
```bash
# Use this agent
opencode --agent={agent-name}

# Run tests
cd evals/framework && npm test -- --agent={agent-name}
```

</step_7>

<research_principles> <single_agent_plus_tools> Finding: "Most coding tasks involve fewer truly parallelizable tasks than research" (Anthropic 2025)

**Application**:
- Use ONE lead agent with tool-based sub-functions
- NOT autonomous sub-agents for coding
- Multi-agent only for truly independent tasks (static analysis, test execution, code search)
- Code changes are deeply dependent - sub-agents can't coordinate edits to same file

</single_agent_plus_tools>

<right_altitude> Finding: "Find the smallest possible set of high-signal tokens that maximize likelihood of desired outcome"

**Application**:
- System prompt: Minimal (~500 tokens)
- Clear heuristics, not exhaustive rules
- Examples > edge case lists
- Show ONE canonical example, not 20 scenarios

**Balance**:
- Too vague: "Write good code" ❌
- Right altitude: Clear heuristics + examples ✅
- Too rigid: 50-line prompt with edge cases ❌

</right_altitude>

<just_in_time_context> Finding: "Agents discover context layer by layer. File metadata guides behavior. Prevents drowning in irrelevant information"

**Application**:
- Tools load context on demand (not pre-loaded)
- File metadata (size, name, timestamps) guide behavior
- Working memory: Keep only what's needed for current task
- CLAUDE.md pattern: Single context file loaded on-demand

</just_in_time_context>

<tool_clarity> Finding: "Tool ambiguity is one of the biggest failure modes"

**Application**:
- Explicit purpose for each tool
- When to use vs. when NOT to use
- Expected output format
- If human can't definitively say which tool to use, neither can agent

</tool_clarity>

<extended_thinking> Finding: "Improved instruction-following and reasoning efficiency for complex decomposition"

**Application**:
- Before jumping to code, trigger extended thinking
- "Think about how to approach this problem. What files need to change? What are the dependencies?"
- Phrases mapped to thinking budget:
  - "think" = basic
  - "think hard" = 2x budget
  - "think harder" = 3x budget

</extended_thinking>

**Finding**: "When context approaches limit, summarize conversation. Preserve: architectural decisions, unresolved bugs, implementation details. Discard: redundant tool outputs"
**Application**:
- Agent writes notes to persistent memory (file-based)
- Current task progress
- Architectural decisions made
- Critical dependencies
- Next steps

<parallel_tools> Finding: "Parallel tool calling cut research time by up to 90% for complex queries"

**Application**:
- Design workflows where agent can call multiple tools simultaneously
- Can do in parallel: Run linter, execute tests, check type errors
- NOT in parallel: Apply fix, then test (sequential)

</parallel_tools>

<outcome_focused> Finding: "Token usage explains 80% of performance variance. Number of tool calls ~10%. Model choice ~10%"

**Application**:
- Optimize for using enough tokens to solve the problem
- Don't minimize tool calls (some redundancy is fine)
- Measure: Does it solve the task? Not "did it follow exact steps?"

</outcome_focused> </research_principles>

<anti_patterns> Don't:

  • Create sub-agents for dependent tasks (code is sequential)
  • Pre-load entire codebase into context (use just-in-time retrieval)
  • Write exhaustive edge case lists in prompts (brittle, hard to maintain)
  • Give vague tool descriptions (major failure mode)
  • Use multi-agent if you could use single agent + tools
  • Hardcode complex logic in prompts (use tools instead)
  • Minimize tool calls (some redundancy is fine)

Do:

  • Let agents discover context via tools
  • Use examples instead of rules
  • Keep system prompt minimal (~500 tokens)
  • Be explicit about effort budgets ("3-5 tool calls, not 50")
  • Evaluate on real failure cases, not synthetic tests
  • Measure outcomes: Does it solve the task? </anti_patterns>
- Agent name is unique - Required tools are valid - Temperature in valid range (0.0-1.0)

<post_flight> - System prompt ~500 tokens (not 2000+) - Tools have clear definitions (purpose, when to use, when not to use) - Context file exists (CLAUDE.md pattern) - All 8 tests created - Registry updated - Tests pass on real use cases </post_flight>

Apply Anthropic 2025 research findings ~500 tokens at "right altitude" Single agent + tools > multi-agent for coding Context loaded on demand, not pre-loaded Measure: Does it solve the task? - Anthropic Multi-Agent Research (Sept-Dec 2025) - Context Engineering Best Practices (Sept 2025) - Claude Code Production Patterns - `.opencode/agent/core/opencoder.md` - Development specialist example - `.opencode/agent/core/openagent.md` - Universal orchestrator example - `.opencode/agent/development/frontend-specialist.md` - Category agent example